@veilo/sdk-core 0.3.3 → 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 (195) hide show
  1. package/README.md +42 -3
  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 +5 -5
  6. package/dist/cjs/client.js +79 -42
  7. package/dist/cjs/compactNote.d.ts +107 -0
  8. package/dist/cjs/compactNote.js +167 -0
  9. package/dist/cjs/events.d.ts +1 -1
  10. package/dist/cjs/events.js +2 -2
  11. package/dist/cjs/idl/privacy_pool.d.ts +5 -0
  12. package/dist/cjs/idl/privacy_pool.js +15218 -0
  13. package/dist/cjs/index.d.ts +16 -13
  14. package/dist/cjs/index.js +40 -30
  15. package/dist/cjs/merkle.d.ts +13 -0
  16. package/dist/cjs/merkle.js +31 -8
  17. package/dist/cjs/program.d.ts +11 -0
  18. package/dist/cjs/program.js +26 -3
  19. package/dist/cjs/proof.d.ts +1 -1
  20. package/dist/cjs/proof.js +37 -37
  21. package/dist/cjs/prover.d.ts +1 -1
  22. package/dist/cjs/prover.js +2 -2
  23. package/dist/cjs/random.d.ts +16 -0
  24. package/dist/cjs/random.js +28 -0
  25. package/dist/cjs/relayer.d.ts +27 -4
  26. package/dist/cjs/relayer.js +16 -5
  27. package/dist/cjs/shield/alt.d.ts +87 -0
  28. package/dist/cjs/shield/alt.js +194 -0
  29. package/dist/cjs/shield/computeBudget.d.ts +61 -0
  30. package/dist/cjs/shield/computeBudget.js +64 -0
  31. package/dist/cjs/shield/errors.d.ts +58 -0
  32. package/dist/cjs/shield/errors.js +121 -0
  33. package/dist/cjs/shield/finalize.d.ts +45 -0
  34. package/dist/cjs/shield/finalize.js +119 -0
  35. package/dist/cjs/shield/index.d.ts +35 -0
  36. package/dist/cjs/shield/index.js +68 -0
  37. package/dist/cjs/shield/ix.d.ts +54 -0
  38. package/dist/cjs/shield/ix.js +119 -0
  39. package/dist/cjs/shield/owner.d.ts +36 -0
  40. package/dist/cjs/shield/owner.js +126 -0
  41. package/dist/cjs/shield/ports.d.ts +43 -0
  42. package/dist/cjs/shield/ports.js +153 -0
  43. package/dist/cjs/shield/preflight.d.ts +30 -0
  44. package/dist/cjs/shield/preflight.js +154 -0
  45. package/dist/cjs/shield/shield.d.ts +68 -0
  46. package/dist/cjs/shield/shield.js +499 -0
  47. package/dist/cjs/shield/types.d.ts +202 -0
  48. package/dist/cjs/shield/types.js +2 -0
  49. package/dist/cjs/utxo.d.ts +20 -0
  50. package/dist/cjs/utxo.js +41 -28
  51. package/dist/esm/client.d.ts +407 -0
  52. package/dist/esm/client.js +9 -5
  53. package/dist/esm/compactNote.d.ts +107 -0
  54. package/dist/esm/compactNote.js +156 -0
  55. package/dist/esm/config.d.ts +82 -0
  56. package/dist/esm/events.d.ts +77 -0
  57. package/dist/esm/events.js +1 -1
  58. package/dist/esm/idl/privacy_pool.d.ts +5 -0
  59. package/dist/esm/idl/privacy_pool.js +15216 -0
  60. package/dist/esm/index.d.ts +16 -0
  61. package/dist/esm/index.js +18 -11
  62. package/dist/esm/merkle.d.ts +77 -0
  63. package/dist/esm/merkle.js +23 -1
  64. package/dist/esm/package.json +1 -0
  65. package/dist/esm/poseidon.d.ts +29 -0
  66. package/dist/esm/program.d.ts +37 -0
  67. package/dist/esm/program.js +23 -1
  68. package/dist/esm/proof.d.ts +183 -0
  69. package/dist/esm/proof.js +2 -2
  70. package/dist/esm/prover.d.ts +54 -0
  71. package/dist/esm/prover.js +1 -1
  72. package/dist/esm/random.d.ts +16 -0
  73. package/dist/esm/random.js +21 -0
  74. package/dist/esm/relayer.d.ts +318 -0
  75. package/dist/esm/relayer.js +16 -5
  76. package/dist/esm/retry.d.ts +32 -0
  77. package/dist/esm/shield/alt.d.ts +87 -0
  78. package/dist/esm/shield/alt.js +186 -0
  79. package/dist/esm/shield/computeBudget.d.ts +61 -0
  80. package/dist/esm/shield/computeBudget.js +61 -0
  81. package/dist/esm/shield/errors.d.ts +58 -0
  82. package/dist/esm/shield/errors.js +115 -0
  83. package/dist/esm/shield/finalize.d.ts +45 -0
  84. package/dist/esm/shield/finalize.js +83 -0
  85. package/dist/esm/shield/index.d.ts +35 -0
  86. package/dist/esm/shield/index.js +32 -0
  87. package/dist/esm/shield/ix.d.ts +54 -0
  88. package/dist/esm/shield/ix.js +82 -0
  89. package/dist/esm/shield/owner.d.ts +36 -0
  90. package/dist/esm/shield/owner.js +122 -0
  91. package/dist/esm/shield/ports.d.ts +43 -0
  92. package/dist/esm/shield/ports.js +147 -0
  93. package/dist/esm/shield/preflight.d.ts +30 -0
  94. package/dist/esm/shield/preflight.js +151 -0
  95. package/dist/esm/shield/shield.d.ts +68 -0
  96. package/dist/esm/shield/shield.js +492 -0
  97. package/dist/esm/shield/types.d.ts +202 -0
  98. package/dist/esm/shield/types.js +1 -0
  99. package/dist/esm/utxo.d.ts +235 -0
  100. package/dist/esm/utxo.js +18 -8
  101. package/dist/src/client.d.ts +407 -0
  102. package/dist/src/client.js +951 -0
  103. package/dist/src/compactNote.d.ts +107 -0
  104. package/dist/src/compactNote.js +167 -0
  105. package/dist/src/config.d.ts +82 -0
  106. package/dist/src/config.js +57 -0
  107. package/dist/src/events.d.ts +77 -0
  108. package/dist/src/events.js +167 -0
  109. package/dist/src/idl/privacy_pool.d.ts +5 -0
  110. package/dist/src/idl/privacy_pool.js +15218 -0
  111. package/dist/src/index.d.ts +16 -0
  112. package/dist/src/index.js +67 -0
  113. package/dist/src/merkle.d.ts +77 -0
  114. package/dist/src/merkle.js +156 -0
  115. package/dist/src/poseidon.d.ts +29 -0
  116. package/dist/src/poseidon.js +100 -0
  117. package/dist/src/program.d.ts +37 -0
  118. package/dist/src/program.js +61 -0
  119. package/dist/src/proof.d.ts +183 -0
  120. package/dist/src/proof.js +292 -0
  121. package/dist/src/prover.d.ts +54 -0
  122. package/dist/src/prover.js +112 -0
  123. package/dist/src/random.d.ts +16 -0
  124. package/dist/src/random.js +28 -0
  125. package/dist/src/relayer.d.ts +318 -0
  126. package/dist/src/relayer.js +257 -0
  127. package/dist/src/retry.d.ts +32 -0
  128. package/dist/src/retry.js +75 -0
  129. package/dist/src/shield/alt.d.ts +87 -0
  130. package/dist/src/shield/alt.js +194 -0
  131. package/dist/src/shield/computeBudget.d.ts +61 -0
  132. package/dist/src/shield/computeBudget.js +64 -0
  133. package/dist/src/shield/errors.d.ts +58 -0
  134. package/dist/src/shield/errors.js +121 -0
  135. package/dist/src/shield/finalize.d.ts +45 -0
  136. package/dist/src/shield/finalize.js +119 -0
  137. package/dist/src/shield/index.d.ts +35 -0
  138. package/dist/src/shield/index.js +68 -0
  139. package/dist/src/shield/ix.d.ts +54 -0
  140. package/dist/src/shield/ix.js +119 -0
  141. package/dist/src/shield/owner.d.ts +36 -0
  142. package/dist/src/shield/owner.js +126 -0
  143. package/dist/src/shield/ports.d.ts +43 -0
  144. package/dist/src/shield/ports.js +153 -0
  145. package/dist/src/shield/preflight.d.ts +30 -0
  146. package/dist/src/shield/preflight.js +154 -0
  147. package/dist/src/shield/shield.d.ts +68 -0
  148. package/dist/src/shield/shield.js +499 -0
  149. package/dist/src/shield/types.d.ts +202 -0
  150. package/dist/src/shield/types.js +2 -0
  151. package/dist/src/utxo.d.ts +235 -0
  152. package/dist/src/utxo.js +407 -0
  153. package/dist/tests/compact-note.test.d.ts +1 -0
  154. package/dist/tests/compact-note.test.js +173 -0
  155. package/dist/tests/config.test.d.ts +1 -0
  156. package/dist/tests/config.test.js +102 -0
  157. package/dist/tests/edge-cases.test.d.ts +1 -0
  158. package/dist/tests/edge-cases.test.js +220 -0
  159. package/dist/tests/encryption.test.d.ts +1 -0
  160. package/dist/tests/encryption.test.js +215 -0
  161. package/dist/tests/events.test.d.ts +1 -0
  162. package/dist/tests/events.test.js +78 -0
  163. package/dist/tests/multi-tree.test.d.ts +1 -0
  164. package/dist/tests/multi-tree.test.js +405 -0
  165. package/dist/tests/pda.test.d.ts +1 -0
  166. package/dist/tests/pda.test.js +229 -0
  167. package/dist/tests/poseidon-builder-parity.test.d.ts +1 -0
  168. package/dist/tests/poseidon-builder-parity.test.js +72 -0
  169. package/dist/tests/poseidon.test.d.ts +1 -0
  170. package/dist/tests/poseidon.test.js +142 -0
  171. package/dist/tests/proof.test.d.ts +1 -0
  172. package/dist/tests/proof.test.js +296 -0
  173. package/dist/tests/relayer.test.d.ts +1 -0
  174. package/dist/tests/relayer.test.js +271 -0
  175. package/dist/tests/sdk.integration.test.d.ts +1 -0
  176. package/dist/tests/sdk.integration.test.js +330 -0
  177. package/dist/tests/shield-owner.test.d.ts +1 -0
  178. package/dist/tests/shield-owner.test.js +89 -0
  179. package/dist/tests/shield-preflight.test.d.ts +1 -0
  180. package/dist/tests/shield-preflight.test.js +87 -0
  181. package/dist/tests/shield-realproof.test.d.ts +1 -0
  182. package/dist/tests/shield-realproof.test.js +272 -0
  183. package/dist/tests/shield.test.d.ts +1 -0
  184. package/dist/tests/shield.test.js +403 -0
  185. package/dist/tests/utxo.test.d.ts +1 -0
  186. package/dist/tests/utxo.test.js +140 -0
  187. package/package.json +69 -11
  188. package/poseidon.d.ts +2 -0
  189. package/poseidon.js +4 -0
  190. package/proof.d.ts +2 -0
  191. package/proof.js +4 -0
  192. package/prover.d.ts +2 -0
  193. package/prover.js +4 -0
  194. package/shield.d.ts +2 -0
  195. package/shield.js +4 -0
@@ -0,0 +1,318 @@
1
+ export interface VeiloRelayerConfig {
2
+ /** Base URL of the relayer. Defaults to Veilo's production service. */
3
+ relayerUrl?: string;
4
+ /** API key sent as x-api-key header */
5
+ apiKey: string;
6
+ /** Relayer's NaCl box public key (base64-encoded, 32 bytes) */
7
+ relayerPublicKey: string;
8
+ /** Optional JWT auth token for authenticated endpoints */
9
+ authToken?: string;
10
+ }
11
+ /** Structured error thrown by VeiloRelayerClient on API failures. */
12
+ export declare class VeiloApiError extends Error {
13
+ code: string;
14
+ status: number;
15
+ details?: unknown;
16
+ constructor(code: string, message: string, status: number, details?: unknown);
17
+ }
18
+ /** Retry configuration for the relayer HTTP client. */
19
+ export interface RetryPolicy {
20
+ /** Max number of retry attempts (default: 3) */
21
+ maxRetries: number;
22
+ /** Base delay in ms for exponential backoff (default: 1000) */
23
+ baseDelayMs: number;
24
+ /** HTTP status codes that trigger a retry (default: [429, 502, 503, 504]) */
25
+ retryableStatuses: number[];
26
+ }
27
+ export interface RelayerEncryptedNote {
28
+ noteId: string;
29
+ commitment: string;
30
+ ephemeralPublicKey: string;
31
+ encryptedBlob: string;
32
+ timestamp: number;
33
+ blockHeight?: number;
34
+ txSignature?: string;
35
+ spent?: boolean;
36
+ onchainId?: string;
37
+ spentTx?: string;
38
+ spentAt?: number;
39
+ compactEphemeralKey?: string | null;
40
+ compactBlob?: string | null;
41
+ viewTag?: number | null;
42
+ leafIndex?: number | null;
43
+ mintAddress?: string | null;
44
+ treeId?: number | null;
45
+ }
46
+ export interface QueryNotesRequest {
47
+ lastCheckedTimestamp?: number;
48
+ limit?: number;
49
+ offset?: number;
50
+ walletPublicKey?: string;
51
+ }
52
+ export interface QueryNotesResponse {
53
+ success: boolean;
54
+ notes: RelayerEncryptedNote[];
55
+ total: number;
56
+ limit: number;
57
+ offset: number;
58
+ }
59
+ export interface SaveEncryptedNoteRequest {
60
+ commitment: string;
61
+ ephemeralPublicKey: string;
62
+ encryptedBlob: string;
63
+ timestamp: number;
64
+ blockHeight?: number;
65
+ txSignature?: string;
66
+ recipientWalletPublicKey?: string;
67
+ compactEphemeralKey?: string | null;
68
+ compactBlob?: string | null;
69
+ viewTag?: number | null;
70
+ leafIndex?: number;
71
+ newRoot?: string;
72
+ mintAddress?: string;
73
+ treeId?: number;
74
+ amountRaw?: string;
75
+ }
76
+ export interface SaveEncryptedNoteResponse {
77
+ success: boolean;
78
+ noteId?: string;
79
+ message?: string;
80
+ error?: string;
81
+ }
82
+ export interface MerkleRootResponse {
83
+ success: boolean;
84
+ data: {
85
+ root: string;
86
+ nextIndex: number;
87
+ treeId: number;
88
+ onChainTreeId: number;
89
+ mintAddress: string;
90
+ };
91
+ }
92
+ export interface MerkleTreeResponse {
93
+ success: boolean;
94
+ data: {
95
+ treeId: number;
96
+ onChainTreeId: number;
97
+ mintAddress: string;
98
+ height: number;
99
+ nextIndex: number;
100
+ root: string;
101
+ totalCommitments: number;
102
+ leaves: Array<{
103
+ commitment: string;
104
+ index: number;
105
+ txSignature: string;
106
+ slot: number;
107
+ timestamp: string;
108
+ }>;
109
+ reconstructionInfo: {
110
+ instructions: string;
111
+ treeHeight: number;
112
+ hashFunction?: string;
113
+ };
114
+ };
115
+ }
116
+ export interface TransactNote {
117
+ commitment: string;
118
+ privateKey: string;
119
+ publicKey: string;
120
+ blinding: string;
121
+ amount: string;
122
+ nullifier: string;
123
+ leafIndex?: number;
124
+ noteId?: string;
125
+ }
126
+ export interface WithdrawRequest {
127
+ notes: TransactNote[];
128
+ recipient: string;
129
+ amount: string;
130
+ userPublicKey: string;
131
+ mintAddress: string;
132
+ }
133
+ export interface WithdrawResponse {
134
+ success: boolean;
135
+ message: string;
136
+ data?: {
137
+ withdrawRecipient: string;
138
+ withdrawAmount: number;
139
+ changeAmount: number;
140
+ changeNote: {
141
+ commitment: string;
142
+ privateKey: string;
143
+ publicKey: string;
144
+ blinding: string;
145
+ amount: string;
146
+ nullifier: string;
147
+ };
148
+ spentNoteIds?: string[];
149
+ txSignature?: string;
150
+ };
151
+ }
152
+ export interface PrivateTransferRequest {
153
+ notes: TransactNote[];
154
+ amount: string;
155
+ recipientUsername: string;
156
+ userPublicKey?: string;
157
+ mintAddress?: string;
158
+ }
159
+ export interface PrivateTransferResponse {
160
+ success: boolean;
161
+ message: string;
162
+ data?: {
163
+ recipient: string;
164
+ transferAmount: number;
165
+ senderChangeAmount: number;
166
+ txSignature: string;
167
+ recipientNote: {
168
+ commitment: string;
169
+ amount: string;
170
+ leafIndex: number;
171
+ savedNoteId: string;
172
+ };
173
+ senderChangeNote: {
174
+ commitment: string;
175
+ privateKey: string;
176
+ publicKey: string;
177
+ blinding: string;
178
+ amount: string;
179
+ leafIndex: number;
180
+ savedNoteId: string;
181
+ } | null;
182
+ };
183
+ }
184
+ export interface PrivateSwapRequest {
185
+ notes: TransactNote[];
186
+ sourceMintAddress: string;
187
+ destMintAddress: string;
188
+ sourceJupiterMint?: string;
189
+ destJupiterMint?: string;
190
+ swapAmountRaw: string;
191
+ minAmountOut: string;
192
+ slippageBps: number;
193
+ userPublicKey: string;
194
+ veiloPublicKey: string;
195
+ }
196
+ export interface PrivateSwapResponse {
197
+ success: boolean;
198
+ message: string;
199
+ data?: {
200
+ txSignature: string;
201
+ swapAmountRaw: string;
202
+ outputAmount: string;
203
+ minAmountOut: string;
204
+ changeAmount: string;
205
+ };
206
+ }
207
+ export interface ChallengeResponse {
208
+ success: boolean;
209
+ challenge: string;
210
+ expiresAt: number;
211
+ }
212
+ export interface RegisterRequest {
213
+ username: string;
214
+ walletPublicKey: string;
215
+ signature: string;
216
+ challenge: string;
217
+ veiloPublicKey: string;
218
+ }
219
+ export interface RegisterResponse {
220
+ success: boolean;
221
+ token: string;
222
+ message?: string;
223
+ }
224
+ export interface RestoreRequest {
225
+ walletPublicKey: string;
226
+ signature: string;
227
+ challenge: string;
228
+ }
229
+ export interface RestoreResponse {
230
+ success: boolean;
231
+ token: string;
232
+ username: string;
233
+ veiloPublicKey: string;
234
+ }
235
+ export interface CheckUsernameResponse {
236
+ success: boolean;
237
+ available: boolean;
238
+ }
239
+ export interface VeiloPublicKeyResponse {
240
+ success: boolean;
241
+ username: string;
242
+ pubK: string;
243
+ veiloPublicKey: string;
244
+ }
245
+ export interface PreRegisterKeyResponse {
246
+ success: boolean;
247
+ veiloPublicKey: string;
248
+ }
249
+ export interface DeleteUserDataResponse {
250
+ success: boolean;
251
+ message: string;
252
+ deletedCount?: number;
253
+ }
254
+ /**
255
+ * HTTP client for the Veilo relayer API.
256
+ *
257
+ * Handles auth, notes, merkle, and encrypted transact endpoints with
258
+ * automatic retry on transient failures and NaCl box payload encryption.
259
+ *
260
+ * @example
261
+ * ```ts
262
+ * const client = new VeiloRelayerClient({
263
+ * apiKey: "your-api-key",
264
+ * relayerPublicKey: "<base64 NaCl public key>",
265
+ * });
266
+ * const root = await client.getMerkleRoot("So111...");
267
+ * ```
268
+ */
269
+ export declare class VeiloRelayerClient {
270
+ private readonly baseUrl;
271
+ private readonly apiKey;
272
+ private readonly relayerPubKey;
273
+ private authToken;
274
+ private readonly retry;
275
+ constructor(config: VeiloRelayerConfig, retry?: Partial<RetryPolicy>);
276
+ /** Update the auth token (e.g. after register/restore). */
277
+ setAuthToken(token: string): void;
278
+ private headers;
279
+ private request;
280
+ private encrypt;
281
+ /** Request a signature challenge for wallet authentication. */
282
+ getChallenge(walletPublicKey: string): Promise<ChallengeResponse>;
283
+ /** Register a new account with a signed challenge. Returns a JWT auth token. */
284
+ register(data: RegisterRequest): Promise<RegisterResponse>;
285
+ /** Restore an existing account using a signed challenge. Returns a JWT auth token. */
286
+ restore(data: RestoreRequest): Promise<RestoreResponse>;
287
+ /** Check whether a username is available for registration. */
288
+ checkUsername(username: string): Promise<CheckUsernameResponse>;
289
+ /** Look up a user's Veilo public key by username or wallet public key. */
290
+ getVeiloPublicKey(params: {
291
+ username: string;
292
+ publicKey?: never;
293
+ } | {
294
+ publicKey: string;
295
+ username?: never;
296
+ }): Promise<VeiloPublicKeyResponse>;
297
+ /**
298
+ * Provision (or retrieve) the Veilo spend key paired with a Solana address.
299
+ * Public and idempotent; the response contains public key material only.
300
+ */
301
+ preRegisterKey(solanaAddress: string): Promise<PreRegisterKeyResponse>;
302
+ /** Save an encrypted note to the relayer's database. */
303
+ saveEncryptedNote(data: SaveEncryptedNoteRequest): Promise<SaveEncryptedNoteResponse>;
304
+ /** Query encrypted notes for the authenticated user. Requires auth token. */
305
+ queryEncryptedNotes(params?: QueryNotesRequest): Promise<QueryNotesResponse>;
306
+ /** Delete all stored data for the authenticated user. Requires auth token. */
307
+ deleteUserData(): Promise<DeleteUserDataResponse>;
308
+ /** Fetch the current Merkle root for a pool, optionally filtered by mint and tree ID. */
309
+ getMerkleRoot(mintAddress?: string, treeId?: number): Promise<MerkleRootResponse>;
310
+ /** Fetch the full Merkle tree (all leaves) for a pool. */
311
+ getMerkleTree(mintAddress?: string, treeId?: number): Promise<MerkleTreeResponse>;
312
+ /** Submit an encrypted withdrawal request to the relayer. Not retried on failure. */
313
+ submitWithdraw(data: WithdrawRequest): Promise<WithdrawResponse>;
314
+ /** Submit an encrypted private transfer request. Not retried on failure. */
315
+ submitPrivateTransfer(data: PrivateTransferRequest): Promise<PrivateTransferResponse>;
316
+ /** Submit an encrypted private swap request. Not retried on failure. */
317
+ submitPrivateSwap(data: PrivateSwapRequest): Promise<PrivateSwapResponse>;
318
+ }
@@ -1,14 +1,16 @@
1
1
  import nacl from "tweetnacl";
2
+ const DEFAULT_RELAYER_URL = "https://relayer-server.onrender.com";
2
3
  // =============================================================================
3
4
  // Structured Error
4
5
  // =============================================================================
5
6
  /** Structured error thrown by VeiloRelayerClient on API failures. */
6
7
  export class VeiloApiError extends Error {
7
- constructor(code, message, status) {
8
+ constructor(code, message, status, details) {
8
9
  super(message);
9
10
  this.name = "VeiloApiError";
10
11
  this.code = code;
11
12
  this.status = status;
13
+ this.details = details;
12
14
  }
13
15
  }
14
16
  const DEFAULT_RETRY = {
@@ -65,7 +67,6 @@ function encryptForRelayer(data, relayerPublicKey) {
65
67
  * @example
66
68
  * ```ts
67
69
  * const client = new VeiloRelayerClient({
68
- * relayerUrl: "https://relayer.veilo.io",
69
70
  * apiKey: "your-api-key",
70
71
  * relayerPublicKey: "<base64 NaCl public key>",
71
72
  * });
@@ -74,7 +75,7 @@ function encryptForRelayer(data, relayerPublicKey) {
74
75
  */
75
76
  export class VeiloRelayerClient {
76
77
  constructor(config, retry) {
77
- this.baseUrl = config.relayerUrl.replace(/\/+$/, "");
78
+ this.baseUrl = (config.relayerUrl?.trim() || DEFAULT_RELAYER_URL).replace(/\/+$/, "");
78
79
  this.apiKey = config.apiKey;
79
80
  this.relayerPubKey = fromBase64(config.relayerPublicKey);
80
81
  this.authToken = config.authToken;
@@ -90,8 +91,9 @@ export class VeiloRelayerClient {
90
91
  headers(authenticated) {
91
92
  const h = {
92
93
  "Content-Type": "application/json",
93
- "x-api-key": this.apiKey,
94
94
  };
95
+ if (this.apiKey)
96
+ h["x-api-key"] = this.apiKey;
95
97
  if (authenticated && this.authToken) {
96
98
  h["Authorization"] = `Bearer ${this.authToken}`;
97
99
  }
@@ -124,7 +126,7 @@ export class VeiloRelayerClient {
124
126
  if (res.ok && data.success !== false) {
125
127
  return data;
126
128
  }
127
- lastError = new VeiloApiError(data.error || "UNKNOWN", data.message || data.error || `Request failed: ${res.status}`, res.status);
129
+ lastError = new VeiloApiError(data.error || "UNKNOWN", data.message || data.error || `Request failed: ${res.status}`, res.status, data);
128
130
  // Only retry on transient statuses
129
131
  if (!this.retry.retryableStatuses.includes(res.status)) {
130
132
  throw lastError;
@@ -167,6 +169,15 @@ export class VeiloRelayerClient {
167
169
  : `publicKey=${encodeURIComponent(params.publicKey)}`;
168
170
  return this.request("GET", `/auth/veiloPublicKey?${query}`);
169
171
  }
172
+ /**
173
+ * Provision (or retrieve) the Veilo spend key paired with a Solana address.
174
+ * Public and idempotent; the response contains public key material only.
175
+ */
176
+ async preRegisterKey(solanaAddress) {
177
+ return this.request("POST", "/auth/pre-register-key", {
178
+ body: { solanaAddress },
179
+ });
180
+ }
170
181
  // ---------------------------------------------------------------------------
171
182
  // Notes
172
183
  // ---------------------------------------------------------------------------
@@ -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 "../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
+ }