@veilo/sdk-core 0.3.3 → 0.5.0

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.
Files changed (251) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +289 -1262
  3. package/dist/cjs/accounts/admin.d.ts +84 -0
  4. package/dist/cjs/accounts/admin.js +208 -0
  5. package/dist/cjs/accounts/errors.d.ts +6 -0
  6. package/dist/cjs/accounts/errors.js +98 -0
  7. package/dist/cjs/accounts/index.d.ts +4 -0
  8. package/dist/cjs/accounts/index.js +20 -0
  9. package/dist/cjs/accounts/pdas.d.ts +23 -0
  10. package/dist/cjs/accounts/pdas.js +44 -0
  11. package/dist/cjs/accounts/queries.d.ts +41 -0
  12. package/dist/cjs/accounts/queries.js +95 -0
  13. package/dist/cjs/client.d.ts +2 -407
  14. package/dist/cjs/client.js +17 -912
  15. package/dist/cjs/cloak/client.d.ts +28 -0
  16. package/dist/cjs/cloak/client.js +68 -0
  17. package/dist/cjs/cloak/errors.d.ts +13 -0
  18. package/dist/cjs/cloak/errors.js +25 -0
  19. package/dist/cjs/cloak/helpers.d.ts +6 -0
  20. package/dist/cjs/cloak/helpers.js +35 -0
  21. package/dist/cjs/cloak/index.d.ts +6 -0
  22. package/dist/cjs/cloak/index.js +24 -0
  23. package/dist/cjs/cloak/polling.d.ts +7 -0
  24. package/dist/cjs/cloak/polling.js +66 -0
  25. package/dist/cjs/cloak/transport.d.ts +15 -0
  26. package/dist/cjs/cloak/transport.js +119 -0
  27. package/dist/cjs/cloak/types.d.ts +188 -0
  28. package/dist/cjs/cloak/types.js +5 -0
  29. package/dist/cjs/cloak.d.ts +1 -0
  30. package/dist/cjs/cloak.js +18 -0
  31. package/dist/cjs/compactNote.d.ts +128 -0
  32. package/dist/cjs/compactNote.js +191 -0
  33. package/dist/cjs/events.d.ts +1 -1
  34. package/dist/cjs/events.js +2 -2
  35. package/dist/cjs/idl/privacy_pool.d.ts +5 -0
  36. package/dist/cjs/idl/privacy_pool.js +15218 -0
  37. package/dist/cjs/index.d.ts +17 -13
  38. package/dist/cjs/index.js +43 -30
  39. package/dist/cjs/merkle.d.ts +13 -0
  40. package/dist/cjs/merkle.js +31 -8
  41. package/dist/cjs/notes/encryption.d.ts +41 -0
  42. package/dist/cjs/notes/encryption.js +75 -0
  43. package/dist/cjs/notes/index.d.ts +5 -0
  44. package/dist/cjs/notes/index.js +21 -0
  45. package/dist/cjs/notes/mailbox.d.ts +70 -0
  46. package/dist/cjs/notes/mailbox.js +164 -0
  47. package/dist/cjs/notes/model.d.ts +91 -0
  48. package/dist/cjs/notes/model.js +109 -0
  49. package/dist/cjs/notes/nullifier.d.ts +27 -0
  50. package/dist/cjs/notes/nullifier.js +45 -0
  51. package/dist/cjs/notes/recovery.d.ts +10 -0
  52. package/dist/cjs/notes/recovery.js +31 -0
  53. package/dist/cjs/program.d.ts +11 -0
  54. package/dist/cjs/program.js +26 -3
  55. package/dist/cjs/proof.d.ts +1 -183
  56. package/dist/cjs/proof.js +16 -290
  57. package/dist/cjs/proofs/encoding.d.ts +17 -0
  58. package/dist/cjs/proofs/encoding.js +72 -0
  59. package/dist/cjs/proofs/formatting.d.ts +6 -0
  60. package/dist/cjs/proofs/formatting.js +34 -0
  61. package/dist/cjs/proofs/index.d.ts +5 -0
  62. package/dist/cjs/proofs/index.js +21 -0
  63. package/dist/cjs/proofs/swap.d.ts +87 -0
  64. package/dist/cjs/proofs/swap.js +144 -0
  65. package/dist/cjs/proofs/transaction.d.ts +28 -0
  66. package/dist/cjs/proofs/transaction.js +110 -0
  67. package/dist/cjs/proofs/types.d.ts +70 -0
  68. package/dist/cjs/proofs/types.js +2 -0
  69. package/dist/cjs/prover.d.ts +4 -1
  70. package/dist/cjs/prover.js +12 -2
  71. package/dist/cjs/random.d.ts +16 -0
  72. package/dist/cjs/random.js +28 -0
  73. package/dist/cjs/relayer/client.d.ts +61 -0
  74. package/dist/cjs/relayer/client.js +151 -0
  75. package/dist/cjs/relayer/crypto.d.ts +5 -0
  76. package/dist/cjs/relayer/crypto.js +26 -0
  77. package/dist/cjs/relayer/encoding.d.ts +2 -0
  78. package/dist/cjs/relayer/encoding.js +23 -0
  79. package/dist/cjs/relayer/errors.d.ts +7 -0
  80. package/dist/cjs/relayer/errors.js +17 -0
  81. package/dist/cjs/relayer/index.d.ts +3 -0
  82. package/dist/cjs/relayer/index.js +19 -0
  83. package/dist/cjs/relayer/transport.d.ts +17 -0
  84. package/dist/cjs/relayer/transport.js +63 -0
  85. package/dist/cjs/relayer/types.d.ts +276 -0
  86. package/dist/cjs/relayer/types.js +5 -0
  87. package/dist/cjs/relayer.d.ts +1 -295
  88. package/dist/cjs/relayer.js +15 -243
  89. package/dist/cjs/shield/alt.d.ts +87 -0
  90. package/dist/cjs/shield/alt.js +194 -0
  91. package/dist/cjs/shield/computeBudget.d.ts +61 -0
  92. package/dist/cjs/shield/computeBudget.js +64 -0
  93. package/dist/cjs/shield/errors.d.ts +58 -0
  94. package/dist/cjs/shield/errors.js +121 -0
  95. package/dist/cjs/shield/finalize.d.ts +45 -0
  96. package/dist/cjs/shield/finalize.js +119 -0
  97. package/dist/cjs/shield/index.d.ts +35 -0
  98. package/dist/cjs/shield/index.js +68 -0
  99. package/dist/cjs/shield/ix.d.ts +54 -0
  100. package/dist/cjs/shield/ix.js +119 -0
  101. package/dist/cjs/shield/owner.d.ts +36 -0
  102. package/dist/cjs/shield/owner.js +127 -0
  103. package/dist/cjs/shield/ports.d.ts +43 -0
  104. package/dist/cjs/shield/ports.js +153 -0
  105. package/dist/cjs/shield/preflight.d.ts +30 -0
  106. package/dist/cjs/shield/preflight.js +154 -0
  107. package/dist/cjs/shield/shield.d.ts +68 -0
  108. package/dist/cjs/shield/shield.js +500 -0
  109. package/dist/cjs/shield/types.d.ts +202 -0
  110. package/dist/cjs/shield/types.js +2 -0
  111. package/dist/cjs/transactions/deposit.d.ts +94 -0
  112. package/dist/cjs/transactions/deposit.js +234 -0
  113. package/dist/cjs/transactions/index.d.ts +7 -0
  114. package/dist/cjs/transactions/index.js +26 -0
  115. package/dist/cjs/transactions/swap.d.ts +71 -0
  116. package/dist/cjs/transactions/swap.js +184 -0
  117. package/dist/cjs/transactions/transact.d.ts +34 -0
  118. package/dist/cjs/transactions/transact.js +146 -0
  119. package/dist/cjs/transactions/transfer.d.ts +51 -0
  120. package/dist/cjs/transactions/transfer.js +106 -0
  121. package/dist/cjs/transactions/withdraw.d.ts +52 -0
  122. package/dist/cjs/transactions/withdraw.js +104 -0
  123. package/dist/cjs/utxo.d.ts +1 -215
  124. package/dist/cjs/utxo.js +15 -391
  125. package/dist/esm/accounts/admin.d.ts +84 -0
  126. package/dist/esm/accounts/admin.js +165 -0
  127. package/dist/esm/accounts/errors.d.ts +6 -0
  128. package/dist/esm/accounts/errors.js +95 -0
  129. package/dist/esm/accounts/index.d.ts +4 -0
  130. package/dist/esm/accounts/index.js +4 -0
  131. package/dist/esm/accounts/pdas.d.ts +23 -0
  132. package/dist/esm/accounts/pdas.js +38 -0
  133. package/dist/esm/accounts/queries.d.ts +41 -0
  134. package/dist/esm/accounts/queries.js +88 -0
  135. package/dist/esm/client.d.ts +2 -0
  136. package/dist/esm/client.js +3 -887
  137. package/dist/esm/cloak/client.d.ts +28 -0
  138. package/dist/esm/cloak/client.js +64 -0
  139. package/dist/esm/cloak/errors.d.ts +13 -0
  140. package/dist/esm/cloak/errors.js +21 -0
  141. package/dist/esm/cloak/helpers.d.ts +6 -0
  142. package/dist/esm/cloak/helpers.js +31 -0
  143. package/dist/esm/cloak/index.d.ts +6 -0
  144. package/dist/esm/cloak/index.js +6 -0
  145. package/dist/esm/cloak/polling.d.ts +7 -0
  146. package/dist/esm/cloak/polling.js +63 -0
  147. package/dist/esm/cloak/transport.d.ts +15 -0
  148. package/dist/esm/cloak/transport.js +115 -0
  149. package/dist/esm/cloak/types.d.ts +188 -0
  150. package/dist/esm/cloak/types.js +4 -0
  151. package/dist/esm/cloak.d.ts +1 -0
  152. package/dist/esm/cloak.js +2 -0
  153. package/dist/esm/compactNote.d.ts +128 -0
  154. package/dist/esm/compactNote.js +179 -0
  155. package/dist/esm/config.d.ts +82 -0
  156. package/dist/esm/events.d.ts +77 -0
  157. package/dist/esm/events.js +1 -1
  158. package/dist/esm/idl/privacy_pool.d.ts +5 -0
  159. package/dist/esm/idl/privacy_pool.js +15216 -0
  160. package/dist/esm/index.d.ts +17 -0
  161. package/dist/esm/index.js +20 -11
  162. package/dist/esm/merkle.d.ts +77 -0
  163. package/dist/esm/merkle.js +23 -1
  164. package/dist/esm/notes/encryption.d.ts +41 -0
  165. package/dist/esm/notes/encryption.js +67 -0
  166. package/dist/esm/notes/index.d.ts +5 -0
  167. package/dist/esm/notes/index.js +5 -0
  168. package/dist/esm/notes/mailbox.d.ts +70 -0
  169. package/dist/esm/notes/mailbox.js +154 -0
  170. package/dist/esm/notes/model.d.ts +91 -0
  171. package/dist/esm/notes/model.js +99 -0
  172. package/dist/esm/notes/nullifier.d.ts +27 -0
  173. package/dist/esm/notes/nullifier.js +40 -0
  174. package/dist/esm/notes/recovery.d.ts +10 -0
  175. package/dist/esm/notes/recovery.js +28 -0
  176. package/dist/esm/package.json +1 -0
  177. package/dist/esm/poseidon.d.ts +29 -0
  178. package/dist/esm/program.d.ts +37 -0
  179. package/dist/esm/program.js +23 -1
  180. package/dist/esm/proof.d.ts +1 -0
  181. package/dist/esm/proof.js +2 -281
  182. package/dist/esm/proofs/encoding.d.ts +17 -0
  183. package/dist/esm/proofs/encoding.js +68 -0
  184. package/dist/esm/proofs/formatting.d.ts +6 -0
  185. package/dist/esm/proofs/formatting.js +31 -0
  186. package/dist/esm/proofs/index.d.ts +5 -0
  187. package/dist/esm/proofs/index.js +5 -0
  188. package/dist/esm/proofs/swap.d.ts +87 -0
  189. package/dist/esm/proofs/swap.js +138 -0
  190. package/dist/esm/proofs/transaction.d.ts +28 -0
  191. package/dist/esm/proofs/transaction.js +105 -0
  192. package/dist/esm/proofs/types.d.ts +70 -0
  193. package/dist/esm/proofs/types.js +1 -0
  194. package/dist/esm/prover.d.ts +57 -0
  195. package/dist/esm/prover.js +10 -1
  196. package/dist/esm/random.d.ts +16 -0
  197. package/dist/esm/random.js +21 -0
  198. package/dist/esm/relayer/client.d.ts +61 -0
  199. package/dist/esm/relayer/client.js +144 -0
  200. package/dist/esm/relayer/crypto.d.ts +5 -0
  201. package/dist/esm/relayer/crypto.js +20 -0
  202. package/dist/esm/relayer/encoding.d.ts +2 -0
  203. package/dist/esm/relayer/encoding.js +19 -0
  204. package/dist/esm/relayer/errors.d.ts +7 -0
  205. package/dist/esm/relayer/errors.js +13 -0
  206. package/dist/esm/relayer/index.d.ts +3 -0
  207. package/dist/esm/relayer/index.js +3 -0
  208. package/dist/esm/relayer/transport.d.ts +17 -0
  209. package/dist/esm/relayer/transport.js +59 -0
  210. package/dist/esm/relayer/types.d.ts +276 -0
  211. package/dist/esm/relayer/types.js +4 -0
  212. package/dist/esm/relayer.d.ts +1 -0
  213. package/dist/esm/relayer.js +2 -238
  214. package/dist/esm/retry.d.ts +32 -0
  215. package/dist/esm/shield/alt.d.ts +87 -0
  216. package/dist/esm/shield/alt.js +186 -0
  217. package/dist/esm/shield/computeBudget.d.ts +61 -0
  218. package/dist/esm/shield/computeBudget.js +61 -0
  219. package/dist/esm/shield/errors.d.ts +58 -0
  220. package/dist/esm/shield/errors.js +115 -0
  221. package/dist/esm/shield/finalize.d.ts +45 -0
  222. package/dist/esm/shield/finalize.js +83 -0
  223. package/dist/esm/shield/index.d.ts +35 -0
  224. package/dist/esm/shield/index.js +32 -0
  225. package/dist/esm/shield/ix.d.ts +54 -0
  226. package/dist/esm/shield/ix.js +82 -0
  227. package/dist/esm/shield/owner.d.ts +36 -0
  228. package/dist/esm/shield/owner.js +123 -0
  229. package/dist/esm/shield/ports.d.ts +43 -0
  230. package/dist/esm/shield/ports.js +147 -0
  231. package/dist/esm/shield/preflight.d.ts +30 -0
  232. package/dist/esm/shield/preflight.js +151 -0
  233. package/dist/esm/shield/shield.d.ts +68 -0
  234. package/dist/esm/shield/shield.js +493 -0
  235. package/dist/esm/shield/types.d.ts +202 -0
  236. package/dist/esm/shield/types.js +1 -0
  237. package/dist/esm/transactions/deposit.d.ts +94 -0
  238. package/dist/esm/transactions/deposit.js +198 -0
  239. package/dist/esm/transactions/index.d.ts +7 -0
  240. package/dist/esm/transactions/index.js +7 -0
  241. package/dist/esm/transactions/swap.d.ts +71 -0
  242. package/dist/esm/transactions/swap.js +144 -0
  243. package/dist/esm/transactions/transact.d.ts +34 -0
  244. package/dist/esm/transactions/transact.js +110 -0
  245. package/dist/esm/transactions/transfer.d.ts +51 -0
  246. package/dist/esm/transactions/transfer.js +103 -0
  247. package/dist/esm/transactions/withdraw.d.ts +52 -0
  248. package/dist/esm/transactions/withdraw.js +101 -0
  249. package/dist/esm/utxo.d.ts +1 -0
  250. package/dist/esm/utxo.js +2 -372
  251. package/package.json +111 -15
@@ -1,914 +1,19 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
2
16
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPoolPdas = getPoolPdas;
4
- exports.getNoteTreePda = getNoteTreePda;
5
- exports.getGlobalConfigPda = getGlobalConfigPda;
6
- exports.getNullifierMarkerPda = getNullifierMarkerPda;
7
- exports.fetchPoolConfig = fetchPoolConfig;
8
- exports.checkNullifierSpent = checkNullifierSpent;
9
- exports.getTreeInfo = getTreeInfo;
10
- exports.getAllTreeInfo = getAllTreeInfo;
11
- exports.getBestTreeForDeposit = getBestTreeForDeposit;
12
- exports.parseOnChainError = parseOnChainError;
13
- exports.initializeGlobalConfig = initializeGlobalConfig;
14
- exports.initializePool = initializePool;
15
- exports.updatePoolConfig = updatePoolConfig;
16
- exports.addMerkleTree = addMerkleTree;
17
- exports.getPoolConfig = getPoolConfig;
18
- exports.addRelayer = addRelayer;
19
- exports.setPaused = setPaused;
20
- exports.transact = transact;
21
- exports.deposit = deposit;
22
- exports.withdraw = withdraw;
23
- exports.privateTransfer = privateTransfer;
24
- exports.updateGlobalConfig = updateGlobalConfig;
25
- exports.getSwapExecutorPda = getSwapExecutorPda;
26
- exports.fundNativeSource = fundNativeSource;
27
- exports.transactSwap = transactSwap;
28
- const anchor_1 = require("@coral-xyz/anchor");
29
- const web3_js_1 = require("@solana/web3.js");
30
- const spl_token_1 = require("@solana/spl-token");
31
- const proof_1 = require("./proof");
32
- const utxo_1 = require("./utxo");
33
- const config_1 = require("./config");
34
- const retry_1 = require("./retry");
35
- // -----------------------------------------------------------------------------
36
- // PDA Helpers
37
- // -----------------------------------------------------------------------------
38
- /**
39
- * Get pool PDAs for a given mint address.
40
- * Note: All seeds use "v3" suffix.
41
- */
42
- function getPoolPdas(programId, mintAddress) {
43
- const [config] = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("privacy_config_v3"), mintAddress.toBuffer()], programId);
44
- const [vault] = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("privacy_vault_v3"), mintAddress.toBuffer()], programId);
45
- const [nullifiers] = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("privacy_nullifiers_v3"), mintAddress.toBuffer()], programId);
46
- return { config, vault, nullifiers };
47
- }
48
- /**
49
- * Get the note tree PDA for a specific tree ID.
50
- */
51
- function getNoteTreePda(programId, mintAddress, treeId) {
52
- const treeIdBuffer = Buffer.alloc(2);
53
- treeIdBuffer.writeUInt16LE(treeId);
54
- const [noteTree] = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("privacy_note_tree_v3"), mintAddress.toBuffer(), treeIdBuffer], programId);
55
- return noteTree;
56
- }
57
- /**
58
- * Get the global config PDA.
59
- */
60
- function getGlobalConfigPda(programId) {
61
- const [globalConfig] = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("global_config_v1")], programId);
62
- return globalConfig;
63
- }
64
- /**
65
- * Get the nullifier marker PDA for a specific nullifier.
66
- * NOTE: Nullifier markers are global (no tree_id) to prevent cross-tree double-spend.
67
- */
68
- function getNullifierMarkerPda(programId, mintAddress, nullifier) {
69
- const [marker] = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("nullifier_v3"), mintAddress.toBuffer(), nullifier], programId);
70
- return marker;
71
- }
72
- // -----------------------------------------------------------------------------
73
- // On-Chain Account Fetchers
74
- // -----------------------------------------------------------------------------
75
- /**
76
- * Fetch and decode the on-chain PrivacyConfig account for a pool.
77
- */
78
- async function fetchPoolConfig(program, mintAddress) {
79
- const { config } = getPoolPdas(program.programId, mintAddress);
80
- return program.account.privacyConfig.fetch(config);
81
- }
82
- /**
83
- * Check whether a nullifier has been spent on-chain.
84
- * Returns true if the nullifier marker PDA exists (funds already spent).
85
- */
86
- async function checkNullifierSpent(program, mintAddress, nullifier) {
87
- const marker = getNullifierMarkerPda(program.programId, mintAddress, nullifier);
88
- const info = await program.provider.connection.getAccountInfo(marker);
89
- return info !== null;
90
- }
91
- const TREE_CAPACITY = Math.pow(2, 22); // 4,194,304 leaves (depth 22)
92
- /**
93
- * Fetch utilization info for a specific tree.
94
- * Returns null if the tree does not exist yet.
95
- */
96
- async function getTreeInfo(program, mintAddress, treeId) {
97
- try {
98
- const treePDA = getNoteTreePda(program.programId, mintAddress, treeId);
99
- const tree = await program.account.merkleTreeAccount.fetch(treePDA);
100
- const leafCount = Number(tree.nextIndex);
101
- const remainingCapacity = TREE_CAPACITY - leafCount;
102
- return {
103
- treeId,
104
- leafCount,
105
- capacity: TREE_CAPACITY,
106
- utilizationPercent: (leafCount / TREE_CAPACITY) * 100,
107
- remainingCapacity,
108
- isFull: leafCount >= TREE_CAPACITY,
109
- treePDA,
110
- };
111
- }
112
- catch {
113
- return null;
114
- }
115
- }
116
- /**
117
- * Fetch utilization info for all trees in a pool.
118
- */
119
- async function getAllTreeInfo(program, mintAddress) {
120
- try {
121
- const { config } = getPoolPdas(program.programId, mintAddress);
122
- const cfg = await program.account.privacyConfig.fetch(config);
123
- const numTrees = Number(cfg.numTrees);
124
- const results = [];
125
- for (let id = 0; id < numTrees; id++) {
126
- const info = await getTreeInfo(program, mintAddress, id);
127
- if (info)
128
- results.push(info);
129
- }
130
- return results;
131
- }
132
- catch {
133
- return [];
134
- }
135
- }
136
- /**
137
- * Find the best tree to deposit into.
138
- *
139
- * Strategy (matches veilo-dapp):
140
- * 1. Discard full trees.
141
- * 2. Prefer the LOWEST tree ID with remaining capacity ≥ minCapacity (default 0.01%).
142
- * 3. Ensures trees fill sequentially: 0 → 1 → 2 → …
143
- * 4. Fallback to the tree with the most remaining capacity.
144
- */
145
- async function getBestTreeForDeposit(program, mintAddress, minCapacity = Math.floor(TREE_CAPACITY * 0.0001)) {
146
- const trees = await getAllTreeInfo(program, mintAddress);
147
- const available = trees.filter((t) => !t.isFull);
148
- if (available.length === 0)
149
- return null;
150
- // Prefer lowest-id tree that still has meaningful capacity
151
- const preferred = available
152
- .filter((t) => t.remainingCapacity >= minCapacity)
153
- .sort((a, b) => a.treeId - b.treeId);
154
- if (preferred.length > 0)
155
- return preferred[0];
156
- // Fallback: most remaining capacity
157
- return available.sort((a, b) => b.remainingCapacity - a.remainingCapacity)[0];
158
- }
159
- // -----------------------------------------------------------------------------
160
- // Error Parsing
161
- // -----------------------------------------------------------------------------
162
- /**
163
- * Convert a Solana/Anchor transaction error into a user-friendly message.
164
- * Maps privacy_pool program error codes (6000–6060) to readable strings.
165
- * Mirrors relayer-server/src/controllers/transaction.helpers.ts `parseOnChainError`.
166
- */
167
- function parseOnChainError(error) {
168
- const raw = (error?.message ?? error?.toString() ?? "").toLowerCase();
169
- const hexMatch = raw.match(/custom program error:\s*0x([0-9a-f]+)/);
170
- const numMatch = raw.match(/error number:\s*(\d+)/);
171
- const code = hexMatch
172
- ? parseInt(hexMatch[1], 16)
173
- : numMatch
174
- ? parseInt(numMatch[1], 10)
175
- : null;
176
- const PROGRAM_ERRORS = {
177
- 6000: "The pool is temporarily paused. Please try again later.",
178
- 6001: "No denominations configured for this pool.",
179
- 6002: "Too many denominations configured.",
180
- 6003: "Bad denomination index.",
181
- 6004: "Math overflow in the contract. Please try again.",
182
- 6005: "These funds have already been spent.",
183
- 6006: "The nullifier table is full. Please contact support.",
184
- 6007: "The relayer is out of sync with the network. Please wait a moment and try again.",
185
- 6008: "This relayer is not authorised for this pool.",
186
- 6009: "The pool does not have enough funds to fulfil this request.",
187
- 6010: "Too many relayers registered for this pool.",
188
- 6011: "Proof encoding is invalid. Please try again.",
189
- 6012: "Zero-knowledge proof verification failed. Please try again.",
190
- 6013: "The pool is at capacity. Please try again later.",
191
- 6014: "Merkle hash computation failed. Please try again.",
192
- 6015: "Transaction data mismatch. Please refresh and try again.",
193
- 6016: "Recipient address mismatch.",
194
- 6017: "Invalid token address.",
195
- 6018: "The fee exceeds the allowed limit.",
196
- 6019: "The relayer fee was insufficient. Please try again.",
197
- 6020: "Arithmetic error in the contract. Please try again.",
198
- 6021: "Your balance is not enough to cover the withdrawal including network fees.",
199
- 6022: "Your balance is not enough to cover the fee.",
200
- 6023: "Invalid transaction amount. Please try again.",
201
- 6024: "Invalid fee amount. Please try again.",
202
- 6025: "Duplicate fund inputs detected. Please refresh and try again.",
203
- 6026: "Duplicate output detected. Please refresh and try again.",
204
- 6027: "Token account required for SPL token operations.",
205
- 6028: "Token program required for SPL token operations.",
206
- 6029: "Invalid token account authority.",
207
- 6030: "Relayer account does not match the expected relayer.",
208
- 6031: "Relayer token account not owned by the expected relayer.",
209
- 6032: "Recipient token account not owned by the expected recipient.",
210
- 6033: "Depositor token account not owned or delegated to the relayer.",
211
- 6034: "Private transfers must have zero fee and refund.",
212
- 6035: "Amount is below the pool minimum.",
213
- 6036: "Amount exceeds the pool maximum.",
214
- 6037: "Withdrawal amount is below the pool minimum.",
215
- 6038: "Withdrawal amount exceeds the pool maximum.",
216
- 6039: "Invalid pool configuration: minimum exceeds maximum.",
217
- 6040: "Fee basis points exceed the maximum allowed (1%).",
218
- 6041: "Fee error margin exceeds the maximum allowed (50%).",
219
- 6042: "Only the authorized admin can initialize.",
220
- 6043: "Unauthorized: only admin or relayers can perform this action.",
221
- 6044: "Invalid tree ID: tree does not exist.",
222
- 6045: "Maximum number of Merkle trees reached for this pool.",
223
- 6046: "Deposits must use zero nullifiers (no notes consumed).",
224
- 6047: "Nullifier cannot be zero for withdrawals or transfers.",
225
- 6048: "Output commitment cannot be zero.",
226
- 6049: "Token account must be owned by SPL Token Program.",
227
- 6050: "Vault token account must be the canonical Associated Token Account.",
228
- 6051: "Amount is too small to cover the minimum fee. Try a larger amount.",
229
- 6052: "Nullifier marker account does not correspond to zero nullifier for deposits.",
230
- 6053: "Insufficient token delegation for deposit.",
231
- 6054: "Invalid swap program. Please try again.",
232
- 6055: "Invalid swap accounts. Please refresh and try again.",
233
- 6056: "Jupiter swap requires additional routing accounts.",
234
- 6057: "Swap instruction is invalid or unsupported. Please try again.",
235
- 6058: "Swap parameters are inconsistent. Please refresh and try again.",
236
- 6059: "Missing required swap instructions in transaction. Both fund_native_source and transact_swap must be present.",
237
- 6060: "The transaction deadline expired. Please try again.",
238
- };
239
- if (code !== null && PROGRAM_ERRORS[code])
240
- return PROGRAM_ERRORS[code];
241
- if (raw.includes("blockhash not found") ||
242
- raw.includes("block height exceeded"))
243
- return "The transaction expired before it could be confirmed. Please try again.";
244
- if (raw.includes("insufficient funds") ||
245
- raw.includes("insufficient lamports"))
246
- return "Insufficient SOL to pay for the transaction fee.";
247
- if (raw.includes("timeout") || raw.includes("timed out"))
248
- return "The request timed out. Please try again.";
249
- if (raw.includes("simulation failed"))
250
- return "Transaction simulation failed. Please refresh and try again.";
251
- return "The transaction could not be completed. Your funds are safe — please try again.";
252
- }
253
- // -----------------------------------------------------------------------------
254
- // Global Config Initialization
255
- // -----------------------------------------------------------------------------
256
- /**
257
- * Initialize the global config (one-time setup).
258
- */
259
- async function initializeGlobalConfig(params) {
260
- const { program, admin, payer } = params;
261
- const globalConfig = getGlobalConfigPda(program.programId);
262
- await program.methods
263
- .initializeGlobalConfig()
264
- .accounts({
265
- globalConfig,
266
- admin: admin.publicKey,
267
- payer: payer.publicKey,
268
- systemProgram: web3_js_1.SystemProgram.programId,
269
- })
270
- .signers([payer])
271
- .rpc();
272
- }
273
- // -----------------------------------------------------------------------------
274
- // Pool Initialization
275
- // -----------------------------------------------------------------------------
276
- /**
277
- * Initialize a privacy pool with the new parameters.
278
- * Creates the first merkle tree (tree ID 0).
279
- */
280
- async function initializePool(params) {
281
- const { program, admin, payer, feeBps, mintAddress, minDepositAmount, maxDepositAmount, minWithdrawAmount, maxWithdrawAmount, } = params;
282
- const { config, vault, nullifiers } = getPoolPdas(program.programId, mintAddress);
283
- const noteTree = getNoteTreePda(program.programId, mintAddress, 0);
284
- await program.methods
285
- .initialize(feeBps, mintAddress, minDepositAmount ? new anchor_1.BN(minDepositAmount.toString()) : null, maxDepositAmount ? new anchor_1.BN(maxDepositAmount.toString()) : null, minWithdrawAmount ? new anchor_1.BN(minWithdrawAmount.toString()) : null, maxWithdrawAmount ? new anchor_1.BN(maxWithdrawAmount.toString()) : null)
286
- .accounts({
287
- config,
288
- vault,
289
- noteTree,
290
- nullifiers,
291
- admin: admin.publicKey,
292
- payer: payer.publicKey,
293
- systemProgram: web3_js_1.SystemProgram.programId,
294
- })
295
- .signers([payer])
296
- .rpc();
297
- }
298
- // -----------------------------------------------------------------------------
299
- // Pool Config Updates
300
- // -----------------------------------------------------------------------------
301
- /**
302
- * Update pool configuration.
303
- */
304
- async function updatePoolConfig(params) {
305
- const { program, admin, mintAddress, minDepositAmount, maxDepositAmount, minWithdrawAmount, maxWithdrawAmount, feeBps, feeErrorMarginBps, minWithdrawalFee, minSwapFee, swapFeeBps, } = params;
306
- const { config } = getPoolPdas(program.programId, mintAddress);
307
- await program.methods
308
- .updatePoolConfig(mintAddress, minDepositAmount ? new anchor_1.BN(minDepositAmount.toString()) : null, maxDepositAmount ? new anchor_1.BN(maxDepositAmount.toString()) : null, minWithdrawAmount ? new anchor_1.BN(minWithdrawAmount.toString()) : null, maxWithdrawAmount ? new anchor_1.BN(maxWithdrawAmount.toString()) : null, feeBps != null ? new anchor_1.BN(feeBps) : null, minWithdrawalFee ? new anchor_1.BN(minWithdrawalFee.toString()) : null, feeErrorMarginBps != null ? new anchor_1.BN(feeErrorMarginBps) : null, minSwapFee ? new anchor_1.BN(minSwapFee.toString()) : null, swapFeeBps != null ? new anchor_1.BN(swapFeeBps) : null)
309
- .accounts({
310
- config,
311
- admin: admin.publicKey,
312
- })
313
- .rpc();
314
- }
315
- /**
316
- * Add a new Merkle tree to the pool.
317
- * The treeId must equal the current num_trees value in the pool config.
318
- */
319
- async function addMerkleTree(params) {
320
- const { program, relayer, mintAddress, treeId } = params;
321
- const { config } = getPoolPdas(program.programId, mintAddress);
322
- const noteTree = getNoteTreePda(program.programId, mintAddress, treeId);
323
- await program.methods
324
- .addMerkleTree(mintAddress, treeId)
325
- .accounts({
326
- config,
327
- noteTree,
328
- relayer: relayer.publicKey,
329
- systemProgram: web3_js_1.SystemProgram.programId,
330
- })
331
- .signers([relayer])
332
- .rpc();
333
- }
334
- /**
335
- * Get the pool configuration account.
336
- */
337
- async function getPoolConfig(program, mintAddress) {
338
- const { config } = getPoolPdas(program.programId, mintAddress);
339
- const account = await program.account.privacyConfig.fetch(config);
340
- return {
341
- bump: account.bump,
342
- vaultBump: account.vaultBump,
343
- admin: account.admin,
344
- feeBps: account.feeBps,
345
- feeErrorMarginBps: account.feeErrorMarginBps,
346
- minWithdrawalFee: BigInt(account.minWithdrawalFee.toString()),
347
- minSwapFee: account.minSwapFee != null ? BigInt(account.minSwapFee.toString()) : 0n,
348
- swapFeeBps: account.swapFeeBps ?? 0,
349
- totalTvl: BigInt(account.totalTvl.toString()),
350
- mintAddress: account.mintAddress,
351
- minDepositAmount: BigInt(account.minDepositAmount.toString()),
352
- maxDepositAmount: BigInt(account.maxDepositAmount.toString()),
353
- minWithdrawAmount: BigInt(account.minWithdrawAmount.toString()),
354
- maxWithdrawAmount: BigInt(account.maxWithdrawAmount.toString()),
355
- numRelayers: account.numRelayers,
356
- relayers: account.relayers,
357
- numTrees: account.numTrees,
358
- nextTreeIndex: account.nextTreeIndex,
359
- };
360
- }
361
- // -----------------------------------------------------------------------------
362
- // Relayer Management
363
- // -----------------------------------------------------------------------------
364
- /**
365
- * Add a relayer to the pool.
366
- */
367
- async function addRelayer(params) {
368
- const { program, admin, mintAddress, newRelayer } = params;
369
- const { config } = getPoolPdas(program.programId, mintAddress);
370
- await program.methods
371
- .addRelayer(mintAddress, newRelayer)
372
- .accounts({
373
- config,
374
- admin: admin.publicKey,
375
- })
376
- .rpc();
377
- }
378
- // -----------------------------------------------------------------------------
379
- // Pause/Unpause
380
- // -----------------------------------------------------------------------------
381
- /**
382
- * Set the paused state of a pool.
383
- */
384
- async function setPaused(params) {
385
- const { program, admin, mintAddress, paused } = params;
386
- const { config } = getPoolPdas(program.programId, mintAddress);
387
- await program.methods
388
- .setPaused(mintAddress, paused)
389
- .accounts({
390
- config,
391
- admin: admin.publicKey,
392
- })
393
- .rpc();
394
- }
395
- // -----------------------------------------------------------------------------
396
- // Main Transaction Instruction
397
- // -----------------------------------------------------------------------------
398
- /**
399
- * Execute a transaction on the privacy pool.
400
- * This is the low-level function that calls the on-chain `transact` instruction.
401
- *
402
- * @param publicAmount - Positive for deposits, negative for withdrawals, 0 for transfers
403
- * @param inputTreeId - The tree ID where input UTXOs are located
404
- * @param outputTreeId - The tree ID where output commitments will be inserted
405
- */
406
- async function transact(params) {
407
- const { program, relayer, recipient, mintAddress, root, inputTreeId, outputTreeId, publicAmount, inputNullifiers, outputCommitments, extData, proof, deadline = 0n, vaultTokenAccount, userTokenAccount, recipientTokenAccount, relayerTokenAccount, } = params;
408
- const { config, vault, nullifiers } = getPoolPdas(program.programId, mintAddress);
409
- const globalConfig = getGlobalConfigPda(program.programId);
410
- const inputTree = getNoteTreePda(program.programId, mintAddress, inputTreeId);
411
- const outputTree = getNoteTreePda(program.programId, mintAddress, outputTreeId);
412
- // Nullifier markers are global (no tree_id) to prevent cross-tree double-spend
413
- const nullifierMarker0 = getNullifierMarkerPda(program.programId, mintAddress, inputNullifiers[0]);
414
- const nullifierMarker1 = getNullifierMarkerPda(program.programId, mintAddress, inputNullifiers[1]);
415
- const extDataHash = (0, proof_1.computeExtDataHash)(extData);
416
- const isNativeSol = mintAddress.equals(config_1.NATIVE_SOL_MINT);
417
- // For SPL tokens, resolve token accounts
418
- let vaultTA = vaultTokenAccount;
419
- let userTA = userTokenAccount;
420
- let recipientTA = recipientTokenAccount;
421
- let relayerTA = relayerTokenAccount;
422
- if (!isNativeSol) {
423
- if (!vaultTA) {
424
- vaultTA = await (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, vault, true);
425
- }
426
- if (!userTA) {
427
- userTA = await (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, relayer.publicKey);
428
- }
429
- if (!recipientTA) {
430
- recipientTA = await (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, recipient);
431
- }
432
- if (!relayerTA) {
433
- relayerTA = await (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, relayer.publicKey);
434
- }
435
- }
436
- const tx = program.methods
437
- .transact(Array.from(root), inputTreeId, outputTreeId, new anchor_1.BN(publicAmount.toString()), Array.from(extDataHash), mintAddress, Array.from(inputNullifiers[0]), Array.from(inputNullifiers[1]), Array.from(outputCommitments[0]), Array.from(outputCommitments[1]), new anchor_1.BN(deadline.toString()), {
438
- recipient: extData.recipient,
439
- relayer: extData.relayer,
440
- fee: new anchor_1.BN(extData.fee.toString()),
441
- refund: new anchor_1.BN(extData.refund.toString()),
442
- }, {
443
- proofA: proof.proofA,
444
- proofB: proof.proofB,
445
- proofC: proof.proofC,
446
- })
447
- .accounts({
448
- config,
449
- globalConfig,
450
- vault,
451
- inputTree,
452
- outputTree,
453
- nullifiers,
454
- nullifierMarker0,
455
- nullifierMarker1,
456
- relayer: relayer.publicKey,
457
- recipient,
458
- vaultTokenAccount: vaultTA ?? vault,
459
- userTokenAccount: userTA ?? relayer.publicKey,
460
- recipientTokenAccount: recipientTA ?? recipient,
461
- relayerTokenAccount: relayerTA ?? relayer.publicKey,
462
- tokenProgram: isNativeSol ? web3_js_1.SystemProgram.programId : spl_token_1.TOKEN_PROGRAM_ID,
463
- systemProgram: web3_js_1.SystemProgram.programId,
464
- })
465
- .signers([relayer]);
466
- return (0, retry_1.withRpcRetry)(() => tx.rpc());
467
- }
468
- /**
469
- * Build an unsigned deposit {@link Transaction} for the privacy pool.
470
- *
471
- * For deposits, we use zero input UTXOs (amount=0) and create output UTXOs
472
- * with the deposit amount. `publicAmount` is positive. The caller is
473
- * responsible for signing and submitting the returned transaction, and then
474
- * calling `commit()` once it confirms.
475
- *
476
- * @param amount - Amount to deposit in lamports/token units
477
- * @param recipientPubkey - UTXO public key that will own the deposited funds
478
- * @param treeId - The tree ID to deposit into (defaults to 0)
479
- */
480
- async function deposit(params) {
481
- const { program, depositor, amount, mintAddress, recipientPubkey, tree, proofBuilder, treeId = 0, extData: partialExtData, } = params;
482
- // Create a random keypair for the zero inputs (they don't matter since amount is 0)
483
- const zeroKeypair = (0, utxo_1.generateKeypair)();
484
- // Create zero input UTXOs (for deposits, we don't spend any existing UTXOs)
485
- const zeroInput0 = (0, utxo_1.createOwnedZeroUTXO)(zeroKeypair.privateKey, mintAddress);
486
- const zeroInput1 = (0, utxo_1.createOwnedZeroUTXO)(zeroKeypair.privateKey, mintAddress);
487
- // The circuit skips the Merkle proof check for zero-amount inputs (amount == 0
488
- // causes `enabled = 0` in MerkleProofIfEnabled). So we provide a dummy path using
489
- // the tree's pre-computed zero chain without inserting anything into the tree.
490
- const dummyPath = tree.zeroes.slice(0, tree.depth);
491
- const currentRoot = tree.root;
492
- const inputUTXOs = [
493
- {
494
- ...zeroInput0,
495
- pathIndex: 0,
496
- pathElements: dummyPath,
497
- privateKey: zeroKeypair.privateKey,
498
- },
499
- {
500
- ...zeroInput1,
501
- pathIndex: 0,
502
- pathElements: dummyPath,
503
- privateKey: zeroKeypair.privateKey,
504
- },
505
- ];
506
- const outputUTXO0 = (0, utxo_1.createUTXO)({
507
- amount: amount,
508
- pubkey: recipientPubkey,
509
- mintAddress,
510
- });
511
- const outputUTXO1 = (0, utxo_1.createUTXO)({
512
- amount: 0n,
513
- pubkey: recipientPubkey,
514
- mintAddress,
515
- });
516
- const outputUTXOs = [
517
- outputUTXO0,
518
- outputUTXO1,
519
- ];
520
- const depositorPubkey = depositor.publicKey;
521
- const extData = {
522
- recipient: partialExtData?.recipient ?? depositorPubkey,
523
- relayer: partialExtData?.relayer ?? depositorPubkey,
524
- fee: partialExtData?.fee ?? 0n,
525
- refund: partialExtData?.refund ?? 0n,
526
- claimant: partialExtData?.claimant ?? web3_js_1.SystemProgram.programId,
527
- };
528
- const circuitInputs = (0, proof_1.prepareTransactionInputs)({
529
- inputUTXOs,
530
- outputUTXOs,
531
- root: currentRoot,
532
- publicAmount: amount, // Positive for deposits
533
- extData,
534
- mintAddress,
535
- });
536
- const rawProof = await proofBuilder(circuitInputs);
537
- const proof = (0, proof_1.encodeSnarkjsProofToTransactionProof)(rawProof);
538
- // -----------------------------------------------------------------------
539
- // Build the transact instruction inline (duplicated from `transact()`).
540
- //
541
- // We intentionally don't reuse the `transact()` helper: it submits via
542
- // anchor's `.rpc()` with `.signers([relayer])`, which assumes the caller
543
- // holds a real Keypair. For deposit, we want to return an unsigned
544
- // Transaction so the caller (typically a browser wallet) can sign it
545
- // themselves. Duplicating ~40 lines here keeps the change contained to
546
- // this function and leaves the relayer path (`transact()` →
547
- // `withdraw`/`privateTransfer`/`transactSwap`) completely untouched.
548
- // -----------------------------------------------------------------------
549
- const { config, vault, nullifiers } = getPoolPdas(program.programId, mintAddress);
550
- const globalConfig = getGlobalConfigPda(program.programId);
551
- const inputTree = getNoteTreePda(program.programId, mintAddress, treeId);
552
- const outputTree = getNoteTreePda(program.programId, mintAddress, treeId);
553
- const nullifierMarker0 = getNullifierMarkerPda(program.programId, mintAddress, circuitInputs.inputNullifiers[0]);
554
- const nullifierMarker1 = getNullifierMarkerPda(program.programId, mintAddress, circuitInputs.inputNullifiers[1]);
555
- const extDataHash = (0, proof_1.computeExtDataHash)(extData);
556
- const isNativeSol = mintAddress.equals(config_1.NATIVE_SOL_MINT);
557
- let vaultTA;
558
- let userTA;
559
- let recipientTA;
560
- let relayerTA;
561
- if (!isNativeSol) {
562
- vaultTA = await (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, vault, true);
563
- userTA = await (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, depositorPubkey);
564
- recipientTA = await (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, extData.recipient);
565
- relayerTA = await (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, depositorPubkey);
566
- }
567
- const builtTx = await program.methods
568
- .transact(Array.from(currentRoot), treeId, treeId, new anchor_1.BN(amount.toString()), Array.from(extDataHash), mintAddress, Array.from(circuitInputs.inputNullifiers[0]), Array.from(circuitInputs.inputNullifiers[1]), Array.from(circuitInputs.outputCommitments[0]), Array.from(circuitInputs.outputCommitments[1]), new anchor_1.BN(Math.floor(Date.now() / 1000) + 3600), // 1-hour window from build time
569
- {
570
- recipient: extData.recipient,
571
- relayer: extData.relayer,
572
- fee: new anchor_1.BN(extData.fee.toString()),
573
- refund: new anchor_1.BN(extData.refund.toString()),
574
- }, {
575
- proofA: proof.proofA,
576
- proofB: proof.proofB,
577
- proofC: proof.proofC,
578
- })
579
- .accounts({
580
- config,
581
- globalConfig,
582
- vault,
583
- inputTree,
584
- outputTree,
585
- nullifiers,
586
- nullifierMarker0,
587
- nullifierMarker1,
588
- relayer: depositorPubkey,
589
- recipient: extData.recipient,
590
- vaultTokenAccount: vaultTA ?? vault,
591
- userTokenAccount: userTA ?? depositorPubkey,
592
- recipientTokenAccount: recipientTA ?? extData.recipient,
593
- relayerTokenAccount: relayerTA ?? depositorPubkey,
594
- tokenProgram: isNativeSol ? web3_js_1.SystemProgram.programId : spl_token_1.TOKEN_PROGRAM_ID,
595
- systemProgram: web3_js_1.SystemProgram.programId,
596
- })
597
- .transaction();
598
- // Add compute budget instruction for higher CU limit
599
- const computeBudgetIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({
600
- units: 1400000,
601
- });
602
- builtTx.instructions.unshift(computeBudgetIx);
603
- // Populate feePayer + recentBlockhash so the wallet only has to sign.
604
- const provider = program.provider;
605
- builtTx.feePayer = depositorPubkey;
606
- const { blockhash } = await provider.connection.getLatestBlockhash();
607
- builtTx.recentBlockhash = blockhash;
608
- const commit = () => {
609
- const { index: outIdx0 } = tree.insert(outputUTXOs[0].commitment);
610
- const { index: outIdx1, root: newRoot } = tree.insert(outputUTXOs[1].commitment);
611
- return {
612
- outputUTXOs,
613
- leafIndices: [outIdx0, outIdx1],
614
- root: newRoot,
615
- };
616
- };
617
- return {
618
- transaction: builtTx,
619
- outputUTXOs,
620
- commit,
621
- };
622
- }
623
- /**
624
- * Withdraw funds from the privacy pool.
625
- *
626
- * For withdrawals, we spend input UTXOs and create change output UTXOs.
627
- * The publicAmount is negative (funds flowing out).
628
- *
629
- * @param withdrawAmount - Amount to withdraw in lamports/token units
630
- * @param inputUTXOs - The UTXOs being spent
631
- * @param changePubkey - UTXO public key for the change output
632
- * @param inputTreeId - The tree ID where input UTXOs are located
633
- * @param outputTreeId - The tree ID where change outputs will be inserted
634
- */
635
- async function withdraw(params) {
636
- const { program, relayer, recipient, mintAddress, inputUTXOs, changePubkey, withdrawAmount, fee, refund, root, inputTreeId, outputTreeId, tree, proofBuilder, } = params;
637
- const totalInput = inputUTXOs[0].amount + inputUTXOs[1].amount;
638
- const changeAmount = totalInput - withdrawAmount - fee;
639
- if (changeAmount < 0n) {
640
- throw new Error("Insufficient input balance for withdrawal");
641
- }
642
- const changeUTXO = (0, utxo_1.createUTXO)({
643
- amount: changeAmount,
644
- pubkey: changePubkey,
645
- mintAddress,
646
- });
647
- const zeroUTXO = (0, utxo_1.createUTXO)({
648
- amount: 0n,
649
- pubkey: changePubkey,
650
- mintAddress,
651
- });
652
- const outputUTXOs = [changeUTXO, zeroUTXO];
653
- const extData = {
654
- recipient,
655
- relayer: relayer.publicKey,
656
- fee,
657
- refund,
658
- claimant: web3_js_1.SystemProgram.programId,
659
- };
660
- // publicAmount is negative for withdrawals
661
- const publicAmount = -withdrawAmount;
662
- const circuitInputs = (0, proof_1.prepareTransactionInputs)({
663
- inputUTXOs,
664
- outputUTXOs,
665
- root,
666
- publicAmount,
667
- extData,
668
- mintAddress,
669
- });
670
- const rawProof = await proofBuilder(circuitInputs);
671
- const proof = (0, proof_1.encodeSnarkjsProofToTransactionProof)(rawProof);
672
- await transact({
673
- program,
674
- relayer,
675
- recipient,
676
- mintAddress,
677
- root,
678
- inputTreeId,
679
- outputTreeId,
680
- publicAmount,
681
- inputNullifiers: circuitInputs.inputNullifiers,
682
- outputCommitments: circuitInputs.outputCommitments,
683
- extData,
684
- proof,
685
- });
686
- const { index: changeIdx, root: newRoot } = tree.insert(changeUTXO.commitment);
687
- tree.insert(zeroUTXO.commitment);
688
- return {
689
- changeUTXO,
690
- leafIndex: changeIdx,
691
- root: newRoot,
692
- };
693
- }
694
- /**
695
- * Execute a private transfer within the pool.
696
- *
697
- * For transfers, the publicAmount is 0 (no funds enter or leave the pool).
698
- * Input amounts must equal output amounts.
699
- *
700
- * @param inputUTXOs - The UTXOs being spent
701
- * @param outputPubkeys - UTXO public keys for the recipients
702
- * @param outputAmounts - Amounts for each output (must sum to input total)
703
- * @param inputTreeId - The tree ID where input UTXOs are located
704
- * @param outputTreeId - The tree ID where output commitments will be inserted
705
- */
706
- async function privateTransfer(params) {
707
- const { program, relayer, mintAddress, inputUTXOs, outputPubkeys, outputAmounts, root, inputTreeId, outputTreeId, tree, proofBuilder, fee = 0n, } = params;
708
- const totalInput = inputUTXOs[0].amount + inputUTXOs[1].amount;
709
- const totalOutput = outputAmounts[0] + outputAmounts[1] + fee;
710
- if (totalInput !== totalOutput) {
711
- throw new Error(`Balance mismatch: inputs=${totalInput}, outputs=${totalOutput}`);
712
- }
713
- const outputUTXO0 = (0, utxo_1.createUTXO)({
714
- amount: outputAmounts[0],
715
- pubkey: outputPubkeys[0],
716
- mintAddress,
717
- });
718
- const outputUTXO1 = (0, utxo_1.createUTXO)({
719
- amount: outputAmounts[1],
720
- pubkey: outputPubkeys[1],
721
- mintAddress,
722
- });
723
- const outputUTXOs = [
724
- outputUTXO0,
725
- outputUTXO1,
726
- ];
727
- // Prepare ext data (for transfers, recipient can be anyone)
728
- const extData = {
729
- recipient: relayer.publicKey, // No external recipient for transfers
730
- relayer: relayer.publicKey,
731
- fee,
732
- refund: 0n,
733
- claimant: web3_js_1.SystemProgram.programId,
734
- };
735
- // publicAmount is 0 for transfers
736
- const publicAmount = 0n;
737
- const circuitInputs = (0, proof_1.prepareTransactionInputs)({
738
- inputUTXOs,
739
- outputUTXOs,
740
- root,
741
- publicAmount,
742
- extData,
743
- mintAddress,
744
- });
745
- const rawProof = await proofBuilder(circuitInputs);
746
- const proof = (0, proof_1.encodeSnarkjsProofToTransactionProof)(rawProof);
747
- await transact({
748
- program,
749
- relayer,
750
- recipient: relayer.publicKey,
751
- mintAddress,
752
- root,
753
- inputTreeId,
754
- outputTreeId,
755
- publicAmount,
756
- inputNullifiers: circuitInputs.inputNullifiers,
757
- outputCommitments: circuitInputs.outputCommitments,
758
- extData,
759
- proof,
760
- });
761
- const { index: outIdx0 } = tree.insert(outputUTXOs[0].commitment);
762
- const { index: outIdx1, root: newRoot } = tree.insert(outputUTXOs[1].commitment);
763
- return {
764
- outputUTXOs,
765
- leafIndices: [outIdx0, outIdx1],
766
- root: newRoot,
767
- };
768
- }
769
- // -----------------------------------------------------------------------------
770
- // Global Config
771
- // -----------------------------------------------------------------------------
772
- /**
773
- * Update the global config.
774
- * Currently takes no extra args — only admin verification.
775
- */
776
- async function updateGlobalConfig(params) {
777
- const { program, admin } = params;
778
- const globalConfig = getGlobalConfigPda(program.programId);
779
- await program.methods
780
- .updateGlobalConfig()
781
- .accounts({
782
- globalConfig,
783
- admin: admin.publicKey,
784
- })
785
- .rpc();
786
- }
787
- // -----------------------------------------------------------------------------
788
- // Swap Helpers
789
- // -----------------------------------------------------------------------------
790
- /**
791
- * Get the swap executor PDA.
792
- * Seeds: ["swap_executor", source_mint, dest_mint, input_nullifier_0, relayer]
793
- */
794
- function getSwapExecutorPda(programId, sourceMint, destMint, inputNullifier0, relayer) {
795
- const [executor] = web3_js_1.PublicKey.findProgramAddressSync([
796
- Buffer.from("swap_executor"),
797
- sourceMint.toBuffer(),
798
- destMint.toBuffer(),
799
- inputNullifier0,
800
- relayer.toBuffer(),
801
- ], programId);
802
- return executor;
803
- }
804
- /**
805
- * Build the `fund_native_source` instruction that pre-funds the swap executor
806
- * with native SOL from the source vault. Only for native SOL source pools.
807
- *
808
- * This instruction MUST be the first instruction in the same atomic transaction
809
- * as `transactSwap`. Call `transactSwap` directly — it handles this internally.
810
- */
811
- async function fundNativeSource(params) {
812
- const { program, relayer, sourceMint, destMint, inputNullifier0, swapAmount, } = params;
813
- const { vault: sourceVault, config: sourceConfig } = getPoolPdas(program.programId, sourceMint);
814
- const executor = getSwapExecutorPda(program.programId, sourceMint, destMint, inputNullifier0, relayer.publicKey);
815
- const executorSourceToken = await (0, spl_token_1.getAssociatedTokenAddress)(spl_token_1.NATIVE_MINT, executor, true);
816
- return program.methods
817
- .fundNativeSource(sourceMint, destMint, Array.from(inputNullifier0), new anchor_1.BN(swapAmount.toString()))
818
- .accounts({
819
- executor,
820
- executorSourceToken,
821
- sourceVault,
822
- sourceConfig,
823
- sourceMintAccount: spl_token_1.NATIVE_MINT,
824
- relayer: relayer.publicKey,
825
- instructionsSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
826
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
827
- systemProgram: web3_js_1.SystemProgram.programId,
828
- associatedTokenProgram: spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID,
829
- })
830
- .instruction();
831
- }
832
- /**
833
- * Execute an atomic cross-pool private swap.
834
- *
835
- * For native SOL source pools (`sourceMint === NATIVE_SOL_MINT`), this function
836
- * automatically prepends the `fund_native_source` instruction in the same
837
- * transaction so the on-chain atomicity requirement is always satisfied.
838
- *
839
- * @param swapProgram - Jupiter/Raydium CPMM/AMM program ID
840
- * @param swapData - Raw DEX instruction bytes
841
- */
842
- async function transactSwap(params) {
843
- const { program, relayer, sourceMint, destMint, sourceRoot, sourceTreeId, destTreeId, inputNullifiers, outputCommitments, proof, swapParams, swapAmount, swapData, extData, sourceVaultTokenAccount, sourceMintAccount, destVaultTokenAccount, destMintAccount, relayerTokenAccount, swapProgram, jupiterEventAuthority, } = params;
844
- const { config: sourceConfig, vault: sourceVault, nullifiers: sourceNullifiers, } = getPoolPdas(program.programId, sourceMint);
845
- const { config: destConfig, vault: destVault } = getPoolPdas(program.programId, destMint);
846
- const globalConfig = getGlobalConfigPda(program.programId);
847
- const sourceTree = getNoteTreePda(program.programId, sourceMint, sourceTreeId);
848
- const destTree = getNoteTreePda(program.programId, destMint, destTreeId);
849
- const sourceNullifierMarker0 = getNullifierMarkerPda(program.programId, sourceMint, inputNullifiers[0]);
850
- const sourceNullifierMarker1 = getNullifierMarkerPda(program.programId, sourceMint, inputNullifiers[1]);
851
- const executor = getSwapExecutorPda(program.programId, sourceMint, destMint, inputNullifiers[0], relayer.publicKey);
852
- const executorSourceToken = await (0, spl_token_1.getAssociatedTokenAddress)(sourceMintAccount, executor, true);
853
- const executorDestToken = await (0, spl_token_1.getAssociatedTokenAddress)(destMintAccount, executor, true);
854
- const swapIx = await program.methods
855
- .transactSwap({
856
- proofA: proof.proofA,
857
- proofB: proof.proofB,
858
- proofC: proof.proofC,
859
- }, Array.from(sourceRoot), sourceTreeId, sourceMint, Array.from(inputNullifiers[0]), Array.from(inputNullifiers[1]), destTreeId, destMint, Array.from(outputCommitments[0]), Array.from(outputCommitments[1]), {
860
- minAmountOut: new anchor_1.BN(swapParams.minAmountOut.toString()),
861
- deadline: new anchor_1.BN(swapParams.deadline.toString()),
862
- sourceMint: swapParams.sourceMint,
863
- destMint: swapParams.destMint,
864
- destAmount: new anchor_1.BN(swapParams.destAmount.toString()),
865
- swapDataHash: Array.from(swapParams.swapDataHash),
866
- }, new anchor_1.BN(swapAmount.toString()), swapData, {
867
- recipient: extData.recipient,
868
- relayer: extData.relayer,
869
- fee: new anchor_1.BN(extData.fee.toString()),
870
- refund: new anchor_1.BN(extData.refund.toString()),
871
- })
872
- .accounts({
873
- sourceConfig,
874
- globalConfig,
875
- sourceVault,
876
- sourceTree,
877
- sourceNullifiers,
878
- sourceNullifierMarker0,
879
- sourceNullifierMarker1,
880
- sourceVaultTokenAccount,
881
- sourceMintAccount,
882
- destConfig,
883
- destVault,
884
- destTree,
885
- destVaultTokenAccount,
886
- destMintAccount,
887
- executor,
888
- executorSourceToken,
889
- executorDestToken,
890
- relayer: relayer.publicKey,
891
- relayerTokenAccount,
892
- swapProgram,
893
- jupiterEventAuthority,
894
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
895
- systemProgram: web3_js_1.SystemProgram.programId,
896
- associatedTokenProgram: spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID,
897
- })
898
- .instruction();
899
- const provider = program.provider;
900
- const tx = new web3_js_1.Transaction();
901
- if (sourceMint.equals(config_1.NATIVE_SOL_MINT)) {
902
- const fundIx = await fundNativeSource({
903
- program,
904
- relayer,
905
- sourceMint,
906
- destMint,
907
- inputNullifier0: inputNullifiers[0],
908
- swapAmount,
909
- });
910
- tx.add(fundIx);
911
- }
912
- tx.add(swapIx);
913
- return (0, retry_1.withRpcRetry)(() => provider.sendAndConfirm(tx, [relayer]));
914
- }
17
+ // Backward-compatible entry point. Implementations are grouped by domain.
18
+ __exportStar(require("./accounts/index.js"), exports);
19
+ __exportStar(require("./transactions/index.js"), exports);