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