sla-escrow-api 0.2.6

SLA-Escrow: Service Level Agreement Enforcer for AI Agents
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
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
use steel::*;

use crate::{
    consts::{
        BASIS_POINTS_DENOMINATOR, DEFAULT_FEE_BPS, PAYMENT_STATE_FUNDED, PAYMENT_STATE_REFUNDED,
        PAYMENT_STATE_RELEASED,
    },
    error::EscrowError,
    instruction::*,
    state::{bank_pda, escrow_pda, payment_pda, sol_storage_pda, Payment},
};

/// SDK for interacting with the Escrow program
pub struct EscrowSdk;

impl EscrowSdk {
    /// Get the program ID
    pub fn program_id() -> Pubkey {
        crate::ID
    }

    /// Get the bank PDA
    pub fn bank_pda() -> (Pubkey, u8) {
        bank_pda()
    }

    /// Get the config PDA
    pub fn config_pda() -> (Pubkey, u8) {
        crate::state::config_pda()
    }

    /// Get an escrow PDA for a specific mint
    pub fn escrow_pda(mint: Pubkey) -> (Pubkey, u8) {
        let (bank_pda, _) = Self::bank_pda();
        escrow_pda(mint, bank_pda)
    }

    /// Get a payment PDA for a specific payment UID
    pub fn payment_pda(payment_uid: &str, bank: Pubkey) -> (Pubkey, u8) {
        payment_pda(payment_uid, bank)
    }

    /// Get a SOL storage PDA for a specific escrow
    pub fn sol_storage_pda(mint: Pubkey, bank: Pubkey, escrow: Pubkey) -> (Pubkey, u8) {
        sol_storage_pda(mint, bank, escrow)
    }

    /// Get the associated token account for a wallet and mint
    pub fn associated_token_account(wallet: Pubkey, mint: Pubkey) -> Pubkey {
        spl_associated_token_account::get_associated_token_address_with_program_id(
            &wallet,
            &mint,
            &spl_token::ID,
        )
    }

    /// Get the associated token account for an escrow
    pub fn escrow_token_account(mint: Pubkey) -> Pubkey {
        let (escrow_pda, _) = Self::escrow_pda(mint);
        spl_associated_token_account::get_associated_token_address_with_program_id(
            &escrow_pda,
            &mint,
            &spl_token::ID,
        )
    }

    /// Calculate the minimum gross amount to charge a Buyer in order to receive a specific net payout
    /// hitting the Seller's wallet, taking into account protocol fees and oracle tips.
    ///
    /// # Explanation of `desired_net`
    /// `desired_net` is the final actual quantity of tokens deposited into the Seller's wallet after
    /// `sla-escrow` subtracts all protocol fees and oracle fees during `ReleasePayment`.
    ///
    /// *Example:*
    /// If you are an AI Image Generation Agent where a single generation costs you $0.80 in cloud GPU overhead,
    /// and you want to make exactly $0.20 in profit, your `desired_net` must be `$1.00` (which is $0.80 cost + $0.20 profit).
    /// You pass `$1.00` (in raw token decimals) as `desired_net`, and this function will return the inflated `gross_quote` (e.g. $1.15)
    /// that you must charge the Buyer in order to mathematically satisfy the protocol fees and walk away with exactly `$1.00`.
    pub fn calculate_gross_quote(
        desired_net: u64,
        fee_bps: u16,
        min_fee_amount: u64,
        oracle_fee_bps: u16,
    ) -> u64 {
        // Option A: Protocol fee is based on min_fee_amount
        // payout = amount - min_fee_amount - amount * oracle_fee_bps / 10000
        // amount * (10000 - oracle_fee_bps) = (payout + min_fee_amount) * 10000
        let numerator_a =
            (desired_net as u128 + min_fee_amount as u128).saturating_mul(BASIS_POINTS_DENOMINATOR);
        let denominator_a = (BASIS_POINTS_DENOMINATOR - oracle_fee_bps as u128).max(1);
        let amount_a = (numerator_a.saturating_add(denominator_a - 1) / denominator_a) as u64;

        // Option B: Protocol fee is based strictly on fee_bps percentage
        // payout = amount - amount * (fee_bps + oracle_fee_bps) / 10000
        // amount * (10000 - fee_bps - oracle_fee_bps) = payout * 10000
        let numerator_b = (desired_net as u128).saturating_mul(BASIS_POINTS_DENOMINATOR);
        let denominator_b =
            (BASIS_POINTS_DENOMINATOR - fee_bps as u128 - oracle_fee_bps as u128).max(1);
        let amount_b = (numerator_b.saturating_add(denominator_b - 1) / denominator_b) as u64;

        // Choose the correct amount: taking the maximum of the two ensures both constraints are satisfied.
        amount_a.max(amount_b)
    }

    // ============================================================================
    // INSTRUCTION BUILDERS (Following Steel Framework Patterns)
    // ============================================================================

    /// Create an initialize instruction
    pub fn initialize(signer: Pubkey, fee_bps: Option<u16>) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();
        let (config_pda, _) = Self::config_pda();
        Instruction {
            program_id: Self::program_id(),
            accounts: vec![
                AccountMeta::new(signer, true),
                AccountMeta::new(bank_pda, false),
                AccountMeta::new(config_pda, false),
                AccountMeta::new_readonly(solana_program::system_program::ID, false),
                AccountMeta::new_readonly(solana_program::sysvar::rent::ID, false),
            ],
            data: Initialize {
                fee_bps: (fee_bps.unwrap_or(DEFAULT_FEE_BPS)).to_le_bytes(),
                _padding: [0; 6], // Pad to 8 bytes for alignment
            }
            .to_bytes(),
        }
    }

    /// Create an open escrow instruction
    /// signer: bank authority
    /// payer: funder
    /// mint: token mint
    /// min_payment_amount: minimum payment amount
    /// max_payment_amount: maximum payment amount
    /// fee_bps: fee basis points
    /// oracle_fee_bps: oracle tip basis points (0 = disabled)
    #[allow(clippy::too_many_arguments)]
    pub fn open_escrow(
        signer: Pubkey,
        payer: Pubkey,
        mint: Pubkey,
        min_payment_amount: u64,
        max_payment_amount: u64,
        min_fee_amount: u64,
        fee_bps: u16,
        oracle_fee_bps: u16,
    ) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();
        let (escrow_pda, _) = Self::escrow_pda(mint);
        let escrow_tokens = if mint == Pubkey::default() {
            // For SOL, the escrow account itself holds the SOL
            escrow_pda
        } else {
            // For SPL tokens, use the associated token account
            Self::escrow_token_account(mint)
        };

        let mut accounts = vec![
            AccountMeta::new(signer, true),
            AccountMeta::new(payer, true),
            AccountMeta::new_readonly(bank_pda, false),
            AccountMeta::new(escrow_pda, false),
            AccountMeta::new(escrow_tokens, false),
            AccountMeta::new_readonly(mint, false),
            AccountMeta::new_readonly(solana_program::system_program::ID, false),
            AccountMeta::new_readonly(spl_token::ID, false),
            AccountMeta::new_readonly(spl_associated_token_account::ID, false),
            AccountMeta::new_readonly(solana_program::sysvar::rent::ID, false),
        ];

        // For SOL, add SOL storage PDA account
        if mint == Pubkey::default() {
            let (sol_storage_pda, _) = Self::sol_storage_pda(mint, bank_pda, escrow_pda);
            accounts.push(AccountMeta::new(sol_storage_pda, false));
        }

        Instruction {
            program_id: Self::program_id(),
            accounts,
            data: OpenEscrow {
                min_payment_amount: min_payment_amount.to_le_bytes(),
                max_payment_amount: max_payment_amount.to_le_bytes(),
                min_fee_amount: min_fee_amount.to_le_bytes(),
                fee_bps: fee_bps.to_le_bytes(),
                oracle_fee_bps: oracle_fee_bps.to_le_bytes(),
                _padding: [0; 4],
            }
            .to_bytes(),
        }
    }

    /// Helper function to sanitize payment_uid for PDA derivation
    fn sanitize_payment_uid(payment_uid: &str) -> [u8; 32] {
        let mut uid_bytes = [0u8; 32];
        let uid_str = payment_uid.replace('-', "");
        let uid_bytes_str = uid_str.as_bytes();
        let len = uid_bytes_str.len().min(32);
        uid_bytes[..len].copy_from_slice(&uid_bytes_str[..len]);
        uid_bytes
    }

    /// Create a fund payment instruction (supports both SOL and SPL tokens)
    /// For SOL: mint should be Pubkey::default()
    /// For SPL tokens: mint should be the actual token mint
    #[allow(clippy::too_many_arguments)]
    pub fn fund_payment(
        buyer: Pubkey,
        buyer_tokens: Option<Pubkey>, // None for SOL, Some(ata) for SPL tokens
        seller: Pubkey,
        mint: Pubkey,
        amount: u64,
        ttl_seconds: i64,
        payment_uid: &str,
        sla_hash: [u8; 32],
        oracle_authority: Pubkey,
    ) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();
        let (config_pda, _) = Self::config_pda();
        let (escrow_pda, _) = Self::escrow_pda(mint);
        let (payment_pda, _) = crate::state::payment_pda(payment_uid, bank_pda);

        let is_sol = mint == Pubkey::default();

        let mut accounts = vec![
            AccountMeta::new(buyer, true),
            AccountMeta::new_readonly(bank_pda, false),
            AccountMeta::new_readonly(config_pda, false),
            AccountMeta::new(escrow_pda, false),
            AccountMeta::new(payment_pda, false),
            AccountMeta::new_readonly(mint, false),
        ];

        if is_sol {
            // SOL-specific accounts: [sol_storage_pda, system_program]
            let (sol_storage_pda, _) = Self::sol_storage_pda(mint, bank_pda, escrow_pda);
            accounts.push(AccountMeta::new(sol_storage_pda, false));
            accounts.push(AccountMeta::new_readonly(
                solana_program::system_program::ID,
                false,
            ));
        } else {
            // SPL Token-specific accounts: [escrow_tokens, buyer_tokens, token_program, system_program]
            let buyer_tokens = buyer_tokens.expect("buyer_tokens required for SPL tokens");
            let escrow_tokens = Self::escrow_token_account(mint);
            accounts.push(AccountMeta::new(escrow_tokens, false));
            accounts.push(AccountMeta::new(buyer_tokens, false));
            accounts.push(AccountMeta::new_readonly(spl_token::ID, false));
            accounts.push(AccountMeta::new_readonly(
                solana_program::system_program::ID,
                false,
            ));
        }

        Instruction {
            program_id: Self::program_id(),
            accounts,
            data: FundPayment {
                seller,
                mint,
                oracle_authority,
                payment_uid: Self::sanitize_payment_uid(payment_uid),
                sla_hash,
                amount: amount.to_le_bytes(),
                ttl_seconds: ttl_seconds.to_le_bytes(),
            }
            .to_bytes(),
        }
    }

    /// Create a release payment instruction (supports both SOL and SPL tokens)
    /// For SOL: mint should be Pubkey::default()
    /// For SPL tokens: mint should be the actual token mint
    pub fn release_payment(
        caller: Pubkey,
        seller_tokens: Option<Pubkey>, // None for SOL, Some(ata) for SPL tokens
        seller: Option<Pubkey>,        // Seller's account info for ATA creation (SPL tokens only)
        mint: Pubkey,
        payment_uid: &str,
    ) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();
        let (config_pda, _) = Self::config_pda();
        let (escrow_pda, _) = Self::escrow_pda(mint);
        let (payment_pda, _) = Self::payment_pda(payment_uid, bank_pda);

        let is_sol = mint == Pubkey::default();

        let mut accounts = vec![
            AccountMeta::new(caller, true),
            AccountMeta::new_readonly(bank_pda, false),
            AccountMeta::new_readonly(config_pda, false),
            AccountMeta::new(escrow_pda, false),
            AccountMeta::new(payment_pda, false),
            AccountMeta::new_readonly(mint, false),
        ];

        if is_sol {
            // SOL accounts: [caller, bank, config, escrow, payment, mint, sol_storage_pda, seller, system_program]
            let (sol_storage_pda, _) = Self::sol_storage_pda(mint, bank_pda, escrow_pda);
            accounts.push(AccountMeta::new(sol_storage_pda, false));
            accounts.push(AccountMeta::new(
                seller.expect("seller required for SOL"),
                false,
            ));
            accounts.push(AccountMeta::new_readonly(
                solana_program::system_program::ID,
                false,
            ));
        } else {
            // SPL Token accounts: [caller, bank, config, escrow, payment, mint, escrow_tokens, seller_tokens, seller, token_program, associated_token_program, system_program]
            let seller_tokens = seller_tokens.expect("seller_tokens required for SPL tokens");
            let seller = seller.expect("seller account required for SPL tokens");
            let escrow_tokens = Self::escrow_token_account(mint);
            accounts.push(AccountMeta::new(escrow_tokens, false));
            accounts.push(AccountMeta::new(seller_tokens, false));
            accounts.push(AccountMeta::new(seller, false));
            accounts.push(AccountMeta::new_readonly(spl_token::ID, false));
            accounts.push(AccountMeta::new_readonly(
                spl_associated_token_account::ID,
                false,
            ));
            accounts.push(AccountMeta::new_readonly(
                solana_program::system_program::ID,
                false,
            ));
        }

        Instruction {
            program_id: Self::program_id(),
            accounts,
            data: ReleasePayment {}.to_bytes(),
        }
    }

    /// Create a refund payment instruction (supports both SOL and SPL tokens)
    /// For SOL: mint should be Pubkey::default()
    /// For SPL tokens: mint should be the actual token mint
    pub fn refund_payment(
        caller: Pubkey,
        buyer_tokens: Option<Pubkey>, // None for SOL, Some(ata) for SPL tokens
        mint: Pubkey,
        payment_uid: &str,
    ) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();
        let (config_pda, _) = Self::config_pda();
        let (escrow_pda, _) = Self::escrow_pda(mint);
        let (payment_pda, _) = Self::payment_pda(payment_uid, bank_pda);

        let is_sol = mint == Pubkey::default();

        let mut accounts = vec![
            AccountMeta::new(caller, true),
            AccountMeta::new_readonly(bank_pda, false),
            AccountMeta::new_readonly(config_pda, false),
            AccountMeta::new(escrow_pda, false),
            AccountMeta::new(payment_pda, false),
            AccountMeta::new_readonly(mint, false),
        ];

        if is_sol {
            // SOL accounts: [caller, bank, config, escrow, payment, mint, sol_storage_pda, buyer, system_program]
            let (sol_storage_pda, _) = Self::sol_storage_pda(mint, bank_pda, escrow_pda);
            accounts.push(AccountMeta::new(sol_storage_pda, false));
            accounts.push(AccountMeta::new(
                buyer_tokens.expect("buyer required for SOL"),
                false,
            ));
            accounts.push(AccountMeta::new_readonly(
                solana_program::system_program::ID,
                false,
            ));
        } else {
            // SPL Token accounts: [caller, bank, config, escrow, payment, mint, escrow_tokens, buyer_tokens, token_program]
            let buyer_tokens = buyer_tokens.expect("buyer_tokens required for SPL tokens");
            let escrow_tokens = Self::escrow_token_account(mint);
            accounts.push(AccountMeta::new(escrow_tokens, false));
            accounts.push(AccountMeta::new(buyer_tokens, false));
            accounts.push(AccountMeta::new_readonly(spl_token::ID, false));
        }

        Instruction {
            program_id: Self::program_id(),
            accounts,
            data: RefundPayment {}.to_bytes(),
        }
    }

    /// Create a submit delivery instruction
    pub fn submit_delivery(
        caller: Pubkey,
        mint: Pubkey,
        payment_uid: &str,
        delivery_hash: [u8; 32],
    ) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();
        let (escrow_pda, _) = Self::escrow_pda(mint);
        let (payment_pda, _) = Self::payment_pda(payment_uid, bank_pda);

        Instruction {
            program_id: Self::program_id(),
            accounts: vec![
                AccountMeta::new(caller, true), // signer (seller or admin)
                AccountMeta::new_readonly(bank_pda, false),
                AccountMeta::new_readonly(escrow_pda, false),
                AccountMeta::new(payment_pda, false),
            ],
            data: SubmitDelivery { delivery_hash }.to_bytes(),
        }
    }

    /// Create a close payment instruction
    pub fn close_payment(
        caller: Pubkey,
        buyer: Pubkey,
        mint: Pubkey,
        payment_uid: &str,
    ) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();
        let (config_pda, _) = Self::config_pda();
        let (escrow_pda, _) = Self::escrow_pda(mint);
        let (payment_pda, _) = Self::payment_pda(payment_uid, bank_pda);

        Instruction {
            program_id: Self::program_id(),
            accounts: vec![
                AccountMeta::new(caller, true), // signer (buyer or admin)
                AccountMeta::new(buyer, false), // rent receiver
                AccountMeta::new_readonly(bank_pda, false),
                AccountMeta::new_readonly(config_pda, false),
                AccountMeta::new(escrow_pda, false),
                AccountMeta::new(payment_pda, false),
                AccountMeta::new_readonly(solana_program::system_program::ID, false),
            ],
            data: ClosePayment {}.to_bytes(),
        }
    }

    /// Create a withdraw fees instruction (supports both SOL and SPL tokens)
    /// For SOL: mint should be Pubkey::default()
    /// For SPL tokens: mint should be the actual token mint
    pub fn withdraw_fees(
        authority: Pubkey,
        beneficiary: Pubkey,
        mint: Pubkey,
        amount: u64,
    ) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();
        let (config_pda, _) = Self::config_pda();
        let (escrow_pda, _) = Self::escrow_pda(mint);

        let is_sol = mint == Pubkey::default();

        let mut accounts = vec![
            AccountMeta::new(authority, true),
            AccountMeta::new_readonly(bank_pda, false),
            AccountMeta::new_readonly(config_pda, false),
            AccountMeta::new(escrow_pda, false),
            AccountMeta::new(beneficiary, false),
        ];

        if is_sol {
            // SOL accounts: [authority, bank, config, escrow, beneficiary, sol_storage_pda, system_program]
            let (sol_storage_pda, _) = Self::sol_storage_pda(mint, bank_pda, escrow_pda);
            accounts.push(AccountMeta::new(sol_storage_pda, false));
            accounts.push(AccountMeta::new_readonly(
                solana_program::system_program::ID,
                false,
            ));
        } else {
            // SPL Token accounts: [authority, bank, config, escrow, escrow_tokens, beneficiary_tokens, mint, token_program]
            let escrow_tokens = Self::escrow_token_account(mint);
            let beneficiary_tokens = Self::associated_token_account(beneficiary, mint);
            // Replace beneficiary with escrow_tokens, then add beneficiary_tokens
            accounts[4] = AccountMeta::new(escrow_tokens, false);
            accounts.push(AccountMeta::new(beneficiary_tokens, false));
            accounts.push(AccountMeta::new_readonly(mint, false));
            accounts.push(AccountMeta::new_readonly(spl_token::ID, false));
        }

        Instruction {
            program_id: Self::program_id(),
            accounts,
            data: WithdrawFees {
                amount: amount.to_le_bytes(),
            }
            .to_bytes(),
        }
    }

    /// Create an extend payment TTL instruction
    pub fn extend_payment_ttl(
        caller: Pubkey,
        mint: Pubkey,
        payment_uid: &str,
        additional_seconds: i64,
    ) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();
        let (config_pda, _) = Self::config_pda();
        let (escrow_pda, _) = Self::escrow_pda(mint);
        let (payment_pda, _) = Self::payment_pda(payment_uid, bank_pda);

        Instruction {
            program_id: Self::program_id(),
            accounts: vec![
                AccountMeta::new(caller, true),
                AccountMeta::new_readonly(bank_pda, false), // Bank is writable in program
                AccountMeta::new_readonly(config_pda, false),
                AccountMeta::new_readonly(escrow_pda, false),
                AccountMeta::new(payment_pda, false), // Payment is writable in program
                AccountMeta::new_readonly(solana_program::system_program::ID, false),
                AccountMeta::new_readonly(solana_program::sysvar::rent::ID, false),
            ],
            data: ExtendPaymentTTL {
                additional_seconds: additional_seconds.to_le_bytes(),
            }
            .to_bytes(),
        }
    }

    /// Create a close escrow instruction
    pub fn close_escrow(authority: Pubkey, recipient: Pubkey, mint: Pubkey) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();
        let (escrow_pda, _) = Self::escrow_pda(mint);
        let escrow_tokens = if mint == Pubkey::default() {
            let (sol_storage_pda, _) = Self::sol_storage_pda(mint, bank_pda, escrow_pda);
            sol_storage_pda
        } else {
            Self::escrow_token_account(mint)
        };

        Instruction {
            program_id: Self::program_id(),
            accounts: vec![
                AccountMeta::new(authority, true),
                AccountMeta::new_readonly(bank_pda, false),
                AccountMeta::new(escrow_pda, false),
                AccountMeta::new(escrow_tokens, false),
                AccountMeta::new_readonly(mint, false),
                AccountMeta::new_readonly(spl_token::ID, false),
                AccountMeta::new(recipient, false),
            ],
            data: CloseEscrow {}.to_bytes(),
        }
    }

    /// Create an update escrow settings instruction
    pub fn update_escrow_settings(
        authority: Pubkey,
        escrow: Pubkey,
        fee_bps: u16,
        min_payment_amount: u64,
        max_payment_amount: u64,
        min_fee_amount: u64,
        oracle_fee_bps: u16,
    ) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();
        let (config_pda, _) = Self::config_pda();

        Instruction {
            program_id: Self::program_id(),
            accounts: vec![
                AccountMeta::new(authority, true),
                AccountMeta::new_readonly(bank_pda, false), // Bank is writable in program
                AccountMeta::new_readonly(config_pda, false),
                AccountMeta::new(escrow, false), // Escrow is writable in program
                AccountMeta::new_readonly(solana_program::system_program::ID, false),
                AccountMeta::new_readonly(solana_program::sysvar::rent::ID, false),
            ],
            data: UpdateEscrowSettings {
                min_payment_amount: min_payment_amount.to_le_bytes(),
                max_payment_amount: max_payment_amount.to_le_bytes(),
                min_fee_amount: min_fee_amount.to_le_bytes(),
                new_fee_bps: fee_bps.to_le_bytes(),
                new_oracle_fee_bps: oracle_fee_bps.to_le_bytes(),
                _padding: [0; 4],
            }
            .to_bytes(),
        }
    }

    /// Create a pause escrow instruction
    pub fn pause_escrow(authority: Pubkey, mint: Pubkey, pause: bool) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();
        let (config_pda, _) = Self::config_pda();
        let (escrow_pda, _) = Self::escrow_pda(mint);

        Instruction {
            program_id: Self::program_id(),
            accounts: vec![
                AccountMeta::new(authority, true),
                AccountMeta::new_readonly(bank_pda, false), // Bank is writable in program
                AccountMeta::new_readonly(config_pda, false),
                AccountMeta::new(escrow_pda, false), // Escrow is writable in program
                AccountMeta::new_readonly(solana_program::system_program::ID, false),
                AccountMeta::new_readonly(solana_program::sysvar::rent::ID, false),
            ],
            data: PauseEscrow {
                pause: if pause { 1 } else { 0 },
            }
            .to_bytes(),
        }
    }

    /// Create an update authority instruction
    pub fn update_authority(current_authority: Pubkey, new_authority: Pubkey) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();

        Instruction {
            program_id: Self::program_id(),
            accounts: vec![
                AccountMeta::new(current_authority, true),
                AccountMeta::new(bank_pda, false),
            ],
            data: UpdateAuthority { new_authority }.to_bytes(),
        }
    }

    /// Create a confirm oracle instruction (oracle confirms fulfillment)
    pub fn confirm_oracle(
        oracle_authority: Pubkey,
        mint: Pubkey,
        payment_uid: &str,
        delivery_hash: [u8; 32],
        resolution_state: u8,
    ) -> Instruction {
        let (bank_pda, _) = Self::bank_pda();
        let (config_pda, _) = Self::config_pda();
        let (escrow_pda, _) = Self::escrow_pda(mint);
        let (payment_pda, _) = Self::payment_pda(payment_uid, bank_pda);

        Instruction {
            program_id: Self::program_id(),
            accounts: vec![
                AccountMeta::new(oracle_authority, true), // Oracle must sign
                AccountMeta::new_readonly(bank_pda, false),
                AccountMeta::new_readonly(config_pda, false),
                AccountMeta::new_readonly(escrow_pda, false),
                AccountMeta::new(payment_pda, false), // Payment is writable
            ],
            data: ConfirmOracle {
                delivery_hash,
                resolution_state,
                _padding: [0; 7],
            }
            .to_bytes(),
        }
    }

    // ============================================================================
    // VALIDATION HELPERS
    // ============================================================================

    /// Validate that a payment is in the correct state for funding
    pub fn validate_payment_for_funding(payment: &Payment) -> Result<(), EscrowError> {
        if payment.state != PAYMENT_STATE_FUNDED {
            return Err(EscrowError::InvalidPaymentState);
        }
        Ok(())
    }

    /// Validate that a payment is in the correct state for release
    pub fn validate_payment_for_release(payment: &Payment) -> Result<(), EscrowError> {
        if payment.state != PAYMENT_STATE_FUNDED {
            return Err(EscrowError::InvalidPaymentState);
        }
        Ok(())
    }

    /// Validate that a payment is in the correct state for refund
    pub fn validate_payment_for_refund(payment: &Payment) -> Result<(), EscrowError> {
        if payment.state != PAYMENT_STATE_FUNDED {
            return Err(EscrowError::InvalidPaymentState);
        }
        Ok(())
    }

    // ============================================================================
    // UTILITY FUNCTIONS
    // ============================================================================

    /// Calculate fee amount based on payment amount, fee basis points, and minimum fee
    pub fn calculate_fee(amount: u64, fee_bps: u16, min_fee_amount: u64) -> u64 {
        let fee_bps = fee_bps as u128;
        let amount_128 = amount as u128;
        let calculated_fee = ((amount_128 * fee_bps) / BASIS_POINTS_DENOMINATOR) as u64;
        // FIX(#8): Apply min_fee_amount floor and amount ceiling, matching on-chain logic
        calculated_fee.max(min_fee_amount).min(amount)
    }

    /// Calculate payout amount after deducting fees
    pub fn calculate_payout(amount: u64, fee_bps: u16, min_fee_amount: u64) -> u64 {
        let fee = Self::calculate_fee(amount, fee_bps, min_fee_amount);
        amount.saturating_sub(fee)
    }

    /// Check if a payment has expired
    pub fn is_payment_expired(payment: &Payment) -> bool {
        let clock = solana_program::clock::Clock::get().unwrap_or_default();
        clock.unix_timestamp > payment.expires_at
    }

    /// Get payment state as string
    pub fn get_payment_state_string(state: u8) -> &'static str {
        match state {
            PAYMENT_STATE_FUNDED => "Funded",
            PAYMENT_STATE_RELEASED => "Released",
            PAYMENT_STATE_REFUNDED => "Refunded",
            _ => "Unknown",
        }
    }

    /// Get escrow state as string
    pub fn get_escrow_state_string(paused: u8) -> &'static str {
        match paused {
            0 => "Active",
            1 => "Paused",
            _ => "Unknown",
        }
    }

    // ============================================================================
    // ACCOUNT DERIVATION HELPERS
    // ============================================================================

    /// Get all required accounts for a payment operation
    pub fn get_payment_accounts(
        buyer: Pubkey,
        seller: Pubkey,
        mint: Pubkey,
        payment_uid: &str,
    ) -> PaymentAccounts {
        let (bank_pda, _) = Self::bank_pda();
        let (escrow_pda, _) = Self::escrow_pda(mint);
        let (payment_pda, _) = Self::payment_pda(payment_uid, bank_pda);
        let escrow_tokens = Self::escrow_token_account(mint);

        PaymentAccounts {
            buyer,
            seller,
            mint,
            bank: bank_pda,
            escrow: escrow_pda,
            payment: payment_pda,
            escrow_tokens,
        }
    }

    /// Get all required accounts for an escrow operation
    pub fn get_escrow_accounts(mint: Pubkey) -> EscrowAccounts {
        let (bank_pda, _) = Self::bank_pda();
        let (escrow_pda, _) = Self::escrow_pda(mint);
        let escrow_tokens = Self::escrow_token_account(mint);

        EscrowAccounts {
            mint,
            bank: bank_pda,
            escrow: escrow_pda,
            escrow_tokens,
        }
    }
}

// ============================================================================
// CONVENIENCE STRUCTS FOR COMMON OPERATIONS
// ============================================================================

/// Accounts required for payment operations
#[derive(Debug, Clone)]
pub struct PaymentAccounts {
    pub buyer: Pubkey,
    pub seller: Pubkey,
    pub mint: Pubkey,
    pub bank: Pubkey,
    pub escrow: Pubkey,
    pub payment: Pubkey,
    pub escrow_tokens: Pubkey,
}

/// Accounts required for escrow operations
#[derive(Debug, Clone)]
pub struct EscrowAccounts {
    pub mint: Pubkey,
    pub bank: Pubkey,
    pub escrow: Pubkey,
    pub escrow_tokens: Pubkey,
}

/// Builder for creating payment instructions
pub struct PaymentBuilder {
    buyer: Option<Pubkey>,
    buyer_tokens: Option<Pubkey>,
    seller: Option<Pubkey>,
    mint: Option<Pubkey>,
    amount: Option<u64>,
    ttl_seconds: Option<i64>,
    payment_uid: Option<String>,
    sla_hash: Option<[u8; 32]>,
    oracle_authority: Option<Pubkey>,
}

impl PaymentBuilder {
    pub fn new() -> Self {
        Self {
            buyer: None,
            buyer_tokens: None,
            seller: None,
            mint: None,
            amount: None,
            ttl_seconds: None,
            payment_uid: None,
            sla_hash: None,
            oracle_authority: None,
        }
    }

    pub fn buyer(mut self, buyer: Pubkey) -> Self {
        self.buyer = Some(buyer);
        self
    }

    pub fn buyer_tokens(mut self, buyer_tokens: Pubkey) -> Self {
        self.buyer_tokens = Some(buyer_tokens);
        self
    }

    pub fn seller(mut self, seller: Pubkey) -> Self {
        self.seller = Some(seller);
        self
    }

    pub fn mint(mut self, mint: Pubkey) -> Self {
        self.mint = Some(mint);
        self
    }

    pub fn amount(mut self, amount: u64) -> Self {
        self.amount = Some(amount);
        self
    }

    pub fn ttl_seconds(mut self, ttl_seconds: i64) -> Self {
        self.ttl_seconds = Some(ttl_seconds);
        self
    }

    pub fn payment_uid(mut self, payment_uid: &str) -> Self {
        self.payment_uid = Some(payment_uid.to_string());
        self
    }

    pub fn sla_hash(mut self, sla_hash: [u8; 32]) -> Self {
        self.sla_hash = Some(sla_hash);
        self
    }

    pub fn oracle_authority(mut self, oracle_authority: Pubkey) -> Self {
        self.oracle_authority = Some(oracle_authority);
        self
    }

    pub fn build(self) -> Result<Instruction, EscrowError> {
        let buyer = self.buyer.ok_or(EscrowError::MissingRequiredField)?;
        let buyer_tokens = self.buyer_tokens; // Now optional
        let seller = self.seller.ok_or(EscrowError::MissingRequiredField)?;
        let mint = self.mint.ok_or(EscrowError::MissingRequiredField)?;
        let amount = self.amount.ok_or(EscrowError::MissingRequiredField)?;
        let ttl_seconds = self.ttl_seconds.ok_or(EscrowError::MissingRequiredField)?;
        let payment_uid = self.payment_uid.ok_or(EscrowError::MissingRequiredField)?;
        let sla_hash = self.sla_hash.unwrap_or([0; 32]);
        let oracle_authority = self.oracle_authority.unwrap_or_default();

        Ok(EscrowSdk::fund_payment(
            buyer,
            buyer_tokens,
            seller,
            mint,
            amount,
            ttl_seconds,
            &payment_uid,
            sla_hash,
            oracle_authority,
        ))
    }
}

impl Default for PaymentBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for escrow management operations
pub struct EscrowBuilder {
    authority: Option<Pubkey>,
    funder: Option<Pubkey>,
    mint: Option<Pubkey>,
    min_payment_amount: Option<u64>,
    max_payment_amount: Option<u64>,
    min_fee_amount: Option<u64>,
    fee_bps: Option<u16>,
    oracle_fee_bps: Option<u16>,
}

impl EscrowBuilder {
    pub fn new() -> Self {
        Self {
            authority: None,
            funder: None,
            mint: None,
            min_payment_amount: None,
            max_payment_amount: None,
            min_fee_amount: None,
            fee_bps: None,
            oracle_fee_bps: None,
        }
    }

    pub fn authority(mut self, authority: Pubkey) -> Self {
        self.authority = Some(authority);
        self
    }

    pub fn funder(mut self, funder: Pubkey) -> Self {
        self.funder = Some(funder);
        self
    }

    pub fn mint(mut self, mint: Pubkey) -> Self {
        self.mint = Some(mint);
        self
    }

    pub fn min_payment_amount(mut self, min_payment_amount: u64) -> Self {
        self.min_payment_amount = Some(min_payment_amount);
        self
    }

    pub fn max_payment_amount(mut self, max_payment_amount: u64) -> Self {
        self.max_payment_amount = Some(max_payment_amount);
        self
    }

    pub fn min_fee_amount(mut self, min_fee_amount: u64) -> Self {
        self.min_fee_amount = Some(min_fee_amount);
        self
    }

    pub fn fee_bps(mut self, fee_bps: u16) -> Self {
        self.fee_bps = Some(fee_bps);
        self
    }

    pub fn oracle_fee_bps(mut self, oracle_fee_bps: u16) -> Self {
        self.oracle_fee_bps = Some(oracle_fee_bps);
        self
    }

    pub fn create_escrow(self) -> Result<Instruction, EscrowError> {
        let authority = self.authority.ok_or(EscrowError::MissingRequiredField)?;
        let funder = self.funder.ok_or(EscrowError::MissingRequiredField)?;
        let mint = self.mint.ok_or(EscrowError::MissingRequiredField)?;
        let min_payment_amount = self
            .min_payment_amount
            .unwrap_or(crate::consts::DEFAULT_MIN_PAYMENT_RAW_USDC_DECIMALS_6);
        let max_payment_amount = self.max_payment_amount.unwrap_or(u64::MAX); // Default: no limit
        let min_fee_amount = self
            .min_fee_amount
            .unwrap_or(crate::consts::DEFAULT_MIN_FEE_RAW_USDC_DECIMALS_6);
        let fee_bps = self.fee_bps.unwrap_or(DEFAULT_FEE_BPS);
        let oracle_fee_bps = self.oracle_fee_bps.unwrap_or(0); // Default: no oracle tip

        Ok(EscrowSdk::open_escrow(
            authority,
            funder,
            mint,
            min_payment_amount,
            max_payment_amount,
            min_fee_amount,
            fee_bps,
            oracle_fee_bps,
        ))
    }

    pub fn pause_escrow(self, paused: bool) -> Result<Instruction, EscrowError> {
        let authority = self.authority.ok_or(EscrowError::MissingRequiredField)?;
        let mint = self.mint.ok_or(EscrowError::MissingRequiredField)?;

        Ok(EscrowSdk::pause_escrow(authority, mint, paused))
    }
}

impl Default for EscrowBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// CONSTANTS AND HELPER FUNCTIONS
// ============================================================================

/// Common token mint addresses
pub mod tokens {
    use solana_program::pubkey::Pubkey;

    /// USDC mint address
    pub const USDC: Pubkey =
        solana_program::pubkey!("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");

    /// USDT mint address
    pub const USDT: Pubkey =
        solana_program::pubkey!("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB");

    /// WSOL mint address
    pub const WSOL: Pubkey = solana_program::pubkey!("So11111111111111111111111111111111111111112");

    /// MARS mint address
    pub const MARS: Pubkey =
        solana_program::pubkey!("7RAV5UPRTzxn46kLeA8MiJsdNy9VKc5fip8FWEgTpTHh");

    /// MIRACLE mint address
    pub const MIRACLE: Pubkey =
        solana_program::pubkey!("Mirab4SFVff6sCuK48PPnSUj7PNpDDrBWY6FkJmuifG");

    /// TESTCOIN mint address
    pub const TESTCOIN: Pubkey =
        solana_program::pubkey!("2gNCDGj8Xi9Zs7LNQTPWf4pfZvAM7UHusY4xhKNYg6W6");
}

/// Payment states
pub mod payment_states {
    use crate::consts::{PAYMENT_STATE_FUNDED, PAYMENT_STATE_REFUNDED, PAYMENT_STATE_RELEASED};

    pub const FUNDED: u8 = PAYMENT_STATE_FUNDED;
    pub const RELEASED: u8 = PAYMENT_STATE_RELEASED;
    pub const REFUNDED: u8 = PAYMENT_STATE_REFUNDED;
}

/// Escrow states
pub mod escrow_states {
    pub const ACTIVE: u8 = 0;
    pub const PAUSED: u8 = 1;
}