Skip to main content

cast/cmd/tempo/zone/
mod.rs

1//! Deposits to Tempo L1 portals and authenticated zone withdrawals.
2
3use crate::tempo::tempo_provider;
4use alloy_network::primitives::ReceiptResponse;
5use alloy_primitives::{Address, B256, Bytes, U256};
6use alloy_provider::{PendingTransactionBuilder, Provider, ProviderBuilder};
7use alloy_rpc_types::BlockId;
8use clap::Parser;
9use eyre::{Result, WrapErr, ensure};
10use foundry_cli::{json::print_scalar, opts::RpcOpts, utils::LoadConfig};
11use foundry_common::{sh_status, shell};
12use foundry_config::Config;
13use foundry_wallets::{WalletOpts, WalletSigner};
14use signer::{ConfigurableAccountOpts, ZoneSigner};
15use std::{sync::Arc, time::Duration};
16use tempo_alloy::{TempoNetwork, rpc::TempoTransactionReceipt};
17use tempo_contracts::precompiles::{ITIP20, PATH_USD_ADDRESS};
18
19mod abi;
20mod auth;
21mod earn;
22mod encryption;
23mod l1;
24mod signer;
25
26// Mirrored from zones/crates/primitives and zones/crates/precompiles at a1c15e9f.
27const MAX_CALLBACK_GAS_LIMIT: u64 = 10_000_000;
28const MAX_CALLBACK_DATA_SIZE: usize = 1024;
29
30/// Tempo zone operations.
31#[derive(Debug, Parser)]
32pub struct ZoneArgs {
33    #[command(subcommand)]
34    command: ZoneSubcommand,
35}
36
37#[derive(Debug, Parser)]
38enum ZoneSubcommand {
39    /// Encrypt a deposit and submit it to a portal on Tempo L1.
40    ///
41    /// --rpc-url selects the L1 RPC. The receipt confirms L1 submission, not zone completion.
42    Deposit(DepositArgs),
43    /// Request a withdrawal using the authenticated zone RPC.
44    ///
45    /// --rpc-url selects the zone RPC. The receipt confirms the request, not L1 settlement.
46    Withdraw(WithdrawArgs),
47    /// Build encrypted callbacks for the scoped Earn router.
48    Earn(earn::EarnArgs),
49}
50
51#[derive(Debug, Parser)]
52struct TransferArgs {
53    /// TIP-20 token address on the source chain.
54    #[arg(long, default_value_t = PATH_USD_ADDRESS)]
55    token: Address,
56    /// Amount in the token's smallest units.
57    #[arg(long)]
58    amount: u128,
59    /// Destination address. Defaults to the sender.
60    #[arg(long)]
61    to: Option<Address>,
62    /// Transfer memo.
63    #[arg(long, default_value_t = B256::ZERO)]
64    memo: B256,
65    /// Approve the required amount (including withdrawal fees) if allowance is insufficient.
66    #[arg(long)]
67    approve: bool,
68    #[command(flatten)]
69    rpc: RpcOpts,
70    #[command(flatten)]
71    wallet: WalletOpts,
72    #[command(flatten)]
73    configurable_account: ConfigurableAccountOpts,
74}
75
76#[derive(Debug, Parser)]
77struct DepositArgs {
78    /// Zone portal address on Tempo L1.
79    #[arg(long, env = "L1_PORTAL_ADDRESS")]
80    portal: Address,
81    /// Tempo L1 refund recipient if the deposit fails. Defaults to the sender.
82    #[arg(long)]
83    refund_recipient: Option<Address>,
84    #[command(flatten)]
85    transfer: TransferArgs,
86}
87
88#[derive(Debug, Parser)]
89struct WithdrawArgs {
90    /// Zone ID used to scope the RPC authorization token.
91    #[arg(long, env = "ZONE_ID")]
92    zone_id: u32,
93    /// Zone chain ID used to sign the RPC authorization token before connecting.
94    #[arg(long, env = "ZONE_CHAIN_ID")]
95    zone_chain_id: u64,
96    /// L1 callback gas limit. Zero disables the callback.
97    #[arg(long, default_value_t = 0)]
98    callback_gas_limit: u64,
99    /// Zone recipient for bounced withdrawals if L1 execution fails. Defaults to the sender.
100    #[arg(long)]
101    fallback_recipient: Option<Address>,
102    /// Data passed to the L1 receiver's withdrawal callback, without a function selector.
103    #[arg(long, default_value = "0x")]
104    callback_data: Bytes,
105    /// Compressed secp256k1 key for revealing the withdrawal sender.
106    #[arg(long, default_value = "0x")]
107    reveal_to: Bytes,
108    /// Wait for successful L1 delivery, including callback execution. Does not wait for a return
109    /// deposit.
110    #[arg(long)]
111    wait_l1: bool,
112    /// Maximum seconds to wait for L1 settlement after zone inclusion.
113    #[arg(long, default_value_t = 180, value_parser = clap::value_parser!(u64).range(1..))]
114    wait_timeout: u64,
115    #[command(flatten)]
116    l1: l1::L1Args,
117    #[command(flatten)]
118    transfer: TransferArgs,
119}
120
121impl ZoneArgs {
122    pub async fn run(self) -> Result<()> {
123        match self.command {
124            ZoneSubcommand::Deposit(args) => args.run().await,
125            ZoneSubcommand::Withdraw(args) => args.run().await,
126            ZoneSubcommand::Earn(args) => args.run().await,
127        }
128    }
129}
130
131impl TransferArgs {
132    /// Checks the transfer and returns the wallet's key, if any.
133    async fn local_signer(&self) -> Result<Option<WalletSigner>> {
134        ensure!(!self.rpc.curl, "zone operations do not support --curl");
135        ensure!(self.amount > 0, "amount must be greater than zero");
136        Ok(self.wallet.maybe_signer().await?.0)
137    }
138
139    /// Resolves the sender from the wallet's key `local`, detecting a configurable account on
140    /// the Tempo L1 that `l1` connects to.
141    async fn signer(
142        &self,
143        local: Option<WalletSigner>,
144        l1: Option<&Config>,
145    ) -> Result<Arc<ZoneSigner>> {
146        let signer = ZoneSigner::resolve(&self.wallet, &self.configurable_account, local, l1);
147        Ok(Arc::new(signer.await?))
148    }
149
150    async fn ensure_allowance(
151        &self,
152        provider: &impl Provider<TempoNetwork>,
153        signer: &ZoneSigner,
154        spender: Address,
155        amount: u128,
156        gas_price: Option<u128>,
157    ) -> Result<()> {
158        let sender = signer.address();
159        let token = ITIP20::new(self.token, provider);
160        let amount = U256::from(amount);
161        if token.allowance(sender, spender).from(sender).call().await? < amount {
162            ensure!(
163                self.approve,
164                "insufficient token allowance for {spender}; use --approve to approve the deposit or withdrawal amount"
165            );
166            sh_status!("Approving {} for {}", amount, spender)?;
167            let mut approval =
168                token.approve(spender, amount).from(sender).map(|tx| signer.prepare(tx));
169            if let Some(gas_price) = gas_price {
170                approval = approval.max_fee_per_gas(gas_price).max_priority_fee_per_gas(0);
171            }
172            let receipt = submitted_receipt("token approval", approval.send().await?).await?;
173            ensure!(receipt.status(), "token approval reverted: {}", receipt.transaction_hash());
174        }
175        Ok(())
176    }
177}
178
179impl DepositArgs {
180    async fn run(self) -> Result<()> {
181        let (config, provider) = tempo_provider(&self.transfer.rpc)?;
182        let local = self.transfer.local_signer().await?;
183        let signer = self.transfer.signer(local, Some(&config)).await?;
184        let sender = signer.address();
185        let provider = ProviderBuilder::new_with_network::<TempoNetwork>()
186            .wallet(signer.clone())
187            .connect_provider(provider);
188        let portal = abi::IZonePortal::new(self.portal, &provider);
189        let block = provider.get_block_number().await?;
190        let key = portal
191            .encryptionKeyAtBlock(block)
192            .block(BlockId::number(block))
193            .call()
194            .await
195            .wrap_err("failed to fetch portal encryption key")?;
196        let payload = encryption::encrypt_deposit(
197            key.x,
198            key.yParity,
199            self.transfer.to.unwrap_or(sender),
200            self.transfer.memo,
201            sender,
202            self.portal,
203            key.keyIndex,
204        )?;
205        self.transfer
206            .ensure_allowance(&provider, &signer, self.portal, self.transfer.amount, None)
207            .await?;
208        let pending = portal
209            .deposit(
210                self.transfer.token,
211                self.transfer.amount,
212                key.keyIndex,
213                payload,
214                self.refund_recipient.unwrap_or(sender),
215            )
216            .from(sender)
217            .map(|tx| signer.prepare(tx))
218            .send()
219            .await?;
220        let receipt = submitted_receipt("deposit", pending).await?;
221        ensure!(receipt.status(), "deposit reverted: {}", receipt.transaction_hash());
222        let _ = sh_status!("Deposit submitted on L1; zone processing is asynchronous.");
223        print_receipt(&receipt)
224    }
225}
226
227impl WithdrawArgs {
228    async fn run(self) -> Result<()> {
229        validate_callback(&self.callback_data, self.callback_gas_limit)?;
230        ensure!(self.zone_id != 0, "--zone-id must be nonzero");
231        ensure!(self.zone_chain_id != 0, "--zone-chain-id must be nonzero");
232        if !self.reveal_to.is_empty() {
233            ensure!(
234                self.reveal_to.len() == 33
235                    && k256::PublicKey::from_sec1_bytes(&self.reveal_to).is_ok(),
236                "--reveal-to must be a compressed secp256k1 public key"
237            );
238        }
239        // The zone RPC needs the token before it answers, so a configurable account sender is
240        // detected on Tempo L1, whose commitments zones follow (TIP-1154). Only a sender that may
241        // be one queries L1, so that a plain key does not reveal itself to a public L1 RPC.
242        let local = self.transfer.local_signer().await?;
243        let configurable = &self.transfer.configurable_account;
244        let l1 = if configurable.may_select(&self.transfer.wallet, local.as_ref())? {
245            let url =
246                self.l1.parent_rpc_url(self.zone_chain_id, self.zone_id).await.wrap_err(
247                    "could not check the sender on the zone's Tempo L1; pass --l1-rpc-url",
248                )?;
249            Some(Config { eth_rpc_url: Some(url), ..Default::default() })
250        } else {
251            None
252        };
253        let signer = self.transfer.signer(local, l1.as_ref()).await?;
254        let sender = signer.address();
255        let token = auth::sign_token(&signer, self.zone_id, self.zone_chain_id)
256            .await
257            .wrap_err("wallet could not sign zone RPC authorization")?;
258        let mut config = self.transfer.rpc.load_config()?;
259        let headers = config.eth_rpc_headers.get_or_insert_default();
260        headers.retain(|header| {
261            !header
262                .split_once(':')
263                .is_some_and(|(name, _)| name.trim().eq_ignore_ascii_case(auth::HEADER))
264        });
265        headers.push(format!("{}: {token}", auth::HEADER));
266        let provider =
267            foundry_common::provider::ProviderBuilder::<TempoNetwork>::from_config(&config)?
268                .build()?;
269        let provider = ProviderBuilder::new_with_network::<TempoNetwork>()
270            .wallet(signer.clone())
271            .connect_provider(provider);
272        let chain_id = match provider.get_chain_id().await {
273            Ok(chain_id) => chain_id,
274            // The zone answers a rejected token with a bare 401 or 403.
275            Err(err)
276                if err
277                    .as_transport_err()
278                    .and_then(|err| err.as_http_error())
279                    .is_some_and(|err| matches!(err.status, 401 | 403)) =>
280            {
281                let hint = match &*signer {
282                    ZoneSigner::ConfigurableAccount(_) => format!(
283                        "zone RPC rejected the authorization of {sender}; if its configuration \
284                         changed recently on Tempo L1, retry once the zone follows it"
285                    ),
286                    ZoneSigner::Wallet(_) => format!(
287                        "zone RPC rejected the authorization of {sender}; if it is a Tempo \
288                         configurable account, pass --tempo.configurable-account {sender}"
289                    ),
290                };
291                return Err(eyre::Report::new(err).wrap_err(hint));
292            }
293            Err(err) => return Err(err.into()),
294        };
295        ensure!(chain_id == self.zone_chain_id, "zone RPC chain ID differs from --zone-chain-id");
296        // Snapshot L1 before submitting, so fast settlement cannot be missed.
297        let wait = if self.wait_l1 {
298            let l1_provider = self.l1.provider(self.zone_chain_id, self.zone_id).await?;
299            let from_block = l1_provider.get_block_number().await?;
300            Some((l1_provider, from_block))
301        } else {
302            None
303        };
304        let outbox = abi::IZoneOutbox::new(abi::OUTBOX, &provider);
305        let fee =
306            outbox.calculateWithdrawalFee(self.callback_gas_limit).from(sender).call().await?;
307        let total = self
308            .transfer
309            .amount
310            .checked_add(fee)
311            .ok_or_else(|| eyre::eyre!("withdrawal amount plus fee exceeds uint128"))?;
312        // Use the private RPC's gas-price quote without requiring fee-history support.
313        let gas_price = provider.get_gas_price().await?;
314        self.transfer
315            .ensure_allowance(&provider, &signer, abi::OUTBOX, total, Some(gas_price))
316            .await?;
317        let to = self.transfer.to.unwrap_or(sender);
318        let pending = outbox
319            .requestWithdrawal(
320                self.transfer.token,
321                to,
322                self.transfer.amount,
323                self.transfer.memo,
324                self.callback_gas_limit,
325                self.fallback_recipient.unwrap_or(sender),
326                self.callback_data,
327                self.reveal_to,
328            )
329            .max_fee_per_gas(gas_price)
330            .max_priority_fee_per_gas(0)
331            .from(sender)
332            .map(|tx| signer.prepare(tx))
333            .send()
334            .await?;
335        let receipt = submitted_receipt("withdrawal", pending).await?;
336        ensure!(receipt.status(), "withdrawal reverted: {}", receipt.transaction_hash());
337        let hash = receipt.transaction_hash();
338        if let Some((l1_provider, from_block)) = wait {
339            let _ = sh_status!("Withdrawal requested: {hash}; waiting for L1 delivery.");
340            let result = l1::wait_for_withdrawal(
341                &provider,
342                &l1_provider,
343                self.l1.portal()?,
344                from_block,
345                receipt.block_number().ok_or_else(|| eyre::eyre!("missing zone receipt block"))?,
346                hash,
347            );
348            let l1_hash = tokio::time::timeout(Duration::from_secs(self.wait_timeout), result)
349                .await
350                .wrap_err_with(|| {
351                    format!(
352                        "L1 wait timed out; withdrawal {hash} is already submitted; do not resubmit"
353                    )
354                })?
355                .wrap_err_with(|| format!("L1 wait failed for submitted withdrawal {hash}"))?;
356            let _ = sh_status!("Withdrawal delivered on L1: {l1_hash}");
357        } else {
358            let _ = sh_status!("Withdrawal requested on the zone; L1 settlement is asynchronous.");
359        }
360        print_receipt(&receipt)
361    }
362}
363
364async fn submitted_receipt(
365    action: &str,
366    pending: PendingTransactionBuilder<TempoNetwork>,
367) -> Result<TempoTransactionReceipt> {
368    let hash = *pending.tx_hash();
369    let receipt = pending.with_timeout(Some(Duration::from_secs(120))).get_receipt();
370    tokio::time::timeout(Duration::from_secs(120), receipt)
371        .await
372        .wrap_err_with(|| {
373            format!("{action} {hash} was submitted; receipt polling timed out; do not resubmit")
374        })?
375        .wrap_err_with(|| {
376            format!("{action} {hash} was submitted; receipt polling failed; do not resubmit")
377        })
378}
379
380fn validate_callback(data: &Bytes, gas_limit: u64) -> Result<()> {
381    ensure!(
382        data.is_empty() || gas_limit > 0,
383        "--callback-data requires a nonzero --callback-gas-limit"
384    );
385    ensure!(
386        data.len() <= MAX_CALLBACK_DATA_SIZE,
387        "--callback-data exceeds the protocol limit of {MAX_CALLBACK_DATA_SIZE} bytes"
388    );
389    ensure!(
390        gas_limit <= MAX_CALLBACK_GAS_LIMIT,
391        "--callback-gas-limit exceeds the protocol limit of {MAX_CALLBACK_GAS_LIMIT}"
392    );
393    Ok(())
394}
395
396fn print_receipt(receipt: &(impl ReceiptResponse + serde::Serialize)) -> Result<()> {
397    if shell::is_json() {
398        foundry_common::sh_println!("{}", serde_json::to_string(receipt)?)?;
399        Ok(())
400    } else {
401        print_scalar(receipt.transaction_hash())
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408    use crate::cmd::tempo::{TempoArgs, TempoSubcommand};
409
410    #[test]
411    fn zone_commands_accept_cast_keystore_wallets() {
412        for args in [
413            vec![
414                "tempo",
415                "zone",
416                "deposit",
417                "--portal",
418                "0x1111111111111111111111111111111111111111",
419                "--amount",
420                "1000000",
421                "--account",
422                "zone-test",
423                "--password-file",
424                "/tmp/password",
425                "--approve",
426            ],
427            vec![
428                "tempo",
429                "zone",
430                "withdraw",
431                "--zone-id",
432                "42",
433                "--zone-chain-id",
434                "1337",
435                "--amount",
436                "1000000",
437                "--account",
438                "zone-test",
439                "--password-file",
440                "/tmp/password",
441                "--approve",
442            ],
443        ] {
444            let tempo = TempoArgs::try_parse_from(args).unwrap();
445            assert!(matches!(tempo.command, TempoSubcommand::Zone(_)));
446        }
447    }
448
449    #[test]
450    fn callback_limits_match_zone_protocol() {
451        assert!(validate_callback(&Bytes::from(vec![0; 1024]), 10_000_000).is_ok());
452        assert!(validate_callback(&Bytes::from(vec![0; 1025]), 10_000_000).is_err());
453        assert!(validate_callback(&Bytes::new(), 10_000_001).is_err());
454        assert!(validate_callback(&Bytes::from_static(&[1]), 0).is_err());
455    }
456
457    #[test]
458    fn parses_settlement_wait() {
459        assert!(
460            TempoArgs::try_parse_from([
461                "tempo",
462                "zone",
463                "withdraw",
464                "--zone-id",
465                "42",
466                "--zone-chain-id",
467                "1337",
468                "--amount",
469                "1",
470                "--wait-l1",
471            ])
472            .is_ok()
473        );
474    }
475}