moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
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
//! Sign + prove + finalize + submit a wallet recipe.
//!
//! Returns the bytes alongside the submission event so hosts that want
//! to record the transaction (CLI's pending-tx + tx-history disk
//! stores) can do so without recomputing the on-chain payload.

use std::sync::Arc;
use std::time::Duration as StdDuration;

use anyhow::{anyhow, Context, Result};
use moonproof_ledger::base_crypto::time::{Duration as MidnightDuration, Timestamp};
use moonproof_node_client::{SubmissionEvent, SubmissionStage};
use moonproof_prover::{EngineProvingProvider, HttpProvingProvider, ProverEngine};

use crate::facade::{
    finalize_recipe as finalize_facade_recipe, serialize_finalized, sign_recipe, submit_finalized,
};
use crate::{SubmissionOptions, TokenType, UnprovenTransactionRecipe, WalletError};

/// Where to compute the ZK proof for a wallet-built transaction.
/// Mirrors the proof-server picker in the Flutter app's Settings.
#[derive(Debug, Clone, Default)]
pub enum ProvingBackend {
    /// In-process `ProverEngine` — moonproof's differentiator. SRS
    /// and key files cached at the platform default data dir; no
    /// proof-server required.
    #[default]
    InProcess,
    /// HTTP proof-server. Use the LOCAL preset URL
    /// (`http://127.0.0.1:6300` for the dev-loop harness),
    /// REMOTE preset URL (network's published proof-server), or
    /// any custom URL.
    HttpServer { base_url: String },
}

impl ProvingBackend {
    /// Pick the proving backend for `network`: route through its HTTP
    /// proof-server when one is configured (`proof_server_url`),
    /// otherwise prove in-process via the bundled `ProverEngine`.
    #[must_use]
    pub fn for_network(network: &super::network::NetworkConfig) -> Self {
        match &network.proof_server_url {
            Some(base_url) => Self::HttpServer {
                base_url: base_url.clone(),
            },
            None => Self::InProcess,
        }
    }
}

use super::connect::WalletSession;
use super::sync::{resolve_indexer_sync_timeout, sync_wallet_fresh, sync_wallet_resumable};
use crate::facade::FacadeState;

/// Default TTL added to every wallet-built transaction. Matches the
/// upstream local-dev funding script's 30-minute window plus the
/// integration tests' 1-hour window — pick the longer of the two so
/// users on slow harnesses don't hit a TTL-expired rejection.
pub const TRANSACTION_TTL_SECS: u64 = 3600;

/// Compute the TTL stamped on every wallet-built transaction —
/// `block_ts + TRANSACTION_TTL_SECS`. Single helper so all four
/// recipe-builder call sites (balance, transfer, register-dust,
/// faucet) agree on the window.
#[must_use]
pub fn ttl_from(block_ts: Timestamp) -> Timestamp {
    block_ts + MidnightDuration::from_secs(i128::from(TRANSACTION_TTL_SECS))
}

/// Default submission wait-stage for `network`.
///
/// `Finalized` for fund-class networks (`mainnet`, `preprod`) — a
/// chain re-org can orphan a block-inclusion event, and we don't want
/// the wallet returning success on a tx the chain later drops.
/// `InBlock` for everything else (local-dev, preview) — block
/// inclusion is the practical end-state on those networks, and
/// `Finalized` waits ~30 s of additional latency that adds nothing in
/// dev workflows.
#[must_use]
pub fn default_submission_stage(network: &super::network::NetworkConfig) -> SubmissionStage {
    if network.is_fund_class() {
        SubmissionStage::Finalized
    } else {
        SubmissionStage::InBlock
    }
}

/// Build the proving provider used to finalize wallet recipes. Local
/// in-process proving via `MidnightDataProvider`'s on-demand SRS
/// fetch — mirrors the `mint_deploy` example and the genesis
/// submission integration test.
pub fn build_engine_provider() -> Result<EngineProvingProvider> {
    let engine = ProverEngine::from_env().context("init ProverEngine (MIDNIGHT_PP)")?;
    Ok(EngineProvingProvider::new(Arc::new(engine)))
}

/// Finalize a recipe through the chosen proving backend. The recipe
/// is typically signed first (see [`submit_signed_recipe_with_backend`]),
/// but proving and signing are independent — the granular `tx prove`
/// CLI verb passes an externally-built recipe straight through.
pub async fn finalize_with_backend(
    recipe: UnprovenTransactionRecipe,
    backend: &ProvingBackend,
) -> Result<crate::FinalizedTransactionRecipe> {
    match backend {
        ProvingBackend::InProcess => {
            #[cfg(target_arch = "wasm32")]
            {
                let _ = recipe;
                Err(anyhow!(
                    "in-process proving is not supported on wasm32; configure an HTTP proofServerUrl"
                ))
            }
            #[cfg(not(target_arch = "wasm32"))]
            {
                let engine = build_engine_provider()?;
                finalize_facade_recipe(&recipe, engine)
                    .await
                    .map_err(|e| anyhow!("finalize_recipe (in-process): {e}"))
            }
        }
        ProvingBackend::HttpServer { base_url } => {
            let engine = HttpProvingProvider::new(base_url.clone());
            finalize_facade_recipe(&recipe, engine)
                .await
                .map_err(|e| anyhow!("finalize_recipe (remote {base_url}): {e}"))
        }
    }
}

/// Outcome of a session submission. `event` is the node-client event
/// describing the requested stage; `raw_tx_bytes` is the wire-encoded
/// transaction handed to the node (kept so callers can persist it
/// alongside the pending-tx + tx-history records).
pub struct SubmissionOutcome {
    pub event: SubmissionEvent,
    pub raw_tx_bytes: Vec<u8>,
}

/// Sign, prove, serialize, submit, and wait for the requested stage.
/// Defaults to in-process proving — see
/// [`submit_signed_recipe_with_backend`] to route proof generation
/// through a remote / loopback proof-server instead.
pub async fn submit_signed_recipe(
    session: &WalletSession,
    recipe: UnprovenTransactionRecipe,
    stage: SubmissionStage,
) -> Result<SubmissionOutcome> {
    submit_signed_recipe_with_backend(session, recipe, stage, &ProvingBackend::InProcess).await
}

/// Same as [`submit_signed_recipe`] but routes proof generation
/// through `backend`. Backends:
///
/// - [`ProvingBackend::InProcess`] — moonproof's in-process
///   `ProverEngine`. Default.
/// - [`ProvingBackend::HttpServer`] — POSTs to a local or remote
///   proof-server's `/check` + `/prove` endpoints (same wire format
///   the official Midnight proof-server speaks).
pub async fn submit_signed_recipe_with_backend(
    session: &WalletSession,
    recipe: UnprovenTransactionRecipe,
    stage: SubmissionStage,
    backend: &ProvingBackend,
) -> Result<SubmissionOutcome> {
    let finalized = prove_signed_recipe(session, recipe, backend).await?;
    let bytes = serialize_finalized(&finalized).map_err(|e| anyhow!("serialize_finalized: {e}"))?;
    let bytes_for_record = bytes.clone();

    let event = submit_finalized(session.node.as_ref(), bytes, SubmissionOptions { stage })
        .await
        .map_err(|e| translate_submission_error(&e, &session.network.name))?;
    wait_until_indexed(&session.network.indexer_http, &event).await?;

    Ok(SubmissionOutcome {
        event,
        raw_tx_bytes: bytes_for_record,
    })
}

/// How long a landed transaction's block may take to reach the indexer,
/// which ingests finalized blocks only.
const INDEXING_TIMEOUT: StdDuration = StdDuration::from_secs(180);

/// Wait until the indexer serves the block `event` landed in.
///
/// Every wallet sync reads the indexer, so a transaction it has not
/// indexed is invisible to the next sync: that sync offers the spent
/// UTXOs and dust coins again, and the node rejects whatever is built
/// from them. Waiting here means a submission that returns is one every
/// later sync, in this process or another, already sees.
pub async fn wait_until_indexed(indexer_http: &str, event: &SubmissionEvent) -> Result<()> {
    use moonproof_indexer_client::{BlockOffset, HttpIndexerClient, PublicDataProvider};

    let block_hash = match event {
        SubmissionEvent::Submitted { .. } => return Ok(()),
        SubmissionEvent::InBlock { block_hash, .. }
        | SubmissionEvent::Finalized { block_hash, .. } => {
            block_hash.trim_start_matches("0x").to_ascii_lowercase()
        }
    };
    let indexer =
        HttpIndexerClient::new(indexer_http).map_err(|e| anyhow!("indexer URL parse: {e}"))?;
    let deadline = moonproof_utils::rt::Instant::now() + INDEXING_TIMEOUT;
    loop {
        match indexer
            .block(Some(BlockOffset::Hash(block_hash.clone())))
            .await
        {
            Ok(Some(_)) => return Ok(()),
            Ok(None) => {}
            Err(e) => tracing::debug!("indexer block lookup for {block_hash}: {e}"),
        }
        if moonproof_utils::rt::Instant::now() >= deadline {
            return Err(anyhow!(
                "transaction {} landed in block {block_hash}, but the indexer at {indexer_http} \
                 had not indexed that block after {}s",
                event.tx_hash(),
                INDEXING_TIMEOUT.as_secs()
            ));
        }
        moonproof_utils::rt::sleep(StdDuration::from_millis(500)).await;
    }
}

/// Sign `recipe` with the session's NIGHT key and prove it through
/// `backend`, ready to submit. The first half of
/// [`submit_signed_recipe_with_backend`], for a host that submits
/// through a [`crate::facade::SubmissionWatch`] to follow the
/// transaction past the stage it waits for.
pub async fn prove_signed_recipe(
    session: &WalletSession,
    recipe: UnprovenTransactionRecipe,
    backend: &ProvingBackend,
) -> Result<crate::FinalizedTransactionRecipe> {
    let signed_recipe = {
        let mut rng = rand::rngs::OsRng;
        sign_recipe(recipe, &session.wallet.signing_key, &mut rng)
            .map_err(|e| anyhow!("sign_recipe: {e}"))?
    };
    finalize_with_backend(signed_recipe, backend).await
}

/// A submission error, with the name of the ledger error a node
/// rejection carries as a bare number.
pub fn translate_submission_error(err: &WalletError, network: &str) -> anyhow::Error {
    let rendered = err.to_string();
    match extract_custom_error_code(&rendered).and_then(describe_node_error_code) {
        Some(name) => anyhow!("submission to {network} failed: {rendered} [{name}]"),
        None => anyhow!("submission to {network} failed: {rendered}"),
    }
}

/// Pull the numeric code out of the node's `custom error: N`
/// rejection string.
pub(crate) fn extract_custom_error_code(s: &str) -> Option<u16> {
    let idx = s.find("custom error:")?;
    s[idx + "custom error:".len()..]
        .trim_start()
        .split(|c: char| !c.is_ascii_digit())
        .next()?
        .parse()
        .ok()
}

const RETIRED_ERROR_CODE: &str =
    "retired error code — node and wallet ledger versions likely disagree, \
     or wallet state is stale for this chain";

const NODE_ERROR_CODES: &[(u16, &str)] = &[
    (100, "EffectsMismatch"),
    (101, "ContractAlreadyDeployed"),
    (102, "ContractNotPresent"),
    (103, "Zswap::Unknown"),
    (104, "Transcript"),
    (105, "InsufficientClaimable"),
    (106, "VerifierKeyNotFound"),
    (107, "VerifierKeyAlreadyPresent"),
    (108, "ReplayCounterMismatch"),
    (109, "UnknownError"),
    (110, "VerifierKeyNotSet"),
    (111, "TransactionTooLarge"),
    (112, "VerifierKeyTooLarge"),
    (113, "VerifierKeyNotPresent"),
    (114, "ContractNotPresent"),
    (115, "InvalidProof"),
    (116, "BindingCommitmentOpeningInvalid"),
    (117, "NotNormalized"),
    (118, "FallibleWithoutCheckpoint"),
    (119, "ClaimReceiveFailed"),
    (120, "ClaimSpendFailed"),
    (121, "ClaimNullifierFailed"),
    (122, "ClaimCallFailed"),
    (123, "InvalidSchnorrProof"),
    (124, "UnclaimedCoinCom"),
    (125, "UnclaimedNullifier"),
    (126, "Unbalanced — transaction inputs/outputs don't balance"),
    (127, "Zswap::Unknown"),
    (128, "BuiltinDecode"),
    (129, "GuaranteedLimit"),
    (130, "MergingContracts"),
    (131, "CantMergeTypes"),
    (132, "ClaimOverflow"),
    (133, "ClaimCoinMismatch"),
    (134, "KeyNotInCommittee"),
    (135, "InvalidCommitteeSignature"),
    (136, "ThresholdMissed"),
    (137, "TooManyZswapEntries"),
    (138, "BalanceCheckOverspend — spending more than available"),
    (139, "UnknownError"),
    (140, "SystemTransaction::NotAllowedForCaller"),
    (141, "ContractDustTransfer"),
    (142, "RepeatedCommitteeSignature"),
    (143, "RepeatedDustRegistration"),
    (144, "FeeCalculation::RepeatedEntries"),
    (145, "FeeCalculation::Unknown"),
    (146, "MalformedContractDeploy::TooManyOperations"),
    (150, "LedgerApi::LedgerCacheError"),
    (151, "LedgerApi::NoLedgerState"),
    (152, "LedgerApi::LedgerStateScaleDecodingError"),
    (153, "LedgerApi::ContractCallCostError"),
    (154, "LedgerApi::BlockLimitExceededError"),
    (155, "LedgerApi::FeeCalculationError"),
    (156, "LedgerApi::ContractNotPresent"),
    (157, "LedgerApi::BeneficiaryNotFound"),
    (165, "LedgerApi::GetTransactionContextError"),
    (166, "InvalidNetworkId"),
    (167, "IllegallyDeclaredGuaranteed"),
    (168, RETIRED_ERROR_CODE),
    (169, "InvalidDustRegistrationSignature"),
    (170, "InvalidDustSpendProof"),
    (171, "OutOfDustValidityWindow"),
    (172, "MultipleDustRegistrationsForKey"),
    (173, "InsufficientDustForRegistrationFee"),
    (174, "MalformedContractDeploy::Unknown"),
    (175, "IntentSignatureVerificationFailure"),
    (176, "IntentSignatureKeyMismatch"),
    (177, "IntentSegmentIdCollision"),
    (178, "IntentAtGuaranteedSegmentId"),
    (179, "UnsupportedProofVersion"),
    (180, "GuaranteedTranscriptVersion"),
    (181, "FallibleTranscriptVersion"),
    (182, RETIRED_ERROR_CODE),
    (183, "BalanceCheckOutOfBounds"),
    (184, "BalanceCheckConversionFailure"),
    (185, "PedersenCheckFailure"),
    (186, RETIRED_ERROR_CODE),
    (187, RETIRED_ERROR_CODE),
    (188, RETIRED_ERROR_CODE),
    (189, "InputsNotSorted"),
    (190, "OutputsNotSorted"),
    (191, "DuplicateInputs"),
    (192, "InputsSignaturesLengthMismatch"),
    (193, RETIRED_ERROR_CODE),
    (194, "BalanceCheckOutOfBounds"),
    (
        195,
        "InputNotInUtxos — spending a UTXO the chain doesn't have (stale wallet state?)",
    ),
    (196, "DustDoubleSpend"),
    (197, "DustDeregistrationNotRegistered"),
    (198, "GenerationInfoAlreadyPresent"),
    (199, "InvariantViolation"),
    (200, "RewardTooSmall"),
    (201, "SystemTransaction::IllegalPayout"),
    (202, "SystemTransaction::InsufficientTreasuryFunds"),
    (203, "SystemTransaction::CommitmentAlreadyPresent"),
    (204, "SystemTransaction::UnknownError"),
    (205, RETIRED_ERROR_CODE),
    (206, "SystemTransaction::IllegalReserveDistribution"),
    (207, "SystemTransaction::GenerationInfoAlreadyPresent"),
    (208, "SystemTransaction::InvalidBasisPoints"),
    (209, "SystemTransaction::InvariantViolation"),
    (210, "SystemTransaction::TreasuryDisabled"),
    (211, "SystemTransaction::MerkleTreeError"),
    (212, "EffectsCheck::RealCallsSubsetCheckFailure"),
    (213, "EffectsCheck::AllCommitmentsSubsetCheckFailure"),
    (214, "EffectsCheck::RealUnshieldedSpendsSubsetCheckFailure"),
    (
        215,
        "EffectsCheck::ClaimedUnshieldedSpendsUniquenessFailure",
    ),
    (216, "EffectsCheck::ClaimedCallsUniquenessFailure"),
    (217, "EffectsCheck::NullifiersNeqClaimedNullifiers"),
    (218, "EffectsCheck::CommitmentsNeqClaimedShieldedReceives"),
    (219, "SequencingCheck::CallSequencingViolation"),
    (220, "SequencingCheck::SequencingCorrelationViolation"),
    (221, "SequencingCheck::GuaranteedInFallibleContextViolation"),
    (222, "SequencingCheck::FallibleInGuaranteedContextViolation"),
    (223, "SequencingCheck::CausalityConstraintViolation"),
    (224, "SequencingCheck::CallHasEmptyTranscripts"),
    (225, "DisjointCheck::ShieldedInputsDisjointFailure"),
    (226, "DisjointCheck::ShieldedOutputsDisjointFailure"),
    (227, "DisjointCheck::UnshieldedInputsDisjointFailure"),
    (228, "IntentTtlExpired"),
    (229, "IntentTtlTooFarInFuture"),
    (230, "IntentAlreadyExists"),
    (231, "FeeCalculation::OutsideTimeToDismiss"),
    (232, "FeeCalculation::BlockLimitExceeded"),
    (233, "MalformedContractDeploy::NonZeroBalance"),
    (234, "MalformedContractDeploy::IncorrectChargedState"),
    (235, "MalformedZswap::InvalidProof"),
    (236, "MalformedZswap::ContractSentCiphertext"),
    (237, "MalformedZswap::NonDisjointCoinMerge"),
    (238, "MalformedZswap::NotNormalized"),
    (
        239,
        "Zswap::NullifierAlreadyPresent — double spend of a shielded coin",
    ),
    (240, "Zswap::CommitmentAlreadyPresent"),
    (
        241,
        "Zswap::UnknownMerkleRoot — wallet state out of sync with chain",
    ),
    (242, "IntentTtlExpired"),
    (243, "IntentTtlTooFarInFuture"),
    (244, "IntentAlreadyExists"),
    (245, "IntentTtlExpired"),
    (246, "IntentTtlTooFarInFuture"),
    (247, "IntentAlreadyExists"),
    (248, "DivideByZero"),
    (249, "MerkleTreeError"),
    (250, "MerkleTreeError"),
    (251, "BridgeClaimTooSmall"),
    (
        252,
        "ContractTooManyOperations — a contract holds at most 256 operations",
    ),
    (253, "TooManyPublicInputs"),
    (254, "TranscriptGasExceedsBlockLimits"),
    (255, "LedgerApi::HostApiError"),
];

/// Human name for the midnight-node ledger error codes embedded in
/// `Invalid transaction with custom error: N` rejections. Source:
/// midnight-node `ledger/src/ledger_9/types.rs` (node 2.1.101).
#[must_use]
pub fn describe_node_error_code(code: u16) -> Option<&'static str> {
    NODE_ERROR_CODES
        .iter()
        .find(|(c, _)| *c == code)
        .map(|&(_, name)| name)
}

/// Poll budget for [`wait_for_native_balance`] / [`wait_for_dust_balance`].
/// 60s matches the indexer-sync ceiling; per-iteration sleep is short
/// enough to land within one block on local-dev.
const WAIT_POLL_INTERVAL: StdDuration = StdDuration::from_secs(2);

/// Re-sync `session` until its native NIGHT available balance is at
/// least `min_amount`, or [`INDEXER_SYNC_TIMEOUT`] elapses. Used by
/// the faucet between NIGHT transfer + DUST registration to wait out
/// the indexer's index-after-in-block lag.
///
/// The first poll syncs from genesis (no on-disk persistence assumed —
/// the wait helper stays disk-agnostic); every subsequent poll resumes
/// from the in-memory state and folds only new ticks, so re-polling
/// against a long chain costs one delta-drain instead of a full
/// genesis replay each iteration.
pub async fn wait_for_native_balance(
    session: &WalletSession,
    min_amount: u128,
) -> Result<FacadeState> {
    let native = TokenType::new("native");
    let timeout = resolve_indexer_sync_timeout(&session.network);
    let deadline = moonproof_utils::rt::Instant::now() + timeout;
    let mut last = sync_wallet_fresh(session).await?;
    loop {
        let avail = last.unshielded.available_balance(&native);
        if avail >= min_amount {
            return Ok(last);
        }
        if moonproof_utils::rt::Instant::now() >= deadline {
            anyhow::bail!(
                "timed out after {}s waiting for {min_amount} NIGHT to land at {}",
                timeout.as_secs(),
                session.wallet.bech32_address
            );
        }
        moonproof_utils::rt::sleep(WAIT_POLL_INTERVAL).await;
        last = sync_wallet_resumable(session, Some(last)).await?;
    }
}

/// Re-sync `session` until its DUST balance is at least `min_amount`,
/// or [`resolve_indexer_sync_timeout`] elapses. Used by the faucet
/// after `register-dust` to confirm dust generation actually started.
pub async fn wait_for_dust_balance(
    session: &WalletSession,
    min_amount: u128,
) -> Result<FacadeState> {
    let timeout = resolve_indexer_sync_timeout(&session.network);
    let deadline = moonproof_utils::rt::Instant::now() + timeout;
    let mut last = sync_wallet_fresh(session).await?;
    loop {
        let avail = crate::dust_wallet_balance(&last.dust, last.chain_tip_ts());
        if avail >= min_amount {
            return Ok(last);
        }
        if moonproof_utils::rt::Instant::now() >= deadline {
            anyhow::bail!(
                "timed out after {}s waiting for DUST to accrue at {}",
                timeout.as_secs(),
                session.wallet.bech32_address
            );
        }
        moonproof_utils::rt::sleep(WAIT_POLL_INTERVAL).await;
        last = sync_wallet_resumable(session, Some(last)).await?;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn extracts_the_code_from_a_node_rejection() {
        assert_eq!(
            extract_custom_error_code("Invalid transaction with custom error: 170"),
            Some(170)
        );
        assert_eq!(extract_custom_error_code("rejected"), None);
    }

    /// Codes ledger 9.1 introduced. Unnamed, a rejection reports only
    /// the bare number.
    #[test]
    fn names_the_ledger_9_1_codes() {
        for code in [
            140, 141, 142, 143, 144, 146, 150, 157, 201, 211, 251, 252, 253, 254, 255,
        ] {
            assert!(
                describe_node_error_code(code).is_some(),
                "code {code} unnamed"
            );
        }
        assert_eq!(
            describe_node_error_code(254),
            Some("TranscriptGasExceedsBlockLimits")
        );
        assert_eq!(describe_node_error_code(999), None);
    }
}