thruput-testkit 0.42.0

Multi-agent integration-test harness for Thruput contract applications
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
//! Contract method helpers.
//!
//! [`entrypoint_id`] computes a method selector from an interface identity.
//! [`Contract`] binds an address plus that identity and offers typed
//! `call`/`view`, encoding arguments and decoding returns with `xdrs` so tests
//! name methods and pass Rust values instead of hand-building calldata.
//! [`ContractCall`] is a prepared, typed call: the building block for typed
//! clients whose methods mirror a contract interface.
//!
//! [`Caller`] implements [`RemoteInvoker`], so an interface's generated
//! `<Iface>Remote` proxy (from `#[contract]` with `thruput-sdk/remote`) can
//! serve as that typed client. Its methods declared `pure` or `readOnly` return
//! a [`ContractView`]; all others, including those that declare no effect,
//! return a [`ContractCall`].
//!
//! Awaiting either gives the decoded return. A [`ContractCall`] can instead be
//! awaited with its receipt, submitted without waiting, or simulated. With the
//! `Counter` interface from the [crate docs](crate#typed-calls), plus a
//! `peek` method that declares no effect:
//!
//! ```rust,no_run
//! # #![allow(unexpected_cfgs)]
//! # mod counter {
//! #     use thruput_sdk::contract;
//! #     #[contract(version = "0.1.0")]
//! #     pub trait Counter {
//! #         fn increment(&mut self, by: u64) -> u64;
//! #         #[contract(effect = "readOnly")]
//! #         fn get(&self) -> u64;
//! #         fn peek(&self) -> u64;
//! #     }
//! # }
//! # use counter::CounterRemote;
//! use thruput_testkit::{AgentContext, Caller, Result, TestkitError};
//!
//! async fn exercise(ctx: &AgentContext, counter: &CounterRemote<Caller>) -> Result<()> {
//!     // Submit, require success, and decode the return.
//!     let count = counter.increment(1).await?;
//!
//!     // The same, keeping the receipt for its events or gas.
//!     let (next, receipt) = counter.increment(1).with_receipt().await?;
//!     assert_eq!(next, count + 1);
//!     println!("{} events, {} gas", receipt.events.len(), receipt.gas_used);
//!
//!     // Only the receipt, ignoring the return value.
//!     let receipt = counter.increment(1).receipt().await?;
//!     println!("{} gas", receipt.gas_used);
//!
//!     // Submit now and await later: several calls can land in one block,
//!     // which a manual block driver produces on request.
//!     let first = counter.increment(1).submit().await?;
//!     let second = counter.increment(1).submit().await?;
//!     first.await_pending().await?;
//!     second.await_pending().await?;
//!     ctx.network().produce_block().await?;
//!     first.await_receipt().await?;
//!     second.await_receipt().await?;
//!
//!     // A call that reverts is an error, which a test can expect.
//!     match counter.increment(u64::MAX).await {
//!         Err(TestkitError::Reverted { .. }) => {}
//!         other => panic!("an overflowing increment should revert, got {other:?}"),
//!     }
//!
//!     // A method that declares no effect returns a `ContractCall`, even when
//!     // it only reads: `simulate` it, since awaiting it would submit.
//!     assert_eq!(counter.peek().simulate().await?, counter.get().await?);
//!     Ok(())
//! }
//! # fn main() {}
//! ```

pub use thruput_xdr::contract::ContractEntrypointID;

use std::fmt;
use std::future::{Future, IntoFuture};
use std::marker::PhantomData;
use std::pin::Pin;

use thruput_contract_util::remote::{RemoteInvoker, RemoteMethod};
use thruput_contract_util::semver::try_major_version_from_string;
use thruput_json_rpc_types::responses::InvocationOutput;
use thruput_json_rpc_types::responses::{ReceiptExecution, TransactionReceipt};
use thruput_json_rpc_types::transaction::TxHash;
use thruput_signing::default_wallet::decode_default_wallet_call_return;
use thruput_xdr::types::ContractAddress;

use xdrs::{ReadXDR, WriteXDR};

use crate::caller::Caller;
use crate::error::{Result, TestkitError};
use crate::network::SubmittedTransaction;

/// A typed contract call submitted without waiting for block production.
#[derive(Debug, Clone)]
#[must_use = "submitted contract calls should be awaited or intentionally retained"]
pub struct SubmittedContractCall {
    transaction: SubmittedTransaction,
    method: String,
}

impl SubmittedContractCall {
    /// Canonical transaction hash returned by submission.
    pub fn tx_hash(&self) -> TxHash {
        self.transaction.tx_hash()
    }

    /// Wait until the scheduler reports this call as pending.
    pub async fn await_pending(&self) -> Result<()> {
        self.transaction.await_pending().await
    }

    /// Wait for the receipt and require successful execution.
    pub async fn await_receipt(&self) -> Result<TransactionReceipt> {
        let receipt = self.transaction.await_receipt().await?;
        match receipt.execution {
            ReceiptExecution::Return { .. } => Ok(receipt),
            ref status => Err(TestkitError::Reverted {
                method: self.method.clone(),
                status: format!("{status:?}"),
            }),
        }
    }
}

/// A typed state-changing contract call, prepared but not yet submitted.
///
/// Built by [`Contract::prepare_call`], and the natural return type of a typed
/// client's call methods. Awaiting it submits the call, requires successful
/// execution, and decodes the return as `R`. To see the receipt as well, use
/// [`with_receipt`](Self::with_receipt); to submit without waiting, use
/// [`submit`](Self::submit).
#[must_use = "a contract call does nothing until it is awaited or submitted"]
pub struct ContractCall<R> {
    caller: Caller,
    target: ContractAddress,
    method: String,
    prepared: Result<(ContractEntrypointID, Vec<u8>)>,
    returns: PhantomData<fn() -> R>,
}

impl<R> fmt::Debug for ContractCall<R> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ContractCall")
            .field("caller", &self.caller.address())
            .field("target", &self.target)
            .field("method", &self.method)
            .finish_non_exhaustive()
    }
}

impl<R> ContractCall<R> {
    /// Submit the call without waiting for its receipt.
    pub async fn submit(self) -> Result<SubmittedContractCall> {
        let (selector, calldata) = self.prepared?;
        let transaction = self
            .caller
            .submit_call(self.target, selector, &calldata)
            .await?;
        Ok(SubmittedContractCall {
            transaction,
            method: self.method,
        })
    }

    /// Submit the call and await its receipt, requiring successful execution
    /// but ignoring the return value.
    pub async fn receipt(self) -> Result<TransactionReceipt> {
        self.submit().await?.await_receipt().await
    }
}

impl<R> ContractCall<R>
where
    R: for<'r> ReadXDR<'r>,
{
    /// Submit the call, require successful execution, and return the decoded
    /// return value together with the receipt (for its events or gas).
    pub async fn with_receipt(self) -> Result<(R, TransactionReceipt)> {
        let receipt = self.receipt().await?;
        let returned = decode_call_return(&receipt)?;
        Ok((returned, receipt))
    }

    /// Simulate the call instead of submitting it, with the caller as
    /// `msg.sender`, and decode its return. For reading through a method
    /// whose interface does not declare it read-only; any state changes are
    /// discarded.
    pub async fn simulate(self) -> Result<R> {
        let (selector, calldata) = self.prepared?;
        let sender = self.caller.address();
        simulate_return(&self.caller, self.target, selector, &calldata, Some(sender)).await
    }
}

/// A typed read-only contract invocation, prepared but not yet simulated.
///
/// Returned by a generated `<Iface>Remote` proxy for methods declared `pure`
/// or `readOnly`. Awaiting it simulates the method with the caller as
/// `msg.sender` and decodes the return as `R`. Nothing is submitted.
#[must_use = "a contract view does nothing until it is awaited"]
pub struct ContractView<R> {
    caller: Caller,
    target: ContractAddress,
    method: String,
    prepared: Result<(ContractEntrypointID, Vec<u8>)>,
    returns: PhantomData<fn() -> R>,
}

impl<R> fmt::Debug for ContractView<R> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ContractView")
            .field("caller", &self.caller.address())
            .field("target", &self.target)
            .field("method", &self.method)
            .finish_non_exhaustive()
    }
}

impl<R> IntoFuture for ContractView<R>
where
    R: for<'r> ReadXDR<'r> + Send + 'static,
{
    type Output = Result<R>;
    type IntoFuture = Pin<Box<dyn Future<Output = Result<R>> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let (selector, calldata) = self.prepared?;
            let sender = self.caller.address();
            simulate_return(&self.caller, self.target, selector, &calldata, Some(sender)).await
        })
    }
}

/// Encode `args` now, so the prepared invocation borrows nothing.
fn encode_for<A>(method: &RemoteMethod, args: &A) -> Result<(ContractEntrypointID, Vec<u8>)>
where
    A: WriteXDR + ?Sized,
{
    let calldata = xdrs::cxs::encode(args).map_err(TestkitError::encode)?;
    Ok((method.entrypoint, calldata))
}

impl RemoteInvoker for Caller {
    type Call<R> = ContractCall<R>;
    type View<R> = ContractView<R>;

    fn call<R, A>(
        &self,
        target: &ContractAddress,
        method: RemoteMethod,
        args: &A,
    ) -> ContractCall<R>
    where
        R: xdrs::ReadXDROwned,
        A: WriteXDR + ?Sized,
    {
        ContractCall {
            caller: self.clone(),
            target: *target,
            method: method.name.to_owned(),
            prepared: encode_for(&method, args),
            returns: PhantomData,
        }
    }

    fn view<R, A>(
        &self,
        target: &ContractAddress,
        method: RemoteMethod,
        args: &A,
    ) -> ContractView<R>
    where
        R: xdrs::ReadXDROwned,
        A: WriteXDR + ?Sized,
    {
        ContractView {
            caller: self.clone(),
            target: *target,
            method: method.name.to_owned(),
            prepared: encode_for(&method, args),
            returns: PhantomData,
        }
    }
}

impl<R> IntoFuture for ContractCall<R>
where
    R: for<'r> ReadXDR<'r> + Send + 'static,
{
    type Output = Result<R>;
    type IntoFuture = Pin<Box<dyn Future<Output = Result<R>> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move { Ok(self.with_receipt().await?.0) })
    }
}

/// Compute the entrypoint selector for a contract method.
///
/// It is derived from the contract's interface `name`, `version`, and `method`
/// name exactly as the `thruput` CLI derives selectors, so tests can name
/// methods instead of pasting raw hex (which drifts whenever a fixture is
/// rebuilt).
///
/// ```
/// let bump = thruput_testkit::entrypoint_id("CallerCounter", "0.1.0", "bump");
/// ```
#[must_use]
pub fn entrypoint_id(interface: &str, version: &str, method: &str) -> ContractEntrypointID {
    thruput_client::codec::method_entrypoint_id(interface, version, method)
}

/// Fallible form of [`entrypoint_id`] for interface identities from untrusted input.
pub fn try_entrypoint_id(
    interface: &str,
    version: &str,
    method: &str,
) -> Result<ContractEntrypointID> {
    if try_major_version_from_string(version).is_none() {
        return Err(TestkitError::InvalidContractVersion {
            version: version.to_owned(),
        });
    }
    Ok(entrypoint_id(interface, version, method))
}

/// A deployed contract instance bound to its interface identity.
///
/// `call` and `view` encode the argument value (typically a tuple of the
/// method's arguments) with the contract (CXS) codec and decode the return the
/// same way, so a test works in Rust values rather than raw calldata. The
/// argument and return types must implement `xdrs` `WriteXDR` / `ReadXDR` (the
/// method's own argument/return types from a contract's interface crate do).
///
/// Each method takes anything that can reach a [`Caller`]: an agent's `&ctx`,
/// or a `Caller` cloned out of it with
/// [`AgentContext::caller`](crate::AgentContext::caller).
///
/// Prefer an interface's generated `<Iface>Remote` proxy (see the
/// [module docs](self)), which checks method names and argument types at
/// compile time. A `Contract` suits a contract with no interface crate to
/// generate one from:
///
/// ```rust,no_run
/// use thruput_testkit::xdr::types::ContractAddress;
/// use thruput_testkit::{AgentContext, Contract, Result};
///
/// async fn bump(ctx: &AgentContext, address: ContractAddress) -> Result<u64> {
///     let counter = Contract::new(address, "Counter", "0.1.0");
///     // One argument is passed as itself; several, as a tuple.
///     counter.call(ctx, "increment", &1u64).await?;
///     let count: u64 = counter.call_returning(ctx, "increment", &1u64).await?;
///     let read: u64 = counter.view(ctx, "get", &(), Some(ctx.address())).await?;
///     assert_eq!(read, count);
///     Ok(count)
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Contract {
    address: ContractAddress,
    interface: String,
    version: String,
}

impl Contract {
    /// Bind a handle to a deployed `address` and its interface identity.
    pub fn new(
        address: ContractAddress,
        interface: impl Into<String>,
        version: impl Into<String>,
    ) -> Self {
        Self {
            address,
            interface: interface.into(),
            version: version.into(),
        }
    }

    /// The deployed contract address.
    #[must_use]
    pub fn address(&self) -> ContractAddress {
        self.address
    }

    fn selector(&self, method: &str) -> Result<ContractEntrypointID> {
        try_entrypoint_id(&self.interface, &self.version, method)
    }

    /// Prepare a state-changing call to `method` from `ctx`'s account, whose
    /// return decodes as `R`. Nothing is submitted until the [`ContractCall`]
    /// is awaited or submitted.
    ///
    /// The arguments are encoded now, so the call borrows nothing: it can be
    /// held, moved into another task, or returned from a typed client method.
    pub fn prepare_call<R, A>(
        &self,
        ctx: &(impl AsRef<Caller> + ?Sized),
        method: &str,
        args: &A,
    ) -> ContractCall<R>
    where
        A: WriteXDR + ?Sized,
    {
        let prepared = self.selector(method).and_then(|selector| {
            let calldata = xdrs::cxs::encode(args).map_err(TestkitError::encode)?;
            Ok((selector, calldata))
        });
        ContractCall {
            caller: ctx.as_ref().clone(),
            target: self.address,
            method: method.to_owned(),
            prepared,
            returns: PhantomData,
        }
    }

    /// Submit a state-changing call to `method` through the agent's wallet,
    /// awaiting the receipt and requiring successful execution.
    ///
    /// Returns [`TestkitError::Reverted`] if the transaction executed but its
    /// status was not `Ok`, so callers can `?` a call they expect to succeed
    /// instead of asserting on the receipt. Add call-site context with
    /// `map_err` where the method name alone does not identify the call.
    pub async fn call<A>(
        &self,
        ctx: &(impl AsRef<Caller> + ?Sized),
        method: &str,
        args: &A,
    ) -> Result<TransactionReceipt>
    where
        A: WriteXDR + ?Sized,
    {
        self.prepare_call::<(), _>(ctx, method, args)
            .receipt()
            .await
    }

    /// Submit a state-changing call without waiting for its receipt.
    pub async fn submit_call<A>(
        &self,
        ctx: &(impl AsRef<Caller> + ?Sized),
        method: &str,
        args: &A,
    ) -> Result<SubmittedContractCall>
    where
        A: WriteXDR + ?Sized,
    {
        self.prepare_call::<(), _>(ctx, method, args).submit().await
    }

    /// Call `method`, requiring success, and decode the return value to `R`.
    pub async fn call_returning<A, R>(
        &self,
        ctx: &(impl AsRef<Caller> + ?Sized),
        method: &str,
        args: &A,
    ) -> Result<R>
    where
        A: WriteXDR + ?Sized,
        R: for<'r> ReadXDR<'r>,
    {
        let (returned, _) = self
            .prepare_call::<R, _>(ctx, method, args)
            .with_receipt()
            .await?;
        Ok(returned)
    }

    /// Simulate a read-only `view` of `method`, decoding the return to `R`.
    ///
    /// `caller` sets the simulated `msg.sender`; pass an agent's own address for
    /// state keyed by the caller.
    pub async fn view<A, R>(
        &self,
        ctx: &(impl AsRef<Caller> + ?Sized),
        method: &str,
        args: &A,
        caller: Option<ContractAddress>,
    ) -> Result<R>
    where
        A: WriteXDR + ?Sized,
        R: for<'r> ReadXDR<'r>,
    {
        let calldata = xdrs::cxs::encode(args).map_err(TestkitError::encode)?;
        simulate_return(
            ctx.as_ref(),
            self.address,
            self.selector(method)?,
            &calldata,
            caller,
        )
        .await
    }
}

/// Simulate `selector` on `target` and decode its return. A simulation
/// invokes the target directly, so the return is not wallet-wrapped.
async fn simulate_return<R>(
    caller: &Caller,
    target: ContractAddress,
    selector: ContractEntrypointID,
    calldata: &[u8],
    sender: Option<ContractAddress>,
) -> Result<R>
where
    R: for<'r> ReadXDR<'r>,
{
    let response = caller
        .network()
        .view_call(target, selector, calldata, sender)
        .await?;
    match response.output {
        InvocationOutput::Return { return_data } => decode_return(&return_data.0),
        other => Err(TestkitError::NoReturn {
            kind: "view",
            detail: format!("{other:?}"),
        }),
    }
}

/// Decode a successful call's return from its receipt. The account's wallet
/// wraps the method's return, one buffer per call it made; absent return data
/// is rejected rather than read as an empty return.
fn decode_call_return<R>(receipt: &TransactionReceipt) -> Result<R>
where
    R: for<'r> ReadXDR<'r>,
{
    let ReceiptExecution::Return { return_data } = &receipt.execution else {
        return Err(TestkitError::NoReturn {
            kind: "call",
            detail: format!("{:?}", receipt.execution),
        });
    };
    let data = return_data.as_ref();
    let bytes = decode_default_wallet_call_return(data).map_err(TestkitError::decode)?;
    decode_return(&bytes)
}

fn decode_return<R>(bytes: &[u8]) -> Result<R>
where
    R: for<'r> ReadXDR<'r>,
{
    xdrs::cxs::decode::<R>(bytes).map_err(TestkitError::decode)
}

#[cfg(test)]
mod tests {
    use thruput_xdr::types::ContractAddress;

    use crate::account::Account;
    use crate::caller::Caller;
    use crate::error::TestkitError;
    use crate::manifest::derive_native_accounts;
    use crate::network::Network;
    use crate::nonce::NonceNamespace;

    use thruput_json_rpc_types::BlockHeight;
    use thruput_json_rpc_types::responses::{ReceiptExecution, TransactionReceipt};
    use thruput_json_rpc_types::transaction::TxHash;
    use thruput_json_rpc_types::{base58::Base58, hex::HexBytes};
    use thruput_xdr::types::SHA256Hash;

    use super::{
        Contract, ContractEntrypointID, decode_call_return, decode_return, entrypoint_id,
        try_entrypoint_id,
    };

    fn receipt(return_data: Option<Vec<u8>>) -> TransactionReceipt {
        TransactionReceipt {
            transaction_hash: TxHash(Base58(SHA256Hash::from([1; 32]))),
            block_height: BlockHeight::from(1),
            execution: ReceiptExecution::Return {
                return_data: HexBytes(return_data.unwrap_or_default()),
            },
            events: Vec::new(),
            gas_used: 1,
        }
    }

    #[test]
    fn call_return_requires_exactly_one_wallet_result() {
        let wrap = |results: Vec<Vec<u8>>| Some(xdrs::cxs::encode(&results).unwrap());

        // One empty child result is a valid `()` return.
        decode_call_return::<()>(&receipt(wrap(vec![Vec::new()]))).unwrap();
        let value = xdrs::cxs::encode(&7u64).unwrap();
        assert_eq!(
            decode_call_return::<u64>(&receipt(wrap(vec![value.clone()]))).unwrap(),
            7
        );

        // Missing data, or other than one child result, is not.
        for return_data in [None, wrap(Vec::new()), wrap(vec![value.clone(), value])] {
            assert!(matches!(
                decode_call_return::<()>(&receipt(return_data)),
                Err(TestkitError::Decode { .. })
            ));
        }
    }

    #[test]
    fn matches_known_erc20_selector() {
        // Same known-answer vector the CLI pins for `method_entrypoint_id`.
        assert_eq!(
            entrypoint_id("ERC20", "0.1.0", "transfer"),
            ContractEntrypointID::from([0x63, 0x28, 0x5b, 0x35, 0x23, 0xf9, 0xdc, 0x3f])
        );
    }

    #[test]
    fn invalid_version_returns_an_error_instead_of_panicking() {
        assert!(matches!(
            try_entrypoint_id("ERC20", "latest", "transfer"),
            Err(TestkitError::InvalidContractVersion { version }) if version == "latest"
        ));
    }

    #[test]
    fn cxs_round_trip_matches_helper_bounds() {
        // Confirms the encode/decode plumbing and trait bounds the `Contract`
        // helper relies on (a tuple of method arguments).
        let encoded = xdrs::cxs::encode(&(7u64, 9u32)).expect("encode");
        let (a, b): (u64, u32) = decode_return(&encoded).expect("decode");
        assert_eq!((a, b), (7, 9));
    }

    #[tokio::test]
    async fn prepared_call_reports_a_bad_identity_when_awaited() {
        let dev = derive_native_accounts(1, "seed", None).remove(0);
        let caller = Caller::new(
            Account::new(dev, NonceNamespace::for_run("seed", 0)),
            Network::offline(),
        );
        let contract = Contract::new(ContractAddress::from([7; 32]), "ERC20", "latest");

        // Preparing never fails; the error surfaces once the call is used.
        let call = contract.prepare_call::<u64, _>(&caller, "get", &());
        assert!(matches!(
            call.await,
            Err(TestkitError::InvalidContractVersion { version }) if version == "latest"
        ));
    }
}