circles-sdk 0.1.1

Circles SDK orchestrating RPC, profiles, pathfinding, transfers, and contract runners.
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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
//! Runner abstractions and concrete wallet-backed implementations for write-capable SDK flows.
//!
//! The SDK prepares transactions as ABI-encoded calls and delegates submission to
//! an implementation of [`ContractRunner`]. This keeps the read path independent
//! from any wallet, Safe, or signer transport while still allowing a concrete
//! execution backend when the caller wants write parity.

use alloy_network::AnyNetwork;
use alloy_primitives::{Address, B256, Bytes, U256, aliases::TxHash};
use alloy_provider::{Identity, Provider, ProviderBuilder, RootProvider};
use alloy_rpc_types::TransactionRequest;
use alloy_signer_local::PrivateKeySigner;
use alloy_sol_types::SolCall;
use async_trait::async_trait;
use reqwest::Url;
use safe_rs::{
    Call, CallBuilder, ChainConfig, Eoa, EoaBatchResult, Error as SafeRsError, ExecutionResult,
    IMultiSend, ISafe, Operation, Safe, SafeTxParams, Wallet, WalletBuilder,
    encoding::{compute_safe_transaction_hash, encode_multisend_data},
};
use thiserror::Error;

type AnyHttpProvider = RootProvider<AnyNetwork>;
type SafeWallet = Wallet<Safe<AnyHttpProvider>>;
type EoaWallet = Wallet<Eoa<AnyHttpProvider>>;

/// Prepared transaction for a runner to submit. This is intentionally simple;
/// we can swap to richer contract-specific types as we wire more flows.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreparedTransaction {
    /// Contract address to call.
    pub to: Address,
    /// ABI-encoded calldata.
    pub data: Bytes,
    /// Optional native value to send alongside the call.
    pub value: Option<U256>,
}

/// Helper to turn a SolCall into a prepared transaction.
pub fn call_to_tx<C: SolCall>(to: Address, call: C, value: Option<U256>) -> PreparedTransaction {
    PreparedTransaction {
        to,
        data: Bytes::from(call.abi_encode()),
        value,
    }
}

/// Result stub for submitted transactions.
///
/// For Safe-backed execution this will usually contain a single item because the
/// full batch is submitted atomically as one on-chain Safe transaction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubmittedTx {
    /// Runner-reported transaction hash bytes.
    pub tx_hash: Bytes,
    /// Whether the underlying backend reported this transaction as successful.
    pub success: bool,
    /// Position of the transaction inside a sequential batch, when meaningful.
    pub index: Option<usize>,
}

/// Prepared Safe execution data for browser/external-signature workflows.
///
/// This is the Rust analogue of the TypeScript Safe batch `getSafeTransaction()`
/// seam: it captures the canonical Safe transaction fields plus the EIP-712 hash
/// that an external signer/backend would sign before turning it into an
/// `execTransaction` call.
#[derive(Debug, Clone)]
pub struct PreparedSafeExecution {
    /// Safe account that will execute the transaction.
    pub safe_address: Address,
    /// Chain id used when computing the Safe EIP-712 hash.
    pub chain_id: u64,
    /// Original SDK-prepared transactions before Safe wrapping.
    pub transactions: Vec<PreparedTransaction>,
    /// Canonical Safe transaction parameters.
    pub safe_tx: SafeTxParams,
    /// EIP-712 hash that the signer/backend must authorize.
    pub safe_tx_hash: B256,
}

impl PreparedSafeExecution {
    /// Whether this prepared Safe execution wraps multiple inner transactions.
    pub fn is_batch(&self) -> bool {
        self.transactions.len() > 1
    }

    /// Build the final Safe `execTransaction` call once signatures are available.
    pub fn to_exec_transaction(&self, signatures: Bytes) -> PreparedTransaction {
        call_to_tx(
            self.safe_address,
            ISafe::execTransactionCall {
                to: self.safe_tx.to,
                value: self.safe_tx.value,
                data: self.safe_tx.data.clone(),
                operation: self.safe_tx.operation.as_u8(),
                safeTxGas: self.safe_tx.safe_tx_gas,
                baseGas: self.safe_tx.base_gas,
                gasPrice: self.safe_tx.gas_price,
                gasToken: self.safe_tx.gas_token,
                refundReceiver: self.safe_tx.refund_receiver,
                signatures,
            },
            None,
        )
    }
}

/// Read-only Safe execution builder for browser/external signing workflows.
///
/// Unlike [`SafeContractRunner`], this does not require a local private key and
/// does not execute transactions. It only fetches the current Safe nonce/chain id
/// and produces the canonical Safe payload/hash a browser signer would need next.
pub struct SafeExecutionBuilder {
    safe_address: Address,
    provider: AnyHttpProvider,
}

impl SafeExecutionBuilder {
    /// Connect a Safe execution builder to the given RPC URL and Safe address.
    pub fn connect(rpc_url: &str, safe_address: Address) -> Result<Self, RunnerError> {
        let rpc_url = parse_rpc_url(rpc_url)?;
        let provider = build_read_provider(rpc_url);
        Ok(Self {
            safe_address,
            provider,
        })
    }

    /// Safe address this builder targets.
    pub fn safe_address(&self) -> Address {
        self.safe_address
    }

    /// Prepare a canonical Safe transaction from one or more SDK transactions.
    pub async fn prepare_transactions(
        &self,
        txs: Vec<PreparedTransaction>,
    ) -> Result<PreparedSafeExecution, RunnerError> {
        let chain_id = self
            .provider
            .get_chain_id()
            .await
            .map_err(|err| RunnerError::Transport(err.to_string()))?;
        let nonce = ISafe::new(self.safe_address, &self.provider)
            .nonce()
            .call()
            .await
            .map_err(|err| RunnerError::Transport(err.to_string()))?;
        prepare_safe_execution(self.safe_address, chain_id, nonce, txs)
    }
}

/// Buffered batch helper mirroring the TypeScript `BatchRun` concept.
#[async_trait]
pub trait BatchRun: Send {
    /// Add a transaction to the buffered batch.
    fn add_transaction(&mut self, tx: PreparedTransaction);

    /// Execute the buffered transactions via the underlying runner.
    async fn run(&mut self) -> Result<Vec<SubmittedTx>, RunnerError>;
}

/// Default batch-run implementation for any [`ContractRunner`].
pub struct BufferedBatchRun<'a, R: ContractRunner + ?Sized> {
    runner: &'a R,
    txs: Vec<PreparedTransaction>,
}

impl<'a, R: ContractRunner + ?Sized> BufferedBatchRun<'a, R> {
    /// Create a buffered batch bound to the given runner.
    pub fn new(runner: &'a R) -> Self {
        Self {
            runner,
            txs: Vec::new(),
        }
    }
}

#[async_trait]
impl<R: ContractRunner + ?Sized> BatchRun for BufferedBatchRun<'_, R> {
    fn add_transaction(&mut self, tx: PreparedTransaction) {
        self.txs.push(tx);
    }

    async fn run(&mut self) -> Result<Vec<SubmittedTx>, RunnerError> {
        self.runner
            .send_transactions(std::mem::take(&mut self.txs))
            .await
    }
}

/// Trait that allows the SDK to send transactions (e.g., via a Safe or EOA backend).
#[async_trait]
pub trait ContractRunner: Send + Sync {
    /// Address of the sender/safe/owner associated with this runner.
    fn sender_address(&self) -> Address;

    /// Optional alias matching the TypeScript runner surface.
    fn address(&self) -> Option<Address> {
        Some(self.sender_address())
    }

    /// Estimate gas for a prepared transaction.
    async fn estimate_gas(&self, _tx: PreparedTransaction) -> Result<u64, RunnerError> {
        Err(RunnerError::Unsupported(
            "gas estimation is not supported by this runner".to_string(),
        ))
    }

    /// Execute a read-only call using the runner's backend/provider.
    async fn call(&self, _tx: PreparedTransaction) -> Result<Bytes, RunnerError> {
        Err(RunnerError::Unsupported(
            "contract calls are not supported by this runner".to_string(),
        ))
    }

    /// Resolve a name to an address when supported.
    ///
    /// Rust currently guarantees direct hex-address parsing here; richer ENS
    /// integration remains a backend follow-up.
    async fn resolve_name(&self, name: &str) -> Result<Option<Address>, RunnerError> {
        Ok(name.parse().ok())
    }

    /// Create a buffered batch helper using this runner.
    fn send_batch_transaction(&self) -> Box<dyn BatchRun + '_> {
        Box::new(BufferedBatchRun::new(self))
    }

    /// Submit one or more prepared transactions.
    async fn send_transactions(
        &self,
        txs: Vec<PreparedTransaction>,
    ) -> Result<Vec<SubmittedTx>, RunnerError>;
}

/// Errors surfaced by the runner.
#[derive(Debug, Error)]
pub enum RunnerError {
    #[error("runner refused to send transactions: {0}")]
    Rejected(String),
    #[error("runner transport error: {0}")]
    Transport(String),
    #[error("runner capability unsupported: {0}")]
    Unsupported(String),
}

fn tx_hash_to_bytes(tx_hash: TxHash) -> Bytes {
    Bytes::copy_from_slice(tx_hash.as_slice())
}

fn prepared_to_request(from: Option<Address>, tx: PreparedTransaction) -> TransactionRequest {
    let mut request = TransactionRequest::default()
        .to(tx.to)
        .input(tx.data.into())
        .with_input_and_data();

    if let Some(from) = from {
        request = request.from(from);
    }

    if let Some(value) = tx.value {
        request = request.value(value);
    }

    request
}

fn submitted_from_execution_result(result: ExecutionResult) -> Vec<SubmittedTx> {
    vec![SubmittedTx {
        tx_hash: tx_hash_to_bytes(result.tx_hash),
        success: result.success,
        index: None,
    }]
}

fn submitted_from_eoa_result(result: EoaBatchResult) -> Vec<SubmittedTx> {
    result
        .results
        .into_iter()
        .map(|tx| SubmittedTx {
            tx_hash: tx_hash_to_bytes(tx.tx_hash),
            success: tx.success,
            index: Some(tx.index),
        })
        .collect()
}

fn map_safe_error(error: SafeRsError) -> RunnerError {
    match error {
        SafeRsError::Provider(_) | SafeRsError::Fetch { .. } | SafeRsError::UnsupportedChain(_) => {
            RunnerError::Transport(error.to_string())
        }
        _ => RunnerError::Rejected(error.to_string()),
    }
}

fn parse_rpc_url(rpc_url: &str) -> Result<Url, RunnerError> {
    rpc_url
        .parse()
        .map_err(|err| RunnerError::Rejected(format!("invalid rpc url: {err}")))
}

fn parse_private_key(private_key: &str) -> Result<PrivateKeySigner, RunnerError> {
    private_key
        .parse()
        .map_err(|err| RunnerError::Rejected(format!("invalid private key: {err}")))
}

fn build_read_provider(rpc_url: Url) -> AnyHttpProvider {
    ProviderBuilder::<Identity, Identity, AnyNetwork>::default().connect_http(rpc_url)
}

fn prepared_to_safe_call(tx: &PreparedTransaction) -> Call {
    Call::new(tx.to, tx.value.unwrap_or_default(), tx.data.clone())
}

fn build_safe_inner_tx(
    txs: &[PreparedTransaction],
    chain_config: &ChainConfig,
) -> (Address, U256, Bytes, Operation) {
    if txs.len() == 1 {
        let tx = &txs[0];
        (
            tx.to,
            tx.value.unwrap_or_default(),
            tx.data.clone(),
            Operation::Call,
        )
    } else {
        let calls = txs.iter().map(prepared_to_safe_call).collect::<Vec<_>>();
        let transactions = encode_multisend_data(&calls);
        let calldata = Bytes::from(IMultiSend::multiSendCall { transactions }.abi_encode());
        (
            chain_config.addresses.multi_send,
            U256::ZERO,
            calldata,
            Operation::DelegateCall,
        )
    }
}

fn prepare_safe_execution(
    safe_address: Address,
    chain_id: u64,
    nonce: U256,
    txs: Vec<PreparedTransaction>,
) -> Result<PreparedSafeExecution, RunnerError> {
    if txs.is_empty() {
        return Err(RunnerError::Rejected(
            "no transactions provided".to_string(),
        ));
    }

    let chain_config = ChainConfig::new(chain_id);
    let (to, value, data, operation) = build_safe_inner_tx(&txs, &chain_config);
    let safe_tx = SafeTxParams {
        to,
        value,
        data,
        operation,
        safe_tx_gas: U256::ZERO,
        base_gas: U256::ZERO,
        gas_price: U256::ZERO,
        gas_token: Address::ZERO,
        refund_receiver: Address::ZERO,
        nonce,
    };
    let safe_tx_hash = compute_safe_transaction_hash(chain_id, safe_address, &safe_tx);

    Ok(PreparedSafeExecution {
        safe_address,
        chain_id,
        transactions: txs,
        safe_tx,
        safe_tx_hash,
    })
}

fn attach_prepared_transactions<B>(builder: B, txs: Vec<PreparedTransaction>) -> B
where
    B: CallBuilder,
{
    txs.into_iter().fold(builder, |builder, tx| {
        builder.add_raw(tx.to, tx.value.unwrap_or_default(), tx.data)
    })
}

/// Safe-backed contract runner using `safe-rs`.
///
/// This currently targets single-owner (1/1 threshold) Safes, matching the
/// current capabilities of the underlying Safe crate used here.
pub struct SafeContractRunner {
    wallet: SafeWallet,
    provider: AnyHttpProvider,
}

impl SafeContractRunner {
    /// Connect to an existing Safe using the given RPC URL, signer private key,
    /// and Safe address.
    pub async fn connect(
        rpc_url: &str,
        private_key: &str,
        safe_address: Address,
    ) -> Result<Self, RunnerError> {
        let rpc_url = parse_rpc_url(rpc_url)?;
        let signer = parse_private_key(private_key)?;
        let provider = build_read_provider(rpc_url);
        let wallet = WalletBuilder::new(provider.clone(), signer)
            .connect(safe_address)
            .await
            .map_err(map_safe_error)?;
        wallet
            .inner()
            .verify_single_owner()
            .await
            .map_err(map_safe_error)?;
        Ok(Self { wallet, provider })
    }

    /// Prepare the canonical Safe payload/hash for one or more SDK transactions
    /// without executing them immediately.
    pub async fn prepare_transactions(
        &self,
        txs: Vec<PreparedTransaction>,
    ) -> Result<PreparedSafeExecution, RunnerError> {
        let chain_id = self
            .provider
            .get_chain_id()
            .await
            .map_err(|err| RunnerError::Transport(err.to_string()))?;
        let nonce = ISafe::new(self.wallet.address(), &self.provider)
            .nonce()
            .call()
            .await
            .map_err(|err| RunnerError::Transport(err.to_string()))?;
        prepare_safe_execution(self.wallet.address(), chain_id, nonce, txs)
    }
}

#[async_trait]
impl ContractRunner for SafeContractRunner {
    fn sender_address(&self) -> Address {
        self.wallet.address()
    }

    async fn estimate_gas(&self, tx: PreparedTransaction) -> Result<u64, RunnerError> {
        self.provider
            .estimate_gas(prepared_to_request(self.address(), tx).into())
            .await
            .map_err(|err| RunnerError::Transport(err.to_string()))
    }

    async fn call(&self, tx: PreparedTransaction) -> Result<Bytes, RunnerError> {
        self.provider
            .call(prepared_to_request(self.address(), tx).into())
            .await
            .map_err(|err| RunnerError::Transport(err.to_string()))
    }

    async fn send_transactions(
        &self,
        txs: Vec<PreparedTransaction>,
    ) -> Result<Vec<SubmittedTx>, RunnerError> {
        if txs.is_empty() {
            return Err(RunnerError::Rejected(
                "no transactions provided".to_string(),
            ));
        }

        let result = attach_prepared_transactions(self.wallet.batch(), txs)
            .execute()
            .await
            .map_err(map_safe_error)?;
        Ok(submitted_from_execution_result(result))
    }
}

/// EOA-backed contract runner using the same call-builder model as the Safe runner.
///
/// Unlike Safe execution, multi-transaction batches are submitted sequentially
/// and therefore are not atomic.
pub struct EoaContractRunner {
    wallet: EoaWallet,
    provider: AnyHttpProvider,
}

impl EoaContractRunner {
    /// Connect to an EOA signer using the given RPC URL and private key.
    pub async fn connect(rpc_url: &str, private_key: &str) -> Result<Self, RunnerError> {
        let rpc_url = parse_rpc_url(rpc_url)?;
        let signer = parse_private_key(private_key)?;
        let provider = build_read_provider(rpc_url.clone());
        let wallet = WalletBuilder::new(provider.clone(), signer)
            .connect_eoa(rpc_url)
            .await
            .map_err(map_safe_error)?;
        Ok(Self { wallet, provider })
    }
}

#[async_trait]
impl ContractRunner for EoaContractRunner {
    fn sender_address(&self) -> Address {
        self.wallet.address()
    }

    async fn estimate_gas(&self, tx: PreparedTransaction) -> Result<u64, RunnerError> {
        self.provider
            .estimate_gas(prepared_to_request(self.address(), tx).into())
            .await
            .map_err(|err| RunnerError::Transport(err.to_string()))
    }

    async fn call(&self, tx: PreparedTransaction) -> Result<Bytes, RunnerError> {
        self.provider
            .call(prepared_to_request(self.address(), tx).into())
            .await
            .map_err(|err| RunnerError::Transport(err.to_string()))
    }

    async fn send_transactions(
        &self,
        txs: Vec<PreparedTransaction>,
    ) -> Result<Vec<SubmittedTx>, RunnerError> {
        if txs.is_empty() {
            return Err(RunnerError::Rejected(
                "no transactions provided".to_string(),
            ));
        }

        let result = attach_prepared_transactions(self.wallet.batch(), txs)
            .execute()
            .await
            .map_err(map_safe_error)?;
        Ok(submitted_from_eoa_result(result))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloy_node_bindings::Anvil;
    use alloy_primitives::{TxKind, address};
    use alloy_provider::Provider;
    use safe_rs::{Call, EoaTxResult, SimulationResult};
    use std::process::{Command, Stdio};
    use std::sync::Mutex;

    const ANVIL_FIRST_PRIVATE_KEY: &str =
        "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
    const ANVIL_FIRST_ADDRESS: Address = address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266");
    const ANVIL_SECOND_ADDRESS: Address = address!("70997970C51812dc3A010C7d01b50e0d17dc79C8");

    fn anvil_binary_available() -> bool {
        Command::new("anvil")
            .arg("--version")
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .is_ok()
    }

    struct RecordingRunner {
        sender: Address,
        sent: Mutex<Vec<Vec<PreparedTransaction>>>,
    }

    impl Default for RecordingRunner {
        fn default() -> Self {
            Self {
                sender: Address::repeat_byte(0x55),
                sent: Mutex::new(Vec::new()),
            }
        }
    }

    #[async_trait]
    impl ContractRunner for RecordingRunner {
        fn sender_address(&self) -> Address {
            self.sender
        }

        async fn send_transactions(
            &self,
            txs: Vec<PreparedTransaction>,
        ) -> Result<Vec<SubmittedTx>, RunnerError> {
            self.sent.lock().expect("record sent txs").push(txs);
            Ok(vec![SubmittedTx {
                tx_hash: Bytes::copy_from_slice(&[0x77; 32]),
                success: true,
                index: None,
            }])
        }
    }

    #[derive(Default)]
    struct StubBuilder {
        calls: Vec<Call>,
        simulation_result: Option<SimulationResult>,
    }

    impl CallBuilder for StubBuilder {
        fn calls_mut(&mut self) -> &mut Vec<Call> {
            &mut self.calls
        }

        fn calls(&self) -> &Vec<Call> {
            &self.calls
        }

        fn with_gas_limit(self, _gas_limit: u64) -> Self {
            self
        }

        async fn simulate(self) -> safe_rs::Result<Self> {
            Ok(self)
        }

        fn simulation_result(&self) -> Option<&SimulationResult> {
            self.simulation_result.as_ref()
        }

        fn simulation_success(self) -> safe_rs::Result<Self> {
            Ok(self)
        }
    }

    #[test]
    fn attach_prepared_transactions_preserves_order_and_default_value() {
        let txs = vec![
            PreparedTransaction {
                to: Address::repeat_byte(0x11),
                data: Bytes::from_static(&[0xaa, 0xbb]),
                value: None,
            },
            PreparedTransaction {
                to: Address::repeat_byte(0x22),
                data: Bytes::from_static(&[0xcc]),
                value: Some(U256::from(42u64)),
            },
        ];

        let builder = attach_prepared_transactions(StubBuilder::default(), txs);
        assert_eq!(builder.calls.len(), 2);
        assert_eq!(builder.calls[0].to, Address::repeat_byte(0x11));
        assert_eq!(builder.calls[0].value, U256::ZERO);
        assert_eq!(builder.calls[0].data, Bytes::from_static(&[0xaa, 0xbb]));
        assert_eq!(builder.calls[1].to, Address::repeat_byte(0x22));
        assert_eq!(builder.calls[1].value, U256::from(42u64));
        assert_eq!(builder.calls[1].data, Bytes::from_static(&[0xcc]));
    }

    #[test]
    fn submitted_from_execution_result_returns_single_hash() {
        let submitted = submitted_from_execution_result(ExecutionResult {
            tx_hash: TxHash::repeat_byte(0x44),
            success: true,
        });

        assert_eq!(submitted.len(), 1);
        assert_eq!(submitted[0].tx_hash, Bytes::copy_from_slice(&[0x44; 32]));
        assert!(submitted[0].success);
        assert_eq!(submitted[0].index, None);
    }

    #[test]
    fn submitted_from_eoa_result_preserves_order() {
        let submitted = submitted_from_eoa_result(EoaBatchResult {
            results: vec![
                EoaTxResult {
                    tx_hash: TxHash::repeat_byte(0x01),
                    success: true,
                    index: 0,
                },
                EoaTxResult {
                    tx_hash: TxHash::repeat_byte(0x02),
                    success: true,
                    index: 1,
                },
            ],
            success_count: 2,
            failure_count: 0,
            first_failure: None,
        });

        assert_eq!(submitted.len(), 2);
        assert_eq!(submitted[0].tx_hash, Bytes::copy_from_slice(&[0x01; 32]));
        assert_eq!(submitted[1].tx_hash, Bytes::copy_from_slice(&[0x02; 32]));
        assert!(submitted[0].success);
        assert!(submitted[1].success);
        assert_eq!(submitted[0].index, Some(0));
        assert_eq!(submitted[1].index, Some(1));
    }

    #[test]
    fn prepare_safe_execution_uses_direct_call_for_single_transaction() {
        let tx = PreparedTransaction {
            to: Address::repeat_byte(0x11),
            data: Bytes::from_static(&[0xaa, 0xbb]),
            value: Some(U256::from(7u64)),
        };

        let prepared = prepare_safe_execution(
            Address::repeat_byte(0x44),
            100,
            U256::from(9u64),
            vec![tx.clone()],
        )
        .expect("prepare safe execution");

        assert!(!prepared.is_batch());
        assert_eq!(prepared.transactions, vec![tx.clone()]);
        assert_eq!(prepared.safe_tx.to, tx.to);
        assert_eq!(prepared.safe_tx.value, U256::from(7u64));
        assert_eq!(prepared.safe_tx.data, tx.data);
        assert_eq!(prepared.safe_tx.operation, Operation::Call);
        assert_eq!(prepared.safe_tx.nonce, U256::from(9u64));
        assert_eq!(
            prepared.safe_tx_hash,
            compute_safe_transaction_hash(100, Address::repeat_byte(0x44), &prepared.safe_tx)
        );
    }

    #[test]
    fn prepare_safe_execution_uses_multisend_for_batches() {
        let txs = vec![
            PreparedTransaction {
                to: Address::repeat_byte(0x11),
                data: Bytes::from_static(&[0xaa]),
                value: None,
            },
            PreparedTransaction {
                to: Address::repeat_byte(0x22),
                data: Bytes::from_static(&[0xbb, 0xcc]),
                value: Some(U256::from(5u64)),
            },
        ];
        let calls = txs.iter().map(prepared_to_safe_call).collect::<Vec<_>>();
        let expected_multisend = encode_multisend_data(&calls);
        let expected_data = Bytes::from(
            IMultiSend::multiSendCall {
                transactions: expected_multisend,
            }
            .abi_encode(),
        );

        let prepared = prepare_safe_execution(
            Address::repeat_byte(0x55),
            100,
            U256::from(3u64),
            txs.clone(),
        )
        .expect("prepare safe execution");

        assert!(prepared.is_batch());
        assert_eq!(prepared.transactions, txs);
        assert_eq!(
            prepared.safe_tx.to,
            ChainConfig::new(100).addresses.multi_send
        );
        assert_eq!(prepared.safe_tx.value, U256::ZERO);
        assert_eq!(prepared.safe_tx.operation, Operation::DelegateCall);
        assert_eq!(prepared.safe_tx.data, expected_data);
    }

    #[test]
    fn prepared_safe_execution_builds_exec_transaction_call() {
        let prepared = prepare_safe_execution(
            Address::repeat_byte(0x66),
            100,
            U256::from(1u64),
            vec![PreparedTransaction {
                to: Address::repeat_byte(0x11),
                data: Bytes::from_static(&[0xab, 0xcd]),
                value: Some(U256::from(2u64)),
            }],
        )
        .expect("prepare safe execution");

        let tx = prepared.to_exec_transaction(Bytes::from_static(&[0x12, 0x34]));
        let decoded =
            ISafe::execTransactionCall::abi_decode(&tx.data).expect("decode execTransaction call");

        assert_eq!(tx.to, prepared.safe_address);
        assert_eq!(tx.value, None);
        assert_eq!(decoded.to, prepared.safe_tx.to);
        assert_eq!(decoded.value, prepared.safe_tx.value);
        assert_eq!(decoded.data, prepared.safe_tx.data);
        assert_eq!(decoded.operation, prepared.safe_tx.operation.as_u8());
        assert_eq!(decoded.safeTxGas, prepared.safe_tx.safe_tx_gas);
        assert_eq!(decoded.baseGas, prepared.safe_tx.base_gas);
        assert_eq!(decoded.gasPrice, prepared.safe_tx.gas_price);
        assert_eq!(decoded.gasToken, prepared.safe_tx.gas_token);
        assert_eq!(decoded.refundReceiver, prepared.safe_tx.refund_receiver);
        assert_eq!(decoded.signatures, Bytes::from_static(&[0x12, 0x34]));
    }

    #[test]
    fn prepare_safe_execution_rejects_empty_batches() {
        let result = prepare_safe_execution(Address::ZERO, 100, U256::ZERO, Vec::new());

        assert!(matches!(result, Err(RunnerError::Rejected(_))));
    }

    #[test]
    fn prepared_to_request_preserves_fields_and_duplicates_input_data() {
        let tx = PreparedTransaction {
            to: ANVIL_SECOND_ADDRESS,
            data: Bytes::from_static(&[0xde, 0xad, 0xbe, 0xef]),
            value: Some(U256::from(321u64)),
        };

        let request = prepared_to_request(Some(ANVIL_FIRST_ADDRESS), tx.clone());

        assert_eq!(request.from, Some(ANVIL_FIRST_ADDRESS));
        assert_eq!(request.to, Some(TxKind::Call(ANVIL_SECOND_ADDRESS)));
        assert_eq!(request.value, Some(U256::from(321u64)));
        assert_eq!(request.input.input(), Some(&tx.data));
        assert_eq!(request.input.data.as_ref(), Some(&tx.data));
    }

    #[test]
    fn contract_runner_address_defaults_to_sender_address() {
        let runner = RecordingRunner::default();

        assert_eq!(runner.address(), Some(runner.sender_address()));
    }

    #[tokio::test]
    async fn batch_runner_buffers_and_forwards_transactions() {
        let runner = RecordingRunner::default();
        let mut batch = runner.send_batch_transaction();

        batch.add_transaction(PreparedTransaction {
            to: Address::repeat_byte(0x11),
            data: Bytes::from_static(&[0xaa]),
            value: None,
        });
        batch.add_transaction(PreparedTransaction {
            to: Address::repeat_byte(0x22),
            data: Bytes::from_static(&[0xbb, 0xcc]),
            value: Some(U256::from(9u64)),
        });

        let submitted = batch.run().await.expect("batch run succeeds");
        let sent = runner.sent.lock().expect("inspect recorded batch");

        assert_eq!(sent.len(), 1);
        assert_eq!(sent[0].len(), 2);
        assert_eq!(sent[0][0].to, Address::repeat_byte(0x11));
        assert_eq!(sent[0][1].to, Address::repeat_byte(0x22));
        assert_eq!(sent[0][1].value, Some(U256::from(9u64)));
        assert_eq!(submitted[0].tx_hash, Bytes::copy_from_slice(&[0x77; 32]));
        assert!(submitted[0].success);
    }

    #[tokio::test]
    async fn default_resolve_name_parses_hex_address_strings() {
        let runner = RecordingRunner::default();

        assert_eq!(
            runner
                .resolve_name(&ANVIL_FIRST_ADDRESS.to_string())
                .await
                .expect("default resolver succeeds"),
            Some(ANVIL_FIRST_ADDRESS)
        );
        assert_eq!(
            runner
                .resolve_name("alice.eth")
                .await
                .expect("default resolver succeeds"),
            None
        );
    }

    #[tokio::test]
    async fn safe_runner_rejects_invalid_private_key() {
        let result = SafeContractRunner::connect(
            "https://rpc.example.invalid",
            "not-a-private-key",
            Address::ZERO,
        )
        .await;

        assert!(matches!(result, Err(RunnerError::Rejected(_))));
    }

    #[tokio::test]
    async fn eoa_runner_rejects_invalid_private_key() {
        let result = EoaContractRunner::connect("https://rpc.example.invalid", "bad-key").await;

        assert!(matches!(result, Err(RunnerError::Rejected(_))));
    }

    #[test]
    fn safe_execution_builder_rejects_invalid_rpc_url() {
        let result = SafeExecutionBuilder::connect("not-a-url", Address::ZERO);

        assert!(matches!(result, Err(RunnerError::Rejected(_))));
    }

    #[tokio::test]
    async fn eoa_runner_executes_value_transfer_on_anvil() {
        if !anvil_binary_available() {
            eprintln!("skipping anvil-backed test because `anvil` is not installed");
            return;
        }

        let anvil = Anvil::new().spawn();
        let provider = build_read_provider(anvil.endpoint_url());
        let before = provider
            .get_balance(ANVIL_SECOND_ADDRESS)
            .await
            .expect("balance before transfer");
        let runner = EoaContractRunner::connect(&anvil.endpoint(), ANVIL_FIRST_PRIVATE_KEY)
            .await
            .expect("connect EOA runner");

        assert_eq!(runner.sender_address(), ANVIL_FIRST_ADDRESS);

        let submitted = runner
            .send_transactions(vec![PreparedTransaction {
                to: ANVIL_SECOND_ADDRESS,
                data: Bytes::new(),
                value: Some(U256::from(123u64)),
            }])
            .await
            .expect("EOA transfer executes");

        assert_eq!(submitted.len(), 1);

        let after = provider
            .get_balance(ANVIL_SECOND_ADDRESS)
            .await
            .expect("balance after transfer");
        assert_eq!(after - before, U256::from(123u64));
    }

    #[tokio::test]
    async fn eoa_runner_exposes_estimate_and_call_helpers() {
        if !anvil_binary_available() {
            eprintln!("skipping anvil-backed test because `anvil` is not installed");
            return;
        }

        let anvil = Anvil::new().spawn();
        let runner = EoaContractRunner::connect(&anvil.endpoint(), ANVIL_FIRST_PRIVATE_KEY)
            .await
            .expect("connect EOA runner");

        let gas = runner
            .estimate_gas(PreparedTransaction {
                to: ANVIL_SECOND_ADDRESS,
                data: Bytes::new(),
                value: Some(U256::from(1u64)),
            })
            .await
            .expect("estimate gas");
        assert!(gas > 0);

        let call_output = runner
            .call(PreparedTransaction {
                to: ANVIL_SECOND_ADDRESS,
                data: Bytes::new(),
                value: None,
            })
            .await
            .expect("eth_call succeeds");
        assert_eq!(call_output, Bytes::new());
    }

    #[tokio::test]
    async fn safe_runner_rejects_non_safe_address_on_plain_anvil() {
        if !anvil_binary_available() {
            eprintln!("skipping anvil-backed test because `anvil` is not installed");
            return;
        }

        let anvil = Anvil::new().spawn();
        let result = SafeContractRunner::connect(
            &anvil.endpoint(),
            ANVIL_FIRST_PRIVATE_KEY,
            ANVIL_FIRST_ADDRESS,
        )
        .await;

        assert!(matches!(result, Err(RunnerError::Transport(_))));
    }
}