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