Skip to main content

cast/cmd/
receive_policy.rs

1use crate::{
2    cmd::{rpc_provider, tip20::send_tip20_transaction, tip403::policy_type_label},
3    tempo::{ensure_tempo_precompile_active, print_payload, tempo_provider},
4    tx::{SendTxOpts, TxParams},
5};
6use alloy_ens::NameOrAddress;
7use alloy_primitives::{Address, Bytes, U256, keccak256};
8use alloy_sol_types::{SolCall, SolValue};
9use clap::{Parser, Subcommand};
10use eyre::{Result, WrapErr, ensure};
11use foundry_cli::opts::RpcOpts;
12use foundry_common::provider::RetryProvider;
13use foundry_evm_networks::TEMPO_PRECOMPILE_ADDRESSES;
14use serde_json::{Value, json};
15use std::str::FromStr;
16use tempo_alloy::{TempoNetwork, chainspec::hardfork::TempoHardfork};
17use tempo_contracts::precompiles::{
18    ADDRESS_REGISTRY_ADDRESS, IAddressRegistry, IReceivePolicyGuard, ITIP403Registry,
19    RECEIVE_POLICY_GUARD_ADDRESS, TIP403_REGISTRY_ADDRESS,
20};
21use tempo_primitives::TempoAddressExt;
22
23/// Account-level receive policy operations (Tempo).
24#[derive(Debug, Parser, Clone)]
25pub enum ReceivePolicySubcommand {
26    /// Set the caller's TIP-403 receive policy.
27    ///
28    /// Create the sender and token-filter policies referenced here with `cast tip403 create`.
29    Set {
30        /// Sender policy ID to evaluate for inbound transfer originators.
31        sender_policy_id: u64,
32
33        /// Token filter policy ID to evaluate for inbound TIP-20 tokens.
34        token_filter_id: u64,
35
36        /// Address authorized to recover held receipts. Defaults to originator recovery.
37        #[arg(long, value_name = "ADDRESS", default_value_t = Address::ZERO)]
38        recovery_authority: Address,
39
40        /// Print the calldata and receive-policy warning without sending a transaction.
41        #[arg(long, visible_alias = "dry-run")]
42        preview: bool,
43
44        /// Suppress the originator-recovery/system-sender warning.
45        #[arg(long)]
46        force: bool,
47
48        #[command(flatten)]
49        send_tx: SendTxOpts,
50
51        #[command(flatten)]
52        tx: TxParams,
53    },
54
55    /// Get an account's configured receive policy.
56    Get {
57        /// Account whose receive policy should be queried.
58        #[arg(value_parser = NameOrAddress::from_str)]
59        account: NameOrAddress,
60
61        #[command(flatten)]
62        rpc: RpcOpts,
63    },
64
65    /// Validate whether an inbound TIP-20 transfer or mint would be credited or held.
66    Validate {
67        /// TIP-20 token address.
68        #[arg(value_parser = NameOrAddress::from_str)]
69        token: NameOrAddress,
70
71        /// Inbound transfer sender or mint originator.
72        #[arg(value_parser = NameOrAddress::from_str)]
73        sender: NameOrAddress,
74
75        /// Intended recipient.
76        #[arg(value_parser = NameOrAddress::from_str)]
77        receiver: NameOrAddress,
78
79        #[command(flatten)]
80        rpc: RpcOpts,
81    },
82
83    /// Blocked receive-policy receipt utilities.
84    Receipt {
85        #[command(subcommand)]
86        command: ReceivePolicyReceiptSubcommand,
87    },
88
89    /// Claim held TIP-20 funds using a blocked receive-policy receipt.
90    Claim {
91        /// Desired release target. The guard decides onchain whether to resume or reroute.
92        #[arg(value_parser = NameOrAddress::from_str)]
93        to: NameOrAddress,
94
95        /// ABI-encoded ReceivePolicyGuard claim receipt.
96        receipt: Bytes,
97
98        #[command(flatten)]
99        send_tx: SendTxOpts,
100
101        #[command(flatten)]
102        tx: TxParams,
103    },
104}
105
106#[derive(Debug, Subcommand, Clone)]
107pub enum ReceivePolicyReceiptSubcommand {
108    /// Decode an ABI-encoded ReceivePolicyGuard claim receipt.
109    Decode {
110        /// ABI-encoded ReceivePolicyGuard claim receipt.
111        receipt: Bytes,
112    },
113
114    /// Query the held TIP-20 balance for a claim receipt.
115    Balance {
116        /// ABI-encoded ReceivePolicyGuard claim receipt.
117        receipt: Bytes,
118
119        #[command(flatten)]
120        rpc: RpcOpts,
121    },
122
123    /// Burn held funds for a blocked receipt when authorized by the token.
124    Burn {
125        /// ABI-encoded ReceivePolicyGuard claim receipt.
126        receipt: Bytes,
127
128        #[command(flatten)]
129        send_tx: Box<SendTxOpts>,
130
131        #[command(flatten)]
132        tx: Box<TxParams>,
133    },
134}
135
136impl ReceivePolicySubcommand {
137    pub async fn run(self) -> Result<()> {
138        match self {
139            Self::Set {
140                sender_policy_id,
141                token_filter_id,
142                recovery_authority,
143                preview,
144                force,
145                send_tx,
146                tx,
147            } => {
148                set(
149                    sender_policy_id,
150                    token_filter_id,
151                    recovery_authority,
152                    preview,
153                    force,
154                    send_tx,
155                    tx,
156                )
157                .await?
158            }
159            Self::Get { account, rpc } => get(account, rpc).await?,
160            Self::Validate { token, sender, receiver, rpc } => {
161                validate(token, sender, receiver, rpc).await?
162            }
163            Self::Receipt { command } => match command {
164                ReceivePolicyReceiptSubcommand::Decode { receipt } => decode_receipt(receipt)?,
165                ReceivePolicyReceiptSubcommand::Balance { receipt, rpc } => {
166                    receipt_balance(receipt, rpc).await?
167                }
168                ReceivePolicyReceiptSubcommand::Burn { receipt, send_tx, tx } => {
169                    burn_receipt(receipt, *send_tx, *tx).await?
170                }
171            },
172            Self::Claim { to, receipt, send_tx, tx } => claim(to, receipt, send_tx, tx).await?,
173        }
174
175        Ok(())
176    }
177}
178
179async fn set(
180    sender_policy_id: u64,
181    token_filter_id: u64,
182    recovery_authority: Address,
183    preview: bool,
184    force: bool,
185    send_tx: SendTxOpts,
186    tx: TxParams,
187) -> Result<()> {
188    // Reject authorities that can never satisfy `ReceivePolicyGuard.claim()` before doing
189    // anything else; `--force` only suppresses the softer originator-recovery warning below.
190    if let Some(message) = invalid_recovery_authority_message(recovery_authority) {
191        eyre::bail!("{message}");
192    }
193
194    let warning = if force {
195        None
196    } else {
197        recovery_warning(sender_policy_id, recovery_authority, &send_tx.eth.rpc).await?
198    };
199
200    let calldata = ITIP403Registry::setReceivePolicyCall {
201        senderPolicyId: sender_policy_id,
202        tokenFilterId: token_filter_id,
203        recoveryAuthority: recovery_authority,
204    }
205    .abi_encode();
206
207    if preview {
208        let payload = json!({
209            "action": "set_receive_policy",
210            "registry": format!("{TIP403_REGISTRY_ADDRESS}"),
211            "sender_policy_id": sender_policy_id,
212            "token_filter_id": token_filter_id,
213            "recovery_authority": format!("{recovery_authority}"),
214            "recovery_mode": recovery_mode(recovery_authority),
215            "calldata": Bytes::from(calldata),
216            "warning": warning,
217        });
218        return print_payload(payload, |payload| {
219            sh_println!(
220                "Registry:           {TIP403_REGISTRY_ADDRESS}\n\
221                 Sender policy ID:   {sender_policy_id}\n\
222                 Token filter ID:    {token_filter_id}\n\
223                 Recovery authority: {recovery_authority}\n\
224                 Recovery mode:      {}\n\
225                 Calldata:           {}",
226                recovery_mode(recovery_authority),
227                payload["calldata"].as_str().unwrap_or_default(),
228            )?;
229            if let Some(warning) = payload["warning"].as_str() {
230                sh_warn!("{warning}")?;
231            }
232            Ok(())
233        });
234    }
235
236    if let Some(warning) = warning.as_deref() {
237        sh_warn!("{warning}")?;
238    }
239
240    send_tip20_transaction(TIP403_REGISTRY_ADDRESS, calldata, send_tx, tx).await
241}
242
243async fn get(account: NameOrAddress, rpc: RpcOpts) -> Result<()> {
244    let provider = rpc_provider(&rpc)?;
245    let account = account.resolve(&provider).await?;
246    let registry = ITIP403Registry::new(TIP403_REGISTRY_ADDRESS, provider);
247    let policy = registry.receivePolicy(account).call().await?;
248
249    let payload = json!({
250        "account": format!("{account}"),
251        "has_receive_policy": policy.hasReceivePolicy,
252        "sender_policy_id": policy.senderPolicyId,
253        "sender_policy_type": policy_type_label(policy.senderPolicyType),
254        "token_filter_id": policy.tokenFilterId,
255        "token_filter_type": policy_type_label(policy.tokenFilterType),
256        "recovery_authority": format!("{}", policy.recoveryAuthority),
257        "recovery_mode": recovery_mode(policy.recoveryAuthority),
258    });
259    print_payload(payload, |payload| {
260        sh_println!(
261            "Account:            {}\n\
262             Has receive policy: {}\n\
263             Sender policy ID:   {}\n\
264             Sender policy type: {}\n\
265             Token filter ID:    {}\n\
266             Token filter type:  {}\n\
267             Recovery authority: {}\n\
268             Recovery mode:      {}",
269            payload["account"].as_str().unwrap_or_default(),
270            payload["has_receive_policy"].as_bool().unwrap_or_default(),
271            payload["sender_policy_id"],
272            payload["sender_policy_type"].as_str().unwrap_or_default(),
273            payload["token_filter_id"],
274            payload["token_filter_type"].as_str().unwrap_or_default(),
275            payload["recovery_authority"].as_str().unwrap_or_default(),
276            payload["recovery_mode"].as_str().unwrap_or_default(),
277        )
278    })
279}
280
281async fn validate(
282    token: NameOrAddress,
283    sender: NameOrAddress,
284    receiver: NameOrAddress,
285    rpc: RpcOpts,
286) -> Result<()> {
287    let provider = rpc_provider(&rpc)?;
288    let token = token.resolve(&provider).await?;
289    let sender = sender.resolve(&provider).await?;
290    let receiver = receiver.resolve(&provider).await?;
291    let effective_receiver = IAddressRegistry::new(ADDRESS_REGISTRY_ADDRESS, &provider)
292        .resolveRecipient(receiver)
293        .call()
294        .await?;
295    let registry = ITIP403Registry::new(TIP403_REGISTRY_ADDRESS, provider);
296    let result = registry.validateReceivePolicy(token, sender, effective_receiver).call().await?;
297    let delivery_state = if result.authorized { "credited" } else { "held" };
298
299    let payload = validate_payload(
300        token,
301        sender,
302        receiver,
303        effective_receiver,
304        result.authorized,
305        result.blockedReason,
306        delivery_state,
307    );
308    print_payload(payload, |payload| {
309        sh_println!(
310            "Token:          {}\n\
311             Sender:         {}\n\
312             Receiver:       {}\n\
313             Effective recv: {}\n\
314             Authorized:     {}\n\
315             Blocked reason: {}\n\
316             Delivery state: {}",
317            payload["token"].as_str().unwrap_or_default(),
318            payload["sender"].as_str().unwrap_or_default(),
319            payload["receiver"].as_str().unwrap_or_default(),
320            payload["effective_receiver"].as_str().unwrap_or_default(),
321            payload["authorized"].as_bool().unwrap_or_default(),
322            payload["blocked_reason"].as_str().unwrap_or_default(),
323            payload["delivery_state"].as_str().unwrap_or_default(),
324        )
325    })
326}
327
328fn validate_payload(
329    token: Address,
330    sender: Address,
331    receiver: Address,
332    effective_receiver: Address,
333    authorized: bool,
334    blocked_reason_value: ITIP403Registry::BlockedReason,
335    delivery_state: &str,
336) -> Value {
337    json!({
338        "token": format!("{token}"),
339        "sender": format!("{sender}"),
340        "receiver": format!("{receiver}"),
341        "effective_receiver": format!("{effective_receiver}"),
342        "receiver_was_resolved": receiver != effective_receiver,
343        "authorized": authorized,
344        "blocked_reason": blocked_reason(blocked_reason_value as u8),
345        "delivery_state": delivery_state,
346    })
347}
348
349fn decode_receipt(receipt: Bytes) -> Result<()> {
350    let decoded = decode_claim_receipt(&receipt)?;
351    let payload = receipt_payload(&receipt, &decoded, None);
352    print_payload(payload, |payload| {
353        print_decoded_receipt(payload)?;
354        print_claim_hint(payload)
355    })
356}
357
358async fn receipt_balance(receipt: Bytes, rpc: RpcOpts) -> Result<()> {
359    let provider = rpc_provider(&rpc)?;
360    let guard = IReceivePolicyGuard::new(RECEIVE_POLICY_GUARD_ADDRESS, provider);
361    let amount = guard.balanceOf(receipt.clone()).call().await?;
362    let decoded = decode_claim_receipt(&receipt)?;
363    let payload = receipt_payload(&receipt, &decoded, Some(amount));
364    print_payload(payload, |payload| {
365        print_decoded_receipt(payload)?;
366        sh_println!("Held balance: {}", payload["held_balance"].as_str().unwrap_or_default())
367    })
368}
369
370/// Checks the receipt and that the RPC is T6+: the ReceivePolicyGuard precompile only has code from
371/// T6 onwards, so a pre-T6 call would succeed as a silent no-op instead of reverting.
372async fn guard_provider(
373    receipt: &Bytes,
374    send_tx: &SendTxOpts,
375    command: &str,
376) -> Result<RetryProvider<TempoNetwork>> {
377    decode_claim_receipt(receipt)?;
378    let (_, provider) = tempo_provider(&send_tx.eth.rpc)?;
379    ensure_tempo_precompile_active(
380        &provider,
381        TempoHardfork::T6,
382        RECEIVE_POLICY_GUARD_ADDRESS,
383        &format!("{command} requires a Tempo T6-capable ReceivePolicy RPC"),
384    )
385    .await?;
386    Ok(provider)
387}
388
389async fn burn_receipt(receipt: Bytes, send_tx: SendTxOpts, tx: TxParams) -> Result<()> {
390    guard_provider(&receipt, &send_tx, "cast receive-policy receipt burn").await?;
391    let data = IReceivePolicyGuard::burnBlockedReceiptCall { receipt }.abi_encode();
392    send_tip20_transaction(RECEIVE_POLICY_GUARD_ADDRESS, data, send_tx, tx).await
393}
394
395async fn claim(to: NameOrAddress, receipt: Bytes, send_tx: SendTxOpts, tx: TxParams) -> Result<()> {
396    let provider = guard_provider(&receipt, &send_tx, "cast receive-policy claim").await?;
397    let to = to.resolve(&provider).await?;
398    let data = IReceivePolicyGuard::claimCall { to, receipt }.abi_encode();
399    send_tip20_transaction(RECEIVE_POLICY_GUARD_ADDRESS, data, send_tx, tx).await
400}
401
402async fn recovery_warning(
403    sender_policy_id: u64,
404    recovery_authority: Address,
405    rpc: &RpcOpts,
406) -> Result<Option<String>> {
407    if !recovery_authority.is_zero() {
408        return Ok(None);
409    }
410
411    let provider = rpc_provider(rpc)?;
412    let registry = ITIP403Registry::new(TIP403_REGISTRY_ADDRESS, provider);
413    let mut blocked = Vec::new();
414    for address in TEMPO_PRECOMPILE_ADDRESSES {
415        if !registry.isAuthorizedSender(sender_policy_id, *address).call().await.unwrap_or(true) {
416            blocked.push(*address);
417        }
418    }
419
420    if blocked.is_empty() {
421        return Ok(None);
422    }
423
424    Ok(Some(format!(
425        "originator recovery is enabled because recovery authority is 0x0, but sender policy \
426         {sender_policy_id} blocks {} Tempo system/precompile sender(s): {}. Receipts created \
427         for those senders may not be claimable by a user. Choose receiver or third-party \
428         recovery authority when blocking system senders, or pass --force if this is intentional.",
429        blocked.len(),
430        blocked.iter().map(Address::to_string).collect::<Vec<_>>().join(", ")
431    )))
432}
433
434/// Returns an error message when `recovery_authority` could never pass
435/// `ReceivePolicyGuard.claim()` and would leave held receipts unclaimable.
436///
437/// `address(0)` is the originator-recovery sentinel and a receiver's own address is valid
438/// (receiver recovery), so those pass. Virtual and TIP-20 addresses are always rejected. Fixed
439/// system precompiles are rejected conservatively against the full known list (a superset of the
440/// registry's spec-aware check), since a not-yet-active precompile is never a sound authority and
441/// becomes unclaimable once it activates.
442fn invalid_recovery_authority_message(recovery_authority: Address) -> Option<String> {
443    if recovery_authority.is_zero() {
444        return None;
445    }
446    if recovery_authority.is_virtual() {
447        return Some("recovery authority cannot be a TIP-1022 virtual address".to_string());
448    }
449    if recovery_authority.is_tip20() {
450        return Some("recovery authority cannot be a TIP-20 token address".to_string());
451    }
452    if TEMPO_PRECOMPILE_ADDRESSES.contains(&recovery_authority) {
453        return Some(format!(
454            "recovery authority cannot be a fixed Tempo system precompile: {recovery_authority}"
455        ));
456    }
457    None
458}
459
460fn decode_claim_receipt(receipt: &Bytes) -> Result<IReceivePolicyGuard::ClaimReceiptV1> {
461    let decoded = IReceivePolicyGuard::ClaimReceiptV1::abi_decode(receipt)
462        .wrap_err("invalid ReceivePolicyGuard claim receipt")?;
463
464    ensure!(
465        decoded.version == 1,
466        "unsupported ReceivePolicyGuard claim receipt version {}",
467        decoded.version
468    );
469    ensure!(!decoded.token.is_zero(), "ReceivePolicyGuard claim receipt token is zero");
470    ensure!(
471        decoded.recipient != RECEIVE_POLICY_GUARD_ADDRESS,
472        "ReceivePolicyGuard claim receipt recipient cannot be the guard precompile"
473    );
474    ensure!(
475        decoded.blockedReason == ITIP403Registry::BlockedReason::TOKEN_FILTER as u8
476            || decoded.blockedReason == ITIP403Registry::BlockedReason::RECEIVE_POLICY as u8,
477        "ReceivePolicyGuard claim receipt blocked reason is not claimable"
478    );
479    ensure!(
480        matches!(
481            decoded.kind,
482            IReceivePolicyGuard::InboundKind::TRANSFER | IReceivePolicyGuard::InboundKind::MINT
483        ),
484        "ReceivePolicyGuard claim receipt inbound kind is unknown"
485    );
486
487    Ok(decoded)
488}
489
490fn receipt_payload(
491    receipt: &Bytes,
492    decoded: &IReceivePolicyGuard::ClaimReceiptV1,
493    amount: Option<U256>,
494) -> Value {
495    let receipt_key = keccak256(receipt);
496    let delivery_state = match amount {
497        Some(amount) if amount > U256::ZERO => "held",
498        Some(_) => "not_held",
499        None => "unknown",
500    };
501    let mut payload = json!({
502        "receipt": format!("{receipt}"),
503        "receipt_key": format!("{receipt_key}"),
504        "version": decoded.version,
505        "token": format!("{}", decoded.token),
506        "recovery_authority": format!("{}", decoded.recoveryAuthority),
507        "recovery_mode": recovery_mode(decoded.recoveryAuthority),
508        "originator": format!("{}", decoded.originator),
509        "recipient": format!("{}", decoded.recipient),
510        "recipient_is_virtual": decoded.recipient.is_virtual(),
511        "claim_target": if decoded.recipient.is_virtual() || decoded.recoveryAuthority.is_zero() {
512            Value::Null
513        } else {
514            json!(format!("{}", decoded.recipient))
515        },
516        "blocked_at": decoded.blockedAt,
517        "blocked_nonce": decoded.blockedNonce,
518        "blocked_reason": blocked_reason(decoded.blockedReason),
519        "kind": inbound_kind(decoded.kind),
520        "memo": format!("{}", decoded.memo),
521        "delivery_state": delivery_state,
522    });
523    if let Some(amount) = amount {
524        payload["held_balance"] = json!(amount.to_string());
525    }
526    payload
527}
528
529fn print_decoded_receipt(payload: &Value) -> Result<()> {
530    sh_println!(
531        "Receipt key:        {}\n\
532         Token:              {}\n\
533         Recovery authority: {}\n\
534         Recovery mode:      {}\n\
535         Originator:         {}\n\
536         Recipient:          {}\n\
537         Blocked at:         {}\n\
538         Blocked nonce:      {}\n\
539         Blocked reason:     {}\n\
540         Kind:               {}\n\
541         Memo:               {}\n\
542         Delivery state:     {}",
543        payload["receipt_key"].as_str().unwrap_or_default(),
544        payload["token"].as_str().unwrap_or_default(),
545        payload["recovery_authority"].as_str().unwrap_or_default(),
546        payload["recovery_mode"].as_str().unwrap_or_default(),
547        payload["originator"].as_str().unwrap_or_default(),
548        payload["recipient"].as_str().unwrap_or_default(),
549        payload["blocked_at"],
550        payload["blocked_nonce"],
551        payload["blocked_reason"].as_str().unwrap_or_default(),
552        payload["kind"].as_str().unwrap_or_default(),
553        payload["memo"].as_str().unwrap_or_default(),
554        payload["delivery_state"].as_str().unwrap_or_default(),
555    )
556}
557
558fn print_claim_hint(payload: &Value) -> Result<()> {
559    let recipient = payload["recipient"].as_str().unwrap_or_default();
560    let receipt = payload["receipt"].as_str().unwrap_or_default();
561    if payload["recovery_mode"].as_str() == Some("originator") {
562        sh_println!(
563            "\nClaim target: originator recovery reroutes funds, so do not default to the blocked recipient. Claim to an address that can receive the token:\n  cast receive-policy claim <target-address> {receipt}"
564        )
565    } else if payload["recipient_is_virtual"].as_bool().unwrap_or_default() {
566        sh_println!(
567            "\nClaim target: recipient is a virtual address; resolve it first with:\n  cast vaddr resolve {recipient}\nThen claim to the registered master address:\n  cast receive-policy claim <master-address> {receipt}"
568        )
569    } else {
570        sh_println!("\nClaim path: cast receive-policy claim {recipient} {receipt}")
571    }
572}
573
574fn recovery_mode(recovery_authority: Address) -> &'static str {
575    if recovery_authority.is_zero() { "originator" } else { "authority" }
576}
577
578/// Labels a `BlockedReason` discriminant; receipts carry it as a raw `u8`.
579const fn blocked_reason(reason: u8) -> &'static str {
580    match reason {
581        0 => "none",
582        1 => "token_filter",
583        2 => "receive_policy",
584        _ => "unknown",
585    }
586}
587
588const fn inbound_kind(kind: IReceivePolicyGuard::InboundKind) -> &'static str {
589    match kind {
590        IReceivePolicyGuard::InboundKind::TRANSFER => "transfer",
591        IReceivePolicyGuard::InboundKind::MINT => "mint",
592        _ => "unknown",
593    }
594}
595
596#[cfg(test)]
597mod tests {
598
599    use super::*;
600    use alloy_primitives::{B256, address};
601    use tempo_primitives::{MasterId, UserTag};
602
603    fn sample_receipt() -> Bytes {
604        IReceivePolicyGuard::ClaimReceiptV1::new(
605            Address::with_last_byte(0x10),
606            Address::with_last_byte(0x20),
607            Address::with_last_byte(0x30),
608            Address::with_last_byte(0x40),
609            1_780_000_000,
610            7,
611            ITIP403Registry::BlockedReason::RECEIVE_POLICY as u8,
612            IReceivePolicyGuard::InboundKind::TRANSFER,
613            B256::with_last_byte(0x42),
614        )
615        .abi_encode()
616        .into()
617    }
618
619    #[test]
620    fn decodes_guard_claim_receipt() {
621        let receipt = sample_receipt();
622        let decoded = decode_claim_receipt(&receipt).unwrap();
623        assert_eq!(decoded.version, 1);
624        assert_eq!(decoded.token, Address::with_last_byte(0x10));
625        assert_eq!(decoded.recoveryAuthority, Address::with_last_byte(0x20));
626        assert_eq!(decoded.originator, Address::with_last_byte(0x30));
627        assert_eq!(decoded.recipient, Address::with_last_byte(0x40));
628        assert_eq!(decoded.blockedNonce, 7);
629        assert_eq!(decoded.kind, IReceivePolicyGuard::InboundKind::TRANSFER);
630    }
631
632    #[test]
633    fn rejects_invalid_guard_claim_receipt() {
634        let err = decode_claim_receipt(&Bytes::from_static(&[0xde, 0xad])).unwrap_err();
635        assert!(err.to_string().contains("invalid ReceivePolicyGuard claim receipt"));
636    }
637
638    #[test]
639    fn rejects_semantically_invalid_guard_claim_receipts() {
640        let receipt = sample_receipt();
641        let decoded = IReceivePolicyGuard::ClaimReceiptV1::abi_decode(&receipt).unwrap();
642
643        let mut bad_version = decoded.clone();
644        bad_version.version = 2;
645        let err = decode_claim_receipt(&bad_version.abi_encode().into()).unwrap_err();
646        assert!(err.to_string().contains("unsupported ReceivePolicyGuard claim receipt version"));
647
648        let mut bad_token = decoded.clone();
649        bad_token.token = Address::ZERO;
650        let err = decode_claim_receipt(&bad_token.abi_encode().into()).unwrap_err();
651        assert!(err.to_string().contains("token is zero"));
652
653        let mut bad_recipient = decoded.clone();
654        bad_recipient.recipient = RECEIVE_POLICY_GUARD_ADDRESS;
655        let err = decode_claim_receipt(&bad_recipient.abi_encode().into()).unwrap_err();
656        assert!(err.to_string().contains("recipient cannot be the guard precompile"));
657
658        let mut bad_reason = decoded;
659        bad_reason.blockedReason = ITIP403Registry::BlockedReason::NONE as u8;
660        let err = decode_claim_receipt(&bad_reason.abi_encode().into()).unwrap_err();
661        assert!(err.to_string().contains("blocked reason is not claimable"));
662    }
663
664    #[test]
665    fn validate_payload_records_effective_receiver() {
666        let receiver = Address::new_virtual(
667            MasterId::from([0x12, 0x34, 0x56, 0x78]),
668            UserTag::from([0xab, 0xcd, 0xef, 0x01, 0x23, 0x45]),
669        );
670        let effective_receiver = Address::with_last_byte(0x40);
671
672        let payload = validate_payload(
673            Address::with_last_byte(0x10),
674            Address::with_last_byte(0x30),
675            receiver,
676            effective_receiver,
677            false,
678            ITIP403Registry::BlockedReason::RECEIVE_POLICY,
679            "held",
680        );
681
682        assert_eq!(payload["receiver"], format!("{receiver}"));
683        assert_eq!(payload["effective_receiver"], format!("{effective_receiver}"));
684        assert_eq!(payload["receiver_was_resolved"], true);
685        assert_eq!(payload["authorized"], false);
686        assert_eq!(payload["blocked_reason"], "receive_policy");
687        assert_eq!(payload["delivery_state"], "held");
688    }
689
690    #[test]
691    fn receipt_payload_preserves_delivery_state_confidence() {
692        let receipt = sample_receipt();
693        let decoded = decode_claim_receipt(&receipt).unwrap();
694
695        let unknown = receipt_payload(&receipt, &decoded, None);
696        assert_eq!(unknown["delivery_state"], "unknown");
697
698        let held = receipt_payload(&receipt, &decoded, Some(U256::ONE));
699        assert_eq!(held["delivery_state"], "held");
700        assert_eq!(held["blocked_reason"], "receive_policy");
701        assert_eq!(held["kind"], "transfer");
702        assert_eq!(held["held_balance"], "1");
703        assert_eq!(held["recipient_is_virtual"], false);
704        assert_eq!(held["claim_target"], format!("{}", decoded.recipient));
705
706        let not_held = receipt_payload(&receipt, &decoded, Some(U256::ZERO));
707        assert_eq!(not_held["delivery_state"], "not_held");
708        assert_eq!(not_held["held_balance"], "0");
709    }
710
711    #[test]
712    fn virtual_receipt_recipient_requires_resolved_claim_target() {
713        let receipt = sample_receipt();
714        let mut decoded = decode_claim_receipt(&receipt).unwrap();
715        decoded.recipient = Address::new_virtual(
716            MasterId::from([0x12, 0x34, 0x56, 0x78]),
717            UserTag::from([0xab, 0xcd, 0xef, 0x01, 0x23, 0x45]),
718        );
719
720        let payload = receipt_payload(&receipt, &decoded, None);
721        assert_eq!(payload["recipient"], format!("{}", decoded.recipient));
722        assert_eq!(payload["recipient_is_virtual"], true);
723        assert_eq!(payload["claim_target"], Value::Null);
724    }
725
726    #[test]
727    fn originator_recovery_receipt_requires_explicit_claim_target() {
728        let receipt = sample_receipt();
729        let mut decoded = decode_claim_receipt(&receipt).unwrap();
730        decoded.recoveryAuthority = Address::ZERO;
731
732        let payload = receipt_payload(&receipt, &decoded, None);
733        assert_eq!(payload["recovery_mode"], "originator");
734        assert_eq!(payload["recipient_is_virtual"], false);
735        assert_eq!(payload["claim_target"], Value::Null);
736    }
737
738    #[test]
739    fn originator_recovery_takes_precedence_over_virtual_recipient() {
740        let receipt = sample_receipt();
741        let mut decoded = decode_claim_receipt(&receipt).unwrap();
742        decoded.recoveryAuthority = Address::ZERO;
743        decoded.recipient = Address::new_virtual(
744            MasterId::from([0x12, 0x34, 0x56, 0x78]),
745            UserTag::from([0xab, 0xcd, 0xef, 0x01, 0x23, 0x45]),
746        );
747
748        let payload = receipt_payload(&receipt, &decoded, None);
749        assert_eq!(payload["recovery_mode"], "originator");
750        assert_eq!(payload["recipient_is_virtual"], true);
751        assert_eq!(payload["claim_target"], Value::Null);
752    }
753
754    #[test]
755    fn rejects_unclaimable_recovery_authorities() {
756        // Originator recovery and a plain EOA authority are valid.
757        assert_eq!(invalid_recovery_authority_message(Address::ZERO), None);
758        assert_eq!(invalid_recovery_authority_message(Address::repeat_byte(0x11)), None);
759
760        // Every fixed Tempo system precompile is unclaimable.
761        for authority in TEMPO_PRECOMPILE_ADDRESSES {
762            let err = invalid_recovery_authority_message(*authority).unwrap();
763            assert!(err.contains("fixed Tempo system precompile"));
764        }
765
766        // TIP-20 token and TIP-1022 virtual addresses are unclaimable too.
767        let err = invalid_recovery_authority_message(address!(
768            "20c0000000000000000000000000000000000001"
769        ))
770        .unwrap();
771        assert!(err.contains("TIP-20 token address"));
772
773        let virtual_address = Address::new_virtual(
774            MasterId::from([0x12, 0x34, 0x56, 0x78]),
775            UserTag::from([0xab, 0xcd, 0xef, 0x01, 0x23, 0x45]),
776        );
777        let err = invalid_recovery_authority_message(virtual_address).unwrap();
778        assert!(err.contains("TIP-1022 virtual address"));
779    }
780}