@veilo/sdk-core 0.1.17 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +1296 -272
  2. package/SHIELD_INTEGRATION.md +143 -0
  3. package/config.d.ts +2 -0
  4. package/config.js +4 -0
  5. package/dist/cjs/client.d.ts +407 -0
  6. package/dist/cjs/client.js +951 -0
  7. package/dist/cjs/compactNote.d.ts +107 -0
  8. package/dist/cjs/compactNote.js +167 -0
  9. package/dist/cjs/config.d.ts +82 -0
  10. package/dist/cjs/config.js +57 -0
  11. package/dist/cjs/events.d.ts +77 -0
  12. package/dist/cjs/events.js +167 -0
  13. package/dist/cjs/idl/privacy_pool.d.ts +5 -0
  14. package/dist/cjs/idl/privacy_pool.js +15218 -0
  15. package/dist/cjs/idl/privacy_pool.json +10313 -0
  16. package/dist/cjs/index.d.ts +16 -0
  17. package/dist/cjs/index.js +67 -0
  18. package/dist/cjs/merkle.d.ts +77 -0
  19. package/dist/cjs/merkle.js +156 -0
  20. package/dist/cjs/poseidon.d.ts +29 -0
  21. package/dist/cjs/poseidon.js +100 -0
  22. package/dist/cjs/program.d.ts +37 -0
  23. package/dist/cjs/program.js +61 -0
  24. package/dist/cjs/proof.d.ts +183 -0
  25. package/dist/cjs/proof.js +292 -0
  26. package/dist/cjs/prover.d.ts +54 -0
  27. package/dist/cjs/prover.js +112 -0
  28. package/dist/cjs/random.d.ts +16 -0
  29. package/dist/cjs/random.js +28 -0
  30. package/dist/cjs/relayer.d.ts +318 -0
  31. package/dist/cjs/relayer.js +257 -0
  32. package/dist/cjs/retry.d.ts +32 -0
  33. package/dist/cjs/retry.js +75 -0
  34. package/dist/cjs/shield/alt.d.ts +87 -0
  35. package/dist/cjs/shield/alt.js +194 -0
  36. package/dist/cjs/shield/computeBudget.d.ts +61 -0
  37. package/dist/cjs/shield/computeBudget.js +64 -0
  38. package/dist/cjs/shield/errors.d.ts +58 -0
  39. package/dist/cjs/shield/errors.js +121 -0
  40. package/dist/cjs/shield/finalize.d.ts +45 -0
  41. package/dist/cjs/shield/finalize.js +119 -0
  42. package/dist/cjs/shield/index.d.ts +35 -0
  43. package/dist/cjs/shield/index.js +68 -0
  44. package/dist/cjs/shield/ix.d.ts +54 -0
  45. package/dist/cjs/shield/ix.js +119 -0
  46. package/dist/cjs/shield/owner.d.ts +36 -0
  47. package/dist/cjs/shield/owner.js +126 -0
  48. package/dist/cjs/shield/ports.d.ts +43 -0
  49. package/dist/cjs/shield/ports.js +153 -0
  50. package/dist/cjs/shield/preflight.d.ts +30 -0
  51. package/dist/cjs/shield/preflight.js +154 -0
  52. package/dist/cjs/shield/shield.d.ts +68 -0
  53. package/dist/cjs/shield/shield.js +499 -0
  54. package/dist/cjs/shield/types.d.ts +202 -0
  55. package/dist/cjs/shield/types.js +2 -0
  56. package/dist/cjs/utxo.d.ts +235 -0
  57. package/dist/cjs/utxo.js +407 -0
  58. package/dist/esm/client.d.ts +407 -0
  59. package/dist/esm/client.js +891 -0
  60. package/dist/esm/compactNote.d.ts +107 -0
  61. package/dist/esm/compactNote.js +156 -0
  62. package/dist/esm/config.d.ts +82 -0
  63. package/dist/esm/config.js +51 -0
  64. package/dist/esm/events.d.ts +77 -0
  65. package/dist/esm/events.js +129 -0
  66. package/dist/esm/idl/privacy_pool.d.ts +5 -0
  67. package/dist/esm/idl/privacy_pool.js +15216 -0
  68. package/dist/esm/idl/privacy_pool.json +10313 -0
  69. package/dist/esm/index.d.ts +16 -0
  70. package/dist/esm/index.js +29 -0
  71. package/dist/esm/merkle.d.ts +77 -0
  72. package/dist/esm/merkle.js +151 -0
  73. package/dist/esm/package.json +1 -0
  74. package/dist/esm/poseidon.d.ts +29 -0
  75. package/dist/esm/poseidon.js +87 -0
  76. package/dist/esm/program.d.ts +37 -0
  77. package/dist/esm/program.js +53 -0
  78. package/dist/esm/proof.d.ts +183 -0
  79. package/dist/esm/proof.js +281 -0
  80. package/dist/esm/prover.d.ts +54 -0
  81. package/dist/esm/prover.js +75 -0
  82. package/dist/esm/random.d.ts +16 -0
  83. package/dist/esm/random.js +21 -0
  84. package/dist/esm/relayer.d.ts +318 -0
  85. package/dist/esm/relayer.js +249 -0
  86. package/dist/esm/retry.d.ts +32 -0
  87. package/dist/esm/retry.js +71 -0
  88. package/dist/esm/shield/alt.d.ts +87 -0
  89. package/dist/esm/shield/alt.js +186 -0
  90. package/dist/esm/shield/computeBudget.d.ts +61 -0
  91. package/dist/esm/shield/computeBudget.js +61 -0
  92. package/dist/esm/shield/errors.d.ts +58 -0
  93. package/dist/esm/shield/errors.js +115 -0
  94. package/dist/esm/shield/finalize.d.ts +45 -0
  95. package/dist/esm/shield/finalize.js +83 -0
  96. package/dist/esm/shield/index.d.ts +35 -0
  97. package/dist/esm/shield/index.js +32 -0
  98. package/dist/esm/shield/ix.d.ts +54 -0
  99. package/dist/esm/shield/ix.js +82 -0
  100. package/dist/esm/shield/owner.d.ts +36 -0
  101. package/dist/esm/shield/owner.js +122 -0
  102. package/dist/esm/shield/ports.d.ts +43 -0
  103. package/dist/esm/shield/ports.js +147 -0
  104. package/dist/esm/shield/preflight.d.ts +30 -0
  105. package/dist/esm/shield/preflight.js +151 -0
  106. package/dist/esm/shield/shield.d.ts +68 -0
  107. package/dist/esm/shield/shield.js +492 -0
  108. package/dist/esm/shield/types.d.ts +202 -0
  109. package/dist/esm/shield/types.js +1 -0
  110. package/dist/esm/utxo.d.ts +235 -0
  111. package/dist/esm/utxo.js +382 -0
  112. package/dist/src/client.d.ts +407 -0
  113. package/dist/src/client.js +951 -0
  114. package/dist/src/compactNote.d.ts +107 -0
  115. package/dist/src/compactNote.js +167 -0
  116. package/dist/src/config.d.ts +82 -0
  117. package/dist/src/config.js +57 -0
  118. package/dist/src/events.d.ts +77 -0
  119. package/dist/src/events.js +167 -0
  120. package/dist/src/idl/privacy_pool.d.ts +5 -0
  121. package/dist/src/idl/privacy_pool.js +15218 -0
  122. package/dist/src/index.d.ts +16 -0
  123. package/dist/src/index.js +67 -0
  124. package/dist/src/merkle.d.ts +77 -0
  125. package/dist/src/merkle.js +156 -0
  126. package/dist/src/poseidon.d.ts +29 -0
  127. package/dist/src/poseidon.js +100 -0
  128. package/dist/src/program.d.ts +37 -0
  129. package/dist/src/program.js +61 -0
  130. package/dist/src/proof.d.ts +183 -0
  131. package/dist/src/proof.js +292 -0
  132. package/dist/src/prover.d.ts +54 -0
  133. package/dist/src/prover.js +112 -0
  134. package/dist/src/random.d.ts +16 -0
  135. package/dist/src/random.js +28 -0
  136. package/dist/src/relayer.d.ts +318 -0
  137. package/dist/src/relayer.js +257 -0
  138. package/dist/src/retry.d.ts +32 -0
  139. package/dist/src/retry.js +75 -0
  140. package/dist/src/shield/alt.d.ts +87 -0
  141. package/dist/src/shield/alt.js +194 -0
  142. package/dist/src/shield/computeBudget.d.ts +61 -0
  143. package/dist/src/shield/computeBudget.js +64 -0
  144. package/dist/src/shield/errors.d.ts +58 -0
  145. package/dist/src/shield/errors.js +121 -0
  146. package/dist/src/shield/finalize.d.ts +45 -0
  147. package/dist/src/shield/finalize.js +119 -0
  148. package/dist/src/shield/index.d.ts +35 -0
  149. package/dist/src/shield/index.js +68 -0
  150. package/dist/src/shield/ix.d.ts +54 -0
  151. package/dist/src/shield/ix.js +119 -0
  152. package/dist/src/shield/owner.d.ts +36 -0
  153. package/dist/src/shield/owner.js +126 -0
  154. package/dist/src/shield/ports.d.ts +43 -0
  155. package/dist/src/shield/ports.js +153 -0
  156. package/dist/src/shield/preflight.d.ts +30 -0
  157. package/dist/src/shield/preflight.js +154 -0
  158. package/dist/src/shield/shield.d.ts +68 -0
  159. package/dist/src/shield/shield.js +499 -0
  160. package/dist/src/shield/types.d.ts +202 -0
  161. package/dist/src/shield/types.js +2 -0
  162. package/dist/src/utxo.d.ts +235 -0
  163. package/dist/src/utxo.js +407 -0
  164. package/dist/tests/compact-note.test.d.ts +1 -0
  165. package/dist/tests/compact-note.test.js +173 -0
  166. package/dist/tests/config.test.d.ts +1 -0
  167. package/dist/tests/config.test.js +102 -0
  168. package/dist/tests/edge-cases.test.d.ts +1 -0
  169. package/dist/tests/edge-cases.test.js +220 -0
  170. package/dist/tests/encryption.test.d.ts +1 -0
  171. package/dist/tests/encryption.test.js +215 -0
  172. package/dist/tests/events.test.d.ts +1 -0
  173. package/dist/tests/events.test.js +78 -0
  174. package/dist/tests/multi-tree.test.d.ts +1 -0
  175. package/dist/tests/multi-tree.test.js +405 -0
  176. package/dist/tests/pda.test.d.ts +1 -0
  177. package/dist/tests/pda.test.js +229 -0
  178. package/dist/tests/poseidon-builder-parity.test.d.ts +1 -0
  179. package/dist/tests/poseidon-builder-parity.test.js +72 -0
  180. package/dist/tests/poseidon.test.d.ts +1 -0
  181. package/dist/tests/poseidon.test.js +142 -0
  182. package/dist/tests/proof.test.d.ts +1 -0
  183. package/dist/tests/proof.test.js +296 -0
  184. package/dist/tests/relayer.test.d.ts +1 -0
  185. package/dist/tests/relayer.test.js +271 -0
  186. package/dist/tests/sdk.integration.test.d.ts +1 -0
  187. package/dist/tests/sdk.integration.test.js +330 -0
  188. package/dist/tests/shield-owner.test.d.ts +1 -0
  189. package/dist/tests/shield-owner.test.js +89 -0
  190. package/dist/tests/shield-preflight.test.d.ts +1 -0
  191. package/dist/tests/shield-preflight.test.js +87 -0
  192. package/dist/tests/shield-realproof.test.d.ts +1 -0
  193. package/dist/tests/shield-realproof.test.js +272 -0
  194. package/dist/tests/shield.test.d.ts +1 -0
  195. package/dist/tests/shield.test.js +403 -0
  196. package/dist/tests/utxo.test.d.ts +1 -0
  197. package/dist/tests/utxo.test.js +140 -0
  198. package/package.json +105 -11
  199. package/poseidon.d.ts +2 -0
  200. package/poseidon.js +4 -0
  201. package/proof.d.ts +2 -0
  202. package/proof.js +4 -0
  203. package/prover.d.ts +2 -0
  204. package/prover.js +4 -0
  205. package/shield.d.ts +2 -0
  206. package/shield.js +4 -0
  207. package/src/client.ts +0 -352
  208. package/src/config.ts +0 -13
  209. package/src/index.ts +0 -6
  210. package/src/merkle.ts +0 -178
  211. package/src/note.ts +0 -193
  212. package/src/poseidon.ts +0 -62
  213. package/src/proof.ts +0 -170
  214. package/test/script.js +0 -0
  215. package/test-tsconfig.json +0 -19
  216. package/tests/note.test.ts +0 -50
  217. package/tests/sdk.integration.test.ts +0 -210
  218. package/tsconfig.json +0 -18
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Compact note ciphers — the 80-byte payload carried inside the on-chain
3
+ * `transact` instruction (`note_ciphers: Option<NoteCiphers>`) and re-emitted in
4
+ * `CommitmentEvent`.
5
+ *
6
+ * This is what makes a note recoverable from chain data alone: a recipient who
7
+ * was never told about a deposit can still find it by scanning `view_tag` and
8
+ * decrypting the blob. Without it, note delivery depends on someone calling the
9
+ * relayer, which a third-party integrator cannot be trusted to do.
10
+ *
11
+ * ## Byte-compatibility is load-bearing
12
+ *
13
+ * Four sibling implementations already exist (relayer-server, extension ×2,
14
+ * wallet-app). This is the canonical one, and it MUST agree with them byte for
15
+ * byte in both directions:
16
+ *
17
+ * - disagree on encrypt → new notes are invisible to every existing client
18
+ * - disagree on decrypt → the entire historical note corpus becomes unreadable
19
+ *
20
+ * Three details are easy to get wrong and are individually fatal:
21
+ *
22
+ * 1. The KDF is `nacl.hash(x).slice(0, 32)` — **truncated SHA-512**, despite the
23
+ * sibling helper being named `sha256ForNotes`. See `kdfSHA512_256` in utxo.ts.
24
+ * 2. The ephemeral key published on-chain is **Ed25519**; it is converted to
25
+ * X25519 only for the Diffie-Hellman. Scanners convert it back.
26
+ * 3. `viewTag` is the first byte of the hash of the **raw shared secret**, not of
27
+ * the derived key. A wrong view tag makes every note invisible to the scan
28
+ * loop, which rejects ~255/256 candidates on this byte alone.
29
+ *
30
+ * The ECDH primitives are imported from `utxo.ts` rather than reimplemented — a
31
+ * fifth independent Edwards→Montgomery implementation is exactly how the current
32
+ * drift risk between the four siblings arose.
33
+ *
34
+ * Verified against the siblings by `tests/compact-note.test.ts` (golden vectors)
35
+ * and `scripts/verify-compact-cipher-parity.mjs` (differential).
36
+ */
37
+ /** Size of the on-chain compact blob: nonce[24] || secretbox(40-byte plaintext)[56]. */
38
+ export declare const COMPACT_BLOB_LENGTH = 80;
39
+ export type CompactNoteCipher = {
40
+ /** Ed25519 ephemeral public key, published on-chain. */
41
+ ephemeralPublicKey: Uint8Array;
42
+ /** 80 bytes: nonce[24] || ciphertext[56]. */
43
+ compactBlob: Uint8Array;
44
+ /** 1-byte scan filter. */
45
+ viewTag: number;
46
+ };
47
+ /**
48
+ * Test-only determinism hook. NOT part of the public contract — it exists so
49
+ * golden vectors can pin exact bytes against the sibling implementations, which
50
+ * is the only way to prove byte-compatibility rather than assume it.
51
+ *
52
+ * @internal
53
+ */
54
+ export type CompactNoteDeterminism = {
55
+ ephemeralSeed: Uint8Array;
56
+ nonce: Uint8Array;
57
+ };
58
+ /**
59
+ * Encrypt a note's secret material to a recipient's Solana wallet key.
60
+ *
61
+ * The recipient does not need to be the signer of the transaction, or to have
62
+ * any prior relationship with the sender — this is what makes shielding to an
63
+ * arbitrary owner possible.
64
+ *
65
+ * @param recipientWalletPubkey 32-byte Ed25519 Solana wallet public key
66
+ * @param blinding 32-byte big-endian blinding factor
67
+ * @param amount note amount in base units
68
+ */
69
+ export declare function createCompactNoteCipher(recipientWalletPubkey: Uint8Array, blinding: Uint8Array, amount: bigint,
70
+ /** @internal */ __det?: CompactNoteDeterminism): CompactNoteCipher;
71
+ /**
72
+ * Recover a note's blinding and amount from an on-chain compact cipher.
73
+ *
74
+ * Returns `null` when the blob was not encrypted to this key — the expected
75
+ * outcome for the overwhelming majority of candidates during a scan, so callers
76
+ * should filter on `viewTag` first (see {@link matchesViewTag}) and only attempt
77
+ * decryption on the ~1/256 that survive.
78
+ *
79
+ * @param walletSecretKey 32-byte Ed25519 seed or 64-byte secret key
80
+ */
81
+ export declare function decryptCompactNoteCipher(walletSecretKey: Uint8Array, ephemeralPublicKey: Uint8Array, compactBlob: Uint8Array, precomputed?: {
82
+ sharedSecret?: Uint8Array;
83
+ x25519Private?: Uint8Array;
84
+ }): {
85
+ blinding: Uint8Array;
86
+ amount: bigint;
87
+ } | null;
88
+ /**
89
+ * Cheap scan filter: does this on-chain cipher plausibly belong to us?
90
+ *
91
+ * Rejects ~255/256 candidates for the cost of one scalar multiplication and one
92
+ * hash, versus a full secretbox open. Hoist `x25519Private` across a scan loop
93
+ * with {@link toX25519Private}.
94
+ */
95
+ export declare function matchesViewTag(walletSecretKey: Uint8Array, ephemeralPublicKey: Uint8Array, viewTag: number, precomputed?: {
96
+ x25519Private?: Uint8Array;
97
+ }): {
98
+ matches: boolean;
99
+ sharedSecret: Uint8Array;
100
+ };
101
+ /**
102
+ * Convert an Ed25519 wallet secret key to its X25519 scalar once, for reuse
103
+ * across a scan loop.
104
+ */
105
+ export declare function toX25519Private(walletSecretKey: Uint8Array): Uint8Array;
106
+ /** The all-zero cipher the program treats as "no note here". */
107
+ export declare function emptyNoteCipher(): CompactNoteCipher;
@@ -0,0 +1,156 @@
1
+ import nacl from "tweetnacl";
2
+ import { ed25519PublicKeyToX25519, ed25519SeedToX25519Private, kdfSHA512_256, } from "./utxo.js";
3
+ import { randomBytes } from "./random.js";
4
+ /**
5
+ * Compact note ciphers — the 80-byte payload carried inside the on-chain
6
+ * `transact` instruction (`note_ciphers: Option<NoteCiphers>`) and re-emitted in
7
+ * `CommitmentEvent`.
8
+ *
9
+ * This is what makes a note recoverable from chain data alone: a recipient who
10
+ * was never told about a deposit can still find it by scanning `view_tag` and
11
+ * decrypting the blob. Without it, note delivery depends on someone calling the
12
+ * relayer, which a third-party integrator cannot be trusted to do.
13
+ *
14
+ * ## Byte-compatibility is load-bearing
15
+ *
16
+ * Four sibling implementations already exist (relayer-server, extension ×2,
17
+ * wallet-app). This is the canonical one, and it MUST agree with them byte for
18
+ * byte in both directions:
19
+ *
20
+ * - disagree on encrypt → new notes are invisible to every existing client
21
+ * - disagree on decrypt → the entire historical note corpus becomes unreadable
22
+ *
23
+ * Three details are easy to get wrong and are individually fatal:
24
+ *
25
+ * 1. The KDF is `nacl.hash(x).slice(0, 32)` — **truncated SHA-512**, despite the
26
+ * sibling helper being named `sha256ForNotes`. See `kdfSHA512_256` in utxo.ts.
27
+ * 2. The ephemeral key published on-chain is **Ed25519**; it is converted to
28
+ * X25519 only for the Diffie-Hellman. Scanners convert it back.
29
+ * 3. `viewTag` is the first byte of the hash of the **raw shared secret**, not of
30
+ * the derived key. A wrong view tag makes every note invisible to the scan
31
+ * loop, which rejects ~255/256 candidates on this byte alone.
32
+ *
33
+ * The ECDH primitives are imported from `utxo.ts` rather than reimplemented — a
34
+ * fifth independent Edwards→Montgomery implementation is exactly how the current
35
+ * drift risk between the four siblings arose.
36
+ *
37
+ * Verified against the siblings by `tests/compact-note.test.ts` (golden vectors)
38
+ * and `scripts/verify-compact-cipher-parity.mjs` (differential).
39
+ */
40
+ /** Size of the on-chain compact blob: nonce[24] || secretbox(40-byte plaintext)[56]. */
41
+ export const COMPACT_BLOB_LENGTH = 80;
42
+ /** Plaintext layout: blinding[32] || amount as little-endian u64[8]. */
43
+ const COMPACT_PLAINTEXT_LENGTH = 40;
44
+ const NONCE_LENGTH = 24;
45
+ /**
46
+ * Encrypt a note's secret material to a recipient's Solana wallet key.
47
+ *
48
+ * The recipient does not need to be the signer of the transaction, or to have
49
+ * any prior relationship with the sender — this is what makes shielding to an
50
+ * arbitrary owner possible.
51
+ *
52
+ * @param recipientWalletPubkey 32-byte Ed25519 Solana wallet public key
53
+ * @param blinding 32-byte big-endian blinding factor
54
+ * @param amount note amount in base units
55
+ */
56
+ export function createCompactNoteCipher(recipientWalletPubkey, blinding, amount,
57
+ /** @internal */ __det) {
58
+ if (recipientWalletPubkey.length !== 32) {
59
+ throw new Error(`recipientWalletPubkey must be 32 bytes, got ${recipientWalletPubkey.length}`);
60
+ }
61
+ if (blinding.length < 32) {
62
+ throw new Error(`blinding must be at least 32 bytes, got ${blinding.length}`);
63
+ }
64
+ if (amount < 0n || amount > 0xffffffffffffffffn) {
65
+ throw new Error(`amount ${amount} does not fit in a u64`);
66
+ }
67
+ // Ed25519 ephemeral keypair. `nacl.sign.keyPair.fromSeed(seed)` produces the
68
+ // same public key as web3.js `Keypair.generate()` for the same seed, which is
69
+ // what the sibling implementations use — but without pulling @solana/web3.js
70
+ // into the crypto path.
71
+ const ephemeralSeed = __det?.ephemeralSeed ?? randomBytes(32);
72
+ const ephemeralPublicKey = nacl.sign.keyPair.fromSeed(ephemeralSeed).publicKey;
73
+ const sharedSecret = deriveSharedSecret(ephemeralSeed, recipientWalletPubkey);
74
+ const key = kdfSHA512_256(sharedSecret);
75
+ const plaintext = new Uint8Array(COMPACT_PLAINTEXT_LENGTH);
76
+ plaintext.set(blinding.slice(0, 32), 0);
77
+ let amt = amount;
78
+ for (let i = 0; i < 8; i++) {
79
+ plaintext[32 + i] = Number(amt & 0xffn);
80
+ amt >>= 8n;
81
+ }
82
+ const nonce = __det?.nonce ?? nacl.randomBytes(NONCE_LENGTH);
83
+ const encrypted = nacl.secretbox(plaintext, nonce, key);
84
+ const compactBlob = new Uint8Array(COMPACT_BLOB_LENGTH);
85
+ compactBlob.set(nonce, 0);
86
+ compactBlob.set(encrypted, NONCE_LENGTH);
87
+ // First byte of the hash of the RAW shared secret — not of `key`.
88
+ const viewTag = nacl.hash(sharedSecret)[0];
89
+ return { ephemeralPublicKey, compactBlob, viewTag };
90
+ }
91
+ /**
92
+ * Recover a note's blinding and amount from an on-chain compact cipher.
93
+ *
94
+ * Returns `null` when the blob was not encrypted to this key — the expected
95
+ * outcome for the overwhelming majority of candidates during a scan, so callers
96
+ * should filter on `viewTag` first (see {@link matchesViewTag}) and only attempt
97
+ * decryption on the ~1/256 that survive.
98
+ *
99
+ * @param walletSecretKey 32-byte Ed25519 seed or 64-byte secret key
100
+ */
101
+ export function decryptCompactNoteCipher(walletSecretKey, ephemeralPublicKey, compactBlob, precomputed) {
102
+ if (compactBlob.length !== COMPACT_BLOB_LENGTH)
103
+ return null;
104
+ const sharedSecret = precomputed?.sharedSecret ??
105
+ (precomputed?.x25519Private
106
+ ? nacl.scalarMult(precomputed.x25519Private, ed25519PublicKeyToX25519(ephemeralPublicKey))
107
+ : deriveSharedSecret(walletSecretKey, ephemeralPublicKey));
108
+ const key = kdfSHA512_256(sharedSecret);
109
+ const nonce = compactBlob.slice(0, NONCE_LENGTH);
110
+ const encrypted = compactBlob.slice(NONCE_LENGTH);
111
+ const plaintext = nacl.secretbox.open(encrypted, nonce, key);
112
+ if (!plaintext)
113
+ return null;
114
+ const blinding = new Uint8Array(plaintext.slice(0, 32));
115
+ let amount = 0n;
116
+ for (let i = 7; i >= 0; i--) {
117
+ amount = (amount << 8n) | BigInt(plaintext[32 + i]);
118
+ }
119
+ return { blinding, amount };
120
+ }
121
+ /**
122
+ * Cheap scan filter: does this on-chain cipher plausibly belong to us?
123
+ *
124
+ * Rejects ~255/256 candidates for the cost of one scalar multiplication and one
125
+ * hash, versus a full secretbox open. Hoist `x25519Private` across a scan loop
126
+ * with {@link toX25519Private}.
127
+ */
128
+ export function matchesViewTag(walletSecretKey, ephemeralPublicKey, viewTag, precomputed) {
129
+ const sharedSecret = precomputed?.x25519Private
130
+ ? nacl.scalarMult(precomputed.x25519Private, ed25519PublicKeyToX25519(ephemeralPublicKey))
131
+ : deriveSharedSecret(walletSecretKey, ephemeralPublicKey);
132
+ return { matches: nacl.hash(sharedSecret)[0] === viewTag, sharedSecret };
133
+ }
134
+ /**
135
+ * Convert an Ed25519 wallet secret key to its X25519 scalar once, for reuse
136
+ * across a scan loop.
137
+ */
138
+ export function toX25519Private(walletSecretKey) {
139
+ return ed25519SeedToX25519Private(seedOf(walletSecretKey));
140
+ }
141
+ /** The all-zero cipher the program treats as "no note here". */
142
+ export function emptyNoteCipher() {
143
+ return {
144
+ ephemeralPublicKey: new Uint8Array(32),
145
+ compactBlob: new Uint8Array(COMPACT_BLOB_LENGTH),
146
+ viewTag: 0,
147
+ };
148
+ }
149
+ // -- internal -----------------------------------------------------------------
150
+ /** Accept either a 32-byte Ed25519 seed or a 64-byte secret key, as the siblings do. */
151
+ function seedOf(secretKey) {
152
+ return secretKey.length === 64 ? secretKey.slice(0, 32) : secretKey;
153
+ }
154
+ function deriveSharedSecret(mySecretKey, theirEd25519PublicKey) {
155
+ return nacl.scalarMult(ed25519SeedToX25519Private(seedOf(mySecretKey)), ed25519PublicKeyToX25519(theirEd25519PublicKey));
156
+ }
@@ -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,51 @@
1
+ import { LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js";
2
+ // -----------------------------------------------------------------------------
3
+ // Constants
4
+ // -----------------------------------------------------------------------------
5
+ /** Default relayer fee in basis points (50 = 0.5%). */
6
+ export const DEFAULT_FEE_BPS = 50;
7
+ /** Merkle tree depth - matches on-chain MerkleTreeAccount subtrees array size */
8
+ export const MERKLE_TREE_DEPTH = 22;
9
+ /** Root history size - matches on-chain MerkleTreeAccount root_history array size */
10
+ export const ROOT_HISTORY_SIZE = 256;
11
+ /** Native SOL mint address (Pubkey::default() = all zeros) */
12
+ export const NATIVE_SOL_MINT = PublicKey.default;
13
+ // -----------------------------------------------------------------------------
14
+ // Helpers
15
+ // -----------------------------------------------------------------------------
16
+ /** Convert SOL to lamports (e.g. `sol(1.5)` → `1_500_000_000n`). */
17
+ export function sol(n) {
18
+ return BigInt(n * LAMPORTS_PER_SOL);
19
+ }
20
+ // -----------------------------------------------------------------------------
21
+ // Fee Calculation Helpers
22
+ // -----------------------------------------------------------------------------
23
+ /**
24
+ * Compute the relayer fee for a withdrawal.
25
+ * Mirrors the formula in the relayer-server:
26
+ * fee = max(amount * feeBps / 10_000, minWithdrawalFee)
27
+ *
28
+ * @returns fee in base token units, and the amount that reaches the recipient
29
+ */
30
+ export function computeWithdrawalFee(amount, feeBps, minWithdrawalFee) {
31
+ const computed = (amount * BigInt(feeBps)) / 10000n;
32
+ const fee = computed > minWithdrawalFee ? computed : minWithdrawalFee;
33
+ return { fee, toRecipient: amount - fee };
34
+ }
35
+ /**
36
+ * Compute the relayer fee for a cross-pool swap.
37
+ * Mirrors the formula in the relayer-server:
38
+ * relayerFee = max(estimatedOutput * swapFeeBps / 10_000, minSwapFee)
39
+ * destAmount = minAmountOut - relayerFee
40
+ *
41
+ * @param estimatedOutput Jupiter quote output amount
42
+ * @param swapFeeBps From the destination pool's PrivacyConfigAccount
43
+ * @param minSwapFee From the destination pool's PrivacyConfigAccount
44
+ * @param minAmountOut User-agreed minimum swap output (after slippage)
45
+ * @returns relayerFee and the amount committed into the destination UTXO
46
+ */
47
+ export function computeSwapFee(estimatedOutput, swapFeeBps, minSwapFee, minAmountOut) {
48
+ const computed = (estimatedOutput * BigInt(swapFeeBps)) / 10000n;
49
+ const relayerFee = computed > minSwapFee ? computed : minSwapFee;
50
+ return { relayerFee, destAmount: minAmountOut - relayerFee };
51
+ }
@@ -0,0 +1,77 @@
1
+ import { PublicKey } from "@solana/web3.js";
2
+ import { Program, Idl } from "@coral-xyz/anchor";
3
+ import { MerkleTree } from "./merkle.js";
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,129 @@
1
+ import * as anchor from "@coral-xyz/anchor";
2
+ import { MerkleTree } from "./merkle.js";
3
+ // -----------------------------------------------------------------------------
4
+ // Event Scanning
5
+ // -----------------------------------------------------------------------------
6
+ /**
7
+ * Fetch and parse CommitmentEvents for a program, optionally filtered by mint.
8
+ *
9
+ * @param program - Anchor program instance
10
+ * @param mintAddress - Filter to a specific pool; omit to get all pools
11
+ * @param before - Start paging before this signature (exclusive)
12
+ * @param until - Stop paging at this signature (exclusive)
13
+ * @param limit - Max signatures to fetch per page (default 1000)
14
+ */
15
+ export async function scanCommitmentEvents(params) {
16
+ const { program, mintAddress, before, until, limit = 1000 } = params;
17
+ const out = [];
18
+ const eventParser = new anchor.EventParser(program.programId, new anchor.BorshCoder(program.idl));
19
+ const sigs = await program.provider.connection.getSignaturesForAddress(program.programId, { before, until, limit });
20
+ for (const sigInfo of sigs) {
21
+ if (sigInfo.err)
22
+ continue;
23
+ const tx = await program.provider.connection.getTransaction(sigInfo.signature, { commitment: "confirmed", maxSupportedTransactionVersion: 0 });
24
+ if (!tx)
25
+ continue;
26
+ const events = Array.from(eventParser.parseLogs(tx.meta?.logMessages ?? []));
27
+ for (const ev of events) {
28
+ if (ev.name !== "commitmentEvent")
29
+ continue;
30
+ const d = ev.data;
31
+ const evMint = d.mintAddress;
32
+ if (mintAddress && !evMint.equals(mintAddress))
33
+ continue;
34
+ out.push({
35
+ commitment: new Uint8Array(d.commitment),
36
+ leafIndex: Number(d.leafIndex),
37
+ newRoot: new Uint8Array(d.newRoot),
38
+ timestamp: Number(d.timestamp),
39
+ mintAddress: evMint,
40
+ treeId: Number(d.treeId),
41
+ txSignature: sigInfo.signature,
42
+ slot: sigInfo.slot,
43
+ });
44
+ }
45
+ }
46
+ return out;
47
+ }
48
+ /**
49
+ * Fetch and parse NullifierSpent events for a program, optionally filtered by mint.
50
+ */
51
+ export async function scanNullifierEvents(params) {
52
+ const { program, mintAddress, before, until, limit = 1000 } = params;
53
+ const out = [];
54
+ const eventParser = new anchor.EventParser(program.programId, new anchor.BorshCoder(program.idl));
55
+ const sigs = await program.provider.connection.getSignaturesForAddress(program.programId, { before, until, limit });
56
+ for (const sigInfo of sigs) {
57
+ if (sigInfo.err)
58
+ continue;
59
+ const tx = await program.provider.connection.getTransaction(sigInfo.signature, { commitment: "confirmed", maxSupportedTransactionVersion: 0 });
60
+ if (!tx)
61
+ continue;
62
+ const events = Array.from(eventParser.parseLogs(tx.meta?.logMessages ?? []));
63
+ for (const ev of events) {
64
+ if (ev.name !== "nullifierSpent")
65
+ continue;
66
+ const d = ev.data;
67
+ const evMint = d.mintAddress;
68
+ if (mintAddress && !evMint.equals(mintAddress))
69
+ continue;
70
+ out.push({
71
+ nullifier: new Uint8Array(d.nullifier),
72
+ timestamp: Number(d.timestamp),
73
+ mintAddress: evMint,
74
+ treeId: Number(d.treeId),
75
+ txSignature: sigInfo.signature,
76
+ slot: sigInfo.slot,
77
+ });
78
+ }
79
+ }
80
+ return out;
81
+ }
82
+ // -----------------------------------------------------------------------------
83
+ // Tree Reconstruction
84
+ // -----------------------------------------------------------------------------
85
+ /**
86
+ * Rebuild a local MerkleTree from on-chain CommitmentEvents.
87
+ * Use this to get a valid inclusion proof for spending any UTXO.
88
+ *
89
+ * CommitmentEvents are sorted by (treeId, leafIndex) so the local tree
90
+ * matches the on-chain state exactly.
91
+ *
92
+ * @param program - Anchor program instance
93
+ * @param mintAddress - Pool to reconstruct
94
+ * @param treeId - Which tree to reconstruct (default 0)
95
+ * @param depth - Merkle tree depth (default 22, must match on-chain)
96
+ */
97
+ export async function buildTreeFromEvents(params) {
98
+ const { program, mintAddress, treeId = 0, depth = 22 } = params;
99
+ // Fetch all commitment events for this pool (page until no more results).
100
+ // Oldest-first so we insert leaves in the correct order.
101
+ const allEvents = [];
102
+ let before;
103
+ while (true) {
104
+ const page = await scanCommitmentEvents({
105
+ program,
106
+ mintAddress,
107
+ before,
108
+ limit: 1000,
109
+ });
110
+ if (page.length === 0)
111
+ break;
112
+ allEvents.push(...page);
113
+ before = page[page.length - 1].txSignature;
114
+ if (page.length < 1000)
115
+ break;
116
+ }
117
+ // Keep only events for this treeId, sort by leafIndex ascending
118
+ const treeEvents = allEvents
119
+ .filter((e) => e.treeId === treeId)
120
+ .sort((a, b) => a.leafIndex - b.leafIndex);
121
+ const tree = new MerkleTree(depth);
122
+ for (const ev of treeEvents) {
123
+ tree.insert(ev.commitment);
124
+ }
125
+ const latestSignature = treeEvents.length > 0
126
+ ? treeEvents[treeEvents.length - 1].txSignature
127
+ : undefined;
128
+ return { tree, events: treeEvents, latestSignature };
129
+ }
@@ -0,0 +1,5 @@
1
+ import type { Idl } from "@coral-xyz/anchor";
2
+ declare const IDL_JSON: Idl & {
3
+ address: string;
4
+ };
5
+ export default IDL_JSON;