@veilo/sdk-core 0.5.0 → 0.6.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 (236) hide show
  1. package/README.md +237 -19
  2. package/accounts.d.ts +2 -0
  3. package/accounts.js +3 -0
  4. package/cloak.d.ts +2 -0
  5. package/cloak.js +3 -0
  6. package/config.d.ts +2 -0
  7. package/config.js +3 -0
  8. package/dist/cjs/events/index.d.ts +6 -0
  9. package/dist/cjs/events/index.js +22 -0
  10. package/dist/cjs/events/parsing.d.ts +25 -0
  11. package/dist/cjs/events/parsing.js +158 -0
  12. package/dist/cjs/events/position.d.ts +26 -0
  13. package/dist/cjs/events/position.js +53 -0
  14. package/dist/cjs/events/recovery.d.ts +87 -0
  15. package/dist/cjs/events/recovery.js +281 -0
  16. package/dist/cjs/events/scanning.d.ts +35 -0
  17. package/dist/cjs/events/scanning.js +98 -0
  18. package/dist/cjs/events/tree.d.ts +27 -0
  19. package/dist/cjs/events/tree.js +63 -0
  20. package/dist/cjs/events/types.d.ts +39 -0
  21. package/dist/cjs/events/types.js +2 -0
  22. package/dist/cjs/events.d.ts +1 -77
  23. package/dist/cjs/events.js +6 -154
  24. package/dist/cjs/identity/encoding.d.ts +9 -0
  25. package/dist/cjs/identity/encoding.js +85 -0
  26. package/dist/cjs/identity/index.d.ts +4 -0
  27. package/dist/cjs/identity/index.js +20 -0
  28. package/dist/cjs/identity/noteKey.d.ts +33 -0
  29. package/dist/cjs/identity/noteKey.js +97 -0
  30. package/dist/cjs/identity/spending.d.ts +18 -0
  31. package/dist/cjs/identity/spending.js +46 -0
  32. package/dist/cjs/identity/viewKey.d.ts +38 -0
  33. package/dist/cjs/identity/viewKey.js +105 -0
  34. package/dist/cjs/idl/index.d.ts +18 -0
  35. package/dist/cjs/idl/index.js +24 -0
  36. package/dist/cjs/idl/privacy_pool.json +9907 -9907
  37. package/dist/cjs/idl/privacy_pool_legacy.d.ts +5 -0
  38. package/dist/cjs/idl/privacy_pool_legacy.js +3307 -0
  39. package/dist/cjs/idl/privacy_pool_legacy.json +2302 -0
  40. package/dist/cjs/idl/privacy_pool_legacy2.d.ts +5 -0
  41. package/dist/cjs/idl/privacy_pool_legacy2.js +3397 -0
  42. package/dist/cjs/idl/privacy_pool_legacy2.json +2376 -0
  43. package/dist/cjs/index.d.ts +8 -3
  44. package/dist/cjs/index.js +12 -2
  45. package/dist/cjs/notes/amount.d.ts +2 -0
  46. package/dist/cjs/notes/amount.js +21 -0
  47. package/dist/cjs/notes/index.d.ts +3 -0
  48. package/dist/cjs/notes/index.js +3 -0
  49. package/dist/cjs/notes/recovery.d.ts +16 -6
  50. package/dist/cjs/notes/recovery.js +33 -16
  51. package/dist/cjs/notes/selection.d.ts +77 -0
  52. package/dist/cjs/notes/selection.js +193 -0
  53. package/dist/cjs/notes/spent.d.ts +60 -0
  54. package/dist/cjs/notes/spent.js +101 -0
  55. package/dist/cjs/perps/constants.d.ts +16 -0
  56. package/dist/cjs/perps/constants.js +52 -0
  57. package/dist/cjs/perps/index.d.ts +5 -0
  58. package/dist/cjs/perps/index.js +21 -0
  59. package/dist/cjs/perps/keys.d.ts +16 -0
  60. package/dist/cjs/perps/keys.js +43 -0
  61. package/dist/cjs/perps/pdas.d.ts +29 -0
  62. package/dist/cjs/perps/pdas.js +55 -0
  63. package/dist/cjs/perps/relayer.d.ts +9 -0
  64. package/dist/cjs/perps/relayer.js +35 -0
  65. package/dist/cjs/perps/types.d.ts +126 -0
  66. package/dist/cjs/perps/types.js +2 -0
  67. package/dist/cjs/positions/index.d.ts +4 -0
  68. package/dist/cjs/positions/index.js +20 -0
  69. package/dist/cjs/positions/keys.d.ts +29 -0
  70. package/dist/cjs/positions/keys.js +71 -0
  71. package/dist/cjs/positions/pdas.d.ts +15 -0
  72. package/dist/cjs/positions/pdas.js +54 -0
  73. package/dist/cjs/positions/relayer.d.ts +4 -0
  74. package/dist/cjs/positions/relayer.js +15 -0
  75. package/dist/cjs/positions/types.d.ts +97 -0
  76. package/dist/cjs/positions/types.js +2 -0
  77. package/dist/cjs/predictions/client.d.ts +41 -0
  78. package/dist/cjs/predictions/client.js +147 -0
  79. package/dist/cjs/predictions/index.d.ts +5 -0
  80. package/dist/cjs/predictions/index.js +21 -0
  81. package/dist/cjs/predictions/keys.d.ts +14 -0
  82. package/dist/cjs/predictions/keys.js +40 -0
  83. package/dist/cjs/predictions/pdas.d.ts +6 -0
  84. package/dist/cjs/predictions/pdas.js +13 -0
  85. package/dist/cjs/predictions/relayer.d.ts +3 -0
  86. package/dist/cjs/predictions/relayer.js +11 -0
  87. package/dist/cjs/predictions/types.d.ts +178 -0
  88. package/dist/cjs/predictions/types.js +2 -0
  89. package/dist/cjs/program.d.ts +2 -0
  90. package/dist/cjs/program.js +8 -7
  91. package/dist/cjs/prover.d.ts +27 -4
  92. package/dist/cjs/prover.js +107 -48
  93. package/dist/cjs/relayer/api.d.ts +31 -0
  94. package/dist/cjs/relayer/api.js +86 -0
  95. package/dist/cjs/relayer/client.d.ts +29 -17
  96. package/dist/cjs/relayer/client.js +72 -17
  97. package/dist/cjs/relayer/errors.d.ts +1 -1
  98. package/dist/cjs/relayer/errors.js +1 -1
  99. package/dist/cjs/relayer/index.d.ts +4 -1
  100. package/dist/cjs/relayer/index.js +1 -1
  101. package/dist/cjs/relayer/internal-config.d.ts +36 -0
  102. package/dist/cjs/relayer/internal-config.js +9 -0
  103. package/dist/cjs/relayer/internal.d.ts +6 -0
  104. package/dist/cjs/relayer/internal.js +14 -0
  105. package/dist/cjs/relayer/transport.d.ts +4 -2
  106. package/dist/cjs/relayer/transport.js +10 -5
  107. package/dist/cjs/relayer/types.d.ts +9 -10
  108. package/dist/cjs/relayer/types.js +1 -1
  109. package/dist/cjs/shield/owner.js +1 -4
  110. package/dist/esm/events/index.d.ts +6 -0
  111. package/dist/esm/events/index.js +6 -0
  112. package/dist/esm/events/parsing.d.ts +25 -0
  113. package/dist/esm/events/parsing.js +120 -0
  114. package/dist/esm/events/position.d.ts +26 -0
  115. package/dist/esm/events/position.js +48 -0
  116. package/dist/esm/events/recovery.d.ts +87 -0
  117. package/dist/esm/events/recovery.js +237 -0
  118. package/dist/esm/events/scanning.d.ts +35 -0
  119. package/dist/esm/events/scanning.js +92 -0
  120. package/dist/esm/events/tree.d.ts +27 -0
  121. package/dist/esm/events/tree.js +58 -0
  122. package/dist/esm/events/types.d.ts +39 -0
  123. package/dist/esm/events/types.js +1 -0
  124. package/dist/esm/events.d.ts +1 -77
  125. package/dist/esm/events.js +3 -129
  126. package/dist/esm/identity/encoding.d.ts +9 -0
  127. package/dist/esm/identity/encoding.js +75 -0
  128. package/dist/esm/identity/index.d.ts +4 -0
  129. package/dist/esm/identity/index.js +4 -0
  130. package/dist/esm/identity/noteKey.d.ts +33 -0
  131. package/dist/esm/identity/noteKey.js +91 -0
  132. package/dist/esm/identity/spending.d.ts +18 -0
  133. package/dist/esm/identity/spending.js +35 -0
  134. package/dist/esm/identity/viewKey.d.ts +38 -0
  135. package/dist/esm/identity/viewKey.js +96 -0
  136. package/dist/esm/idl/index.d.ts +18 -0
  137. package/dist/esm/idl/index.js +18 -0
  138. package/dist/esm/idl/privacy_pool.json +9907 -9907
  139. package/dist/esm/idl/privacy_pool_legacy.d.ts +5 -0
  140. package/dist/esm/idl/privacy_pool_legacy.js +3305 -0
  141. package/dist/esm/idl/privacy_pool_legacy.json +2302 -0
  142. package/dist/esm/idl/privacy_pool_legacy2.d.ts +5 -0
  143. package/dist/esm/idl/privacy_pool_legacy2.js +3395 -0
  144. package/dist/esm/idl/privacy_pool_legacy2.json +2376 -0
  145. package/dist/esm/index.d.ts +8 -3
  146. package/dist/esm/index.js +8 -3
  147. package/dist/esm/notes/amount.d.ts +2 -0
  148. package/dist/esm/notes/amount.js +18 -0
  149. package/dist/esm/notes/index.d.ts +3 -0
  150. package/dist/esm/notes/index.js +3 -0
  151. package/dist/esm/notes/recovery.d.ts +16 -6
  152. package/dist/esm/notes/recovery.js +33 -16
  153. package/dist/esm/notes/selection.d.ts +77 -0
  154. package/dist/esm/notes/selection.js +188 -0
  155. package/dist/esm/notes/spent.d.ts +60 -0
  156. package/dist/esm/notes/spent.js +96 -0
  157. package/dist/esm/perps/constants.d.ts +16 -0
  158. package/dist/esm/perps/constants.js +48 -0
  159. package/dist/esm/perps/index.d.ts +5 -0
  160. package/dist/esm/perps/index.js +5 -0
  161. package/dist/esm/perps/keys.d.ts +16 -0
  162. package/dist/esm/perps/keys.js +35 -0
  163. package/dist/esm/perps/pdas.d.ts +29 -0
  164. package/dist/esm/perps/pdas.js +47 -0
  165. package/dist/esm/perps/relayer.d.ts +9 -0
  166. package/dist/esm/perps/relayer.js +25 -0
  167. package/dist/esm/perps/types.d.ts +126 -0
  168. package/dist/esm/perps/types.js +1 -0
  169. package/dist/esm/positions/index.d.ts +4 -0
  170. package/dist/esm/positions/index.js +4 -0
  171. package/dist/esm/positions/keys.d.ts +29 -0
  172. package/dist/esm/positions/keys.js +65 -0
  173. package/dist/esm/positions/pdas.d.ts +15 -0
  174. package/dist/esm/positions/pdas.js +44 -0
  175. package/dist/esm/positions/relayer.d.ts +4 -0
  176. package/dist/esm/positions/relayer.js +10 -0
  177. package/dist/esm/positions/types.d.ts +97 -0
  178. package/dist/esm/positions/types.js +1 -0
  179. package/dist/esm/predictions/client.d.ts +41 -0
  180. package/dist/esm/predictions/client.js +141 -0
  181. package/dist/esm/predictions/index.d.ts +5 -0
  182. package/dist/esm/predictions/index.js +5 -0
  183. package/dist/esm/predictions/keys.d.ts +14 -0
  184. package/dist/esm/predictions/keys.js +33 -0
  185. package/dist/esm/predictions/pdas.d.ts +6 -0
  186. package/dist/esm/predictions/pdas.js +10 -0
  187. package/dist/esm/predictions/relayer.d.ts +3 -0
  188. package/dist/esm/predictions/relayer.js +7 -0
  189. package/dist/esm/predictions/types.d.ts +178 -0
  190. package/dist/esm/predictions/types.js +1 -0
  191. package/dist/esm/program.d.ts +2 -0
  192. package/dist/esm/program.js +4 -3
  193. package/dist/esm/prover.d.ts +27 -4
  194. package/dist/esm/prover.js +106 -15
  195. package/dist/esm/relayer/api.d.ts +31 -0
  196. package/dist/esm/relayer/api.js +55 -0
  197. package/dist/esm/relayer/client.d.ts +29 -17
  198. package/dist/esm/relayer/client.js +72 -17
  199. package/dist/esm/relayer/errors.d.ts +1 -1
  200. package/dist/esm/relayer/errors.js +1 -1
  201. package/dist/esm/relayer/index.d.ts +4 -1
  202. package/dist/esm/relayer/index.js +1 -1
  203. package/dist/esm/relayer/internal-config.d.ts +36 -0
  204. package/dist/esm/relayer/internal-config.js +6 -0
  205. package/dist/esm/relayer/internal.d.ts +6 -0
  206. package/dist/esm/relayer/internal.js +10 -0
  207. package/dist/esm/relayer/transport.d.ts +4 -2
  208. package/dist/esm/relayer/transport.js +10 -5
  209. package/dist/esm/relayer/types.d.ts +9 -10
  210. package/dist/esm/relayer/types.js +1 -1
  211. package/dist/esm/shield/owner.js +1 -4
  212. package/identity.d.ts +2 -0
  213. package/identity.js +3 -0
  214. package/idl.d.ts +2 -0
  215. package/idl.js +3 -0
  216. package/notes.d.ts +2 -0
  217. package/notes.js +3 -0
  218. package/package.json +85 -3
  219. package/perps.d.ts +2 -0
  220. package/perps.js +3 -0
  221. package/poseidon.d.ts +2 -0
  222. package/poseidon.js +3 -0
  223. package/positions.d.ts +2 -0
  224. package/positions.js +3 -0
  225. package/predictions.d.ts +2 -0
  226. package/predictions.js +3 -0
  227. package/proof.d.ts +2 -0
  228. package/proof.js +3 -0
  229. package/prover.d.ts +2 -0
  230. package/prover.js +3 -0
  231. package/relayer.d.ts +2 -0
  232. package/relayer.js +3 -0
  233. package/shield.d.ts +2 -0
  234. package/shield.js +3 -0
  235. package/transactions.d.ts +2 -0
  236. package/transactions.js +3 -0
@@ -4,10 +4,15 @@ export * from "./config.js";
4
4
  export * from "./merkle.js";
5
5
  export * from "./proof.js";
6
6
  export * from "./events.js";
7
- export { createVeiloProgram, createReadonlyVeiloProgram, PRIVACY_POOL_IDL, PRIVACY_POOL_PROGRAM_ID, } from "./program.js";
7
+ export * from "./identity/index.js";
8
+ export * from "./positions/index.js";
9
+ export * from "./perps/index.js";
10
+ export * from "./predictions/index.js";
11
+ export { createVeiloProgram, createReadonlyVeiloProgram, PRIVACY_POOL_CURRENT_IDL, PRIVACY_POOL_IDL, PRIVACY_POOL_IDLS, PRIVACY_POOL_LEGACY_IDL, PRIVACY_POOL_LEGACY2_IDL, PRIVACY_POOL_PROGRAM_ID, } from "./program.js";
12
+ export type { PrivacyPoolIdlVersion } from "./idl/index.js";
8
13
  export * from "./shield/index.js";
9
- export { createTransactionProver, createSwapProver, verifyProof, } from "./prover.js";
10
- export type { CircuitArtifacts } from "./prover.js";
14
+ export { createTransactionProver, createSwapProver, resolveCircuitArtifacts, verifyProof, } from "./prover.js";
15
+ export type { CircuitArtifacts, CircuitName } from "./prover.js";
11
16
  export * from "./compactNote.js";
12
17
  export { randomBytes, randomBytes32 } from "./random.js";
13
18
  export * from "./relayer.js";
package/dist/esm/index.js CHANGED
@@ -10,18 +10,23 @@ export * from "./merkle.js";
10
10
  export * from "./proof.js";
11
11
  // On-chain event scanning and tree reconstruction
12
12
  export * from "./events.js";
13
+ // Private product helpers: keys, PDAs, request types, and unsigned API clients.
14
+ export * from "./identity/index.js";
15
+ export * from "./positions/index.js";
16
+ export * from "./perps/index.js";
17
+ export * from "./predictions/index.js";
13
18
  // Program factory and IDL
14
- export { createVeiloProgram, createReadonlyVeiloProgram, PRIVACY_POOL_IDL, PRIVACY_POOL_PROGRAM_ID, } from "./program.js";
19
+ export { createVeiloProgram, createReadonlyVeiloProgram, PRIVACY_POOL_CURRENT_IDL, PRIVACY_POOL_IDL, PRIVACY_POOL_IDLS, PRIVACY_POOL_LEGACY_IDL, PRIVACY_POOL_LEGACY2_IDL, PRIVACY_POOL_PROGRAM_ID, } from "./program.js";
15
20
  // Wallet-agnostic shielding — build an unsigned deposit for any external wallet
16
21
  export * from "./shield/index.js";
17
22
  // Proof generation (requires snarkjs peer dependency)
18
- export { createTransactionProver, createSwapProver, verifyProof, } from "./prover.js";
23
+ export { createTransactionProver, createSwapProver, resolveCircuitArtifacts, verifyProof, } from "./prover.js";
19
24
  // Compact note ciphers — the on-chain payload that makes notes recoverable
20
25
  // from chain data alone, without any relayer involvement.
21
26
  export * from "./compactNote.js";
22
27
  // Cross-platform CSPRNG (no node:crypto import — safe in browser bundles)
23
28
  export { randomBytes, randomBytes32 } from "./random.js";
24
- // Relayer API client
29
+ // Managed relayer API helpers (network configuration remains internal)
25
30
  export * from "./relayer.js";
26
31
  // Veilo Cloak Partner API client and helpers
27
32
  export * from "./cloak.js";
@@ -0,0 +1,2 @@
1
+ /** Coerce a note amount to base units without ever going through Number. */
2
+ export declare function toBaseUnits(amount: bigint | string | number, label: string): bigint;
@@ -0,0 +1,18 @@
1
+ /** Coerce a note amount to base units without ever going through Number. */
2
+ export function toBaseUnits(amount, label) {
3
+ if (typeof amount === "bigint")
4
+ return amount;
5
+ if (typeof amount === "number") {
6
+ if (!Number.isSafeInteger(amount)) {
7
+ throw new Error(`${label} ${amount} is not a safe integer; pass a bigint or a decimal ` +
8
+ "string for token amounts.");
9
+ }
10
+ return BigInt(amount);
11
+ }
12
+ try {
13
+ return BigInt(amount);
14
+ }
15
+ catch {
16
+ throw new Error(`${label} ${JSON.stringify(amount)} is not a valid amount.`);
17
+ }
18
+ }
@@ -3,3 +3,6 @@ export * from "./nullifier.js";
3
3
  export * from "./encryption.js";
4
4
  export * from "./mailbox.js";
5
5
  export * from "./recovery.js";
6
+ export * from "./spent.js";
7
+ export * from "./selection.js";
8
+ export * from "./amount.js";
@@ -3,3 +3,6 @@ export * from "./nullifier.js";
3
3
  export * from "./encryption.js";
4
4
  export * from "./mailbox.js";
5
5
  export * from "./recovery.js";
6
+ export * from "./spent.js";
7
+ export * from "./selection.js";
8
+ export * from "./amount.js";
@@ -1,10 +1,20 @@
1
1
  import type { DecryptedNote } from "./mailbox.js";
2
2
  /**
3
- * Fetch all encrypted notes for a wallet from the relayer's Blind Mailbox endpoint
4
- * and decrypt them using the wallet's secret key.
3
+ * Fetch this account's encrypted notes from the relayer and decrypt them.
5
4
  *
6
- * @param walletPublicKey Base58 wallet address used to query the relayer
7
- * @param walletSecretKey Full 64-byte keypair.secretKey for decryption
8
- * @param relayerUrl Relayer base URL (e.g. "https://relay.veilo.app")
5
+ * Goes through the managed relayer helper, so the network coordinates stay
6
+ * internal there is no URL to pass. Notes that fail to decrypt are skipped:
7
+ * a query can return rows addressed to other keys, and one bad row must not
8
+ * lose the rest.
9
+ *
10
+ * @param authToken token from `register()` / `restore()`
11
+ * @param walletSecretKey full 64-byte keypair.secretKey, used for decryption
12
+ * @param walletPublicKey optional base58 filter, narrowing the query server-side
9
13
  */
10
- export declare function fetchAndDecryptNotes(walletPublicKey: string, walletSecretKey: Uint8Array, relayerUrl: string): Promise<DecryptedNote[]>;
14
+ export declare function fetchAndDecryptNotes(params: {
15
+ authToken: string;
16
+ walletSecretKey: Uint8Array;
17
+ walletPublicKey?: string;
18
+ limit?: number;
19
+ offset?: number;
20
+ }): Promise<DecryptedNote[]>;
@@ -1,28 +1,45 @@
1
+ import { queryEncryptedNotes } from "../relayer/api.js";
1
2
  import { decryptBlindMailboxNote } from "./mailbox.js";
2
3
  /**
3
- * Fetch all encrypted notes for a wallet from the relayer's Blind Mailbox endpoint
4
- * and decrypt them using the wallet's secret key.
4
+ * Fetch this account's encrypted notes from the relayer and decrypt them.
5
5
  *
6
- * @param walletPublicKey Base58 wallet address used to query the relayer
7
- * @param walletSecretKey Full 64-byte keypair.secretKey for decryption
8
- * @param relayerUrl Relayer base URL (e.g. "https://relay.veilo.app")
6
+ * Goes through the managed relayer helper, so the network coordinates stay
7
+ * internal there is no URL to pass. Notes that fail to decrypt are skipped:
8
+ * a query can return rows addressed to other keys, and one bad row must not
9
+ * lose the rest.
10
+ *
11
+ * @param authToken token from `register()` / `restore()`
12
+ * @param walletSecretKey full 64-byte keypair.secretKey, used for decryption
13
+ * @param walletPublicKey optional base58 filter, narrowing the query server-side
9
14
  */
10
- export async function fetchAndDecryptNotes(walletPublicKey, walletSecretKey, relayerUrl) {
11
- const resp = await fetch(`${relayerUrl}/api/notes?recipientPublicKey=${walletPublicKey}`);
12
- if (!resp.ok) {
13
- throw new Error(`fetchAndDecryptNotes: ${resp.status} ${resp.statusText}`);
14
- }
15
- const { notes } = (await resp.json());
15
+ export async function fetchAndDecryptNotes(params) {
16
+ const { authToken, walletSecretKey, walletPublicKey, limit, offset } = params;
17
+ const { notes } = await queryEncryptedNotes(authToken, {
18
+ ...(walletPublicKey ? { walletPublicKey } : {}),
19
+ ...(limit === undefined ? {} : { limit }),
20
+ ...(offset === undefined ? {} : { offset }),
21
+ });
16
22
  const results = [];
17
- for (const note of notes) {
23
+ for (const note of notes ?? []) {
24
+ if (!note.ephemeralPublicKey || !note.encryptedBlob)
25
+ continue;
18
26
  try {
19
- const epk = Buffer.from(note.ephemeralPublicKey, "base64");
20
- const decrypted = decryptBlindMailboxNote(walletSecretKey, new Uint8Array(epk), note.encryptedBlob);
21
- results.push(decrypted);
27
+ results.push(decryptBlindMailboxNote(walletSecretKey, base64ToBytes(note.ephemeralPublicKey), note.encryptedBlob));
22
28
  }
23
29
  catch {
24
- // Note not for this key or corrupted — skip silently
30
+ // Not addressed to this key, or corrupted — skip it.
25
31
  }
26
32
  }
27
33
  return results;
28
34
  }
35
+ /** Base64 → bytes without assuming a Node Buffer global. */
36
+ function base64ToBytes(value) {
37
+ if (typeof atob === "function") {
38
+ const binary = atob(value);
39
+ const out = new Uint8Array(binary.length);
40
+ for (let i = 0; i < binary.length; i++)
41
+ out[i] = binary.charCodeAt(i);
42
+ return out;
43
+ }
44
+ return new Uint8Array(Buffer.from(value, "base64"));
45
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Choosing which notes to spend.
3
+ *
4
+ * Two constraints drive everything here:
5
+ *
6
+ * 1. The transaction circuit is 2-in-2-out, so a single transaction can spend
7
+ * at most TWO notes.
8
+ * 2. Notes can only be co-spent if they live in the SAME Merkle tree, and the
9
+ * tree is derived from the MINT — see `canonicalTreeId`.
10
+ */
11
+ /** Inputs the transaction circuit accepts in one proof. */
12
+ export declare const MAX_INPUT_NOTES = 2;
13
+ /**
14
+ * The tree a note belongs to, derived from its mint.
15
+ *
16
+ * Mirrors the relayer's `mintAddressToTreeId` byte for byte: the all-zero
17
+ * native-SOL mint maps to 0, anything else to its first four mint bytes as a
18
+ * big-endian uint32.
19
+ *
20
+ * DERIVE THIS, NEVER TRUST A STORED `treeId`. Change notes are written with the
21
+ * on-chain shard index (a small 0/1/2…) while deposits and synced notes carry
22
+ * the mint-derived id. For native SOL both are 0 so the difference hides; for
23
+ * SPL tokens the two land in different buckets, and co-spending across them
24
+ * fails at proof time as a commitment mismatch.
25
+ *
26
+ * An undecodable mint falls back to the SOL bucket rather than inventing a
27
+ * phantom tree, matching the server.
28
+ */
29
+ export declare function canonicalTreeId(mintAddress?: string | null): number;
30
+ /** The minimum a note must carry to be selectable. */
31
+ export interface SelectableNote {
32
+ /** Base units. bigint preferred; strings and safe integers accepted. */
33
+ amount: bigint | string | number;
34
+ /** Mint address; determines the tree. Absent means native SOL. */
35
+ mint?: string | null;
36
+ }
37
+ export interface NoteSelection<T> {
38
+ ok: true;
39
+ /** The chosen notes, your own objects. */
40
+ notes: T[];
41
+ /** Tree every chosen note belongs to. */
42
+ treeId: number;
43
+ /** Sum of the chosen notes. */
44
+ total: bigint;
45
+ /** total - amount. Becomes the change note. */
46
+ change: bigint;
47
+ /**
48
+ * True when more than MAX_INPUT_NOTES were needed, so this cannot be proved
49
+ * as one transaction — the notes must be combined first.
50
+ */
51
+ requiresMerge: boolean;
52
+ }
53
+ export interface NoteSelectionFailure {
54
+ ok: false;
55
+ reason: "NO_NOTES" | "INSUFFICIENT_FUNDS";
56
+ /** Largest total reachable within a single tree. */
57
+ available: bigint;
58
+ message: string;
59
+ }
60
+ export type NoteSelectionResult<T> = NoteSelection<T> | NoteSelectionFailure;
61
+ /**
62
+ * Pick notes to cover `amount`, preferring the fewest notes and least change.
63
+ *
64
+ * Considers each tree separately, since notes cannot be co-spent across trees,
65
+ * and returns the best single-tree selection:
66
+ *
67
+ * 1. one note that covers the amount (smallest such note, least change);
68
+ * 2. otherwise the best PAIR, found by a two-pointer scan over the
69
+ * amount-sorted notes — O(n) rather than an O(n²) all-pairs search;
70
+ * 3. otherwise the largest notes greedily, flagged `requiresMerge` because
71
+ * more than two inputs cannot go into one proof.
72
+ *
73
+ * @param amount base units to cover
74
+ */
75
+ export declare function selectNotesForAmount<T extends SelectableNote>(notes: T[], amount: bigint | string | number, options?: {
76
+ mint?: string | null;
77
+ }): NoteSelectionResult<T>;
@@ -0,0 +1,188 @@
1
+ import { PublicKey } from "@solana/web3.js";
2
+ import { toBaseUnits } from "./amount.js";
3
+ /**
4
+ * Choosing which notes to spend.
5
+ *
6
+ * Two constraints drive everything here:
7
+ *
8
+ * 1. The transaction circuit is 2-in-2-out, so a single transaction can spend
9
+ * at most TWO notes.
10
+ * 2. Notes can only be co-spent if they live in the SAME Merkle tree, and the
11
+ * tree is derived from the MINT — see `canonicalTreeId`.
12
+ */
13
+ /** Inputs the transaction circuit accepts in one proof. */
14
+ export const MAX_INPUT_NOTES = 2;
15
+ /**
16
+ * The tree a note belongs to, derived from its mint.
17
+ *
18
+ * Mirrors the relayer's `mintAddressToTreeId` byte for byte: the all-zero
19
+ * native-SOL mint maps to 0, anything else to its first four mint bytes as a
20
+ * big-endian uint32.
21
+ *
22
+ * DERIVE THIS, NEVER TRUST A STORED `treeId`. Change notes are written with the
23
+ * on-chain shard index (a small 0/1/2…) while deposits and synced notes carry
24
+ * the mint-derived id. For native SOL both are 0 so the difference hides; for
25
+ * SPL tokens the two land in different buckets, and co-spending across them
26
+ * fails at proof time as a commitment mismatch.
27
+ *
28
+ * An undecodable mint falls back to the SOL bucket rather than inventing a
29
+ * phantom tree, matching the server.
30
+ */
31
+ export function canonicalTreeId(mintAddress) {
32
+ if (!mintAddress || mintAddress.trim() === "")
33
+ return 0;
34
+ try {
35
+ const bytes = new PublicKey(mintAddress).toBytes();
36
+ if (bytes.every((byte) => byte === 0))
37
+ return 0;
38
+ return (((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) >>> 0);
39
+ }
40
+ catch {
41
+ return 0;
42
+ }
43
+ }
44
+ /**
45
+ * Pick notes to cover `amount`, preferring the fewest notes and least change.
46
+ *
47
+ * Considers each tree separately, since notes cannot be co-spent across trees,
48
+ * and returns the best single-tree selection:
49
+ *
50
+ * 1. one note that covers the amount (smallest such note, least change);
51
+ * 2. otherwise the best PAIR, found by a two-pointer scan over the
52
+ * amount-sorted notes — O(n) rather than an O(n²) all-pairs search;
53
+ * 3. otherwise the largest notes greedily, flagged `requiresMerge` because
54
+ * more than two inputs cannot go into one proof.
55
+ *
56
+ * @param amount base units to cover
57
+ */
58
+ export function selectNotesForAmount(notes, amount, options = {}) {
59
+ const target = toBaseUnits(amount, "amount");
60
+ if (target <= 0n) {
61
+ throw new Error(`amount must be positive, got ${target}`);
62
+ }
63
+ const wanted = options.mint === undefined ? undefined : canonicalTreeId(options.mint);
64
+ const byTree = new Map();
65
+ notes.forEach((note, index) => {
66
+ const treeId = canonicalTreeId(note.mint);
67
+ if (wanted !== undefined && treeId !== wanted)
68
+ return;
69
+ const entry = {
70
+ note,
71
+ amount: toBaseUnits(note.amount, `notes[${index}].amount`),
72
+ };
73
+ if (entry.amount <= 0n)
74
+ return;
75
+ const bucket = byTree.get(treeId);
76
+ if (bucket)
77
+ bucket.push(entry);
78
+ else
79
+ byTree.set(treeId, [entry]);
80
+ });
81
+ if (byTree.size === 0) {
82
+ return {
83
+ ok: false,
84
+ reason: "NO_NOTES",
85
+ available: 0n,
86
+ message: "No spendable notes for the requested mint.",
87
+ };
88
+ }
89
+ let best;
90
+ let available = 0n;
91
+ for (const [treeId, bucket] of byTree) {
92
+ const treeTotal = bucket.reduce((sum, entry) => sum + entry.amount, 0n);
93
+ if (treeTotal > available)
94
+ available = treeTotal;
95
+ const selection = selectWithinTree(bucket, target, treeId);
96
+ if (!selection)
97
+ continue;
98
+ if (!best || isBetter(selection, best))
99
+ best = selection;
100
+ }
101
+ if (!best) {
102
+ return {
103
+ ok: false,
104
+ reason: "INSUFFICIENT_FUNDS",
105
+ available,
106
+ message: `No single tree holds ${target} base units. Largest tree total is ` +
107
+ `${available}. Notes in different trees cannot be co-spent.`,
108
+ };
109
+ }
110
+ return best;
111
+ }
112
+ /** Fewer inputs first, then least change. */
113
+ function isBetter(a, b) {
114
+ if (a.notes.length !== b.notes.length)
115
+ return a.notes.length < b.notes.length;
116
+ return a.change < b.change;
117
+ }
118
+ function selectWithinTree(bucket, target, treeId) {
119
+ // Descending by amount, compared as bigint: Number() would lose precision
120
+ // above 2^53 base units.
121
+ const sorted = [...bucket].sort((a, b) => b.amount > a.amount ? 1 : b.amount < a.amount ? -1 : 0);
122
+ // 1. Smallest single note that covers the target — walk up from the end.
123
+ let single;
124
+ for (let i = sorted.length - 1; i >= 0; i--) {
125
+ if (sorted[i].amount >= target) {
126
+ single = sorted[i];
127
+ break;
128
+ }
129
+ }
130
+ if (single) {
131
+ return {
132
+ ok: true,
133
+ notes: [single.note],
134
+ treeId,
135
+ total: single.amount,
136
+ change: single.amount - target,
137
+ requiresMerge: false,
138
+ };
139
+ }
140
+ // 2. Best pair by two-pointer scan over the descending list.
141
+ let bestPair;
142
+ let bestChange = 0n;
143
+ let lo = 0;
144
+ let hi = sorted.length - 1;
145
+ while (lo < hi) {
146
+ const combined = sorted[lo].amount + sorted[hi].amount;
147
+ if (combined >= target) {
148
+ const change = combined - target;
149
+ if (!bestPair || change < bestChange) {
150
+ bestChange = change;
151
+ bestPair = [sorted[lo], sorted[hi]];
152
+ }
153
+ lo++;
154
+ }
155
+ else {
156
+ hi--;
157
+ }
158
+ }
159
+ if (bestPair) {
160
+ return {
161
+ ok: true,
162
+ notes: [bestPair[0].note, bestPair[1].note],
163
+ treeId,
164
+ total: bestPair[0].amount + bestPair[1].amount,
165
+ change: bestChange,
166
+ requiresMerge: false,
167
+ };
168
+ }
169
+ // 3. Greedy over the largest notes. More than two inputs, so it needs a merge.
170
+ const chosen = [];
171
+ let total = 0n;
172
+ for (const entry of sorted) {
173
+ chosen.push(entry);
174
+ total += entry.amount;
175
+ if (total >= target)
176
+ break;
177
+ }
178
+ if (total < target)
179
+ return undefined;
180
+ return {
181
+ ok: true,
182
+ notes: chosen.map((entry) => entry.note),
183
+ treeId,
184
+ total,
185
+ change: total - target,
186
+ requiresMerge: chosen.length > MAX_INPUT_NOTES,
187
+ };
188
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Spend status and private balance.
3
+ *
4
+ * A note is yours until its nullifier is published; nothing in the note itself
5
+ * says whether it has been spent. So a balance is always two steps: ask which
6
+ * nullifiers are spent, then sum what is left. This module is that pair.
7
+ */
8
+ /** Server-side cap per check-batch request (notes.constants MAX_NULLIFIERS_PER_CHECK). */
9
+ export declare const MAX_NULLIFIERS_PER_CHECK = 200;
10
+ /** Grouping key used for notes that carry no mint. */
11
+ export declare const UNKNOWN_MINT = "unknown";
12
+ /**
13
+ * Ask the relayer which of these nullifiers are spent.
14
+ *
15
+ * Deduplicates, lower-cases, and splits into MAX_NULLIFIERS_PER_CHECK batches
16
+ * that are issued concurrently. Returns a Set for membership testing; a
17
+ * nullifier absent from it is unspent as far as the relayer knows.
18
+ *
19
+ * @throws if any entry is not 64-char hex — a malformed nullifier that silently
20
+ * read as "unspent" would overstate a balance.
21
+ */
22
+ export declare function checkNullifiersSpent(nullifiers: string[]): Promise<Set<string>>;
23
+ /** The minimum a note must carry to be counted. */
24
+ export interface SpendableNote {
25
+ /** Base units. bigint preferred; strings and safe integers are accepted. */
26
+ amount: bigint | string | number;
27
+ /** 64-character hex nullifier for this note. */
28
+ nullifier: string;
29
+ /** Mint this note is denominated in. Groups the result; optional. */
30
+ mint?: string;
31
+ }
32
+ export interface PrivateBalance<T extends SpendableNote = SpendableNote> {
33
+ /** Sum of every unspent note, across all mints. */
34
+ total: bigint;
35
+ /** Unspent totals keyed by mint (UNKNOWN_MINT when a note carries none). */
36
+ byMint: Record<string, bigint>;
37
+ /** The caller's own note objects, partitioned. */
38
+ unspent: T[];
39
+ spent: T[];
40
+ }
41
+ export interface PrivateBalanceOptions {
42
+ /**
43
+ * Supply spend status yourself instead of asking the relayer — e.g. from a
44
+ * chain scan of nullifier events, or a local cache. Receives normalized
45
+ * lower-case hex.
46
+ */
47
+ resolveSpent?: (nullifiers: string[]) => Promise<Set<string>> | Set<string>;
48
+ }
49
+ /**
50
+ * Sum unspent notes, per mint and in total.
51
+ *
52
+ * ```ts
53
+ * const { total, byMint, unspent } = await getPrivateBalance(myNotes);
54
+ * ```
55
+ *
56
+ * Amounts are base units and stay bigint throughout — never sum note amounts as
57
+ * numbers. Notes are matched to spend status by nullifier, so every note needs
58
+ * one; the partitioned arrays hand back your own objects, not copies.
59
+ */
60
+ export declare function getPrivateBalance<T extends SpendableNote>(notes: T[], options?: PrivateBalanceOptions): Promise<PrivateBalance<T>>;
@@ -0,0 +1,96 @@
1
+ import { checkNullifiers } from "../relayer/api.js";
2
+ import { toBaseUnits } from "./amount.js";
3
+ /**
4
+ * Spend status and private balance.
5
+ *
6
+ * A note is yours until its nullifier is published; nothing in the note itself
7
+ * says whether it has been spent. So a balance is always two steps: ask which
8
+ * nullifiers are spent, then sum what is left. This module is that pair.
9
+ */
10
+ /** Server-side cap per check-batch request (notes.constants MAX_NULLIFIERS_PER_CHECK). */
11
+ export const MAX_NULLIFIERS_PER_CHECK = 200;
12
+ /** Grouping key used for notes that carry no mint. */
13
+ export const UNKNOWN_MINT = "unknown";
14
+ const HEX64 = /^[0-9a-f]{64}$/;
15
+ /**
16
+ * Normalize a nullifier to the form the relayer answers in.
17
+ *
18
+ * The endpoint's validator is case-INSENSITIVE, but it answers with
19
+ * `Buffer.toString("hex")` — always lowercase. Sending upper-case hex therefore
20
+ * returns a `spent` list that never matches what you sent, and every note reads
21
+ * as unspent. Normalizing here is what makes membership testing sound.
22
+ */
23
+ function normalizeNullifier(nullifier, index) {
24
+ const normalized = nullifier.trim().toLowerCase();
25
+ if (!HEX64.test(normalized)) {
26
+ throw new Error(`nullifiers[${index}] must be a 64-character hex string, got ` +
27
+ `${JSON.stringify(nullifier)}`);
28
+ }
29
+ return normalized;
30
+ }
31
+ function chunk(items, size) {
32
+ const out = [];
33
+ for (let i = 0; i < items.length; i += size)
34
+ out.push(items.slice(i, i + size));
35
+ return out;
36
+ }
37
+ /**
38
+ * Ask the relayer which of these nullifiers are spent.
39
+ *
40
+ * Deduplicates, lower-cases, and splits into MAX_NULLIFIERS_PER_CHECK batches
41
+ * that are issued concurrently. Returns a Set for membership testing; a
42
+ * nullifier absent from it is unspent as far as the relayer knows.
43
+ *
44
+ * @throws if any entry is not 64-char hex — a malformed nullifier that silently
45
+ * read as "unspent" would overstate a balance.
46
+ */
47
+ export async function checkNullifiersSpent(nullifiers) {
48
+ const unique = [...new Set(nullifiers.map(normalizeNullifier))];
49
+ if (unique.length === 0)
50
+ return new Set();
51
+ const batches = await Promise.all(chunk(unique, MAX_NULLIFIERS_PER_CHECK).map((batch) => checkNullifiers(batch)));
52
+ const spent = new Set();
53
+ for (const response of batches) {
54
+ for (const nullifier of response.spent ?? []) {
55
+ spent.add(nullifier.toLowerCase());
56
+ }
57
+ }
58
+ return spent;
59
+ }
60
+ /**
61
+ * Sum unspent notes, per mint and in total.
62
+ *
63
+ * ```ts
64
+ * const { total, byMint, unspent } = await getPrivateBalance(myNotes);
65
+ * ```
66
+ *
67
+ * Amounts are base units and stay bigint throughout — never sum note amounts as
68
+ * numbers. Notes are matched to spend status by nullifier, so every note needs
69
+ * one; the partitioned arrays hand back your own objects, not copies.
70
+ */
71
+ export async function getPrivateBalance(notes, options = {}) {
72
+ const normalized = notes.map((note, index) => ({
73
+ note,
74
+ amount: toBaseUnits(note.amount, `notes[${index}].amount`),
75
+ nullifier: normalizeNullifier(note.nullifier, index),
76
+ }));
77
+ const resolve = options.resolveSpent ?? checkNullifiersSpent;
78
+ const spentSet = await resolve(normalized.map((entry) => entry.nullifier));
79
+ const balance = {
80
+ total: 0n,
81
+ byMint: {},
82
+ unspent: [],
83
+ spent: [],
84
+ };
85
+ for (const entry of normalized) {
86
+ if (spentSet.has(entry.nullifier)) {
87
+ balance.spent.push(entry.note);
88
+ continue;
89
+ }
90
+ const mint = entry.note.mint ?? UNKNOWN_MINT;
91
+ balance.unspent.push(entry.note);
92
+ balance.total += entry.amount;
93
+ balance.byMint[mint] = (balance.byMint[mint] ?? 0n) + entry.amount;
94
+ }
95
+ return balance;
96
+ }
@@ -0,0 +1,16 @@
1
+ import type { JperpMarket, JperpMarketPayload, JperpSide } from "./types.js";
2
+ export declare const JUPITER_PERPS_PROGRAM_ID = "PERPHjGBqRHArX4DySjwM6UJHiR3sWAatqfdBS2qQJu";
3
+ export declare const JUPITER_PERPS_EVENT_AUTHORITY = "37hJBDnntwqhGbK7L6M1bLyvccj4u55CCUiLPdYkiqBN";
4
+ export declare const JUPITER_PERPS_POOL = "5BUwFW4nRbftYTDMbgxykoFWqWHPzahFSNAaaaJtVKsq";
5
+ export declare const JUPITER_JLP_MINT = "27G8MtK7VtTcCHkpASjSDdkWWYfoqT6ggEuKidVJidD4";
6
+ export declare const JPERP_USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
7
+ export declare const JPERP_NATIVE_SOL_MINT = "11111111111111111111111111111111";
8
+ export declare const JPERP_WRAPPED_SOL_MINT = "So11111111111111111111111111111111111111112";
9
+ export declare const JUPITER_PERPS_CUSTODIES: Record<JperpMarket | "USDC" | "USDT", string>;
10
+ export declare const JUPITER_PERPS_DOVES_ORACLES: Record<JperpMarket, string>;
11
+ export declare const JPERP_LONG_POOL_MINTS: Record<JperpMarket, string>;
12
+ export declare const JPERP_LONG_JUPITER_MINTS: Record<JperpMarket, string>;
13
+ export declare const JPERP_LONG_DECIMALS: Record<JperpMarket, number>;
14
+ export declare const JPERP_USD_DECIMALS = 6;
15
+ /** Resolve the exact market payload duplicated by the wallet-app reference. */
16
+ export declare function getJperpMarketPayload(market: JperpMarket, side: JperpSide): JperpMarketPayload;
@@ -0,0 +1,48 @@
1
+ export const JUPITER_PERPS_PROGRAM_ID = "PERPHjGBqRHArX4DySjwM6UJHiR3sWAatqfdBS2qQJu";
2
+ export const JUPITER_PERPS_EVENT_AUTHORITY = "37hJBDnntwqhGbK7L6M1bLyvccj4u55CCUiLPdYkiqBN";
3
+ export const JUPITER_PERPS_POOL = "5BUwFW4nRbftYTDMbgxykoFWqWHPzahFSNAaaaJtVKsq";
4
+ export const JUPITER_JLP_MINT = "27G8MtK7VtTcCHkpASjSDdkWWYfoqT6ggEuKidVJidD4";
5
+ export const JPERP_USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
6
+ export const JPERP_NATIVE_SOL_MINT = "11111111111111111111111111111111";
7
+ export const JPERP_WRAPPED_SOL_MINT = "So11111111111111111111111111111111111111112";
8
+ export const JUPITER_PERPS_CUSTODIES = {
9
+ SOL: "7xS2gz2bTp3fwCC7knJvUWTEU9Tycczu6VhJYKgi1wdz",
10
+ ETH: "AQCGyheWPLeo6Qp9WpYS9m3Qj479t7R636N9ey1rEjEn",
11
+ BTC: "5Pv3gM9JrFFH883SWAhvJC9RPYmo8UNxuFtv5bMMALkm",
12
+ USDC: "G18jKKXQwBbrHeiK3C9MRXhkHsLHf7XgCSisykV46EZa",
13
+ USDT: "4vkNeXiYEUizLdrpdPS1eC2mccyM4NUPRtERrk6ZETkk",
14
+ };
15
+ export const JUPITER_PERPS_DOVES_ORACLES = {
16
+ SOL: "FYq2BWQ1V5P1WFBqr3qB2Kb5yHVvSv7upzKodgQE5zXh",
17
+ ETH: "AFZnHPzy4mvVCffrVwhewHbFc93uTHvDSFrVH7GtfXF1",
18
+ BTC: "hUqAT1KQ7eW1i6Csp9CXYtpPfSAvi835V7wKi5fRfmC",
19
+ };
20
+ export const JPERP_LONG_POOL_MINTS = {
21
+ SOL: JPERP_NATIVE_SOL_MINT,
22
+ ETH: "7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs",
23
+ BTC: "3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh",
24
+ };
25
+ export const JPERP_LONG_JUPITER_MINTS = {
26
+ SOL: JPERP_WRAPPED_SOL_MINT,
27
+ ETH: JPERP_LONG_POOL_MINTS.ETH,
28
+ BTC: JPERP_LONG_POOL_MINTS.BTC,
29
+ };
30
+ export const JPERP_LONG_DECIMALS = {
31
+ SOL: 9,
32
+ ETH: 8,
33
+ BTC: 8,
34
+ };
35
+ export const JPERP_USD_DECIMALS = 6;
36
+ /** Resolve the exact market payload duplicated by the wallet-app reference. */
37
+ export function getJperpMarketPayload(market, side) {
38
+ const isLong = side === "long";
39
+ return {
40
+ custody: JUPITER_PERPS_CUSTODIES[market],
41
+ collateralCustody: JUPITER_PERPS_CUSTODIES[isLong ? market : "USDC"],
42
+ inputMint: isLong ? JPERP_LONG_POOL_MINTS[market] : JPERP_USDC_MINT,
43
+ jupiterInputMint: isLong
44
+ ? JPERP_LONG_JUPITER_MINTS[market]
45
+ : JPERP_USDC_MINT,
46
+ dovesOracle: JUPITER_PERPS_DOVES_ORACLES[market],
47
+ };
48
+ }