trident-sdk 0.1.2

SDK for Trident protocol
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
use crate::eips::eip712::EIP712;
use crate::eips::eip7597::{EIP7597, EIP7597PermitMessage};
use crate::eips::erc20::IERC20;
use crate::error::Error;
use crate::types::{
    DepositInEvmChainWithApprovalResponse, EvmToEvmSpendRequest, EvmToEvmSpendResponse,
};
use alloy_primitives::{Address, Bytes, Signature, U256};
use alloy_provider::{Network, Provider};
use alloy_sol_types::{Eip712Domain, sol};
use rand_core::TryRngCore;
use std::collections::{HashMap, HashSet};
use tides_core_types::{ChainType, TidesChainId};
use tonic::codegen::StdError;
use tonic::transport::{Channel, Endpoint};
use trident_proto_types::trident::attester::v1::attester_service_client::AttesterServiceClient;
use trident_proto_types::trident::attester::v1::{GetChainTokenMappingsRequest, SpendRequest};
use trident_proto_types::trident::attester::v1::{
    GetDeploymentsRequest, GetLastFinalizedBlockRequest, GetSupportedDepositTokensRequest,
};
use trident_proto_types::trident::core::v1::SpendIntentSigned;
use trident_types::core::{FixedBytes32, SpendIntent, SpendSpec, TridentDeployment};
use trident_types::evm::abi::{TridentDelivery, TridentDeposits};

/// Client for interacting with Trident attester services and EVM contracts.
/// Maintains deployments, supported tokens, and exposes high-level operations.
pub struct TridentClient {
    deployments: HashMap<TidesChainId, TridentDeployment>,
    supported_tokens: HashMap<TidesChainId, HashSet<Address>>,
    // Expressed as percentage points.
    max_block_height_buffer_percentage: u64,
    /// gRPC client to the Trident Attester service.
    pub attester: AttesterServiceClient<Channel>,
}

impl TridentClient {
    /// Default buffer percentage applied to the minimum validity blocks
    /// when suggesting a spend intent's max block height.
    pub const DEFAULT_MAX_BLOCK_HEIGHT_BUFFER_PERCENTAGE: u64 = 10;
    /// Connects to the attester endpoint, loads deployments and supported deposit tokens.
    pub async fn connect<D>(endpoint: D) -> Result<Self, Error>
    where
        D: TryInto<Endpoint>,
        D::Error: Into<StdError>,
    {
        let mut attester = AttesterServiceClient::connect(endpoint).await?;

        // get deployments
        let deployments = attester
            .get_deployments(GetDeploymentsRequest {})
            .await?
            .into_inner()
            .deployments
            .into_iter()
            .map(|d| d.deployment.ok_or(Error::InvalidService))
            .map(|d| Ok(TridentDeployment::try_from(d?)?))
            .map(|d| d.map(|d| (d.chain_id, d)))
            .collect::<Result<HashMap<_, _>, Error>>()?;

        // get supported deposit tokens per deployment/chain
        let mut supported_tokens: HashMap<TidesChainId, HashSet<Address>> = HashMap::new();
        for (chain_id, _) in deployments.iter() {
            let resp = attester
                .get_supported_deposit_tokens(GetSupportedDepositTokensRequest {
                    chain_id: *chain_id,
                })
                .await?
                .into_inner();
            for t in resp.tokens.into_iter() {
                if t.address.len() == 32 {
                    let addr = Address::from_slice(&t.address[12..]);
                    supported_tokens.entry(*chain_id).or_default().insert(addr);
                }
            }
        }

        Ok(Self {
            attester,
            deployments,
            supported_tokens,
            max_block_height_buffer_percentage: Self::DEFAULT_MAX_BLOCK_HEIGHT_BUFFER_PERCENTAGE,
        })
    }

    pub async fn connect_testnet() -> Result<Self, Error> {
        Self::connect(crate::envs::testnet::trident::ENDPOINT).await
    }

    /// Sets the buffer percentage applied to the minimum validity blocks
    /// when suggesting spend intent expirations.
    pub fn with_max_block_height_buffer_percentage(mut self, buffer: u64) -> Self {
        self.max_block_height_buffer_percentage = buffer;
        self
    }

    /// Approves and deposits `amount` of `token` into the Trident deposits contract on an EVM chain.
    /// Returns receipts for both the approval and deposit transactions.
    pub async fn evm_deposit_with_approval<N: Network, P: Provider<N>>(
        &self,
        provider: P,
        tides_chain_id: u32,
        token: Address,
        amount: U256,
    ) -> Result<DepositInEvmChainWithApprovalResponse<N>, Error> {
        let deposits_contract = self.validate_evm_deposit(tides_chain_id, token)?;
        let approval_tx_receipt = self
            .evm_approve_token(&provider, token, deposits_contract, amount)
            .await?;
        let deposit_tx_receipt = self
            .evm_deposit_token(&provider, deposits_contract, token, amount)
            .await?;

        Ok(DepositInEvmChainWithApprovalResponse {
            approval_tx_receipt,
            deposit_tx_receipt,
        })
    }

    fn validate_evm_deposit(
        &self,
        tides_chain_id: TidesChainId,
        token: Address,
    ) -> Result<Address, Error> {
        let deployment = self.ensure_evm_chain(tides_chain_id)?;

        self.ensure_supported_token(tides_chain_id, token)?;

        let dep_addr_bytes = &deployment.trident_deposits_contract;
        if dep_addr_bytes.len() != 32 {
            return Err(Error::InvalidService);
        }
        Ok(Address::from_slice(&dep_addr_bytes[12..]))
    }

    async fn evm_approve_token<N: Network, P: Provider<N>>(
        &self,
        provider: &P,
        token: Address,
        spender: Address,
        amount: U256,
    ) -> Result<<N as Network>::ReceiptResponse, Error> {
        let erc20 = IERC20::new(token, provider);
        let tx = erc20.approve(spender, amount).send().await?;
        Ok(tx.get_receipt().await?)
    }

    /// Submits a deposit transaction to the Trident deposits contract for the given ERC-20 `token` and `amount`.
    pub async fn evm_deposit_token<N: Network, P: Provider<N>>(
        &self,
        provider: &P,
        deposits_contract: Address,
        token: Address,
        amount: U256,
    ) -> Result<<N as Network>::ReceiptResponse, Error> {
        let deposits = TridentDeposits::new(deposits_contract, provider);
        let tx = deposits.deposit(token, amount).send().await?;
        Ok(tx.get_receipt().await?)
    }

    pub async fn evm_sign_and_deposit_with_permit<
        N: Network,
        P: Provider<N>,
        S: alloy_signer::Signer + Send + Sync,
    >(
        &self,
        provider: P,
        mut signer: S,
        tides_chain_id: u32,
        token: Address,
        amount: U256,
        deadline: U256,
    ) -> Result<N::ReceiptResponse, Error> {
        let deposits_contract = self.validate_evm_deposit(tides_chain_id, token)?;
        let owner = signer.address();

        let signature = {
            let domain = EIP712::query_domain(&provider, token).await?;
            let nonce = EIP7597::get_nonce(&provider, token, owner).await?;
            self.evm_sign_deposit_with_permit_request(
                &mut signer,
                domain,
                deposits_contract,
                amount,
                nonce,
                deadline,
            )
            .await?
        };

        let deposit_tx_receipt = self
            .evm_deposit_with_permit(
                &provider,
                deposits_contract,
                token,
                owner,
                amount,
                deadline,
                Bytes::from(signature.as_bytes()),
            )
            .await?;

        Ok(deposit_tx_receipt)
    }

    pub async fn evm_sign_deposit_with_permit_request<S: alloy_signer::Signer + Send + Sync>(
        &self,
        mut signer: S,
        domain: Eip712Domain,
        spender: Address,
        amount: U256,
        nonce: U256,
        deadline: U256,
    ) -> Result<Signature, Error> {
        let typed_data = EIP7597::permit_typed_data(
            domain,
            EIP7597PermitMessage {
                owner: signer.address(),
                spender,
                value: amount,
                nonce,
                deadline,
            },
        );

        let sig = EIP712::sign(typed_data, &mut signer).await?;

        Ok(sig)
    }

    /// Deposit tokens with an EIP-7597 permit, passing the signature as bytes to allow for SCA deposits
    #[allow(clippy::too_many_arguments)]
    pub async fn evm_deposit_with_permit<N: Network, P: Provider<N>>(
        &self,
        provider: &P,
        deposits_contract: Address,
        token: Address,
        owner: Address,
        amount: U256,
        deadline: U256,
        signature: Bytes,
    ) -> Result<<N as Network>::ReceiptResponse, Error> {
        let deposits = TridentDeposits::new(deposits_contract, provider);
        let tx = deposits
            .depositWithPermit(token, owner, amount, deadline, signature)
            .send()
            .await?;
        Ok(tx.get_receipt().await?)
    }

    /// Executes a spend attestation on the destination chain by calling `TridentDelivery.deliverToken`.
    pub async fn evm_deliver<N: Network, P: Provider<N>>(
        &mut self,
        provider: &P,
        destination_chain: TidesChainId,
        attestation_payload: Vec<u8>,
        signature: Vec<u8>,
    ) -> Result<<N as Network>::ReceiptResponse, Error> {
        // Ensure destination chain is EVM and fetch delivery contract
        let dep = self.ensure_evm_chain(destination_chain)?;
        let delivery_addr = Address::try_from(dep.trident_delivery_contract)?;

        // Call deliverToken(attestationPayload, signature)
        let delivery = TridentDelivery::new(delivery_addr, provider);
        let tx = delivery
            .deliverToken(attestation_payload.into(), signature.into())
            .send()
            .await?;
        let receipt = tx.get_receipt().await?;
        Ok(receipt)
    }

    /// Creates, signs, and submits an EVM-to-EVM spend intent, then triggers delivery on the destination chain.
    /// Resolves destination token (if omitted), checks balances/fees, and returns the delivery receipt.
    pub async fn evm_to_evm_spend<'a, DN: Network, S: alloy_signer::Signer, DP: Provider<DN>>(
        &mut self,
        req: EvmToEvmSpendRequest<'a, S, DP, DN>,
    ) -> Result<EvmToEvmSpendResponse<DN>, Error> {
        let signer = req.source_signer.address();

        // Validate source and destination chains are known and EVM
        self.ensure_evm_chain(req.source_chain_id)?;
        self.ensure_evm_chain(req.destination_chain_id)?;

        // Validate source token supported
        self.ensure_supported_token(req.source_chain_id, req.source_token)?;

        // Resolve destination token mapping
        let dst_token = if let Some(tok) = req.destination_token {
            tok
        } else {
            self.resolve_single_destination_token(
                req.source_chain_id,
                req.destination_chain_id,
                req.source_token,
            )
            .await?
        };

        // Ensure destination token (resolved or provided) is supported on destination chain.
        // This will be relevant only in case the user provides its own tokens.
        self.ensure_supported_token(req.destination_chain_id, dst_token)?;

        // make spend spec
        let spend_spec = self.make_spend_spec(
            req.source_chain_id,
            signer,
            req.source_token,
            req.source_token_amount,
            req.destination_chain_id,
            dst_token,
            req.destination_recipient,
            req.destination_caller.unwrap_or(signer),
            req.salt.map(Ok).unwrap_or_else(|| self.generate_salt())?,
            req.destination_callback.map(|v| v.to_vec()),
        )?;

        // get suggested fee
        let fees = match req.source_max_fees {
            Some(fees) => fees,
            None => {
                self.get_suggested_fee(
                    req.source_chain_id,
                    req.source_token,
                    req.source_token_amount,
                    req.destination_chain_id,
                    dst_token,
                )
                .await?
            }
        };

        // ensure sufficient balance
        self.ensure_sufficient_source_balance(
            req.source_chain_id,
            signer,
            req.source_token,
            fees + req.source_token_amount,
        )
        .await?;

        // infer expiration height
        let max_block_height = match req.max_block_height {
            Some(max_block_height) => max_block_height,
            None => {
                self.suggest_spend_intent_max_block_height(req.source_chain_id)
                    .await?
            }
        };

        // make spend intent
        let spend_intent = self.make_spend_intent(fees, max_block_height, spend_spec);

        // sign spend intent
        let signature = trident_types::evm::spend_intent_signing::sign_spend_intent(
            req.source_signer,
            &spend_intent,
        )
        .await?
        .as_bytes()
        .to_vec();

        // send the spend intent to the attester
        let spend_attestation_signed = self
            .attester
            .spend(SpendRequest {
                intent: Some(SpendIntentSigned {
                    intent: Some(spend_intent.clone().into()),
                    signature,
                }),
            })
            .await?
            .into_inner()
            .attestation
            .expect("attester.spend.attestation");

        // invoke the EVM contract for delivery now.
        let delivery_tx_receipt = match self
            .evm_deliver(
                req.destination_provider,
                req.destination_chain_id,
                spend_attestation_signed.attestation_bytes.clone(),
                spend_attestation_signed.signature.clone(),
            )
            .await
        {
            Ok(r) => r,
            Err(e) => {
                return Err(Error::EvmDeliveryFailed(Box::new(
                    crate::error::EvmDeliveryFailed {
                        spend_intent,
                        attestation_payload: spend_attestation_signed.attestation_bytes,
                        signature: spend_attestation_signed.signature,
                        cause: Box::new(e),
                    },
                )));
            }
        };

        Ok(EvmToEvmSpendResponse {
            destination_token: dst_token,
            applied_fees: fees,
            max_block_height,
            delivery_tx_receipt,
        })
    }

    async fn resolve_single_destination_token(
        &mut self,
        source_chain_id: TidesChainId,
        destination_chain_id: TidesChainId,
        source_token: Address,
    ) -> Result<Address, Error> {
        let candidates: Vec<Address> = self
            .resolve_destination_tokens::<Address, Address>(
                source_chain_id,
                destination_chain_id,
                source_token,
            )
            .await?;

        match candidates.len() {
            0 => Err(Error::NoDestinationTokenMapping(
                source_token,
                source_chain_id,
                destination_chain_id,
            )),
            1 => Ok(candidates[0]),
            _ => Err(Error::AmbiguousDestinationTokenMapping(
                source_token,
                source_chain_id,
                destination_chain_id,
            )),
        }
    }

    /// Resolves the given source token into destination token(s) for `destination_chain`.
    /// `T1` must convert into `FixedBytes32`; `T2` must convert from `FixedBytes32`.
    pub async fn resolve_destination_tokens<T1, T2>(
        &mut self,
        source_chain_id: TidesChainId,
        destination_chain_id: TidesChainId,
        source_token: T1,
    ) -> Result<Vec<T2>, Error>
    where
        T1: Into<FixedBytes32>,
        T2: TryFrom<FixedBytes32>,
        <T2 as TryFrom<FixedBytes32>>::Error: core::fmt::Display,
    {
        if source_chain_id == destination_chain_id {
            let fb32: FixedBytes32 = source_token.into();
            let t2 = T2::try_from(fb32).map_err(|err: <T2 as TryFrom<FixedBytes32>>::Error| {
                Error::TokenConversion(err.to_string())
            })?;
            return Ok(vec![t2]);
        }

        let mappings = self
            .attester
            .get_chain_token_mappings(GetChainTokenMappingsRequest {
                chain_id: source_chain_id,
            })
            .await?
            .into_inner()
            .mappings;

        // find the entry for the source token
        let fb32: FixedBytes32 = source_token.into();
        let fb32_bytes = fb32.to_vec();

        let fb32s = mappings
            .into_iter()
            // get only source token.
            .filter(|v| match &v.token {
                None => false,
                Some(v) => v.address == fb32_bytes,
            })
            // collect only mappings, and flatten them
            .flat_map(|v| v.mappings)
            // collect only for the given destination chain
            .filter(|v| v.chain_id == destination_chain_id)
            // convert all the destination tokens into FixedBytes32
            .map(|v| Result::<_, Error>::Ok(FixedBytes32::try_from(v.address)?))
            // collect
            .collect::<Result<Vec<FixedBytes32>, Error>>()?;

        // finally convert all the fixed bytes 32 into T2.
        fb32s
            .into_iter()
            .map(|v| T2::try_from(v).map_err(|err| Error::TokenConversion(err.to_string())))
            .collect()
    }

    /// Ensures the given `account` has at least `amount` of `token` available on `chain_id`.
    async fn ensure_sufficient_source_balance(
        &mut self,
        chain_id: TidesChainId,
        account: Address,
        token: Address,
        amount: U256,
    ) -> Result<(), Error> {
        let resp = self
            .attester
            .balances(
                trident_proto_types::trident::attester::v1::BalancesRequest {
                    chain_id,
                    address: FixedBytes32::from(account).to_vec(),
                },
            )
            .await?
            .into_inner();

        // Find available balance for the specified token
        let mut available = U256::ZERO;
        for b in resp.available_balances.into_iter() {
            // token bytes are 32-byte left-padded address
            if b.token.len() == 32 {
                let fb = FixedBytes32::try_from(b.token)?;
                let tok_addr = Address::try_from(fb)?;
                if tok_addr == token {
                    // amount is 32-byte big-endian U256
                    let arr: [u8; 32] = b.amount.as_slice().try_into()?;
                    available = U256::from_be_bytes(arr);
                    break;
                }
            }
        }

        if available < amount {
            return Err(Error::InsufficientBalance(amount, available));
        }
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    /// Builds a `SpendSpec` after validating the source and destination chains.
    pub fn make_spend_spec(
        &self,
        source_chain: TidesChainId,
        source_depositor: Address,
        source_token: impl Into<FixedBytes32>,
        source_token_amount: U256,
        destination_chain: TidesChainId,
        destination_token: impl Into<FixedBytes32>,
        destination_recipient: impl Into<FixedBytes32>,
        destination_caller: impl Into<FixedBytes32>,
        salt: impl Into<FixedBytes32>,
        callback_data: Option<Vec<u8>>,
    ) -> Result<SpendSpec, Error> {
        // Validate chains are known and EVM
        let src_dep = self.ensure_evm_chain(source_chain)?;
        let dst_dep = self.ensure_evm_chain(destination_chain)?;

        // Build spec
        let spec = SpendSpec {
            version: 0,
            source_chain,
            source_contract: src_dep.trident_deposits_contract,
            source_token: source_token.into(),
            source_token_amount,
            source_depositor: FixedBytes32::from(source_depositor),
            destination_chain,
            destination_contract: dst_dep.trident_delivery_contract,
            destination_token: destination_token.into(),
            destination_recipient: destination_recipient.into(),
            destination_caller: destination_caller.into(),
            salt: salt.into(),
            callback_data: callback_data.unwrap_or_default(),
        };

        Ok(spec)
    }

    /// Wraps a `SpendSpec` into a `SpendIntent` with fee cap and expiration height.
    pub fn make_spend_intent(
        &self,
        max_fee: U256,
        max_block_height: u64,
        spend_spec: SpendSpec,
    ) -> SpendIntent {
        SpendIntent {
            max_fee: max_fee.try_into().unwrap(),
            max_block_height,
            spend_spec,
        }
    }

    fn generate_salt(&self) -> Result<FixedBytes32, Error> {
        let mut rng = rand::rngs::OsRng;
        let mut buf = [0u8; 32];
        rng.try_fill_bytes(&mut buf)?;
        Ok(FixedBytes32::from(buf))
    }

    /// Suggests a source-side fee for the given route and amount. Placeholder returning zero for now.
    pub async fn get_suggested_fee(
        &mut self,
        _source_chain: TidesChainId,
        _source_token: impl Into<FixedBytes32>,
        _source_token_amount: U256,
        _destination_chain: TidesChainId,
        _destination_token: impl Into<FixedBytes32>,
    ) -> Result<U256, Error> {
        // TODO: impl
        Ok(U256::ZERO)
    }

    /// Suggests a spend intent's max block height using:
    /// last finalized block + (min validity blocks + buffered min validity blocks).
    pub async fn suggest_spend_intent_max_block_height(
        &mut self,
        src_chain_id: TidesChainId,
    ) -> Result<u64, Error> {
        // 1) Get the min required validity blocks from deployment.
        let min_blocks = {
            let dep = self.ensure_known_chain(src_chain_id)?;
            dep.min_spend_intent_validity_blocks
        };

        // 2) Immediately apply buffer to the min required blocks
        let pct = self.max_block_height_buffer_percentage as u128;
        let buffer_blocks_u128 = (min_blocks as u128)
            .checked_mul(pct)
            .ok_or(Error::BlockHeightOverflow)?
            .checked_div(100u128)
            .ok_or(Error::BlockHeightOverflow)?;
        let buffer_blocks: u64 =
            u64::try_from(buffer_blocks_u128).map_err(|_| Error::BlockHeightOverflow)?;

        let min_blocks_with_buffer = min_blocks
            .checked_add(buffer_blocks)
            .ok_or(Error::BlockHeightOverflow)?;

        // 3) Query last finalized block for the source chain
        let last_finalized = self
            .attester
            .get_last_finalized_block(GetLastFinalizedBlockRequest {
                chain_id: src_chain_id,
            })
            .await?
            .into_inner()
            .last_finalized_block;

        // 4) Suggested max block height = last_finalized + min_blocks_with_buffer
        let suggested = last_finalized
            .checked_add(min_blocks_with_buffer)
            .ok_or(Error::BlockHeightOverflow)?;

        Ok(suggested)
    }

    fn ensure_known_chain(&self, chain_id: TidesChainId) -> Result<&TridentDeployment, Error> {
        self.deployments
            .get(&chain_id)
            .ok_or(Error::UnknownChain(chain_id))
    }

    fn ensure_evm_chain(&self, chain_id: TidesChainId) -> Result<&TridentDeployment, Error> {
        let dep = self.ensure_known_chain(chain_id)?;
        if dep.chain_type != ChainType::Evm {
            return Err(Error::UnsupportedChainType(dep.chain_type as i32));
        }
        Ok(dep)
    }

    fn ensure_supported_token(&self, chain_id: TidesChainId, token: Address) -> Result<(), Error> {
        let is_supported = self
            .supported_tokens
            .get(&chain_id)
            .map(|set| set.contains(&token))
            .unwrap_or(false);
        if is_supported {
            Ok(())
        } else {
            Err(Error::UnsupportedToken(token))
        }
    }

    /// Faucets tokens by calling `mint(address,uint256)` on an open‑mint token.
    /// `amount` is provided in the token's smallest unit.
    pub async fn evm_faucet<N: Network, P: Provider<N>>(
        &self,
        provider: &P,
        token: Address,
        recipient: Address,
        amount: U256,
    ) -> Result<N::ReceiptResponse, Error> {
        sol! {
            #[sol(rpc)]
            contract Faucet {
                function mint(address, uint256);
            }
        }

        // Call mint(to, amount)
        let faucet = Faucet::new(token, provider);
        let pending = faucet.mint(recipient, amount).send().await?;
        let receipt = pending.get_receipt().await?;

        Ok(receipt)
    }

    pub fn get_deployments(&self) -> &HashMap<TidesChainId, TridentDeployment> {
        &self.deployments
    }

    pub fn get_deployment_by_name(&self, name: impl AsRef<str>) -> Option<&TridentDeployment> {
        let name = name.as_ref();
        self.deployments.iter().find_map(|(_, value)| {
            if value.chain_name.eq(name) {
                Some(value)
            } else {
                None
            }
        })
    }

    pub async fn evm_balances(
        &mut self,
        chain_id: TidesChainId,
        address: impl Into<Address>,
    ) -> Result<HashMap<Address, U256>, Error> {
        // ensures EVM chain.
        self.ensure_evm_chain(chain_id)?;

        // gets balances.
        self.attester
            .balances(
                trident_proto_types::trident::attester::v1::BalancesRequest {
                    chain_id,
                    address: FixedBytes32::from(address.into()).to_vec(),
                },
            )
            .await?
            .into_inner()
            .available_balances
            .into_iter()
            .map(|balance| {
                let token: Address = FixedBytes32::try_from(balance.token)?.try_into()?;
                let amount =
                    U256::try_from_be_slice(&balance.amount).ok_or(Error::InvalidU256ByteSlice)?;
                Ok((token, amount))
            })
            .collect()
    }

    pub async fn evm_balance(
        &mut self,
        chain_id: TidesChainId,
        address: impl Into<Address>,
        want: impl Into<Address>,
    ) -> Result<U256, Error> {
        let want = want.into();
        self.evm_balances(chain_id, address).await.map(|v| {
            v.into_iter()
                .find_map(|(token, amount)| {
                    if token == want {
                        return Some(amount);
                    }
                    None
                })
                .unwrap_or_default()
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::{Error, TridentClient};
    use alloy_primitives::Address;
    use rand_core::TryRngCore;
    use std::collections::HashMap;
    use tides_core_types::{ChainType, TidesChainId};
    use tonic::transport::Channel;
    use trident_proto_types::trident::attester::v1::attester_service_client::AttesterServiceClient;
    use trident_types::core::{FixedBytes32, TridentDeployment};

    fn make_fb32() -> FixedBytes32 {
        let mut fb = FixedBytes32([0u8; 32]);
        rand::rngs::OsRng
            .try_fill_bytes(&mut fb.0)
            .expect("OsRng.try_fill_bytes");
        fb
    }

    fn make_deployment(chain_type: ChainType, chain_id: u32) -> TridentDeployment {
        TridentDeployment {
            chain_type,
            chain_name: "ethereum".to_string(),
            chain_id,
            trident_deposits_contract: make_fb32(),
            trident_claims_contract: make_fb32(),
            trident_delivery_contract: make_fb32(),
            min_spend_intent_validity_blocks: 10,
            max_spend_attestation_validity_blocks: 20,
            anchor_block: 1,
        }
    }

    fn make_test_client(deployments: HashMap<TidesChainId, TridentDeployment>) -> TridentClient {
        let attester =
            AttesterServiceClient::new(Channel::from_static("http://localhost:1").connect_lazy());

        TridentClient {
            deployments,
            supported_tokens: HashMap::new(),
            max_block_height_buffer_percentage:
                TridentClient::DEFAULT_MAX_BLOCK_HEIGHT_BUFFER_PERCENTAGE,
            attester,
        }
    }

    // ensure_known_chain tests (appears before ensure_evm_chain)
    #[tokio::test]
    async fn test_trident_client_ensure_known_chain_known_chain_success() {
        let chain_id: TidesChainId = 1;
        let mut deployments = HashMap::new();
        deployments.insert(chain_id, make_deployment(ChainType::Evm, chain_id));
        let client = make_test_client(deployments);

        let res = client.ensure_known_chain(chain_id);
        assert!(res.is_ok());
    }

    #[tokio::test]
    async fn test_trident_client_ensure_known_chain_unknown_chain_error() {
        let client = make_test_client(HashMap::new());
        let chain_id: TidesChainId = 42;

        let res = client.ensure_known_chain(chain_id);
        assert!(matches!(res, Err(Error::UnknownChain(id)) if id == chain_id));
    }

    // ensure_evm_chain tests
    #[tokio::test]
    async fn test_trident_client_ensure_evm_chain_evm_chain_success() {
        let chain_id: TidesChainId = 5;
        let mut deployments = HashMap::new();
        deployments.insert(chain_id, make_deployment(ChainType::Evm, chain_id));
        let client = make_test_client(deployments);

        let res = client.ensure_evm_chain(chain_id);
        assert!(res.is_ok());
    }

    // ensure_supported_token tests
    #[tokio::test]
    async fn test_trident_client_ensure_supported_token_supported_success() {
        let chain_id: TidesChainId = 9;
        let mut deployments = HashMap::new();
        deployments.insert(chain_id, make_deployment(ChainType::Evm, chain_id));
        let mut client = make_test_client(deployments);

        // insert token
        let token = Address::from([0x11u8; 20]);
        client
            .supported_tokens
            .entry(chain_id)
            .or_default()
            .insert(token);

        let res = client.ensure_supported_token(chain_id, token);
        assert!(matches!(res, Ok(())));
    }

    #[tokio::test]
    async fn test_trident_client_ensure_supported_token_unsupported_error() {
        let chain_id: TidesChainId = 10;
        let mut deployments = HashMap::new();
        deployments.insert(chain_id, make_deployment(ChainType::Evm, chain_id));
        let client = make_test_client(deployments);

        let token = Address::from([0x22u8; 20]);
        let res = client.ensure_supported_token(chain_id, token);
        assert!(matches!(res, Err(Error::UnsupportedToken(t)) if t == token));
    }

    #[tokio::test]
    async fn test_trident_client_resolve_destination_tokens_same_chain_success() {
        let chain_id: TidesChainId = 123;

        let mut client = {
            // For same-chain case, no deployments or attester lookups are needed.
            let deployments = HashMap::new();
            make_test_client(deployments)
        };

        let src_token = Address::from([0xAAu8; 20]);

        let res = client
            .resolve_destination_tokens::<Address, Address>(chain_id, chain_id, src_token)
            .await;

        assert!(res.is_ok());
        let v = res.unwrap();
        assert_eq!(v.len(), 1);
        assert_eq!(v[0], src_token);
    }
}