@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,87 @@
1
+ import { AddressLookupTableAccount, Connection, PublicKey } from "@solana/web3.js";
2
+ import type { AltSource, ShieldCachePort } from "./types.js";
3
+ /**
4
+ * Address lookup table handling for the shield path.
5
+ *
6
+ * The ALT is not an optimisation here — it is load-bearing. A `transact` carries
7
+ * 847 bytes of instruction data across 16 accounts, which is ~1500 bytes as a
8
+ * legacy transaction and therefore unlandable. Compressing the constant pool
9
+ * accounts to 1-byte indices is what brings it to ~1163 and leaves room for
10
+ * Phantom's Lighthouse guard instructions.
11
+ */
12
+ /**
13
+ * The shared, team-owned deposit table.
14
+ *
15
+ * Deliberately shared rather than per-wallet: creating a per-wallet table costs
16
+ * the signer an extra signature and unrecoverable rent, which is unacceptable to
17
+ * ask of an external wallet shielding once, and impossible to ask of a
18
+ * third-party platform's managed wallet.
19
+ */
20
+ export declare const SHARED_DEPOSIT_ALT: PublicKey;
21
+ /** Mints the shared table is provisioned for. */
22
+ export declare const SHARED_ALT_MINTS: {
23
+ symbol: string;
24
+ mint: PublicKey;
25
+ }[];
26
+ /**
27
+ * Load the shared table, and verify it actually covers this shield.
28
+ *
29
+ * The verification is the important part. Coverage is an *operational* property,
30
+ * not a code property: the table is populated by a script, and if a mint or a
31
+ * tree is missing, every one of its accounts falls back to a 32-byte static key
32
+ * and the transaction silently grows past 1232. Failing here with a list of the
33
+ * missing addresses is far better than failing at `signTransaction` with
34
+ * "transaction too large" and no indication why.
35
+ */
36
+ export declare function sharedDepositAlt(address?: PublicKey, opts?: {
37
+ cache?: ShieldCachePort;
38
+ verifyCoverage?: boolean;
39
+ }): AltSource;
40
+ /** Use a table the caller already loaded. Skips both the RPC call and the coverage check. */
41
+ export declare function explicitAlt(account: AddressLookupTableAccount): AltSource;
42
+ type NamedKey = {
43
+ label: string;
44
+ address: PublicKey;
45
+ };
46
+ /**
47
+ * Accounts that must be in the table for a shield of `mint` into `outputTreeId`
48
+ * to fit.
49
+ *
50
+ * The signer, the two nullifier markers, and the user's token account are
51
+ * deliberately excluded: markers are unique per transaction and the others are
52
+ * per-user, so none can live in a shared table. They are the static keys the
53
+ * size budget accounts for.
54
+ */
55
+ export declare function requiredAltKeys(params: {
56
+ mint: PublicKey;
57
+ outputTreeId: number;
58
+ programId?: PublicKey;
59
+ }): NamedKey[];
60
+ /**
61
+ * Everything the shared table should contain across every supported mint and
62
+ * every tree up to `maxTreeId`.
63
+ *
64
+ * Exported so this can be asserted in CI. The table currently only covers tree 0
65
+ * per mint, which means the size budget quietly loses 32 bytes of headroom the
66
+ * day tree 0 fills and `getBestTreeForDeposit` starts returning tree 1. That is
67
+ * a scheduled failure, and this function is how it gets caught before a user
68
+ * finds it.
69
+ */
70
+ export declare function expectedDepositAltKeys(params: {
71
+ mints?: PublicKey[];
72
+ maxTreeId?: number;
73
+ programId?: PublicKey;
74
+ }): Promise<NamedKey[]>;
75
+ /** Diff the on-chain table against {@link expectedDepositAltKeys}. */
76
+ export declare function auditDepositAlt(connection: Connection, params?: {
77
+ address?: PublicKey;
78
+ mints?: PublicKey[];
79
+ maxTreeId?: number;
80
+ programId?: PublicKey;
81
+ }): Promise<{
82
+ ok: boolean;
83
+ present: number;
84
+ missing: NamedKey[];
85
+ extra: string[];
86
+ }>;
87
+ export {};
@@ -0,0 +1,186 @@
1
+ import { ComputeBudgetProgram, PublicKey, SystemProgram, } from "@solana/web3.js";
2
+ import { TOKEN_PROGRAM_ID, getAssociatedTokenAddress, getAssociatedTokenAddressSync, } from "@solana/spl-token";
3
+ import { getGlobalConfigPda, getNoteTreePda, getPoolPdas, } from "../client.js";
4
+ import { PRIVACY_POOL_PROGRAM_ID } from "../program.js";
5
+ import { NATIVE_SOL_MINT } from "../config.js";
6
+ import { ShieldError } from "./errors.js";
7
+ /**
8
+ * Address lookup table handling for the shield path.
9
+ *
10
+ * The ALT is not an optimisation here — it is load-bearing. A `transact` carries
11
+ * 847 bytes of instruction data across 16 accounts, which is ~1500 bytes as a
12
+ * legacy transaction and therefore unlandable. Compressing the constant pool
13
+ * accounts to 1-byte indices is what brings it to ~1163 and leaves room for
14
+ * Phantom's Lighthouse guard instructions.
15
+ */
16
+ /**
17
+ * The shared, team-owned deposit table.
18
+ *
19
+ * Deliberately shared rather than per-wallet: creating a per-wallet table costs
20
+ * the signer an extra signature and unrecoverable rent, which is unacceptable to
21
+ * ask of an external wallet shielding once, and impossible to ask of a
22
+ * third-party platform's managed wallet.
23
+ */
24
+ export const SHARED_DEPOSIT_ALT = new PublicKey("3x2JxCgAPmv4U4EJonFBntm1q4W3xzpnB6aT1tCvxftk");
25
+ /** Mints the shared table is provisioned for. */
26
+ export const SHARED_ALT_MINTS = [
27
+ { symbol: "SOL", mint: NATIVE_SOL_MINT },
28
+ { symbol: "USDC", mint: new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v") },
29
+ { symbol: "USDT", mint: new PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB") },
30
+ { symbol: "USD1", mint: new PublicKey("USD1ttGY1N17NEEHLmELoaybftRBUSErhqYiQzvEmuB") },
31
+ { symbol: "JUP", mint: new PublicKey("JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN") },
32
+ { symbol: "ARX", mint: new PublicKey("ARXwZkNAtzPfdcoqQiduJn8EPv9fKiDfGn2KyggyDrFs") },
33
+ ];
34
+ const ALT_CACHE_TTL_MS = 10 * 60000;
35
+ /**
36
+ * Load the shared table, and verify it actually covers this shield.
37
+ *
38
+ * The verification is the important part. Coverage is an *operational* property,
39
+ * not a code property: the table is populated by a script, and if a mint or a
40
+ * tree is missing, every one of its accounts falls back to a 32-byte static key
41
+ * and the transaction silently grows past 1232. Failing here with a list of the
42
+ * missing addresses is far better than failing at `signTransaction` with
43
+ * "transaction too large" and no indication why.
44
+ */
45
+ export function sharedDepositAlt(address = SHARED_DEPOSIT_ALT, opts = {}) {
46
+ return {
47
+ async resolve({ connection, mint, outputTreeId, programId }) {
48
+ const key = `alt:${address.toBase58()}`;
49
+ let account = await opts.cache?.get(key);
50
+ if (!account) {
51
+ // "finalized" so every RPC the signer's wallet might simulate against
52
+ // has already seen the table. A table read at "processed" can be
53
+ // invisible to the wallet's own simulator.
54
+ const res = await connection.getAddressLookupTable(address, {
55
+ commitment: "finalized",
56
+ });
57
+ if (!res.value) {
58
+ throw new ShieldError("ALT_NOT_FOUND", `Deposit address lookup table ${address.toBase58()} was not found at ` +
59
+ `finalized commitment. Without it a shield cannot fit in 1232 bytes.`, { context: { address: address.toBase58() } });
60
+ }
61
+ account = res.value;
62
+ await opts.cache?.set(key, account, ALT_CACHE_TTL_MS);
63
+ }
64
+ if (opts.verifyCoverage !== false) {
65
+ const missing = missingCoverage(account, {
66
+ mint,
67
+ outputTreeId,
68
+ programId,
69
+ });
70
+ if (missing.length > 0) {
71
+ throw new ShieldError("ALT_INCOMPLETE", `The deposit lookup table does not cover this shield: ${missing.length} ` +
72
+ `required account(s) are absent, so the transaction would exceed 1232 ` +
73
+ `bytes. Extend the table before shielding this mint/tree.`, {
74
+ context: {
75
+ alt: address.toBase58(),
76
+ mint: mint.toBase58(),
77
+ outputTreeId,
78
+ missing: missing.map((m) => `${m.label} (${m.address.toBase58()})`),
79
+ },
80
+ });
81
+ }
82
+ }
83
+ return account;
84
+ },
85
+ };
86
+ }
87
+ /** Use a table the caller already loaded. Skips both the RPC call and the coverage check. */
88
+ export function explicitAlt(account) {
89
+ return { async resolve() { return account; } };
90
+ }
91
+ /**
92
+ * Accounts that must be in the table for a shield of `mint` into `outputTreeId`
93
+ * to fit.
94
+ *
95
+ * The signer, the two nullifier markers, and the user's token account are
96
+ * deliberately excluded: markers are unique per transaction and the others are
97
+ * per-user, so none can live in a shared table. They are the static keys the
98
+ * size budget accounts for.
99
+ */
100
+ export function requiredAltKeys(params) {
101
+ const programId = params.programId ?? PRIVACY_POOL_PROGRAM_ID;
102
+ const { config, vault, nullifiers } = getPoolPdas(programId, params.mint);
103
+ const keys = [
104
+ { label: "programId", address: programId },
105
+ { label: "computeBudgetProgram", address: ComputeBudgetProgram.programId },
106
+ { label: "systemProgram", address: SystemProgram.programId },
107
+ { label: "globalConfig", address: getGlobalConfigPda(programId) },
108
+ { label: "config", address: config },
109
+ { label: "vault", address: vault },
110
+ { label: "nullifiers", address: nullifiers },
111
+ { label: "inputTree(0)", address: getNoteTreePda(programId, params.mint, 0) },
112
+ ];
113
+ if (params.outputTreeId !== 0) {
114
+ keys.push({
115
+ label: `outputTree(${params.outputTreeId})`,
116
+ address: getNoteTreePda(programId, params.mint, params.outputTreeId),
117
+ });
118
+ }
119
+ if (!params.mint.equals(NATIVE_SOL_MINT)) {
120
+ keys.push({ label: "tokenProgram", address: TOKEN_PROGRAM_ID }, {
121
+ label: "vaultAta",
122
+ address: getAssociatedTokenAddressSync(params.mint, vault, true),
123
+ });
124
+ }
125
+ return keys;
126
+ }
127
+ function missingCoverage(account, params) {
128
+ const present = new Set(account.state.addresses.map((a) => a.toBase58()));
129
+ return requiredAltKeys(params).filter((k) => !present.has(k.address.toBase58()));
130
+ }
131
+ /**
132
+ * Everything the shared table should contain across every supported mint and
133
+ * every tree up to `maxTreeId`.
134
+ *
135
+ * Exported so this can be asserted in CI. The table currently only covers tree 0
136
+ * per mint, which means the size budget quietly loses 32 bytes of headroom the
137
+ * day tree 0 fills and `getBestTreeForDeposit` starts returning tree 1. That is
138
+ * a scheduled failure, and this function is how it gets caught before a user
139
+ * finds it.
140
+ */
141
+ export async function expectedDepositAltKeys(params) {
142
+ const programId = params.programId ?? PRIVACY_POOL_PROGRAM_ID;
143
+ const mints = params.mints ?? SHARED_ALT_MINTS.map((m) => m.mint);
144
+ const maxTreeId = params.maxTreeId ?? 4;
145
+ const out = [
146
+ { label: "programId", address: programId },
147
+ { label: "computeBudgetProgram", address: ComputeBudgetProgram.programId },
148
+ { label: "systemProgram", address: SystemProgram.programId },
149
+ { label: "tokenProgram", address: TOKEN_PROGRAM_ID },
150
+ { label: "globalConfig", address: getGlobalConfigPda(programId) },
151
+ ];
152
+ for (const mint of mints) {
153
+ const label = mint.equals(NATIVE_SOL_MINT) ? "SOL" : mint.toBase58().slice(0, 4);
154
+ const { config, vault, nullifiers } = getPoolPdas(programId, mint);
155
+ out.push({ label: `${label}.config`, address: config }, { label: `${label}.vault`, address: vault }, { label: `${label}.nullifiers`, address: nullifiers });
156
+ for (let t = 0; t <= maxTreeId; t++) {
157
+ out.push({
158
+ label: `${label}.tree(${t})`,
159
+ address: getNoteTreePda(programId, mint, t),
160
+ });
161
+ }
162
+ if (!mint.equals(NATIVE_SOL_MINT)) {
163
+ out.push({
164
+ label: `${label}.vaultAta`,
165
+ address: await getAssociatedTokenAddress(mint, vault, true),
166
+ });
167
+ }
168
+ }
169
+ return out;
170
+ }
171
+ /** Diff the on-chain table against {@link expectedDepositAltKeys}. */
172
+ export async function auditDepositAlt(connection, params = {}) {
173
+ const address = params.address ?? SHARED_DEPOSIT_ALT;
174
+ const res = await connection.getAddressLookupTable(address, {
175
+ commitment: "finalized",
176
+ });
177
+ if (!res.value) {
178
+ throw new ShieldError("ALT_NOT_FOUND", `Deposit ALT ${address.toBase58()} not found`, { context: { address: address.toBase58() } });
179
+ }
180
+ const present = new Set(res.value.state.addresses.map((a) => a.toBase58()));
181
+ const expected = await expectedDepositAltKeys(params);
182
+ const expectedSet = new Set(expected.map((e) => e.address.toBase58()));
183
+ const missing = expected.filter((e) => !present.has(e.address.toBase58()));
184
+ const extra = [...present].filter((p) => !expectedSet.has(p));
185
+ return { ok: missing.length === 0, present: present.size, missing, extra };
186
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Compute budget and transaction size constants for the shield path.
3
+ *
4
+ * These numbers are empirical and load-bearing. They are constants rather than
5
+ * inline literals so a future program change that invalidates them has one
6
+ * place to be fixed and one place to be read.
7
+ */
8
+ /**
9
+ * Compute unit limit reserved for a shield.
10
+ *
11
+ * Measured usage for a deposit is ~377k CU; 700k leaves roughly 2× headroom
12
+ * while staying low enough that Phantom's Lighthouse guard still fits its own
13
+ * instructions alongside ours.
14
+ *
15
+ * Do NOT raise this to 1.4M (what the stale `client.ts` `deposit()` reserves).
16
+ * An oversized CU reservation is one of the signals that makes Phantom render
17
+ * the transaction with a malicious-dApp warning.
18
+ *
19
+ * Ported from veilo-dapp/features/transactions/handleDeposit.ts:673-681.
20
+ */
21
+ export declare const SHIELD_COMPUTE_UNIT_LIMIT = 700000;
22
+ /** Typical measured usage. If real usage approaches the limit above, revisit both. */
23
+ export declare const SHIELD_COMPUTE_UNITS_MEASURED_TYPICAL = 377000;
24
+ /** Default priority fee. Set to 0 to omit the instruction entirely (saves ~40 bytes). */
25
+ export declare const SHIELD_COMPUTE_UNIT_PRICE_MICRO_LAMPORTS = 50000;
26
+ /** Solana's hard cap on a serialized transaction, signatures included. */
27
+ export declare const MAX_TRANSACTION_BYTES = 1232;
28
+ /** One ed25519 signature: 64 bytes plus the compact-array length prefix. */
29
+ export declare const SIGNATURE_BYTES = 65;
30
+ /**
31
+ * `NullifierMarker::LEN` (privacy-program .../lib.rs:415). Two markers are
32
+ * created per transact and paid for by the signer — see the note on sponsorship
33
+ * in the module docs of `shield.ts`.
34
+ */
35
+ export declare const NULLIFIER_MARKER_ACCOUNT_BYTES = 10;
36
+ /** Markers created per `transact` — one per circuit input. */
37
+ export declare const NULLIFIER_MARKERS_PER_TRANSACT = 2;
38
+ /** Default validity window for the on-chain `deadline` argument. */
39
+ export declare const DEFAULT_DEADLINE_SECONDS = 3600;
40
+ /**
41
+ * Serialized size of the `transact` instruction data, for reference:
42
+ *
43
+ * 8 discriminator
44
+ * 32 root
45
+ * 2 input_tree_id
46
+ * 2 output_tree_id
47
+ * 8 public_amount
48
+ * 32 ext_data_hash
49
+ * 32 mint_address
50
+ * 128 2 nullifiers + 2 commitments
51
+ * 8 deadline
52
+ * 112 ExtData (recipient, relayer, fee, refund, claimant)
53
+ * 256 Groth16 proof (a:64, b:128, c:64)
54
+ * 227 Option<NoteCiphers> (1 tag + 226)
55
+ * ---
56
+ * 847
57
+ *
58
+ * With 16 accounts this cannot fit in a legacy transaction (~1500 bytes), which
59
+ * is why the shield path is v0-with-ALT and not optional.
60
+ */
61
+ export declare const TRANSACT_INSTRUCTION_DATA_BYTES = 847;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Compute budget and transaction size constants for the shield path.
3
+ *
4
+ * These numbers are empirical and load-bearing. They are constants rather than
5
+ * inline literals so a future program change that invalidates them has one
6
+ * place to be fixed and one place to be read.
7
+ */
8
+ /**
9
+ * Compute unit limit reserved for a shield.
10
+ *
11
+ * Measured usage for a deposit is ~377k CU; 700k leaves roughly 2× headroom
12
+ * while staying low enough that Phantom's Lighthouse guard still fits its own
13
+ * instructions alongside ours.
14
+ *
15
+ * Do NOT raise this to 1.4M (what the stale `client.ts` `deposit()` reserves).
16
+ * An oversized CU reservation is one of the signals that makes Phantom render
17
+ * the transaction with a malicious-dApp warning.
18
+ *
19
+ * Ported from veilo-dapp/features/transactions/handleDeposit.ts:673-681.
20
+ */
21
+ export const SHIELD_COMPUTE_UNIT_LIMIT = 700000;
22
+ /** Typical measured usage. If real usage approaches the limit above, revisit both. */
23
+ export const SHIELD_COMPUTE_UNITS_MEASURED_TYPICAL = 377000;
24
+ /** Default priority fee. Set to 0 to omit the instruction entirely (saves ~40 bytes). */
25
+ export const SHIELD_COMPUTE_UNIT_PRICE_MICRO_LAMPORTS = 50000;
26
+ /** Solana's hard cap on a serialized transaction, signatures included. */
27
+ export const MAX_TRANSACTION_BYTES = 1232;
28
+ /** One ed25519 signature: 64 bytes plus the compact-array length prefix. */
29
+ export const SIGNATURE_BYTES = 65;
30
+ /**
31
+ * `NullifierMarker::LEN` (privacy-program .../lib.rs:415). Two markers are
32
+ * created per transact and paid for by the signer — see the note on sponsorship
33
+ * in the module docs of `shield.ts`.
34
+ */
35
+ export const NULLIFIER_MARKER_ACCOUNT_BYTES = 10;
36
+ /** Markers created per `transact` — one per circuit input. */
37
+ export const NULLIFIER_MARKERS_PER_TRANSACT = 2;
38
+ /** Default validity window for the on-chain `deadline` argument. */
39
+ export const DEFAULT_DEADLINE_SECONDS = 3600;
40
+ /**
41
+ * Serialized size of the `transact` instruction data, for reference:
42
+ *
43
+ * 8 discriminator
44
+ * 32 root
45
+ * 2 input_tree_id
46
+ * 2 output_tree_id
47
+ * 8 public_amount
48
+ * 32 ext_data_hash
49
+ * 32 mint_address
50
+ * 128 2 nullifiers + 2 commitments
51
+ * 8 deadline
52
+ * 112 ExtData (recipient, relayer, fee, refund, claimant)
53
+ * 256 Groth16 proof (a:64, b:128, c:64)
54
+ * 227 Option<NoteCiphers> (1 tag + 226)
55
+ * ---
56
+ * 847
57
+ *
58
+ * With 16 accounts this cannot fit in a legacy transaction (~1500 bytes), which
59
+ * is why the shield path is v0-with-ALT and not optional.
60
+ */
61
+ export const TRANSACT_INSTRUCTION_DATA_BYTES = 847;
@@ -0,0 +1,58 @@
1
+ import { TransactionInstruction } from "@solana/web3.js";
2
+ /**
3
+ * Error taxonomy for the shield path.
4
+ *
5
+ * `parseOnChainError` already turns program codes into readable sentences. What
6
+ * it does not give you is a *decision*: can this be retried, and how? That is
7
+ * what integrators actually need, because the three retry classes have wildly
8
+ * different costs:
9
+ *
10
+ * - `rebuild` — reuse the proof, new blockhash. Milliseconds.
11
+ * - `reshield` — the proof is stale, prove again. 10–30 seconds.
12
+ * - `none` — retrying cannot help; something must change first.
13
+ */
14
+ export type ShieldRetryClass = "rebuild" | "reshield" | "none";
15
+ export type ShieldErrorCode = "POOL_NOT_FOUND" | "POOL_PAUSED" | "AMOUNT_BELOW_MINIMUM" | "AMOUNT_ABOVE_MAXIMUM" | "TREE_FULL" | "INSUFFICIENT_SOL" | "INSUFFICIENT_TOKEN_BALANCE" | "TOKEN_ACCOUNT_MISSING" | "TOKEN_ACCOUNT_WRONG_MINT" | "TOKEN_ACCOUNT_WRONG_OWNER" | "TOKEN_ACCOUNT_DELEGATED" | "TOKEN_ACCOUNT_FROZEN" | "VAULT_ATA_MISSING" | "ALT_NOT_FOUND" | "ALT_INCOMPLETE" | "TX_TOO_LARGE" | "OWNER_INVARIANT_UNACKNOWLEDGED" | "UNRESOLVED_ACCOUNT" | "BLOCKHASH_EXPIRED" | "DEADLINE_EXPIRED" | "ROOT_STALE" | "NULLIFIER_COLLISION" | "COMPUTE_BUDGET_EXCEEDED" | "PROOF_REJECTED" | "UNKNOWN";
16
+ export type ShieldErrorRemedy = {
17
+ /** Human-readable description of what would fix this. */
18
+ description: string;
19
+ /** Instructions that, once executed, clear the condition. */
20
+ instructions: TransactionInstruction[];
21
+ };
22
+ export declare class ShieldError extends Error {
23
+ readonly code: ShieldErrorCode;
24
+ /** Program error code (6000–6060) when this was derived from a chain error. */
25
+ readonly programCode?: number;
26
+ /** Whether and how a retry can succeed. */
27
+ readonly retryable: ShieldRetryClass;
28
+ /** Machine-readable detail: which account, what value, what was expected. */
29
+ readonly context?: Record<string, unknown>;
30
+ /** Present when the condition is fixable by executing instructions first. */
31
+ readonly remedy?: ShieldErrorRemedy;
32
+ readonly cause?: unknown;
33
+ constructor(code: ShieldErrorCode, message: string, opts?: {
34
+ programCode?: number;
35
+ retryable?: ShieldRetryClass;
36
+ context?: Record<string, unknown>;
37
+ remedy?: ShieldErrorRemedy;
38
+ cause?: unknown;
39
+ });
40
+ }
41
+ /** Extract a privacy_pool program error code from an arbitrary thrown value. */
42
+ export declare function extractProgramCode(error: any): number | null;
43
+ /**
44
+ * Map a submission failure onto the taxonomy.
45
+ *
46
+ * Two mappings here are not obvious and are worth stating plainly:
47
+ *
48
+ * **Nullifier collision means "already landed", not "already spent."** The
49
+ * marker PDAs are `init`, not `init_if_needed`, so a second submission of the
50
+ * same shield fails at account resolution. For a deposit the nullifiers derive
51
+ * from freshly generated random keys, so a genuine collision is impossible —
52
+ * in practice this only ever means the first attempt succeeded. Telling a user
53
+ * their funds were "already spent" here would be alarming and wrong.
54
+ *
55
+ * **`UnknownRoot` is recoverable but not by `rebuild()`.** The proof commits to
56
+ * the root, so a stale root needs a fresh proof, not a fresh blockhash.
57
+ */
58
+ export declare function mapShieldError(error: unknown): ShieldError;
@@ -0,0 +1,115 @@
1
+ import { parseOnChainError } from "../client.js";
2
+ export class ShieldError extends Error {
3
+ constructor(code, message, opts = {}) {
4
+ super(message);
5
+ this.name = "ShieldError";
6
+ this.code = code;
7
+ this.programCode = opts.programCode;
8
+ this.retryable = opts.retryable ?? "none";
9
+ this.context = opts.context;
10
+ this.remedy = opts.remedy;
11
+ this.cause = opts.cause;
12
+ }
13
+ }
14
+ /** Extract a privacy_pool program error code from an arbitrary thrown value. */
15
+ export function extractProgramCode(error) {
16
+ const raw = (error?.message ?? error?.toString() ?? "").toLowerCase();
17
+ const hex = raw.match(/custom program error:\s*0x([0-9a-f]+)/);
18
+ if (hex)
19
+ return parseInt(hex[1], 16);
20
+ const num = raw.match(/error number:\s*(\d+)/);
21
+ if (num)
22
+ return parseInt(num[1], 10);
23
+ if (typeof error?.error?.errorCode?.number === "number") {
24
+ return error.error.errorCode.number;
25
+ }
26
+ return null;
27
+ }
28
+ /**
29
+ * Map a submission failure onto the taxonomy.
30
+ *
31
+ * Two mappings here are not obvious and are worth stating plainly:
32
+ *
33
+ * **Nullifier collision means "already landed", not "already spent."** The
34
+ * marker PDAs are `init`, not `init_if_needed`, so a second submission of the
35
+ * same shield fails at account resolution. For a deposit the nullifiers derive
36
+ * from freshly generated random keys, so a genuine collision is impossible —
37
+ * in practice this only ever means the first attempt succeeded. Telling a user
38
+ * their funds were "already spent" here would be alarming and wrong.
39
+ *
40
+ * **`UnknownRoot` is recoverable but not by `rebuild()`.** The proof commits to
41
+ * the root, so a stale root needs a fresh proof, not a fresh blockhash.
42
+ */
43
+ export function mapShieldError(error) {
44
+ if (error instanceof ShieldError)
45
+ return error;
46
+ const err = error;
47
+ const raw = (err?.message ?? String(err ?? "")).toLowerCase();
48
+ const programCode = extractProgramCode(err);
49
+ const readable = parseOnChainError(err);
50
+ if (programCode !== null) {
51
+ switch (programCode) {
52
+ case 6000:
53
+ return new ShieldError("POOL_PAUSED", readable, { programCode, cause: err });
54
+ case 6007:
55
+ return new ShieldError("ROOT_STALE", "The Merkle root this shield was proven against is no longer in the on-chain " +
56
+ "history. Build a new shield — the proof cannot be reused.", { programCode, retryable: "reshield", cause: err });
57
+ case 6012:
58
+ return new ShieldError("PROOF_REJECTED", readable, { programCode, cause: err });
59
+ case 6013:
60
+ return new ShieldError("TREE_FULL", readable, {
61
+ programCode,
62
+ retryable: "reshield",
63
+ cause: err,
64
+ });
65
+ case 6017:
66
+ return new ShieldError("TOKEN_ACCOUNT_WRONG_MINT", readable, {
67
+ programCode,
68
+ cause: err,
69
+ });
70
+ case 6029:
71
+ return new ShieldError("TOKEN_ACCOUNT_DELEGATED", "The source token account has an active delegate. Revoke it, then shield again.", { programCode, cause: err });
72
+ case 6033:
73
+ return new ShieldError("TOKEN_ACCOUNT_WRONG_OWNER", "The source token account is not owned by the signing wallet.", { programCode, cause: err });
74
+ case 6035:
75
+ return new ShieldError("AMOUNT_BELOW_MINIMUM", readable, { programCode, cause: err });
76
+ case 6036:
77
+ return new ShieldError("AMOUNT_ABOVE_MAXIMUM", readable, { programCode, cause: err });
78
+ case 6050:
79
+ return new ShieldError("VAULT_ATA_MISSING", readable, { programCode, cause: err });
80
+ case 6005:
81
+ case 6046:
82
+ case 6052:
83
+ return new ShieldError("NULLIFIER_COLLISION", ALREADY_SHIELDED_MESSAGE, {
84
+ programCode,
85
+ cause: err,
86
+ });
87
+ case 6060:
88
+ return new ShieldError("DEADLINE_EXPIRED", "The shield's deadline passed before it landed. Rebuild it — the proof is still valid.", { programCode, retryable: "rebuild", cause: err });
89
+ default:
90
+ return new ShieldError("UNKNOWN", readable, { programCode, cause: err });
91
+ }
92
+ }
93
+ // Non-program failures.
94
+ if (raw.includes("block height exceeded") ||
95
+ raw.includes("blockhash not found") ||
96
+ err?.name === "TransactionExpiredBlockheightExceededError") {
97
+ return new ShieldError("BLOCKHASH_EXPIRED", "The blockhash expired before the shield landed. Rebuild it — the proof is still valid.", { retryable: "rebuild", cause: err });
98
+ }
99
+ if (raw.includes("already in use")) {
100
+ return new ShieldError("NULLIFIER_COLLISION", ALREADY_SHIELDED_MESSAGE, { cause: err });
101
+ }
102
+ if (raw.includes("exceeded cus") ||
103
+ raw.includes("computational budget exceeded") ||
104
+ raw.includes("exceeded compute")) {
105
+ return new ShieldError("COMPUTE_BUDGET_EXCEEDED", `The shield exceeded its compute budget. Real usage has grown past the reserved ` +
106
+ `limit — SHIELD_COMPUTE_UNIT_LIMIT needs revisiting.`, { cause: err });
107
+ }
108
+ if (raw.includes("too large") || raw.includes("transaction too large")) {
109
+ return new ShieldError("TX_TOO_LARGE", readable, { cause: err });
110
+ }
111
+ return new ShieldError("UNKNOWN", readable, { cause: err });
112
+ }
113
+ const ALREADY_SHIELDED_MESSAGE = "This shield has already been submitted — check the transaction signature before " +
114
+ "retrying. (The nullifier markers already exist on-chain, which for a deposit means " +
115
+ "the original transaction landed; it does not mean the funds were spent.)";
@@ -0,0 +1,45 @@
1
+ import { Connection, PublicKey } from "@solana/web3.js";
2
+ import type { ShieldNote, ShieldOwner } from "./types.js";
3
+ /**
4
+ * Read the authoritative leaf index for a landed shield, and produce the
5
+ * mailbox blob for optional relayer delivery.
6
+ *
7
+ * ## Why this is a separate step
8
+ *
9
+ * Every existing deposit implementation records `tree.nextIndex` read *before*
10
+ * submission as the note's leaf index. Under concurrent deposits into the same
11
+ * tree that value is wrong, and it is wrong permanently — the stored index is
12
+ * what a later withdrawal builds its Merkle path from, so the note becomes
13
+ * unspendable through the normal path.
14
+ *
15
+ * That race is rare for a single wallet and constant for an SDK: a platform
16
+ * batching shields for many users will hit it routinely. So `shield()` reports
17
+ * only a `predictedLeafIndex`, and the real one is read here from the
18
+ * transaction's own `CommitmentEvent` after it confirms.
19
+ *
20
+ * ## What is optional
21
+ *
22
+ * Everything, strictly. The note is recoverable from chain data alone via the
23
+ * on-chain compact cipher, so a caller that skips finalization has not lost the
24
+ * funds — only the fast path to finding them. Persist nothing that depends on a
25
+ * leaf index without calling this first.
26
+ */
27
+ export declare function finalizeShield(params: {
28
+ connection: Connection;
29
+ signature: string;
30
+ note: ShieldNote;
31
+ owner: ShieldOwner;
32
+ programId?: PublicKey;
33
+ /** Defaults to "confirmed". Use "finalized" if the index will be persisted. */
34
+ commitment?: "confirmed" | "finalized";
35
+ }): Promise<{
36
+ leafIndex: number;
37
+ newRoot: Uint8Array;
38
+ treeId: number;
39
+ slot: number;
40
+ /** Encrypted note blob, ready for POST /notes/save if the caller wants mailbox delivery. */
41
+ blob: {
42
+ ephemeralPublicKey: Uint8Array;
43
+ encryptedBlob: string;
44
+ };
45
+ }>;