@audren-xyz/sdk 0.0.0-stage → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1139 @@
1
+ /**
2
+ * Builders for all 9 Audren v1 instructions (`0x00..=0x08`) and exact SHA-256 `ctx_hash`
3
+ * transcripts matching `crates/client/src/instructions.rs` and `program/src/lib.rs` bit-for-bit.
4
+ */
5
+ import { sha256 } from '@noble/hashes/sha2.js';
6
+ import { ASSET_MODE_PRIVATE, ASSET_MODE_PUBLIC, ASSOCIATED_TOKEN_PROGRAM_ID, AUDREN_PROGRAM_ID, CLASSIC_TOKEN_PROGRAM_ID, CTX_DOMAIN_EXEC_VIA_ESCROW, CTX_DOMAIN_ROUTER_ACCOUNTS, CTX_DOMAIN_TRANSACT, CU_LIMIT_DEPOSIT, CU_LIMIT_DEPOSIT_HOOK, CU_LIMIT_EXEC_VIA_ESCROW_BASE, CU_LIMIT_OPEN_PAGE, CU_LIMIT_TRANSACT_FULL_EXIT, CU_LIMIT_TRANSACT_PRIVATE, CU_LIMIT_TRANSACT_WITHDRAW, CU_LIMIT_TRANSACT_WITHDRAW_HOOK, DEFAULT_ROOT_EPOCH_INTERVAL, DEPOSIT_FLAG_FEE_FROM_AMOUNT, DEPOSIT_FLAG_NATIVE_SOL, DYN_MEMO_HEAD_LEN, EPOCH_RING_LEN, EXEC_FLAG_FEE_ON_OUTPUT, GROTH16_PROOF_LEN, MAX_ROOT_EPOCH_INTERVAL, MAX_TX_CU_LIMIT, MEMO_CT_LEN, MEMO_ENTRY_WIRE_LEN, MEMO_NOTES_PER_PAGE, NF_PER_PAGE, NUM_ESCROW_SHARDS, NUM_LANES, OPEN_PAGE_KIND_MEMO, OPEN_PAGE_KIND_NULLIFIER, OPEN_PAGE_KIND_SUBROOT, OPEN_PAGE_KIND_SUBTREE, ROOT_RING_EPOCH, ROOT_RING_SLOT, SLOT_RING_LEN, SUBROOTS_PER_PAGE, SUBTREE_LEAVES, SYSTEM_PROGRAM_ID, TAG_DEPOSIT, TAG_EXEC_VIA_ESCROW, TAG_INIT_LANE, TAG_INIT_POOL, TAG_INIT_ROOT_HISTORY, TAG_OPEN_PAGE, TAG_SET_PAUSED, TAG_TRANSACT, TAG_UPDATE_POOL, UPDATE_POOL_ACCEPT_AUTHORITY, UPDATE_POOL_PARAMS, UPDATE_POOL_PROPOSE_AUTHORITY, UPDATE_POOL_RENOUNCE_AUTHORITY, VK_ID_DEFAULT, WITHDRAW_FLAG_UNWRAP_WSOL, WSOL_MINT, } from './constants.js';
7
+ import { MAX_LEAVES_PER_LANE } from './layout.js';
8
+ import { base58Decode, base58Encode, deriveAssociatedTokenAddressSync, deriveEscrowPdaSync, deriveLanePdaSync, deriveLaneRentVaultPdaSync, deriveMemoPdaSync, deriveNfPagePdaSync, deriveNullifierPdaSync, derivePoolPdaSync, deriveRootsPdaSync, deriveSubrootPdaSync, deriveSubtreePdaSync, deriveUnwrapPdaSync, deriveVaultAuthPdaSync, toPubkeyBytes, } from './pda.js';
9
+ import { bytes32ToFrMasked, frToBeBytes } from './poseidon.js';
10
+ import { prepareEscrowAccountsForAudren } from './swap.js';
11
+ const utf8Encoder = new TextEncoder();
12
+ function concat(...parts) {
13
+ let len = 0;
14
+ for (const p of parts) {
15
+ if (!(p instanceof Uint8Array)) {
16
+ throw new RangeError(`Expected Uint8Array chunk, got ${String(p)}`);
17
+ }
18
+ len += p.byteLength;
19
+ }
20
+ const out = new Uint8Array(len);
21
+ let off = 0;
22
+ for (const p of parts) {
23
+ out.set(p, off);
24
+ off += p.byteLength;
25
+ }
26
+ return out;
27
+ }
28
+ const U8_MAX = 0xff;
29
+ const U16_MAX = 0xffff;
30
+ const U32_MAX = 0xffff_ffff;
31
+ const U64_MAX = 0xffffffffffffffffn;
32
+ function assertU8(n, label) {
33
+ if (!Number.isInteger(n) || n < 0 || n > U8_MAX) {
34
+ throw new RangeError(`${label} must be a u8 integer in 0..=${U8_MAX}, got ${n}`);
35
+ }
36
+ }
37
+ function assertU16(n, label) {
38
+ if (!Number.isInteger(n) || n < 0 || n > U16_MAX) {
39
+ throw new RangeError(`${label} must be a u16 integer in 0..=${U16_MAX}, got ${n}`);
40
+ }
41
+ }
42
+ function assertU32(n, label) {
43
+ if (!Number.isInteger(n) || n < 0 || n > U32_MAX) {
44
+ throw new RangeError(`${label} must be a u32 integer in 0..=${U32_MAX}, got ${n}`);
45
+ }
46
+ }
47
+ function assertU64(n, label) {
48
+ if (typeof n !== 'bigint' || n < 0n || n > U64_MAX) {
49
+ throw new RangeError(`${label} must be a u64 bigint in 0..=2^64-1, got ${String(n)}`);
50
+ }
51
+ }
52
+ function assertLaneId(n, label = 'laneId') {
53
+ if (!Number.isInteger(n) || n < 0 || n >= NUM_LANES) {
54
+ throw new RangeError(`${label} must be an integer in 0..${NUM_LANES - 1}, got ${n}`);
55
+ }
56
+ }
57
+ function assertEscrowShard(n) {
58
+ if (!Number.isInteger(n) || n < 0 || n >= NUM_ESCROW_SHARDS) {
59
+ throw new RangeError(`escrowShard must be an integer in 0..${NUM_ESCROW_SHARDS - 1}, got ${n}`);
60
+ }
61
+ }
62
+ function assertRootRing(rootRingKind, rootRingIdx) {
63
+ if (rootRingKind === ROOT_RING_SLOT) {
64
+ if (!Number.isInteger(rootRingIdx) || rootRingIdx < 0 || rootRingIdx >= SLOT_RING_LEN) {
65
+ throw new RangeError(`rootRingIdx must be an integer in 0..${SLOT_RING_LEN - 1} for ROOT_RING_SLOT, got ${rootRingIdx}`);
66
+ }
67
+ }
68
+ else if (rootRingKind === ROOT_RING_EPOCH) {
69
+ if (!Number.isInteger(rootRingIdx) || rootRingIdx < 0 || rootRingIdx >= EPOCH_RING_LEN) {
70
+ throw new RangeError(`rootRingIdx must be an integer in 0..${EPOCH_RING_LEN - 1} for ROOT_RING_EPOCH, got ${rootRingIdx}`);
71
+ }
72
+ }
73
+ else {
74
+ throw new RangeError(`rootRingKind must be ROOT_RING_SLOT (${ROOT_RING_SLOT}) or ROOT_RING_EPOCH (${ROOT_RING_EPOCH}), got ${rootRingKind}`);
75
+ }
76
+ }
77
+ function assertRootEpochInterval(n) {
78
+ assertU64(n, 'rootEpochInterval');
79
+ if (n < 1n || n > MAX_ROOT_EPOCH_INTERVAL) {
80
+ throw new RangeError(`rootEpochInterval must be in 1..=${MAX_ROOT_EPOCH_INTERVAL}, got ${n}`);
81
+ }
82
+ }
83
+ function u16le(n, label = 'u16') {
84
+ assertU16(n, label);
85
+ const b = new Uint8Array(2);
86
+ new DataView(b.buffer).setUint16(0, n, true);
87
+ return b;
88
+ }
89
+ function u32le(n, label = 'u32') {
90
+ assertU32(n, label);
91
+ const b = new Uint8Array(4);
92
+ new DataView(b.buffer).setUint32(0, n, true);
93
+ return b;
94
+ }
95
+ function u64le(n, label = 'u64') {
96
+ assertU64(n, label);
97
+ const b = new Uint8Array(8);
98
+ new DataView(b.buffer).setBigUint64(0, n, true);
99
+ return b;
100
+ }
101
+ function isAllZero32(b) {
102
+ if (!(b instanceof Uint8Array) || b.byteLength !== 32)
103
+ return false;
104
+ for (let i = 0; i < 32; i++)
105
+ if (b[i] !== 0)
106
+ return false;
107
+ return true;
108
+ }
109
+ function assertUint8Array(bytes, label) {
110
+ if (!(bytes instanceof Uint8Array)) {
111
+ throw new RangeError(`${label} must be a Uint8Array, got ${String(bytes)}`);
112
+ }
113
+ }
114
+ function assertLen(bytes, expected, label) {
115
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength !== expected) {
116
+ throw new RangeError(`${label} must be a ${expected}-byte Uint8Array, got ${bytes instanceof Uint8Array ? bytes.byteLength : String(bytes)}`);
117
+ }
118
+ }
119
+ function assertU64OrSafeInt(v, label) {
120
+ if (typeof v === 'bigint') {
121
+ if (v < 0n || v > U64_MAX) {
122
+ throw new RangeError(`${label} must be a u64 bigint in 0..=2^64-1, got ${String(v)}`);
123
+ }
124
+ return v;
125
+ }
126
+ if (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0) {
127
+ return BigInt(v);
128
+ }
129
+ throw new RangeError(`${label} must be a non-negative safe integer or u64 bigint, got ${String(v)}`);
130
+ }
131
+ function assertNonNegativeSafeInt(v, label) {
132
+ if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0) {
133
+ throw new RangeError(`${label} must be a non-negative safe integer, got ${String(v)}`);
134
+ }
135
+ return v;
136
+ }
137
+ function pubkeyToB58(pk) {
138
+ return typeof pk === 'string' ? pk : base58Encode(toPubkeyBytes(pk));
139
+ }
140
+ function divCeil(a, b) {
141
+ return (a + b - 1n) / b;
142
+ }
143
+ /** Deterministic per-note `LaneRentVault` fee matching `deterministic_note_rent_fee` on-chain. */
144
+ export function deterministicNoteRentFee(poolNoteRentFeeCap, subRent, srRent, memoRent) {
145
+ assertU64(poolNoteRentFeeCap, 'poolNoteRentFeeCap');
146
+ assertU64(subRent, 'subRent');
147
+ assertU64(srRent, 'srRent');
148
+ assertU64(memoRent, 'memoRent');
149
+ const live = divCeil(subRent > 0n ? subRent : 1n, BigInt(SUBTREE_LEAVES)) +
150
+ divCeil(srRent > 0n ? srRent : 1n, BigInt(SUBTREE_LEAVES * SUBROOTS_PER_PAGE)) +
151
+ divCeil(memoRent > 0n ? memoRent : 1n, BigInt(MEMO_NOTES_PER_PAGE));
152
+ return poolNoteRentFeeCap < live ? poolNoteRentFeeCap : live;
153
+ }
154
+ /**
155
+ * Compute primary page sequences and atomic rollover page sequences matching
156
+ * `append_leaf_and_memo` and `append_nullifier_prefix` in `program/src/lib.rs` byte-for-byte.
157
+ */
158
+ export function computePageRollovers(params) {
159
+ if (!params || typeof params !== 'object') {
160
+ throw new RangeError('computePageRollovers params must be an object');
161
+ }
162
+ const leafCount = assertU64OrSafeInt(params.leafCount, 'leafCount');
163
+ const nfCount = assertU64OrSafeInt(params.nfCount, 'nfCount');
164
+ const outputCount = assertNonNegativeSafeInt(params.outputCount, 'outputCount');
165
+ const spentNullifiers = assertNonNegativeSafeInt(params.spentNullifiers, 'spentNullifiers');
166
+ const subSize = BigInt(SUBTREE_LEAVES);
167
+ const srSize = BigInt(SUBROOTS_PER_PAGE);
168
+ const memoSize = BigInt(MEMO_NOTES_PER_PAGE);
169
+ const nfSize = BigInt(NF_PER_PAGE);
170
+ const outSubSeqBig = leafCount / subSize;
171
+ const outRootSeqBig = outSubSeqBig / srSize;
172
+ const outMemoSeqBig = leafCount / memoSize;
173
+ const nfPageSeqBig = nfCount / nfSize;
174
+ const plan = {
175
+ outSubSeq: Number(outSubSeqBig),
176
+ outRootSeq: Number(outRootSeqBig),
177
+ outMemoSeq: Number(outMemoSeqBig),
178
+ nfPageSeq: Number(nfPageSeqBig),
179
+ };
180
+ if (outputCount > 0) {
181
+ const lastLeaf = leafCount + BigInt(outputCount - 1);
182
+ const lastSubSeqBig = lastLeaf / subSize;
183
+ const lastRootSeqBig = lastSubSeqBig / srSize;
184
+ const lastMemoSeqBig = lastLeaf / memoSize;
185
+ if (lastSubSeqBig > outSubSeqBig)
186
+ plan.nextSubSeq = Number(lastSubSeqBig);
187
+ if (lastRootSeqBig > outRootSeqBig)
188
+ plan.nextRootSeq = Number(lastRootSeqBig);
189
+ if (lastMemoSeqBig > outMemoSeqBig)
190
+ plan.nextMemoSeq = Number(lastMemoSeqBig);
191
+ }
192
+ if (spentNullifiers > 0) {
193
+ const lastNf = nfCount + BigInt(spentNullifiers - 1);
194
+ const lastNfSeqBig = lastNf / nfSize;
195
+ if (lastNfSeqBig > nfPageSeqBig)
196
+ plan.nextNfSeq = Number(lastNfSeqBig);
197
+ }
198
+ return plan;
199
+ }
200
+ /** Auto-`OpenPage` proactive pre-open thresholds (`>= 90%` full, matching on-chain `OpenPage` bounds). */
201
+ export const AUTO_OPEN_SUBTREE_REM_THRESHOLD = 26;
202
+ export const AUTO_OPEN_MEMO_REM_THRESHOLD = 10;
203
+ export const AUTO_OPEN_NF_REM_THRESHOLD = 60;
204
+ export const AUTO_OPEN_SUBROOT_SLOT_THRESHOLD = 280;
205
+ /**
206
+ * Zero-crank Auto-`OpenPage` planner: returns every idempotent `OpenPage` (`Tag 2`) target
207
+ * required for a lane when it is at an exact rollover boundary (`mandatory: true`) OR `>= 90%` full
208
+ * (`mandatory: false`: `subRem <= 26`, `memoRem <= 10`, `nfRem <= 60`, `subrootSlot >= 280`) and
209
+ * the target page PDA is not present in `existingPages`.
210
+ */
211
+ export function planAutoOpenPages(params) {
212
+ if (!params || typeof params !== 'object') {
213
+ throw new RangeError('planAutoOpenPages params must be an object');
214
+ }
215
+ const poolId = params.poolId ?? 0;
216
+ assertU32(poolId, 'poolId');
217
+ assertLaneId(params.laneId, 'laneId');
218
+ const nextLeaf = assertU64OrSafeInt(params.nextLeaf, 'nextLeaf');
219
+ const nfCount = assertU64OrSafeInt(params.nfCount, 'nfCount');
220
+ const numOutputs = assertNonNegativeSafeInt(params.numOutputs, 'numOutputs');
221
+ const numNfs = assertNonNegativeSafeInt(params.numNfs, 'numNfs');
222
+ const programId = params.programId ?? AUDREN_PROGRAM_ID;
223
+ const existing = params.existingPages === undefined
224
+ ? null
225
+ : params.existingPages instanceof Set
226
+ ? params.existingPages
227
+ : new Set(params.existingPages);
228
+ const targets = [];
229
+ const seenIdx = new Map();
230
+ const addCandidate = (pageKind, pageSeq, pda, mandatory) => {
231
+ if (existing?.has(pda))
232
+ return;
233
+ const prevIdx = seenIdx.get(pda);
234
+ if (prevIdx !== undefined) {
235
+ if (mandatory)
236
+ targets[prevIdx].mandatory = true;
237
+ return;
238
+ }
239
+ seenIdx.set(pda, targets.length);
240
+ targets.push({ pageKind, pageSeq, pda, mandatory });
241
+ };
242
+ if (numOutputs > 0 && nextLeaf < MAX_LEAVES_PER_LANE) {
243
+ const subSize = BigInt(SUBTREE_LEAVES);
244
+ const srSize = BigInt(SUBROOTS_PER_PAGE);
245
+ const memoSize = BigInt(MEMO_NOTES_PER_PAGE);
246
+ const maxSubPages = MAX_LEAVES_PER_LANE / subSize;
247
+ const maxSrPages = divCeil(maxSubPages, srSize);
248
+ const maxMemoPages = divCeil(MAX_LEAVES_PER_LANE, memoSize);
249
+ const curSubSeq = nextLeaf / subSize;
250
+ const subUsed = Number(nextLeaf % subSize);
251
+ const subRem = SUBTREE_LEAVES - subUsed;
252
+ if (curSubSeq > 0n && subUsed === 0) {
253
+ addCandidate(OPEN_PAGE_KIND_SUBTREE, curSubSeq, deriveSubtreePdaSync(poolId, params.laneId, curSubSeq, programId).address, true);
254
+ }
255
+ const subMandatoryNext = subRem < numOutputs;
256
+ if (subMandatoryNext || subRem <= AUTO_OPEN_SUBTREE_REM_THRESHOLD) {
257
+ const nextSubSeq = curSubSeq + 1n;
258
+ if (nextSubSeq < maxSubPages) {
259
+ addCandidate(OPEN_PAGE_KIND_SUBTREE, nextSubSeq, deriveSubtreePdaSync(poolId, params.laneId, nextSubSeq, programId).address, subMandatoryNext);
260
+ }
261
+ }
262
+ const curRootSeq = curSubSeq / srSize;
263
+ const subrootSlot = Number(curSubSeq % srSize);
264
+ if (curRootSeq > 0n && subrootSlot === 0) {
265
+ addCandidate(OPEN_PAGE_KIND_SUBROOT, curRootSeq, deriveSubrootPdaSync(poolId, params.laneId, curRootSeq, programId).address, true);
266
+ }
267
+ // A single transaction appends at most 3 outputs (<< 256), so crossing from SubtreePage #299
268
+ // into #300 seals #299 into `curRootSeq` and writes leaf 0 of #300 without touching `curRootSeq + 1`.
269
+ // `curRootSeq + 1` is therefore proactive at `subrootSlot >= 280` (and becomes mandatory at `subrootSlot === 0`).
270
+ if (subrootSlot >= AUTO_OPEN_SUBROOT_SLOT_THRESHOLD) {
271
+ const nextRootSeq = curRootSeq + 1n;
272
+ if (nextRootSeq < maxSrPages) {
273
+ addCandidate(OPEN_PAGE_KIND_SUBROOT, nextRootSeq, deriveSubrootPdaSync(poolId, params.laneId, nextRootSeq, programId).address, false);
274
+ }
275
+ }
276
+ const curMemoSeq = nextLeaf / memoSize;
277
+ const memoUsed = Number(nextLeaf % memoSize);
278
+ const memoRem = MEMO_NOTES_PER_PAGE - memoUsed;
279
+ if (curMemoSeq > 0n && memoUsed === 0) {
280
+ addCandidate(OPEN_PAGE_KIND_MEMO, curMemoSeq, deriveMemoPdaSync(poolId, params.laneId, curMemoSeq, programId).address, true);
281
+ }
282
+ const memoMandatoryNext = memoRem < numOutputs;
283
+ if (memoMandatoryNext || memoRem <= AUTO_OPEN_MEMO_REM_THRESHOLD) {
284
+ const nextMemoSeq = curMemoSeq + 1n;
285
+ if (nextMemoSeq < maxMemoPages) {
286
+ addCandidate(OPEN_PAGE_KIND_MEMO, nextMemoSeq, deriveMemoPdaSync(poolId, params.laneId, nextMemoSeq, programId).address, memoMandatoryNext);
287
+ }
288
+ }
289
+ }
290
+ if (numNfs > 0) {
291
+ const nfSize = BigInt(NF_PER_PAGE);
292
+ const curNfSeq = nfCount / nfSize;
293
+ const nfUsed = Number(nfCount % nfSize);
294
+ const nfRem = NF_PER_PAGE - nfUsed;
295
+ if (curNfSeq > 0n && nfUsed === 0) {
296
+ addCandidate(OPEN_PAGE_KIND_NULLIFIER, curNfSeq, deriveNfPagePdaSync(poolId, params.laneId, curNfSeq, programId).address, true);
297
+ }
298
+ const nfMandatoryNext = nfRem < numNfs;
299
+ if (nfMandatoryNext || nfRem <= AUTO_OPEN_NF_REM_THRESHOLD) {
300
+ const nextNfSeq = curNfSeq + 1n;
301
+ addCandidate(OPEN_PAGE_KIND_NULLIFIER, nextNfSeq, deriveNfPagePdaSync(poolId, params.laneId, nextNfSeq, programId).address, nfMandatoryNext);
302
+ }
303
+ }
304
+ return targets;
305
+ }
306
+ /**
307
+ * Build idempotent `OpenPage` (`Tag 2`) pre-instructions returned by `planAutoOpenPages` so
308
+ * wallets and relayers keep lanes provisioned with zero external cranking.
309
+ *
310
+ * Proactive (`!mandatory`) lookahead instructions ALWAYS set `maxPayerDeficit = 0n` so
311
+ * `LaneRentVault` bears 100% of rent and TOCTOU drains revert cleanly instead of debiting `payer`.
312
+ * Pass `includeProactive: false` when `LaneRentVault` is known to be underfunded.
313
+ */
314
+ export function buildAutoOpenPageInstructions(params) {
315
+ const includeProactive = params.includeProactive ?? true;
316
+ const mandatoryMaxPayerDeficit = params.mandatoryMaxPayerDeficit ?? U64_MAX;
317
+ const targets = planAutoOpenPages({
318
+ programId: params.programId,
319
+ poolId: params.poolId,
320
+ laneId: params.laneId,
321
+ nextLeaf: params.nextLeaf,
322
+ nfCount: params.nfCount,
323
+ numOutputs: params.numOutputs,
324
+ numNfs: params.numNfs,
325
+ existingPages: params.existingPages,
326
+ });
327
+ return targets
328
+ .filter((t) => t.mandatory || includeProactive)
329
+ .map((t) => buildOpenPageInstruction({
330
+ programId: params.programId,
331
+ payer: params.payer,
332
+ pageKind: t.pageKind,
333
+ poolId: params.poolId,
334
+ laneId: params.laneId,
335
+ pageSeq: t.pageSeq,
336
+ maxPayerDeficit: t.mandatory ? mandatoryMaxPayerDeficit : 0n,
337
+ }));
338
+ }
339
+ /** Convert an `AudrenInstruction` (base58 pubkeys) into a binary `V1Instruction` for `compileV1Message`. */
340
+ export function toV1Instruction(ix) {
341
+ return {
342
+ programId: base58Decode(ix.programId),
343
+ accounts: ix.accounts.map((a) => ({
344
+ pubkey: base58Decode(a.pubkey),
345
+ isSigner: a.isSigner,
346
+ isWritable: a.isWritable,
347
+ })),
348
+ data: ix.data,
349
+ };
350
+ }
351
+ const CU_LIMIT_CREATE_ATA_CLASSIC = 30_000;
352
+ const CU_LIMIT_CREATE_ATA_TOKEN_2022 = 45_000;
353
+ const CU_LIMIT_EXEC_VIA_ESCROW_T22_LEG = 25_000;
354
+ /** Compute Unit cost per failed `find_program_address` bump iteration on Solana (`1,500` CU). */
355
+ export const CU_PER_PDA_BUMP_ITERATION = 1_500;
356
+ function nonNegativeInt(n, label = 'count') {
357
+ if (n === undefined)
358
+ return 0;
359
+ if (typeof n !== 'number' || !Number.isFinite(n) || n < 0) {
360
+ throw new RangeError(`${label} must be a non-negative finite number, got ${String(n)}`);
361
+ }
362
+ return Math.trunc(n);
363
+ }
364
+ /**
365
+ * Compute extra Compute Unit headroom for non-255 PDA bumps (`sum((255 - bump) * 1_500)`),
366
+ * validating every bump is a `u8` integer in `0..=255` and capping safely at `1,400,000` CU.
367
+ */
368
+ export function computeBumpCuMargin(bumps) {
369
+ if (!Array.isArray(bumps)) {
370
+ throw new RangeError('bumps must be an array of u8 integers in 0..=255');
371
+ }
372
+ let total = 0;
373
+ for (let i = 0; i < bumps.length; i++) {
374
+ const b = bumps[i];
375
+ if (typeof b !== 'number' || !Number.isInteger(b) || b < 0 || b > U8_MAX) {
376
+ throw new RangeError(`bumps[${i}] must be a u8 integer in 0..=${U8_MAX}, got ${String(b)}`);
377
+ }
378
+ total = Math.min(MAX_TX_CU_LIMIT, total + (U8_MAX - b) * CU_PER_PDA_BUMP_ITERATION);
379
+ }
380
+ return total;
381
+ }
382
+ /** Recommended tight Compute Unit limit for standalone or batched `OpenPage` (`Tag 2`) instructions. */
383
+ export function recommendedOpenPageCuLimit(params) {
384
+ const openPages = params?.openPageCount === undefined ? 1 : nonNegativeInt(params.openPageCount);
385
+ const bumpMargin = params?.bumps !== undefined ? computeBumpCuMargin(params.bumps) : 0;
386
+ return Math.min(MAX_TX_CU_LIMIT, openPages * CU_LIMIT_OPEN_PAGE + bumpMargin);
387
+ }
388
+ /** Recommended tight Compute Unit limit for `Deposit` (`Tag 3`) plus any prepended `OpenPage` / ATA setup instructions. */
389
+ export function recommendedDepositCuLimit(params) {
390
+ const base = params?.hasTransferHook ? CU_LIMIT_DEPOSIT_HOOK : CU_LIMIT_DEPOSIT;
391
+ const openPages = nonNegativeInt(params?.openPageCount);
392
+ const classicAtas = nonNegativeInt(params?.createAtaCount);
393
+ const t22Atas = nonNegativeInt(params?.createToken2022AtaCount);
394
+ const bumpMargin = params?.bumps !== undefined ? computeBumpCuMargin(params.bumps) : 0;
395
+ return Math.min(MAX_TX_CU_LIMIT, base +
396
+ openPages * CU_LIMIT_OPEN_PAGE +
397
+ classicAtas * CU_LIMIT_CREATE_ATA_CLASSIC +
398
+ t22Atas * CU_LIMIT_CREATE_ATA_TOKEN_2022 +
399
+ bumpMargin);
400
+ }
401
+ /** Recommended tight Compute Unit limit for `Transact` (`Tag 5`) plus any prepended `OpenPage` / ATA setup instructions. */
402
+ export function recommendedTransactCuLimit(params) {
403
+ if (params.assetMode !== ASSET_MODE_PRIVATE && params.assetMode !== ASSET_MODE_PUBLIC) {
404
+ throw new RangeError(`Invalid assetMode ${params.assetMode} (expected 0=PRIVATE or 1=PUBLIC)`);
405
+ }
406
+ const base = params.assetMode === ASSET_MODE_PUBLIC
407
+ ? params.hasTransferHook
408
+ ? CU_LIMIT_TRANSACT_WITHDRAW_HOOK
409
+ : params.outputMask === 0
410
+ ? CU_LIMIT_TRANSACT_FULL_EXIT
411
+ : CU_LIMIT_TRANSACT_WITHDRAW
412
+ : CU_LIMIT_TRANSACT_PRIVATE;
413
+ const openPages = nonNegativeInt(params.openPageCount);
414
+ const classicAtas = nonNegativeInt(params.createAtaCount);
415
+ const t22Atas = nonNegativeInt(params.createToken2022AtaCount);
416
+ const bumpMargin = params.bumps !== undefined ? computeBumpCuMargin(params.bumps) : 0;
417
+ return Math.min(MAX_TX_CU_LIMIT, base +
418
+ openPages * CU_LIMIT_OPEN_PAGE +
419
+ classicAtas * CU_LIMIT_CREATE_ATA_CLASSIC +
420
+ t22Atas * CU_LIMIT_CREATE_ATA_TOKEN_2022 +
421
+ bumpMargin);
422
+ }
423
+ /** Recommended tight Compute Unit limit for `ExecViaEscrow` (`Tag 6`) plus router CU, optional Token-2022 leg headroom, and any prepended `OpenPage` / ATA setup instructions. */
424
+ export function recommendedExecViaEscrowCuLimit(params) {
425
+ const routerCu = nonNegativeInt(params?.routerCuLimit);
426
+ const t22LegCu = params?.hasToken2022Leg ? CU_LIMIT_EXEC_VIA_ESCROW_T22_LEG : 0;
427
+ const openPages = nonNegativeInt(params?.openPageCount);
428
+ const classicAtas = nonNegativeInt(params?.createAtaCount);
429
+ const t22Atas = nonNegativeInt(params?.createToken2022AtaCount);
430
+ const bumpMargin = params?.bumps !== undefined ? computeBumpCuMargin(params.bumps) : 0;
431
+ return Math.min(MAX_TX_CU_LIMIT, CU_LIMIT_EXEC_VIA_ESCROW_BASE +
432
+ t22LegCu +
433
+ routerCu +
434
+ openPages * CU_LIMIT_OPEN_PAGE +
435
+ classicAtas * CU_LIMIT_CREATE_ATA_CLASSIC +
436
+ t22Atas * CU_LIMIT_CREATE_ATA_TOKEN_2022 +
437
+ bumpMargin);
438
+ }
439
+ /**
440
+ * Build a canonical SPL Associated Token Account `CreateIdempotent` (`data = [1]`) instruction
441
+ * supporting both Classic SPL Token and SPL Token-2022 mints.
442
+ */
443
+ export function buildCreateAtaIdempotentInstruction(params) {
444
+ return {
445
+ programId: ASSOCIATED_TOKEN_PROGRAM_ID,
446
+ accounts: [
447
+ { pubkey: params.payer, isSigner: true, isWritable: true },
448
+ { pubkey: params.ata, isSigner: false, isWritable: true },
449
+ { pubkey: params.owner, isSigner: false, isWritable: false },
450
+ { pubkey: params.mint, isSigner: false, isWritable: false },
451
+ { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },
452
+ {
453
+ pubkey: params.tokenProgram ?? CLASSIC_TOKEN_PROGRAM_ID,
454
+ isSigner: false,
455
+ isWritable: false,
456
+ },
457
+ ],
458
+ data: new Uint8Array([1]),
459
+ };
460
+ }
461
+ /** Exact `Transact` (`Tag 5`) `ctx_hash` matching `program/src/lib.rs` bit-for-bit (binds `vkId`). */
462
+ export function computeTransactCtxHash(params) {
463
+ assertLen(params.publicAssetId, 32, 'publicAssetId');
464
+ assertUint8Array(params.memosBytes, 'memosBytes');
465
+ assertU32(params.poolId, 'poolId');
466
+ const vkId = params.vkId ?? VK_ID_DEFAULT;
467
+ assertU8(vkId, 'vkId');
468
+ assertLaneId(params.outLaneId, 'outLaneId');
469
+ if (!Number.isInteger(params.outputMask) || params.outputMask < 0 || params.outputMask > 0b111) {
470
+ throw new RangeError(`outputMask must be an integer in 0..=7, got ${params.outputMask}`);
471
+ }
472
+ if (params.assetMode !== ASSET_MODE_PRIVATE && params.assetMode !== ASSET_MODE_PUBLIC) {
473
+ throw new RangeError(`Invalid assetMode ${params.assetMode} (expected 0=PRIVATE or 1=PUBLIC)`);
474
+ }
475
+ if (params.unwrapWsol && params.assetMode !== ASSET_MODE_PUBLIC) {
476
+ throw new Error('unwrapWsol requires ASSET_MODE_PUBLIC');
477
+ }
478
+ assertU64(params.publicAmountOut, 'publicAmountOut');
479
+ assertU64(params.relayerFeeAmount, 'relayerFeeAmount');
480
+ const programBytes = toPubkeyBytes(params.programId ?? AUDREN_PROGRAM_ID);
481
+ if (params.publicAmountOut > 0n && !params.recipient) {
482
+ throw new Error('recipient is required when publicAmountOut > 0');
483
+ }
484
+ if (params.relayerFeeAmount > 0n && !params.relayerFeeRecipient) {
485
+ throw new Error('relayerFeeRecipient is required when relayerFeeAmount > 0');
486
+ }
487
+ const recBytes = params.publicAmountOut > 0n ? toPubkeyBytes(params.recipient) : new Uint8Array(32);
488
+ const feeRecBytes = params.relayerFeeAmount > 0n ? toPubkeyBytes(params.relayerFeeRecipient) : new Uint8Array(32);
489
+ const preimage = concat(utf8Encoder.encode(CTX_DOMAIN_TRANSACT), programBytes, u32le(params.poolId, 'poolId'), new Uint8Array([
490
+ vkId,
491
+ params.outLaneId,
492
+ params.outputMask,
493
+ params.assetMode,
494
+ params.unwrapWsol ? 1 : 0,
495
+ ]), recBytes, feeRecBytes, params.publicAssetId, u64le(params.publicAmountOut, 'publicAmountOut'), u64le(params.relayerFeeAmount, 'relayerFeeAmount'), params.memosBytes);
496
+ return bytes32ToFrMasked(sha256(preimage));
497
+ }
498
+ /** Exact `router_accounts` hash matching `hash_router_accounts_arena` in `program/src/lib.rs`. */
499
+ export function computeRouterAccountsHash(routerAccounts) {
500
+ if (!Array.isArray(routerAccounts)) {
501
+ throw new RangeError('routerAccounts must be an array');
502
+ }
503
+ assertU16(routerAccounts.length, 'routerAccounts.length');
504
+ const parts = [
505
+ utf8Encoder.encode(CTX_DOMAIN_ROUTER_ACCOUNTS),
506
+ u16le(routerAccounts.length, 'routerAccounts.length'),
507
+ ];
508
+ for (const acc of routerAccounts) {
509
+ if (!acc || typeof acc !== 'object') {
510
+ throw new RangeError('Each routerAccounts entry must be an object');
511
+ }
512
+ parts.push(toPubkeyBytes(acc.pubkey));
513
+ parts.push(new Uint8Array([acc.isWritable ? 1 : 0]));
514
+ }
515
+ return sha256(concat(...parts));
516
+ }
517
+ /**
518
+ * Exact `ExecViaEscrow` (`Tag 6`) `ctx_hash` matching `program/src/lib.rs` bit-for-bit
519
+ * (binds `vkId`, SPL/Token-2022 only, `72 B` `dynMemoMask`).
520
+ *
521
+ * Applies Solana's transaction-wide writability promotion across `escrowPda`,
522
+ * `relayerFeeRecipient`, `extraWritablePubkeys`, and duplicate writable `routerAccounts`
523
+ * before hashing `router_accounts` so PDA/duplicate accounts match on-chain `AccountView::is_writable()`.
524
+ */
525
+ export function computeExecCtxHash(params) {
526
+ assertLen(params.assetIn, 32, 'assetIn');
527
+ assertLen(params.assetOut, 32, 'assetOut');
528
+ assertLen(params.outStealthOwner, 32, 'outStealthOwner');
529
+ assertLen(params.outBlinding, 32, 'outBlinding');
530
+ assertLen(params.dynMemoHead, DYN_MEMO_HEAD_LEN, 'dynMemoHead');
531
+ assertLen(params.dynMemoMask, MEMO_CT_LEN, 'dynMemoMask');
532
+ assertUint8Array(params.routerIxData, 'routerIxData');
533
+ assertUint8Array(params.changeMemos, 'changeMemos');
534
+ if (!Array.isArray(params.routerAccounts)) {
535
+ throw new RangeError('routerAccounts must be an array');
536
+ }
537
+ assertU32(params.poolId, 'poolId');
538
+ const vkId = params.vkId ?? VK_ID_DEFAULT;
539
+ assertU8(vkId, 'vkId');
540
+ assertLaneId(params.outLaneId, 'outLaneId');
541
+ assertEscrowShard(params.escrowShard);
542
+ if (!Number.isInteger(params.changeMask) || params.changeMask < 0 || params.changeMask > 0b11) {
543
+ throw new RangeError(`changeMask must be an integer in 0..=3, got ${params.changeMask}`);
544
+ }
545
+ assertU64(params.amountIn, 'amountIn');
546
+ assertU64(params.relayerFeeAmount, 'relayerFeeAmount');
547
+ assertU64(params.minAmountOut, 'minAmountOut');
548
+ assertU16(params.routerAccounts.length, 'routerAccounts.length');
549
+ assertU16(params.routerIxData.byteLength, 'routerIxData.byteLength');
550
+ if (params.relayerFeeAmount > 0n && !params.relayerFeeRecipient) {
551
+ throw new Error('relayerFeeRecipient is required when relayerFeeAmount > 0');
552
+ }
553
+ const programId = params.programId ?? AUDREN_PROGRAM_ID;
554
+ const programBytes = toPubkeyBytes(programId);
555
+ const escrowPda = deriveEscrowPdaSync(params.poolId, params.escrowShard, programId).address;
556
+ const extraWritable = [];
557
+ if (params.payer)
558
+ extraWritable.push(pubkeyToB58(params.payer));
559
+ if (params.escrowInAta)
560
+ extraWritable.push(pubkeyToB58(params.escrowInAta));
561
+ if (params.escrowOutAta)
562
+ extraWritable.push(pubkeyToB58(params.escrowOutAta));
563
+ if (params.vaultInAta)
564
+ extraWritable.push(pubkeyToB58(params.vaultInAta));
565
+ if (params.vaultOutAta)
566
+ extraWritable.push(pubkeyToB58(params.vaultOutAta));
567
+ if (params.relayerFeeAmount > 0n && params.relayerFeeRecipient) {
568
+ extraWritable.push(pubkeyToB58(params.relayerFeeRecipient));
569
+ }
570
+ if (params.extraWritablePubkeys) {
571
+ for (const pk of params.extraWritablePubkeys) {
572
+ extraWritable.push(pubkeyToB58(pk));
573
+ }
574
+ }
575
+ const normalizedRouterAccounts = prepareEscrowAccountsForAudren(params.routerAccounts, escrowPda, extraWritable);
576
+ const routerAccsHash = computeRouterAccountsHash(normalizedRouterAccounts);
577
+ const feeRecBytes = params.relayerFeeAmount > 0n ? toPubkeyBytes(params.relayerFeeRecipient) : new Uint8Array(32);
578
+ const preimage = concat(utf8Encoder.encode(CTX_DOMAIN_EXEC_VIA_ESCROW), programBytes, u32le(params.poolId, 'poolId'), new Uint8Array([
579
+ vkId,
580
+ params.outLaneId,
581
+ params.escrowShard,
582
+ params.changeMask,
583
+ params.feeOnOutput ? 1 : 0,
584
+ ]), params.assetIn, u64le(params.amountIn, 'amountIn'), u64le(params.relayerFeeAmount, 'relayerFeeAmount'), feeRecBytes, params.assetOut, u64le(params.minAmountOut, 'minAmountOut'), toPubkeyBytes(params.routerProg), routerAccsHash, params.outStealthOwner, params.outBlinding, params.dynMemoHead, params.dynMemoMask, u16le(params.routerIxData.byteLength, 'routerIxData.byteLength'), params.routerIxData, params.changeMemos);
585
+ return bytes32ToFrMasked(sha256(preimage));
586
+ }
587
+ // =============================================================================
588
+ // 9 Canonical Audren v1 Instruction Builders (0x00..=0x08)
589
+ // =============================================================================
590
+ /** Tag 0: `InitPool` (4 accounts including `GlobalRootHistory`, 29 B). */
591
+ export function buildInitPoolInstruction(params) {
592
+ const rootEpochInterval = params.rootEpochInterval ?? DEFAULT_ROOT_EPOCH_INTERVAL;
593
+ assertU32(params.poolId, 'poolId');
594
+ assertRootEpochInterval(rootEpochInterval);
595
+ assertU64(params.noteRentFee, 'noteRentFee');
596
+ assertU64(params.nfRentFee, 'nfRentFee');
597
+ const programId = params.programId ?? AUDREN_PROGRAM_ID;
598
+ const data = concat(new Uint8Array([TAG_INIT_POOL]), u32le(params.poolId, 'poolId'), u64le(rootEpochInterval, 'rootEpochInterval'), u64le(params.noteRentFee, 'noteRentFee'), u64le(params.nfRentFee, 'nfRentFee'));
599
+ return {
600
+ programId,
601
+ accounts: [
602
+ { pubkey: params.payer, isSigner: true, isWritable: true },
603
+ { pubkey: derivePoolPdaSync(params.poolId, programId).address, isSigner: false, isWritable: true },
604
+ { pubkey: deriveRootsPdaSync(params.poolId, programId).address, isSigner: false, isWritable: true },
605
+ { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },
606
+ ],
607
+ data,
608
+ };
609
+ }
610
+ /** Tag 1: `InitLane` (9 accounts, 6 B). */
611
+ export function buildInitLaneInstruction(params) {
612
+ assertU32(params.poolId, 'poolId');
613
+ assertLaneId(params.laneId, 'laneId');
614
+ const programId = params.programId ?? AUDREN_PROGRAM_ID;
615
+ const data = concat(new Uint8Array([TAG_INIT_LANE]), u32le(params.poolId, 'poolId'), new Uint8Array([params.laneId]));
616
+ return {
617
+ programId,
618
+ accounts: [
619
+ { pubkey: params.authority, isSigner: true, isWritable: true },
620
+ { pubkey: derivePoolPdaSync(params.poolId, programId).address, isSigner: false, isWritable: true },
621
+ { pubkey: deriveLanePdaSync(params.poolId, params.laneId, programId).address, isSigner: false, isWritable: true },
622
+ { pubkey: deriveLaneRentVaultPdaSync(params.poolId, params.laneId, programId).address, isSigner: false, isWritable: true },
623
+ { pubkey: deriveSubtreePdaSync(params.poolId, params.laneId, 0n, programId).address, isSigner: false, isWritable: true },
624
+ { pubkey: deriveSubrootPdaSync(params.poolId, params.laneId, 0n, programId).address, isSigner: false, isWritable: true },
625
+ { pubkey: deriveMemoPdaSync(params.poolId, params.laneId, 0n, programId).address, isSigner: false, isWritable: true },
626
+ { pubkey: deriveNfPagePdaSync(params.poolId, params.laneId, 0n, programId).address, isSigner: false, isWritable: true },
627
+ { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },
628
+ ],
629
+ data,
630
+ };
631
+ }
632
+ /** Tag 2: `OpenPage` (6 accounts, 23 B). */
633
+ export function buildOpenPageInstruction(params) {
634
+ assertU32(params.poolId, 'poolId');
635
+ assertLaneId(params.laneId, 'laneId');
636
+ assertU64(params.pageSeq, 'pageSeq');
637
+ const maxPayerDeficit = params.maxPayerDeficit ?? 0n;
638
+ assertU64(maxPayerDeficit, 'maxPayerDeficit');
639
+ const programId = params.programId ?? AUDREN_PROGRAM_ID;
640
+ let pagePda;
641
+ if (params.pageKind === OPEN_PAGE_KIND_SUBTREE) {
642
+ pagePda = deriveSubtreePdaSync(params.poolId, params.laneId, params.pageSeq, programId).address;
643
+ }
644
+ else if (params.pageKind === OPEN_PAGE_KIND_SUBROOT) {
645
+ pagePda = deriveSubrootPdaSync(params.poolId, params.laneId, params.pageSeq, programId).address;
646
+ }
647
+ else if (params.pageKind === OPEN_PAGE_KIND_MEMO) {
648
+ pagePda = deriveMemoPdaSync(params.poolId, params.laneId, params.pageSeq, programId).address;
649
+ }
650
+ else if (params.pageKind === OPEN_PAGE_KIND_NULLIFIER) {
651
+ pagePda = deriveNfPagePdaSync(params.poolId, params.laneId, params.pageSeq, programId).address;
652
+ }
653
+ else {
654
+ throw new RangeError(`Invalid pageKind ${params.pageKind}`);
655
+ }
656
+ const data = concat(new Uint8Array([TAG_OPEN_PAGE, params.pageKind]), u32le(params.poolId, 'poolId'), new Uint8Array([params.laneId]), u64le(params.pageSeq, 'pageSeq'), u64le(maxPayerDeficit, 'maxPayerDeficit'));
657
+ return {
658
+ programId,
659
+ accounts: [
660
+ { pubkey: params.payer, isSigner: true, isWritable: true },
661
+ { pubkey: derivePoolPdaSync(params.poolId, programId).address, isSigner: false, isWritable: false },
662
+ { pubkey: deriveLanePdaSync(params.poolId, params.laneId, programId).address, isSigner: false, isWritable: false },
663
+ { pubkey: deriveLaneRentVaultPdaSync(params.poolId, params.laneId, programId).address, isSigner: false, isWritable: true },
664
+ { pubkey: pagePda, isSigner: false, isWritable: true },
665
+ { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },
666
+ ],
667
+ data,
668
+ };
669
+ }
670
+ /**
671
+ * Tag 3: Unified `Deposit` (14 fixed accounts with writable `GlobalRootHistory` at `[2]` +
672
+ * optional rollover + optional hook accounts, 185 B).
673
+ *
674
+ * - Set `nativeSol: true` to deposit Native SOL atomically via `SyncNative` into the pool's
675
+ * canonical WSOL `vault_auth` ATA (`mint` defaults to `WSOL_MINT`, `sourceAccount` defaults to
676
+ * `depositor`, `tokenProgram` defaults to `CLASSIC_TOKEN_PROGRAM_ID`, `feeFromAmount` optional).
677
+ * - Omit `nativeSol` (or `false`) for Classic SPL / Token-2022 deposits (`mint` and `sourceAccount`
678
+ * required; `vaultAta` auto-derives the canonical `vault_auth` ATA when omitted).
679
+ */
680
+ export function buildDepositInstruction(params) {
681
+ assertLen(params.memo, MEMO_ENTRY_WIRE_LEN, 'memo');
682
+ assertU32(params.poolId, 'poolId');
683
+ assertLaneId(params.laneId, 'laneId');
684
+ assertU64(params.subPageSeq, 'subPageSeq');
685
+ assertU64(params.rootPageSeq, 'rootPageSeq');
686
+ assertU64(params.memoPageSeq, 'memoPageSeq');
687
+ assertU64(params.amount, 'amount');
688
+ const nativeSol = Boolean(params.nativeSol);
689
+ const feeFromAmount = Boolean(params.feeFromAmount);
690
+ if (feeFromAmount && !nativeSol) {
691
+ throw new Error('feeFromAmount is only valid when nativeSol is true');
692
+ }
693
+ const programId = params.programId ?? AUDREN_PROGRAM_ID;
694
+ const vaultAuth = deriveVaultAuthPdaSync(params.poolId, programId).address;
695
+ let mint;
696
+ let sourceAccount;
697
+ let tokenProgram;
698
+ if (nativeSol) {
699
+ mint = params.mint ?? WSOL_MINT;
700
+ if (mint !== WSOL_MINT) {
701
+ throw new Error(`nativeSol deposit requires WSOL_MINT (${WSOL_MINT})`);
702
+ }
703
+ tokenProgram = params.tokenProgram ?? CLASSIC_TOKEN_PROGRAM_ID;
704
+ if (tokenProgram !== CLASSIC_TOKEN_PROGRAM_ID) {
705
+ throw new Error('nativeSol deposit requires CLASSIC_TOKEN_PROGRAM_ID');
706
+ }
707
+ sourceAccount = params.sourceAccount ?? params.depositor;
708
+ if (sourceAccount !== params.depositor) {
709
+ throw new Error('nativeSol deposit requires sourceAccount === depositor');
710
+ }
711
+ }
712
+ else {
713
+ if (!params.mint)
714
+ throw new Error('mint is required for SPL / Token-2022 deposit');
715
+ if (!params.sourceAccount) {
716
+ throw new Error('sourceAccount (depositor token account) is required for SPL / Token-2022 deposit');
717
+ }
718
+ mint = params.mint;
719
+ sourceAccount = params.sourceAccount;
720
+ tokenProgram = params.tokenProgram ?? CLASSIC_TOKEN_PROGRAM_ID;
721
+ }
722
+ const vaultAta = params.vaultAta ??
723
+ deriveAssociatedTokenAddressSync(vaultAuth, mint, tokenProgram).address;
724
+ const nextSubSeq = params.rollover?.nextSubSeq ?? null;
725
+ const nextMemoSeq = params.rollover?.nextMemoSeq ?? null;
726
+ if (nextSubSeq != null)
727
+ assertU64(nextSubSeq, 'rollover.nextSubSeq');
728
+ if (nextMemoSeq != null)
729
+ assertU64(nextMemoSeq, 'rollover.nextMemoSeq');
730
+ const flags = (nextSubSeq != null ? 1 : 0) |
731
+ (nextMemoSeq != null ? 2 : 0) |
732
+ (feeFromAmount ? DEPOSIT_FLAG_FEE_FROM_AMOUNT : 0) |
733
+ (nativeSol ? DEPOSIT_FLAG_NATIVE_SOL : 0);
734
+ const stealthBytes = typeof params.stealthOwner === 'bigint' ? frToBeBytes(params.stealthOwner) : params.stealthOwner;
735
+ const blindBytes = typeof params.blinding === 'bigint' ? frToBeBytes(params.blinding) : params.blinding;
736
+ assertLen(stealthBytes, 32, 'stealthOwner');
737
+ assertLen(blindBytes, 32, 'blinding');
738
+ const data = concat(new Uint8Array([TAG_DEPOSIT]), u32le(params.poolId), new Uint8Array([params.laneId, flags]), u64le(params.amount), stealthBytes, blindBytes, params.memo);
739
+ const accounts = [
740
+ { pubkey: params.depositor, isSigner: true, isWritable: true },
741
+ { pubkey: derivePoolPdaSync(params.poolId, programId).address, isSigner: false, isWritable: false },
742
+ { pubkey: deriveRootsPdaSync(params.poolId, programId).address, isSigner: false, isWritable: true },
743
+ { pubkey: vaultAuth, isSigner: false, isWritable: false },
744
+ { pubkey: mint, isSigner: false, isWritable: false },
745
+ { pubkey: sourceAccount, isSigner: nativeSol, isWritable: true },
746
+ { pubkey: vaultAta, isSigner: false, isWritable: true },
747
+ { pubkey: tokenProgram, isSigner: false, isWritable: false },
748
+ { pubkey: deriveLanePdaSync(params.poolId, params.laneId, programId).address, isSigner: false, isWritable: true },
749
+ { pubkey: deriveLaneRentVaultPdaSync(params.poolId, params.laneId, programId).address, isSigner: false, isWritable: true },
750
+ { pubkey: deriveSubtreePdaSync(params.poolId, params.laneId, params.subPageSeq, programId).address, isSigner: false, isWritable: true },
751
+ { pubkey: deriveSubrootPdaSync(params.poolId, params.laneId, params.rootPageSeq, programId).address, isSigner: false, isWritable: true },
752
+ { pubkey: deriveMemoPdaSync(params.poolId, params.laneId, params.memoPageSeq, programId).address, isSigner: false, isWritable: true },
753
+ { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },
754
+ ];
755
+ if (nextSubSeq != null) {
756
+ accounts.push({
757
+ pubkey: deriveSubtreePdaSync(params.poolId, params.laneId, nextSubSeq, programId).address,
758
+ isSigner: false,
759
+ isWritable: true,
760
+ });
761
+ }
762
+ if (nextMemoSeq != null) {
763
+ accounts.push({
764
+ pubkey: deriveMemoPdaSync(params.poolId, params.laneId, nextMemoSeq, programId).address,
765
+ isSigner: false,
766
+ isWritable: true,
767
+ });
768
+ }
769
+ if (params.hookAccounts)
770
+ accounts.push(...params.hookAccounts);
771
+ return { programId, accounts, data };
772
+ }
773
+ /** Tag 4: `InitRootHistory` (`4 + activeLanes` accounts, 13 B). */
774
+ export function buildInitRootHistoryInstruction(params) {
775
+ const rootEpochInterval = params.rootEpochInterval ?? DEFAULT_ROOT_EPOCH_INTERVAL;
776
+ assertU32(params.poolId, 'poolId');
777
+ assertRootEpochInterval(rootEpochInterval);
778
+ if (!Number.isInteger(params.activeLanes) || params.activeLanes < 0 || params.activeLanes > NUM_LANES) {
779
+ throw new RangeError(`activeLanes must be an integer in 0..=${NUM_LANES}, got ${params.activeLanes}`);
780
+ }
781
+ const programId = params.programId ?? AUDREN_PROGRAM_ID;
782
+ const data = concat(new Uint8Array([TAG_INIT_ROOT_HISTORY]), u32le(params.poolId, 'poolId'), u64le(rootEpochInterval, 'rootEpochInterval'));
783
+ const accounts = [
784
+ { pubkey: params.authority, isSigner: true, isWritable: true },
785
+ { pubkey: derivePoolPdaSync(params.poolId, programId).address, isSigner: false, isWritable: true },
786
+ { pubkey: deriveRootsPdaSync(params.poolId, programId).address, isSigner: false, isWritable: true },
787
+ { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },
788
+ ];
789
+ for (let l = 0; l < params.activeLanes; l++) {
790
+ accounts.push({
791
+ pubkey: deriveLanePdaSync(params.poolId, l, programId).address,
792
+ isSigner: false,
793
+ isWritable: false,
794
+ });
795
+ }
796
+ return { programId, accounts, data };
797
+ }
798
+ /**
799
+ * Tag 5: `Transact` (`380 + num_outputs * 106 B`).
800
+ * Supports `ASSET_MODE_PRIVATE` (0) and `ASSET_MODE_PUBLIC` (1, including `unwrapWsol: true`
801
+ * atomic WSOL -> Native SOL unwrapping and pause-exempt full exits with read-only `roots`).
802
+ */
803
+ export function buildTransactInstruction(params) {
804
+ assertLen(params.proof192, GROTH16_PROOF_LEN, 'proof192');
805
+ assertLen(params.nf0, 32, 'nf0');
806
+ assertLen(params.nf1, 32, 'nf1');
807
+ assertLen(params.cm0, 32, 'cm0');
808
+ assertLen(params.cm1, 32, 'cm1');
809
+ assertLen(params.cm2, 32, 'cm2');
810
+ assertUint8Array(params.memosBytes, 'memosBytes');
811
+ assertU32(params.poolId, 'poolId');
812
+ const vkId = params.vkId ?? VK_ID_DEFAULT;
813
+ assertU8(vkId, 'vkId');
814
+ assertRootRing(params.rootRingKind, params.rootRingIdx);
815
+ assertLaneId(params.outLaneId, 'outLaneId');
816
+ assertU64(params.outSubSeq, 'outSubSeq');
817
+ assertU64(params.outRootSeq, 'outRootSeq');
818
+ assertU64(params.outMemoSeq, 'outMemoSeq');
819
+ assertU64(params.outNfSeq, 'outNfSeq');
820
+ if (!Number.isInteger(params.outputMask) || params.outputMask < 0 || params.outputMask > 0b111) {
821
+ throw new RangeError(`outputMask must be an integer in 0..=7, got ${params.outputMask}`);
822
+ }
823
+ if (params.assetMode !== ASSET_MODE_PRIVATE && params.assetMode !== ASSET_MODE_PUBLIC) {
824
+ throw new RangeError(`Invalid assetMode ${params.assetMode} (expected 0=PRIVATE or 1=PUBLIC)`);
825
+ }
826
+ const unwrapWsol = Boolean(params.unwrapWsol);
827
+ if (unwrapWsol && params.assetMode !== ASSET_MODE_PUBLIC) {
828
+ throw new Error('unwrapWsol requires ASSET_MODE_PUBLIC');
829
+ }
830
+ assertU64(params.publicAmountOut, 'publicAmountOut');
831
+ assertU64(params.relayerFeeAmount, 'relayerFeeAmount');
832
+ if (params.publicAmountOut > 0n && !params.recipient) {
833
+ throw new Error('recipient is required when publicAmountOut > 0');
834
+ }
835
+ if (params.relayerFeeAmount > 0n && !params.relayerFeeRecipient) {
836
+ throw new Error('relayerFeeRecipient is required when relayerFeeAmount > 0');
837
+ }
838
+ const programId = params.programId ?? AUDREN_PROGRAM_ID;
839
+ const rSub = params.rollover?.nextSubSeq ?? null;
840
+ const rMemo = params.rollover?.nextMemoSeq ?? null;
841
+ const rNf = params.rollover?.nextNfSeq ?? null;
842
+ if (rSub != null)
843
+ assertU64(rSub, 'rollover.nextSubSeq');
844
+ if (rMemo != null)
845
+ assertU64(rMemo, 'rollover.nextMemoSeq');
846
+ if (rNf != null)
847
+ assertU64(rNf, 'rollover.nextNfSeq');
848
+ const flags = (rSub != null ? 1 : 0) |
849
+ (rMemo != null ? 2 : 0) |
850
+ (rNf != null ? 4 : 0) |
851
+ (unwrapWsol ? WITHDRAW_FLAG_UNWRAP_WSOL : 0);
852
+ const data = concat(new Uint8Array([TAG_TRANSACT]), u32le(params.poolId, 'poolId'), new Uint8Array([
853
+ vkId,
854
+ params.outLaneId,
855
+ params.outputMask,
856
+ params.assetMode,
857
+ flags,
858
+ params.rootRingKind,
859
+ params.rootRingIdx,
860
+ ]), params.proof192, params.nf0, params.nf1, params.cm0, params.cm1, params.cm2, u64le(params.publicAmountOut), u64le(params.relayerFeeAmount), params.memosBytes);
861
+ const nf1Meta = isAllZero32(params.nf1)
862
+ ? { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false }
863
+ : {
864
+ pubkey: deriveNullifierPdaSync(params.poolId, params.nf1, programId).address,
865
+ isSigner: false,
866
+ isWritable: true,
867
+ };
868
+ const accounts = [
869
+ { pubkey: params.payer, isSigner: true, isWritable: true },
870
+ { pubkey: derivePoolPdaSync(params.poolId, programId).address, isSigner: false, isWritable: false },
871
+ {
872
+ pubkey: deriveRootsPdaSync(params.poolId, programId).address,
873
+ isSigner: false,
874
+ isWritable: params.outputMask !== 0,
875
+ },
876
+ { pubkey: deriveNullifierPdaSync(params.poolId, params.nf0, programId).address, isSigner: false, isWritable: true },
877
+ nf1Meta,
878
+ { pubkey: deriveLanePdaSync(params.poolId, params.outLaneId, programId).address, isSigner: false, isWritable: true },
879
+ { pubkey: deriveLaneRentVaultPdaSync(params.poolId, params.outLaneId, programId).address, isSigner: false, isWritable: true },
880
+ { pubkey: deriveSubtreePdaSync(params.poolId, params.outLaneId, params.outSubSeq, programId).address, isSigner: false, isWritable: true },
881
+ { pubkey: deriveSubrootPdaSync(params.poolId, params.outLaneId, params.outRootSeq, programId).address, isSigner: false, isWritable: true },
882
+ { pubkey: deriveMemoPdaSync(params.poolId, params.outLaneId, params.outMemoSeq, programId).address, isSigner: false, isWritable: true },
883
+ { pubkey: deriveNfPagePdaSync(params.poolId, params.outLaneId, params.outNfSeq, programId).address, isSigner: false, isWritable: true },
884
+ { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },
885
+ ];
886
+ const rec = params.recipient ?? SYSTEM_PROGRAM_ID;
887
+ const feeRec = params.relayerFeeRecipient ?? SYSTEM_PROGRAM_ID;
888
+ if (params.assetMode === ASSET_MODE_PUBLIC) {
889
+ const outflow = params.publicOutflow ??
890
+ (unwrapWsol ? { mint: WSOL_MINT, tokenProgram: CLASSIC_TOKEN_PROGRAM_ID } : null);
891
+ if (!outflow) {
892
+ throw new Error('publicOutflow is required for ASSET_MODE_PUBLIC');
893
+ }
894
+ const vaultAuth = deriveVaultAuthPdaSync(params.poolId, programId).address;
895
+ const tokenProgram = outflow.tokenProgram ?? CLASSIC_TOKEN_PROGRAM_ID;
896
+ const vaultAta = outflow.vaultAta ??
897
+ deriveAssociatedTokenAddressSync(vaultAuth, outflow.mint, tokenProgram).address;
898
+ accounts.push({ pubkey: vaultAuth, isSigner: false, isWritable: false });
899
+ accounts.push({ pubkey: outflow.mint, isSigner: false, isWritable: false });
900
+ accounts.push({ pubkey: vaultAta, isSigner: false, isWritable: true });
901
+ accounts.push({ pubkey: tokenProgram, isSigner: false, isWritable: false });
902
+ accounts.push({ pubkey: rec, isSigner: false, isWritable: true });
903
+ accounts.push({ pubkey: feeRec, isSigner: false, isWritable: params.relayerFeeAmount > 0n });
904
+ if (unwrapWsol) {
905
+ accounts.push({
906
+ pubkey: deriveUnwrapPdaSync(params.poolId, params.nf0, programId).address,
907
+ isSigner: false,
908
+ isWritable: true,
909
+ });
910
+ }
911
+ }
912
+ if (rSub != null) {
913
+ accounts.push({
914
+ pubkey: deriveSubtreePdaSync(params.poolId, params.outLaneId, rSub, programId).address,
915
+ isSigner: false,
916
+ isWritable: true,
917
+ });
918
+ }
919
+ if (rMemo != null) {
920
+ accounts.push({
921
+ pubkey: deriveMemoPdaSync(params.poolId, params.outLaneId, rMemo, programId).address,
922
+ isSigner: false,
923
+ isWritable: true,
924
+ });
925
+ }
926
+ if (rNf != null) {
927
+ accounts.push({
928
+ pubkey: deriveNfPagePdaSync(params.poolId, params.outLaneId, rNf, programId).address,
929
+ isSigner: false,
930
+ isWritable: true,
931
+ });
932
+ }
933
+ if (params.hookAccounts)
934
+ accounts.push(...params.hookAccounts);
935
+ return { programId, accounts, data };
936
+ }
937
+ /**
938
+ * Tag 6: `ExecViaEscrow` (`560 + routerIxData.length + num_changes * 106 B`, SPL/Token-2022 only).
939
+ */
940
+ export function buildExecViaEscrowInstruction(params) {
941
+ assertLen(params.proof192, GROTH16_PROOF_LEN, 'proof192');
942
+ assertLen(params.nf0, 32, 'nf0');
943
+ assertLen(params.nf1, 32, 'nf1');
944
+ assertLen(params.cm0, 32, 'cm0');
945
+ assertLen(params.cm1, 32, 'cm1');
946
+ assertLen(params.cm2, 32, 'cm2');
947
+ assertLen(params.outStealthOwner, 32, 'outStealthOwner');
948
+ assertLen(params.outBlinding, 32, 'outBlinding');
949
+ assertLen(params.dynMemoHead, DYN_MEMO_HEAD_LEN, 'dynMemoHead');
950
+ assertLen(params.dynMemoMask, MEMO_CT_LEN, 'dynMemoMask');
951
+ assertUint8Array(params.routerIxData, 'routerIxData');
952
+ assertUint8Array(params.changeMemos, 'changeMemos');
953
+ if (!Array.isArray(params.routerAccounts)) {
954
+ throw new RangeError('routerAccounts must be an array');
955
+ }
956
+ assertU32(params.poolId, 'poolId');
957
+ const vkId = params.vkId ?? VK_ID_DEFAULT;
958
+ assertU8(vkId, 'vkId');
959
+ assertRootRing(params.rootRingKind, params.rootRingIdx);
960
+ assertLaneId(params.outLaneId, 'outLaneId');
961
+ assertU64(params.outSubSeq, 'outSubSeq');
962
+ assertU64(params.outRootSeq, 'outRootSeq');
963
+ assertU64(params.outMemoSeq, 'outMemoSeq');
964
+ assertU64(params.outNfSeq, 'outNfSeq');
965
+ assertEscrowShard(params.escrowShard);
966
+ if (!Number.isInteger(params.changeMask) || params.changeMask < 0 || params.changeMask > 0b11) {
967
+ throw new RangeError(`changeMask must be an integer in 0..=3, got ${params.changeMask}`);
968
+ }
969
+ assertU64(params.amountIn, 'amountIn');
970
+ assertU64(params.minAmountOut, 'minAmountOut');
971
+ assertU64(params.relayerFeeAmount, 'relayerFeeAmount');
972
+ assertU16(params.routerIxData.byteLength, 'routerIxData.byteLength');
973
+ assertU16(params.routerAccounts.length, 'routerAccounts.length');
974
+ if (params.relayerFeeAmount > 0n && !params.relayerFeeRecipient) {
975
+ throw new Error('relayerFeeRecipient is required when relayerFeeAmount > 0');
976
+ }
977
+ const programId = params.programId ?? AUDREN_PROGRAM_ID;
978
+ const vaultAuth = deriveVaultAuthPdaSync(params.poolId, programId).address;
979
+ const escrowPda = deriveEscrowPdaSync(params.poolId, params.escrowShard, programId).address;
980
+ const feeOnOutput = Boolean(params.feeOnOutput);
981
+ const rSub = params.rollover?.nextSubSeq ?? null;
982
+ const rMemo = params.rollover?.nextMemoSeq ?? null;
983
+ const rNf = params.rollover?.nextNfSeq ?? null;
984
+ if (rSub != null)
985
+ assertU64(rSub, 'rollover.nextSubSeq');
986
+ if (rMemo != null)
987
+ assertU64(rMemo, 'rollover.nextMemoSeq');
988
+ if (rNf != null)
989
+ assertU64(rNf, 'rollover.nextNfSeq');
990
+ const flags = (rSub != null ? 1 : 0) |
991
+ (rMemo != null ? 2 : 0) |
992
+ (rNf != null ? 4 : 0) |
993
+ (feeOnOutput ? EXEC_FLAG_FEE_ON_OUTPUT : 0);
994
+ const data = concat(new Uint8Array([TAG_EXEC_VIA_ESCROW]), u32le(params.poolId, 'poolId'), new Uint8Array([
995
+ vkId,
996
+ params.outLaneId,
997
+ params.escrowShard,
998
+ params.changeMask,
999
+ flags,
1000
+ params.rootRingKind,
1001
+ params.rootRingIdx,
1002
+ ]), params.proof192, params.nf0, params.nf1, params.cm0, params.cm1, params.cm2, u64le(params.amountIn), u64le(params.minAmountOut), u64le(params.relayerFeeAmount), params.outStealthOwner, params.outBlinding, params.dynMemoHead, params.dynMemoMask, u16le(params.routerIxData.byteLength), params.routerIxData, params.changeMemos);
1003
+ const nf1Meta = isAllZero32(params.nf1)
1004
+ ? { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false }
1005
+ : {
1006
+ pubkey: deriveNullifierPdaSync(params.poolId, params.nf1, programId).address,
1007
+ isSigner: false,
1008
+ isWritable: true,
1009
+ };
1010
+ const inTokenProg = params.inLeg.tokenProgram ?? CLASSIC_TOKEN_PROGRAM_ID;
1011
+ const inVaultAta = params.inLeg.vaultAta ??
1012
+ deriveAssociatedTokenAddressSync(vaultAuth, params.inLeg.mint, inTokenProg).address;
1013
+ const inEscrowAta = params.inLeg.escrowAta ??
1014
+ deriveAssociatedTokenAddressSync(escrowPda, params.inLeg.mint, inTokenProg).address;
1015
+ const outTokenProg = params.outLeg.tokenProgram ?? CLASSIC_TOKEN_PROGRAM_ID;
1016
+ const outVaultAta = params.outLeg.vaultAta ??
1017
+ deriveAssociatedTokenAddressSync(vaultAuth, params.outLeg.mint, outTokenProg).address;
1018
+ const outEscrowAta = params.outLeg.escrowAta ??
1019
+ deriveAssociatedTokenAddressSync(escrowPda, params.outLeg.mint, outTokenProg).address;
1020
+ const accounts = [
1021
+ { pubkey: params.payer, isSigner: true, isWritable: true },
1022
+ { pubkey: derivePoolPdaSync(params.poolId, programId).address, isSigner: false, isWritable: false },
1023
+ { pubkey: deriveRootsPdaSync(params.poolId, programId).address, isSigner: false, isWritable: true },
1024
+ { pubkey: deriveNullifierPdaSync(params.poolId, params.nf0, programId).address, isSigner: false, isWritable: true },
1025
+ nf1Meta,
1026
+ { pubkey: deriveLanePdaSync(params.poolId, params.outLaneId, programId).address, isSigner: false, isWritable: true },
1027
+ { pubkey: deriveLaneRentVaultPdaSync(params.poolId, params.outLaneId, programId).address, isSigner: false, isWritable: true },
1028
+ { pubkey: deriveSubtreePdaSync(params.poolId, params.outLaneId, params.outSubSeq, programId).address, isSigner: false, isWritable: true },
1029
+ { pubkey: deriveSubrootPdaSync(params.poolId, params.outLaneId, params.outRootSeq, programId).address, isSigner: false, isWritable: true },
1030
+ { pubkey: deriveMemoPdaSync(params.poolId, params.outLaneId, params.outMemoSeq, programId).address, isSigner: false, isWritable: true },
1031
+ { pubkey: deriveNfPagePdaSync(params.poolId, params.outLaneId, params.outNfSeq, programId).address, isSigner: false, isWritable: true },
1032
+ { pubkey: escrowPda, isSigner: false, isWritable: true },
1033
+ { pubkey: params.routerProg, isSigner: false, isWritable: false },
1034
+ { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },
1035
+ // Input leg
1036
+ { pubkey: vaultAuth, isSigner: false, isWritable: false },
1037
+ { pubkey: params.inLeg.mint, isSigner: false, isWritable: false },
1038
+ { pubkey: inVaultAta, isSigner: false, isWritable: true },
1039
+ { pubkey: inEscrowAta, isSigner: false, isWritable: true },
1040
+ { pubkey: inTokenProg, isSigner: false, isWritable: false },
1041
+ ];
1042
+ if (params.relayerFeeAmount > 0n && !feeOnOutput) {
1043
+ accounts.push({ pubkey: params.relayerFeeRecipient, isSigner: false, isWritable: true });
1044
+ }
1045
+ // Output leg
1046
+ accounts.push({ pubkey: vaultAuth, isSigner: false, isWritable: false }, { pubkey: params.outLeg.mint, isSigner: false, isWritable: false }, { pubkey: outVaultAta, isSigner: false, isWritable: true }, { pubkey: outEscrowAta, isSigner: false, isWritable: true }, { pubkey: outTokenProg, isSigner: false, isWritable: false });
1047
+ if (params.relayerFeeAmount > 0n && feeOnOutput) {
1048
+ accounts.push({ pubkey: params.relayerFeeRecipient, isSigner: false, isWritable: true });
1049
+ }
1050
+ if (rSub != null) {
1051
+ accounts.push({
1052
+ pubkey: deriveSubtreePdaSync(params.poolId, params.outLaneId, rSub, programId).address,
1053
+ isSigner: false,
1054
+ isWritable: true,
1055
+ });
1056
+ }
1057
+ if (rMemo != null) {
1058
+ accounts.push({
1059
+ pubkey: deriveMemoPdaSync(params.poolId, params.outLaneId, rMemo, programId).address,
1060
+ isSigner: false,
1061
+ isWritable: true,
1062
+ });
1063
+ }
1064
+ if (rNf != null) {
1065
+ accounts.push({
1066
+ pubkey: deriveNfPagePdaSync(params.poolId, params.outLaneId, rNf, programId).address,
1067
+ isSigner: false,
1068
+ isWritable: true,
1069
+ });
1070
+ }
1071
+ const precedingWritable = accounts.filter((a) => a.isWritable).map((a) => a.pubkey);
1072
+ const normalizedRouterAccounts = prepareEscrowAccountsForAudren(params.routerAccounts, escrowPda, params.extraWritablePubkeys
1073
+ ? [...precedingWritable, ...params.extraWritablePubkeys]
1074
+ : precedingWritable);
1075
+ accounts.push(...normalizedRouterAccounts);
1076
+ return { programId, accounts, data };
1077
+ }
1078
+ /** Tag 7: `SetPaused` (2 accounts, 6 B). */
1079
+ export function buildSetPausedInstruction(params) {
1080
+ const programId = params.programId ?? AUDREN_PROGRAM_ID;
1081
+ const data = concat(new Uint8Array([TAG_SET_PAUSED]), u32le(params.poolId), new Uint8Array([params.paused ? 1 : 0]));
1082
+ return {
1083
+ programId,
1084
+ accounts: [
1085
+ { pubkey: params.authority, isSigner: true, isWritable: false },
1086
+ { pubkey: derivePoolPdaSync(params.poolId, programId).address, isSigner: false, isWritable: true },
1087
+ ],
1088
+ data,
1089
+ };
1090
+ }
1091
+ /**
1092
+ * Tag 8: `UpdatePool` (2 accounts: `signer(s)`, `pool(w)`).
1093
+ * Sub-actions: `params` (22 B: `noteRentFee` + `nfRentFee`), `proposeAuthority` (38 B),
1094
+ * `acceptAuthority` (6 B), `renounceAuthority` (6 B, requires `!paused`).
1095
+ */
1096
+ export function buildUpdatePoolInstruction(params) {
1097
+ if (!params || typeof params !== 'object' || !params.action || typeof params.action !== 'object') {
1098
+ throw new RangeError('buildUpdatePoolInstruction requires a valid action object');
1099
+ }
1100
+ const programId = params.programId ?? AUDREN_PROGRAM_ID;
1101
+ let data;
1102
+ switch (params.action.kind) {
1103
+ case 'params':
1104
+ data = concat(new Uint8Array([TAG_UPDATE_POOL]), u32le(params.poolId, 'poolId'), new Uint8Array([UPDATE_POOL_PARAMS]), u64le(params.action.noteRentFee, 'noteRentFee'), u64le(params.action.nfRentFee, 'nfRentFee'));
1105
+ break;
1106
+ case 'proposeAuthority':
1107
+ data = concat(new Uint8Array([TAG_UPDATE_POOL]), u32le(params.poolId, 'poolId'), new Uint8Array([UPDATE_POOL_PROPOSE_AUTHORITY]), toPubkeyBytes(params.action.pendingAuthority));
1108
+ break;
1109
+ case 'acceptAuthority':
1110
+ data = concat(new Uint8Array([TAG_UPDATE_POOL]), u32le(params.poolId, 'poolId'), new Uint8Array([UPDATE_POOL_ACCEPT_AUTHORITY]));
1111
+ break;
1112
+ case 'renounceAuthority':
1113
+ data = concat(new Uint8Array([TAG_UPDATE_POOL]), u32le(params.poolId, 'poolId'), new Uint8Array([UPDATE_POOL_RENOUNCE_AUTHORITY]));
1114
+ break;
1115
+ default:
1116
+ throw new RangeError(`Unknown UpdatePool action kind: ${String(params.action.kind)}`);
1117
+ }
1118
+ return {
1119
+ programId,
1120
+ accounts: [
1121
+ { pubkey: params.signer, isSigner: true, isWritable: false },
1122
+ { pubkey: derivePoolPdaSync(params.poolId, programId).address, isSigner: false, isWritable: true },
1123
+ ],
1124
+ data,
1125
+ };
1126
+ }
1127
+ /** Tag 8 convenience builder for `UPDATE_POOL_PARAMS` (`22 B`: `noteRentFee`, `nfRentFee`). */
1128
+ export function buildUpdatePoolParamsInstruction(params) {
1129
+ return buildUpdatePoolInstruction({
1130
+ programId: params.programId,
1131
+ signer: params.authority,
1132
+ poolId: params.poolId,
1133
+ action: {
1134
+ kind: 'params',
1135
+ noteRentFee: params.noteRentFee,
1136
+ nfRentFee: params.nfRentFee,
1137
+ },
1138
+ });
1139
+ }