@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
@@ -1,238 +1,2 @@
1
- import nacl from "tweetnacl";
2
- // =============================================================================
3
- // Structured Error
4
- // =============================================================================
5
- /** Structured error thrown by VeiloRelayerClient on API failures. */
6
- export class VeiloApiError extends Error {
7
- constructor(code, message, status) {
8
- super(message);
9
- this.name = "VeiloApiError";
10
- this.code = code;
11
- this.status = status;
12
- }
13
- }
14
- const DEFAULT_RETRY = {
15
- maxRetries: 3,
16
- baseDelayMs: 1000,
17
- retryableStatuses: [429, 502, 503, 504],
18
- };
19
- // =============================================================================
20
- // Base64 helpers (no dependency on tweetnacl-util)
21
- // =============================================================================
22
- function toBase64(bytes) {
23
- if (typeof Buffer !== "undefined") {
24
- return Buffer.from(bytes).toString("base64");
25
- }
26
- return btoa(String.fromCharCode(...bytes));
27
- }
28
- function fromBase64(str) {
29
- if (typeof Buffer !== "undefined") {
30
- return new Uint8Array(Buffer.from(str, "base64"));
31
- }
32
- const binary = atob(str);
33
- const bytes = new Uint8Array(binary.length);
34
- for (let i = 0; i < binary.length; i++)
35
- bytes[i] = binary.charCodeAt(i);
36
- return bytes;
37
- }
38
- // =============================================================================
39
- // Encryption
40
- // =============================================================================
41
- /**
42
- * Encrypt a JSON-serializable payload for the relayer using NaCl box.
43
- * Layout: [ephemeralPubKey (32)] [nonce (24)] [ciphertext (...)]
44
- */
45
- function encryptForRelayer(data, relayerPublicKey) {
46
- const ephemeral = nacl.box.keyPair();
47
- const message = new TextEncoder().encode(JSON.stringify(data));
48
- const nonce = nacl.randomBytes(nacl.box.nonceLength);
49
- const ciphertext = nacl.box(message, nonce, relayerPublicKey, ephemeral.secretKey);
50
- const payload = new Uint8Array(ephemeral.publicKey.length + nonce.length + ciphertext.length);
51
- payload.set(ephemeral.publicKey, 0);
52
- payload.set(nonce, ephemeral.publicKey.length);
53
- payload.set(ciphertext, ephemeral.publicKey.length + nonce.length);
54
- return toBase64(payload);
55
- }
56
- // =============================================================================
57
- // Relayer Client
58
- // =============================================================================
59
- /**
60
- * HTTP client for the Veilo relayer API.
61
- *
62
- * Handles auth, notes, merkle, and encrypted transact endpoints with
63
- * automatic retry on transient failures and NaCl box payload encryption.
64
- *
65
- * @example
66
- * ```ts
67
- * const client = new VeiloRelayerClient({
68
- * relayerUrl: "https://relayer.veilo.io",
69
- * apiKey: "your-api-key",
70
- * relayerPublicKey: "<base64 NaCl public key>",
71
- * });
72
- * const root = await client.getMerkleRoot("So111...");
73
- * ```
74
- */
75
- export class VeiloRelayerClient {
76
- constructor(config, retry) {
77
- this.baseUrl = config.relayerUrl.replace(/\/+$/, "");
78
- this.apiKey = config.apiKey;
79
- this.relayerPubKey = fromBase64(config.relayerPublicKey);
80
- this.authToken = config.authToken;
81
- this.retry = { ...DEFAULT_RETRY, ...retry };
82
- }
83
- /** Update the auth token (e.g. after register/restore). */
84
- setAuthToken(token) {
85
- this.authToken = token;
86
- }
87
- // ---------------------------------------------------------------------------
88
- // Internal helpers
89
- // ---------------------------------------------------------------------------
90
- headers(authenticated) {
91
- const h = {
92
- "Content-Type": "application/json",
93
- "x-api-key": this.apiKey,
94
- };
95
- if (authenticated && this.authToken) {
96
- h["Authorization"] = `Bearer ${this.authToken}`;
97
- }
98
- return h;
99
- }
100
- async request(method, path, opts = {}) {
101
- const url = `${this.baseUrl}/api${path}`;
102
- const { body, authenticated = false, retryable = true } = opts;
103
- const maxAttempts = retryable ? this.retry.maxRetries + 1 : 1;
104
- let lastError;
105
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
106
- if (attempt > 0) {
107
- const delay = this.retry.baseDelayMs * Math.pow(2, attempt - 1) +
108
- Math.random() * 200;
109
- await new Promise((r) => setTimeout(r, delay));
110
- }
111
- let res;
112
- try {
113
- res = await fetch(url, {
114
- method,
115
- headers: this.headers(authenticated),
116
- body: body != null ? JSON.stringify(body) : undefined,
117
- });
118
- }
119
- catch (err) {
120
- lastError = new VeiloApiError("NETWORK_ERROR", err.message || "Network request failed", 0);
121
- continue;
122
- }
123
- const data = await res.json().catch(() => ({}));
124
- if (res.ok && data.success !== false) {
125
- return data;
126
- }
127
- lastError = new VeiloApiError(data.error || "UNKNOWN", data.message || data.error || `Request failed: ${res.status}`, res.status);
128
- // Only retry on transient statuses
129
- if (!this.retry.retryableStatuses.includes(res.status)) {
130
- throw lastError;
131
- }
132
- }
133
- throw lastError;
134
- }
135
- encrypt(data) {
136
- return encryptForRelayer({
137
- ...data,
138
- timestamp: Date.now(),
139
- nonce: toBase64(nacl.randomBytes(32)),
140
- }, this.relayerPubKey);
141
- }
142
- // ---------------------------------------------------------------------------
143
- // Auth
144
- // ---------------------------------------------------------------------------
145
- /** Request a signature challenge for wallet authentication. */
146
- async getChallenge(walletPublicKey) {
147
- return this.request("POST", "/auth/challenge", {
148
- body: { walletPublicKey },
149
- });
150
- }
151
- /** Register a new account with a signed challenge. Returns a JWT auth token. */
152
- async register(data) {
153
- return this.request("POST", "/auth/register", { body: data });
154
- }
155
- /** Restore an existing account using a signed challenge. Returns a JWT auth token. */
156
- async restore(data) {
157
- return this.request("POST", "/auth/restore", { body: data });
158
- }
159
- /** Check whether a username is available for registration. */
160
- async checkUsername(username) {
161
- return this.request("GET", `/auth/checkUsername?username=${encodeURIComponent(username)}`);
162
- }
163
- /** Look up a user's Veilo public key by username or wallet public key. */
164
- async getVeiloPublicKey(params) {
165
- const query = "username" in params && params.username
166
- ? `username=${encodeURIComponent(params.username)}`
167
- : `publicKey=${encodeURIComponent(params.publicKey)}`;
168
- return this.request("GET", `/auth/veiloPublicKey?${query}`);
169
- }
170
- // ---------------------------------------------------------------------------
171
- // Notes
172
- // ---------------------------------------------------------------------------
173
- /** Save an encrypted note to the relayer's database. */
174
- async saveEncryptedNote(data) {
175
- return this.request("POST", "/notes/save", { body: data });
176
- }
177
- /** Query encrypted notes for the authenticated user. Requires auth token. */
178
- async queryEncryptedNotes(params = {}) {
179
- return this.request("POST", "/notes/query", {
180
- body: params,
181
- authenticated: true,
182
- });
183
- }
184
- /** Delete all stored data for the authenticated user. Requires auth token. */
185
- async deleteUserData() {
186
- return this.request("POST", "/notes/delete", { authenticated: true });
187
- }
188
- // ---------------------------------------------------------------------------
189
- // Merkle
190
- // ---------------------------------------------------------------------------
191
- /** Fetch the current Merkle root for a pool, optionally filtered by mint and tree ID. */
192
- async getMerkleRoot(mintAddress, treeId) {
193
- const params = new URLSearchParams();
194
- if (mintAddress)
195
- params.append("mintAddress", mintAddress);
196
- if (treeId !== undefined)
197
- params.append("treeId", treeId.toString());
198
- const qs = params.toString();
199
- return this.request("GET", `/merkle/root${qs ? `?${qs}` : ""}`);
200
- }
201
- /** Fetch the full Merkle tree (all leaves) for a pool. */
202
- async getMerkleTree(mintAddress, treeId) {
203
- const params = new URLSearchParams();
204
- if (mintAddress)
205
- params.append("mintAddress", mintAddress);
206
- if (treeId !== undefined)
207
- params.append("treeId", treeId.toString());
208
- const qs = params.toString();
209
- return this.request("GET", `/merkle/tree${qs ? `?${qs}` : ""}`);
210
- }
211
- // ---------------------------------------------------------------------------
212
- // Transact (encrypted payloads)
213
- // ---------------------------------------------------------------------------
214
- /** Submit an encrypted withdrawal request to the relayer. Not retried on failure. */
215
- async submitWithdraw(data) {
216
- const encryptedPayload = this.encrypt(data);
217
- return this.request("POST", "/transact/withdra", {
218
- body: { encryptedPayload },
219
- retryable: false,
220
- });
221
- }
222
- /** Submit an encrypted private transfer request. Not retried on failure. */
223
- async submitPrivateTransfer(data) {
224
- const encryptedPayload = this.encrypt(data);
225
- return this.request("POST", "/transact/private-transfer", {
226
- body: { encryptedPayload },
227
- retryable: false,
228
- });
229
- }
230
- /** Submit an encrypted private swap request. Not retried on failure. */
231
- async submitPrivateSwap(data) {
232
- const encryptedPayload = this.encrypt(data);
233
- return this.request("POST", "/transact/private-swap", {
234
- body: { encryptedPayload },
235
- retryable: false,
236
- });
237
- }
238
- }
1
+ // Backward-compatible entry point. Relayer responsibilities live in src/relayer.
2
+ export * from "./relayer/index.js";
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Configuration for retry behavior on Solana RPC calls.
3
+ */
4
+ export interface RpcRetryPolicy {
5
+ /** Maximum number of retry attempts (default: 3) */
6
+ maxRetries: number;
7
+ /** Base delay in ms for exponential backoff (default: 1000) */
8
+ baseDelayMs: number;
9
+ /** Maximum delay cap in ms (default: 10000) */
10
+ maxDelayMs: number;
11
+ }
12
+ export declare const DEFAULT_RPC_RETRY: RpcRetryPolicy;
13
+ /**
14
+ * Execute an async function with retries on transient RPC failures.
15
+ *
16
+ * Retries on: BlockhashNotFound, HTTP 429/502/503/504, timeouts, connection resets.
17
+ * Does NOT retry on: program errors (6xxx), signature verification failures, or other
18
+ * deterministic errors that would fail again.
19
+ *
20
+ * @param fn The async operation to execute
21
+ * @param policy Retry configuration (uses sensible defaults if omitted)
22
+ * @returns The result of the async operation
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const txSig = await withRpcRetry(
27
+ * () => program.methods.transact(...).accounts({...}).signers([...]).rpc(),
28
+ * { maxRetries: 5 },
29
+ * );
30
+ * ```
31
+ */
32
+ export declare function withRpcRetry<T>(fn: () => Promise<T>, policy?: Partial<RpcRetryPolicy>): Promise<T>;
@@ -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 "../accounts/pdas.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;