@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,22 @@
1
+ // Core client functions
2
+ export * from "./client";
3
+ // UTXO types and functions (replaces note.ts)
4
+ export * from "./utxo";
5
+ // Configuration constants and types
6
+ export * from "./config";
7
+ // Merkle tree implementation
8
+ export * from "./merkle";
9
+ // Proof types and helpers
10
+ export * from "./proof";
11
+ // On-chain event scanning and tree reconstruction
12
+ export * from "./events";
13
+ // Program factory and IDL
14
+ export { createVeiloProgram, PRIVACY_POOL_IDL, PRIVACY_POOL_PROGRAM_ID, } from "./program";
15
+ // Proof generation (requires snarkjs peer dependency)
16
+ export { createTransactionProver, verifyProof } from "./prover";
17
+ // Relayer API client
18
+ export * from "./relayer";
19
+ // RPC retry / resilience
20
+ export { withRpcRetry, DEFAULT_RPC_RETRY } from "./retry";
21
+ // Poseidon hash functions
22
+ export { initPoseidon, getPoseidon, BN254_FR_MODULUS, bytesToBigIntBE, bigIntToBytesBE, frToBigInt, poseidon1, poseidon2, poseidon3, poseidon4, pubkeyToField, } from "./poseidon";
@@ -0,0 +1,129 @@
1
+ import { BN254_FR_MODULUS, bytesToBigIntBE, bigIntToBytesBE, getPoseidon, frToBigInt, } from "./poseidon";
2
+ // Poseidon-based hash of two 32-byte field elements.
3
+ function hashPair(left, right) {
4
+ if (left.length !== 32 || right.length !== 32) {
5
+ throw new Error("hashPair expects 32-byte inputs");
6
+ }
7
+ const poseidon = getPoseidon();
8
+ const lf = bytesToBigIntBE(left) % BN254_FR_MODULUS;
9
+ const rf = bytesToBigIntBE(right) % BN254_FR_MODULUS;
10
+ const fe = poseidon([lf, rf]);
11
+ const outBig = frToBigInt(fe) % BN254_FR_MODULUS;
12
+ return bigIntToBytesBE(outBig);
13
+ }
14
+ /**
15
+ * Fixed-depth binary Merkle tree over BN254 Fr:
16
+ * - Leaves and internal nodes are 32-byte big-endian Fr elements.
17
+ * - Hash is Poseidon(2)(left, right).
18
+ * - Unfilled leaves use the Poseidon zero chain:
19
+ * zero[0] = 0
20
+ * zero[i+1] = Poseidon(zero[i], zero[i])
21
+ *
22
+ * Depth must match:
23
+ * - Circom WithdrawCircuit(depth)
24
+ * - Rust MERKLE_TREE_HEIGHT
25
+ */
26
+ export class MerkleTree {
27
+ constructor(depth = 22) {
28
+ this.depth = depth;
29
+ this.zeroes = [];
30
+ this.layers = [];
31
+ // zero[0] = 0 (Fr), then zero[i+1] = Poseidon(zero[i], zero[i])
32
+ let zero = bigIntToBytesBE(0n);
33
+ this.zeroes.push(zero);
34
+ for (let level = 1; level <= depth; level++) {
35
+ zero = hashPair(zero, zero);
36
+ this.zeroes.push(zero);
37
+ }
38
+ // Allocate layers:
39
+ // level 0: 2^depth leaves
40
+ // level 1: 2^(depth-1) parents
41
+ // ...
42
+ // level depth: 1 root
43
+ for (let level = 0; level <= depth; level++) {
44
+ const size = 1 << (depth - level);
45
+ if (!Number.isSafeInteger(size) || size <= 0) {
46
+ throw new Error(`Invalid MerkleTree depth=${depth}, level=${level}, size=${size}`);
47
+ }
48
+ const arr = new Array(size);
49
+ for (let i = 0; i < size; i++) {
50
+ arr[i] = this.zeroes[level];
51
+ }
52
+ this.layers.push(arr);
53
+ }
54
+ this.nextIndex = 0;
55
+ }
56
+ get capacity() {
57
+ return 1 << this.depth;
58
+ }
59
+ get root() {
60
+ return this.layers[this.depth][0];
61
+ }
62
+ /**
63
+ * Insert a leaf and recompute the path up to the root.
64
+ * Returns the leaf index and the new root.
65
+ */
66
+ insert(leaf) {
67
+ if (leaf.length !== 32) {
68
+ throw new Error("leaf must be 32 bytes");
69
+ }
70
+ const index = this.nextIndex;
71
+ if (index >= this.capacity) {
72
+ throw new Error("Merkle tree is full");
73
+ }
74
+ // Set leaf
75
+ this.layers[0][index] = leaf;
76
+ // Bubble up
77
+ let idx = index;
78
+ for (let level = 1; level <= this.depth; level++) {
79
+ const parentIndex = Math.floor(idx / 2);
80
+ const leftIndex = parentIndex * 2;
81
+ const rightIndex = leftIndex + 1;
82
+ const left = this.layers[level - 1][leftIndex];
83
+ const right = rightIndex < this.layers[level - 1].length
84
+ ? this.layers[level - 1][rightIndex]
85
+ : this.zeroes[level - 1];
86
+ this.layers[level][parentIndex] = hashPair(left, right);
87
+ idx = parentIndex;
88
+ }
89
+ this.nextIndex++;
90
+ return { index, root: this.root };
91
+ }
92
+ /**
93
+ * Return Merkle proof (path + indices) for a given leaf index.
94
+ * This feeds directly into the Circom `MerklePathVerifier(depth)`:
95
+ * - `pathElements[i]` = sibling
96
+ * - `pathIndices[i]` = 0/1 as defined above
97
+ */
98
+ getPath(index) {
99
+ if (index < 0 || index >= this.capacity) {
100
+ throw new Error("index out of range");
101
+ }
102
+ const path = [];
103
+ const indices = [];
104
+ let idx = index;
105
+ for (let level = 0; level < this.depth; level++) {
106
+ const isRight = idx % 2 === 1;
107
+ const siblingIndex = isRight ? idx - 1 : idx + 1;
108
+ const sibling = siblingIndex < this.layers[level].length
109
+ ? this.layers[level][siblingIndex]
110
+ : this.zeroes[level];
111
+ path.push(sibling);
112
+ // 0 = current is left, 1 = current is right
113
+ indices.push(isRight ? 1 : 0);
114
+ idx = Math.floor(idx / 2);
115
+ }
116
+ return { leafIndex: index, path, indices };
117
+ }
118
+ /**
119
+ * Return Merkle proof in circuit-compatible format.
120
+ * The circuit uses pathIndex directly and converts to bits via Num2Bits(levels).
121
+ */
122
+ getCircuitPath(index) {
123
+ const merklePath = this.getPath(index);
124
+ return {
125
+ pathIndex: index,
126
+ pathElements: merklePath.path.map((p) => bytesToBigIntBE(p) % BN254_FR_MODULUS),
127
+ };
128
+ }
129
+ }
@@ -0,0 +1,87 @@
1
+ import { buildPoseidonReference } from "circomlibjs";
2
+ let poseidonInstance = null;
3
+ /** Initialize the Poseidon hash instance. Must be called once before using any UTXO/merkle/proof helpers. */
4
+ export async function initPoseidon() {
5
+ poseidonInstance = (await buildPoseidonReference());
6
+ }
7
+ /** Get the initialized Poseidon instance. Throws if `initPoseidon()` has not been called. */
8
+ export function getPoseidon() {
9
+ if (!poseidonInstance) {
10
+ throw new Error("Poseidon not initialized. Call initPoseidon() once before using utxo/merkle/proof helpers.");
11
+ }
12
+ return poseidonInstance;
13
+ }
14
+ /** The BN254 (alt_bn128) scalar field modulus. All Poseidon outputs are reduced modulo this value. */
15
+ export const BN254_FR_MODULUS = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
16
+ /** Convert a big-endian byte array to a bigint. */
17
+ export function bytesToBigIntBE(bytes) {
18
+ let x = 0n;
19
+ for (const b of bytes) {
20
+ x = (x << 8n) | BigInt(b);
21
+ }
22
+ return x;
23
+ }
24
+ /** Convert a bigint to a 32-byte big-endian array. */
25
+ export function bigIntToBytesBE(x) {
26
+ const out = new Uint8Array(32);
27
+ let v = x;
28
+ for (let i = 31; i >= 0; i--) {
29
+ out[i] = Number(v & 0xffn);
30
+ v >>= 8n;
31
+ }
32
+ return out;
33
+ }
34
+ /** Convert ffjavascript field element → bigint safely */
35
+ export function frToBigInt(fe) {
36
+ const poseidon = getPoseidon();
37
+ const F = poseidon.F;
38
+ if (typeof fe === "bigint") {
39
+ return fe;
40
+ }
41
+ if (F && typeof F.toObject === "function") {
42
+ // This is how ffjavascript exposes the underlying BigInt
43
+ return F.toObject(fe);
44
+ }
45
+ // Fallback: treat as decimal string
46
+ return BigInt(fe.toString());
47
+ }
48
+ // -----------------------------------------------------------------------------
49
+ // Helper functions for variable-arity Poseidon hashing
50
+ // -----------------------------------------------------------------------------
51
+ /** Poseidon hash with 1 input - used for keypair derivation: pubkey = Poseidon(privateKey) */
52
+ export function poseidon1(a) {
53
+ const poseidon = getPoseidon();
54
+ const fe = poseidon([a % BN254_FR_MODULUS]);
55
+ return frToBigInt(fe) % BN254_FR_MODULUS;
56
+ }
57
+ /** Poseidon hash with 2 inputs */
58
+ export function poseidon2(a, b) {
59
+ const poseidon = getPoseidon();
60
+ const fe = poseidon([a % BN254_FR_MODULUS, b % BN254_FR_MODULUS]);
61
+ return frToBigInt(fe) % BN254_FR_MODULUS;
62
+ }
63
+ /** Poseidon hash with 3 inputs - used for signature: Poseidon(privateKey, commitment, pathIndex) */
64
+ export function poseidon3(a, b, c) {
65
+ const poseidon = getPoseidon();
66
+ const fe = poseidon([
67
+ a % BN254_FR_MODULUS,
68
+ b % BN254_FR_MODULUS,
69
+ c % BN254_FR_MODULUS,
70
+ ]);
71
+ return frToBigInt(fe) % BN254_FR_MODULUS;
72
+ }
73
+ /** Poseidon hash with 4 inputs - used for UTXO commitment: Poseidon(amount, pubkey, blinding, mintAddress) */
74
+ export function poseidon4(a, b, c, d) {
75
+ const poseidon = getPoseidon();
76
+ const fe = poseidon([
77
+ a % BN254_FR_MODULUS,
78
+ b % BN254_FR_MODULUS,
79
+ c % BN254_FR_MODULUS,
80
+ d % BN254_FR_MODULUS,
81
+ ]);
82
+ return frToBigInt(fe) % BN254_FR_MODULUS;
83
+ }
84
+ /** Convert a Solana PublicKey to a BN254 field element */
85
+ export function pubkeyToField(pubkey) {
86
+ return bytesToBigIntBE(pubkey.toBytes()) % BN254_FR_MODULUS;
87
+ }
@@ -0,0 +1,31 @@
1
+ import { Program, AnchorProvider } from "@coral-xyz/anchor";
2
+ import { PublicKey } from "@solana/web3.js";
3
+ import IDL_JSON from "./idl/privacy_pool.json";
4
+ // Re-export so consumers can access the raw IDL if needed
5
+ export const PRIVACY_POOL_IDL = IDL_JSON;
6
+ /** Deployed program ID extracted from the bundled IDL. */
7
+ export const PRIVACY_POOL_PROGRAM_ID = new PublicKey(IDL_JSON.address);
8
+ /**
9
+ * Create an Anchor `Program` instance for the Veilo Privacy Pool.
10
+ *
11
+ * @param connection Solana RPC connection
12
+ * @param wallet Anchor-compatible wallet (must implement `publicKey` and `signTransaction`)
13
+ * @param opts Optional commitment level (default: "confirmed")
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { createVeiloProgram } from "@veilo/sdk-core";
18
+ * import { Connection } from "@solana/web3.js";
19
+ *
20
+ * const program = createVeiloProgram(
21
+ * new Connection("https://api.devnet.solana.com"),
22
+ * wallet,
23
+ * );
24
+ * ```
25
+ */
26
+ export function createVeiloProgram(connection, wallet, opts) {
27
+ const provider = new AnchorProvider(connection, wallet, {
28
+ commitment: opts?.commitment ?? "confirmed",
29
+ });
30
+ return new Program(PRIVACY_POOL_IDL, provider);
31
+ }
@@ -0,0 +1,281 @@
1
+ import { sha256 } from "@noble/hashes/sha256";
2
+ import { BN254_FR_MODULUS, bigIntToBytesBE, bytesToBigIntBE, poseidon2, poseidon3, pubkeyToField, } from "./poseidon";
3
+ import { deriveNullifier } from "./utxo";
4
+ // -----------------------------------------------------------------------------
5
+ // ExtData Hash Computation
6
+ // -----------------------------------------------------------------------------
7
+ /**
8
+ * Compute the external data hash.
9
+ * Matches on-chain computation:
10
+ * hash1 = Poseidon(recipient, relayer)
11
+ * hash2 = Poseidon(fee, refund)
12
+ * extDataHash = Poseidon(hash1, hash2, claimant)
13
+ */
14
+ export function computeExtDataHash(extData) {
15
+ const recipientField = pubkeyToField(extData.recipient);
16
+ const relayerField = pubkeyToField(extData.relayer);
17
+ const feeField = extData.fee % BN254_FR_MODULUS;
18
+ const refundField = extData.refund % BN254_FR_MODULUS;
19
+ const claimantField = pubkeyToField(extData.claimant);
20
+ const hash1 = poseidon2(recipientField, relayerField);
21
+ const hash2 = poseidon2(feeField, refundField);
22
+ const finalHash = poseidon3(hash1, hash2, claimantField);
23
+ return bigIntToBytesBE(finalHash);
24
+ }
25
+ // -----------------------------------------------------------------------------
26
+ // Circuit Input Preparation
27
+ // -----------------------------------------------------------------------------
28
+ /**
29
+ * Convert i64 to field element (handles negative via modular arithmetic).
30
+ * For negative values, we add the field modulus to get the equivalent positive representation.
31
+ */
32
+ export function i64ToField(value) {
33
+ if (value >= 0n) {
34
+ return value % BN254_FR_MODULUS;
35
+ }
36
+ return (BN254_FR_MODULUS + value) % BN254_FR_MODULUS;
37
+ }
38
+ /**
39
+ * Prepare transaction circuit inputs from high-level parameters.
40
+ * This converts the SDK types into the format expected by the circuit.
41
+ */
42
+ export function prepareTransactionInputs(params) {
43
+ const { inputUTXOs, outputUTXOs, root, publicAmount, extData, mintAddress } = params;
44
+ const extDataHash = computeExtDataHash(extData);
45
+ const mintField = pubkeyToField(mintAddress);
46
+ // Prepare input UTXO data
47
+ const inAmount = [
48
+ inputUTXOs[0].amount,
49
+ inputUTXOs[1].amount,
50
+ ];
51
+ const inPubkey = [
52
+ inputUTXOs[0].pubkey,
53
+ inputUTXOs[1].pubkey,
54
+ ];
55
+ const inBlinding = [
56
+ inputUTXOs[0].blinding,
57
+ inputUTXOs[1].blinding,
58
+ ];
59
+ const inPathIndex = [
60
+ inputUTXOs[0].pathIndex,
61
+ inputUTXOs[1].pathIndex,
62
+ ];
63
+ const inPathElements = [
64
+ inputUTXOs[0].pathElements.map((e) => bytesToBigIntBE(e) % BN254_FR_MODULUS),
65
+ inputUTXOs[1].pathElements.map((e) => bytesToBigIntBE(e) % BN254_FR_MODULUS),
66
+ ];
67
+ const inPrivateKey = [
68
+ inputUTXOs[0].privateKey,
69
+ inputUTXOs[1].privateKey,
70
+ ];
71
+ // Prepare output UTXO data
72
+ const outAmount = [
73
+ outputUTXOs[0].amount,
74
+ outputUTXOs[1].amount,
75
+ ];
76
+ const outPubkey = [
77
+ outputUTXOs[0].pubkey,
78
+ outputUTXOs[1].pubkey,
79
+ ];
80
+ const outBlinding = [
81
+ outputUTXOs[0].blinding,
82
+ outputUTXOs[1].blinding,
83
+ ];
84
+ // Derive nullifiers for input UTXOs
85
+ const inputNullifiers = [
86
+ deriveNullifier(inputUTXOs[0], inputUTXOs[0].pathIndex, inputUTXOs[0].privateKey),
87
+ deriveNullifier(inputUTXOs[1], inputUTXOs[1].pathIndex, inputUTXOs[1].privateKey),
88
+ ];
89
+ return {
90
+ root,
91
+ publicAmount,
92
+ extDataHash,
93
+ mintAddress,
94
+ inputNullifiers,
95
+ outputCommitments: [outputUTXOs[0].commitment, outputUTXOs[1].commitment],
96
+ inAmount,
97
+ inPubkey,
98
+ inBlinding,
99
+ inPathIndex,
100
+ inPathElements,
101
+ inPrivateKey,
102
+ outAmount,
103
+ outPubkey,
104
+ outBlinding,
105
+ };
106
+ }
107
+ // -----------------------------------------------------------------------------
108
+ // Proof Packing
109
+ // -----------------------------------------------------------------------------
110
+ /**
111
+ * Convert bigint to 32-byte big-endian representation.
112
+ * The alt_bn128 Solana precompile (and ark-works via change_endianness) expect BE.
113
+ */
114
+ function bigintTo32BytesBE(x) {
115
+ const out = new Uint8Array(32);
116
+ let v = x;
117
+ for (let i = 31; i >= 0; i--) {
118
+ out[i] = Number(v & 0xffn);
119
+ v >>= 8n;
120
+ }
121
+ return out;
122
+ }
123
+ /**
124
+ * Turn a snarkjs Groth16 proof into 256 bytes:
125
+ * A(G1) | B(G2) | C(G1)
126
+ * where:
127
+ * A = (ax, ay) -> 64 bytes
128
+ * B = (bx1, bx0, by1, by0) -> 128 bytes (swapped pairs for alt_bn128)
129
+ * C = (cx, cy) -> 64 bytes
130
+ *
131
+ * Each field element is encoded as 32-byte BE to match the on-chain verifier.
132
+ * We ignore the extra projective/z components snarkjs keeps.
133
+ */
134
+ export function packProofToBytes(proof) {
135
+ const chunks = [];
136
+ const ax = BigInt(proof.pi_a[0]);
137
+ const ay = BigInt(proof.pi_a[1]);
138
+ chunks.push(bigintTo32BytesBE(ax), bigintTo32BytesBE(ay));
139
+ const bx = proof.pi_b[0];
140
+ const by = proof.pi_b[1];
141
+ const bx0 = BigInt(bx[0]);
142
+ const bx1 = BigInt(bx[1]);
143
+ const by0 = BigInt(by[0]);
144
+ const by1 = BigInt(by[1]);
145
+ // alt_bn128 expects the G2 pairs swapped: bx1 before bx0, by1 before by0
146
+ chunks.push(bigintTo32BytesBE(bx1), bigintTo32BytesBE(bx0), bigintTo32BytesBE(by1), bigintTo32BytesBE(by0));
147
+ const cx = BigInt(proof.pi_c[0]);
148
+ const cy = BigInt(proof.pi_c[1]);
149
+ chunks.push(bigintTo32BytesBE(cx), bigintTo32BytesBE(cy));
150
+ const out = new Uint8Array(32 * (2 + 4 + 2)); // 256
151
+ let offset = 0;
152
+ for (const c of chunks) {
153
+ out.set(c, offset);
154
+ offset += c.length;
155
+ }
156
+ return out;
157
+ }
158
+ /**
159
+ * Encode a snarkjs proof into the TransactionProofStruct format expected by the on-chain program.
160
+ */
161
+ export function encodeSnarkjsProofToTransactionProof(proof) {
162
+ const full = packProofToBytes(proof);
163
+ if (full.length !== 256) {
164
+ throw new Error(`Expected 256 proof bytes, got ${full.length}`);
165
+ }
166
+ const proofA = full.slice(0, 64);
167
+ const proofB = full.slice(64, 192);
168
+ const proofC = full.slice(192, 256);
169
+ return {
170
+ proofA: Array.from(proofA),
171
+ proofB: Array.from(proofB),
172
+ proofC: Array.from(proofC),
173
+ };
174
+ }
175
+ // -----------------------------------------------------------------------------
176
+ // Snarkjs Input Formatting
177
+ // -----------------------------------------------------------------------------
178
+ /**
179
+ * Convert TransactionCircuitInputs to the format expected by snarkjs.groth16.fullProve().
180
+ * All values are converted to strings (snarkjs expects string inputs for field elements).
181
+ */
182
+ export function formatInputsForSnarkjs(inputs) {
183
+ return {
184
+ // Public inputs
185
+ root: bytesToBigIntBE(inputs.root).toString(),
186
+ publicAmount: i64ToField(inputs.publicAmount).toString(),
187
+ extDataHash: bytesToBigIntBE(inputs.extDataHash).toString(),
188
+ mintAddress: pubkeyToField(inputs.mintAddress).toString(),
189
+ inputNullifier: inputs.inputNullifiers.map((n) => bytesToBigIntBE(n).toString()),
190
+ outputCommitment: inputs.outputCommitments.map((c) => bytesToBigIntBE(c).toString()),
191
+ // Private inputs - Input UTXOs
192
+ inAmount: inputs.inAmount.map((a) => a.toString()),
193
+ inPubkey: inputs.inPubkey.map((p) => p.toString()),
194
+ inBlinding: inputs.inBlinding.map((b) => b.toString()),
195
+ inPathIndex: inputs.inPathIndex.map((i) => i.toString()),
196
+ inPathElements: inputs.inPathElements.map((path) => path.map((e) => e.toString())),
197
+ inPrivateKey: inputs.inPrivateKey.map((k) => k.toString()),
198
+ // Private inputs - Output UTXOs
199
+ outAmount: inputs.outAmount.map((a) => a.toString()),
200
+ outPubkey: inputs.outPubkey.map((p) => p.toString()),
201
+ outBlinding: inputs.outBlinding.map((b) => b.toString()),
202
+ };
203
+ }
204
+ /**
205
+ * Convert SwapCircuitInputs into the shape expected by
206
+ * snarkjs.groth16.fullProve() for swap.circom. Every value is emitted as a
207
+ * decimal string (or string array) because snarkjs only accepts field
208
+ * elements as strings.
209
+ *
210
+ * Mirrors `generateSwapProof` in
211
+ * relayer-server/src/controllers/swap.helpers.ts so SDK-side swap proofs
212
+ * verify against the same circuit the relayer uses.
213
+ */
214
+ export function formatSwapInputsForSnarkjs(inputs) {
215
+ return {
216
+ // Public inputs
217
+ sourceRoot: bytesToBigIntBE(inputs.sourceRoot).toString(),
218
+ swapParamsHash: bytesToBigIntBE(inputs.swapParamsHash).toString(),
219
+ extDataHash: bytesToBigIntBE(inputs.extDataHash).toString(),
220
+ sourceMint: pubkeyToField(inputs.sourceMint).toString(),
221
+ destMint: pubkeyToField(inputs.destMint).toString(),
222
+ inputNullifier: inputs.inputNullifiers.map((n) => bytesToBigIntBE(n).toString()),
223
+ changeCommitment: bytesToBigIntBE(inputs.changeCommitment).toString(),
224
+ destCommitment: bytesToBigIntBE(inputs.destCommitment).toString(),
225
+ swapAmount: inputs.swapAmount.toString(),
226
+ // Private inputs - Input UTXOs
227
+ inAmount: inputs.inAmount.map((a) => a.toString()),
228
+ inPubkey: inputs.inPubkey.map((p) => p.toString()),
229
+ inBlinding: inputs.inBlinding.map((b) => b.toString()),
230
+ inPathIndex: inputs.inPathIndex.map((i) => i.toString()),
231
+ inPathElements: inputs.inPathElements.map((path) => path.map((e) => e.toString())),
232
+ inPrivateKey: inputs.inPrivateKey.map((k) => k.toString()),
233
+ // Private inputs - Change UTXO
234
+ changeAmount: inputs.changeAmount.toString(),
235
+ changePubkey: inputs.changePubkey.toString(),
236
+ changeBlinding: inputs.changeBlinding.toString(),
237
+ // Private inputs - Destination UTXO
238
+ destAmount: inputs.destAmount.toString(),
239
+ destPubkey: inputs.destPubkey.toString(),
240
+ destBlinding: inputs.destBlinding.toString(),
241
+ // Swap params
242
+ minAmountOut: inputs.minAmountOut.toString(),
243
+ deadline: inputs.deadline.toString(),
244
+ };
245
+ }
246
+ // -----------------------------------------------------------------------------
247
+ // Swap Parameter Hashing
248
+ // -----------------------------------------------------------------------------
249
+ /**
250
+ * Compute the swap params hash that the swap circuit and on-chain program verify.
251
+ * Mirrors relayer-server/src/controllers/swap.helpers.ts `computeSwapParamsHash`.
252
+ *
253
+ * Circuit formula (swap.circom lines 293-307):
254
+ * mintPairHash = Poseidon(sourceMint, destMint)
255
+ * swapTermsHash = Poseidon(minAmountOut, deadline, destAmount)
256
+ * swapParamsHash = Poseidon(mintPairHash, swapTermsHash)
257
+ *
258
+ * @param sourceMint Source pool mint
259
+ * @param destMint Destination pool mint
260
+ * @param minAmountOut Minimum accepted output amount (slippage protected)
261
+ * @param deadline Unix timestamp deadline (i64, 0 = no deadline)
262
+ * @param destAmount Actual amount committed to destination UTXO (≥ minAmountOut -
263
+ * relayerFee). If omitted, defaults to minAmountOut.
264
+ */
265
+ export function computeSwapParamsHash(sourceMint, destMint, minAmountOut, deadline, destAmount) {
266
+ const srcField = pubkeyToField(sourceMint);
267
+ const dstField = pubkeyToField(destMint);
268
+ const mintPairHash = poseidon2(srcField, dstField);
269
+ const dest = destAmount ?? minAmountOut;
270
+ const swapTermsHash = poseidon3(minAmountOut, deadline, dest);
271
+ const paramsHash = poseidon2(mintPairHash, swapTermsHash);
272
+ return bigIntToBytesBE(paramsHash);
273
+ }
274
+ /**
275
+ * Compute the swap data hash committed on-chain for Jupiter instruction integrity.
276
+ * SHA-256 of the raw Jupiter swap instruction data bytes.
277
+ * Mirrors relayer-server/src/controllers/swap.helpers.ts `computeSwapDataHash`.
278
+ */
279
+ export function computeSwapDataHash(swapData) {
280
+ return sha256(swapData instanceof Buffer ? new Uint8Array(swapData) : swapData);
281
+ }
@@ -0,0 +1,75 @@
1
+ import { formatInputsForSnarkjs, } from "./proof";
2
+ /** Lazy-load snarkjs — works in both CJS and ESM contexts. */
3
+ async function loadSnarkjs() {
4
+ try {
5
+ // Dynamic import works in both CJS (Node 12+) and ESM
6
+ return await Function('return import("snarkjs")')();
7
+ }
8
+ catch {
9
+ throw new Error("snarkjs is required for proof generation. Install it: npm install snarkjs");
10
+ }
11
+ }
12
+ /**
13
+ * Create a proof builder function for the transaction circuit.
14
+ *
15
+ * Uses dynamic `import("snarkjs")` so the dependency is only loaded when
16
+ * proof generation is actually called. Install snarkjs as a peer dependency:
17
+ *
18
+ * ```
19
+ * npm install snarkjs
20
+ * ```
21
+ *
22
+ * @param artifacts Paths or buffers to the circuit WASM and zkey files
23
+ * @returns A `TransactionProofBuilder` callback compatible with the SDK's client functions
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * import { createTransactionProver } from "@veilo/sdk-core";
28
+ *
29
+ * const prover = createTransactionProver({
30
+ * wasmPath: "./circuits/transaction.wasm",
31
+ * zkeyPath: "./circuits/transaction_final.zkey",
32
+ * });
33
+ *
34
+ * // Pass to SDK functions that accept a TransactionProofBuilder
35
+ * const proof = await prover(circuitInputs);
36
+ * ```
37
+ */
38
+ export function createTransactionProver(artifacts) {
39
+ return async (inputs) => {
40
+ const snarkjs = await loadSnarkjs();
41
+ const formattedInputs = formatInputsForSnarkjs(inputs);
42
+ const { proof } = await snarkjs.groth16.fullProve(formattedInputs, artifacts.wasmPath, artifacts.zkeyPath);
43
+ return proof;
44
+ };
45
+ }
46
+ /**
47
+ * Verify a Groth16 proof against public signals and a verification key.
48
+ *
49
+ * Useful for local verification before submitting to the relayer.
50
+ *
51
+ * @param proof The raw snarkjs proof
52
+ * @param publicSignals Array of public signal strings
53
+ * @param vkeyPath Path to the verification key JSON file, or the parsed JSON object
54
+ * @returns true if the proof is valid
55
+ */
56
+ export async function verifyProof(proof, publicSignals, vkey) {
57
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
58
+ let snarkjs;
59
+ try {
60
+ snarkjs = require("snarkjs");
61
+ }
62
+ catch {
63
+ throw new Error('snarkjs is required for proof verification. Install it: npm install snarkjs');
64
+ }
65
+ let vkeyObj;
66
+ if (typeof vkey === "string") {
67
+ // Node.js file path — read and parse
68
+ const fs = await import("fs");
69
+ vkeyObj = JSON.parse(fs.readFileSync(vkey, "utf-8"));
70
+ }
71
+ else {
72
+ vkeyObj = vkey;
73
+ }
74
+ return snarkjs.groth16.verify(vkeyObj, publicSignals, proof);
75
+ }