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