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.
@@ -40,7 +40,7 @@ function formatBaseUnits(value, decimals) {
40
40
 
41
41
  // src/idl/veilix-devnet.json
42
42
  var veilix_devnet_default = {
43
- address: "HbatG5gpfs2g3N4gc2Qkfmmeu4zaBEVxzrDdYtWNLyyA",
43
+ address: "Vxi1QK84Akv4yGngjvkWNmEsK7XpsSrpDaPBoiyXGPG",
44
44
  metadata: {
45
45
  name: "veilix",
46
46
  version: "0.2.0",
@@ -641,6 +641,38 @@ var veilix_devnet_default = {
641
641
  {
642
642
  name: "system_program",
643
643
  address: "11111111111111111111111111111111"
644
+ },
645
+ {
646
+ name: "event_authority",
647
+ pda: {
648
+ seeds: [
649
+ {
650
+ kind: "const",
651
+ value: [
652
+ 95,
653
+ 95,
654
+ 101,
655
+ 118,
656
+ 101,
657
+ 110,
658
+ 116,
659
+ 95,
660
+ 97,
661
+ 117,
662
+ 116,
663
+ 104,
664
+ 111,
665
+ 114,
666
+ 105,
667
+ 116,
668
+ 121
669
+ ]
670
+ }
671
+ ]
672
+ }
673
+ },
674
+ {
675
+ name: "program"
644
676
  }
645
677
  ],
646
678
  args: [
@@ -703,6 +735,91 @@ var veilix_devnet_default = {
703
735
  ]
704
736
  }
705
737
  },
738
+ {
739
+ name: "program_data",
740
+ docs: [
741
+ "This program's ProgramData. Only its upgrade authority may initialize the network,",
742
+ "so nobody can claim the config authority between deploy and setup."
743
+ ],
744
+ pda: {
745
+ seeds: [
746
+ {
747
+ kind: "const",
748
+ value: [
749
+ 7,
750
+ 107,
751
+ 64,
752
+ 50,
753
+ 251,
754
+ 172,
755
+ 47,
756
+ 215,
757
+ 89,
758
+ 179,
759
+ 92,
760
+ 125,
761
+ 67,
762
+ 162,
763
+ 96,
764
+ 45,
765
+ 239,
766
+ 91,
767
+ 223,
768
+ 168,
769
+ 251,
770
+ 138,
771
+ 165,
772
+ 133,
773
+ 253,
774
+ 74,
775
+ 152,
776
+ 142,
777
+ 6,
778
+ 85,
779
+ 93,
780
+ 119
781
+ ]
782
+ }
783
+ ],
784
+ program: {
785
+ kind: "const",
786
+ value: [
787
+ 2,
788
+ 168,
789
+ 246,
790
+ 145,
791
+ 78,
792
+ 136,
793
+ 161,
794
+ 176,
795
+ 226,
796
+ 16,
797
+ 21,
798
+ 62,
799
+ 247,
800
+ 99,
801
+ 174,
802
+ 43,
803
+ 0,
804
+ 194,
805
+ 185,
806
+ 61,
807
+ 22,
808
+ 193,
809
+ 36,
810
+ 210,
811
+ 192,
812
+ 83,
813
+ 122,
814
+ 16,
815
+ 4,
816
+ 128,
817
+ 0,
818
+ 0
819
+ ]
820
+ }
821
+ }
822
+ },
706
823
  {
707
824
  name: "system_program",
708
825
  address: "11111111111111111111111111111111"
@@ -1031,6 +1148,31 @@ var veilix_devnet_default = {
1031
1148
  ]
1032
1149
  }
1033
1150
  },
1151
+ {
1152
+ name: "treasury",
1153
+ docs: [
1154
+ "Holds the SOL pool. Funded with its rent-exempt reserve here so that no withdrawal",
1155
+ "can fail for leaving it below that reserve."
1156
+ ],
1157
+ writable: true,
1158
+ pda: {
1159
+ seeds: [
1160
+ {
1161
+ kind: "const",
1162
+ value: [
1163
+ 116,
1164
+ 114,
1165
+ 101,
1166
+ 97,
1167
+ 115,
1168
+ 117,
1169
+ 114,
1170
+ 121
1171
+ ]
1172
+ }
1173
+ ]
1174
+ }
1175
+ },
1034
1176
  {
1035
1177
  name: "system_program",
1036
1178
  address: "11111111111111111111111111111111"
@@ -1461,6 +1603,336 @@ var veilix_devnet_default = {
1461
1603
  }
1462
1604
  ]
1463
1605
  },
1606
+ {
1607
+ name: "swap",
1608
+ docs: [
1609
+ "Private swap. Remaining accounts: the protocol fee wallets for the input asset (SOL",
1610
+ "accounts or their token accounts, in config order), then the DEX instruction's accounts."
1611
+ ],
1612
+ discriminator: [
1613
+ 248,
1614
+ 198,
1615
+ 158,
1616
+ 145,
1617
+ 225,
1618
+ 117,
1619
+ 135,
1620
+ 200
1621
+ ],
1622
+ accounts: [
1623
+ {
1624
+ name: "relayer",
1625
+ writable: true,
1626
+ signer: true
1627
+ },
1628
+ {
1629
+ name: "relayer_account",
1630
+ writable: true,
1631
+ pda: {
1632
+ seeds: [
1633
+ {
1634
+ kind: "const",
1635
+ value: [
1636
+ 114,
1637
+ 101,
1638
+ 108,
1639
+ 97,
1640
+ 121,
1641
+ 101,
1642
+ 114
1643
+ ]
1644
+ },
1645
+ {
1646
+ kind: "account",
1647
+ path: "relayer_account.owner",
1648
+ account: "RelayerAccount"
1649
+ }
1650
+ ]
1651
+ }
1652
+ },
1653
+ {
1654
+ name: "network_state",
1655
+ pda: {
1656
+ seeds: [
1657
+ {
1658
+ kind: "const",
1659
+ value: [
1660
+ 99,
1661
+ 111,
1662
+ 110,
1663
+ 102,
1664
+ 105,
1665
+ 103
1666
+ ]
1667
+ }
1668
+ ]
1669
+ }
1670
+ },
1671
+ {
1672
+ name: "swap_config",
1673
+ pda: {
1674
+ seeds: [
1675
+ {
1676
+ kind: "const",
1677
+ value: [
1678
+ 115,
1679
+ 119,
1680
+ 97,
1681
+ 112,
1682
+ 95,
1683
+ 99,
1684
+ 111,
1685
+ 110,
1686
+ 102,
1687
+ 105,
1688
+ 103
1689
+ ]
1690
+ }
1691
+ ]
1692
+ }
1693
+ },
1694
+ {
1695
+ name: "tree_in",
1696
+ docs: [
1697
+ "Tree of the asset being spent. The handler checks it is the PDA for its mint."
1698
+ ],
1699
+ writable: true
1700
+ },
1701
+ {
1702
+ name: "tree_out",
1703
+ docs: [
1704
+ "Tree that receives the swapped note."
1705
+ ],
1706
+ writable: true
1707
+ },
1708
+ {
1709
+ name: "treasury",
1710
+ writable: true,
1711
+ pda: {
1712
+ seeds: [
1713
+ {
1714
+ kind: "const",
1715
+ value: [
1716
+ 116,
1717
+ 114,
1718
+ 101,
1719
+ 97,
1720
+ 115,
1721
+ 117,
1722
+ 114,
1723
+ 121
1724
+ ]
1725
+ }
1726
+ ]
1727
+ }
1728
+ },
1729
+ {
1730
+ name: "escrow",
1731
+ docs: [
1732
+ "Signs the DEX call. Holds nothing between transactions."
1733
+ ],
1734
+ writable: true,
1735
+ pda: {
1736
+ seeds: [
1737
+ {
1738
+ kind: "const",
1739
+ value: [
1740
+ 115,
1741
+ 119,
1742
+ 97,
1743
+ 112,
1744
+ 95,
1745
+ 101,
1746
+ 115,
1747
+ 99,
1748
+ 114,
1749
+ 111,
1750
+ 119
1751
+ ]
1752
+ }
1753
+ ]
1754
+ }
1755
+ },
1756
+ {
1757
+ name: "treasury_ata_in",
1758
+ docs: [
1759
+ "Treasury ATA for `mint_in`. `None` when spending SOL."
1760
+ ],
1761
+ writable: true,
1762
+ optional: true
1763
+ },
1764
+ {
1765
+ name: "treasury_ata_out",
1766
+ docs: [
1767
+ "Treasury ATA for `mint_out`. `None` when receiving SOL."
1768
+ ],
1769
+ writable: true,
1770
+ optional: true
1771
+ },
1772
+ {
1773
+ name: "escrow_ata_in",
1774
+ docs: [
1775
+ "Escrow ATA for `mint_in` (wrapped SOL when spending SOL). Must exist: prepend an",
1776
+ "idempotent ATA create. A wrapped-SOL escrow account is closed at the end of the swap."
1777
+ ],
1778
+ writable: true
1779
+ },
1780
+ {
1781
+ name: "escrow_ata_out",
1782
+ docs: [
1783
+ "Escrow ATA for `mint_out` (wrapped SOL when receiving SOL). Must exist, as above."
1784
+ ],
1785
+ writable: true
1786
+ },
1787
+ {
1788
+ name: "relayer_ata",
1789
+ docs: [
1790
+ "Relayer ATA for `mint_in`, paid the relayer fee. `None` when spending SOL."
1791
+ ],
1792
+ writable: true,
1793
+ optional: true
1794
+ },
1795
+ {
1796
+ name: "nullifier0",
1797
+ writable: true,
1798
+ pda: {
1799
+ seeds: [
1800
+ {
1801
+ kind: "const",
1802
+ value: [
1803
+ 110,
1804
+ 117,
1805
+ 108,
1806
+ 108,
1807
+ 105,
1808
+ 102,
1809
+ 105,
1810
+ 101,
1811
+ 114
1812
+ ]
1813
+ },
1814
+ {
1815
+ kind: "arg",
1816
+ path: "proof.input_nullifiers [0]"
1817
+ }
1818
+ ]
1819
+ }
1820
+ },
1821
+ {
1822
+ name: "nullifier1",
1823
+ writable: true,
1824
+ pda: {
1825
+ seeds: [
1826
+ {
1827
+ kind: "const",
1828
+ value: [
1829
+ 110,
1830
+ 117,
1831
+ 108,
1832
+ 108,
1833
+ 105,
1834
+ 102,
1835
+ 105,
1836
+ 101,
1837
+ 114
1838
+ ]
1839
+ },
1840
+ {
1841
+ kind: "arg",
1842
+ path: "proof.input_nullifiers [1]"
1843
+ }
1844
+ ]
1845
+ }
1846
+ },
1847
+ {
1848
+ name: "mint_in",
1849
+ docs: [
1850
+ "Mint of the spent asset (the native mint when spending SOL)."
1851
+ ]
1852
+ },
1853
+ {
1854
+ name: "mint_out",
1855
+ docs: [
1856
+ "Mint of the received asset (the native mint when receiving SOL)."
1857
+ ]
1858
+ },
1859
+ {
1860
+ name: "token_program_in"
1861
+ },
1862
+ {
1863
+ name: "token_program_out"
1864
+ },
1865
+ {
1866
+ name: "dex_program"
1867
+ },
1868
+ {
1869
+ name: "system_program",
1870
+ address: "11111111111111111111111111111111"
1871
+ },
1872
+ {
1873
+ name: "event_authority",
1874
+ pda: {
1875
+ seeds: [
1876
+ {
1877
+ kind: "const",
1878
+ value: [
1879
+ 95,
1880
+ 95,
1881
+ 101,
1882
+ 118,
1883
+ 101,
1884
+ 110,
1885
+ 116,
1886
+ 95,
1887
+ 97,
1888
+ 117,
1889
+ 116,
1890
+ 104,
1891
+ 111,
1892
+ 114,
1893
+ 105,
1894
+ 116,
1895
+ 121
1896
+ ]
1897
+ }
1898
+ ]
1899
+ }
1900
+ },
1901
+ {
1902
+ name: "program"
1903
+ }
1904
+ ],
1905
+ args: [
1906
+ {
1907
+ name: "proof",
1908
+ type: {
1909
+ defined: {
1910
+ name: "TransactionProof"
1911
+ }
1912
+ }
1913
+ },
1914
+ {
1915
+ name: "params",
1916
+ type: {
1917
+ defined: {
1918
+ name: "SwapParams"
1919
+ }
1920
+ }
1921
+ },
1922
+ {
1923
+ name: "encrypted_output1",
1924
+ type: "bytes"
1925
+ },
1926
+ {
1927
+ name: "encrypted_output2",
1928
+ type: "bytes"
1929
+ },
1930
+ {
1931
+ name: "route_data",
1932
+ type: "bytes"
1933
+ }
1934
+ ]
1935
+ },
1464
1936
  {
1465
1937
  name: "token_deposit",
1466
1938
  discriminator: [
@@ -1687,14 +2159,46 @@ var veilix_devnet_default = {
1687
2159
  }
1688
2160
  },
1689
2161
  {
1690
- name: "mint"
1691
- },
1692
- {
1693
- name: "token_program"
1694
- },
1695
- {
1696
- name: "system_program",
1697
- address: "11111111111111111111111111111111"
2162
+ name: "mint"
2163
+ },
2164
+ {
2165
+ name: "token_program"
2166
+ },
2167
+ {
2168
+ name: "system_program",
2169
+ address: "11111111111111111111111111111111"
2170
+ },
2171
+ {
2172
+ name: "event_authority",
2173
+ pda: {
2174
+ seeds: [
2175
+ {
2176
+ kind: "const",
2177
+ value: [
2178
+ 95,
2179
+ 95,
2180
+ 101,
2181
+ 118,
2182
+ 101,
2183
+ 110,
2184
+ 116,
2185
+ 95,
2186
+ 97,
2187
+ 117,
2188
+ 116,
2189
+ 104,
2190
+ 111,
2191
+ 114,
2192
+ 105,
2193
+ 116,
2194
+ 121
2195
+ ]
2196
+ }
2197
+ ]
2198
+ }
2199
+ },
2200
+ {
2201
+ name: "program"
1698
2202
  }
1699
2203
  ],
1700
2204
  args: [
@@ -2061,6 +2565,38 @@ var veilix_devnet_default = {
2061
2565
  {
2062
2566
  name: "system_program",
2063
2567
  address: "11111111111111111111111111111111"
2568
+ },
2569
+ {
2570
+ name: "event_authority",
2571
+ pda: {
2572
+ seeds: [
2573
+ {
2574
+ kind: "const",
2575
+ value: [
2576
+ 95,
2577
+ 95,
2578
+ 101,
2579
+ 118,
2580
+ 101,
2581
+ 110,
2582
+ 116,
2583
+ 95,
2584
+ 97,
2585
+ 117,
2586
+ 116,
2587
+ 104,
2588
+ 111,
2589
+ 114,
2590
+ 105,
2591
+ 116,
2592
+ 121
2593
+ ]
2594
+ }
2595
+ ]
2596
+ }
2597
+ },
2598
+ {
2599
+ name: "program"
2064
2600
  }
2065
2601
  ],
2066
2602
  args: [
@@ -2509,6 +3045,83 @@ var veilix_devnet_default = {
2509
3045
  }
2510
3046
  ]
2511
3047
  },
3048
+ {
3049
+ name: "update_swap_config",
3050
+ docs: [
3051
+ "Replaces the list of DEX programs the swap escrow may call. Config authority only."
3052
+ ],
3053
+ discriminator: [
3054
+ 123,
3055
+ 172,
3056
+ 158,
3057
+ 60,
3058
+ 104,
3059
+ 133,
3060
+ 39,
3061
+ 13
3062
+ ],
3063
+ accounts: [
3064
+ {
3065
+ name: "authority",
3066
+ writable: true,
3067
+ signer: true
3068
+ },
3069
+ {
3070
+ name: "network_state",
3071
+ pda: {
3072
+ seeds: [
3073
+ {
3074
+ kind: "const",
3075
+ value: [
3076
+ 99,
3077
+ 111,
3078
+ 110,
3079
+ 102,
3080
+ 105,
3081
+ 103
3082
+ ]
3083
+ }
3084
+ ]
3085
+ }
3086
+ },
3087
+ {
3088
+ name: "swap_config",
3089
+ writable: true,
3090
+ pda: {
3091
+ seeds: [
3092
+ {
3093
+ kind: "const",
3094
+ value: [
3095
+ 115,
3096
+ 119,
3097
+ 97,
3098
+ 112,
3099
+ 95,
3100
+ 99,
3101
+ 111,
3102
+ 110,
3103
+ 102,
3104
+ 105,
3105
+ 103
3106
+ ]
3107
+ }
3108
+ ]
3109
+ }
3110
+ },
3111
+ {
3112
+ name: "system_program",
3113
+ address: "11111111111111111111111111111111"
3114
+ }
3115
+ ],
3116
+ args: [
3117
+ {
3118
+ name: "allowed_programs",
3119
+ type: {
3120
+ vec: "pubkey"
3121
+ }
3122
+ }
3123
+ ]
3124
+ },
2512
3125
  {
2513
3126
  name: "withdraw",
2514
3127
  discriminator: [
@@ -2667,6 +3280,38 @@ var veilix_devnet_default = {
2667
3280
  {
2668
3281
  name: "system_program",
2669
3282
  address: "11111111111111111111111111111111"
3283
+ },
3284
+ {
3285
+ name: "event_authority",
3286
+ pda: {
3287
+ seeds: [
3288
+ {
3289
+ kind: "const",
3290
+ value: [
3291
+ 95,
3292
+ 95,
3293
+ 101,
3294
+ 118,
3295
+ 101,
3296
+ 110,
3297
+ 116,
3298
+ 95,
3299
+ 97,
3300
+ 117,
3301
+ 116,
3302
+ 104,
3303
+ 111,
3304
+ 114,
3305
+ 105,
3306
+ 116,
3307
+ 121
3308
+ ]
3309
+ }
3310
+ ]
3311
+ }
3312
+ },
3313
+ {
3314
+ name: "program"
2670
3315
  }
2671
3316
  ],
2672
3317
  args: [
@@ -2776,6 +3421,19 @@ var veilix_devnet_default = {
2776
3421
  20
2777
3422
  ]
2778
3423
  },
3424
+ {
3425
+ name: "SwapConfig",
3426
+ discriminator: [
3427
+ 212,
3428
+ 45,
3429
+ 70,
3430
+ 222,
3431
+ 245,
3432
+ 122,
3433
+ 125,
3434
+ 166
3435
+ ]
3436
+ },
2779
3437
  {
2780
3438
  name: "TreeAccount",
2781
3439
  discriminator: [
@@ -2817,6 +3475,19 @@ var veilix_devnet_default = {
2817
3475
  159
2818
3476
  ]
2819
3477
  },
3478
+ {
3479
+ name: "PrivateSwapEvent",
3480
+ discriminator: [
3481
+ 150,
3482
+ 165,
3483
+ 138,
3484
+ 189,
3485
+ 123,
3486
+ 86,
3487
+ 117,
3488
+ 39
3489
+ ]
3490
+ },
2820
3491
  {
2821
3492
  name: "RelayerCancelled",
2822
3493
  discriminator: [
@@ -3079,6 +3750,56 @@ var veilix_devnet_default = {
3079
3750
  code: 6033,
3080
3751
  name: "FeeRepaymentAccounts",
3081
3752
  msg: "Fee repayment accounts do not match earned fees"
3753
+ },
3754
+ {
3755
+ code: 6034,
3756
+ name: "DexProgramNotAllowed",
3757
+ msg: "DEX program is not on the swap allowlist"
3758
+ },
3759
+ {
3760
+ code: 6035,
3761
+ name: "TooManyDexPrograms",
3762
+ msg: "Too many allowlisted DEX programs"
3763
+ },
3764
+ {
3765
+ code: 6036,
3766
+ name: "SlippageExceeded",
3767
+ msg: "Swap output is below the minimum amount"
3768
+ },
3769
+ {
3770
+ code: 6037,
3771
+ name: "SwapInputMismatch",
3772
+ msg: "DEX did not use exactly the escrowed swap input"
3773
+ },
3774
+ {
3775
+ code: 6038,
3776
+ name: "InvalidSwapAccounts",
3777
+ msg: "Swap accounts do not match the trees"
3778
+ },
3779
+ {
3780
+ code: 6039,
3781
+ name: "EscrowTampered",
3782
+ msg: "Swap escrow was modified by the DEX"
3783
+ },
3784
+ {
3785
+ code: 6040,
3786
+ name: "InvalidNoteKey",
3787
+ msg: "Note public key or blinding is not a valid field element"
3788
+ },
3789
+ {
3790
+ code: 6041,
3791
+ name: "NotUpgradeAuthority",
3792
+ msg: "Only the program upgrade authority can initialize the network"
3793
+ },
3794
+ {
3795
+ code: 6042,
3796
+ name: "InvalidFeeSplit",
3797
+ msg: "Fee wallets must be distinct, non-default and split at most the allowed total"
3798
+ },
3799
+ {
3800
+ code: 6043,
3801
+ name: "UnsupportedMintExtension",
3802
+ msg: "Token mint has an extension the pool does not support"
3082
3803
  }
3083
3804
  ],
3084
3805
  types: [
@@ -3206,8 +3927,104 @@ var veilix_devnet_default = {
3206
3927
  type: "pubkey"
3207
3928
  },
3208
3929
  {
3209
- name: "index",
3210
- type: "u64"
3930
+ name: "index",
3931
+ type: "u64"
3932
+ },
3933
+ {
3934
+ name: "commitment",
3935
+ type: {
3936
+ array: [
3937
+ "u8",
3938
+ 32
3939
+ ]
3940
+ }
3941
+ },
3942
+ {
3943
+ name: "encrypted_output",
3944
+ type: "bytes"
3945
+ }
3946
+ ]
3947
+ }
3948
+ },
3949
+ {
3950
+ name: "Notes",
3951
+ type: {
3952
+ kind: "struct",
3953
+ fields: [
3954
+ {
3955
+ name: "entries",
3956
+ type: {
3957
+ vec: "string"
3958
+ }
3959
+ }
3960
+ ]
3961
+ }
3962
+ },
3963
+ {
3964
+ name: "NotesV2",
3965
+ type: {
3966
+ kind: "struct",
3967
+ fields: [
3968
+ {
3969
+ name: "entries",
3970
+ type: {
3971
+ vec: "bytes"
3972
+ }
3973
+ }
3974
+ ]
3975
+ }
3976
+ },
3977
+ {
3978
+ name: "Nullifier",
3979
+ type: {
3980
+ kind: "struct"
3981
+ }
3982
+ },
3983
+ {
3984
+ name: "PrivateSwapEvent",
3985
+ docs: [
3986
+ "Emitted once per swap. The asset-B note is `commitment` at `index` in the `mint_out` tree."
3987
+ ],
3988
+ type: {
3989
+ kind: "struct",
3990
+ fields: [
3991
+ {
3992
+ name: "mint_in",
3993
+ type: "pubkey"
3994
+ },
3995
+ {
3996
+ name: "mint_out",
3997
+ type: "pubkey"
3998
+ },
3999
+ {
4000
+ name: "amount_in",
4001
+ type: "u64"
4002
+ },
4003
+ {
4004
+ name: "fee",
4005
+ type: "u64"
4006
+ },
4007
+ {
4008
+ name: "amount_out",
4009
+ type: "u64"
4010
+ },
4011
+ {
4012
+ name: "input_nullifiers",
4013
+ type: {
4014
+ array: [
4015
+ {
4016
+ array: [
4017
+ "u8",
4018
+ 32
4019
+ ]
4020
+ },
4021
+ 2
4022
+ ]
4023
+ }
4024
+ },
4025
+ {
4026
+ name: "relayer",
4027
+ type: "pubkey"
3211
4028
  },
3212
4029
  {
3213
4030
  name: "commitment",
@@ -3219,46 +4036,12 @@ var veilix_devnet_default = {
3219
4036
  }
3220
4037
  },
3221
4038
  {
3222
- name: "encrypted_output",
3223
- type: "bytes"
3224
- }
3225
- ]
3226
- }
3227
- },
3228
- {
3229
- name: "Notes",
3230
- type: {
3231
- kind: "struct",
3232
- fields: [
3233
- {
3234
- name: "entries",
3235
- type: {
3236
- vec: "string"
3237
- }
3238
- }
3239
- ]
3240
- }
3241
- },
3242
- {
3243
- name: "NotesV2",
3244
- type: {
3245
- kind: "struct",
3246
- fields: [
3247
- {
3248
- name: "entries",
3249
- type: {
3250
- vec: "bytes"
3251
- }
4039
+ name: "index",
4040
+ type: "u64"
3252
4041
  }
3253
4042
  ]
3254
4043
  }
3255
4044
  },
3256
- {
3257
- name: "Nullifier",
3258
- type: {
3259
- kind: "struct"
3260
- }
3261
- },
3262
4045
  {
3263
4046
  name: "RelayerAccount",
3264
4047
  docs: [
@@ -3453,6 +4236,86 @@ var veilix_devnet_default = {
3453
4236
  ]
3454
4237
  }
3455
4238
  },
4239
+ {
4240
+ name: "SwapConfig",
4241
+ docs: [
4242
+ 'Programs the swap escrow is allowed to call. PDA seeds: `["swap_config"]`.'
4243
+ ],
4244
+ type: {
4245
+ kind: "struct",
4246
+ fields: [
4247
+ {
4248
+ name: "allowed_programs",
4249
+ type: {
4250
+ vec: "pubkey"
4251
+ }
4252
+ }
4253
+ ]
4254
+ }
4255
+ },
4256
+ {
4257
+ name: "SwapParams",
4258
+ docs: [
4259
+ "Swap parameters. All of them are bound into the proof's `extDataHash`."
4260
+ ],
4261
+ type: {
4262
+ kind: "struct",
4263
+ fields: [
4264
+ {
4265
+ name: "amount_in",
4266
+ docs: [
4267
+ "Asset-A amount spent from the pool, fee included."
4268
+ ],
4269
+ type: "u64"
4270
+ },
4271
+ {
4272
+ name: "fee",
4273
+ docs: [
4274
+ "Asset-A fee: protocol wallets get their split of `amount_in`, the relayer the rest."
4275
+ ],
4276
+ type: "u64"
4277
+ },
4278
+ {
4279
+ name: "min_amount_out",
4280
+ docs: [
4281
+ "Minimum asset-B amount that must reach the treasury."
4282
+ ],
4283
+ type: "u64"
4284
+ },
4285
+ {
4286
+ name: "out_pubkey",
4287
+ docs: [
4288
+ "One-time shielded public key of the asset-B note (32-byte big-endian field element)."
4289
+ ],
4290
+ type: {
4291
+ array: [
4292
+ "u8",
4293
+ 32
4294
+ ]
4295
+ }
4296
+ },
4297
+ {
4298
+ name: "out_blinding",
4299
+ docs: [
4300
+ "Blinding of the asset-B note (32-byte big-endian field element)."
4301
+ ],
4302
+ type: {
4303
+ array: [
4304
+ "u8",
4305
+ 32
4306
+ ]
4307
+ }
4308
+ },
4309
+ {
4310
+ name: "encrypted_note",
4311
+ docs: [
4312
+ "Optional encrypted recovery data for the asset-B note."
4313
+ ],
4314
+ type: "bytes"
4315
+ }
4316
+ ]
4317
+ }
4318
+ },
3456
4319
  {
3457
4320
  name: "TransactionProof",
3458
4321
  docs: [
@@ -7351,7 +8214,7 @@ var MAINNET_TOKEN_MINTS = {
7351
8214
  USDC: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
7352
8215
  };
7353
8216
  var DEVNET_TOKEN_MINTS = {
7354
- Veilix: "GAFN64LvtCBoc5BHncVn3JEJGpq42rUzQjPmvMK2UhZH",
8217
+ Veilix: "Gmo636w21RBZX9ySVtPYcuYP6f1E5bdW5eBYhvK1bc8J",
7355
8218
  Bitcoin: "",
7356
8219
  Ethereum: "",
7357
8220
  USDC: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU"
@@ -7401,7 +8264,7 @@ function getDepositQueueForNetwork(network) {
7401
8264
  // package.json
7402
8265
  var package_default = {
7403
8266
  name: "veilix-sdk",
7404
- version: "0.2.3"};
8267
+ version: "0.3.1"};
7405
8268
 
7406
8269
  // src/circuits/constants.ts
7407
8270
  var PACKAGE_NAME = package_default.name;
@@ -7576,10 +8439,19 @@ async function createRuntimeConfig(options) {
7576
8439
  };
7577
8440
  }
7578
8441
  function pushRuntimeContext(config) {
8442
+ const active = runtimeContextStack.find((other) => other.programId !== config.programId);
8443
+ if (active) {
8444
+ throw new Error(
8445
+ `veilix-sdk: another SDK instance is running on program ${active.programId}; instances on different networks must run one at a time`
8446
+ );
8447
+ }
7579
8448
  runtimeContextStack.push(config);
7580
8449
  }
7581
- function popRuntimeContext() {
7582
- runtimeContextStack.pop();
8450
+ function popRuntimeContext(config) {
8451
+ const index = runtimeContextStack.lastIndexOf(config);
8452
+ if (index !== -1) {
8453
+ runtimeContextStack.splice(index, 1);
8454
+ }
7583
8455
  }
7584
8456
  function getConfig() {
7585
8457
  const active = runtimeContextStack.at(-1);
@@ -7644,10 +8516,10 @@ var DEPOSIT_COMPUTE_UNIT_LIMIT = 35e4;
7644
8516
  function bytesToHex(bytes) {
7645
8517
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
7646
8518
  }
7647
- function hexToBytes(hex) {
7648
- const clean = hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
8519
+ function hexToBytes(hex2) {
8520
+ const clean = hex2.startsWith("0x") || hex2.startsWith("0X") ? hex2.slice(2) : hex2;
7649
8521
  if (clean.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(clean)) {
7650
- throw new Error(`veilix-sdk: invalid hex string "${hex}"`);
8522
+ throw new Error(`veilix-sdk: invalid hex string "${hex2}"`);
7651
8523
  }
7652
8524
  const out = new Uint8Array(clean.length / 2);
7653
8525
  for (let i = 0; i < out.length; i++) {
@@ -7656,15 +8528,15 @@ function hexToBytes(hex) {
7656
8528
  return out;
7657
8529
  }
7658
8530
  function bigintToBytes32(value) {
7659
- const hex = BigInt(value).toString(16).padStart(64, "0");
7660
- if (hex.length > 64) {
8531
+ const hex2 = BigInt(value).toString(16).padStart(64, "0");
8532
+ if (hex2.length > 64) {
7661
8533
  throw new Error("veilix-sdk: value does not fit in 32 bytes");
7662
8534
  }
7663
- return hexToBytes(hex);
8535
+ return hexToBytes(hex2);
7664
8536
  }
7665
8537
  function bytesToBigint(bytes) {
7666
- const hex = bytesToHex(bytes);
7667
- return hex ? BigInt(`0x${hex}`) : 0n;
8538
+ const hex2 = bytesToHex(bytes);
8539
+ return hex2 ? BigInt(`0x${hex2}`) : 0n;
7668
8540
  }
7669
8541
  function toHex32(value) {
7670
8542
  return `0x${BigInt(value).toString(16).padStart(64, "0")}`;
@@ -7782,6 +8654,7 @@ var Utxo = class _Utxo {
7782
8654
  // src/core/note.ts
7783
8655
  var NOTE_PREFIX = "vx2";
7784
8656
  var ENCRYPTED_OUTPUT_VERSION = 1;
8657
+ var ENCRYPTED_SWAP_OUTPUT_VERSION = 2;
7785
8658
  var ENCRYPTED_OUTPUT_PLAINTEXT_BYTES = 1 + 8 + 32 + 32;
7786
8659
  var SECRETBOX_NONCE_BYTES = nacl.secretbox.nonceLength;
7787
8660
  function encodeNote(utxo) {
@@ -7814,14 +8687,14 @@ function decodeNote(note) {
7814
8687
  throw new Error("veilix-sdk: invalid note format");
7815
8688
  }
7816
8689
  const [, amountHex, privKeyHex, blindingHex, mint] = parts;
7817
- const hex = /^[0-9a-f]+$/i;
7818
- if (!hex.test(amountHex) || !hex.test(privKeyHex) || !hex.test(blindingHex)) {
8690
+ const hex2 = /^[0-9a-f]+$/i;
8691
+ if (!hex2.test(amountHex) || !hex2.test(privKeyHex) || !hex2.test(blindingHex)) {
7819
8692
  throw new Error("veilix-sdk: invalid note format");
7820
8693
  }
7821
- let mintKey = null;
8694
+ let mintKey2 = null;
7822
8695
  if (mint) {
7823
8696
  try {
7824
- mintKey = new PublicKey(mint);
8697
+ mintKey2 = new PublicKey(mint);
7825
8698
  } catch {
7826
8699
  throw new Error("veilix-sdk: invalid note mint");
7827
8700
  }
@@ -7830,7 +8703,7 @@ function decodeNote(note) {
7830
8703
  amount: BigInt(`0x${amountHex}`),
7831
8704
  keypair: VeilixKeypair.fromPrivateKey(BigInt(`0x${privKeyHex}`)),
7832
8705
  blinding: BigInt(`0x${blindingHex}`),
7833
- mint: mintKey
8706
+ mint: mintKey2
7834
8707
  });
7835
8708
  }
7836
8709
  function describeUtxo(utxo) {
@@ -7848,7 +8721,7 @@ function describeUtxo(utxo) {
7848
8721
  function parseSecretNote(note) {
7849
8722
  return describeUtxo(decodeNote(note));
7850
8723
  }
7851
- function encryptNoteOutput(key, utxo) {
8724
+ function encryptNoteOutput(key2, utxo) {
7852
8725
  const amount = new Uint8Array(8);
7853
8726
  new DataView(amount.buffer).setBigUint64(0, utxo.amount, true);
7854
8727
  const plaintext = concatBytes([
@@ -7858,21 +8731,38 @@ function encryptNoteOutput(key, utxo) {
7858
8731
  bigintToBytes32(utxo.blinding)
7859
8732
  ]);
7860
8733
  const nonce = nacl.randomBytes(SECRETBOX_NONCE_BYTES);
7861
- return concatBytes([nonce, nacl.secretbox(plaintext, nonce, key)]);
8734
+ return concatBytes([nonce, nacl.secretbox(plaintext, nonce, key2)]);
8735
+ }
8736
+ function encryptSwapNoteOutput(key2, keypair, blinding) {
8737
+ const plaintext = concatBytes([
8738
+ Uint8Array.of(ENCRYPTED_SWAP_OUTPUT_VERSION),
8739
+ new Uint8Array(8),
8740
+ bigintToBytes32(keypair.privKey),
8741
+ bigintToBytes32(blinding)
8742
+ ]);
8743
+ const nonce = nacl.randomBytes(SECRETBOX_NONCE_BYTES);
8744
+ return concatBytes([nonce, nacl.secretbox(plaintext, nonce, key2)]);
7862
8745
  }
7863
- function decryptNoteOutput(key, encryptedOutput, mint, index) {
8746
+ function decryptNoteOutput(key2, encryptedOutput, mint, index, onchainAmount = null) {
7864
8747
  if (encryptedOutput.length !== SECRETBOX_NONCE_BYTES + nacl.secretbox.overheadLength + ENCRYPTED_OUTPUT_PLAINTEXT_BYTES) {
7865
8748
  return null;
7866
8749
  }
7867
8750
  const opened = nacl.secretbox.open(
7868
8751
  encryptedOutput.subarray(SECRETBOX_NONCE_BYTES),
7869
8752
  encryptedOutput.subarray(0, SECRETBOX_NONCE_BYTES),
7870
- key
8753
+ key2
7871
8754
  );
7872
- if (!opened || opened[0] !== ENCRYPTED_OUTPUT_VERSION) {
8755
+ if (!opened) {
8756
+ return null;
8757
+ }
8758
+ let amount;
8759
+ if (opened[0] === ENCRYPTED_OUTPUT_VERSION) {
8760
+ amount = new DataView(opened.buffer, opened.byteOffset + 1, 8).getBigUint64(0, true);
8761
+ } else if (opened[0] === ENCRYPTED_SWAP_OUTPUT_VERSION && onchainAmount !== null) {
8762
+ amount = onchainAmount;
8763
+ } else {
7873
8764
  return null;
7874
8765
  }
7875
- const amount = new DataView(opened.buffer, opened.byteOffset + 1, 8).getBigUint64(0, true);
7876
8766
  return new Utxo({
7877
8767
  amount,
7878
8768
  keypair: VeilixKeypair.fromPrivateKey(bytesToBigint(opened.subarray(9, 41))),
@@ -16353,6 +17243,7 @@ async function proveTransaction({
16353
17243
  inputs = [],
16354
17244
  outputs = [],
16355
17245
  ext,
17246
+ extDataHashOverride,
16356
17247
  circuit
16357
17248
  }) {
16358
17249
  for (const utxo of [...inputs, ...outputs]) {
@@ -16402,7 +17293,7 @@ async function proveTransaction({
16402
17293
  const input = {
16403
17294
  root: proofRoot.toString(),
16404
17295
  publicAmount: publicAmount.toString(),
16405
- extDataHash: (await extDataHash(ext)).toString(),
17296
+ extDataHash: (extDataHashOverride ?? await extDataHash(ext)).toString(),
16406
17297
  mint: mintToField(ext.mint).toString(),
16407
17298
  inputNullifier: inputNullifiers.map(String),
16408
17299
  outputCommitment: outputCommitments.map(String),
@@ -16543,8 +17434,8 @@ function generateDepositParams(amount, mint = null) {
16543
17434
  if (value <= 0n) {
16544
17435
  throw new Error("veilix-sdk: deposit amount must be positive");
16545
17436
  }
16546
- const mintKey = mint && mint !== WRAPPED_SOL_MINT ? new PublicKey(mint) : null;
16547
- const note = encodeNote(new Utxo({ amount: value, mint: mintKey }));
17437
+ const mintKey2 = mint && mint !== WRAPPED_SOL_MINT ? new PublicKey(mint) : null;
17438
+ const note = encodeNote(new Utxo({ amount: value, mint: mintKey2 }));
16548
17439
  return { note, params: parseSecretNote(note) };
16549
17440
  }
16550
17441
  function to32ByteBuffer(value) {
@@ -16578,8 +17469,8 @@ function toPublicKey(value) {
16578
17469
  }
16579
17470
  function normalizeTreeMint(mint) {
16580
17471
  if (!mint) return null;
16581
- const key = toPublicKey(mint);
16582
- return key.equals(NATIVE_MINT) || key.equals(PublicKey.default) ? null : key;
17472
+ const key2 = toPublicKey(mint);
17473
+ return key2.equals(NATIVE_MINT) || key2.equals(PublicKey.default) ? null : key2;
16583
17474
  }
16584
17475
  function getTreePDA(mint) {
16585
17476
  const treeMint = normalizeTreeMint(mint);
@@ -16751,9 +17642,11 @@ async function buildDepositTx({
16751
17642
  onChainBackup = false,
16752
17643
  computeUnitPrice = 5e3,
16753
17644
  computeUnitLimit = DEPOSIT_COMPUTE_UNIT_LIMIT,
16754
- circuitArtifacts
17645
+ circuitArtifacts,
17646
+ encryptKey
16755
17647
  }) {
16756
17648
  const { connection } = getConfig();
17649
+ const sealKey = onChainBackup ? encryptKey ?? requireEncryptKey() : null;
16757
17650
  const sender = toPublicKey(senderPublicKey);
16758
17651
  const utxo = decodeNote(note);
16759
17652
  const mint = utxo.mint;
@@ -16766,7 +17659,7 @@ async function buildDepositTx({
16766
17659
  `veilix-sdk: deposit amount ${utxo.amount} exceeds the tree limit of ${tree.maxDepositAmount}`
16767
17660
  );
16768
17661
  }
16769
- const encryptedOutput1 = onChainBackup ? encryptNoteOutput(requireEncryptKey(), utxo) : new Uint8Array();
17662
+ const encryptedOutput1 = sealKey ? encryptNoteOutput(sealKey, utxo) : new Uint8Array();
16770
17663
  const encryptedOutput2 = new Uint8Array();
16771
17664
  const proved = await withCircuitArtifacts(
16772
17665
  circuitArtifacts,
@@ -16821,17 +17714,16 @@ async function buildInitNotesInstructionIfNeeded(sender) {
16821
17714
  if (await fetchNotesAccount(sender)) return null;
16822
17715
  return program.methods.initNotes().accountsPartial({ user: sender }).instruction();
16823
17716
  }
16824
- async function resolveEncryptKey() {
16825
- const config = getConfig();
17717
+ async function resolveEncryptKey(config) {
16826
17718
  if (!config.encryptKey) {
16827
17719
  config.encryptKey = await getEncryptionKey(config.wallet);
16828
17720
  }
16829
17721
  return config.encryptKey;
16830
17722
  }
16831
- async function buildBackupNotesInstruction(sender, notes) {
16832
- const { program } = getConfig();
16833
- const key = await resolveEncryptKey();
16834
- return program.methods.backupNotes(notes.map((note) => encryptData(key, note))).accountsPartial({ user: sender }).instruction();
17723
+ async function buildBackupNotesInstruction(sender, notes, config = getConfig()) {
17724
+ const { program } = config;
17725
+ const key2 = await resolveEncryptKey(config);
17726
+ return program.methods.backupNotes(notes.map((note) => encryptData(key2, note))).accountsPartial({ user: sender }).instruction();
16835
17727
  }
16836
17728
  async function isExtendBackupPdaNeeded(walletPubkey, newNotesLength) {
16837
17729
  const account = await fetchNotesAccount(walletPubkey);
@@ -16843,7 +17735,8 @@ function buildRequestHeapIx() {
16843
17735
  return ComputeBudgetProgram.requestHeapFrame({ bytes: 32 * 1024 });
16844
17736
  }
16845
17737
  async function buildBackupNotesTx(senderPublicKey, notes) {
16846
- const { connection } = getConfig();
17738
+ const config = getConfig();
17739
+ const { connection } = config;
16847
17740
  const sender = toPublicKey(senderPublicKey);
16848
17741
  const tx = new Transaction();
16849
17742
  const initIx = await buildInitNotesInstructionIfNeeded(sender);
@@ -16852,7 +17745,7 @@ async function buildBackupNotesTx(senderPublicKey, notes) {
16852
17745
  } else if (await isExtendBackupPdaNeeded(sender, notes.length)) {
16853
17746
  tx.add(buildRequestHeapIx());
16854
17747
  }
16855
- tx.add(await buildBackupNotesInstruction(sender, notes));
17748
+ tx.add(await buildBackupNotesInstruction(sender, notes, config));
16856
17749
  tx.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
16857
17750
  tx.feePayer = sender;
16858
17751
  return tx;
@@ -16936,16 +17829,16 @@ async function getEncryptionKey(wallet) {
16936
17829
  }
16937
17830
  return nacl.hash(signature).slice(0, 32);
16938
17831
  }
16939
- function encryptData(key, plaintext) {
17832
+ function encryptData(key2, plaintext) {
16940
17833
  const nonce = nacl.randomBytes(24);
16941
- const box = nacl.secretbox(new TextEncoder().encode(plaintext), nonce, key);
17834
+ const box = nacl.secretbox(new TextEncoder().encode(plaintext), nonce, key2);
16942
17835
  const combined = new Uint8Array(nonce.length + box.length);
16943
17836
  combined.set(nonce);
16944
17837
  combined.set(box, nonce.length);
16945
17838
  return Buffer.from(combined);
16946
17839
  }
16947
- function decryptData(key, combined) {
16948
- const decrypted = nacl.secretbox.open(combined.slice(24), combined.slice(0, 24), key);
17840
+ function decryptData(key2, combined) {
17841
+ const decrypted = nacl.secretbox.open(combined.slice(24), combined.slice(0, 24), key2);
16949
17842
  if (!decrypted) throw new Error("Decryption failed");
16950
17843
  return new TextDecoder().decode(decrypted);
16951
17844
  }
@@ -16983,8 +17876,8 @@ var COMMITMENTS_PAGE_LIMIT = 8e3;
16983
17876
  var VALIDATE_NULLIFIERS_BATCH = 64;
16984
17877
  async function indexerGet(path, params) {
16985
17878
  const query = new URLSearchParams();
16986
- for (const [key, value] of Object.entries(params)) {
16987
- if (value !== void 0 && value !== "") query.set(key, value);
17879
+ for (const [key2, value] of Object.entries(params)) {
17880
+ if (value !== void 0 && value !== "") query.set(key2, value);
16988
17881
  }
16989
17882
  const qs = query.toString();
16990
17883
  return httpFetch(`${getIndexerUrl()}${path}${qs ? `?${qs}` : ""}`, {
@@ -17199,7 +18092,7 @@ async function scanOwnedNotes({
17199
18092
  mints,
17200
18093
  includeSpent = false
17201
18094
  } = {}) {
17202
- const key = requireEncryptKey();
18095
+ const key2 = requireEncryptKey();
17203
18096
  const explicit = mints !== void 0;
17204
18097
  const tokenMints = getTokenMintsForNetwork(getConfig().network);
17205
18098
  const targets = mints ?? [null, tokenMints.Veilix, tokenMints.Bitcoin, tokenMints.Ethereum, tokenMints.USDC].filter(
@@ -17217,7 +18110,13 @@ async function scanOwnedNotes({
17217
18110
  }
17218
18111
  for (const leaf of leaves) {
17219
18112
  if (!leaf.encryptedOutput || leaf.encryptedOutput.length <= 2) continue;
17220
- const utxo = decryptNoteOutput(key, hexToBytes(leaf.encryptedOutput), treeMint, leaf.index);
18113
+ const utxo = decryptNoteOutput(
18114
+ key2,
18115
+ hexToBytes(leaf.encryptedOutput),
18116
+ treeMint,
18117
+ leaf.index,
18118
+ leaf.amountRaw ? BigInt(leaf.amountRaw) : null
18119
+ );
17221
18120
  if (!utxo || utxo.amount === 0n) continue;
17222
18121
  if (toHex32(utxo.commitment()) !== toHex32(BigInt(leaf.commitment))) continue;
17223
18122
  found.push({ utxo, note: encodeNote(utxo), signature: null });
@@ -17497,6 +18396,364 @@ async function getQuote(params) {
17497
18396
  }
17498
18397
  return data;
17499
18398
  }
18399
+ var SWAP_DOMAIN = new TextEncoder().encode("veilix:swap:v1");
18400
+ async function swapExtDataHash(ext) {
18401
+ const hash = await sha256(
18402
+ concatBytes([
18403
+ SWAP_DOMAIN,
18404
+ (ext.mintIn ?? PublicKey.default).toBytes(),
18405
+ (ext.mintOut ?? PublicKey.default).toBytes(),
18406
+ ext.relayer.toBytes(),
18407
+ u64le(ext.amountIn),
18408
+ u64le(ext.fee),
18409
+ u64le(ext.minAmountOut),
18410
+ bigintToBytes32(ext.outPubkey),
18411
+ bigintToBytes32(ext.outBlinding),
18412
+ u32le(ext.encryptedOutput1.length),
18413
+ ext.encryptedOutput1,
18414
+ u32le(ext.encryptedOutput2.length),
18415
+ ext.encryptedOutput2,
18416
+ u32le(ext.encryptedNote.length),
18417
+ ext.encryptedNote
18418
+ ])
18419
+ );
18420
+ hash[0] = 0;
18421
+ return bytesToBigint(hash);
18422
+ }
18423
+ var CPMM_PROGRAM_IDS = {
18424
+ devnet: "DRaycpLY18LhpbydsBWbVJtxpNv9oXPgjRSfpF2bWpYb",
18425
+ mainnet: "CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"
18426
+ };
18427
+ var FEE_RATE_DENOMINATOR = 1000000n;
18428
+ var SWAP_DISABLED_BIT = 2;
18429
+ var key = (data, offset) => new PublicKey(data.subarray(offset, offset + 32));
18430
+ var u64 = (data, offset) => new DataView(data.buffer, data.byteOffset + offset, 8).getBigUint64(0, true);
18431
+ var ceilDiv = (a, b) => (a + b - 1n) / b;
18432
+ var feeOf = (amount, rate) => ceilDiv(amount * rate, FEE_RATE_DENOMINATOR);
18433
+ async function quoteCpmm(connection, network, poolAddress, treeMintIn, treeMintOut, amountIn) {
18434
+ const programId = new PublicKey(CPMM_PROGRAM_IDS[network]);
18435
+ const poolInfo = await connection.getAccountInfo(poolAddress, "confirmed");
18436
+ if (!poolInfo || !poolInfo.owner.equals(programId) || poolInfo.data.length < 381) {
18437
+ throw new Error("veilix-sdk: swap pool is not a Raydium CPMM pool");
18438
+ }
18439
+ const data = poolInfo.data;
18440
+ const pool = {
18441
+ ammConfig: key(data, 8),
18442
+ vault0: key(data, 72),
18443
+ vault1: key(data, 104),
18444
+ mint0: key(data, 168),
18445
+ mint1: key(data, 200),
18446
+ status: data[329],
18447
+ protocolFees: [u64(data, 341), u64(data, 349)],
18448
+ fundFees: [u64(data, 357), u64(data, 365)],
18449
+ creatorFeeOn: data.length >= 413 ? data[389] : 0,
18450
+ enableCreatorFee: data.length >= 413 ? data[390] === 1 : false,
18451
+ creatorFees: data.length >= 413 ? [u64(data, 397), u64(data, 405)] : [0n, 0n]
18452
+ };
18453
+ if (pool.status >> SWAP_DISABLED_BIT & 1) {
18454
+ throw new Error("veilix-sdk: swaps are disabled on this pool");
18455
+ }
18456
+ const mintIn = treeMintIn ?? NATIVE_MINT;
18457
+ const mintOut = treeMintOut ?? NATIVE_MINT;
18458
+ let zeroForOne;
18459
+ if (pool.mint0.equals(mintIn) && pool.mint1.equals(mintOut)) zeroForOne = true;
18460
+ else if (pool.mint1.equals(mintIn) && pool.mint0.equals(mintOut)) zeroForOne = false;
18461
+ else throw new Error("veilix-sdk: swap pool does not trade this pair");
18462
+ const [i, o] = zeroForOne ? [0, 1] : [1, 0];
18463
+ const [configInfo, vaultIn, vaultOut] = await connection.getMultipleAccountsInfo(
18464
+ [pool.ammConfig, zeroForOne ? pool.vault0 : pool.vault1, zeroForOne ? pool.vault1 : pool.vault0],
18465
+ "confirmed"
18466
+ );
18467
+ if (!configInfo || !vaultIn || !vaultOut) {
18468
+ throw new Error("veilix-sdk: swap pool accounts are missing");
18469
+ }
18470
+ const tradeFeeRate = u64(configInfo.data, 12);
18471
+ const creatorFeeRate = pool.enableCreatorFee && configInfo.data.length >= 116 ? u64(configInfo.data, 108) : 0n;
18472
+ const reserveIn = u64(vaultIn.data, 64) - pool.protocolFees[i] - pool.fundFees[i] - pool.creatorFees[i];
18473
+ const reserveOut = u64(vaultOut.data, 64) - pool.protocolFees[o] - pool.fundFees[o] - pool.creatorFees[o];
18474
+ if (reserveIn <= 0n || reserveOut <= 0n) {
18475
+ throw new Error("veilix-sdk: swap pool has no liquidity");
18476
+ }
18477
+ const creatorOnInput = pool.creatorFeeOn === 0 || pool.creatorFeeOn === 1 && zeroForOne || pool.creatorFeeOn === 2 && !zeroForOne;
18478
+ let inLessFees = amountIn - feeOf(amountIn, tradeFeeRate);
18479
+ if (creatorOnInput) inLessFees -= feeOf(amountIn, creatorFeeRate);
18480
+ let amountOut = inLessFees * reserveOut / (reserveIn + inLessFees);
18481
+ if (!creatorOnInput) amountOut -= feeOf(amountOut, creatorFeeRate);
18482
+ if (amountOut <= 0n) {
18483
+ throw new Error("veilix-sdk: swap amount is too small for this pool");
18484
+ }
18485
+ const spotOut = Number(inLessFees) * (Number(reserveOut) / Number(reserveIn));
18486
+ const priceImpact = spotOut > 0 ? Math.max(0, 1 - Number(amountOut) / spotOut) : 1;
18487
+ return { amountOut, priceImpact };
18488
+ }
18489
+
18490
+ // src/swap/execute.ts
18491
+ var SWAP_MAX_WAIT_MS = 18e4;
18492
+ var DEFAULT_SLIPPAGE_BPS = 100;
18493
+ var MAX_SLIPPAGE_BPS = 5e3;
18494
+ var MAX_PRICE_IMPACT = 0.1;
18495
+ var hex = (bytes) => `0x${bytesToHex(bytes)}`;
18496
+ var mintKey = (mint) => mint?.toBase58() ?? null;
18497
+ async function fetchRelayerQuote(relayerUrl, mintIn, mintOut, amountIn) {
18498
+ const params = new URLSearchParams({ amountIn: amountIn.toString() });
18499
+ if (mintIn) params.set("mintIn", mintIn.toBase58());
18500
+ if (mintOut) params.set("mintOut", mintOut.toBase58());
18501
+ const base = relayerUrl.replace(/\/$/, "");
18502
+ const res = await httpFetch(`${base}/v1/swapQuote?${params}`, {
18503
+ headers: { Accept: "application/json" }
18504
+ });
18505
+ const body = await res.json().catch(() => ({}));
18506
+ if (!res.ok) {
18507
+ throw new Error(body.error || `Swap quote failed (${res.status})`);
18508
+ }
18509
+ return { ...body, relayerUrl: base };
18510
+ }
18511
+ function swapCandidates(relayers, relayerUrl) {
18512
+ if (relayerUrl) {
18513
+ const wanted = relayerUrl.replace(/\/$/, "");
18514
+ const match = relayers.find((r) => r.url.replace(/\/$/, "") === wanted);
18515
+ if (!match) throw new Error(`veilix-sdk: relayer ${relayerUrl} is not available`);
18516
+ return [match];
18517
+ }
18518
+ if (!relayers.length) throw new Error("veilix-sdk: no relayer available");
18519
+ const first = getRandomRelayer(relayers);
18520
+ return [first, ...relayers.filter((r) => r !== first)];
18521
+ }
18522
+ async function getSwapQuote(params) {
18523
+ const { relayers } = getConfig();
18524
+ const mintIn = normalizeTreeMint(params.mintIn);
18525
+ const mintOut = normalizeTreeMint(params.mintOut);
18526
+ if (mintKey(mintIn) === mintKey(mintOut)) {
18527
+ throw new Error("veilix-sdk: swap needs two different assets");
18528
+ }
18529
+ const amountIn = BigInt(params.amountIn);
18530
+ if (amountIn <= 0n) throw new Error("veilix-sdk: swap amount must be positive");
18531
+ const { connection, network } = getConfig();
18532
+ const platformWallets = await fetchPlatformFeeWallets();
18533
+ let lastError = null;
18534
+ for (const relayer of swapCandidates(relayers, params.relayerUrl)) {
18535
+ try {
18536
+ const quote = await fetchRelayerQuote(relayer.url, mintIn, mintOut, amountIn);
18537
+ if (quote.relayer !== relayer.value) {
18538
+ throw new Error("Relayer quoted for a different reward account");
18539
+ }
18540
+ const { fee } = computeWithdrawFee(amountIn, relayer.fee, platformWallets);
18541
+ if (fee >= amountIn) throw new Error("Amount is too small to cover the fees");
18542
+ if (BigInt(quote.fee) !== fee) throw new Error("Relayer quoted a different fee");
18543
+ if (quote.dexProgram !== CPMM_PROGRAM_IDS[network]) {
18544
+ throw new Error("Relayer routes through an unsupported DEX");
18545
+ }
18546
+ const own = await quoteCpmm(
18547
+ connection,
18548
+ network,
18549
+ new PublicKey(quote.pool),
18550
+ mintIn,
18551
+ mintOut,
18552
+ amountIn - fee
18553
+ );
18554
+ if (own.priceImpact > MAX_PRICE_IMPACT) {
18555
+ throw new Error(
18556
+ `Price impact ${(own.priceImpact * 100).toFixed(1)}% is too high for this pool; swap less`
18557
+ );
18558
+ }
18559
+ return {
18560
+ quote: {
18561
+ ...quote,
18562
+ swapIn: (amountIn - fee).toString(),
18563
+ amountOut: own.amountOut.toString(),
18564
+ priceImpact: own.priceImpact
18565
+ },
18566
+ relayer
18567
+ };
18568
+ } catch (error) {
18569
+ lastError = error;
18570
+ }
18571
+ }
18572
+ const reason = lastError instanceof Error ? lastError.message : "no relayer routes this pair";
18573
+ throw new Error(`veilix-sdk: no swap route for this pair (${reason})`);
18574
+ }
18575
+ async function buildSwapPayload(params, options = {}) {
18576
+ const { encryptKey } = getConfig();
18577
+ const utxo = decodeNote(params.note);
18578
+ const mintIn = utxo.mint;
18579
+ const mintOut = normalizeTreeMint(params.mintOut ?? null);
18580
+ const slippageBps = params.slippageBps ?? DEFAULT_SLIPPAGE_BPS;
18581
+ if (!Number.isInteger(slippageBps) || slippageBps < 0 || slippageBps > MAX_SLIPPAGE_BPS) {
18582
+ throw new Error(`veilix-sdk: slippageBps must be an integer between 0 and ${MAX_SLIPPAGE_BPS}`);
18583
+ }
18584
+ const { index } = await locateNote(utxo);
18585
+ if (index === null) {
18586
+ throw new Error("Note is not in the Veilix pool yet (deposit not confirmed or not indexed)");
18587
+ }
18588
+ utxo.index = index;
18589
+ if ((await validateNullifier(toHex32(utxo.nullifier()))).exists) {
18590
+ throw new Error("This note has already been spent");
18591
+ }
18592
+ const amountIn = params.amount === void 0 ? utxo.amount : BigInt(params.amount);
18593
+ if (amountIn <= 0n || amountIn > utxo.amount) {
18594
+ throw new Error(`Swap amount must be between 1 and ${utxo.amount}`);
18595
+ }
18596
+ const { quote, relayer } = await getSwapQuote({
18597
+ mintIn,
18598
+ mintOut,
18599
+ amountIn,
18600
+ relayerUrl: params.relayerUrl
18601
+ });
18602
+ const fee = BigInt(quote.fee);
18603
+ const minAmountOut = BigInt(quote.amountOut) * BigInt(1e4 - slippageBps) / 10000n;
18604
+ if (minAmountOut <= 0n) {
18605
+ throw new Error("Swap amount is too small for this pool");
18606
+ }
18607
+ let tree = options.tree;
18608
+ if (!tree || tree.elements.length <= index) {
18609
+ tree = await fetchAssetTree(mintKey(mintIn));
18610
+ }
18611
+ if (tree.elements.length <= index) {
18612
+ throw new Error("The indexer has not synced this note yet, retry shortly");
18613
+ }
18614
+ const change = utxo.amount - amountIn;
18615
+ const changeUtxo = change > 0n ? new Utxo({ amount: change, mint: mintIn }) : null;
18616
+ const encryptedOutput1 = changeUtxo && encryptKey ? encryptNoteOutput(encryptKey, changeUtxo) : new Uint8Array();
18617
+ const encryptedOutput2 = new Uint8Array();
18618
+ const outKeypair = VeilixKeypair.random();
18619
+ const outBlinding = randomFieldElement();
18620
+ const encryptedNote = encryptKey ? encryptSwapNoteOutput(encryptKey, outKeypair, outBlinding) : new Uint8Array();
18621
+ const relayerKey = new PublicKey(relayer.value);
18622
+ const hash = await swapExtDataHash({
18623
+ mintIn,
18624
+ mintOut,
18625
+ relayer: relayerKey,
18626
+ amountIn,
18627
+ fee,
18628
+ minAmountOut,
18629
+ outPubkey: outKeypair.pubKey,
18630
+ outBlinding,
18631
+ encryptedOutput1,
18632
+ encryptedOutput2,
18633
+ encryptedNote
18634
+ });
18635
+ const proved = await withCircuitArtifacts(
18636
+ options.circuitArtifacts,
18637
+ (artifacts) => proveTransaction({
18638
+ tree,
18639
+ inputs: [utxo],
18640
+ outputs: changeUtxo ? [changeUtxo] : [],
18641
+ ext: {
18642
+ mint: mintIn,
18643
+ recipient: PublicKey.default,
18644
+ relayer: relayerKey,
18645
+ extAmount: -amountIn,
18646
+ fee,
18647
+ encryptedOutput1,
18648
+ encryptedOutput2
18649
+ },
18650
+ extDataHashOverride: hash,
18651
+ circuit: artifacts
18652
+ })
18653
+ );
18654
+ const { proof } = proved;
18655
+ const payload = {
18656
+ proof: hex(proof.proof),
18657
+ root: hex(proof.root),
18658
+ inputNullifiers: [hex(proof.inputNullifiers[0]), hex(proof.inputNullifiers[1])],
18659
+ outputCommitments: [hex(proof.outputCommitments[0]), hex(proof.outputCommitments[1])],
18660
+ ...mintIn ? { mintIn: mintIn.toBase58() } : {},
18661
+ ...mintOut ? { mintOut: mintOut.toBase58() } : {},
18662
+ amountIn: amountIn.toString(),
18663
+ fee: fee.toString(),
18664
+ minAmountOut: minAmountOut.toString(),
18665
+ outPubkey: hex(bigintToBytes32(outKeypair.pubKey)),
18666
+ outBlinding: hex(bigintToBytes32(outBlinding)),
18667
+ relayer: relayerKey.toBase58(),
18668
+ encryptedOutput1: hex(encryptedOutput1),
18669
+ encryptedOutput2: hex(encryptedOutput2),
18670
+ encryptedNote: hex(encryptedNote)
18671
+ };
18672
+ return {
18673
+ payload,
18674
+ relayerUrl: quote.relayerUrl,
18675
+ quote,
18676
+ amountIn,
18677
+ fee,
18678
+ minAmountOut,
18679
+ changeNote: changeUtxo ? encodeNote(changeUtxo) : null,
18680
+ output: {
18681
+ mint: mintKey(mintOut),
18682
+ privKey: outKeypair.privKey.toString(),
18683
+ blinding: outBlinding.toString()
18684
+ },
18685
+ nullifiers: [...payload.inputNullifiers]
18686
+ };
18687
+ }
18688
+ async function pollSwapJob(relayerUrl, jobId, maxWaitMs) {
18689
+ const start = Date.now();
18690
+ while (Date.now() - start < maxWaitMs) {
18691
+ const res = await httpFetch(`${relayerUrl}/v1/jobs/${encodeURIComponent(jobId)}`, {
18692
+ headers: { Accept: "application/json" }
18693
+ });
18694
+ const job = await res.json().catch(() => ({}));
18695
+ if (!res.ok) throw new Error(job.error || "Failed to poll relayer job");
18696
+ if (job.status === "CONFIRMED" || job.status === "FAILED") return job;
18697
+ await new Promise((resolve) => setTimeout(resolve, 3e3));
18698
+ }
18699
+ throw new Error("Swap timed out");
18700
+ }
18701
+ function swapOutputNote(output, result) {
18702
+ const utxo = new Utxo({
18703
+ amount: BigInt(result.amountOut),
18704
+ keypair: VeilixKeypair.fromPrivateKey(output.privKey),
18705
+ blinding: BigInt(output.blinding),
18706
+ mint: output.mint ? new PublicKey(output.mint) : null,
18707
+ index: result.outputIndex
18708
+ });
18709
+ if (toHex32(utxo.commitment()) !== toHex32(BigInt(result.outputCommitment))) {
18710
+ throw new Error("veilix-sdk: swapped note does not match the on-chain commitment");
18711
+ }
18712
+ return encodeNote(utxo);
18713
+ }
18714
+ async function submitSwapPayload(bundle) {
18715
+ const res = await httpFetch(`${bundle.relayerUrl}/v1/veilixSwap`, {
18716
+ method: "POST",
18717
+ headers: { "Content-Type": "application/json" },
18718
+ body: JSON.stringify(bundle.payload)
18719
+ });
18720
+ const body = await res.json().catch(() => ({}));
18721
+ if (!res.ok || !body.id) {
18722
+ throw new Error(body.error || "Swap submission failed");
18723
+ }
18724
+ const job = await pollSwapJob(bundle.relayerUrl, body.id, SWAP_MAX_WAIT_MS);
18725
+ const base = {
18726
+ changeNote: bundle.changeNote,
18727
+ amountIn: bundle.amountIn.toString(),
18728
+ fee: bundle.fee.toString(),
18729
+ minAmountOut: bundle.minAmountOut.toString()
18730
+ };
18731
+ if (job.status === "FAILED") {
18732
+ return {
18733
+ ...base,
18734
+ txHash: job.txHash ?? "",
18735
+ status: "failed",
18736
+ error: job.failedReason || "Swap failed",
18737
+ // A failed swap spends nothing: the original note is still valid.
18738
+ outputNote: null,
18739
+ changeNote: null,
18740
+ amountOut: null
18741
+ };
18742
+ }
18743
+ if (!job.txHash || !job.swapResult) {
18744
+ throw new Error("Swap confirmed but the relayer did not report the swapped note");
18745
+ }
18746
+ return {
18747
+ ...base,
18748
+ txHash: job.txHash,
18749
+ status: "success",
18750
+ outputNote: swapOutputNote(bundle.output, job.swapResult),
18751
+ amountOut: job.swapResult.amountOut
18752
+ };
18753
+ }
18754
+ async function executeSwap(params) {
18755
+ return submitSwapPayload(await buildSwapPayload(params));
18756
+ }
17500
18757
 
17501
18758
  // src/withdraw/assets.ts
17502
18759
  var TOKEN_UNITS = {
@@ -17620,6 +18877,8 @@ var SEND_OPTIONS = { skipPreflight: false, maxRetries: 3 };
17620
18877
  var SUBMIT_MAX_PROOFS = 8;
17621
18878
  var NOTE_INDEX_TIMEOUT_MS = 12e4;
17622
18879
  var NOTE_INDEX_POLL_MS = 4e3;
18880
+ var SEND_ATTEMPTS = 4;
18881
+ var SEND_RETRY_MS = 2e3;
17623
18882
  function sleep(ms) {
17624
18883
  return new Promise((resolve) => setTimeout(resolve, ms));
17625
18884
  }
@@ -17641,7 +18900,18 @@ async function signTransactions(wallet, transactions) {
17641
18900
  }
17642
18901
  async function sendAndConfirm(signed) {
17643
18902
  const { connection } = getConfig();
17644
- const signature = await connection.sendRawTransaction(signed.serialize(), SEND_OPTIONS);
18903
+ const raw = signed.serialize();
18904
+ let signature;
18905
+ for (let attempt = 1; signature === void 0; attempt++) {
18906
+ try {
18907
+ signature = await connection.sendRawTransaction(raw, SEND_OPTIONS);
18908
+ } catch (error) {
18909
+ if (attempt >= SEND_ATTEMPTS || !/blockhash not found/i.test(errorMessage(error))) {
18910
+ throw error;
18911
+ }
18912
+ await sleep(SEND_RETRY_MS);
18913
+ }
18914
+ }
17645
18915
  const { value } = await connection.confirmTransaction(signature, "confirmed");
17646
18916
  if (value.err) {
17647
18917
  throw new Error(`Deposit transaction failed: ${JSON.stringify(value.err)}`);
@@ -17687,6 +18957,7 @@ async function executeVeilixTransfer(items, options = {}) {
17687
18957
  const { wallet, network, relayers, encryptKey } = getConfig();
17688
18958
  const sender = wallet.publicKey;
17689
18959
  const onChainBackup = options.onChainBackup ?? !!encryptKey;
18960
+ const sealKey = onChainBackup ? encryptKey ?? requireEncryptKey() : void 0;
17690
18961
  const prepared = prepareDeposits(items);
17691
18962
  result.notes = prepared.map((deposit) => deposit.note);
17692
18963
  const circuitArtifacts = await prepareWithdrawCircuitArtifacts();
@@ -17697,7 +18968,8 @@ async function executeVeilixTransfer(items, options = {}) {
17697
18968
  senderPublicKey: sender,
17698
18969
  note: deposit.note,
17699
18970
  onChainBackup,
17700
- circuitArtifacts
18971
+ circuitArtifacts,
18972
+ ...sealKey ? { encryptKey: sealKey } : {}
17701
18973
  });
17702
18974
  } catch (error) {
17703
18975
  result.depositFailed.push(toDepositFailure(deposit, error));
@@ -17708,6 +18980,10 @@ async function executeVeilixTransfer(items, options = {}) {
17708
18980
  result.error = true;
17709
18981
  return result;
17710
18982
  }
18983
+ const { blockhash } = await getConfig().connection.getLatestBlockhash();
18984
+ toSend.forEach((deposit) => {
18985
+ deposit.tx.message.recentBlockhash = blockhash;
18986
+ });
17711
18987
  const signed = await signTransactions(wallet, toSend.map((deposit) => deposit.tx));
17712
18988
  if (options.downloadNotes ?? true) {
17713
18989
  downloadNotesCsv(toSend.map((deposit) => deposit.note));
@@ -17811,7 +19087,7 @@ var VeilixSDK = class _VeilixSDK {
17811
19087
  try {
17812
19088
  return fn();
17813
19089
  } finally {
17814
- popRuntimeContext();
19090
+ popRuntimeContext(this.config);
17815
19091
  }
17816
19092
  }
17817
19093
  async runAsync(fn) {
@@ -17819,7 +19095,7 @@ var VeilixSDK = class _VeilixSDK {
17819
19095
  try {
17820
19096
  return await fn();
17821
19097
  } finally {
17822
- popRuntimeContext();
19098
+ popRuntimeContext(this.config);
17823
19099
  }
17824
19100
  }
17825
19101
  // ── Config ───────────────────────────────────────────────────────────
@@ -17937,6 +19213,26 @@ var VeilixSDK = class _VeilixSDK {
17937
19213
  submitWithdrawPayload(bundle) {
17938
19214
  return this.runAsync(() => submitWithdrawPayload(bundle));
17939
19215
  }
19216
+ // ── Private swap ─────────────────────────────────────────────────────
19217
+ /** Fee and expected output of swapping `amountIn` of `mintIn` into `mintOut`. */
19218
+ getSwapQuote(params) {
19219
+ return this.runAsync(() => getSwapQuote(params));
19220
+ }
19221
+ /**
19222
+ * Swap a note of asset A into a new shielded note of asset B (`mintOut`, `null` for
19223
+ * SOL) through a relayer and an allowlisted DEX. Funds never leave the pool
19224
+ * unshielded. Returns the asset-B note and any asset-A change note.
19225
+ */
19226
+ swap(params) {
19227
+ return this.runAsync(() => executeSwap(params));
19228
+ }
19229
+ /** Prove a swap without submitting it (see {@link submitSwapPayload}). */
19230
+ buildSwapPayload(params, options) {
19231
+ return this.runAsync(() => buildSwapPayload(params, options));
19232
+ }
19233
+ submitSwapPayload(bundle) {
19234
+ return this.runAsync(() => submitSwapPayload(bundle));
19235
+ }
17940
19236
  /**
17941
19237
  * Private transfer: deposit one note per item, then withdraw each note in full
17942
19238
  * to its recipient through the indexer submission queue.
@@ -18048,15 +19344,15 @@ var VeilixSDK = class _VeilixSDK {
18048
19344
  * Accepts a frontend wallet adapter (`signMessage`) or a backend {@link Keypair}.
18049
19345
  */
18050
19346
  async getEncryptionKey(wallet) {
18051
- const key = await getEncryptionKey(wallet);
18052
- this.config.encryptKey = key;
18053
- return key;
19347
+ const key2 = await getEncryptionKey(wallet);
19348
+ this.config.encryptKey = key2;
19349
+ return key2;
18054
19350
  }
18055
- encryptData(key, plaintext) {
18056
- return encryptData(key, plaintext);
19351
+ encryptData(key2, plaintext) {
19352
+ return encryptData(key2, plaintext);
18057
19353
  }
18058
- decryptData(key, combined) {
18059
- return decryptData(key, combined);
19354
+ decryptData(key2, combined) {
19355
+ return decryptData(key2, combined);
18060
19356
  }
18061
19357
  // ── Utilities ────────────────────────────────────────────────────────
18062
19358
  parseAmountToBaseUnits(amount, decimals) {