@veilo/sdk-core 0.3.3 → 0.5.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 (251) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +289 -1262
  3. package/dist/cjs/accounts/admin.d.ts +84 -0
  4. package/dist/cjs/accounts/admin.js +208 -0
  5. package/dist/cjs/accounts/errors.d.ts +6 -0
  6. package/dist/cjs/accounts/errors.js +98 -0
  7. package/dist/cjs/accounts/index.d.ts +4 -0
  8. package/dist/cjs/accounts/index.js +20 -0
  9. package/dist/cjs/accounts/pdas.d.ts +23 -0
  10. package/dist/cjs/accounts/pdas.js +44 -0
  11. package/dist/cjs/accounts/queries.d.ts +41 -0
  12. package/dist/cjs/accounts/queries.js +95 -0
  13. package/dist/cjs/client.d.ts +2 -407
  14. package/dist/cjs/client.js +17 -912
  15. package/dist/cjs/cloak/client.d.ts +28 -0
  16. package/dist/cjs/cloak/client.js +68 -0
  17. package/dist/cjs/cloak/errors.d.ts +13 -0
  18. package/dist/cjs/cloak/errors.js +25 -0
  19. package/dist/cjs/cloak/helpers.d.ts +6 -0
  20. package/dist/cjs/cloak/helpers.js +35 -0
  21. package/dist/cjs/cloak/index.d.ts +6 -0
  22. package/dist/cjs/cloak/index.js +24 -0
  23. package/dist/cjs/cloak/polling.d.ts +7 -0
  24. package/dist/cjs/cloak/polling.js +66 -0
  25. package/dist/cjs/cloak/transport.d.ts +15 -0
  26. package/dist/cjs/cloak/transport.js +119 -0
  27. package/dist/cjs/cloak/types.d.ts +188 -0
  28. package/dist/cjs/cloak/types.js +5 -0
  29. package/dist/cjs/cloak.d.ts +1 -0
  30. package/dist/cjs/cloak.js +18 -0
  31. package/dist/cjs/compactNote.d.ts +128 -0
  32. package/dist/cjs/compactNote.js +191 -0
  33. package/dist/cjs/events.d.ts +1 -1
  34. package/dist/cjs/events.js +2 -2
  35. package/dist/cjs/idl/privacy_pool.d.ts +5 -0
  36. package/dist/cjs/idl/privacy_pool.js +15218 -0
  37. package/dist/cjs/index.d.ts +17 -13
  38. package/dist/cjs/index.js +43 -30
  39. package/dist/cjs/merkle.d.ts +13 -0
  40. package/dist/cjs/merkle.js +31 -8
  41. package/dist/cjs/notes/encryption.d.ts +41 -0
  42. package/dist/cjs/notes/encryption.js +75 -0
  43. package/dist/cjs/notes/index.d.ts +5 -0
  44. package/dist/cjs/notes/index.js +21 -0
  45. package/dist/cjs/notes/mailbox.d.ts +70 -0
  46. package/dist/cjs/notes/mailbox.js +164 -0
  47. package/dist/cjs/notes/model.d.ts +91 -0
  48. package/dist/cjs/notes/model.js +109 -0
  49. package/dist/cjs/notes/nullifier.d.ts +27 -0
  50. package/dist/cjs/notes/nullifier.js +45 -0
  51. package/dist/cjs/notes/recovery.d.ts +10 -0
  52. package/dist/cjs/notes/recovery.js +31 -0
  53. package/dist/cjs/program.d.ts +11 -0
  54. package/dist/cjs/program.js +26 -3
  55. package/dist/cjs/proof.d.ts +1 -183
  56. package/dist/cjs/proof.js +16 -290
  57. package/dist/cjs/proofs/encoding.d.ts +17 -0
  58. package/dist/cjs/proofs/encoding.js +72 -0
  59. package/dist/cjs/proofs/formatting.d.ts +6 -0
  60. package/dist/cjs/proofs/formatting.js +34 -0
  61. package/dist/cjs/proofs/index.d.ts +5 -0
  62. package/dist/cjs/proofs/index.js +21 -0
  63. package/dist/cjs/proofs/swap.d.ts +87 -0
  64. package/dist/cjs/proofs/swap.js +144 -0
  65. package/dist/cjs/proofs/transaction.d.ts +28 -0
  66. package/dist/cjs/proofs/transaction.js +110 -0
  67. package/dist/cjs/proofs/types.d.ts +70 -0
  68. package/dist/cjs/proofs/types.js +2 -0
  69. package/dist/cjs/prover.d.ts +4 -1
  70. package/dist/cjs/prover.js +12 -2
  71. package/dist/cjs/random.d.ts +16 -0
  72. package/dist/cjs/random.js +28 -0
  73. package/dist/cjs/relayer/client.d.ts +61 -0
  74. package/dist/cjs/relayer/client.js +151 -0
  75. package/dist/cjs/relayer/crypto.d.ts +5 -0
  76. package/dist/cjs/relayer/crypto.js +26 -0
  77. package/dist/cjs/relayer/encoding.d.ts +2 -0
  78. package/dist/cjs/relayer/encoding.js +23 -0
  79. package/dist/cjs/relayer/errors.d.ts +7 -0
  80. package/dist/cjs/relayer/errors.js +17 -0
  81. package/dist/cjs/relayer/index.d.ts +3 -0
  82. package/dist/cjs/relayer/index.js +19 -0
  83. package/dist/cjs/relayer/transport.d.ts +17 -0
  84. package/dist/cjs/relayer/transport.js +63 -0
  85. package/dist/cjs/relayer/types.d.ts +276 -0
  86. package/dist/cjs/relayer/types.js +5 -0
  87. package/dist/cjs/relayer.d.ts +1 -295
  88. package/dist/cjs/relayer.js +15 -243
  89. package/dist/cjs/shield/alt.d.ts +87 -0
  90. package/dist/cjs/shield/alt.js +194 -0
  91. package/dist/cjs/shield/computeBudget.d.ts +61 -0
  92. package/dist/cjs/shield/computeBudget.js +64 -0
  93. package/dist/cjs/shield/errors.d.ts +58 -0
  94. package/dist/cjs/shield/errors.js +121 -0
  95. package/dist/cjs/shield/finalize.d.ts +45 -0
  96. package/dist/cjs/shield/finalize.js +119 -0
  97. package/dist/cjs/shield/index.d.ts +35 -0
  98. package/dist/cjs/shield/index.js +68 -0
  99. package/dist/cjs/shield/ix.d.ts +54 -0
  100. package/dist/cjs/shield/ix.js +119 -0
  101. package/dist/cjs/shield/owner.d.ts +36 -0
  102. package/dist/cjs/shield/owner.js +127 -0
  103. package/dist/cjs/shield/ports.d.ts +43 -0
  104. package/dist/cjs/shield/ports.js +153 -0
  105. package/dist/cjs/shield/preflight.d.ts +30 -0
  106. package/dist/cjs/shield/preflight.js +154 -0
  107. package/dist/cjs/shield/shield.d.ts +68 -0
  108. package/dist/cjs/shield/shield.js +500 -0
  109. package/dist/cjs/shield/types.d.ts +202 -0
  110. package/dist/cjs/shield/types.js +2 -0
  111. package/dist/cjs/transactions/deposit.d.ts +94 -0
  112. package/dist/cjs/transactions/deposit.js +234 -0
  113. package/dist/cjs/transactions/index.d.ts +7 -0
  114. package/dist/cjs/transactions/index.js +26 -0
  115. package/dist/cjs/transactions/swap.d.ts +71 -0
  116. package/dist/cjs/transactions/swap.js +184 -0
  117. package/dist/cjs/transactions/transact.d.ts +34 -0
  118. package/dist/cjs/transactions/transact.js +146 -0
  119. package/dist/cjs/transactions/transfer.d.ts +51 -0
  120. package/dist/cjs/transactions/transfer.js +106 -0
  121. package/dist/cjs/transactions/withdraw.d.ts +52 -0
  122. package/dist/cjs/transactions/withdraw.js +104 -0
  123. package/dist/cjs/utxo.d.ts +1 -215
  124. package/dist/cjs/utxo.js +15 -391
  125. package/dist/esm/accounts/admin.d.ts +84 -0
  126. package/dist/esm/accounts/admin.js +165 -0
  127. package/dist/esm/accounts/errors.d.ts +6 -0
  128. package/dist/esm/accounts/errors.js +95 -0
  129. package/dist/esm/accounts/index.d.ts +4 -0
  130. package/dist/esm/accounts/index.js +4 -0
  131. package/dist/esm/accounts/pdas.d.ts +23 -0
  132. package/dist/esm/accounts/pdas.js +38 -0
  133. package/dist/esm/accounts/queries.d.ts +41 -0
  134. package/dist/esm/accounts/queries.js +88 -0
  135. package/dist/esm/client.d.ts +2 -0
  136. package/dist/esm/client.js +3 -887
  137. package/dist/esm/cloak/client.d.ts +28 -0
  138. package/dist/esm/cloak/client.js +64 -0
  139. package/dist/esm/cloak/errors.d.ts +13 -0
  140. package/dist/esm/cloak/errors.js +21 -0
  141. package/dist/esm/cloak/helpers.d.ts +6 -0
  142. package/dist/esm/cloak/helpers.js +31 -0
  143. package/dist/esm/cloak/index.d.ts +6 -0
  144. package/dist/esm/cloak/index.js +6 -0
  145. package/dist/esm/cloak/polling.d.ts +7 -0
  146. package/dist/esm/cloak/polling.js +63 -0
  147. package/dist/esm/cloak/transport.d.ts +15 -0
  148. package/dist/esm/cloak/transport.js +115 -0
  149. package/dist/esm/cloak/types.d.ts +188 -0
  150. package/dist/esm/cloak/types.js +4 -0
  151. package/dist/esm/cloak.d.ts +1 -0
  152. package/dist/esm/cloak.js +2 -0
  153. package/dist/esm/compactNote.d.ts +128 -0
  154. package/dist/esm/compactNote.js +179 -0
  155. package/dist/esm/config.d.ts +82 -0
  156. package/dist/esm/events.d.ts +77 -0
  157. package/dist/esm/events.js +1 -1
  158. package/dist/esm/idl/privacy_pool.d.ts +5 -0
  159. package/dist/esm/idl/privacy_pool.js +15216 -0
  160. package/dist/esm/index.d.ts +17 -0
  161. package/dist/esm/index.js +20 -11
  162. package/dist/esm/merkle.d.ts +77 -0
  163. package/dist/esm/merkle.js +23 -1
  164. package/dist/esm/notes/encryption.d.ts +41 -0
  165. package/dist/esm/notes/encryption.js +67 -0
  166. package/dist/esm/notes/index.d.ts +5 -0
  167. package/dist/esm/notes/index.js +5 -0
  168. package/dist/esm/notes/mailbox.d.ts +70 -0
  169. package/dist/esm/notes/mailbox.js +154 -0
  170. package/dist/esm/notes/model.d.ts +91 -0
  171. package/dist/esm/notes/model.js +99 -0
  172. package/dist/esm/notes/nullifier.d.ts +27 -0
  173. package/dist/esm/notes/nullifier.js +40 -0
  174. package/dist/esm/notes/recovery.d.ts +10 -0
  175. package/dist/esm/notes/recovery.js +28 -0
  176. package/dist/esm/package.json +1 -0
  177. package/dist/esm/poseidon.d.ts +29 -0
  178. package/dist/esm/program.d.ts +37 -0
  179. package/dist/esm/program.js +23 -1
  180. package/dist/esm/proof.d.ts +1 -0
  181. package/dist/esm/proof.js +2 -281
  182. package/dist/esm/proofs/encoding.d.ts +17 -0
  183. package/dist/esm/proofs/encoding.js +68 -0
  184. package/dist/esm/proofs/formatting.d.ts +6 -0
  185. package/dist/esm/proofs/formatting.js +31 -0
  186. package/dist/esm/proofs/index.d.ts +5 -0
  187. package/dist/esm/proofs/index.js +5 -0
  188. package/dist/esm/proofs/swap.d.ts +87 -0
  189. package/dist/esm/proofs/swap.js +138 -0
  190. package/dist/esm/proofs/transaction.d.ts +28 -0
  191. package/dist/esm/proofs/transaction.js +105 -0
  192. package/dist/esm/proofs/types.d.ts +70 -0
  193. package/dist/esm/proofs/types.js +1 -0
  194. package/dist/esm/prover.d.ts +57 -0
  195. package/dist/esm/prover.js +10 -1
  196. package/dist/esm/random.d.ts +16 -0
  197. package/dist/esm/random.js +21 -0
  198. package/dist/esm/relayer/client.d.ts +61 -0
  199. package/dist/esm/relayer/client.js +144 -0
  200. package/dist/esm/relayer/crypto.d.ts +5 -0
  201. package/dist/esm/relayer/crypto.js +20 -0
  202. package/dist/esm/relayer/encoding.d.ts +2 -0
  203. package/dist/esm/relayer/encoding.js +19 -0
  204. package/dist/esm/relayer/errors.d.ts +7 -0
  205. package/dist/esm/relayer/errors.js +13 -0
  206. package/dist/esm/relayer/index.d.ts +3 -0
  207. package/dist/esm/relayer/index.js +3 -0
  208. package/dist/esm/relayer/transport.d.ts +17 -0
  209. package/dist/esm/relayer/transport.js +59 -0
  210. package/dist/esm/relayer/types.d.ts +276 -0
  211. package/dist/esm/relayer/types.js +4 -0
  212. package/dist/esm/relayer.d.ts +1 -0
  213. package/dist/esm/relayer.js +2 -238
  214. package/dist/esm/retry.d.ts +32 -0
  215. package/dist/esm/shield/alt.d.ts +87 -0
  216. package/dist/esm/shield/alt.js +186 -0
  217. package/dist/esm/shield/computeBudget.d.ts +61 -0
  218. package/dist/esm/shield/computeBudget.js +61 -0
  219. package/dist/esm/shield/errors.d.ts +58 -0
  220. package/dist/esm/shield/errors.js +115 -0
  221. package/dist/esm/shield/finalize.d.ts +45 -0
  222. package/dist/esm/shield/finalize.js +83 -0
  223. package/dist/esm/shield/index.d.ts +35 -0
  224. package/dist/esm/shield/index.js +32 -0
  225. package/dist/esm/shield/ix.d.ts +54 -0
  226. package/dist/esm/shield/ix.js +82 -0
  227. package/dist/esm/shield/owner.d.ts +36 -0
  228. package/dist/esm/shield/owner.js +123 -0
  229. package/dist/esm/shield/ports.d.ts +43 -0
  230. package/dist/esm/shield/ports.js +147 -0
  231. package/dist/esm/shield/preflight.d.ts +30 -0
  232. package/dist/esm/shield/preflight.js +151 -0
  233. package/dist/esm/shield/shield.d.ts +68 -0
  234. package/dist/esm/shield/shield.js +493 -0
  235. package/dist/esm/shield/types.d.ts +202 -0
  236. package/dist/esm/shield/types.js +1 -0
  237. package/dist/esm/transactions/deposit.d.ts +94 -0
  238. package/dist/esm/transactions/deposit.js +198 -0
  239. package/dist/esm/transactions/index.d.ts +7 -0
  240. package/dist/esm/transactions/index.js +7 -0
  241. package/dist/esm/transactions/swap.d.ts +71 -0
  242. package/dist/esm/transactions/swap.js +144 -0
  243. package/dist/esm/transactions/transact.d.ts +34 -0
  244. package/dist/esm/transactions/transact.js +110 -0
  245. package/dist/esm/transactions/transfer.d.ts +51 -0
  246. package/dist/esm/transactions/transfer.js +103 -0
  247. package/dist/esm/transactions/withdraw.d.ts +52 -0
  248. package/dist/esm/transactions/withdraw.js +101 -0
  249. package/dist/esm/utxo.d.ts +1 -0
  250. package/dist/esm/utxo.js +2 -372
  251. package/package.json +111 -15
@@ -0,0 +1,500 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BN254_FR_MODULUS = exports.bytesToBigIntBE = void 0;
4
+ exports.shield = shield;
5
+ exports.rebuild = rebuild;
6
+ exports.serializeProofCache = serializeProofCache;
7
+ exports.deserializeProofCache = deserializeProofCache;
8
+ const web3_js_1 = require("@solana/web3.js");
9
+ const spl_token_1 = require("@solana/spl-token");
10
+ const program_js_1 = require("../program.js");
11
+ const pdas_js_1 = require("../accounts/pdas.js");
12
+ const config_js_1 = require("../config.js");
13
+ const poseidon_js_1 = require("../poseidon.js");
14
+ Object.defineProperty(exports, "bytesToBigIntBE", { enumerable: true, get: function () { return poseidon_js_1.bytesToBigIntBE; } });
15
+ Object.defineProperty(exports, "BN254_FR_MODULUS", { enumerable: true, get: function () { return poseidon_js_1.BN254_FR_MODULUS; } });
16
+ const merkle_js_1 = require("../merkle.js");
17
+ const model_js_1 = require("../notes/model.js");
18
+ const transaction_js_1 = require("../proofs/transaction.js");
19
+ const encoding_js_1 = require("../proofs/encoding.js");
20
+ const compactNote_js_1 = require("../compactNote.js");
21
+ const ix_js_1 = require("./ix.js");
22
+ const alt_js_1 = require("./alt.js");
23
+ const ports_js_1 = require("./ports.js");
24
+ const preflight_js_1 = require("./preflight.js");
25
+ const errors_js_1 = require("./errors.js");
26
+ const computeBudget_js_1 = require("./computeBudget.js");
27
+ /**
28
+ * Build an unsigned transaction that shields public funds into the privacy pool.
29
+ *
30
+ * ## The contract
31
+ *
32
+ * This function builds. It does not sign, submit, confirm, or retry — those
33
+ * belong to whoever holds the key, exactly as with Jupiter's `/swap`. The
34
+ * returned `transaction` is unsigned; the caller signs it with whatever wallet
35
+ * they have and broadcasts it themselves.
36
+ *
37
+ * ## Why this can be handed to a third party
38
+ *
39
+ * Three properties make it safe to build a shield on behalf of a signer you do
40
+ * not control, and to shield to an owner who is not the signer:
41
+ *
42
+ * 1. **Deposits are permissionless.** The program gates its relayer allowlist
43
+ * to `public_amount <= 0`, so any wallet can sign a deposit.
44
+ * 2. **No secrets are involved in building.** The proof for a deposit has no
45
+ * real inputs, and the output commitment binds only the recipient's *public*
46
+ * keys.
47
+ * 3. **The note rides on-chain.** `note_ciphers` travels inside the instruction,
48
+ * so the recipient can find the note by scanning even if the platform that
49
+ * submitted it never says a word.
50
+ *
51
+ * ## What the signer unavoidably pays
52
+ *
53
+ * The signer is the fee payer, the funding source, and the payer of two
54
+ * `NullifierMarker` rents (~0.00192 SOL, permanently burned — the program
55
+ * hardcodes `payer = relayer` on both). A wallet with zero SOL cannot shield
56
+ * through this path no matter who submits the transaction. Fee sponsorship is
57
+ * not achievable here: a second signature costs ~96 bytes against a budget with
58
+ * ~69 to spare, and would not cover the rent anyway.
59
+ */
60
+ async function shield(params) {
61
+ const { connection, amount, owner, signer, prover, mint = config_js_1.NATIVE_SOL_MINT, programId = program_js_1.PRIVACY_POOL_PROGRAM_ID, computeUnitLimit = computeBudget_js_1.SHIELD_COMPUTE_UNIT_LIMIT, computeUnitPriceMicroLamports = computeBudget_js_1.SHIELD_COMPUTE_UNIT_PRICE_MICRO_LAMPORTS, deadlineSeconds = computeBudget_js_1.DEFAULT_DEADLINE_SECONDS, } = params;
62
+ if (amount <= 0n) {
63
+ throw new errors_js_1.ShieldError("UNKNOWN", `shield amount must be positive, got ${amount}`);
64
+ }
65
+ // The owner invariant cannot be verified by anything on-chain or in the type
66
+ // system: if `veiloPublicKey` and `noteViewingKey` belong to different people
67
+ // the note is spendable-but-invisible and the funds are gone from the owner's
68
+ // view with no error anywhere. `resolveShieldOwner()` sets this flag because
69
+ // it fetches both halves from one response and can therefore guarantee they
70
+ // match. Anyone hand-building an owner is asserting they did the same.
71
+ if (!owner.acknowledgeOwnerInvariant) {
72
+ throw new errors_js_1.ShieldError("OWNER_INVARIANT_UNACKNOWLEDGED", "ShieldOwner was constructed by hand. `veiloPublicKey` (spend authority) and " +
73
+ "`noteViewingKey` (detection authority) MUST belong to the same account — if " +
74
+ "they do not, the note is spendable but permanently invisible to its owner. " +
75
+ "Use resolveShieldOwner() to obtain both from a single source, or set " +
76
+ "`acknowledgeOwnerInvariant: true` if you have verified them yourself.");
77
+ }
78
+ const cache = params.cache ?? (0, ports_js_1.memoryCache)();
79
+ const treeSource = params.treeSource ?? (0, ports_js_1.onChainTreeSource)(connection, programId);
80
+ const altSource = params.alt ?? (0, alt_js_1.sharedDepositAlt)(undefined, { cache });
81
+ const isToken = !mint.equals(config_js_1.NATIVE_SOL_MINT);
82
+ const userTokenAccount = isToken
83
+ ? (signer.tokenAccount ?? (await (0, spl_token_1.getAssociatedTokenAddress)(mint, signer.publicKey)))
84
+ : signer.publicKey;
85
+ // --- 1. Pre-flight ---------------------------------------------------------
86
+ // Before the prover, which costs 10-30 seconds. Every check here is one RPC
87
+ // call, and each one pre-empts an on-chain failure whose error message would
88
+ // tell the user nothing actionable.
89
+ if (params.preflight !== false) {
90
+ await (0, preflight_js_1.preflightShield)({
91
+ connection,
92
+ amount,
93
+ mint,
94
+ signer: { publicKey: signer.publicKey, tokenAccount: userTokenAccount },
95
+ programId,
96
+ options: typeof params.preflight === "object" ? params.preflight : {},
97
+ cache,
98
+ computeUnitLimit,
99
+ computeUnitPriceMicroLamports,
100
+ });
101
+ }
102
+ // --- 2. Target tree and root ----------------------------------------------
103
+ const target = await treeSource.getDepositTarget(mint);
104
+ const treeCapacity = 2 ** config_js_1.MERKLE_TREE_DEPTH;
105
+ if (target.outputNextIndex >= treeCapacity) {
106
+ throw new errors_js_1.ShieldError("TREE_FULL", `Merkle tree ${target.outputTreeId} is full (${target.outputNextIndex}/${treeCapacity} leaves).`, {
107
+ retryable: "reshield",
108
+ context: {
109
+ treeId: target.outputTreeId,
110
+ nextIndex: target.outputNextIndex,
111
+ capacity: treeCapacity,
112
+ },
113
+ });
114
+ }
115
+ // --- 3. Outputs ------------------------------------------------------------
116
+ // Output 0 carries the value and is owned by the recipient. Output 1 is a
117
+ // zero-value dummy the 2-in-2-out circuit requires.
118
+ const outputNote = (0, model_js_1.createUTXO)({
119
+ amount,
120
+ pubkey: owner.veiloPublicKey,
121
+ mintAddress: mint,
122
+ });
123
+ const dummyOutput = (0, model_js_1.createUTXO)({
124
+ amount: 0n,
125
+ pubkey: (0, model_js_1.generateKeypair)().publicKey,
126
+ mintAddress: mint,
127
+ });
128
+ // --- 4. Dummy inputs -------------------------------------------------------
129
+ // Two INDEPENDENT keypairs. Reusing one (as the stale client.ts `deposit()`
130
+ // does) only avoids the program's DuplicateNullifiers check by accident of
131
+ // blinding randomness; two keys make it structural.
132
+ const zeroChain = (0, merkle_js_1.poseidonZeroChain)(22).slice(0, 22);
133
+ const dummyInputs = [
134
+ toDummyInput((0, model_js_1.createOwnedZeroUTXO)((0, model_js_1.generateKeypair)().privateKey, mint), zeroChain),
135
+ toDummyInput((0, model_js_1.createOwnedZeroUTXO)((0, model_js_1.generateKeypair)().privateKey, mint), zeroChain),
136
+ ];
137
+ // --- 5. ExtData ------------------------------------------------------------
138
+ // For a deposit these slots carry no payment semantics — no fee is taken and
139
+ // nothing is withdrawn — but they are bound into the proof via ext_data_hash,
140
+ // so they must match exactly what goes on-chain.
141
+ const extData = {
142
+ recipient: signer.publicKey,
143
+ relayer: signer.publicKey,
144
+ fee: 0n,
145
+ refund: 0n,
146
+ claimant: web3_js_1.SystemProgram.programId,
147
+ };
148
+ const extDataHash = (0, transaction_js_1.computeExtDataHash)(extData);
149
+ // --- 6. Prove --------------------------------------------------------------
150
+ const circuitInputs = (0, transaction_js_1.prepareTransactionInputs)({
151
+ inputUTXOs: dummyInputs,
152
+ outputUTXOs: [outputNote, dummyOutput],
153
+ root: target.inputRoot,
154
+ publicAmount: amount,
155
+ extData,
156
+ mintAddress: mint,
157
+ });
158
+ let proof;
159
+ try {
160
+ proof = (0, encoding_js_1.encodeSnarkjsProofToTransactionProof)(await prover(circuitInputs));
161
+ }
162
+ catch (e) {
163
+ throw (0, errors_js_1.mapShieldError)(e);
164
+ }
165
+ // --- 7. Encrypt the note to its owner --------------------------------------
166
+ // Encrypted to `noteViewingKey`, which may be a completely different party
167
+ // from the signer. This is what makes shield-to-someone-else work.
168
+ const compact = (0, compactNote_js_1.createCompactNoteCipher)(owner.noteViewingKey.toBytes(), (0, poseidon_js_1.bigIntToBytesBE)(outputNote.blinding), amount);
169
+ const empty = (0, compactNote_js_1.emptyNoteCipher)();
170
+ // --- 8. Resolve accounts ---------------------------------------------------
171
+ const accounts = resolveTransactAccounts({
172
+ programId,
173
+ mint,
174
+ signer: signer.publicKey,
175
+ userTokenAccount,
176
+ inputTreeId: target.inputTreeId,
177
+ outputTreeId: target.outputTreeId,
178
+ inputNullifiers: circuitInputs.inputNullifiers,
179
+ vaultTokenAccount: isToken
180
+ ? await (0, spl_token_1.getAssociatedTokenAddress)(mint, (0, pdas_js_1.getPoolPdas)(programId, mint).vault, true)
181
+ : (0, pdas_js_1.getPoolPdas)(programId, mint).vault,
182
+ isToken,
183
+ });
184
+ // --- 9. Cache everything needed to rebuild ---------------------------------
185
+ const alt = await altSource.resolve({
186
+ connection,
187
+ mint,
188
+ outputTreeId: target.outputTreeId,
189
+ programId,
190
+ });
191
+ const proofCache = {
192
+ version: 1,
193
+ programId: programId.toBase58(),
194
+ mint: mint.toBase58(),
195
+ signer: signer.publicKey.toBase58(),
196
+ altAddress: alt.key.toBase58(),
197
+ inputTreeId: target.inputTreeId,
198
+ outputTreeId: target.outputTreeId,
199
+ root: hex(target.inputRoot),
200
+ publicAmount: amount.toString(),
201
+ extData: {
202
+ recipient: extData.recipient.toBase58(),
203
+ relayer: extData.relayer.toBase58(),
204
+ fee: extData.fee.toString(),
205
+ refund: extData.refund.toString(),
206
+ claimant: extData.claimant.toBase58(),
207
+ },
208
+ extDataHash: hex(extDataHash),
209
+ inputNullifiers: [
210
+ hex(circuitInputs.inputNullifiers[0]),
211
+ hex(circuitInputs.inputNullifiers[1]),
212
+ ],
213
+ outputCommitments: [hex(outputNote.commitment), hex(dummyOutput.commitment)],
214
+ proof,
215
+ noteCiphers: {
216
+ note0EphemeralKey: hex(compact.ephemeralPublicKey),
217
+ note0Encrypted: hex(compact.compactBlob),
218
+ note0ViewTag: compact.viewTag,
219
+ note1EphemeralKey: hex(empty.ephemeralPublicKey),
220
+ note1Encrypted: hex(empty.compactBlob),
221
+ note1ViewTag: empty.viewTag,
222
+ },
223
+ accounts: Object.fromEntries(Object.entries(accounts).map(([k, v]) => [k, v.toBase58()])),
224
+ computeUnitLimit,
225
+ };
226
+ const note = {
227
+ commitment: outputNote.commitment,
228
+ blinding: outputNote.blinding,
229
+ amount,
230
+ ownerVeiloPublicKey: owner.veiloPublicKey,
231
+ mint,
232
+ treeId: target.outputTreeId,
233
+ compact,
234
+ };
235
+ // --- 10. Assemble ----------------------------------------------------------
236
+ const blockhash = params.blockhash ?? (await connection.getLatestBlockhash("confirmed"));
237
+ const deadline = BigInt(Math.floor(Date.now() / 1000) + deadlineSeconds);
238
+ const built = buildFromCache({
239
+ cache: proofCache,
240
+ alt,
241
+ blockhash,
242
+ deadline,
243
+ computeUnitPriceMicroLamports,
244
+ });
245
+ const estimatedRentLamports = await rentForNullifierMarkers(connection, cache);
246
+ return {
247
+ transaction: built.transaction,
248
+ blockhash: blockhash.blockhash,
249
+ lastValidBlockHeight: blockhash.lastValidBlockHeight,
250
+ deadline,
251
+ note,
252
+ predictedLeafIndex: target.outputNextIndex,
253
+ quote: {
254
+ serializedSize: built.serializedSize,
255
+ computeUnitLimit,
256
+ computeUnitPriceMicroLamports,
257
+ estimatedFeeLamports: 5000n +
258
+ (BigInt(computeUnitLimit) * BigInt(computeUnitPriceMicroLamports)) / 1000000n,
259
+ estimatedRentLamports,
260
+ },
261
+ proofCache,
262
+ };
263
+ }
264
+ /**
265
+ * Re-assemble a shield with a fresh blockhash and deadline, reusing the proof.
266
+ *
267
+ * The Groth16 proof commits to the root, the public amount, `ext_data_hash`, the
268
+ * mint, the nullifiers and the commitments — none of which is time-dependent.
269
+ * `deadline` is a positional instruction argument, outside `ext_data_hash` and
270
+ * therefore outside the proof, so it can be refreshed too. That last part
271
+ * matters: a shield built at T and signed at T+59min needs a new deadline, not
272
+ * just a new blockhash.
273
+ *
274
+ * Costs one `getLatestBlockhash` and a message compile — no proving, no
275
+ * Poseidon, no account resolution.
276
+ *
277
+ * Does NOT recover from `ROOT_STALE`: a stale root invalidates the proof, so
278
+ * that case needs a fresh `shield()` call.
279
+ */
280
+ async function rebuild(result, opts = {}) {
281
+ const cache = result.proofCache;
282
+ const blockhash = opts.blockhash ??
283
+ (opts.connection
284
+ ? await opts.connection.getLatestBlockhash("confirmed")
285
+ : (() => {
286
+ throw new errors_js_1.ShieldError("UNKNOWN", "rebuild() needs either a `connection` or an explicit `blockhash`");
287
+ })());
288
+ const alt = opts.alt ??
289
+ (opts.connection
290
+ ? await (0, alt_js_1.sharedDepositAlt)(new web3_js_1.PublicKey(cache.altAddress), {
291
+ verifyCoverage: false,
292
+ }).resolve({
293
+ connection: opts.connection,
294
+ mint: new web3_js_1.PublicKey(cache.mint),
295
+ outputTreeId: cache.outputTreeId,
296
+ programId: new web3_js_1.PublicKey(cache.programId),
297
+ })
298
+ : (() => {
299
+ throw new errors_js_1.ShieldError("UNKNOWN", "rebuild() needs either a `connection` or an explicit `alt`");
300
+ })());
301
+ const deadline = BigInt(Math.floor(Date.now() / 1000) + (opts.deadlineSeconds ?? computeBudget_js_1.DEFAULT_DEADLINE_SECONDS));
302
+ const priceMicroLamports = opts.computeUnitPriceMicroLamports ?? result.quote.computeUnitPriceMicroLamports;
303
+ const built = buildFromCache({
304
+ cache,
305
+ alt,
306
+ blockhash,
307
+ deadline,
308
+ computeUnitPriceMicroLamports: priceMicroLamports,
309
+ });
310
+ return {
311
+ ...result,
312
+ transaction: built.transaction,
313
+ blockhash: blockhash.blockhash,
314
+ lastValidBlockHeight: blockhash.lastValidBlockHeight,
315
+ deadline,
316
+ quote: {
317
+ ...result.quote,
318
+ serializedSize: built.serializedSize,
319
+ computeUnitPriceMicroLamports: priceMicroLamports,
320
+ },
321
+ };
322
+ }
323
+ /**
324
+ * The single place a shield transaction is assembled and size-checked.
325
+ *
326
+ * Both `shield()` and `rebuild()` route through here so there is exactly one
327
+ * message layout and exactly one size assertion — the failure mode this guards
328
+ * against (a transaction that is 40 bytes too large) is otherwise diagnosed as
329
+ * an opaque wallet error with no indication of which account caused it.
330
+ */
331
+ function buildFromCache(params) {
332
+ const { cache, alt, blockhash, deadline, computeUnitPriceMicroLamports } = params;
333
+ const programId = new web3_js_1.PublicKey(cache.programId);
334
+ const signer = new web3_js_1.PublicKey(cache.signer);
335
+ const accounts = Object.fromEntries(Object.entries(cache.accounts).map(([k, v]) => [k, new web3_js_1.PublicKey(v)]));
336
+ const transactIx = (0, ix_js_1.buildTransactInstruction)(accounts, {
337
+ root: unhex(cache.root),
338
+ inputTreeId: cache.inputTreeId,
339
+ outputTreeId: cache.outputTreeId,
340
+ publicAmount: BigInt(cache.publicAmount),
341
+ extDataHash: unhex(cache.extDataHash),
342
+ mintAddress: new web3_js_1.PublicKey(cache.mint),
343
+ inputNullifiers: [unhex(cache.inputNullifiers[0]), unhex(cache.inputNullifiers[1])],
344
+ outputCommitments: [
345
+ unhex(cache.outputCommitments[0]),
346
+ unhex(cache.outputCommitments[1]),
347
+ ],
348
+ deadline,
349
+ extData: {
350
+ recipient: new web3_js_1.PublicKey(cache.extData.recipient),
351
+ relayer: new web3_js_1.PublicKey(cache.extData.relayer),
352
+ fee: BigInt(cache.extData.fee),
353
+ refund: BigInt(cache.extData.refund),
354
+ claimant: new web3_js_1.PublicKey(cache.extData.claimant),
355
+ },
356
+ proof: cache.proof,
357
+ noteCiphers: {
358
+ note0EphemeralKey: unhex(cache.noteCiphers.note0EphemeralKey),
359
+ note0Encrypted: unhex(cache.noteCiphers.note0Encrypted),
360
+ note0ViewTag: cache.noteCiphers.note0ViewTag,
361
+ note1EphemeralKey: unhex(cache.noteCiphers.note1EphemeralKey),
362
+ note1Encrypted: unhex(cache.noteCiphers.note1Encrypted),
363
+ note1ViewTag: cache.noteCiphers.note1ViewTag,
364
+ },
365
+ }, programId);
366
+ const instructions = [
367
+ web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: cache.computeUnitLimit }),
368
+ ];
369
+ // A zero price omits the instruction entirely — worth ~40 bytes when the
370
+ // budget is tight (the gasless path relies on exactly this).
371
+ if (computeUnitPriceMicroLamports > 0) {
372
+ instructions.push(web3_js_1.ComputeBudgetProgram.setComputeUnitPrice({
373
+ microLamports: computeUnitPriceMicroLamports,
374
+ }));
375
+ }
376
+ instructions.push(transactIx);
377
+ const message = new web3_js_1.TransactionMessage({
378
+ payerKey: signer,
379
+ recentBlockhash: blockhash.blockhash,
380
+ instructions,
381
+ }).compileToV0Message([alt]);
382
+ const transaction = new web3_js_1.VersionedTransaction(message);
383
+ // Measure the message separately and add the one-signature wire section.
384
+ // VersionedTransaction.serialize() cannot be used for diagnostics here: it
385
+ // serializes through a fixed-size buffer and can throw `encoding overruns`
386
+ // before we get a chance to report which ALT keys were missing.
387
+ const serializedSize = serializedMessageSize(message) + computeBudget_js_1.SIGNATURE_BYTES;
388
+ if (serializedSize > computeBudget_js_1.MAX_TRANSACTION_BYTES) {
389
+ const staticKeys = message.staticAccountKeys.map((k) => k.toBase58());
390
+ const inAlt = new Set(alt.state.addresses.map((a) => a.toBase58()));
391
+ throw new errors_js_1.ShieldError("TX_TOO_LARGE", `Shield transaction is ${serializedSize} bytes, over the ${computeBudget_js_1.MAX_TRANSACTION_BYTES} ` +
392
+ `limit by ${serializedSize - computeBudget_js_1.MAX_TRANSACTION_BYTES}. ` +
393
+ `${staticKeys.length} account(s) could not be compressed into the lookup table.`, {
394
+ context: {
395
+ serializedSize,
396
+ limit: computeBudget_js_1.MAX_TRANSACTION_BYTES,
397
+ alt: alt.key.toBase58(),
398
+ uncompressedKeys: staticKeys.filter((k) => !inAlt.has(k)),
399
+ },
400
+ });
401
+ }
402
+ return { transaction, serializedSize };
403
+ }
404
+ /** Exact v0 message wire size without serializing into web3.js' 1232-byte buffer. */
405
+ function serializedMessageSize(message) {
406
+ const staticKeys = message.staticAccountKeys.length;
407
+ const instructions = message.compiledInstructions;
408
+ const lookups = message.addressTableLookups;
409
+ return (1 + // v0 prefix
410
+ 3 + // message header
411
+ shortVecSize(staticKeys) +
412
+ staticKeys * 32 +
413
+ 32 + // recent blockhash
414
+ shortVecSize(instructions.length) +
415
+ instructions.reduce((sum, ix) => sum +
416
+ 1 + // program id index
417
+ shortVecSize(ix.accountKeyIndexes.length) +
418
+ ix.accountKeyIndexes.length +
419
+ shortVecSize(ix.data.length) +
420
+ ix.data.length, 0) +
421
+ shortVecSize(lookups.length) +
422
+ lookups.reduce((sum, lookup) => sum +
423
+ 32 +
424
+ shortVecSize(lookup.writableIndexes.length) +
425
+ lookup.writableIndexes.length +
426
+ shortVecSize(lookup.readonlyIndexes.length) +
427
+ lookup.readonlyIndexes.length, 0));
428
+ }
429
+ /** Number of bytes used by Solana's short-vector length prefix. */
430
+ function shortVecSize(value) {
431
+ let size = 1;
432
+ while (value >= 0x80) {
433
+ value >>>= 7;
434
+ size++;
435
+ }
436
+ return size;
437
+ }
438
+ // -- helpers ------------------------------------------------------------------
439
+ /**
440
+ * Wrap a zero-value UTXO as a circuit input.
441
+ *
442
+ * The path elements are the Poseidon zero chain and the index is 0. Neither is
443
+ * constrained — the circuit disables its Merkle check for zero-amount inputs —
444
+ * but the witness still has to be well-formed and the right length.
445
+ */
446
+ function toDummyInput(utxo, zeroChain) {
447
+ return {
448
+ ...utxo,
449
+ pathIndex: 0,
450
+ pathElements: zeroChain,
451
+ privateKey: utxo.privateKey,
452
+ };
453
+ }
454
+ function resolveTransactAccounts(params) {
455
+ const { programId, mint, signer } = params;
456
+ const { config, vault, nullifiers } = (0, pdas_js_1.getPoolPdas)(programId, mint);
457
+ return {
458
+ config,
459
+ global_config: (0, pdas_js_1.getGlobalConfigPda)(programId),
460
+ vault,
461
+ input_tree: (0, pdas_js_1.getNoteTreePda)(programId, mint, params.inputTreeId),
462
+ output_tree: (0, pdas_js_1.getNoteTreePda)(programId, mint, params.outputTreeId),
463
+ nullifiers,
464
+ nullifier_marker_0: (0, pdas_js_1.getNullifierMarkerPda)(programId, mint, params.inputNullifiers[0]),
465
+ nullifier_marker_1: (0, pdas_js_1.getNullifierMarkerPda)(programId, mint, params.inputNullifiers[1]),
466
+ relayer: signer,
467
+ // For a deposit nothing is withdrawn, so `recipient` is just the signer.
468
+ // Pointing the unused token slots at accounts already in the transaction
469
+ // keeps them from costing 32 static bytes each.
470
+ recipient: signer,
471
+ vault_token_account: params.vaultTokenAccount,
472
+ user_token_account: params.userTokenAccount,
473
+ recipient_token_account: params.userTokenAccount,
474
+ relayer_token_account: params.userTokenAccount,
475
+ token_program: params.isToken ? spl_token_1.TOKEN_PROGRAM_ID : web3_js_1.SystemProgram.programId,
476
+ system_program: web3_js_1.SystemProgram.programId,
477
+ };
478
+ }
479
+ async function rentForNullifierMarkers(connection, cache) {
480
+ const key = `rent:${computeBudget_js_1.NULLIFIER_MARKER_ACCOUNT_BYTES}`;
481
+ let per = await cache.get(key);
482
+ if (per === undefined) {
483
+ per = await connection.getMinimumBalanceForRentExemption(computeBudget_js_1.NULLIFIER_MARKER_ACCOUNT_BYTES);
484
+ await cache.set(key, per, 60 * 60000);
485
+ }
486
+ return BigInt(per) * BigInt(computeBudget_js_1.NULLIFIER_MARKERS_PER_TRANSACT);
487
+ }
488
+ const hex = (u) => Buffer.from(u).toString("hex");
489
+ const unhex = (s) => new Uint8Array(Buffer.from(s, "hex"));
490
+ /** Serialize a proof cache for transport between processes. Contains no secrets. */
491
+ function serializeProofCache(cache) {
492
+ return JSON.stringify(cache);
493
+ }
494
+ function deserializeProofCache(json) {
495
+ const parsed = JSON.parse(json);
496
+ if (parsed?.version !== 1) {
497
+ throw new errors_js_1.ShieldError("UNKNOWN", `unsupported ShieldProofCache version: ${parsed?.version}`);
498
+ }
499
+ return parsed;
500
+ }