aspens 0.8.0

Aspens crosschain trading SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
use std::str::FromStr;

use crate::chain_client::named_chain_for;
use alloy::network::EthereumWallet;
use alloy::primitives::{Address, Bytes, U256};
use alloy::providers::{Provider, ProviderBuilder};
use alloy::signers::Signer;
use alloy::signers::local::PrivateKeySigner;
use eyre::Result;
use url::Url;

use crate::chain_client::ARCH_SOLANA;
use crate::commands::config::config_pb::GetConfigResponse;
use crate::evm::rpc::MidribV3;
use crate::grpc::create_channel;
use crate::wallet::{CurveType, Wallet};

use super::arborter_pb::WithdrawRequest;
use super::arborter_pb::arborter_service_client::ArborterServiceClient;

/// Minimum gas balance required for transactions (0.0001 ETH = 100000 gwei)
const MIN_GAS_BALANCE: u128 = 100_000_000_000_000; // 0.0001 ETH in wei

/// Where the TEE-signed withdrawal voucher is requested from.
///
/// The voucher is the ONLY part of a withdraw that needs the arborter — the gas
/// pre-check, the on-chain submit, and the resubmit-on-transient-revert logic
/// below are pure chain work and are identical either way. Keeping the choice in
/// one enum is what lets the FCE path reuse all of that verbatim instead of
/// forking a second withdraw implementation that could drift.
pub(crate) enum VoucherSource<'a> {
    /// Arborter gRPC at this stack URL (the default).
    Grpc(&'a str),
    /// The FCE ext-proxy (`POST /direct` + poll, command WITHDRAW).
    #[cfg(feature = "fce")]
    Fce(&'a crate::fce::FceClient),
}

/// The voucher fields both transports return, normalized. Deliberately not the
/// gRPC `WithdrawResponse`: the submit code below should not care which wire
/// produced these bytes.
pub(crate) struct Voucher {
    /// u128 decimal, echoed by the arborter.
    amount: String,
    nonce: u64,
    expiry: u64,
    signature: Vec<u8>,
}

impl VoucherSource<'_> {
    /// Request a voucher for an already-authenticated withdraw. `signature` is
    /// the caller's signature over the canonical `network|token|account|amount`
    /// bytes — both transports carry exactly those bytes, so the arborter
    /// authenticates identically regardless of which one is in use.
    async fn fetch(
        &self,
        network: &str,
        token: &str,
        account: &str,
        amount: &str,
        signature: Vec<u8>,
    ) -> Result<Voucher> {
        match self {
            Self::Grpc(url) => {
                let channel = create_channel(url).await?;
                let mut client = ArborterServiceClient::new(channel);
                let v = client
                    .withdraw(tonic::Request::new(WithdrawRequest {
                        network: network.to_string(),
                        token: token.to_string(),
                        account: account.to_string(),
                        amount: amount.to_string(),
                        signature,
                    }))
                    .await?
                    .into_inner();
                Ok(Voucher {
                    amount: v.amount,
                    nonce: v.nonce,
                    expiry: v.expiry,
                    signature: v.signature,
                })
            }
            #[cfg(feature = "fce")]
            Self::Fce(fce) => {
                let outcome = fce
                    .withdraw(&crate::fce::WithdrawRequest {
                        network: network.to_string(),
                        token: token.to_string(),
                        account: account.to_string(),
                        amount: amount.to_string(),
                        signature,
                    })
                    .await?;
                let v = outcome.into_data()?;
                Ok(Voucher {
                    amount: v.amount,
                    nonce: v.nonce,
                    expiry: v.expiry,
                    signature: v.signature,
                })
            }
        }
    }

    /// The instance signer pubkey for `chain` — the Ed25519 key that signed a
    /// Solana voucher, which the on-chain program's verify must recover to.
    ///
    /// Only the gRPC transport has a `GetSignerPublicKey` RPC; the direct-action
    /// wire has no such command. Over FCE this comes from the chain config
    /// instead, which the same proxy already serves via `GET_CONFIG`.
    #[cfg(feature = "solana")]
    async fn instance_signer_pubkey(
        &self,
        chain: &crate::commands::config::config_pb::Chain,
    ) -> Result<String> {
        match self {
            Self::Grpc(url) => {
                let resp = crate::commands::config::get_signer_public_key(
                    url.to_string(),
                    Some(chain.network.clone()),
                )
                .await?;
                resp.chain_keys
                    .get(&chain.network)
                    .map(|k| k.public_key.clone())
                    .ok_or_else(|| {
                        eyre::eyre!("no signer public key for chain '{}'", chain.network)
                    })
            }
            #[cfg(feature = "fce")]
            Self::Fce(_) => {
                let key = chain.instance_signer_address.trim();
                if key.is_empty() {
                    // Fail loudly rather than submitting a voucher whose
                    // signature can't be verified on-chain: the tx would revert
                    // after the hold is already placed.
                    return Err(eyre::eyre!(
                        "chain '{}' has no instance_signer_address in the config, and the FCE \
                         direct-action wire has no GetSignerPublicKey command — the Solana \
                         voucher's signer key cannot be resolved. Set it on the chain entry \
                         (aspens-admin set-chain --instance-signer-address) and re-fetch config.",
                        chain.network
                    ));
                }
                Ok(key.to_string())
            }
        }
    }
}

/// Withdraw tokens using a curve-agnostic wallet.
///
/// Branches on `chain.architecture`:
/// - **EVM**: requests a TEE-signed withdrawal voucher from the arborter
///   (`url`) over gRPC, then submits `MidribV3.withdraw(voucher, signature)`
///   on-chain (the wallet pays gas). There is no permissionless on-chain
///   `withdraw`; the voucher is the authorization.
/// - **Solana**: requests a TEE-signed withdrawal voucher from the arborter,
///   then submits the Midrib program's `withdraw_voucher` instruction
///   on-chain (the wallet pays gas). The voucher is the authorization,
///   mirroring the EVM path.
pub async fn call_withdraw_from_config_with_wallet(
    url: String,
    network: String,
    token_symbol: String,
    amount: u128,
    wallet: &Wallet,
    config: GetConfigResponse,
) -> Result<()> {
    call_withdraw_from_config_with_wallet_opts(
        url,
        network,
        token_symbol,
        amount,
        wallet,
        config,
        WithdrawOpts::default(),
    )
    .await
}

/// Behavior options for [`call_withdraw_from_config_with_wallet_opts`].
#[derive(Debug, Clone)]
pub struct WithdrawOpts {
    /// Solana WSOL (native SOL) withdrawals only: after the voucher withdraw
    /// lands, close the WSOL ATA in the same transaction, unwrapping its
    /// ENTIRE wrapped balance (withdrawn amount + any pre-existing WSOL) plus
    /// rent back to SOL — standard wallet behavior. Set `false` to keep the
    /// withdrawn funds as WSOL (e.g. when deliberately holding wrapped SOL).
    pub unwrap_native: bool,
}

impl Default for WithdrawOpts {
    fn default() -> Self {
        Self {
            unwrap_native: true,
        }
    }
}

/// [`call_withdraw_from_config_with_wallet`] with explicit [`WithdrawOpts`].
pub async fn call_withdraw_from_config_with_wallet_opts(
    url: String,
    network: String,
    token_symbol: String,
    amount: u128,
    wallet: &Wallet,
    config: GetConfigResponse,
    opts: WithdrawOpts,
) -> Result<()> {
    withdraw_from_source(
        VoucherSource::Grpc(&url),
        network,
        token_symbol,
        amount,
        wallet,
        config,
        opts,
    )
    .await
}

/// [`call_withdraw_from_config_with_wallet_opts`], sourcing the voucher from the
/// FCE ext-proxy instead of arborter gRPC.
///
/// Everything after the voucher is byte-identical to the gRPC path — same
/// canonical request signature, same on-chain `MidribV3.withdraw` submit, same
/// retries. Only the transport that carries the voucher request differs.
#[cfg(feature = "fce")]
pub async fn call_withdraw_from_config_with_fce_opts(
    fce: &crate::fce::FceClient,
    network: String,
    token_symbol: String,
    amount: u128,
    wallet: &Wallet,
    config: GetConfigResponse,
    opts: WithdrawOpts,
) -> Result<()> {
    withdraw_from_source(
        VoucherSource::Fce(fce),
        network,
        token_symbol,
        amount,
        wallet,
        config,
        opts,
    )
    .await
}

async fn withdraw_from_source(
    source: VoucherSource<'_>,
    network: String,
    token_symbol: String,
    amount: u128,
    wallet: &Wallet,
    config: GetConfigResponse,
    opts: WithdrawOpts,
) -> Result<()> {
    let chain_for_arch = config
        .get_chain(&network)
        .ok_or_else(|| eyre::eyre!("Chain '{}' not found in configuration", network))?;

    if chain_for_arch
        .architecture
        .eq_ignore_ascii_case(ARCH_SOLANA)
    {
        // Solana SPL token amounts are natively u64 — downcast (checked) at the
        // boundary (DEC-1: u128 upstream, u64 on Solana).
        let spl_amount: u64 = amount.try_into().map_err(|_| {
            eyre::eyre!("amount {amount} exceeds the SPL token u64 max on Solana chain '{network}'")
        })?;
        return solana_withdraw(
            source,
            chain_for_arch,
            &token_symbol,
            spl_amount,
            wallet,
            opts.unwrap_native,
        )
        .await;
    }

    if wallet.curve() != CurveType::Secp256k1 {
        return Err(eyre::eyre!(
            "EVM chain '{}' requires a secp256k1 wallet, got {:?}",
            network,
            wallet.curve()
        ));
    }
    let signer = wallet
        .as_evm()
        .ok_or_else(|| eyre::eyre!("expected EVM wallet for chain '{}'", network))?
        .clone();

    call_withdraw_from_config_evm(source, network, token_symbol, amount, signer, config).await
}

/// Solana withdraw — requests a TEE-signed withdrawal voucher from the
/// arborter, then builds and submits the Midrib program's `withdraw_voucher`
/// instruction. Requires the `solana` feature.
#[cfg(feature = "solana")]
async fn solana_withdraw(
    source: VoucherSource<'_>,
    chain: &crate::commands::config::config_pb::Chain,
    token_symbol: &str,
    amount: u64,
    wallet: &Wallet,
    unwrap_native: bool,
) -> Result<()> {
    use solana_sdk::pubkey::Pubkey;
    use std::str::FromStr;

    let token = chain.tokens.get(token_symbol).ok_or_else(|| {
        eyre::eyre!(
            "Token '{}' not found on Solana chain '{}'",
            token_symbol,
            chain.network
        )
    })?;
    let keypair = wallet.as_solana().ok_or_else(|| {
        eyre::eyre!(
            "Solana chain '{}' requires an Ed25519 wallet (TRADER_PRIVKEY_SOLANA)",
            chain.network
        )
    })?;

    let (program_id, instance) = crate::solana::client::resolve_program_and_instance(chain)?;
    // Before requesting a voucher (which places a hold): a missing or dead
    // endpoint fails here, politely, with nothing held.
    let rpc_url = crate::chain_client::checked_chain_rpc_url(chain).await?;
    let user = solana_sdk::signer::Signer::pubkey(keypair);
    let mint = Pubkey::from_str(&token.address)
        .map_err(|e| eyre::eyre!("invalid Solana mint '{}': {}", token.address, e))?;
    let user_ata = crate::solana::derive_associated_token_account(&user, &mint);

    // 0) Pre-flight SOL check BEFORE requesting a voucher. A voucher places an
    //    off-chain withdraw HOLD on the funds (the arborter reserves them so
    //    they can't be re-withdrawn/traded until the voucher lands or expires).
    //    Requesting one we can't pay to submit — a 0-lamport fee-payer fails
    //    with "Attempt to debit an account but found no record of a prior
    //    credit" — would strand that hold until expiry. Fail fast instead so
    //    the funds stay immediately withdrawable.
    {
        use solana_client::nonblocking::rpc_client::RpcClient;
        let rpc = RpcClient::new(rpc_url.clone());
        let lamports = rpc.get_balance(&user).await.unwrap_or(0);
        if lamports < MIN_SOL_LAMPORTS {
            return Err(eyre::eyre!(
                "insufficient SOL for fees: wallet {user} has {lamports} lamports, \
                 need >= {MIN_SOL_LAMPORTS}. Fund/airdrop SOL before withdrawing — \
                 requesting a voucher now would place an off-chain hold you can't submit.",
            ));
        }
    }

    // 1) Authenticate the request: Ed25519-sign the canonical bytes the arborter
    //    rebuilds (`network|token|account|amount`).
    let account_str = user.to_string();
    let canonical = format!(
        "{}|{}|{}|{}",
        chain.network, token.address, account_str, amount
    );
    let req_sig = wallet.sign_message(canonical.as_bytes()).await?;

    // 2) Request the TEE-signed voucher.
    let voucher = source
        .fetch(
            &chain.network,
            &token.address,
            &account_str,
            &amount.to_string(),
            req_sig,
        )
        .await?;
    tracing::info!(
        "Received Solana withdrawal voucher (nonce={}, deadline_slot={})",
        voucher.nonce,
        voucher.expiry
    );

    // 3) Fetch the instance signer pubkey (the Ed25519 key that signed the
    //    voucher) so the program's Ed25519 verify recovers to it.
    let signer_str = source.instance_signer_pubkey(chain).await?;
    let signer_pk = Pubkey::from_str(&signer_str)
        .map_err(|e| eyre::eyre!("invalid signer pubkey '{}': {}", signer_str, e))?;

    // 4) Rebuild the exact signed payload + the voucher signature.
    let deadline = voucher.expiry; // Solana on-chain deadline is a slot
    let nonce = voucher.nonce;
    let voucher_amount: u64 = voucher
        .amount
        .parse()
        .map_err(|_| eyre::eyre!("invalid voucher amount '{}'", voucher.amount))?;
    let voucher_sig: [u8; 64] = voucher
        .signature
        .as_slice()
        .try_into()
        .map_err(|_| eyre::eyre!("voucher signature must be 64 bytes (Ed25519)"))?;
    let msg = crate::solana::withdrawal_voucher_signing_message(
        &instance,
        &user,
        &mint,
        voucher_amount,
        nonce,
        deadline,
    )?;

    // 5) Submit [create-ATA (idempotent), Ed25519 verify ix, withdraw_voucher ix]
    //    — the user pays + signs. The ATA-create ensures the recipient SPL
    //    account exists (the program won't `init` it); it goes FIRST so the
    //    verify+withdraw pair stay adjacent (the program checks that the ix
    //    immediately before `withdraw_voucher` is the Ed25519 verify).
    let verify_ix = crate::solana::ed25519_verify_ix(&signer_pk.to_bytes(), &voucher_sig, &msg);
    let args = crate::solana::WithdrawVoucherArgs {
        amount: voucher_amount,
        nonce,
        deadline,
        signature: voucher_sig,
    };
    let wd_ix = crate::solana::withdraw_voucher_ix(
        &program_id,
        &instance,
        &user,
        &mint,
        &user_ata,
        &user,
        &args,
    )?;
    // Submit, with a bounded retry on a transient `InsufficientBalance` (custom
    // program error 0x1771 / 6001). The arborter only issues a voucher once it has
    // CONFIRMED a sufficient settled balance — including after a drain-on-demand
    // that force-settles the chain right before returning the voucher. In
    // that case the on-chain settle may not yet be visible to this tx's
    // `deposited >= amount` check, so the first submit can fail preflight. A
    // failed-at-simulation tx never executes (no `used_nonce` tombstone is
    // created), so resubmitting the SAME voucher is safe once the settle lands.
    // Ensure the withdrawer's destination ATA exists before the SPL transfer
    // (SOL-VOUCHER-ATA). Idempotent — harmless if already present — and ordered
    // FIRST so `verify_ix` stays immediately before `wd_ix`.
    let ata_ix = crate::solana::create_idempotent_ata_ix(&user, &user, &mint, &user_ata);
    let mut ixs = vec![ata_ix, verify_ix, wd_ix];
    // Native SOL (WSOL) withdrawal: unwrap in the same tx by closing the WSOL
    // ATA AFTER the voucher transfer credits it — the close sends the account's
    // ENTIRE wrapped balance + rent back to the user as SOL. Appending keeps
    // verify_ix immediately before wd_ix (the program introspects that pair).
    if unwrap_native && crate::solana::is_wsol_mint(&token.address) {
        tracing::info!("WSOL withdrawal: appending unwrap (CloseAccount) to the voucher tx");
        ixs.push(crate::solana::close_token_account_ix(
            &user_ata, &user, &user,
        ));
    }
    let mut last_err = None;
    let mut sig = None;
    for attempt in 0..VOUCHER_SUBMIT_MAX_ATTEMPTS {
        match crate::solana::client::submit_user_signed_multi(&rpc_url, keypair, &ixs).await {
            Ok(s) => {
                sig = Some(s);
                break;
            }
            Err(e) => {
                let msg = e.to_string();
                let transient = msg.contains("0x1771") || msg.contains("InsufficientBalance");
                if transient && attempt + 1 < VOUCHER_SUBMIT_MAX_ATTEMPTS {
                    tracing::warn!(
                        attempt,
                        "voucher submit hit transient InsufficientBalance (settle not yet visible); retrying"
                    );
                    tokio::time::sleep(std::time::Duration::from_millis(VOUCHER_SUBMIT_RETRY_MS))
                        .await;
                    last_err = Some(e);
                    continue;
                }
                return Err(e);
            }
        }
    }
    let sig = sig.ok_or_else(|| {
        last_err.unwrap_or_else(|| eyre::eyre!("voucher submit failed after retries"))
    })?;
    tracing::info!("Solana withdraw voucher submitted: {}", sig);
    Ok(())
}

/// Minimum SOL (lamports) the fee-payer needs before we request a Solana
/// voucher. ~0.003 SOL — covers the worst case where the withdrawer's
/// destination ATA doesn't exist yet and the idempotent create must pay rent
/// (~0.00204 SOL) plus a couple of tx fees of headroom (SOL-VOUCHER-ATA).
#[cfg(feature = "solana")]
const MIN_SOL_LAMPORTS: u64 = 3_000_000;

/// Max attempts for the Solana voucher submit (retries a transient post-drain
/// `InsufficientBalance` while the force-settle propagates).
#[cfg(feature = "solana")]
const VOUCHER_SUBMIT_MAX_ATTEMPTS: usize = 6;
/// Backoff between voucher-submit retries (~ a couple of slots at 400ms each).
#[cfg(feature = "solana")]
const VOUCHER_SUBMIT_RETRY_MS: u64 = 700;

#[cfg(not(feature = "solana"))]
async fn solana_withdraw(
    _source: VoucherSource<'_>,
    chain: &crate::commands::config::config_pb::Chain,
    _token_symbol: &str,
    _amount: u64,
    _wallet: &Wallet,
    _unwrap_native: bool,
) -> Result<()> {
    Err(eyre::eyre!(
        "chain '{}' is Solana but the `solana` feature is disabled",
        chain.network
    ))
}

/// EVM withdraw via the TEE voucher flow: authenticate the request, get an
/// owner-signed voucher from the arborter, submit it on-chain. There is no
/// permissionless on-chain `withdraw`; the voucher is the only authorization
/// for an exit.
async fn call_withdraw_from_config_evm(
    source: VoucherSource<'_>,
    network: String,
    token_symbol: String,
    amount: u128,
    signer: PrivateKeySigner,
    config: GetConfigResponse,
) -> Result<()> {
    // Look up chain info
    let chain = config.get_chain(&network).ok_or_else(|| {
        let available_chains = config
            .config
            .as_ref()
            .map(|c| {
                c.chains
                    .iter()
                    .map(|ch| ch.network.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            })
            .unwrap_or_default();
        eyre::eyre!(
            "Chain '{}' not found in configuration. Available chains: {}",
            network,
            available_chains
        )
    })?;

    // Look up token info
    let token = config.get_token(&network, &token_symbol).ok_or_else(|| {
        let available_tokens = chain
            .tokens
            .keys()
            .map(|s| s.as_str())
            .collect::<Vec<_>>()
            .join(", ");
        eyre::eyre!(
            "Token '{}' not found on chain '{}'. Available tokens: {}",
            token_symbol,
            network,
            available_tokens
        )
    })?;

    // Get trade contract address
    let contract_address = chain
        .trade_contract
        .as_ref()
        .ok_or_else(|| {
            eyre::eyre!(
                "Trade contract not found for chain '{}'. Please ensure the contract is deployed.",
                network
            )
        })?
        .address
        .clone();

    // alloy's chain metadata, when alloy knows the id. The hand-written match
    // this replaces listed nine chains and then ERRORED on anything else, so a
    // chain the venue happily lists but alloy has no variant for -- HyperEVM
    // testnet 998 -- could not deposit or withdraw at all. See
    // [`named_chain_for`]: an unnamed chain is a normal EVM chain, it just gets
    // no metadata. The RPC reports its own id and the tx is signed here.
    let named_chain = named_chain_for(chain.chain_id as u64);

    // Before requesting a voucher (which places a hold): a missing or dead
    // endpoint fails here, politely, with nothing held.
    let rpc_url = crate::chain_client::checked_chain_rpc_url(chain).await?;

    tracing::info!(
        "Withdrawing {} {} from {} (chain_id: {}, rpc: {})",
        amount,
        token_symbol,
        network,
        chain.chain_id,
        crate::chain_client::redact_rpc_url(&rpc_url)
    );

    let contract_addr: Address = contract_address.parse()?;
    let token_addr: Address = token.address.parse()?;
    let signer_address = signer.address();

    // Build the wallet-enabled provider up front so the gas pre-check and the
    // submit share it.
    let wallet = EthereumWallet::new(signer.clone());
    let rpc_url = Url::parse(&rpc_url)?;
    let provider = match named_chain {
        Some(named) => ProviderBuilder::new()
            .with_chain(named)
            .wallet(wallet)
            .connect_http(rpc_url)
            .erased(),
        None => ProviderBuilder::new()
            .wallet(wallet)
            .connect_http(rpc_url)
            .erased(),
    };

    // 1) Pre-flight gas check BEFORE requesting a voucher. A voucher places an
    //    off-chain withdraw HOLD on the funds (reserved until the voucher lands
    //    or expires), so requesting one we can't submit (no gas) would strand
    //    that hold until expiry. Fail fast instead so the funds stay
    //    immediately withdrawable.
    let gas_balance = provider.get_balance(signer_address).await?;
    tracing::info!("Gas balance: {} wei", gas_balance);
    if gas_balance < U256::from(MIN_GAS_BALANCE) {
        let balance_eth = gas_balance.to::<u128>() as f64 / 1e18;
        return Err(eyre::eyre!(
            "insufficient gas: wallet has {:.6} native tokens, need at least 0.0001 for gas. \
            Fund your wallet ({}) with native tokens on {} to pay for transaction fees. \
            (No voucher requested — your withdrawable balance is untouched.)",
            balance_eth,
            signer_address,
            network
        ));
    }

    // 2) Request a TEE-signed voucher from the arborter. Authenticate the
    //    request by signing the canonical bytes the arborter rebuilds
    //    (`network|token|account|amount`) with the wallet key (EIP-191). The
    //    request strings below MUST match those bytes exactly.
    let req_account = signer_address.to_string();
    let req_token = token.address.clone();
    let req_amount = amount.to_string();
    let canonical = format!("{network}|{req_token}|{req_account}|{req_amount}");
    let req_sig = signer.sign_message(canonical.as_bytes()).await?;

    let voucher = source
        .fetch(
            &network,
            &req_token,
            &req_account,
            &req_amount,
            req_sig.as_bytes().to_vec(),
        )
        .await?;
    tracing::info!(
        "Received withdrawal voucher (nonce={}, expiry={})",
        voucher.nonce,
        voucher.expiry
    );

    // 3) Submit withdraw(voucher, signature) on-chain, RESUBMITTING the SAME
    //    voucher on a transient failure. A settle-propagation race can briefly
    //    revert `MidribV3.withdraw` with INSUFFICIENT_BALANCE (the drain settle
    //    that backs the voucher isn't visible to this tx yet); a reverted tx
    //    never sets `usedWithdrawNonces`, so resubmitting the identical voucher
    //    is safe and avoids re-requesting (which would hit the now-held balance).
    let contract = MidribV3::new(contract_addr, &provider);
    let onchain_voucher = MidribV3::WithdrawalVoucher {
        account: signer_address,
        token: token_addr,
        // Echoed back by the arborter; fall back to the requested amount.
        amount: U256::from_str(&voucher.amount).unwrap_or(U256::from(amount)),
        nonce: U256::from(voucher.nonce),
        expiry: U256::from(voucher.expiry),
    };
    let voucher_sig = Bytes::from(voucher.signature);
    let mut last_err = None;
    let mut result = None;
    for attempt in 0..EVM_VOUCHER_SUBMIT_MAX_ATTEMPTS {
        // `send` and `watch` surface distinct alloy error types, so match each
        // rather than `?`-unify them; flatten both into the retry's last_err.
        let outcome = match contract
            .withdraw(onchain_voucher.clone(), voucher_sig.clone())
            .send()
            .await
        {
            Ok(pending) => pending
                .with_required_confirmations(1)
                .watch()
                .await
                .map_err(|e| eyre::eyre!("{e}")),
            Err(e) => Err(eyre::eyre!("{e}")),
        };
        match outcome {
            Ok(tx) => {
                result = Some(tx);
                break;
            }
            Err(e) => {
                last_err = Some(e);
                if attempt + 1 < EVM_VOUCHER_SUBMIT_MAX_ATTEMPTS {
                    tracing::warn!(
                        attempt,
                        "voucher submit failed (possibly settle-propagation race); \
                         resubmitting the same voucher"
                    );
                    tokio::time::sleep(std::time::Duration::from_millis(
                        EVM_VOUCHER_SUBMIT_RETRY_MS,
                    ))
                    .await;
                }
            }
        }
    }
    let result = result.ok_or_else(|| {
        last_err.unwrap_or_else(|| eyre::eyre!("voucher submit failed after retries"))
    })?;

    tracing::info!("Withdraw voucher submitted on-chain: {result:?}");

    Ok(())
}

/// EVM voucher-submit retries: resubmit the SAME voucher on a transient
/// settle-propagation revert. Bounded; a reverted tx doesn't consume the
/// on-chain nonce, so resubmission is safe.
const EVM_VOUCHER_SUBMIT_MAX_ATTEMPTS: usize = 4;
/// Backoff between EVM voucher-submit retries.
const EVM_VOUCHER_SUBMIT_RETRY_MS: u64 = 700;