thruput-testkit 0.43.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
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
//! The network a scenario runs against: how to reach it ([`NetworkConfig`])
//! and the live handle agents use ([`Network`]).

use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use thruput_node_supervisor::{BlockDriverConfig, LogLevel, ManualBlockProducer, ProducedBlock};

use thruput_json_rpc_client::native::{
    NativeClient, NativeClientError,
    receipt::{ReceiptPollConfig, poll_receipt},
};
use thruput_json_rpc_client::{HttpClient, HttpClientBuilder};
use thruput_json_rpc_types::runtime_manifest::RuntimeManifest;
use thruput_json_rpc_types::transaction::TxHash;
use thruput_json_rpc_types::{
    NetworkHash,
    requests::{self, EmptyRequest, EventQuery, TransactionQuery},
    responses::{
        ChainTip, DecodedResponse, EventPage, SimulationResult, StorageResult, TransactionReceipt,
        TransactionStatus,
    },
};
use thruput_json_rpc_types::{base58::Base58, hex::HexBytes};
use thruput_xdr::contract::ContractEntrypointID;
use thruput_xdr::types::ContractAddress;

use crate::error::{Result, TestkitError};

const RECEIPT_POLL_INTERVAL: Duration = Duration::from_millis(250);
const RECEIPT_TIMEOUT: Duration = Duration::from_secs(10);
const PENDING_POLL_INTERVAL: Duration = Duration::from_millis(25);
const PENDING_POLL_ATTEMPTS: usize = 400; // ~10 seconds at the interval above.

/// A cheap, cloneable handle onto the target network.
///
/// Chain verbs return [`TestkitError::Offline`] when the scenario has no live
/// target. [`Network::client`] exposes the underlying typed JSON-RPC client as
/// an escape hatch for methods this handle does not wrap.
#[derive(Clone)]
pub struct Network {
    inner: Arc<NetworkInner>,
}

/// A submitted transaction whose pending status and receipt can be awaited separately.
#[derive(Debug, Clone)]
#[must_use = "submitted transactions should be awaited or intentionally retained"]
pub struct SubmittedTransaction {
    network: Network,
    tx_hash: TxHash,
    tx_hex: String,
}

impl SubmittedTransaction {
    pub(crate) fn new(network: Network, tx_hash: TxHash, tx_hex: String) -> Self {
        Self {
            network,
            tx_hash,
            tx_hex,
        }
    }

    /// Signed bytes retained for reconciliation of the original attempt.
    pub fn signed_transaction(&self) -> &str {
        &self.tx_hex
    }

    /// Canonical transaction hash computed before submission.
    pub fn tx_hash(&self) -> TxHash {
        self.tx_hash
    }

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

    /// Wait until the indexer exposes this transaction's receipt.
    pub async fn await_receipt(&self) -> Result<TransactionReceipt> {
        self.network.await_receipt(self.tx_hash).await
    }
}

#[derive(Debug, PartialEq, Eq)]
struct FundingEvidence {
    tx_hash: TxHash,
    signed_transaction: HexBytes,
}

#[derive(Debug)]
struct LocalFundingAttempt {
    request: requests::FundAccountRequest,
    admitted: Option<thruput_json_rpc_types::responses::FundingSubmission>,
    evidence: Option<FundingEvidence>,
}

impl LocalFundingAttempt {
    fn retained_evidence(&self) -> Option<Box<(TxHash, HexBytes)>> {
        self.evidence
            .as_ref()
            .map(|e| Box::new((e.tx_hash, e.signed_transaction.clone())))
    }

    fn accept_response(
        &mut self,
        response: &thruput_json_rpc_types::responses::FundingSubmission,
    ) -> Result<()> {
        validate_funding_response(response, &self.request).map_err(|error| {
            TestkitError::InvalidFundingResponse {
                response: Box::new(response.clone()),
                retained: self.retained_evidence(),
                detail: error.to_string(),
            }
        })?;
        let evidence = FundingEvidence {
            tx_hash: response.transaction_hash,
            signed_transaction: response.signed_transaction.clone(),
        };
        if self
            .evidence
            .as_ref()
            .is_some_and(|original| original != &evidence)
        {
            return Err(TestkitError::InvalidFundingResponse {
                response: Box::new(response.clone()),
                retained: self.retained_evidence(),
                detail: "local funding replaced retained signed evidence".into(),
            });
        }
        self.admitted = Some(response.clone());
        Ok(())
    }

    fn retain_error_evidence(&mut self, error: &NativeClientError) -> Result<()> {
        use thruput_json_rpc_types::error::native::{DecodedError, ErrorData};
        if let NativeClientError::Application { data, .. } = error
            && let DecodedError::Known { data, .. } = data.as_ref()
        {
            let (tx_hash, signed_transaction) = match data.as_ref() {
                ErrorData::LocalFundingUnresolved {
                    transaction_hash,
                    signed_transaction,
                    ..
                } => (*transaction_hash, signed_transaction.clone()),
                ErrorData::FundingAttemptStopped(stopped) => {
                    let (Some(hash), Some(bytes)) =
                        (stopped.transaction_hash, &stopped.signed_transaction)
                    else {
                        return Ok(());
                    };
                    (hash, bytes.clone())
                }
                _ => return Ok(()),
            };
            let evidence = FundingEvidence {
                tx_hash,
                signed_transaction,
            };
            validate_funding_evidence(&evidence)?;
            if self
                .evidence
                .as_ref()
                .is_some_and(|original| original != &evidence)
            {
                return Err(TestkitError::signing(
                    "local funding replaced retained signed evidence",
                ));
            }
            self.evidence = Some(evidence);
        }
        Ok(())
    }
}

struct NetworkInner {
    rpc_url: Option<String>,
    client: Option<NativeClient<HttpClient>>,
    network_hash: Option<NetworkHash>,
    faucet: tokio::sync::Mutex<Option<crate::manifest::TestAccount>>,
    local_faucet: Option<ContractAddress>,
    local_funding:
        tokio::sync::Mutex<std::collections::HashMap<ContractAddress, LocalFundingAttempt>>,
    manual_block_producer: Option<ManualBlockProducer>,
}

impl fmt::Debug for Network {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Network")
            .field("rpc_url", &self.inner.rpc_url)
            .field("online", &self.inner.client.is_some())
            .field(
                "manual_block_production",
                &self.inner.manual_block_producer.is_some(),
            )
            .finish_non_exhaustive()
    }
}

impl Network {
    /// Connect to a live target, require it to serve the manifest's network, and
    /// retain its explicit bootstrap faucet adapter.
    pub(crate) async fn connect(
        rpc_url: &str,
        manifest: &RuntimeManifest,
        manual_block_producer: Option<ManualBlockProducer>,
    ) -> Result<Self> {
        let transport = HttpClientBuilder::default()
            .build(rpc_url)
            .map_err(|e| TestkitError::rpc("connect", e))?;
        let client = NativeClient::new(transport);
        thruput_client::check_endpoint(
            &client,
            &[
                "getNetworkInfo",
                "sendTransaction",
                "getTransactionStatus",
                "getTransactionReceipt",
            ],
        )
        .await
        .map_err(TestkitError::native)?;
        thruput_client::validate_network(&client, &manifest.network_hash.to_network_hash())
            .await
            .map_err(|error| match error {
                thruput_client::NativeRpcError::NetworkMismatch { .. } => TestkitError::Manifest {
                    field: "networkHash",
                    detail: format!("{error} at {rpc_url}"),
                },
                error => TestkitError::native(error),
            })?;
        Ok(Self {
            inner: Arc::new(NetworkInner {
                rpc_url: Some(rpc_url.to_owned()),
                client: Some(client),
                network_hash: Some(Base58(manifest.network_hash.to_network_hash().into_inner())),
                faucet: tokio::sync::Mutex::new(crate::manifest::derive_faucet(manifest)?),
                local_faucet: local_faucet(manifest)?,
                local_funding: tokio::sync::Mutex::new(std::collections::HashMap::new()),
                manual_block_producer,
            }),
        })
    }

    /// A handle with no live target; every chain verb reports [`TestkitError::Offline`].
    pub(crate) fn offline() -> Self {
        Self {
            inner: Arc::new(NetworkInner {
                rpc_url: None,
                client: None,
                network_hash: None,
                faucet: tokio::sync::Mutex::new(None),
                local_faucet: None,
                local_funding: tokio::sync::Mutex::new(std::collections::HashMap::new()),
                manual_block_producer: None,
            }),
        }
    }

    /// The public JSON-RPC URL, when the target has one.
    pub fn rpc_url(&self) -> Option<&str> {
        self.inner.rpc_url.as_deref()
    }

    /// The underlying typed JSON-RPC client, for methods this handle does not wrap.
    pub fn client(&self) -> Option<&NativeClient<HttpClient>> {
        self.inner.client.as_ref()
    }

    /// Current chain tip.
    pub async fn chain_tip(&self) -> Result<ChainTip> {
        known(
            self.require_client("getChainTip")?
                .get_chain_tip(EmptyRequest {})
                .await,
            "getChainTip",
        )
    }

    /// Submit a pre-signed transaction once, verifying the returned identity.
    pub async fn submit_raw(&self, tx_hex: String) -> Result<TxHash> {
        let bytes = thruput_json_rpc_types::hex::decode_prefixed_hex(&tx_hex)
            .map_err(TestkitError::signing)?;
        let signed: thruput_xdr::transaction::SignedTransaction =
            xdrs::txs::decode(&bytes).map_err(TestkitError::signing)?;
        let hash = TxHash(Base58(
            thruput_signing::transaction_hash(&signed.tx).map_err(TestkitError::signing)?,
        ));
        let canonical = thruput_json_rpc_types::hex::prefixed_hex(&bytes);
        crate::account::submit_signed(self, hash, &canonical).await?;
        Ok(hash)
    }

    /// Fetch a transaction receipt if it is already available.
    pub async fn receipt(&self, tx_hash: TxHash) -> Result<Option<TransactionReceipt>> {
        let receipt: Option<TransactionReceipt> = known(
            self.require_client("getTransactionReceipt")?
                .get_transaction_receipt(TransactionQuery {
                    transaction_hash: tx_hash,
                })
                .await,
            "getTransactionReceipt",
        )?;
        if let Some(observed) = &receipt
            && observed.transaction_hash != tx_hash
        {
            return Err(TestkitError::ReceiptHashMismatch {
                expected: tx_hash,
                receipt: Box::new(observed.clone()),
            });
        }
        if receipt
            .as_ref()
            .is_some_and(|r| r.transaction_hash == tx_hash)
        {
            self.inner.local_funding.lock().await.retain(|_, attempt| {
                !attempt
                    .admitted
                    .as_ref()
                    .is_some_and(|admitted| admitted.transaction_hash == tx_hash)
                    && !attempt
                        .evidence
                        .as_ref()
                        .is_some_and(|evidence| evidence.tx_hash == tx_hash)
            });
        }
        Ok(receipt)
    }

    /// Read-only receipt wait. Errors retain commitment and advisory status evidence;
    /// no status authorizes resubmission or proves that execution cannot occur.
    pub async fn await_receipt(&self, tx_hash: TxHash) -> Result<TransactionReceipt> {
        let client = self.require_client("getTransactionReceipt")?;
        let network_hash = self.inner.network_hash.ok_or(TestkitError::Offline {
            operation: "getTransactionReceipt",
        })?;
        let receipt = poll_receipt(
            client,
            network_hash,
            tx_hash,
            None,
            ReceiptPollConfig {
                timeout: RECEIPT_TIMEOUT,
                interval: RECEIPT_POLL_INTERVAL,
            },
            std::future::pending(),
        )
        .await
        .map_err(|source| TestkitError::ReceiptWait {
            source: Box::new(source),
        })?;
        self.inner.local_funding.lock().await.retain(|_, attempt| {
            !attempt
                .admitted
                .as_ref()
                .is_some_and(|r| r.transaction_hash == tx_hash)
                && !attempt
                    .evidence
                    .as_ref()
                    .is_some_and(|r| r.tx_hash == tx_hash)
        });
        Ok(receipt)
    }

    /// Fetch a transaction's advisory status.
    pub async fn transaction_status(&self, tx_hash: TxHash) -> Result<TransactionStatus> {
        known(
            self.require_client("getTransactionStatus")?
                .get_transaction_status(TransactionQuery {
                    transaction_hash: tx_hash,
                })
                .await,
            "getTransactionStatus",
        )
    }

    /// Wait until the scheduler reports a submitted transaction as pending.
    ///
    /// A successful submit RPC confirms admission, not nomination. Manual
    /// block tests should await this barrier before requesting nomination.
    /// If the transaction commits before `Pending` is observed, this returns
    /// [`TestkitError::TransactionNotPending`] because the requested nomination
    /// boundary has already passed.
    pub async fn await_pending(&self, tx_hash: TxHash) -> Result<()> {
        self.await_pending_inner(tx_hash).await
    }

    async fn await_pending_inner(&self, tx_hash: TxHash) -> Result<()> {
        let mut last_status = TransactionStatus::Unknown {};
        for _ in 0..PENDING_POLL_ATTEMPTS {
            let status = self.transaction_status(tx_hash).await?;
            match classify_pending_status(&status) {
                PendingStatusClassification::Ready => return Ok(()),
                PendingStatusClassification::Retry => {
                    last_status = status;
                    tokio::time::sleep(PENDING_POLL_INTERVAL).await;
                }
                PendingStatusClassification::Terminal => {
                    return Err(TestkitError::TransactionNotPending {
                        tx_hash: format!("{tx_hash:?}"),
                        status: Box::new(status),
                    });
                }
            }
        }
        Err(TestkitError::PendingTimeout {
            tx_hash: format!("{tx_hash:?}"),
            last_status: Box::new(last_status),
        })
    }

    /// Produce one block through a harness-owned local node in manual mode.
    pub async fn produce_block(&self) -> Result<ProducedBlock> {
        self.inner
            .manual_block_producer
            .as_ref()
            .ok_or(TestkitError::ManualBlockProductionUnavailable)?
            .produce_block()
            .await
            .map_err(|source| TestkitError::BlockProduction { source })
    }

    /// Read one latest-committed storage item at `address`/`key`.
    pub async fn get_storage_at(
        &self,
        address: ContractAddress,
        key: &[u8],
    ) -> Result<StorageResult> {
        known(
            self.require_client("getStorage")?
                .get_storage(requests::StorageQuery {
                    address: Base58(address),
                    key: HexBytes(key.to_vec()),
                })
                .await,
            "getStorage",
        )
    }

    /// Simulate a contract call through `simulateInvocation`.
    ///
    /// `caller` sets the simulated `msg.sender`; pass an agent's own address to
    /// read state keyed by that caller.
    pub async fn view_call(
        &self,
        contract: ContractAddress,
        entrypoint: ContractEntrypointID,
        calldata: &[u8],
        caller: Option<ContractAddress>,
    ) -> Result<SimulationResult> {
        let request = requests::SimulateInvocationRequest {
            assumed_auth: None,
            min_state_block_height: None,
            address: Base58(contract),
            entrypoint: HexBytes(entrypoint.into_inner().to_vec()),
            calldata: HexBytes(calldata.to_vec()),
            caller: caller.map(Base58),
            gas_limit: None,
        };
        known(
            self.require_client("simulateInvocation")?
                .simulate_invocation(request)
                .await,
            "simulateInvocation",
        )
    }

    /// Query events using native opaque pagination cursors.
    pub async fn get_events(&self, query: EventQuery) -> Result<EventPage> {
        known(
            self.require_client("getEvents")?.get_events(query).await,
            "getEvents",
        )
    }

    pub(crate) async fn submit_fund(
        &self,
        recipient: ContractAddress,
        amount: u128,
    ) -> Result<SubmittedTransaction> {
        self.require_client("fund")?;
        if let Some(faucet) = self.inner.local_faucet {
            return self.submit_local_fund(recipient, amount, faucet).await;
        }
        let calldata = thruput_signing::native_token_transfer_calldata(&recipient, amount)
            .map_err(TestkitError::signing)?;
        let faucet = self.inner.faucet.lock().await;
        let faucet = faucet.as_ref().ok_or(TestkitError::MissingFaucet)?;
        // The bootstrap faucet is shared across scenarios and processes. Its
        // funding transactions must not replay a deterministic scenario nonce.
        let mut nonce = [0; 8];
        getrandom::fill(&mut nonce).map_err(|error| {
            TestkitError::signing(format!("generate faucet transaction nonce: {error}"))
        })?;
        let (tx_hash, tx_hex) = crate::account::prepare_call(
            faucet,
            thruput_xdr::genesis_addresses::ADDRESS_NATIVE_TOKEN,
            thruput_signing::NATIVE_TOKEN_TRANSFER_ENTRYPOINT,
            &calldata,
            u64::from_le_bytes(nonce),
        )?;
        crate::account::submit_signed(self, tx_hash, &tx_hex).await?;
        Ok(SubmittedTransaction::new(self.clone(), tx_hash, tx_hex))
    }

    // Pending intent is retained on this Network handle before sending. Callers
    // retry on the same handle after uncertainty. Admission and signed bytes are
    // retained until an authoritative receipt, including cancellation of fund().
    async fn submit_local_fund(
        &self,
        recipient: ContractAddress,
        amount: u128,
        faucet: ContractAddress,
    ) -> Result<SubmittedTransaction> {
        use thruput_json_rpc_types::{airdrop::ClientNonce, requests::FundAccountRequest};
        if amount == 0 {
            return Err(TestkitError::signing("funding amount must be positive"));
        }
        let mut pending = self.inner.local_funding.lock().await;
        if let Some(request) = pending.get(&recipient) {
            if request.request.raw_amount != amount {
                return Err(TestkitError::FundingRequestMismatch { recipient });
            }
        } else {
            let mut nonce = [0; 16];
            getrandom::fill(&mut nonce).map_err(TestkitError::signing)?;
            pending.insert(
                recipient,
                LocalFundingAttempt {
                    request: FundAccountRequest {
                        recipient: Base58(recipient),
                        raw_amount: amount,
                        faucet: Base58(faucet),
                        client_nonce: ClientNonce::new(nonce.to_vec())
                            .map_err(TestkitError::signing)?,
                    },
                    admitted: None,
                    evidence: None,
                },
            );
        }
        let attempt = pending
            .get(&recipient)
            .expect("bug: retained funding intent");
        let request = attempt.request.clone();
        let response = if let Some(response) = &attempt.admitted {
            response.clone()
        } else {
            match self
                .require_client("fund")?
                .fund_account(request.clone())
                .await
            {
                Ok(response) => known(Ok(response), "dev_fundAccount")?,
                Err(error) => {
                    let attempt = pending
                        .get_mut(&recipient)
                        .expect("bug: retained funding intent");
                    if let Err(invalid) = attempt.retain_error_evidence(&error) {
                        return Err(TestkitError::InvalidFundingEvidence {
                            detail: invalid.to_string(),
                            retained: attempt.retained_evidence(),
                            source: Box::new(error),
                        });
                    }
                    return Err(match &attempt.evidence {
                        Some(evidence) => TestkitError::Submission {
                            tx_hash: evidence.tx_hash,
                            signed_transaction: thruput_json_rpc_types::hex::prefixed_hex(
                                &evidence.signed_transaction.0,
                            ),
                            detail: error.to_string(),
                            source: Box::new(error),
                        },
                        None => TestkitError::NativeCall {
                            method: "dev_fundAccount",
                            source: Box::new(error),
                        },
                    });
                }
            }
        };
        pending
            .get_mut(&recipient)
            .expect("bug: retained funding intent")
            .accept_response(&response)?;
        Ok(SubmittedTransaction::new(
            self.clone(),
            response.transaction_hash,
            thruput_json_rpc_types::hex::prefixed_hex(&response.signed_transaction.0),
        ))
    }

    pub(crate) fn require_client(
        &self,
        operation: &'static str,
    ) -> Result<&NativeClient<HttpClient>> {
        self.inner
            .client
            .as_ref()
            .ok_or(TestkitError::Offline { operation })
    }
}

fn known<T>(
    result: std::result::Result<DecodedResponse<T>, NativeClientError>,
    method: &'static str,
) -> Result<T> {
    match result {
        Ok(DecodedResponse::Known(value)) => Ok(value),
        Ok(DecodedResponse::Unsupported { raw }) => {
            Err(TestkitError::UnsupportedResponse { method, raw })
        }
        Ok(_) => Err(TestkitError::rpc(
            method,
            "unsupported response representation",
        )),
        Err(source) => Err(TestkitError::NativeCall {
            method,
            source: Box::new(source),
        }),
    }
}

fn validate_funding_response(
    response: &thruput_json_rpc_types::responses::FundingSubmission,
    request: &requests::FundAccountRequest,
) -> Result<()> {
    let signed: thruput_xdr::transaction::SignedTransaction =
        xdrs::txs::decode(&response.signed_transaction.0).map_err(TestkitError::signing)?;
    let hash = thruput_signing::transaction_hash(&signed.tx).map_err(TestkitError::signing)?;
    if response.recipient != request.recipient
        || response.raw_amount != request.raw_amount
        || response.transaction_hash.0.0 != hash
    {
        return Err(TestkitError::signing(
            "local funding response does not match retained request and signed hash",
        ));
    }
    Ok(())
}

fn validate_funding_evidence(evidence: &FundingEvidence) -> Result<()> {
    let signed: thruput_xdr::transaction::SignedTransaction =
        xdrs::txs::decode(&evidence.signed_transaction.0).map_err(TestkitError::signing)?;
    let hash = thruput_signing::transaction_hash(&signed.tx).map_err(TestkitError::signing)?;
    if evidence.tx_hash.0.0 != hash {
        return Err(TestkitError::signing(
            "local funding evidence hash does not match signed bytes",
        ));
    }
    Ok(())
}

fn local_faucet(manifest: &RuntimeManifest) -> Result<Option<ContractAddress>> {
    use thruput_json_rpc_types::runtime_manifest::{
        BOOTSTRAP_ACCOUNT_ROLE_FAUCET, HOGD_DEV_RUNTIME_MANIFEST_KIND,
    };
    if manifest.kind != HOGD_DEV_RUNTIME_MANIFEST_KIND {
        return Ok(None);
    }
    let mut faucets = manifest
        .bootstrap_accounts
        .iter()
        .filter(|a| a.role == BOOTSTRAP_ACCOUNT_ROLE_FAUCET);
    let faucet = faucets.next().ok_or(TestkitError::MissingFaucet)?;
    if faucets.next().is_some()
        || thruput_signing::PubkeyAccount::from_public_key_bytes(*faucet.public_key.0, 0).address()
            != faucet.wallet_address.0
    {
        return Err(TestkitError::Manifest {
            field: "bootstrapAccounts",
            detail: "local faucet must uniquely match its public nonce-zero account".into(),
        });
    }
    Ok(Some(faucet.wallet_address.0))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PendingStatusClassification {
    Ready,
    Retry,
    Terminal,
}

fn classify_pending_status(status: &TransactionStatus) -> PendingStatusClassification {
    match status {
        TransactionStatus::Pending { .. } => PendingStatusClassification::Ready,
        TransactionStatus::Unknown {} => PendingStatusClassification::Retry,
        _ => PendingStatusClassification::Terminal,
    }
}

#[cfg(test)]
mod tests {
    use thruput_json_rpc_types::responses::TransactionStatus;
    use thruput_node_supervisor::BlockDriverMode;

    use super::{
        LocalNetworkConfig, Network, PendingStatusClassification, classify_pending_status,
    };
    use crate::TestkitError;

    #[test]
    fn local_network_keeps_instant_block_production_by_default() {
        assert_eq!(
            LocalNetworkConfig::default().block_driver.mode,
            BlockDriverMode::Instant
        );
    }

    #[test]
    fn pending_status_classification_never_resubmits() {
        use thruput_json_rpc_types::responses::{SchedulerError, SchedulerErrorSource};
        assert_eq!(
            classify_pending_status(&TransactionStatus::Pending {
                recent_failure: None
            }),
            PendingStatusClassification::Ready
        );
        assert_eq!(
            classify_pending_status(&TransactionStatus::Unknown {}),
            PendingStatusClassification::Retry
        );
        for status in [
            TransactionStatus::Committed {
                block_height: 2.into(),
            },
            TransactionStatus::Retry {
                recent_failure: None,
                error: SchedulerError {
                    source: SchedulerErrorSource::Executor,
                    code: 7,
                },
            },
            TransactionStatus::Dropped {
                recent_failure: None,
                error: SchedulerError {
                    source: SchedulerErrorSource::Executor,
                    code: 7,
                },
            },
        ] {
            assert_eq!(
                classify_pending_status(&status),
                PendingStatusClassification::Terminal
            );
        }
    }

    #[tokio::test]
    async fn offline_network_rejects_manual_block_production() {
        let error = Network::offline()
            .produce_block()
            .await
            .expect_err("offline network must not expose manual production");
        assert!(matches!(
            error,
            TestkitError::ManualBlockProductionUnavailable
        ));
    }
}

/// Which network a scenario runs against, and how to reach it.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum NetworkConfig {
    /// An already-running network reached over its public JSON-RPC URL.
    Existing {
        /// Public JSON-RPC URL.
        rpc_url: String,
        /// Path to the network's runtime manifest.
        runtime_manifest: PathBuf,
    },
    /// A local node the harness launches and owns.
    Local(LocalNetworkConfig),
    /// No live network: agents run with locally-derived accounts and no chain.
    ///
    /// Useful for exercising agent coordination, timing, and messaging logic
    /// without a node. Chain verbs return [`crate::TestkitError::Offline`].
    Offline {
        /// Number of empty native accounts to make available to agents.
        accounts: usize,
    },
}

impl NetworkConfig {
    /// Configure an already-running (`existing`) network.
    pub fn existing(rpc_url: impl Into<String>, runtime_manifest: impl Into<PathBuf>) -> Self {
        Self::Existing {
            rpc_url: rpc_url.into(),
            runtime_manifest: runtime_manifest.into(),
        }
    }

    /// Configure a harness-managed (`local`) network.
    pub fn local(config: LocalNetworkConfig) -> Self {
        Self::Local(config)
    }

    /// Configure an offline network with `accounts` locally-derived accounts.
    pub fn offline(accounts: usize) -> Self {
        Self::Offline { accounts }
    }
}

/// Settings for a harness-managed local node.
///
/// The harness binds the public JSON-RPC facade on an ephemeral port and keeps
/// no PID file, so many local networks can run in one process without
/// colliding.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct LocalNetworkConfig {
    /// Explicit `hog-devnode` binary path. Falls back to discovery when unset
    /// (the `THRUPUT_DEVNODE_BINARY` env var, then a sibling of the current
    /// executable, then `PATH`).
    pub hog_devnode_binary: Option<PathBuf>,
    /// Artifact directories searched before the selected devnode's defaults.
    pub contract_artifact_directories: Vec<PathBuf>,
    /// Requested public JSON-RPC port; `0` asks the OS to choose.
    pub rpc_port: u16,
    /// Optional protocol token override for `hog-devnode` intro handshakes.
    ///
    /// Use when a local `hog-devnode` build is ahead of the protocol compiled
    /// into the supervisor; it only overrides the intro token.
    pub hogd_protocol: Option<String>,
    /// Devnode log verbosity. When set, `hog-devnode` is started at this level
    /// and testkit installs a stderr `tracing` subscriber (via `try_init`,
    /// honoring `RUST_LOG`) so the forwarded logs print. Leave `None` for a
    /// quiet node; call [`crate::init_tracing`] directly for finer control.
    pub log_level: Option<LogLevel>,
    /// Initial raw native token allocation per scenario-owned nonce-zero fixture account.
    pub initial_account_tokens: u64,
    /// Maximum time to wait for the node to report readiness.
    pub startup_timeout: Duration,
    /// Local block production policy. Defaults to submit-triggered production.
    pub block_driver: BlockDriverConfig,
}

impl Default for LocalNetworkConfig {
    fn default() -> Self {
        Self {
            hog_devnode_binary: None,
            contract_artifact_directories: Vec::new(),
            rpc_port: 0,
            hogd_protocol: None,
            log_level: None,
            initial_account_tokens: thruput_node_supervisor::config::DEFAULT_LOCAL_ACCOUNT_TOKENS,
            startup_timeout: Duration::from_secs(10),
            block_driver: BlockDriverConfig::default(),
        }
    }
}