@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.
Files changed (52) hide show
  1. package/README.md +1257 -272
  2. package/dist/cjs/client.d.ts +407 -0
  3. package/dist/cjs/client.js +914 -0
  4. package/dist/cjs/config.d.ts +82 -0
  5. package/dist/cjs/config.js +57 -0
  6. package/dist/cjs/events.d.ts +77 -0
  7. package/dist/cjs/events.js +167 -0
  8. package/dist/cjs/idl/privacy_pool.json +10313 -0
  9. package/dist/cjs/index.d.ts +13 -0
  10. package/dist/cjs/index.js +57 -0
  11. package/dist/cjs/merkle.d.ts +64 -0
  12. package/dist/cjs/merkle.js +133 -0
  13. package/dist/cjs/poseidon.d.ts +29 -0
  14. package/dist/cjs/poseidon.js +100 -0
  15. package/dist/cjs/program.d.ts +26 -0
  16. package/dist/cjs/program.js +38 -0
  17. package/dist/cjs/proof.d.ts +183 -0
  18. package/dist/cjs/proof.js +292 -0
  19. package/dist/cjs/prover.d.ts +54 -0
  20. package/dist/cjs/prover.js +112 -0
  21. package/dist/cjs/relayer.d.ts +295 -0
  22. package/dist/cjs/relayer.js +246 -0
  23. package/dist/cjs/retry.d.ts +32 -0
  24. package/dist/cjs/retry.js +75 -0
  25. package/dist/cjs/utxo.d.ts +215 -0
  26. package/dist/cjs/utxo.js +394 -0
  27. package/dist/esm/client.js +887 -0
  28. package/dist/esm/config.js +51 -0
  29. package/dist/esm/events.js +129 -0
  30. package/dist/esm/idl/privacy_pool.json +10313 -0
  31. package/dist/esm/index.js +22 -0
  32. package/dist/esm/merkle.js +129 -0
  33. package/dist/esm/poseidon.js +87 -0
  34. package/dist/esm/program.js +31 -0
  35. package/dist/esm/proof.js +281 -0
  36. package/dist/esm/prover.js +75 -0
  37. package/dist/esm/relayer.js +238 -0
  38. package/dist/esm/retry.js +71 -0
  39. package/dist/esm/utxo.js +372 -0
  40. package/package.json +47 -11
  41. package/src/client.ts +0 -352
  42. package/src/config.ts +0 -13
  43. package/src/index.ts +0 -6
  44. package/src/merkle.ts +0 -178
  45. package/src/note.ts +0 -193
  46. package/src/poseidon.ts +0 -62
  47. package/src/proof.ts +0 -170
  48. package/test/script.js +0 -0
  49. package/test-tsconfig.json +0 -19
  50. package/tests/note.test.ts +0 -50
  51. package/tests/sdk.integration.test.ts +0 -210
  52. package/tsconfig.json +0 -18
@@ -0,0 +1,82 @@
1
+ import { PublicKey } from "@solana/web3.js";
2
+ /** Default relayer fee in basis points (50 = 0.5%). */
3
+ export declare const DEFAULT_FEE_BPS = 50;
4
+ /** Merkle tree depth - matches on-chain MerkleTreeAccount subtrees array size */
5
+ export declare const MERKLE_TREE_DEPTH = 22;
6
+ /** Root history size - matches on-chain MerkleTreeAccount root_history array size */
7
+ export declare const ROOT_HISTORY_SIZE = 256;
8
+ /** Native SOL mint address (Pubkey::default() = all zeros) */
9
+ export declare const NATIVE_SOL_MINT: PublicKey;
10
+ /** Convert SOL to lamports (e.g. `sol(1.5)` → `1_500_000_000n`). */
11
+ export declare function sol(n: number): bigint;
12
+ /** Configuration for initializing a privacy pool */
13
+ export type PoolInitConfig = {
14
+ /** Fee in basis points (0-10000, where 10000 = 100%) */
15
+ feeBps?: number;
16
+ /** Token mint address (use NATIVE_SOL_MINT for SOL pools) */
17
+ mintAddress: PublicKey;
18
+ /** Minimum deposit amount in lamports/token units */
19
+ minDepositAmount?: bigint;
20
+ /** Maximum deposit amount in lamports/token units */
21
+ maxDepositAmount?: bigint;
22
+ /** Minimum withdrawal amount in lamports/token units */
23
+ minWithdrawAmount?: bigint;
24
+ /** Maximum withdrawal amount in lamports/token units */
25
+ maxWithdrawAmount?: bigint;
26
+ };
27
+ /** On-chain PrivacyConfig account structure */
28
+ export type PrivacyConfigAccount = {
29
+ bump: number;
30
+ vaultBump: number;
31
+ admin: PublicKey;
32
+ feeBps: number;
33
+ feeErrorMarginBps: number;
34
+ minWithdrawalFee: bigint;
35
+ /** Minimum fee kept by relayer on swaps (in destination token base units) */
36
+ minSwapFee: bigint;
37
+ /** Fee rate applied to swap output in basis points */
38
+ swapFeeBps: number;
39
+ totalTvl: bigint;
40
+ mintAddress: PublicKey;
41
+ minDepositAmount: bigint;
42
+ maxDepositAmount: bigint;
43
+ minWithdrawAmount: bigint;
44
+ maxWithdrawAmount: bigint;
45
+ numRelayers: number;
46
+ relayers: PublicKey[];
47
+ numTrees: number;
48
+ nextTreeIndex: number;
49
+ };
50
+ /** On-chain GlobalConfig account structure */
51
+ export type GlobalConfigAccount = {
52
+ bump: number;
53
+ admin: PublicKey;
54
+ relayerEnabled: boolean;
55
+ };
56
+ /**
57
+ * Compute the relayer fee for a withdrawal.
58
+ * Mirrors the formula in the relayer-server:
59
+ * fee = max(amount * feeBps / 10_000, minWithdrawalFee)
60
+ *
61
+ * @returns fee in base token units, and the amount that reaches the recipient
62
+ */
63
+ export declare function computeWithdrawalFee(amount: bigint, feeBps: number, minWithdrawalFee: bigint): {
64
+ fee: bigint;
65
+ toRecipient: bigint;
66
+ };
67
+ /**
68
+ * Compute the relayer fee for a cross-pool swap.
69
+ * Mirrors the formula in the relayer-server:
70
+ * relayerFee = max(estimatedOutput * swapFeeBps / 10_000, minSwapFee)
71
+ * destAmount = minAmountOut - relayerFee
72
+ *
73
+ * @param estimatedOutput Jupiter quote output amount
74
+ * @param swapFeeBps From the destination pool's PrivacyConfigAccount
75
+ * @param minSwapFee From the destination pool's PrivacyConfigAccount
76
+ * @param minAmountOut User-agreed minimum swap output (after slippage)
77
+ * @returns relayerFee and the amount committed into the destination UTXO
78
+ */
79
+ export declare function computeSwapFee(estimatedOutput: bigint, swapFeeBps: number, minSwapFee: bigint, minAmountOut: bigint): {
80
+ relayerFee: bigint;
81
+ destAmount: bigint;
82
+ };
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NATIVE_SOL_MINT = exports.ROOT_HISTORY_SIZE = exports.MERKLE_TREE_DEPTH = exports.DEFAULT_FEE_BPS = void 0;
4
+ exports.sol = sol;
5
+ exports.computeWithdrawalFee = computeWithdrawalFee;
6
+ exports.computeSwapFee = computeSwapFee;
7
+ const web3_js_1 = require("@solana/web3.js");
8
+ // -----------------------------------------------------------------------------
9
+ // Constants
10
+ // -----------------------------------------------------------------------------
11
+ /** Default relayer fee in basis points (50 = 0.5%). */
12
+ exports.DEFAULT_FEE_BPS = 50;
13
+ /** Merkle tree depth - matches on-chain MerkleTreeAccount subtrees array size */
14
+ exports.MERKLE_TREE_DEPTH = 22;
15
+ /** Root history size - matches on-chain MerkleTreeAccount root_history array size */
16
+ exports.ROOT_HISTORY_SIZE = 256;
17
+ /** Native SOL mint address (Pubkey::default() = all zeros) */
18
+ exports.NATIVE_SOL_MINT = web3_js_1.PublicKey.default;
19
+ // -----------------------------------------------------------------------------
20
+ // Helpers
21
+ // -----------------------------------------------------------------------------
22
+ /** Convert SOL to lamports (e.g. `sol(1.5)` → `1_500_000_000n`). */
23
+ function sol(n) {
24
+ return BigInt(n * web3_js_1.LAMPORTS_PER_SOL);
25
+ }
26
+ // -----------------------------------------------------------------------------
27
+ // Fee Calculation Helpers
28
+ // -----------------------------------------------------------------------------
29
+ /**
30
+ * Compute the relayer fee for a withdrawal.
31
+ * Mirrors the formula in the relayer-server:
32
+ * fee = max(amount * feeBps / 10_000, minWithdrawalFee)
33
+ *
34
+ * @returns fee in base token units, and the amount that reaches the recipient
35
+ */
36
+ function computeWithdrawalFee(amount, feeBps, minWithdrawalFee) {
37
+ const computed = (amount * BigInt(feeBps)) / 10000n;
38
+ const fee = computed > minWithdrawalFee ? computed : minWithdrawalFee;
39
+ return { fee, toRecipient: amount - fee };
40
+ }
41
+ /**
42
+ * Compute the relayer fee for a cross-pool swap.
43
+ * Mirrors the formula in the relayer-server:
44
+ * relayerFee = max(estimatedOutput * swapFeeBps / 10_000, minSwapFee)
45
+ * destAmount = minAmountOut - relayerFee
46
+ *
47
+ * @param estimatedOutput Jupiter quote output amount
48
+ * @param swapFeeBps From the destination pool's PrivacyConfigAccount
49
+ * @param minSwapFee From the destination pool's PrivacyConfigAccount
50
+ * @param minAmountOut User-agreed minimum swap output (after slippage)
51
+ * @returns relayerFee and the amount committed into the destination UTXO
52
+ */
53
+ function computeSwapFee(estimatedOutput, swapFeeBps, minSwapFee, minAmountOut) {
54
+ const computed = (estimatedOutput * BigInt(swapFeeBps)) / 10000n;
55
+ const relayerFee = computed > minSwapFee ? computed : minSwapFee;
56
+ return { relayerFee, destAmount: minAmountOut - relayerFee };
57
+ }
@@ -0,0 +1,77 @@
1
+ import { PublicKey } from "@solana/web3.js";
2
+ import { Program, Idl } from "@coral-xyz/anchor";
3
+ import { MerkleTree } from "./merkle";
4
+ /**
5
+ * On-chain CommitmentEvent emitted by `transact` and `transact_swap`.
6
+ * Mirrors the IDL CommitmentEvent struct.
7
+ */
8
+ export type CommitmentEvent = {
9
+ commitment: Uint8Array;
10
+ leafIndex: number;
11
+ newRoot: Uint8Array;
12
+ timestamp: number;
13
+ mintAddress: PublicKey;
14
+ treeId: number;
15
+ txSignature: string;
16
+ slot: number;
17
+ };
18
+ /**
19
+ * On-chain NullifierSpent event emitted when a UTXO is consumed.
20
+ * Mirrors the IDL NullifierSpent struct.
21
+ */
22
+ export type NullifierSpentEvent = {
23
+ nullifier: Uint8Array;
24
+ timestamp: number;
25
+ mintAddress: PublicKey;
26
+ treeId: number;
27
+ txSignature: string;
28
+ slot: number;
29
+ };
30
+ /**
31
+ * Fetch and parse CommitmentEvents for a program, optionally filtered by mint.
32
+ *
33
+ * @param program - Anchor program instance
34
+ * @param mintAddress - Filter to a specific pool; omit to get all pools
35
+ * @param before - Start paging before this signature (exclusive)
36
+ * @param until - Stop paging at this signature (exclusive)
37
+ * @param limit - Max signatures to fetch per page (default 1000)
38
+ */
39
+ export declare function scanCommitmentEvents<T extends Idl>(params: {
40
+ program: Program<T>;
41
+ mintAddress?: PublicKey;
42
+ before?: string;
43
+ until?: string;
44
+ limit?: number;
45
+ }): Promise<CommitmentEvent[]>;
46
+ /**
47
+ * Fetch and parse NullifierSpent events for a program, optionally filtered by mint.
48
+ */
49
+ export declare function scanNullifierEvents<T extends Idl>(params: {
50
+ program: Program<T>;
51
+ mintAddress?: PublicKey;
52
+ before?: string;
53
+ until?: string;
54
+ limit?: number;
55
+ }): Promise<NullifierSpentEvent[]>;
56
+ /**
57
+ * Rebuild a local MerkleTree from on-chain CommitmentEvents.
58
+ * Use this to get a valid inclusion proof for spending any UTXO.
59
+ *
60
+ * CommitmentEvents are sorted by (treeId, leafIndex) so the local tree
61
+ * matches the on-chain state exactly.
62
+ *
63
+ * @param program - Anchor program instance
64
+ * @param mintAddress - Pool to reconstruct
65
+ * @param treeId - Which tree to reconstruct (default 0)
66
+ * @param depth - Merkle tree depth (default 22, must match on-chain)
67
+ */
68
+ export declare function buildTreeFromEvents<T extends Idl>(params: {
69
+ program: Program<T>;
70
+ mintAddress: PublicKey;
71
+ treeId?: number;
72
+ depth?: number;
73
+ }): Promise<{
74
+ tree: MerkleTree;
75
+ events: CommitmentEvent[];
76
+ latestSignature?: string;
77
+ }>;
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.scanCommitmentEvents = scanCommitmentEvents;
37
+ exports.scanNullifierEvents = scanNullifierEvents;
38
+ exports.buildTreeFromEvents = buildTreeFromEvents;
39
+ const anchor = __importStar(require("@coral-xyz/anchor"));
40
+ const merkle_1 = require("./merkle");
41
+ // -----------------------------------------------------------------------------
42
+ // Event Scanning
43
+ // -----------------------------------------------------------------------------
44
+ /**
45
+ * Fetch and parse CommitmentEvents for a program, optionally filtered by mint.
46
+ *
47
+ * @param program - Anchor program instance
48
+ * @param mintAddress - Filter to a specific pool; omit to get all pools
49
+ * @param before - Start paging before this signature (exclusive)
50
+ * @param until - Stop paging at this signature (exclusive)
51
+ * @param limit - Max signatures to fetch per page (default 1000)
52
+ */
53
+ async function scanCommitmentEvents(params) {
54
+ const { program, mintAddress, before, until, limit = 1000 } = params;
55
+ const out = [];
56
+ const eventParser = new anchor.EventParser(program.programId, new anchor.BorshCoder(program.idl));
57
+ const sigs = await program.provider.connection.getSignaturesForAddress(program.programId, { before, until, limit });
58
+ for (const sigInfo of sigs) {
59
+ if (sigInfo.err)
60
+ continue;
61
+ const tx = await program.provider.connection.getTransaction(sigInfo.signature, { commitment: "confirmed", maxSupportedTransactionVersion: 0 });
62
+ if (!tx)
63
+ continue;
64
+ const events = Array.from(eventParser.parseLogs(tx.meta?.logMessages ?? []));
65
+ for (const ev of events) {
66
+ if (ev.name !== "commitmentEvent")
67
+ continue;
68
+ const d = ev.data;
69
+ const evMint = d.mintAddress;
70
+ if (mintAddress && !evMint.equals(mintAddress))
71
+ continue;
72
+ out.push({
73
+ commitment: new Uint8Array(d.commitment),
74
+ leafIndex: Number(d.leafIndex),
75
+ newRoot: new Uint8Array(d.newRoot),
76
+ timestamp: Number(d.timestamp),
77
+ mintAddress: evMint,
78
+ treeId: Number(d.treeId),
79
+ txSignature: sigInfo.signature,
80
+ slot: sigInfo.slot,
81
+ });
82
+ }
83
+ }
84
+ return out;
85
+ }
86
+ /**
87
+ * Fetch and parse NullifierSpent events for a program, optionally filtered by mint.
88
+ */
89
+ async function scanNullifierEvents(params) {
90
+ const { program, mintAddress, before, until, limit = 1000 } = params;
91
+ const out = [];
92
+ const eventParser = new anchor.EventParser(program.programId, new anchor.BorshCoder(program.idl));
93
+ const sigs = await program.provider.connection.getSignaturesForAddress(program.programId, { before, until, limit });
94
+ for (const sigInfo of sigs) {
95
+ if (sigInfo.err)
96
+ continue;
97
+ const tx = await program.provider.connection.getTransaction(sigInfo.signature, { commitment: "confirmed", maxSupportedTransactionVersion: 0 });
98
+ if (!tx)
99
+ continue;
100
+ const events = Array.from(eventParser.parseLogs(tx.meta?.logMessages ?? []));
101
+ for (const ev of events) {
102
+ if (ev.name !== "nullifierSpent")
103
+ continue;
104
+ const d = ev.data;
105
+ const evMint = d.mintAddress;
106
+ if (mintAddress && !evMint.equals(mintAddress))
107
+ continue;
108
+ out.push({
109
+ nullifier: new Uint8Array(d.nullifier),
110
+ timestamp: Number(d.timestamp),
111
+ mintAddress: evMint,
112
+ treeId: Number(d.treeId),
113
+ txSignature: sigInfo.signature,
114
+ slot: sigInfo.slot,
115
+ });
116
+ }
117
+ }
118
+ return out;
119
+ }
120
+ // -----------------------------------------------------------------------------
121
+ // Tree Reconstruction
122
+ // -----------------------------------------------------------------------------
123
+ /**
124
+ * Rebuild a local MerkleTree from on-chain CommitmentEvents.
125
+ * Use this to get a valid inclusion proof for spending any UTXO.
126
+ *
127
+ * CommitmentEvents are sorted by (treeId, leafIndex) so the local tree
128
+ * matches the on-chain state exactly.
129
+ *
130
+ * @param program - Anchor program instance
131
+ * @param mintAddress - Pool to reconstruct
132
+ * @param treeId - Which tree to reconstruct (default 0)
133
+ * @param depth - Merkle tree depth (default 22, must match on-chain)
134
+ */
135
+ async function buildTreeFromEvents(params) {
136
+ const { program, mintAddress, treeId = 0, depth = 22 } = params;
137
+ // Fetch all commitment events for this pool (page until no more results).
138
+ // Oldest-first so we insert leaves in the correct order.
139
+ const allEvents = [];
140
+ let before;
141
+ while (true) {
142
+ const page = await scanCommitmentEvents({
143
+ program,
144
+ mintAddress,
145
+ before,
146
+ limit: 1000,
147
+ });
148
+ if (page.length === 0)
149
+ break;
150
+ allEvents.push(...page);
151
+ before = page[page.length - 1].txSignature;
152
+ if (page.length < 1000)
153
+ break;
154
+ }
155
+ // Keep only events for this treeId, sort by leafIndex ascending
156
+ const treeEvents = allEvents
157
+ .filter((e) => e.treeId === treeId)
158
+ .sort((a, b) => a.leafIndex - b.leafIndex);
159
+ const tree = new merkle_1.MerkleTree(depth);
160
+ for (const ev of treeEvents) {
161
+ tree.insert(ev.commitment);
162
+ }
163
+ const latestSignature = treeEvents.length > 0
164
+ ? treeEvents[treeEvents.length - 1].txSignature
165
+ : undefined;
166
+ return { tree, events: treeEvents, latestSignature };
167
+ }