veilix-sdk 0.2.3 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -67,7 +67,7 @@ function formatBaseUnits(value, decimals) {
67
67
 
68
68
  // src/idl/veilix-devnet.json
69
69
  var veilix_devnet_default = {
70
- address: "HbatG5gpfs2g3N4gc2Qkfmmeu4zaBEVxzrDdYtWNLyyA",
70
+ address: "Vxi1QK84Akv4yGngjvkWNmEsK7XpsSrpDaPBoiyXGPG",
71
71
  metadata: {
72
72
  name: "veilix",
73
73
  version: "0.2.0",
@@ -668,6 +668,38 @@ var veilix_devnet_default = {
668
668
  {
669
669
  name: "system_program",
670
670
  address: "11111111111111111111111111111111"
671
+ },
672
+ {
673
+ name: "event_authority",
674
+ pda: {
675
+ seeds: [
676
+ {
677
+ kind: "const",
678
+ value: [
679
+ 95,
680
+ 95,
681
+ 101,
682
+ 118,
683
+ 101,
684
+ 110,
685
+ 116,
686
+ 95,
687
+ 97,
688
+ 117,
689
+ 116,
690
+ 104,
691
+ 111,
692
+ 114,
693
+ 105,
694
+ 116,
695
+ 121
696
+ ]
697
+ }
698
+ ]
699
+ }
700
+ },
701
+ {
702
+ name: "program"
671
703
  }
672
704
  ],
673
705
  args: [
@@ -730,6 +762,91 @@ var veilix_devnet_default = {
730
762
  ]
731
763
  }
732
764
  },
765
+ {
766
+ name: "program_data",
767
+ docs: [
768
+ "This program's ProgramData. Only its upgrade authority may initialize the network,",
769
+ "so nobody can claim the config authority between deploy and setup."
770
+ ],
771
+ pda: {
772
+ seeds: [
773
+ {
774
+ kind: "const",
775
+ value: [
776
+ 7,
777
+ 107,
778
+ 64,
779
+ 50,
780
+ 251,
781
+ 172,
782
+ 47,
783
+ 215,
784
+ 89,
785
+ 179,
786
+ 92,
787
+ 125,
788
+ 67,
789
+ 162,
790
+ 96,
791
+ 45,
792
+ 239,
793
+ 91,
794
+ 223,
795
+ 168,
796
+ 251,
797
+ 138,
798
+ 165,
799
+ 133,
800
+ 253,
801
+ 74,
802
+ 152,
803
+ 142,
804
+ 6,
805
+ 85,
806
+ 93,
807
+ 119
808
+ ]
809
+ }
810
+ ],
811
+ program: {
812
+ kind: "const",
813
+ value: [
814
+ 2,
815
+ 168,
816
+ 246,
817
+ 145,
818
+ 78,
819
+ 136,
820
+ 161,
821
+ 176,
822
+ 226,
823
+ 16,
824
+ 21,
825
+ 62,
826
+ 247,
827
+ 99,
828
+ 174,
829
+ 43,
830
+ 0,
831
+ 194,
832
+ 185,
833
+ 61,
834
+ 22,
835
+ 193,
836
+ 36,
837
+ 210,
838
+ 192,
839
+ 83,
840
+ 122,
841
+ 16,
842
+ 4,
843
+ 128,
844
+ 0,
845
+ 0
846
+ ]
847
+ }
848
+ }
849
+ },
733
850
  {
734
851
  name: "system_program",
735
852
  address: "11111111111111111111111111111111"
@@ -1058,6 +1175,31 @@ var veilix_devnet_default = {
1058
1175
  ]
1059
1176
  }
1060
1177
  },
1178
+ {
1179
+ name: "treasury",
1180
+ docs: [
1181
+ "Holds the SOL pool. Funded with its rent-exempt reserve here so that no withdrawal",
1182
+ "can fail for leaving it below that reserve."
1183
+ ],
1184
+ writable: true,
1185
+ pda: {
1186
+ seeds: [
1187
+ {
1188
+ kind: "const",
1189
+ value: [
1190
+ 116,
1191
+ 114,
1192
+ 101,
1193
+ 97,
1194
+ 115,
1195
+ 117,
1196
+ 114,
1197
+ 121
1198
+ ]
1199
+ }
1200
+ ]
1201
+ }
1202
+ },
1061
1203
  {
1062
1204
  name: "system_program",
1063
1205
  address: "11111111111111111111111111111111"
@@ -1488,6 +1630,336 @@ var veilix_devnet_default = {
1488
1630
  }
1489
1631
  ]
1490
1632
  },
1633
+ {
1634
+ name: "swap",
1635
+ docs: [
1636
+ "Private swap. Remaining accounts: the protocol fee wallets for the input asset (SOL",
1637
+ "accounts or their token accounts, in config order), then the DEX instruction's accounts."
1638
+ ],
1639
+ discriminator: [
1640
+ 248,
1641
+ 198,
1642
+ 158,
1643
+ 145,
1644
+ 225,
1645
+ 117,
1646
+ 135,
1647
+ 200
1648
+ ],
1649
+ accounts: [
1650
+ {
1651
+ name: "relayer",
1652
+ writable: true,
1653
+ signer: true
1654
+ },
1655
+ {
1656
+ name: "relayer_account",
1657
+ writable: true,
1658
+ pda: {
1659
+ seeds: [
1660
+ {
1661
+ kind: "const",
1662
+ value: [
1663
+ 114,
1664
+ 101,
1665
+ 108,
1666
+ 97,
1667
+ 121,
1668
+ 101,
1669
+ 114
1670
+ ]
1671
+ },
1672
+ {
1673
+ kind: "account",
1674
+ path: "relayer_account.owner",
1675
+ account: "RelayerAccount"
1676
+ }
1677
+ ]
1678
+ }
1679
+ },
1680
+ {
1681
+ name: "network_state",
1682
+ pda: {
1683
+ seeds: [
1684
+ {
1685
+ kind: "const",
1686
+ value: [
1687
+ 99,
1688
+ 111,
1689
+ 110,
1690
+ 102,
1691
+ 105,
1692
+ 103
1693
+ ]
1694
+ }
1695
+ ]
1696
+ }
1697
+ },
1698
+ {
1699
+ name: "swap_config",
1700
+ pda: {
1701
+ seeds: [
1702
+ {
1703
+ kind: "const",
1704
+ value: [
1705
+ 115,
1706
+ 119,
1707
+ 97,
1708
+ 112,
1709
+ 95,
1710
+ 99,
1711
+ 111,
1712
+ 110,
1713
+ 102,
1714
+ 105,
1715
+ 103
1716
+ ]
1717
+ }
1718
+ ]
1719
+ }
1720
+ },
1721
+ {
1722
+ name: "tree_in",
1723
+ docs: [
1724
+ "Tree of the asset being spent. The handler checks it is the PDA for its mint."
1725
+ ],
1726
+ writable: true
1727
+ },
1728
+ {
1729
+ name: "tree_out",
1730
+ docs: [
1731
+ "Tree that receives the swapped note."
1732
+ ],
1733
+ writable: true
1734
+ },
1735
+ {
1736
+ name: "treasury",
1737
+ writable: true,
1738
+ pda: {
1739
+ seeds: [
1740
+ {
1741
+ kind: "const",
1742
+ value: [
1743
+ 116,
1744
+ 114,
1745
+ 101,
1746
+ 97,
1747
+ 115,
1748
+ 117,
1749
+ 114,
1750
+ 121
1751
+ ]
1752
+ }
1753
+ ]
1754
+ }
1755
+ },
1756
+ {
1757
+ name: "escrow",
1758
+ docs: [
1759
+ "Signs the DEX call. Holds nothing between transactions."
1760
+ ],
1761
+ writable: true,
1762
+ pda: {
1763
+ seeds: [
1764
+ {
1765
+ kind: "const",
1766
+ value: [
1767
+ 115,
1768
+ 119,
1769
+ 97,
1770
+ 112,
1771
+ 95,
1772
+ 101,
1773
+ 115,
1774
+ 99,
1775
+ 114,
1776
+ 111,
1777
+ 119
1778
+ ]
1779
+ }
1780
+ ]
1781
+ }
1782
+ },
1783
+ {
1784
+ name: "treasury_ata_in",
1785
+ docs: [
1786
+ "Treasury ATA for `mint_in`. `None` when spending SOL."
1787
+ ],
1788
+ writable: true,
1789
+ optional: true
1790
+ },
1791
+ {
1792
+ name: "treasury_ata_out",
1793
+ docs: [
1794
+ "Treasury ATA for `mint_out`. `None` when receiving SOL."
1795
+ ],
1796
+ writable: true,
1797
+ optional: true
1798
+ },
1799
+ {
1800
+ name: "escrow_ata_in",
1801
+ docs: [
1802
+ "Escrow ATA for `mint_in` (wrapped SOL when spending SOL). Must exist: prepend an",
1803
+ "idempotent ATA create. A wrapped-SOL escrow account is closed at the end of the swap."
1804
+ ],
1805
+ writable: true
1806
+ },
1807
+ {
1808
+ name: "escrow_ata_out",
1809
+ docs: [
1810
+ "Escrow ATA for `mint_out` (wrapped SOL when receiving SOL). Must exist, as above."
1811
+ ],
1812
+ writable: true
1813
+ },
1814
+ {
1815
+ name: "relayer_ata",
1816
+ docs: [
1817
+ "Relayer ATA for `mint_in`, paid the relayer fee. `None` when spending SOL."
1818
+ ],
1819
+ writable: true,
1820
+ optional: true
1821
+ },
1822
+ {
1823
+ name: "nullifier0",
1824
+ writable: true,
1825
+ pda: {
1826
+ seeds: [
1827
+ {
1828
+ kind: "const",
1829
+ value: [
1830
+ 110,
1831
+ 117,
1832
+ 108,
1833
+ 108,
1834
+ 105,
1835
+ 102,
1836
+ 105,
1837
+ 101,
1838
+ 114
1839
+ ]
1840
+ },
1841
+ {
1842
+ kind: "arg",
1843
+ path: "proof.input_nullifiers [0]"
1844
+ }
1845
+ ]
1846
+ }
1847
+ },
1848
+ {
1849
+ name: "nullifier1",
1850
+ writable: true,
1851
+ pda: {
1852
+ seeds: [
1853
+ {
1854
+ kind: "const",
1855
+ value: [
1856
+ 110,
1857
+ 117,
1858
+ 108,
1859
+ 108,
1860
+ 105,
1861
+ 102,
1862
+ 105,
1863
+ 101,
1864
+ 114
1865
+ ]
1866
+ },
1867
+ {
1868
+ kind: "arg",
1869
+ path: "proof.input_nullifiers [1]"
1870
+ }
1871
+ ]
1872
+ }
1873
+ },
1874
+ {
1875
+ name: "mint_in",
1876
+ docs: [
1877
+ "Mint of the spent asset (the native mint when spending SOL)."
1878
+ ]
1879
+ },
1880
+ {
1881
+ name: "mint_out",
1882
+ docs: [
1883
+ "Mint of the received asset (the native mint when receiving SOL)."
1884
+ ]
1885
+ },
1886
+ {
1887
+ name: "token_program_in"
1888
+ },
1889
+ {
1890
+ name: "token_program_out"
1891
+ },
1892
+ {
1893
+ name: "dex_program"
1894
+ },
1895
+ {
1896
+ name: "system_program",
1897
+ address: "11111111111111111111111111111111"
1898
+ },
1899
+ {
1900
+ name: "event_authority",
1901
+ pda: {
1902
+ seeds: [
1903
+ {
1904
+ kind: "const",
1905
+ value: [
1906
+ 95,
1907
+ 95,
1908
+ 101,
1909
+ 118,
1910
+ 101,
1911
+ 110,
1912
+ 116,
1913
+ 95,
1914
+ 97,
1915
+ 117,
1916
+ 116,
1917
+ 104,
1918
+ 111,
1919
+ 114,
1920
+ 105,
1921
+ 116,
1922
+ 121
1923
+ ]
1924
+ }
1925
+ ]
1926
+ }
1927
+ },
1928
+ {
1929
+ name: "program"
1930
+ }
1931
+ ],
1932
+ args: [
1933
+ {
1934
+ name: "proof",
1935
+ type: {
1936
+ defined: {
1937
+ name: "TransactionProof"
1938
+ }
1939
+ }
1940
+ },
1941
+ {
1942
+ name: "params",
1943
+ type: {
1944
+ defined: {
1945
+ name: "SwapParams"
1946
+ }
1947
+ }
1948
+ },
1949
+ {
1950
+ name: "encrypted_output1",
1951
+ type: "bytes"
1952
+ },
1953
+ {
1954
+ name: "encrypted_output2",
1955
+ type: "bytes"
1956
+ },
1957
+ {
1958
+ name: "route_data",
1959
+ type: "bytes"
1960
+ }
1961
+ ]
1962
+ },
1491
1963
  {
1492
1964
  name: "token_deposit",
1493
1965
  discriminator: [
@@ -1714,14 +2186,46 @@ var veilix_devnet_default = {
1714
2186
  }
1715
2187
  },
1716
2188
  {
1717
- name: "mint"
1718
- },
1719
- {
1720
- name: "token_program"
1721
- },
1722
- {
1723
- name: "system_program",
1724
- address: "11111111111111111111111111111111"
2189
+ name: "mint"
2190
+ },
2191
+ {
2192
+ name: "token_program"
2193
+ },
2194
+ {
2195
+ name: "system_program",
2196
+ address: "11111111111111111111111111111111"
2197
+ },
2198
+ {
2199
+ name: "event_authority",
2200
+ pda: {
2201
+ seeds: [
2202
+ {
2203
+ kind: "const",
2204
+ value: [
2205
+ 95,
2206
+ 95,
2207
+ 101,
2208
+ 118,
2209
+ 101,
2210
+ 110,
2211
+ 116,
2212
+ 95,
2213
+ 97,
2214
+ 117,
2215
+ 116,
2216
+ 104,
2217
+ 111,
2218
+ 114,
2219
+ 105,
2220
+ 116,
2221
+ 121
2222
+ ]
2223
+ }
2224
+ ]
2225
+ }
2226
+ },
2227
+ {
2228
+ name: "program"
1725
2229
  }
1726
2230
  ],
1727
2231
  args: [
@@ -2088,6 +2592,38 @@ var veilix_devnet_default = {
2088
2592
  {
2089
2593
  name: "system_program",
2090
2594
  address: "11111111111111111111111111111111"
2595
+ },
2596
+ {
2597
+ name: "event_authority",
2598
+ pda: {
2599
+ seeds: [
2600
+ {
2601
+ kind: "const",
2602
+ value: [
2603
+ 95,
2604
+ 95,
2605
+ 101,
2606
+ 118,
2607
+ 101,
2608
+ 110,
2609
+ 116,
2610
+ 95,
2611
+ 97,
2612
+ 117,
2613
+ 116,
2614
+ 104,
2615
+ 111,
2616
+ 114,
2617
+ 105,
2618
+ 116,
2619
+ 121
2620
+ ]
2621
+ }
2622
+ ]
2623
+ }
2624
+ },
2625
+ {
2626
+ name: "program"
2091
2627
  }
2092
2628
  ],
2093
2629
  args: [
@@ -2536,6 +3072,83 @@ var veilix_devnet_default = {
2536
3072
  }
2537
3073
  ]
2538
3074
  },
3075
+ {
3076
+ name: "update_swap_config",
3077
+ docs: [
3078
+ "Replaces the list of DEX programs the swap escrow may call. Config authority only."
3079
+ ],
3080
+ discriminator: [
3081
+ 123,
3082
+ 172,
3083
+ 158,
3084
+ 60,
3085
+ 104,
3086
+ 133,
3087
+ 39,
3088
+ 13
3089
+ ],
3090
+ accounts: [
3091
+ {
3092
+ name: "authority",
3093
+ writable: true,
3094
+ signer: true
3095
+ },
3096
+ {
3097
+ name: "network_state",
3098
+ pda: {
3099
+ seeds: [
3100
+ {
3101
+ kind: "const",
3102
+ value: [
3103
+ 99,
3104
+ 111,
3105
+ 110,
3106
+ 102,
3107
+ 105,
3108
+ 103
3109
+ ]
3110
+ }
3111
+ ]
3112
+ }
3113
+ },
3114
+ {
3115
+ name: "swap_config",
3116
+ writable: true,
3117
+ pda: {
3118
+ seeds: [
3119
+ {
3120
+ kind: "const",
3121
+ value: [
3122
+ 115,
3123
+ 119,
3124
+ 97,
3125
+ 112,
3126
+ 95,
3127
+ 99,
3128
+ 111,
3129
+ 110,
3130
+ 102,
3131
+ 105,
3132
+ 103
3133
+ ]
3134
+ }
3135
+ ]
3136
+ }
3137
+ },
3138
+ {
3139
+ name: "system_program",
3140
+ address: "11111111111111111111111111111111"
3141
+ }
3142
+ ],
3143
+ args: [
3144
+ {
3145
+ name: "allowed_programs",
3146
+ type: {
3147
+ vec: "pubkey"
3148
+ }
3149
+ }
3150
+ ]
3151
+ },
2539
3152
  {
2540
3153
  name: "withdraw",
2541
3154
  discriminator: [
@@ -2694,6 +3307,38 @@ var veilix_devnet_default = {
2694
3307
  {
2695
3308
  name: "system_program",
2696
3309
  address: "11111111111111111111111111111111"
3310
+ },
3311
+ {
3312
+ name: "event_authority",
3313
+ pda: {
3314
+ seeds: [
3315
+ {
3316
+ kind: "const",
3317
+ value: [
3318
+ 95,
3319
+ 95,
3320
+ 101,
3321
+ 118,
3322
+ 101,
3323
+ 110,
3324
+ 116,
3325
+ 95,
3326
+ 97,
3327
+ 117,
3328
+ 116,
3329
+ 104,
3330
+ 111,
3331
+ 114,
3332
+ 105,
3333
+ 116,
3334
+ 121
3335
+ ]
3336
+ }
3337
+ ]
3338
+ }
3339
+ },
3340
+ {
3341
+ name: "program"
2697
3342
  }
2698
3343
  ],
2699
3344
  args: [
@@ -2803,6 +3448,19 @@ var veilix_devnet_default = {
2803
3448
  20
2804
3449
  ]
2805
3450
  },
3451
+ {
3452
+ name: "SwapConfig",
3453
+ discriminator: [
3454
+ 212,
3455
+ 45,
3456
+ 70,
3457
+ 222,
3458
+ 245,
3459
+ 122,
3460
+ 125,
3461
+ 166
3462
+ ]
3463
+ },
2806
3464
  {
2807
3465
  name: "TreeAccount",
2808
3466
  discriminator: [
@@ -2844,6 +3502,19 @@ var veilix_devnet_default = {
2844
3502
  159
2845
3503
  ]
2846
3504
  },
3505
+ {
3506
+ name: "PrivateSwapEvent",
3507
+ discriminator: [
3508
+ 150,
3509
+ 165,
3510
+ 138,
3511
+ 189,
3512
+ 123,
3513
+ 86,
3514
+ 117,
3515
+ 39
3516
+ ]
3517
+ },
2847
3518
  {
2848
3519
  name: "RelayerCancelled",
2849
3520
  discriminator: [
@@ -3106,6 +3777,56 @@ var veilix_devnet_default = {
3106
3777
  code: 6033,
3107
3778
  name: "FeeRepaymentAccounts",
3108
3779
  msg: "Fee repayment accounts do not match earned fees"
3780
+ },
3781
+ {
3782
+ code: 6034,
3783
+ name: "DexProgramNotAllowed",
3784
+ msg: "DEX program is not on the swap allowlist"
3785
+ },
3786
+ {
3787
+ code: 6035,
3788
+ name: "TooManyDexPrograms",
3789
+ msg: "Too many allowlisted DEX programs"
3790
+ },
3791
+ {
3792
+ code: 6036,
3793
+ name: "SlippageExceeded",
3794
+ msg: "Swap output is below the minimum amount"
3795
+ },
3796
+ {
3797
+ code: 6037,
3798
+ name: "SwapInputMismatch",
3799
+ msg: "DEX did not use exactly the escrowed swap input"
3800
+ },
3801
+ {
3802
+ code: 6038,
3803
+ name: "InvalidSwapAccounts",
3804
+ msg: "Swap accounts do not match the trees"
3805
+ },
3806
+ {
3807
+ code: 6039,
3808
+ name: "EscrowTampered",
3809
+ msg: "Swap escrow was modified by the DEX"
3810
+ },
3811
+ {
3812
+ code: 6040,
3813
+ name: "InvalidNoteKey",
3814
+ msg: "Note public key or blinding is not a valid field element"
3815
+ },
3816
+ {
3817
+ code: 6041,
3818
+ name: "NotUpgradeAuthority",
3819
+ msg: "Only the program upgrade authority can initialize the network"
3820
+ },
3821
+ {
3822
+ code: 6042,
3823
+ name: "InvalidFeeSplit",
3824
+ msg: "Fee wallets must be distinct, non-default and split at most the allowed total"
3825
+ },
3826
+ {
3827
+ code: 6043,
3828
+ name: "UnsupportedMintExtension",
3829
+ msg: "Token mint has an extension the pool does not support"
3109
3830
  }
3110
3831
  ],
3111
3832
  types: [
@@ -3233,8 +3954,104 @@ var veilix_devnet_default = {
3233
3954
  type: "pubkey"
3234
3955
  },
3235
3956
  {
3236
- name: "index",
3237
- type: "u64"
3957
+ name: "index",
3958
+ type: "u64"
3959
+ },
3960
+ {
3961
+ name: "commitment",
3962
+ type: {
3963
+ array: [
3964
+ "u8",
3965
+ 32
3966
+ ]
3967
+ }
3968
+ },
3969
+ {
3970
+ name: "encrypted_output",
3971
+ type: "bytes"
3972
+ }
3973
+ ]
3974
+ }
3975
+ },
3976
+ {
3977
+ name: "Notes",
3978
+ type: {
3979
+ kind: "struct",
3980
+ fields: [
3981
+ {
3982
+ name: "entries",
3983
+ type: {
3984
+ vec: "string"
3985
+ }
3986
+ }
3987
+ ]
3988
+ }
3989
+ },
3990
+ {
3991
+ name: "NotesV2",
3992
+ type: {
3993
+ kind: "struct",
3994
+ fields: [
3995
+ {
3996
+ name: "entries",
3997
+ type: {
3998
+ vec: "bytes"
3999
+ }
4000
+ }
4001
+ ]
4002
+ }
4003
+ },
4004
+ {
4005
+ name: "Nullifier",
4006
+ type: {
4007
+ kind: "struct"
4008
+ }
4009
+ },
4010
+ {
4011
+ name: "PrivateSwapEvent",
4012
+ docs: [
4013
+ "Emitted once per swap. The asset-B note is `commitment` at `index` in the `mint_out` tree."
4014
+ ],
4015
+ type: {
4016
+ kind: "struct",
4017
+ fields: [
4018
+ {
4019
+ name: "mint_in",
4020
+ type: "pubkey"
4021
+ },
4022
+ {
4023
+ name: "mint_out",
4024
+ type: "pubkey"
4025
+ },
4026
+ {
4027
+ name: "amount_in",
4028
+ type: "u64"
4029
+ },
4030
+ {
4031
+ name: "fee",
4032
+ type: "u64"
4033
+ },
4034
+ {
4035
+ name: "amount_out",
4036
+ type: "u64"
4037
+ },
4038
+ {
4039
+ name: "input_nullifiers",
4040
+ type: {
4041
+ array: [
4042
+ {
4043
+ array: [
4044
+ "u8",
4045
+ 32
4046
+ ]
4047
+ },
4048
+ 2
4049
+ ]
4050
+ }
4051
+ },
4052
+ {
4053
+ name: "relayer",
4054
+ type: "pubkey"
3238
4055
  },
3239
4056
  {
3240
4057
  name: "commitment",
@@ -3246,46 +4063,12 @@ var veilix_devnet_default = {
3246
4063
  }
3247
4064
  },
3248
4065
  {
3249
- name: "encrypted_output",
3250
- type: "bytes"
3251
- }
3252
- ]
3253
- }
3254
- },
3255
- {
3256
- name: "Notes",
3257
- type: {
3258
- kind: "struct",
3259
- fields: [
3260
- {
3261
- name: "entries",
3262
- type: {
3263
- vec: "string"
3264
- }
3265
- }
3266
- ]
3267
- }
3268
- },
3269
- {
3270
- name: "NotesV2",
3271
- type: {
3272
- kind: "struct",
3273
- fields: [
3274
- {
3275
- name: "entries",
3276
- type: {
3277
- vec: "bytes"
3278
- }
4066
+ name: "index",
4067
+ type: "u64"
3279
4068
  }
3280
4069
  ]
3281
4070
  }
3282
4071
  },
3283
- {
3284
- name: "Nullifier",
3285
- type: {
3286
- kind: "struct"
3287
- }
3288
- },
3289
4072
  {
3290
4073
  name: "RelayerAccount",
3291
4074
  docs: [
@@ -3480,6 +4263,86 @@ var veilix_devnet_default = {
3480
4263
  ]
3481
4264
  }
3482
4265
  },
4266
+ {
4267
+ name: "SwapConfig",
4268
+ docs: [
4269
+ 'Programs the swap escrow is allowed to call. PDA seeds: `["swap_config"]`.'
4270
+ ],
4271
+ type: {
4272
+ kind: "struct",
4273
+ fields: [
4274
+ {
4275
+ name: "allowed_programs",
4276
+ type: {
4277
+ vec: "pubkey"
4278
+ }
4279
+ }
4280
+ ]
4281
+ }
4282
+ },
4283
+ {
4284
+ name: "SwapParams",
4285
+ docs: [
4286
+ "Swap parameters. All of them are bound into the proof's `extDataHash`."
4287
+ ],
4288
+ type: {
4289
+ kind: "struct",
4290
+ fields: [
4291
+ {
4292
+ name: "amount_in",
4293
+ docs: [
4294
+ "Asset-A amount spent from the pool, fee included."
4295
+ ],
4296
+ type: "u64"
4297
+ },
4298
+ {
4299
+ name: "fee",
4300
+ docs: [
4301
+ "Asset-A fee: protocol wallets get their split of `amount_in`, the relayer the rest."
4302
+ ],
4303
+ type: "u64"
4304
+ },
4305
+ {
4306
+ name: "min_amount_out",
4307
+ docs: [
4308
+ "Minimum asset-B amount that must reach the treasury."
4309
+ ],
4310
+ type: "u64"
4311
+ },
4312
+ {
4313
+ name: "out_pubkey",
4314
+ docs: [
4315
+ "One-time shielded public key of the asset-B note (32-byte big-endian field element)."
4316
+ ],
4317
+ type: {
4318
+ array: [
4319
+ "u8",
4320
+ 32
4321
+ ]
4322
+ }
4323
+ },
4324
+ {
4325
+ name: "out_blinding",
4326
+ docs: [
4327
+ "Blinding of the asset-B note (32-byte big-endian field element)."
4328
+ ],
4329
+ type: {
4330
+ array: [
4331
+ "u8",
4332
+ 32
4333
+ ]
4334
+ }
4335
+ },
4336
+ {
4337
+ name: "encrypted_note",
4338
+ docs: [
4339
+ "Optional encrypted recovery data for the asset-B note."
4340
+ ],
4341
+ type: "bytes"
4342
+ }
4343
+ ]
4344
+ }
4345
+ },
3483
4346
  {
3484
4347
  name: "TransactionProof",
3485
4348
  docs: [
@@ -7378,7 +8241,7 @@ var MAINNET_TOKEN_MINTS = {
7378
8241
  USDC: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
7379
8242
  };
7380
8243
  var DEVNET_TOKEN_MINTS = {
7381
- Veilix: "GAFN64LvtCBoc5BHncVn3JEJGpq42rUzQjPmvMK2UhZH",
8244
+ Veilix: "Gmo636w21RBZX9ySVtPYcuYP6f1E5bdW5eBYhvK1bc8J",
7382
8245
  Bitcoin: "",
7383
8246
  Ethereum: "",
7384
8247
  USDC: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU"
@@ -7428,7 +8291,7 @@ function getDepositQueueForNetwork(network) {
7428
8291
  // package.json
7429
8292
  var package_default = {
7430
8293
  name: "veilix-sdk",
7431
- version: "0.2.3"};
8294
+ version: "0.3.1"};
7432
8295
 
7433
8296
  // src/circuits/constants.ts
7434
8297
  var PACKAGE_NAME = package_default.name;
@@ -7603,10 +8466,19 @@ async function createRuntimeConfig(options) {
7603
8466
  };
7604
8467
  }
7605
8468
  function pushRuntimeContext(config) {
8469
+ const active = runtimeContextStack.find((other) => other.programId !== config.programId);
8470
+ if (active) {
8471
+ throw new Error(
8472
+ `veilix-sdk: another SDK instance is running on program ${active.programId}; instances on different networks must run one at a time`
8473
+ );
8474
+ }
7606
8475
  runtimeContextStack.push(config);
7607
8476
  }
7608
- function popRuntimeContext() {
7609
- runtimeContextStack.pop();
8477
+ function popRuntimeContext(config) {
8478
+ const index = runtimeContextStack.lastIndexOf(config);
8479
+ if (index !== -1) {
8480
+ runtimeContextStack.splice(index, 1);
8481
+ }
7610
8482
  }
7611
8483
  function getConfig() {
7612
8484
  const active = runtimeContextStack.at(-1);
@@ -7671,10 +8543,10 @@ var DEPOSIT_COMPUTE_UNIT_LIMIT = 35e4;
7671
8543
  function bytesToHex(bytes) {
7672
8544
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
7673
8545
  }
7674
- function hexToBytes(hex) {
7675
- const clean = hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
8546
+ function hexToBytes(hex2) {
8547
+ const clean = hex2.startsWith("0x") || hex2.startsWith("0X") ? hex2.slice(2) : hex2;
7676
8548
  if (clean.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(clean)) {
7677
- throw new Error(`veilix-sdk: invalid hex string "${hex}"`);
8549
+ throw new Error(`veilix-sdk: invalid hex string "${hex2}"`);
7678
8550
  }
7679
8551
  const out = new Uint8Array(clean.length / 2);
7680
8552
  for (let i = 0; i < out.length; i++) {
@@ -7683,15 +8555,15 @@ function hexToBytes(hex) {
7683
8555
  return out;
7684
8556
  }
7685
8557
  function bigintToBytes32(value) {
7686
- const hex = BigInt(value).toString(16).padStart(64, "0");
7687
- if (hex.length > 64) {
8558
+ const hex2 = BigInt(value).toString(16).padStart(64, "0");
8559
+ if (hex2.length > 64) {
7688
8560
  throw new Error("veilix-sdk: value does not fit in 32 bytes");
7689
8561
  }
7690
- return hexToBytes(hex);
8562
+ return hexToBytes(hex2);
7691
8563
  }
7692
8564
  function bytesToBigint(bytes) {
7693
- const hex = bytesToHex(bytes);
7694
- return hex ? BigInt(`0x${hex}`) : 0n;
8565
+ const hex2 = bytesToHex(bytes);
8566
+ return hex2 ? BigInt(`0x${hex2}`) : 0n;
7695
8567
  }
7696
8568
  function toHex32(value) {
7697
8569
  return `0x${BigInt(value).toString(16).padStart(64, "0")}`;
@@ -7809,6 +8681,7 @@ var Utxo = class _Utxo {
7809
8681
  // src/core/note.ts
7810
8682
  var NOTE_PREFIX = "vx2";
7811
8683
  var ENCRYPTED_OUTPUT_VERSION = 1;
8684
+ var ENCRYPTED_SWAP_OUTPUT_VERSION = 2;
7812
8685
  var ENCRYPTED_OUTPUT_PLAINTEXT_BYTES = 1 + 8 + 32 + 32;
7813
8686
  var SECRETBOX_NONCE_BYTES = nacl__default.default.secretbox.nonceLength;
7814
8687
  function encodeNote(utxo) {
@@ -7841,14 +8714,14 @@ function decodeNote(note) {
7841
8714
  throw new Error("veilix-sdk: invalid note format");
7842
8715
  }
7843
8716
  const [, amountHex, privKeyHex, blindingHex, mint] = parts;
7844
- const hex = /^[0-9a-f]+$/i;
7845
- if (!hex.test(amountHex) || !hex.test(privKeyHex) || !hex.test(blindingHex)) {
8717
+ const hex2 = /^[0-9a-f]+$/i;
8718
+ if (!hex2.test(amountHex) || !hex2.test(privKeyHex) || !hex2.test(blindingHex)) {
7846
8719
  throw new Error("veilix-sdk: invalid note format");
7847
8720
  }
7848
- let mintKey = null;
8721
+ let mintKey2 = null;
7849
8722
  if (mint) {
7850
8723
  try {
7851
- mintKey = new web3_js.PublicKey(mint);
8724
+ mintKey2 = new web3_js.PublicKey(mint);
7852
8725
  } catch {
7853
8726
  throw new Error("veilix-sdk: invalid note mint");
7854
8727
  }
@@ -7857,7 +8730,7 @@ function decodeNote(note) {
7857
8730
  amount: BigInt(`0x${amountHex}`),
7858
8731
  keypair: VeilixKeypair.fromPrivateKey(BigInt(`0x${privKeyHex}`)),
7859
8732
  blinding: BigInt(`0x${blindingHex}`),
7860
- mint: mintKey
8733
+ mint: mintKey2
7861
8734
  });
7862
8735
  }
7863
8736
  function describeUtxo(utxo) {
@@ -7875,7 +8748,7 @@ function describeUtxo(utxo) {
7875
8748
  function parseSecretNote(note) {
7876
8749
  return describeUtxo(decodeNote(note));
7877
8750
  }
7878
- function encryptNoteOutput(key, utxo) {
8751
+ function encryptNoteOutput(key2, utxo) {
7879
8752
  const amount = new Uint8Array(8);
7880
8753
  new DataView(amount.buffer).setBigUint64(0, utxo.amount, true);
7881
8754
  const plaintext = concatBytes([
@@ -7885,21 +8758,38 @@ function encryptNoteOutput(key, utxo) {
7885
8758
  bigintToBytes32(utxo.blinding)
7886
8759
  ]);
7887
8760
  const nonce = nacl__default.default.randomBytes(SECRETBOX_NONCE_BYTES);
7888
- return concatBytes([nonce, nacl__default.default.secretbox(plaintext, nonce, key)]);
8761
+ return concatBytes([nonce, nacl__default.default.secretbox(plaintext, nonce, key2)]);
8762
+ }
8763
+ function encryptSwapNoteOutput(key2, keypair, blinding) {
8764
+ const plaintext = concatBytes([
8765
+ Uint8Array.of(ENCRYPTED_SWAP_OUTPUT_VERSION),
8766
+ new Uint8Array(8),
8767
+ bigintToBytes32(keypair.privKey),
8768
+ bigintToBytes32(blinding)
8769
+ ]);
8770
+ const nonce = nacl__default.default.randomBytes(SECRETBOX_NONCE_BYTES);
8771
+ return concatBytes([nonce, nacl__default.default.secretbox(plaintext, nonce, key2)]);
7889
8772
  }
7890
- function decryptNoteOutput(key, encryptedOutput, mint, index) {
8773
+ function decryptNoteOutput(key2, encryptedOutput, mint, index, onchainAmount = null) {
7891
8774
  if (encryptedOutput.length !== SECRETBOX_NONCE_BYTES + nacl__default.default.secretbox.overheadLength + ENCRYPTED_OUTPUT_PLAINTEXT_BYTES) {
7892
8775
  return null;
7893
8776
  }
7894
8777
  const opened = nacl__default.default.secretbox.open(
7895
8778
  encryptedOutput.subarray(SECRETBOX_NONCE_BYTES),
7896
8779
  encryptedOutput.subarray(0, SECRETBOX_NONCE_BYTES),
7897
- key
8780
+ key2
7898
8781
  );
7899
- if (!opened || opened[0] !== ENCRYPTED_OUTPUT_VERSION) {
8782
+ if (!opened) {
8783
+ return null;
8784
+ }
8785
+ let amount;
8786
+ if (opened[0] === ENCRYPTED_OUTPUT_VERSION) {
8787
+ amount = new DataView(opened.buffer, opened.byteOffset + 1, 8).getBigUint64(0, true);
8788
+ } else if (opened[0] === ENCRYPTED_SWAP_OUTPUT_VERSION && onchainAmount !== null) {
8789
+ amount = onchainAmount;
8790
+ } else {
7900
8791
  return null;
7901
8792
  }
7902
- const amount = new DataView(opened.buffer, opened.byteOffset + 1, 8).getBigUint64(0, true);
7903
8793
  return new Utxo({
7904
8794
  amount,
7905
8795
  keypair: VeilixKeypair.fromPrivateKey(bytesToBigint(opened.subarray(9, 41))),
@@ -16380,6 +17270,7 @@ async function proveTransaction({
16380
17270
  inputs = [],
16381
17271
  outputs = [],
16382
17272
  ext,
17273
+ extDataHashOverride,
16383
17274
  circuit
16384
17275
  }) {
16385
17276
  for (const utxo of [...inputs, ...outputs]) {
@@ -16429,7 +17320,7 @@ async function proveTransaction({
16429
17320
  const input = {
16430
17321
  root: proofRoot.toString(),
16431
17322
  publicAmount: publicAmount.toString(),
16432
- extDataHash: (await extDataHash(ext)).toString(),
17323
+ extDataHash: (extDataHashOverride ?? await extDataHash(ext)).toString(),
16433
17324
  mint: mintToField(ext.mint).toString(),
16434
17325
  inputNullifier: inputNullifiers.map(String),
16435
17326
  outputCommitment: outputCommitments.map(String),
@@ -16570,8 +17461,8 @@ function generateDepositParams(amount, mint = null) {
16570
17461
  if (value <= 0n) {
16571
17462
  throw new Error("veilix-sdk: deposit amount must be positive");
16572
17463
  }
16573
- const mintKey = mint && mint !== WRAPPED_SOL_MINT ? new web3_js.PublicKey(mint) : null;
16574
- const note = encodeNote(new Utxo({ amount: value, mint: mintKey }));
17464
+ const mintKey2 = mint && mint !== WRAPPED_SOL_MINT ? new web3_js.PublicKey(mint) : null;
17465
+ const note = encodeNote(new Utxo({ amount: value, mint: mintKey2 }));
16575
17466
  return { note, params: parseSecretNote(note) };
16576
17467
  }
16577
17468
  function to32ByteBuffer(value) {
@@ -16605,8 +17496,8 @@ function toPublicKey(value) {
16605
17496
  }
16606
17497
  function normalizeTreeMint(mint) {
16607
17498
  if (!mint) return null;
16608
- const key = toPublicKey(mint);
16609
- return key.equals(splToken.NATIVE_MINT) || key.equals(web3_js.PublicKey.default) ? null : key;
17499
+ const key2 = toPublicKey(mint);
17500
+ return key2.equals(splToken.NATIVE_MINT) || key2.equals(web3_js.PublicKey.default) ? null : key2;
16610
17501
  }
16611
17502
  function getTreePDA(mint) {
16612
17503
  const treeMint = normalizeTreeMint(mint);
@@ -16778,9 +17669,11 @@ async function buildDepositTx({
16778
17669
  onChainBackup = false,
16779
17670
  computeUnitPrice = 5e3,
16780
17671
  computeUnitLimit = DEPOSIT_COMPUTE_UNIT_LIMIT,
16781
- circuitArtifacts
17672
+ circuitArtifacts,
17673
+ encryptKey
16782
17674
  }) {
16783
17675
  const { connection } = getConfig();
17676
+ const sealKey = onChainBackup ? encryptKey ?? requireEncryptKey() : null;
16784
17677
  const sender = toPublicKey(senderPublicKey);
16785
17678
  const utxo = decodeNote(note);
16786
17679
  const mint = utxo.mint;
@@ -16793,7 +17686,7 @@ async function buildDepositTx({
16793
17686
  `veilix-sdk: deposit amount ${utxo.amount} exceeds the tree limit of ${tree.maxDepositAmount}`
16794
17687
  );
16795
17688
  }
16796
- const encryptedOutput1 = onChainBackup ? encryptNoteOutput(requireEncryptKey(), utxo) : new Uint8Array();
17689
+ const encryptedOutput1 = sealKey ? encryptNoteOutput(sealKey, utxo) : new Uint8Array();
16797
17690
  const encryptedOutput2 = new Uint8Array();
16798
17691
  const proved = await withCircuitArtifacts(
16799
17692
  circuitArtifacts,
@@ -16848,17 +17741,16 @@ async function buildInitNotesInstructionIfNeeded(sender) {
16848
17741
  if (await fetchNotesAccount(sender)) return null;
16849
17742
  return program.methods.initNotes().accountsPartial({ user: sender }).instruction();
16850
17743
  }
16851
- async function resolveEncryptKey() {
16852
- const config = getConfig();
17744
+ async function resolveEncryptKey(config) {
16853
17745
  if (!config.encryptKey) {
16854
17746
  config.encryptKey = await getEncryptionKey(config.wallet);
16855
17747
  }
16856
17748
  return config.encryptKey;
16857
17749
  }
16858
- async function buildBackupNotesInstruction(sender, notes) {
16859
- const { program } = getConfig();
16860
- const key = await resolveEncryptKey();
16861
- return program.methods.backupNotes(notes.map((note) => encryptData(key, note))).accountsPartial({ user: sender }).instruction();
17750
+ async function buildBackupNotesInstruction(sender, notes, config = getConfig()) {
17751
+ const { program } = config;
17752
+ const key2 = await resolveEncryptKey(config);
17753
+ return program.methods.backupNotes(notes.map((note) => encryptData(key2, note))).accountsPartial({ user: sender }).instruction();
16862
17754
  }
16863
17755
  async function isExtendBackupPdaNeeded(walletPubkey, newNotesLength) {
16864
17756
  const account = await fetchNotesAccount(walletPubkey);
@@ -16870,7 +17762,8 @@ function buildRequestHeapIx() {
16870
17762
  return web3_js.ComputeBudgetProgram.requestHeapFrame({ bytes: 32 * 1024 });
16871
17763
  }
16872
17764
  async function buildBackupNotesTx(senderPublicKey, notes) {
16873
- const { connection } = getConfig();
17765
+ const config = getConfig();
17766
+ const { connection } = config;
16874
17767
  const sender = toPublicKey(senderPublicKey);
16875
17768
  const tx = new web3_js.Transaction();
16876
17769
  const initIx = await buildInitNotesInstructionIfNeeded(sender);
@@ -16879,7 +17772,7 @@ async function buildBackupNotesTx(senderPublicKey, notes) {
16879
17772
  } else if (await isExtendBackupPdaNeeded(sender, notes.length)) {
16880
17773
  tx.add(buildRequestHeapIx());
16881
17774
  }
16882
- tx.add(await buildBackupNotesInstruction(sender, notes));
17775
+ tx.add(await buildBackupNotesInstruction(sender, notes, config));
16883
17776
  tx.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
16884
17777
  tx.feePayer = sender;
16885
17778
  return tx;
@@ -16963,16 +17856,16 @@ async function getEncryptionKey(wallet) {
16963
17856
  }
16964
17857
  return nacl__default.default.hash(signature).slice(0, 32);
16965
17858
  }
16966
- function encryptData(key, plaintext) {
17859
+ function encryptData(key2, plaintext) {
16967
17860
  const nonce = nacl__default.default.randomBytes(24);
16968
- const box = nacl__default.default.secretbox(new TextEncoder().encode(plaintext), nonce, key);
17861
+ const box = nacl__default.default.secretbox(new TextEncoder().encode(plaintext), nonce, key2);
16969
17862
  const combined = new Uint8Array(nonce.length + box.length);
16970
17863
  combined.set(nonce);
16971
17864
  combined.set(box, nonce.length);
16972
17865
  return buffer.Buffer.from(combined);
16973
17866
  }
16974
- function decryptData(key, combined) {
16975
- const decrypted = nacl__default.default.secretbox.open(combined.slice(24), combined.slice(0, 24), key);
17867
+ function decryptData(key2, combined) {
17868
+ const decrypted = nacl__default.default.secretbox.open(combined.slice(24), combined.slice(0, 24), key2);
16976
17869
  if (!decrypted) throw new Error("Decryption failed");
16977
17870
  return new TextDecoder().decode(decrypted);
16978
17871
  }
@@ -17010,8 +17903,8 @@ var COMMITMENTS_PAGE_LIMIT = 8e3;
17010
17903
  var VALIDATE_NULLIFIERS_BATCH = 64;
17011
17904
  async function indexerGet(path, params) {
17012
17905
  const query = new URLSearchParams();
17013
- for (const [key, value] of Object.entries(params)) {
17014
- if (value !== void 0 && value !== "") query.set(key, value);
17906
+ for (const [key2, value] of Object.entries(params)) {
17907
+ if (value !== void 0 && value !== "") query.set(key2, value);
17015
17908
  }
17016
17909
  const qs = query.toString();
17017
17910
  return httpFetch(`${getIndexerUrl()}${path}${qs ? `?${qs}` : ""}`, {
@@ -17226,7 +18119,7 @@ async function scanOwnedNotes({
17226
18119
  mints,
17227
18120
  includeSpent = false
17228
18121
  } = {}) {
17229
- const key = requireEncryptKey();
18122
+ const key2 = requireEncryptKey();
17230
18123
  const explicit = mints !== void 0;
17231
18124
  const tokenMints = getTokenMintsForNetwork(getConfig().network);
17232
18125
  const targets = mints ?? [null, tokenMints.Veilix, tokenMints.Bitcoin, tokenMints.Ethereum, tokenMints.USDC].filter(
@@ -17244,7 +18137,13 @@ async function scanOwnedNotes({
17244
18137
  }
17245
18138
  for (const leaf of leaves) {
17246
18139
  if (!leaf.encryptedOutput || leaf.encryptedOutput.length <= 2) continue;
17247
- const utxo = decryptNoteOutput(key, hexToBytes(leaf.encryptedOutput), treeMint, leaf.index);
18140
+ const utxo = decryptNoteOutput(
18141
+ key2,
18142
+ hexToBytes(leaf.encryptedOutput),
18143
+ treeMint,
18144
+ leaf.index,
18145
+ leaf.amountRaw ? BigInt(leaf.amountRaw) : null
18146
+ );
17248
18147
  if (!utxo || utxo.amount === 0n) continue;
17249
18148
  if (toHex32(utxo.commitment()) !== toHex32(BigInt(leaf.commitment))) continue;
17250
18149
  found.push({ utxo, note: encodeNote(utxo), signature: null });
@@ -17524,6 +18423,364 @@ async function getQuote(params) {
17524
18423
  }
17525
18424
  return data;
17526
18425
  }
18426
+ var SWAP_DOMAIN = new TextEncoder().encode("veilix:swap:v1");
18427
+ async function swapExtDataHash(ext) {
18428
+ const hash = await sha256(
18429
+ concatBytes([
18430
+ SWAP_DOMAIN,
18431
+ (ext.mintIn ?? web3_js.PublicKey.default).toBytes(),
18432
+ (ext.mintOut ?? web3_js.PublicKey.default).toBytes(),
18433
+ ext.relayer.toBytes(),
18434
+ u64le(ext.amountIn),
18435
+ u64le(ext.fee),
18436
+ u64le(ext.minAmountOut),
18437
+ bigintToBytes32(ext.outPubkey),
18438
+ bigintToBytes32(ext.outBlinding),
18439
+ u32le(ext.encryptedOutput1.length),
18440
+ ext.encryptedOutput1,
18441
+ u32le(ext.encryptedOutput2.length),
18442
+ ext.encryptedOutput2,
18443
+ u32le(ext.encryptedNote.length),
18444
+ ext.encryptedNote
18445
+ ])
18446
+ );
18447
+ hash[0] = 0;
18448
+ return bytesToBigint(hash);
18449
+ }
18450
+ var CPMM_PROGRAM_IDS = {
18451
+ devnet: "DRaycpLY18LhpbydsBWbVJtxpNv9oXPgjRSfpF2bWpYb",
18452
+ mainnet: "CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"
18453
+ };
18454
+ var FEE_RATE_DENOMINATOR = 1000000n;
18455
+ var SWAP_DISABLED_BIT = 2;
18456
+ var key = (data, offset) => new web3_js.PublicKey(data.subarray(offset, offset + 32));
18457
+ var u64 = (data, offset) => new DataView(data.buffer, data.byteOffset + offset, 8).getBigUint64(0, true);
18458
+ var ceilDiv = (a, b) => (a + b - 1n) / b;
18459
+ var feeOf = (amount, rate) => ceilDiv(amount * rate, FEE_RATE_DENOMINATOR);
18460
+ async function quoteCpmm(connection, network, poolAddress, treeMintIn, treeMintOut, amountIn) {
18461
+ const programId = new web3_js.PublicKey(CPMM_PROGRAM_IDS[network]);
18462
+ const poolInfo = await connection.getAccountInfo(poolAddress, "confirmed");
18463
+ if (!poolInfo || !poolInfo.owner.equals(programId) || poolInfo.data.length < 381) {
18464
+ throw new Error("veilix-sdk: swap pool is not a Raydium CPMM pool");
18465
+ }
18466
+ const data = poolInfo.data;
18467
+ const pool = {
18468
+ ammConfig: key(data, 8),
18469
+ vault0: key(data, 72),
18470
+ vault1: key(data, 104),
18471
+ mint0: key(data, 168),
18472
+ mint1: key(data, 200),
18473
+ status: data[329],
18474
+ protocolFees: [u64(data, 341), u64(data, 349)],
18475
+ fundFees: [u64(data, 357), u64(data, 365)],
18476
+ creatorFeeOn: data.length >= 413 ? data[389] : 0,
18477
+ enableCreatorFee: data.length >= 413 ? data[390] === 1 : false,
18478
+ creatorFees: data.length >= 413 ? [u64(data, 397), u64(data, 405)] : [0n, 0n]
18479
+ };
18480
+ if (pool.status >> SWAP_DISABLED_BIT & 1) {
18481
+ throw new Error("veilix-sdk: swaps are disabled on this pool");
18482
+ }
18483
+ const mintIn = treeMintIn ?? splToken.NATIVE_MINT;
18484
+ const mintOut = treeMintOut ?? splToken.NATIVE_MINT;
18485
+ let zeroForOne;
18486
+ if (pool.mint0.equals(mintIn) && pool.mint1.equals(mintOut)) zeroForOne = true;
18487
+ else if (pool.mint1.equals(mintIn) && pool.mint0.equals(mintOut)) zeroForOne = false;
18488
+ else throw new Error("veilix-sdk: swap pool does not trade this pair");
18489
+ const [i, o] = zeroForOne ? [0, 1] : [1, 0];
18490
+ const [configInfo, vaultIn, vaultOut] = await connection.getMultipleAccountsInfo(
18491
+ [pool.ammConfig, zeroForOne ? pool.vault0 : pool.vault1, zeroForOne ? pool.vault1 : pool.vault0],
18492
+ "confirmed"
18493
+ );
18494
+ if (!configInfo || !vaultIn || !vaultOut) {
18495
+ throw new Error("veilix-sdk: swap pool accounts are missing");
18496
+ }
18497
+ const tradeFeeRate = u64(configInfo.data, 12);
18498
+ const creatorFeeRate = pool.enableCreatorFee && configInfo.data.length >= 116 ? u64(configInfo.data, 108) : 0n;
18499
+ const reserveIn = u64(vaultIn.data, 64) - pool.protocolFees[i] - pool.fundFees[i] - pool.creatorFees[i];
18500
+ const reserveOut = u64(vaultOut.data, 64) - pool.protocolFees[o] - pool.fundFees[o] - pool.creatorFees[o];
18501
+ if (reserveIn <= 0n || reserveOut <= 0n) {
18502
+ throw new Error("veilix-sdk: swap pool has no liquidity");
18503
+ }
18504
+ const creatorOnInput = pool.creatorFeeOn === 0 || pool.creatorFeeOn === 1 && zeroForOne || pool.creatorFeeOn === 2 && !zeroForOne;
18505
+ let inLessFees = amountIn - feeOf(amountIn, tradeFeeRate);
18506
+ if (creatorOnInput) inLessFees -= feeOf(amountIn, creatorFeeRate);
18507
+ let amountOut = inLessFees * reserveOut / (reserveIn + inLessFees);
18508
+ if (!creatorOnInput) amountOut -= feeOf(amountOut, creatorFeeRate);
18509
+ if (amountOut <= 0n) {
18510
+ throw new Error("veilix-sdk: swap amount is too small for this pool");
18511
+ }
18512
+ const spotOut = Number(inLessFees) * (Number(reserveOut) / Number(reserveIn));
18513
+ const priceImpact = spotOut > 0 ? Math.max(0, 1 - Number(amountOut) / spotOut) : 1;
18514
+ return { amountOut, priceImpact };
18515
+ }
18516
+
18517
+ // src/swap/execute.ts
18518
+ var SWAP_MAX_WAIT_MS = 18e4;
18519
+ var DEFAULT_SLIPPAGE_BPS = 100;
18520
+ var MAX_SLIPPAGE_BPS = 5e3;
18521
+ var MAX_PRICE_IMPACT = 0.1;
18522
+ var hex = (bytes) => `0x${bytesToHex(bytes)}`;
18523
+ var mintKey = (mint) => mint?.toBase58() ?? null;
18524
+ async function fetchRelayerQuote(relayerUrl, mintIn, mintOut, amountIn) {
18525
+ const params = new URLSearchParams({ amountIn: amountIn.toString() });
18526
+ if (mintIn) params.set("mintIn", mintIn.toBase58());
18527
+ if (mintOut) params.set("mintOut", mintOut.toBase58());
18528
+ const base = relayerUrl.replace(/\/$/, "");
18529
+ const res = await httpFetch(`${base}/v1/swapQuote?${params}`, {
18530
+ headers: { Accept: "application/json" }
18531
+ });
18532
+ const body = await res.json().catch(() => ({}));
18533
+ if (!res.ok) {
18534
+ throw new Error(body.error || `Swap quote failed (${res.status})`);
18535
+ }
18536
+ return { ...body, relayerUrl: base };
18537
+ }
18538
+ function swapCandidates(relayers, relayerUrl) {
18539
+ if (relayerUrl) {
18540
+ const wanted = relayerUrl.replace(/\/$/, "");
18541
+ const match = relayers.find((r) => r.url.replace(/\/$/, "") === wanted);
18542
+ if (!match) throw new Error(`veilix-sdk: relayer ${relayerUrl} is not available`);
18543
+ return [match];
18544
+ }
18545
+ if (!relayers.length) throw new Error("veilix-sdk: no relayer available");
18546
+ const first = getRandomRelayer(relayers);
18547
+ return [first, ...relayers.filter((r) => r !== first)];
18548
+ }
18549
+ async function getSwapQuote(params) {
18550
+ const { relayers } = getConfig();
18551
+ const mintIn = normalizeTreeMint(params.mintIn);
18552
+ const mintOut = normalizeTreeMint(params.mintOut);
18553
+ if (mintKey(mintIn) === mintKey(mintOut)) {
18554
+ throw new Error("veilix-sdk: swap needs two different assets");
18555
+ }
18556
+ const amountIn = BigInt(params.amountIn);
18557
+ if (amountIn <= 0n) throw new Error("veilix-sdk: swap amount must be positive");
18558
+ const { connection, network } = getConfig();
18559
+ const platformWallets = await fetchPlatformFeeWallets();
18560
+ let lastError = null;
18561
+ for (const relayer of swapCandidates(relayers, params.relayerUrl)) {
18562
+ try {
18563
+ const quote = await fetchRelayerQuote(relayer.url, mintIn, mintOut, amountIn);
18564
+ if (quote.relayer !== relayer.value) {
18565
+ throw new Error("Relayer quoted for a different reward account");
18566
+ }
18567
+ const { fee } = computeWithdrawFee(amountIn, relayer.fee, platformWallets);
18568
+ if (fee >= amountIn) throw new Error("Amount is too small to cover the fees");
18569
+ if (BigInt(quote.fee) !== fee) throw new Error("Relayer quoted a different fee");
18570
+ if (quote.dexProgram !== CPMM_PROGRAM_IDS[network]) {
18571
+ throw new Error("Relayer routes through an unsupported DEX");
18572
+ }
18573
+ const own = await quoteCpmm(
18574
+ connection,
18575
+ network,
18576
+ new web3_js.PublicKey(quote.pool),
18577
+ mintIn,
18578
+ mintOut,
18579
+ amountIn - fee
18580
+ );
18581
+ if (own.priceImpact > MAX_PRICE_IMPACT) {
18582
+ throw new Error(
18583
+ `Price impact ${(own.priceImpact * 100).toFixed(1)}% is too high for this pool; swap less`
18584
+ );
18585
+ }
18586
+ return {
18587
+ quote: {
18588
+ ...quote,
18589
+ swapIn: (amountIn - fee).toString(),
18590
+ amountOut: own.amountOut.toString(),
18591
+ priceImpact: own.priceImpact
18592
+ },
18593
+ relayer
18594
+ };
18595
+ } catch (error) {
18596
+ lastError = error;
18597
+ }
18598
+ }
18599
+ const reason = lastError instanceof Error ? lastError.message : "no relayer routes this pair";
18600
+ throw new Error(`veilix-sdk: no swap route for this pair (${reason})`);
18601
+ }
18602
+ async function buildSwapPayload(params, options = {}) {
18603
+ const { encryptKey } = getConfig();
18604
+ const utxo = decodeNote(params.note);
18605
+ const mintIn = utxo.mint;
18606
+ const mintOut = normalizeTreeMint(params.mintOut ?? null);
18607
+ const slippageBps = params.slippageBps ?? DEFAULT_SLIPPAGE_BPS;
18608
+ if (!Number.isInteger(slippageBps) || slippageBps < 0 || slippageBps > MAX_SLIPPAGE_BPS) {
18609
+ throw new Error(`veilix-sdk: slippageBps must be an integer between 0 and ${MAX_SLIPPAGE_BPS}`);
18610
+ }
18611
+ const { index } = await locateNote(utxo);
18612
+ if (index === null) {
18613
+ throw new Error("Note is not in the Veilix pool yet (deposit not confirmed or not indexed)");
18614
+ }
18615
+ utxo.index = index;
18616
+ if ((await validateNullifier(toHex32(utxo.nullifier()))).exists) {
18617
+ throw new Error("This note has already been spent");
18618
+ }
18619
+ const amountIn = params.amount === void 0 ? utxo.amount : BigInt(params.amount);
18620
+ if (amountIn <= 0n || amountIn > utxo.amount) {
18621
+ throw new Error(`Swap amount must be between 1 and ${utxo.amount}`);
18622
+ }
18623
+ const { quote, relayer } = await getSwapQuote({
18624
+ mintIn,
18625
+ mintOut,
18626
+ amountIn,
18627
+ relayerUrl: params.relayerUrl
18628
+ });
18629
+ const fee = BigInt(quote.fee);
18630
+ const minAmountOut = BigInt(quote.amountOut) * BigInt(1e4 - slippageBps) / 10000n;
18631
+ if (minAmountOut <= 0n) {
18632
+ throw new Error("Swap amount is too small for this pool");
18633
+ }
18634
+ let tree = options.tree;
18635
+ if (!tree || tree.elements.length <= index) {
18636
+ tree = await fetchAssetTree(mintKey(mintIn));
18637
+ }
18638
+ if (tree.elements.length <= index) {
18639
+ throw new Error("The indexer has not synced this note yet, retry shortly");
18640
+ }
18641
+ const change = utxo.amount - amountIn;
18642
+ const changeUtxo = change > 0n ? new Utxo({ amount: change, mint: mintIn }) : null;
18643
+ const encryptedOutput1 = changeUtxo && encryptKey ? encryptNoteOutput(encryptKey, changeUtxo) : new Uint8Array();
18644
+ const encryptedOutput2 = new Uint8Array();
18645
+ const outKeypair = VeilixKeypair.random();
18646
+ const outBlinding = randomFieldElement();
18647
+ const encryptedNote = encryptKey ? encryptSwapNoteOutput(encryptKey, outKeypair, outBlinding) : new Uint8Array();
18648
+ const relayerKey = new web3_js.PublicKey(relayer.value);
18649
+ const hash = await swapExtDataHash({
18650
+ mintIn,
18651
+ mintOut,
18652
+ relayer: relayerKey,
18653
+ amountIn,
18654
+ fee,
18655
+ minAmountOut,
18656
+ outPubkey: outKeypair.pubKey,
18657
+ outBlinding,
18658
+ encryptedOutput1,
18659
+ encryptedOutput2,
18660
+ encryptedNote
18661
+ });
18662
+ const proved = await withCircuitArtifacts(
18663
+ options.circuitArtifacts,
18664
+ (artifacts) => proveTransaction({
18665
+ tree,
18666
+ inputs: [utxo],
18667
+ outputs: changeUtxo ? [changeUtxo] : [],
18668
+ ext: {
18669
+ mint: mintIn,
18670
+ recipient: web3_js.PublicKey.default,
18671
+ relayer: relayerKey,
18672
+ extAmount: -amountIn,
18673
+ fee,
18674
+ encryptedOutput1,
18675
+ encryptedOutput2
18676
+ },
18677
+ extDataHashOverride: hash,
18678
+ circuit: artifacts
18679
+ })
18680
+ );
18681
+ const { proof } = proved;
18682
+ const payload = {
18683
+ proof: hex(proof.proof),
18684
+ root: hex(proof.root),
18685
+ inputNullifiers: [hex(proof.inputNullifiers[0]), hex(proof.inputNullifiers[1])],
18686
+ outputCommitments: [hex(proof.outputCommitments[0]), hex(proof.outputCommitments[1])],
18687
+ ...mintIn ? { mintIn: mintIn.toBase58() } : {},
18688
+ ...mintOut ? { mintOut: mintOut.toBase58() } : {},
18689
+ amountIn: amountIn.toString(),
18690
+ fee: fee.toString(),
18691
+ minAmountOut: minAmountOut.toString(),
18692
+ outPubkey: hex(bigintToBytes32(outKeypair.pubKey)),
18693
+ outBlinding: hex(bigintToBytes32(outBlinding)),
18694
+ relayer: relayerKey.toBase58(),
18695
+ encryptedOutput1: hex(encryptedOutput1),
18696
+ encryptedOutput2: hex(encryptedOutput2),
18697
+ encryptedNote: hex(encryptedNote)
18698
+ };
18699
+ return {
18700
+ payload,
18701
+ relayerUrl: quote.relayerUrl,
18702
+ quote,
18703
+ amountIn,
18704
+ fee,
18705
+ minAmountOut,
18706
+ changeNote: changeUtxo ? encodeNote(changeUtxo) : null,
18707
+ output: {
18708
+ mint: mintKey(mintOut),
18709
+ privKey: outKeypair.privKey.toString(),
18710
+ blinding: outBlinding.toString()
18711
+ },
18712
+ nullifiers: [...payload.inputNullifiers]
18713
+ };
18714
+ }
18715
+ async function pollSwapJob(relayerUrl, jobId, maxWaitMs) {
18716
+ const start = Date.now();
18717
+ while (Date.now() - start < maxWaitMs) {
18718
+ const res = await httpFetch(`${relayerUrl}/v1/jobs/${encodeURIComponent(jobId)}`, {
18719
+ headers: { Accept: "application/json" }
18720
+ });
18721
+ const job = await res.json().catch(() => ({}));
18722
+ if (!res.ok) throw new Error(job.error || "Failed to poll relayer job");
18723
+ if (job.status === "CONFIRMED" || job.status === "FAILED") return job;
18724
+ await new Promise((resolve) => setTimeout(resolve, 3e3));
18725
+ }
18726
+ throw new Error("Swap timed out");
18727
+ }
18728
+ function swapOutputNote(output, result) {
18729
+ const utxo = new Utxo({
18730
+ amount: BigInt(result.amountOut),
18731
+ keypair: VeilixKeypair.fromPrivateKey(output.privKey),
18732
+ blinding: BigInt(output.blinding),
18733
+ mint: output.mint ? new web3_js.PublicKey(output.mint) : null,
18734
+ index: result.outputIndex
18735
+ });
18736
+ if (toHex32(utxo.commitment()) !== toHex32(BigInt(result.outputCommitment))) {
18737
+ throw new Error("veilix-sdk: swapped note does not match the on-chain commitment");
18738
+ }
18739
+ return encodeNote(utxo);
18740
+ }
18741
+ async function submitSwapPayload(bundle) {
18742
+ const res = await httpFetch(`${bundle.relayerUrl}/v1/veilixSwap`, {
18743
+ method: "POST",
18744
+ headers: { "Content-Type": "application/json" },
18745
+ body: JSON.stringify(bundle.payload)
18746
+ });
18747
+ const body = await res.json().catch(() => ({}));
18748
+ if (!res.ok || !body.id) {
18749
+ throw new Error(body.error || "Swap submission failed");
18750
+ }
18751
+ const job = await pollSwapJob(bundle.relayerUrl, body.id, SWAP_MAX_WAIT_MS);
18752
+ const base = {
18753
+ changeNote: bundle.changeNote,
18754
+ amountIn: bundle.amountIn.toString(),
18755
+ fee: bundle.fee.toString(),
18756
+ minAmountOut: bundle.minAmountOut.toString()
18757
+ };
18758
+ if (job.status === "FAILED") {
18759
+ return {
18760
+ ...base,
18761
+ txHash: job.txHash ?? "",
18762
+ status: "failed",
18763
+ error: job.failedReason || "Swap failed",
18764
+ // A failed swap spends nothing: the original note is still valid.
18765
+ outputNote: null,
18766
+ changeNote: null,
18767
+ amountOut: null
18768
+ };
18769
+ }
18770
+ if (!job.txHash || !job.swapResult) {
18771
+ throw new Error("Swap confirmed but the relayer did not report the swapped note");
18772
+ }
18773
+ return {
18774
+ ...base,
18775
+ txHash: job.txHash,
18776
+ status: "success",
18777
+ outputNote: swapOutputNote(bundle.output, job.swapResult),
18778
+ amountOut: job.swapResult.amountOut
18779
+ };
18780
+ }
18781
+ async function executeSwap(params) {
18782
+ return submitSwapPayload(await buildSwapPayload(params));
18783
+ }
17527
18784
 
17528
18785
  // src/withdraw/assets.ts
17529
18786
  var TOKEN_UNITS = {
@@ -17647,6 +18904,8 @@ var SEND_OPTIONS = { skipPreflight: false, maxRetries: 3 };
17647
18904
  var SUBMIT_MAX_PROOFS = 8;
17648
18905
  var NOTE_INDEX_TIMEOUT_MS = 12e4;
17649
18906
  var NOTE_INDEX_POLL_MS = 4e3;
18907
+ var SEND_ATTEMPTS = 4;
18908
+ var SEND_RETRY_MS = 2e3;
17650
18909
  function sleep(ms) {
17651
18910
  return new Promise((resolve) => setTimeout(resolve, ms));
17652
18911
  }
@@ -17668,7 +18927,18 @@ async function signTransactions(wallet, transactions) {
17668
18927
  }
17669
18928
  async function sendAndConfirm(signed) {
17670
18929
  const { connection } = getConfig();
17671
- const signature = await connection.sendRawTransaction(signed.serialize(), SEND_OPTIONS);
18930
+ const raw = signed.serialize();
18931
+ let signature;
18932
+ for (let attempt = 1; signature === void 0; attempt++) {
18933
+ try {
18934
+ signature = await connection.sendRawTransaction(raw, SEND_OPTIONS);
18935
+ } catch (error) {
18936
+ if (attempt >= SEND_ATTEMPTS || !/blockhash not found/i.test(errorMessage(error))) {
18937
+ throw error;
18938
+ }
18939
+ await sleep(SEND_RETRY_MS);
18940
+ }
18941
+ }
17672
18942
  const { value } = await connection.confirmTransaction(signature, "confirmed");
17673
18943
  if (value.err) {
17674
18944
  throw new Error(`Deposit transaction failed: ${JSON.stringify(value.err)}`);
@@ -17714,6 +18984,7 @@ async function executeVeilixTransfer(items, options = {}) {
17714
18984
  const { wallet, network, relayers, encryptKey } = getConfig();
17715
18985
  const sender = wallet.publicKey;
17716
18986
  const onChainBackup = options.onChainBackup ?? !!encryptKey;
18987
+ const sealKey = onChainBackup ? encryptKey ?? requireEncryptKey() : void 0;
17717
18988
  const prepared = prepareDeposits(items);
17718
18989
  result.notes = prepared.map((deposit) => deposit.note);
17719
18990
  const circuitArtifacts = await prepareWithdrawCircuitArtifacts();
@@ -17724,7 +18995,8 @@ async function executeVeilixTransfer(items, options = {}) {
17724
18995
  senderPublicKey: sender,
17725
18996
  note: deposit.note,
17726
18997
  onChainBackup,
17727
- circuitArtifacts
18998
+ circuitArtifacts,
18999
+ ...sealKey ? { encryptKey: sealKey } : {}
17728
19000
  });
17729
19001
  } catch (error) {
17730
19002
  result.depositFailed.push(toDepositFailure(deposit, error));
@@ -17735,6 +19007,10 @@ async function executeVeilixTransfer(items, options = {}) {
17735
19007
  result.error = true;
17736
19008
  return result;
17737
19009
  }
19010
+ const { blockhash } = await getConfig().connection.getLatestBlockhash();
19011
+ toSend.forEach((deposit) => {
19012
+ deposit.tx.message.recentBlockhash = blockhash;
19013
+ });
17738
19014
  const signed = await signTransactions(wallet, toSend.map((deposit) => deposit.tx));
17739
19015
  if (options.downloadNotes ?? true) {
17740
19016
  downloadNotesCsv(toSend.map((deposit) => deposit.note));
@@ -17838,7 +19114,7 @@ var VeilixSDK = class _VeilixSDK {
17838
19114
  try {
17839
19115
  return fn();
17840
19116
  } finally {
17841
- popRuntimeContext();
19117
+ popRuntimeContext(this.config);
17842
19118
  }
17843
19119
  }
17844
19120
  async runAsync(fn) {
@@ -17846,7 +19122,7 @@ var VeilixSDK = class _VeilixSDK {
17846
19122
  try {
17847
19123
  return await fn();
17848
19124
  } finally {
17849
- popRuntimeContext();
19125
+ popRuntimeContext(this.config);
17850
19126
  }
17851
19127
  }
17852
19128
  // ── Config ───────────────────────────────────────────────────────────
@@ -17964,6 +19240,26 @@ var VeilixSDK = class _VeilixSDK {
17964
19240
  submitWithdrawPayload(bundle) {
17965
19241
  return this.runAsync(() => submitWithdrawPayload(bundle));
17966
19242
  }
19243
+ // ── Private swap ─────────────────────────────────────────────────────
19244
+ /** Fee and expected output of swapping `amountIn` of `mintIn` into `mintOut`. */
19245
+ getSwapQuote(params) {
19246
+ return this.runAsync(() => getSwapQuote(params));
19247
+ }
19248
+ /**
19249
+ * Swap a note of asset A into a new shielded note of asset B (`mintOut`, `null` for
19250
+ * SOL) through a relayer and an allowlisted DEX. Funds never leave the pool
19251
+ * unshielded. Returns the asset-B note and any asset-A change note.
19252
+ */
19253
+ swap(params) {
19254
+ return this.runAsync(() => executeSwap(params));
19255
+ }
19256
+ /** Prove a swap without submitting it (see {@link submitSwapPayload}). */
19257
+ buildSwapPayload(params, options) {
19258
+ return this.runAsync(() => buildSwapPayload(params, options));
19259
+ }
19260
+ submitSwapPayload(bundle) {
19261
+ return this.runAsync(() => submitSwapPayload(bundle));
19262
+ }
17967
19263
  /**
17968
19264
  * Private transfer: deposit one note per item, then withdraw each note in full
17969
19265
  * to its recipient through the indexer submission queue.
@@ -18075,15 +19371,15 @@ var VeilixSDK = class _VeilixSDK {
18075
19371
  * Accepts a frontend wallet adapter (`signMessage`) or a backend {@link Keypair}.
18076
19372
  */
18077
19373
  async getEncryptionKey(wallet) {
18078
- const key = await getEncryptionKey(wallet);
18079
- this.config.encryptKey = key;
18080
- return key;
19374
+ const key2 = await getEncryptionKey(wallet);
19375
+ this.config.encryptKey = key2;
19376
+ return key2;
18081
19377
  }
18082
- encryptData(key, plaintext) {
18083
- return encryptData(key, plaintext);
19378
+ encryptData(key2, plaintext) {
19379
+ return encryptData(key2, plaintext);
18084
19380
  }
18085
- decryptData(key, combined) {
18086
- return decryptData(key, combined);
19381
+ decryptData(key2, combined) {
19382
+ return decryptData(key2, combined);
18087
19383
  }
18088
19384
  // ── Utilities ────────────────────────────────────────────────────────
18089
19385
  parseAmountToBaseUnits(amount, decimals) {