@veilo/sdk-core 0.1.17 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1296 -272
- package/SHIELD_INTEGRATION.md +143 -0
- package/config.d.ts +2 -0
- package/config.js +4 -0
- package/dist/cjs/client.d.ts +407 -0
- package/dist/cjs/client.js +951 -0
- package/dist/cjs/compactNote.d.ts +107 -0
- package/dist/cjs/compactNote.js +167 -0
- package/dist/cjs/config.d.ts +82 -0
- package/dist/cjs/config.js +57 -0
- package/dist/cjs/events.d.ts +77 -0
- package/dist/cjs/events.js +167 -0
- package/dist/cjs/idl/privacy_pool.d.ts +5 -0
- package/dist/cjs/idl/privacy_pool.js +15218 -0
- package/dist/cjs/idl/privacy_pool.json +10313 -0
- package/dist/cjs/index.d.ts +16 -0
- package/dist/cjs/index.js +67 -0
- package/dist/cjs/merkle.d.ts +77 -0
- package/dist/cjs/merkle.js +156 -0
- package/dist/cjs/poseidon.d.ts +29 -0
- package/dist/cjs/poseidon.js +100 -0
- package/dist/cjs/program.d.ts +37 -0
- package/dist/cjs/program.js +61 -0
- package/dist/cjs/proof.d.ts +183 -0
- package/dist/cjs/proof.js +292 -0
- package/dist/cjs/prover.d.ts +54 -0
- package/dist/cjs/prover.js +112 -0
- package/dist/cjs/random.d.ts +16 -0
- package/dist/cjs/random.js +28 -0
- package/dist/cjs/relayer.d.ts +318 -0
- package/dist/cjs/relayer.js +257 -0
- package/dist/cjs/retry.d.ts +32 -0
- package/dist/cjs/retry.js +75 -0
- package/dist/cjs/shield/alt.d.ts +87 -0
- package/dist/cjs/shield/alt.js +194 -0
- package/dist/cjs/shield/computeBudget.d.ts +61 -0
- package/dist/cjs/shield/computeBudget.js +64 -0
- package/dist/cjs/shield/errors.d.ts +58 -0
- package/dist/cjs/shield/errors.js +121 -0
- package/dist/cjs/shield/finalize.d.ts +45 -0
- package/dist/cjs/shield/finalize.js +119 -0
- package/dist/cjs/shield/index.d.ts +35 -0
- package/dist/cjs/shield/index.js +68 -0
- package/dist/cjs/shield/ix.d.ts +54 -0
- package/dist/cjs/shield/ix.js +119 -0
- package/dist/cjs/shield/owner.d.ts +36 -0
- package/dist/cjs/shield/owner.js +126 -0
- package/dist/cjs/shield/ports.d.ts +43 -0
- package/dist/cjs/shield/ports.js +153 -0
- package/dist/cjs/shield/preflight.d.ts +30 -0
- package/dist/cjs/shield/preflight.js +154 -0
- package/dist/cjs/shield/shield.d.ts +68 -0
- package/dist/cjs/shield/shield.js +499 -0
- package/dist/cjs/shield/types.d.ts +202 -0
- package/dist/cjs/shield/types.js +2 -0
- package/dist/cjs/utxo.d.ts +235 -0
- package/dist/cjs/utxo.js +407 -0
- package/dist/esm/client.d.ts +407 -0
- package/dist/esm/client.js +891 -0
- package/dist/esm/compactNote.d.ts +107 -0
- package/dist/esm/compactNote.js +156 -0
- package/dist/esm/config.d.ts +82 -0
- package/dist/esm/config.js +51 -0
- package/dist/esm/events.d.ts +77 -0
- package/dist/esm/events.js +129 -0
- package/dist/esm/idl/privacy_pool.d.ts +5 -0
- package/dist/esm/idl/privacy_pool.js +15216 -0
- package/dist/esm/idl/privacy_pool.json +10313 -0
- package/dist/esm/index.d.ts +16 -0
- package/dist/esm/index.js +29 -0
- package/dist/esm/merkle.d.ts +77 -0
- package/dist/esm/merkle.js +151 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/poseidon.d.ts +29 -0
- package/dist/esm/poseidon.js +87 -0
- package/dist/esm/program.d.ts +37 -0
- package/dist/esm/program.js +53 -0
- package/dist/esm/proof.d.ts +183 -0
- package/dist/esm/proof.js +281 -0
- package/dist/esm/prover.d.ts +54 -0
- package/dist/esm/prover.js +75 -0
- package/dist/esm/random.d.ts +16 -0
- package/dist/esm/random.js +21 -0
- package/dist/esm/relayer.d.ts +318 -0
- package/dist/esm/relayer.js +249 -0
- package/dist/esm/retry.d.ts +32 -0
- package/dist/esm/retry.js +71 -0
- package/dist/esm/shield/alt.d.ts +87 -0
- package/dist/esm/shield/alt.js +186 -0
- package/dist/esm/shield/computeBudget.d.ts +61 -0
- package/dist/esm/shield/computeBudget.js +61 -0
- package/dist/esm/shield/errors.d.ts +58 -0
- package/dist/esm/shield/errors.js +115 -0
- package/dist/esm/shield/finalize.d.ts +45 -0
- package/dist/esm/shield/finalize.js +83 -0
- package/dist/esm/shield/index.d.ts +35 -0
- package/dist/esm/shield/index.js +32 -0
- package/dist/esm/shield/ix.d.ts +54 -0
- package/dist/esm/shield/ix.js +82 -0
- package/dist/esm/shield/owner.d.ts +36 -0
- package/dist/esm/shield/owner.js +122 -0
- package/dist/esm/shield/ports.d.ts +43 -0
- package/dist/esm/shield/ports.js +147 -0
- package/dist/esm/shield/preflight.d.ts +30 -0
- package/dist/esm/shield/preflight.js +151 -0
- package/dist/esm/shield/shield.d.ts +68 -0
- package/dist/esm/shield/shield.js +492 -0
- package/dist/esm/shield/types.d.ts +202 -0
- package/dist/esm/shield/types.js +1 -0
- package/dist/esm/utxo.d.ts +235 -0
- package/dist/esm/utxo.js +382 -0
- package/dist/src/client.d.ts +407 -0
- package/dist/src/client.js +951 -0
- package/dist/src/compactNote.d.ts +107 -0
- package/dist/src/compactNote.js +167 -0
- package/dist/src/config.d.ts +82 -0
- package/dist/src/config.js +57 -0
- package/dist/src/events.d.ts +77 -0
- package/dist/src/events.js +167 -0
- package/dist/src/idl/privacy_pool.d.ts +5 -0
- package/dist/src/idl/privacy_pool.js +15218 -0
- package/dist/src/index.d.ts +16 -0
- package/dist/src/index.js +67 -0
- package/dist/src/merkle.d.ts +77 -0
- package/dist/src/merkle.js +156 -0
- package/dist/src/poseidon.d.ts +29 -0
- package/dist/src/poseidon.js +100 -0
- package/dist/src/program.d.ts +37 -0
- package/dist/src/program.js +61 -0
- package/dist/src/proof.d.ts +183 -0
- package/dist/src/proof.js +292 -0
- package/dist/src/prover.d.ts +54 -0
- package/dist/src/prover.js +112 -0
- package/dist/src/random.d.ts +16 -0
- package/dist/src/random.js +28 -0
- package/dist/src/relayer.d.ts +318 -0
- package/dist/src/relayer.js +257 -0
- package/dist/src/retry.d.ts +32 -0
- package/dist/src/retry.js +75 -0
- package/dist/src/shield/alt.d.ts +87 -0
- package/dist/src/shield/alt.js +194 -0
- package/dist/src/shield/computeBudget.d.ts +61 -0
- package/dist/src/shield/computeBudget.js +64 -0
- package/dist/src/shield/errors.d.ts +58 -0
- package/dist/src/shield/errors.js +121 -0
- package/dist/src/shield/finalize.d.ts +45 -0
- package/dist/src/shield/finalize.js +119 -0
- package/dist/src/shield/index.d.ts +35 -0
- package/dist/src/shield/index.js +68 -0
- package/dist/src/shield/ix.d.ts +54 -0
- package/dist/src/shield/ix.js +119 -0
- package/dist/src/shield/owner.d.ts +36 -0
- package/dist/src/shield/owner.js +126 -0
- package/dist/src/shield/ports.d.ts +43 -0
- package/dist/src/shield/ports.js +153 -0
- package/dist/src/shield/preflight.d.ts +30 -0
- package/dist/src/shield/preflight.js +154 -0
- package/dist/src/shield/shield.d.ts +68 -0
- package/dist/src/shield/shield.js +499 -0
- package/dist/src/shield/types.d.ts +202 -0
- package/dist/src/shield/types.js +2 -0
- package/dist/src/utxo.d.ts +235 -0
- package/dist/src/utxo.js +407 -0
- package/dist/tests/compact-note.test.d.ts +1 -0
- package/dist/tests/compact-note.test.js +173 -0
- package/dist/tests/config.test.d.ts +1 -0
- package/dist/tests/config.test.js +102 -0
- package/dist/tests/edge-cases.test.d.ts +1 -0
- package/dist/tests/edge-cases.test.js +220 -0
- package/dist/tests/encryption.test.d.ts +1 -0
- package/dist/tests/encryption.test.js +215 -0
- package/dist/tests/events.test.d.ts +1 -0
- package/dist/tests/events.test.js +78 -0
- package/dist/tests/multi-tree.test.d.ts +1 -0
- package/dist/tests/multi-tree.test.js +405 -0
- package/dist/tests/pda.test.d.ts +1 -0
- package/dist/tests/pda.test.js +229 -0
- package/dist/tests/poseidon-builder-parity.test.d.ts +1 -0
- package/dist/tests/poseidon-builder-parity.test.js +72 -0
- package/dist/tests/poseidon.test.d.ts +1 -0
- package/dist/tests/poseidon.test.js +142 -0
- package/dist/tests/proof.test.d.ts +1 -0
- package/dist/tests/proof.test.js +296 -0
- package/dist/tests/relayer.test.d.ts +1 -0
- package/dist/tests/relayer.test.js +271 -0
- package/dist/tests/sdk.integration.test.d.ts +1 -0
- package/dist/tests/sdk.integration.test.js +330 -0
- package/dist/tests/shield-owner.test.d.ts +1 -0
- package/dist/tests/shield-owner.test.js +89 -0
- package/dist/tests/shield-preflight.test.d.ts +1 -0
- package/dist/tests/shield-preflight.test.js +87 -0
- package/dist/tests/shield-realproof.test.d.ts +1 -0
- package/dist/tests/shield-realproof.test.js +272 -0
- package/dist/tests/shield.test.d.ts +1 -0
- package/dist/tests/shield.test.js +403 -0
- package/dist/tests/utxo.test.d.ts +1 -0
- package/dist/tests/utxo.test.js +140 -0
- package/package.json +105 -11
- package/poseidon.d.ts +2 -0
- package/poseidon.js +4 -0
- package/proof.d.ts +2 -0
- package/proof.js +4 -0
- package/prover.d.ts +2 -0
- package/prover.js +4 -0
- package/shield.d.ts +2 -0
- package/shield.js +4 -0
- package/src/client.ts +0 -352
- package/src/config.ts +0 -13
- package/src/index.ts +0 -6
- package/src/merkle.ts +0 -178
- package/src/note.ts +0 -193
- package/src/poseidon.ts +0 -62
- package/src/proof.ts +0 -170
- package/test/script.js +0 -0
- package/test-tsconfig.json +0 -19
- package/tests/note.test.ts +0 -50
- package/tests/sdk.integration.test.ts +0 -210
- package/tsconfig.json +0 -18
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import * as anchor from "@coral-xyz/anchor";
|
|
2
|
+
import { PRIVACY_POOL_IDL, PRIVACY_POOL_PROGRAM_ID } from "../program.js";
|
|
3
|
+
import { encryptBlindMailboxNote } from "../utxo.js";
|
|
4
|
+
import { bigIntToBytesBE } from "../poseidon.js";
|
|
5
|
+
import { ShieldError } from "./errors.js";
|
|
6
|
+
/**
|
|
7
|
+
* Read the authoritative leaf index for a landed shield, and produce the
|
|
8
|
+
* mailbox blob for optional relayer delivery.
|
|
9
|
+
*
|
|
10
|
+
* ## Why this is a separate step
|
|
11
|
+
*
|
|
12
|
+
* Every existing deposit implementation records `tree.nextIndex` read *before*
|
|
13
|
+
* submission as the note's leaf index. Under concurrent deposits into the same
|
|
14
|
+
* tree that value is wrong, and it is wrong permanently — the stored index is
|
|
15
|
+
* what a later withdrawal builds its Merkle path from, so the note becomes
|
|
16
|
+
* unspendable through the normal path.
|
|
17
|
+
*
|
|
18
|
+
* That race is rare for a single wallet and constant for an SDK: a platform
|
|
19
|
+
* batching shields for many users will hit it routinely. So `shield()` reports
|
|
20
|
+
* only a `predictedLeafIndex`, and the real one is read here from the
|
|
21
|
+
* transaction's own `CommitmentEvent` after it confirms.
|
|
22
|
+
*
|
|
23
|
+
* ## What is optional
|
|
24
|
+
*
|
|
25
|
+
* Everything, strictly. The note is recoverable from chain data alone via the
|
|
26
|
+
* on-chain compact cipher, so a caller that skips finalization has not lost the
|
|
27
|
+
* funds — only the fast path to finding them. Persist nothing that depends on a
|
|
28
|
+
* leaf index without calling this first.
|
|
29
|
+
*/
|
|
30
|
+
export async function finalizeShield(params) {
|
|
31
|
+
const { connection, signature, note, owner, programId = PRIVACY_POOL_PROGRAM_ID, commitment = "confirmed", } = params;
|
|
32
|
+
const tx = await connection.getTransaction(signature, {
|
|
33
|
+
commitment: commitment === "finalized" ? "finalized" : "confirmed",
|
|
34
|
+
maxSupportedTransactionVersion: 0,
|
|
35
|
+
});
|
|
36
|
+
if (!tx) {
|
|
37
|
+
throw new ShieldError("UNKNOWN", `Transaction ${signature} not found at ${commitment} commitment. ` +
|
|
38
|
+
`If it was just submitted, wait for confirmation and retry.`, { context: { signature } });
|
|
39
|
+
}
|
|
40
|
+
if (tx.meta?.err) {
|
|
41
|
+
throw new ShieldError("UNKNOWN", `Transaction ${signature} failed on-chain; there is no note to finalize.`, { context: { signature, err: tx.meta.err } });
|
|
42
|
+
}
|
|
43
|
+
const parser = new anchor.EventParser(programId, new anchor.BorshCoder(PRIVACY_POOL_IDL));
|
|
44
|
+
const wantCommitment = Buffer.from(note.commitment).toString("hex");
|
|
45
|
+
let match = null;
|
|
46
|
+
for (const event of parser.parseLogs(tx.meta?.logMessages ?? [])) {
|
|
47
|
+
if (event.name !== "CommitmentEvent" && event.name !== "commitmentEvent")
|
|
48
|
+
continue;
|
|
49
|
+
const data = event.data;
|
|
50
|
+
const emitted = Buffer.from(data.commitment).toString("hex");
|
|
51
|
+
if (emitted === wantCommitment) {
|
|
52
|
+
match = data;
|
|
53
|
+
break;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (!match) {
|
|
57
|
+
throw new ShieldError("UNKNOWN", `Transaction ${signature} landed but emitted no CommitmentEvent for this note's ` +
|
|
58
|
+
`commitment. The note may belong to a different transaction.`, { context: { signature, commitment: wantCommitment } });
|
|
59
|
+
}
|
|
60
|
+
const leafIndex = Number(match.leafIndex ?? match.leaf_index);
|
|
61
|
+
const treeId = Number(match.treeId ?? match.tree_id ?? note.treeId);
|
|
62
|
+
const newRoot = new Uint8Array(match.newRoot ?? match.new_root);
|
|
63
|
+
// Mailbox copy. Sending this to the relayer with a `recipientWalletPublicKey`
|
|
64
|
+
// buys instant delivery and a push notification, at the cost of writing the
|
|
65
|
+
// sender→recipient association into the relayer's database AND removing the
|
|
66
|
+
// note from the chain-recovery feed. For shield-to-someone-else, chain-only
|
|
67
|
+
// discovery is usually the better default — see the plan's Phase 3 note.
|
|
68
|
+
const blob = encryptBlindMailboxNote(owner.noteViewingKey.toBytes(), {
|
|
69
|
+
blinding: bigIntToBytesBE(note.blinding),
|
|
70
|
+
leafIndex,
|
|
71
|
+
commitment: note.commitment,
|
|
72
|
+
amount: note.amount,
|
|
73
|
+
mintAddress: note.mint.toBase58(),
|
|
74
|
+
treeId,
|
|
75
|
+
});
|
|
76
|
+
return {
|
|
77
|
+
leafIndex,
|
|
78
|
+
newRoot,
|
|
79
|
+
treeId,
|
|
80
|
+
slot: tx.slot,
|
|
81
|
+
blob,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wallet-agnostic shielding.
|
|
3
|
+
*
|
|
4
|
+
* `shield()` builds an unsigned transaction that deposits public funds into the
|
|
5
|
+
* privacy pool, creating a note owned by an arbitrary recipient. Any external
|
|
6
|
+
* wallet — a browser extension, or a third-party platform's managed wallet —
|
|
7
|
+
* signs and submits it. The SDK never touches a secret key.
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* const owner = await resolveShieldOwner({ username: "alice" });
|
|
11
|
+
* const { transaction, note, proofCache } = await shield({
|
|
12
|
+
* connection, amount, mint, owner,
|
|
13
|
+
* signer: { publicKey: wallet.publicKey },
|
|
14
|
+
* prover: createTransactionProver(artifacts),
|
|
15
|
+
* });
|
|
16
|
+
*
|
|
17
|
+
* const signed = await wallet.signTransaction(transaction);
|
|
18
|
+
* const sig = await connection.sendRawTransaction(signed.serialize());
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* On blockhash expiry, `rebuild(result, { connection })` re-assembles with a
|
|
22
|
+
* fresh blockhash and deadline without re-proving.
|
|
23
|
+
*/
|
|
24
|
+
export { shield, rebuild, serializeProofCache, deserializeProofCache } from "./shield.js";
|
|
25
|
+
export { resolveShieldOwner, unsafeShieldOwner } from "./owner.js";
|
|
26
|
+
export { finalizeShield } from "./finalize.js";
|
|
27
|
+
export { preflightShield } from "./preflight.js";
|
|
28
|
+
export { buildTransactInstruction, TRANSACT_ACCOUNT_NAMES } from "./ix.js";
|
|
29
|
+
export type { TransactAccounts, TransactArgs } from "./ix.js";
|
|
30
|
+
export { sharedDepositAlt, explicitAlt, auditDepositAlt, expectedDepositAltKeys, requiredAltKeys, SHARED_DEPOSIT_ALT, SHARED_ALT_MINTS, } from "./alt.js";
|
|
31
|
+
export { onChainTreeSource, staticTreeSource, memoryCache, noCache } from "./ports.js";
|
|
32
|
+
export { ShieldError, mapShieldError, extractProgramCode, } from "./errors.js";
|
|
33
|
+
export type { ShieldErrorCode, ShieldRetryClass, ShieldErrorRemedy } from "./errors.js";
|
|
34
|
+
export { SHIELD_COMPUTE_UNIT_LIMIT, SHIELD_COMPUTE_UNIT_PRICE_MICRO_LAMPORTS, SHIELD_COMPUTE_UNITS_MEASURED_TYPICAL, MAX_TRANSACTION_BYTES, SIGNATURE_BYTES, TRANSACT_INSTRUCTION_DATA_BYTES, NULLIFIER_MARKER_ACCOUNT_BYTES, NULLIFIER_MARKERS_PER_TRANSACT, DEFAULT_DEADLINE_SECONDS, } from "./computeBudget.js";
|
|
35
|
+
export type { ShieldOwner, ShieldSigner, ShieldParams, ShieldResult, ShieldNote, ShieldProofCache, ShieldQuote, TreeSource, AltSource, ShieldCachePort, DepositTarget, PreflightOptions, } from "./types.js";
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wallet-agnostic shielding.
|
|
3
|
+
*
|
|
4
|
+
* `shield()` builds an unsigned transaction that deposits public funds into the
|
|
5
|
+
* privacy pool, creating a note owned by an arbitrary recipient. Any external
|
|
6
|
+
* wallet — a browser extension, or a third-party platform's managed wallet —
|
|
7
|
+
* signs and submits it. The SDK never touches a secret key.
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* const owner = await resolveShieldOwner({ username: "alice" });
|
|
11
|
+
* const { transaction, note, proofCache } = await shield({
|
|
12
|
+
* connection, amount, mint, owner,
|
|
13
|
+
* signer: { publicKey: wallet.publicKey },
|
|
14
|
+
* prover: createTransactionProver(artifacts),
|
|
15
|
+
* });
|
|
16
|
+
*
|
|
17
|
+
* const signed = await wallet.signTransaction(transaction);
|
|
18
|
+
* const sig = await connection.sendRawTransaction(signed.serialize());
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* On blockhash expiry, `rebuild(result, { connection })` re-assembles with a
|
|
22
|
+
* fresh blockhash and deadline without re-proving.
|
|
23
|
+
*/
|
|
24
|
+
export { shield, rebuild, serializeProofCache, deserializeProofCache } from "./shield.js";
|
|
25
|
+
export { resolveShieldOwner, unsafeShieldOwner } from "./owner.js";
|
|
26
|
+
export { finalizeShield } from "./finalize.js";
|
|
27
|
+
export { preflightShield } from "./preflight.js";
|
|
28
|
+
export { buildTransactInstruction, TRANSACT_ACCOUNT_NAMES } from "./ix.js";
|
|
29
|
+
export { sharedDepositAlt, explicitAlt, auditDepositAlt, expectedDepositAltKeys, requiredAltKeys, SHARED_DEPOSIT_ALT, SHARED_ALT_MINTS, } from "./alt.js";
|
|
30
|
+
export { onChainTreeSource, staticTreeSource, memoryCache, noCache } from "./ports.js";
|
|
31
|
+
export { ShieldError, mapShieldError, extractProgramCode, } from "./errors.js";
|
|
32
|
+
export { SHIELD_COMPUTE_UNIT_LIMIT, SHIELD_COMPUTE_UNIT_PRICE_MICRO_LAMPORTS, SHIELD_COMPUTE_UNITS_MEASURED_TYPICAL, MAX_TRANSACTION_BYTES, SIGNATURE_BYTES, TRANSACT_INSTRUCTION_DATA_BYTES, NULLIFIER_MARKER_ACCOUNT_BYTES, NULLIFIER_MARKERS_PER_TRANSACT, DEFAULT_DEADLINE_SECONDS, } from "./computeBudget.js";
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { PublicKey, TransactionInstruction } from "@solana/web3.js";
|
|
2
|
+
import type { TransactionProofStruct } from "../proof.js";
|
|
3
|
+
/**
|
|
4
|
+
* `transact` instruction assembly, driven by the IDL rather than by a
|
|
5
|
+
* hand-written account list.
|
|
6
|
+
*
|
|
7
|
+
* Every existing deposit implementation spells out all sixteen accounts by hand
|
|
8
|
+
* in an `accountsStrict({...})` literal. That works until the IDL changes, at
|
|
9
|
+
* which point a silently misordered or missing account produces a runtime
|
|
10
|
+
* failure that is very hard to trace. Here the account list and the ordering
|
|
11
|
+
* come from the IDL itself, and an unresolved name throws at build time.
|
|
12
|
+
*
|
|
13
|
+
* Building the instruction directly also means no Anchor `Provider` and no
|
|
14
|
+
* `Wallet` — which is the whole point of a wallet-agnostic shield.
|
|
15
|
+
*/
|
|
16
|
+
/** Account names the IDL declares for `transact`, in order. */
|
|
17
|
+
export type TransactAccounts = Record<string, PublicKey>;
|
|
18
|
+
export type TransactArgs = {
|
|
19
|
+
root: Uint8Array;
|
|
20
|
+
inputTreeId: number;
|
|
21
|
+
outputTreeId: number;
|
|
22
|
+
publicAmount: bigint;
|
|
23
|
+
extDataHash: Uint8Array;
|
|
24
|
+
mintAddress: PublicKey;
|
|
25
|
+
inputNullifiers: [Uint8Array, Uint8Array];
|
|
26
|
+
outputCommitments: [Uint8Array, Uint8Array];
|
|
27
|
+
deadline: bigint;
|
|
28
|
+
extData: {
|
|
29
|
+
recipient: PublicKey;
|
|
30
|
+
relayer: PublicKey;
|
|
31
|
+
fee: bigint;
|
|
32
|
+
refund: bigint;
|
|
33
|
+
claimant: PublicKey;
|
|
34
|
+
};
|
|
35
|
+
proof: TransactionProofStruct;
|
|
36
|
+
noteCiphers: {
|
|
37
|
+
note0EphemeralKey: Uint8Array;
|
|
38
|
+
note0Encrypted: Uint8Array;
|
|
39
|
+
note0ViewTag: number;
|
|
40
|
+
note1EphemeralKey: Uint8Array;
|
|
41
|
+
note1Encrypted: Uint8Array;
|
|
42
|
+
note1ViewTag: number;
|
|
43
|
+
} | null;
|
|
44
|
+
};
|
|
45
|
+
/** Account names in IDL order. Exported so callers can see what must be resolved. */
|
|
46
|
+
export declare const TRANSACT_ACCOUNT_NAMES: string[];
|
|
47
|
+
/**
|
|
48
|
+
* Build the `transact` instruction.
|
|
49
|
+
*
|
|
50
|
+
* @throws ShieldError('UNRESOLVED_ACCOUNT') if the IDL declares an account the
|
|
51
|
+
* caller did not supply — a loud failure is the point, because the
|
|
52
|
+
* alternative is a misordered account list that fails opaquely on-chain.
|
|
53
|
+
*/
|
|
54
|
+
export declare function buildTransactInstruction(accounts: TransactAccounts, args: TransactArgs, programId?: PublicKey): TransactionInstruction;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import * as anchor from "@coral-xyz/anchor";
|
|
2
|
+
import { TransactionInstruction, } from "@solana/web3.js";
|
|
3
|
+
import { PRIVACY_POOL_IDL, PRIVACY_POOL_PROGRAM_ID } from "../program.js";
|
|
4
|
+
import { ShieldError } from "./errors.js";
|
|
5
|
+
import { TRANSACT_INSTRUCTION_DATA_BYTES } from "./computeBudget.js";
|
|
6
|
+
// Anchor is CommonJS and does not expose BN as a detectable named export to
|
|
7
|
+
// Node ESM. Pull both runtime values from the namespace so CJS and ESM agree.
|
|
8
|
+
const { BN, BorshInstructionCoder } = anchor;
|
|
9
|
+
const IDL_TRANSACT = PRIVACY_POOL_IDL.instructions.find((i) => i.name === "transact");
|
|
10
|
+
if (!IDL_TRANSACT) {
|
|
11
|
+
throw new Error("privacy_pool IDL has no `transact` instruction");
|
|
12
|
+
}
|
|
13
|
+
/** Account names in IDL order. Exported so callers can see what must be resolved. */
|
|
14
|
+
export const TRANSACT_ACCOUNT_NAMES = IDL_TRANSACT.accounts.map((a) => a.name);
|
|
15
|
+
/**
|
|
16
|
+
* Build the `transact` instruction.
|
|
17
|
+
*
|
|
18
|
+
* @throws ShieldError('UNRESOLVED_ACCOUNT') if the IDL declares an account the
|
|
19
|
+
* caller did not supply — a loud failure is the point, because the
|
|
20
|
+
* alternative is a misordered account list that fails opaquely on-chain.
|
|
21
|
+
*/
|
|
22
|
+
export function buildTransactInstruction(accounts, args, programId = PRIVACY_POOL_PROGRAM_ID) {
|
|
23
|
+
const keys = IDL_TRANSACT.accounts.map((a) => {
|
|
24
|
+
const pubkey = accounts[a.name];
|
|
25
|
+
if (!pubkey) {
|
|
26
|
+
throw new ShieldError("UNRESOLVED_ACCOUNT", `The IDL declares account "${a.name}" for transact, but it was not resolved. ` +
|
|
27
|
+
`Expected accounts: ${TRANSACT_ACCOUNT_NAMES.join(", ")}`, { context: { missing: a.name, supplied: Object.keys(accounts) } });
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
pubkey,
|
|
31
|
+
isWritable: !!a.writable,
|
|
32
|
+
isSigner: !!a.signer,
|
|
33
|
+
};
|
|
34
|
+
});
|
|
35
|
+
const coder = new BorshInstructionCoder(PRIVACY_POOL_IDL);
|
|
36
|
+
const data = coder.encode("transact", toBorshArgs(args));
|
|
37
|
+
if (data.length !== TRANSACT_INSTRUCTION_DATA_BYTES) {
|
|
38
|
+
// Not fatal — the size budget assertion downstream is authoritative — but a
|
|
39
|
+
// change here means the size arithmetic in computeBudget.ts is stale.
|
|
40
|
+
console.warn(`[veilo] transact instruction data is ${data.length} bytes, expected ` +
|
|
41
|
+
`${TRANSACT_INSTRUCTION_DATA_BYTES}. The shield size budget may no longer hold.`);
|
|
42
|
+
}
|
|
43
|
+
return new TransactionInstruction({ programId, keys, data });
|
|
44
|
+
}
|
|
45
|
+
/** Anchor's Borsh coder wants camelCase field names, BNs, and plain arrays. */
|
|
46
|
+
function toBorshArgs(args) {
|
|
47
|
+
return {
|
|
48
|
+
root: Array.from(args.root),
|
|
49
|
+
input_tree_id: args.inputTreeId,
|
|
50
|
+
output_tree_id: args.outputTreeId,
|
|
51
|
+
public_amount: new BN(args.publicAmount.toString()),
|
|
52
|
+
ext_data_hash: Array.from(args.extDataHash),
|
|
53
|
+
mint_address: args.mintAddress,
|
|
54
|
+
input_nullifier_0: Array.from(args.inputNullifiers[0]),
|
|
55
|
+
input_nullifier_1: Array.from(args.inputNullifiers[1]),
|
|
56
|
+
output_commitment_0: Array.from(args.outputCommitments[0]),
|
|
57
|
+
output_commitment_1: Array.from(args.outputCommitments[1]),
|
|
58
|
+
deadline: new BN(args.deadline.toString()),
|
|
59
|
+
ext_data: {
|
|
60
|
+
recipient: args.extData.recipient,
|
|
61
|
+
relayer: args.extData.relayer,
|
|
62
|
+
fee: new BN(args.extData.fee.toString()),
|
|
63
|
+
refund: new BN(args.extData.refund.toString()),
|
|
64
|
+
claimant: args.extData.claimant,
|
|
65
|
+
},
|
|
66
|
+
proof: {
|
|
67
|
+
proof_a: args.proof.proofA,
|
|
68
|
+
proof_b: args.proof.proofB,
|
|
69
|
+
proof_c: args.proof.proofC,
|
|
70
|
+
},
|
|
71
|
+
note_ciphers: args.noteCiphers
|
|
72
|
+
? {
|
|
73
|
+
note0_ephemeral_key: Array.from(args.noteCiphers.note0EphemeralKey),
|
|
74
|
+
note0_encrypted: Array.from(args.noteCiphers.note0Encrypted),
|
|
75
|
+
note0_view_tag: args.noteCiphers.note0ViewTag,
|
|
76
|
+
note1_ephemeral_key: Array.from(args.noteCiphers.note1EphemeralKey),
|
|
77
|
+
note1_encrypted: Array.from(args.noteCiphers.note1Encrypted),
|
|
78
|
+
note1_view_tag: args.noteCiphers.note1ViewTag,
|
|
79
|
+
}
|
|
80
|
+
: null,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { PublicKey } from "@solana/web3.js";
|
|
2
|
+
import type { ShieldOwner } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Resolve a shield recipient into the pair of keys that must belong to the same
|
|
5
|
+
* account.
|
|
6
|
+
*
|
|
7
|
+
* This is the only mechanism that makes the owner invariant safe. A note's
|
|
8
|
+
* *spend* authority is a Poseidon field element and its *detection* authority is
|
|
9
|
+
* an Ed25519 wallet key; nothing on-chain relates them, and if an integrator
|
|
10
|
+
* sources them separately and gets them wrong, the note is spendable but
|
|
11
|
+
* permanently invisible — the funds are gone from the owner's view with no error
|
|
12
|
+
* raised anywhere in the stack.
|
|
13
|
+
*
|
|
14
|
+
* `GET /auth/veiloPublicKey` returns both halves in a single response, so
|
|
15
|
+
* routing through this function makes the pairing structural rather than a
|
|
16
|
+
* convention integrators are asked to remember.
|
|
17
|
+
*
|
|
18
|
+
* Prefer this over hand-building a {@link ShieldOwner} in all cases.
|
|
19
|
+
*/
|
|
20
|
+
export declare function resolveShieldOwner(target: {
|
|
21
|
+
username: string;
|
|
22
|
+
} | {
|
|
23
|
+
publicKey: string | PublicKey;
|
|
24
|
+
}): Promise<ShieldOwner>;
|
|
25
|
+
/**
|
|
26
|
+
* Build a {@link ShieldOwner} from keys the caller already holds.
|
|
27
|
+
*
|
|
28
|
+
* Only correct when both keys provably belong to the same account. The explicit
|
|
29
|
+
* flag is not ceremony — it is the last checkpoint before a class of bug whose
|
|
30
|
+
* only symptom is a user's money quietly disappearing from their balance.
|
|
31
|
+
*/
|
|
32
|
+
export declare function unsafeShieldOwner(params: {
|
|
33
|
+
veiloPublicKey: bigint;
|
|
34
|
+
noteViewingKey: PublicKey;
|
|
35
|
+
acknowledgeOwnerInvariant: true;
|
|
36
|
+
}): ShieldOwner;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { PublicKey } from "@solana/web3.js";
|
|
2
|
+
import { VeiloApiError, VeiloRelayerClient } from "../relayer.js";
|
|
3
|
+
import { ShieldError } from "./errors.js";
|
|
4
|
+
/**
|
|
5
|
+
* Owner resolution is a Veilo protocol service, not an integrator-selected
|
|
6
|
+
* transport. Keep the production endpoint and public encryption key inside the
|
|
7
|
+
* SDK so callers cannot accidentally resolve the two owner keys from different
|
|
8
|
+
* relayers.
|
|
9
|
+
*
|
|
10
|
+
* These values are public network coordinates, not credentials. In particular,
|
|
11
|
+
* never put a secret API key here: browser/mobile package contents are always
|
|
12
|
+
* inspectable. The two owner endpoints used below are intentionally public and
|
|
13
|
+
* return public key material only.
|
|
14
|
+
*/
|
|
15
|
+
const OWNER_RELAYER = new VeiloRelayerClient({
|
|
16
|
+
apiKey: "",
|
|
17
|
+
relayerPublicKey: "utVxnA7zax09qJCZ7UJsa8PAOoWLRcCwOkdxg/ZGmD4=",
|
|
18
|
+
});
|
|
19
|
+
/**
|
|
20
|
+
* Resolve a shield recipient into the pair of keys that must belong to the same
|
|
21
|
+
* account.
|
|
22
|
+
*
|
|
23
|
+
* This is the only mechanism that makes the owner invariant safe. A note's
|
|
24
|
+
* *spend* authority is a Poseidon field element and its *detection* authority is
|
|
25
|
+
* an Ed25519 wallet key; nothing on-chain relates them, and if an integrator
|
|
26
|
+
* sources them separately and gets them wrong, the note is spendable but
|
|
27
|
+
* permanently invisible — the funds are gone from the owner's view with no error
|
|
28
|
+
* raised anywhere in the stack.
|
|
29
|
+
*
|
|
30
|
+
* `GET /auth/veiloPublicKey` returns both halves in a single response, so
|
|
31
|
+
* routing through this function makes the pairing structural rather than a
|
|
32
|
+
* convention integrators are asked to remember.
|
|
33
|
+
*
|
|
34
|
+
* Prefer this over hand-building a {@link ShieldOwner} in all cases.
|
|
35
|
+
*/
|
|
36
|
+
export async function resolveShieldOwner(target) {
|
|
37
|
+
const query = "username" in target
|
|
38
|
+
? { username: target.username }
|
|
39
|
+
: {
|
|
40
|
+
publicKey: typeof target.publicKey === "string"
|
|
41
|
+
? target.publicKey
|
|
42
|
+
: target.publicKey.toBase58(),
|
|
43
|
+
};
|
|
44
|
+
let response;
|
|
45
|
+
try {
|
|
46
|
+
response = await OWNER_RELAYER.getVeiloPublicKey(query);
|
|
47
|
+
}
|
|
48
|
+
catch (e) {
|
|
49
|
+
// A raw Solana address may not have a Veilo account yet. Provisioning is
|
|
50
|
+
// public and idempotent, and returns only the Poseidon spend key; the
|
|
51
|
+
// address we were given is the matching note-viewing key.
|
|
52
|
+
if ("publicKey" in target &&
|
|
53
|
+
(e?.status === 404 || (e instanceof VeiloApiError && e.status === 404))) {
|
|
54
|
+
const wallet = typeof target.publicKey === "string"
|
|
55
|
+
? new PublicKey(target.publicKey)
|
|
56
|
+
: target.publicKey;
|
|
57
|
+
const provisioned = await OWNER_RELAYER.preRegisterKey(wallet.toBase58());
|
|
58
|
+
if (!provisioned?.veiloPublicKey) {
|
|
59
|
+
throw new ShieldError("UNKNOWN", "The relayer pre-registered the recipient but returned no Veilo public key.", { context: { publicKey: wallet.toBase58(), response: provisioned }, cause: e });
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
veiloPublicKey: BigInt(provisioned.veiloPublicKey),
|
|
63
|
+
noteViewingKey: wallet,
|
|
64
|
+
acknowledgeOwnerInvariant: true,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
// A pre-registered account is one someone else created on the recipient's
|
|
68
|
+
// behalf; the recipient has never proved ownership, so the relayer refuses
|
|
69
|
+
// to resolve it by username. Shielding to them still works, but the caller
|
|
70
|
+
// must address them by Solana address instead.
|
|
71
|
+
if (e?.body?.preRegistered ||
|
|
72
|
+
e?.details?.preRegistered ||
|
|
73
|
+
/preregistered/i.test(String(e?.message ?? ""))) {
|
|
74
|
+
throw new ShieldError("UNKNOWN", `"${"username" in target ? target.username : "that account"}" is pre-registered ` +
|
|
75
|
+
`and cannot be resolved by username. Resolve it by Solana address instead — ` +
|
|
76
|
+
`resolveShieldOwner({ publicKey }).`, { context: { preRegistered: true }, cause: e });
|
|
77
|
+
}
|
|
78
|
+
throw e;
|
|
79
|
+
}
|
|
80
|
+
const veiloPublicKeyRaw = response?.veiloPublicKey;
|
|
81
|
+
const walletRaw = response?.pubK;
|
|
82
|
+
if (!veiloPublicKeyRaw || !walletRaw) {
|
|
83
|
+
throw new ShieldError("UNKNOWN", `The relayer did not return both keys for this recipient ` +
|
|
84
|
+
`(veiloPublicKey=${!!veiloPublicKeyRaw}, pubK=${!!walletRaw}). ` +
|
|
85
|
+
`Shielding without both would create a note the owner cannot find.`, { context: { response } });
|
|
86
|
+
}
|
|
87
|
+
const noteViewingKey = new PublicKey(walletRaw);
|
|
88
|
+
if ("publicKey" in target &&
|
|
89
|
+
!noteViewingKey.equals(typeof target.publicKey === "string"
|
|
90
|
+
? new PublicKey(target.publicKey)
|
|
91
|
+
: target.publicKey)) {
|
|
92
|
+
throw new ShieldError("UNKNOWN", "The Veilo owner service returned a different wallet than the one requested. " +
|
|
93
|
+
"Shielding was stopped to prevent creating a note for the wrong recipient.", {
|
|
94
|
+
context: {
|
|
95
|
+
requested: typeof target.publicKey === "string"
|
|
96
|
+
? target.publicKey
|
|
97
|
+
: target.publicKey.toBase58(),
|
|
98
|
+
returned: noteViewingKey.toBase58(),
|
|
99
|
+
},
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
veiloPublicKey: BigInt(veiloPublicKeyRaw),
|
|
104
|
+
noteViewingKey,
|
|
105
|
+
// Safe to assert: both halves came from one response about one account.
|
|
106
|
+
acknowledgeOwnerInvariant: true,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Build a {@link ShieldOwner} from keys the caller already holds.
|
|
111
|
+
*
|
|
112
|
+
* Only correct when both keys provably belong to the same account. The explicit
|
|
113
|
+
* flag is not ceremony — it is the last checkpoint before a class of bug whose
|
|
114
|
+
* only symptom is a user's money quietly disappearing from their balance.
|
|
115
|
+
*/
|
|
116
|
+
export function unsafeShieldOwner(params) {
|
|
117
|
+
return {
|
|
118
|
+
veiloPublicKey: params.veiloPublicKey,
|
|
119
|
+
noteViewingKey: params.noteViewingKey,
|
|
120
|
+
acknowledgeOwnerInvariant: true,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Connection, PublicKey } from "@solana/web3.js";
|
|
2
|
+
import type { DepositTarget, ShieldCachePort, TreeSource } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Injection points for the shield path.
|
|
5
|
+
*
|
|
6
|
+
* The three production deposit implementations (extension, wallet-app,
|
|
7
|
+
* veilo-dapp) are ~85% identical and diverge on exactly these axes: where
|
|
8
|
+
* proofs come from, where the tree comes from, which lookup table to use, and
|
|
9
|
+
* what to cache into. Making each an explicit port is what lets one
|
|
10
|
+
* implementation serve all of them — and lets a third-party integrator supply
|
|
11
|
+
* their own without forking anything.
|
|
12
|
+
*
|
|
13
|
+
* Proof generation is deliberately NOT redefined here: `TransactionProofBuilder`
|
|
14
|
+
* from `proof.ts` already has the right shape, and a second prover abstraction
|
|
15
|
+
* would be exactly the kind of duplication this module exists to avoid.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Read the target tree and root directly from chain.
|
|
19
|
+
*
|
|
20
|
+
* Note the account decoding: `MerkleTreeAccount::EXPECTED_SIZE` (9107) does not
|
|
21
|
+
* match the size its declared fields sum to (8987), a 120-byte discrepancy that
|
|
22
|
+
* is unexplained. Until it is, hand-slicing this account at fixed byte offsets
|
|
23
|
+
* is unsafe. Anchor's coder reads declared fields from the front and ignores the
|
|
24
|
+
* tail, so `.fetch()` stays correct regardless.
|
|
25
|
+
*/
|
|
26
|
+
export declare function onChainTreeSource(connection: Connection, programId?: PublicKey): TreeSource;
|
|
27
|
+
/**
|
|
28
|
+
* Fixed values, for tests and offline builds.
|
|
29
|
+
*
|
|
30
|
+
* Also the escape hatch for an integrator who already tracks the tree state and
|
|
31
|
+
* does not want the SDK making RPC calls on their behalf.
|
|
32
|
+
*/
|
|
33
|
+
export declare function staticTreeSource(target: DepositTarget): TreeSource;
|
|
34
|
+
/**
|
|
35
|
+
* In-memory cache with TTL. The default.
|
|
36
|
+
*
|
|
37
|
+
* Persistent storage is deliberately the caller's problem — `localStorage`,
|
|
38
|
+
* `chrome.storage`, and `AsyncStorage` are three different answers in three
|
|
39
|
+
* different apps, and none of them belongs in a published SDK.
|
|
40
|
+
*/
|
|
41
|
+
export declare function memoryCache(): ShieldCachePort;
|
|
42
|
+
/** A cache that never stores anything. Useful for tests that assert fetch counts. */
|
|
43
|
+
export declare function noCache(): ShieldCachePort;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { createReadonlyVeiloProgram, PRIVACY_POOL_PROGRAM_ID } from "../program.js";
|
|
2
|
+
import { getNoteTreePda, getPoolPdas } from "../client.js";
|
|
3
|
+
import { MERKLE_TREE_DEPTH } from "../config.js";
|
|
4
|
+
import { ShieldError } from "./errors.js";
|
|
5
|
+
/**
|
|
6
|
+
* Injection points for the shield path.
|
|
7
|
+
*
|
|
8
|
+
* The three production deposit implementations (extension, wallet-app,
|
|
9
|
+
* veilo-dapp) are ~85% identical and diverge on exactly these axes: where
|
|
10
|
+
* proofs come from, where the tree comes from, which lookup table to use, and
|
|
11
|
+
* what to cache into. Making each an explicit port is what lets one
|
|
12
|
+
* implementation serve all of them — and lets a third-party integrator supply
|
|
13
|
+
* their own without forking anything.
|
|
14
|
+
*
|
|
15
|
+
* Proof generation is deliberately NOT redefined here: `TransactionProofBuilder`
|
|
16
|
+
* from `proof.ts` already has the right shape, and a second prover abstraction
|
|
17
|
+
* would be exactly the kind of duplication this module exists to avoid.
|
|
18
|
+
*/
|
|
19
|
+
// -- TreeSource ---------------------------------------------------------------
|
|
20
|
+
/**
|
|
21
|
+
* Read the target tree and root directly from chain.
|
|
22
|
+
*
|
|
23
|
+
* Note the account decoding: `MerkleTreeAccount::EXPECTED_SIZE` (9107) does not
|
|
24
|
+
* match the size its declared fields sum to (8987), a 120-byte discrepancy that
|
|
25
|
+
* is unexplained. Until it is, hand-slicing this account at fixed byte offsets
|
|
26
|
+
* is unsafe. Anchor's coder reads declared fields from the front and ignores the
|
|
27
|
+
* tail, so `.fetch()` stays correct regardless.
|
|
28
|
+
*/
|
|
29
|
+
export function onChainTreeSource(connection, programId = PRIVACY_POOL_PROGRAM_ID) {
|
|
30
|
+
return {
|
|
31
|
+
async getDepositTarget(mint) {
|
|
32
|
+
const program = createReadonlyVeiloProgram(connection);
|
|
33
|
+
const { config } = getPoolPdas(programId, mint);
|
|
34
|
+
const cfg = await program.account.privacyConfig.fetch(config);
|
|
35
|
+
const numTrees = Number(cfg.numTrees);
|
|
36
|
+
if (!Number.isInteger(numTrees) || numTrees <= 0) {
|
|
37
|
+
throw new ShieldError("TREE_FULL", `Pool ${mint.toBase58()} has no deposit tree.`, { context: { mint: mint.toBase58(), numTrees } });
|
|
38
|
+
}
|
|
39
|
+
// Fetch every tree in one RPC call. The older getBestTreeForDeposit path
|
|
40
|
+
// fetched them serially, then fetched the chosen trees a second time.
|
|
41
|
+
const treePdas = Array.from({ length: numTrees }, (_, treeId) => getNoteTreePda(programId, mint, treeId));
|
|
42
|
+
const infos = await connection.getMultipleAccountsInfo(treePdas, {
|
|
43
|
+
commitment: "confirmed",
|
|
44
|
+
});
|
|
45
|
+
const capacity = 2 ** MERKLE_TREE_DEPTH;
|
|
46
|
+
const trees = infos.map((info, treeId) => {
|
|
47
|
+
if (!info)
|
|
48
|
+
return null;
|
|
49
|
+
// Anchor camel-cases the IDL's `MerkleTreeAccount` name when it builds
|
|
50
|
+
// the Borsh account-layout map (the same key exposed as
|
|
51
|
+
// `program.account.merkleTreeAccount`).
|
|
52
|
+
const decoded = program.coder.accounts.decode("merkleTreeAccount", info.data);
|
|
53
|
+
const nextIndex = Number(decoded.nextIndex);
|
|
54
|
+
return {
|
|
55
|
+
treeId,
|
|
56
|
+
decoded,
|
|
57
|
+
nextIndex,
|
|
58
|
+
remainingCapacity: capacity - nextIndex,
|
|
59
|
+
};
|
|
60
|
+
});
|
|
61
|
+
const inputTree = trees[0];
|
|
62
|
+
if (!inputTree) {
|
|
63
|
+
throw new ShieldError("POOL_NOT_FOUND", `Pool ${mint.toBase58()} is missing its input Merkle tree (tree 0).`, { context: { mint: mint.toBase58(), tree: treePdas[0].toBase58() } });
|
|
64
|
+
}
|
|
65
|
+
const available = trees.filter((tree) => !!tree && tree.nextIndex < capacity);
|
|
66
|
+
if (available.length === 0) {
|
|
67
|
+
throw new ShieldError("TREE_FULL", `All ${numTrees} Merkle trees for ${mint.toBase58()} are full.`, { context: { mint: mint.toBase58(), numTrees, capacity } });
|
|
68
|
+
}
|
|
69
|
+
const minCapacity = Math.floor(capacity * 0.0001);
|
|
70
|
+
const preferred = available
|
|
71
|
+
.filter((tree) => tree.remainingCapacity >= minCapacity)
|
|
72
|
+
.sort((a, b) => a.treeId - b.treeId);
|
|
73
|
+
const outputTree = preferred[0] ??
|
|
74
|
+
available.sort((a, b) => b.remainingCapacity - a.remainingCapacity)[0];
|
|
75
|
+
return {
|
|
76
|
+
inputTreeId: 0,
|
|
77
|
+
inputRoot: extractRoot(inputTree.decoded),
|
|
78
|
+
outputTreeId: outputTree.treeId,
|
|
79
|
+
outputNextIndex: outputTree.nextIndex,
|
|
80
|
+
};
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Fixed values, for tests and offline builds.
|
|
86
|
+
*
|
|
87
|
+
* Also the escape hatch for an integrator who already tracks the tree state and
|
|
88
|
+
* does not want the SDK making RPC calls on their behalf.
|
|
89
|
+
*/
|
|
90
|
+
export function staticTreeSource(target) {
|
|
91
|
+
return { async getDepositTarget() { return target; } };
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Read the root from a decoded `MerkleTreeAccount`.
|
|
95
|
+
*
|
|
96
|
+
* Uses `root_history[root_index]` rather than the `root` field. Both are written
|
|
97
|
+
* to the same value by `append` (merkle_tree.rs:108-111) so they agree, but the
|
|
98
|
+
* history read is what all three production implementations use and is therefore
|
|
99
|
+
* the one that is actually exercised against mainnet.
|
|
100
|
+
*/
|
|
101
|
+
function extractRoot(tree) {
|
|
102
|
+
const history = tree.rootHistory ?? tree.root_history;
|
|
103
|
+
const index = Number(tree.rootIndex ?? tree.root_index ?? 0);
|
|
104
|
+
if (Array.isArray(history) && history[index]) {
|
|
105
|
+
return new Uint8Array(history[index]);
|
|
106
|
+
}
|
|
107
|
+
const root = tree.root;
|
|
108
|
+
if (root)
|
|
109
|
+
return new Uint8Array(root);
|
|
110
|
+
throw new Error("could not read a Merkle root from the tree account");
|
|
111
|
+
}
|
|
112
|
+
// -- Cache --------------------------------------------------------------------
|
|
113
|
+
/**
|
|
114
|
+
* In-memory cache with TTL. The default.
|
|
115
|
+
*
|
|
116
|
+
* Persistent storage is deliberately the caller's problem — `localStorage`,
|
|
117
|
+
* `chrome.storage`, and `AsyncStorage` are three different answers in three
|
|
118
|
+
* different apps, and none of them belongs in a published SDK.
|
|
119
|
+
*/
|
|
120
|
+
export function memoryCache() {
|
|
121
|
+
const store = new Map();
|
|
122
|
+
return {
|
|
123
|
+
async get(key) {
|
|
124
|
+
const hit = store.get(key);
|
|
125
|
+
if (!hit)
|
|
126
|
+
return undefined;
|
|
127
|
+
if (hit.expiresAt !== 0 && hit.expiresAt < Date.now()) {
|
|
128
|
+
store.delete(key);
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
return hit.value;
|
|
132
|
+
},
|
|
133
|
+
async set(key, value, ttlMs) {
|
|
134
|
+
store.set(key, {
|
|
135
|
+
value,
|
|
136
|
+
expiresAt: ttlMs && ttlMs > 0 ? Date.now() + ttlMs : 0,
|
|
137
|
+
});
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** A cache that never stores anything. Useful for tests that assert fetch counts. */
|
|
142
|
+
export function noCache() {
|
|
143
|
+
return {
|
|
144
|
+
async get() { return undefined; },
|
|
145
|
+
async set() { },
|
|
146
|
+
};
|
|
147
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Connection, PublicKey } from "@solana/web3.js";
|
|
2
|
+
import type { PreflightOptions, ShieldCachePort } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Checks that run before the prover.
|
|
5
|
+
*
|
|
6
|
+
* Proving costs 10–30 seconds. Every check here is a single RPC call, and each
|
|
7
|
+
* one pre-empts an on-chain failure whose message tells the user nothing they
|
|
8
|
+
* can act on. The delegate check is the clearest example: the program requires
|
|
9
|
+
* `user_token.delegate.is_none()`, so anyone who ever approved a DEX has a
|
|
10
|
+
* permanently broken deposit path that reports only "Invalid token account
|
|
11
|
+
* authority" — with no hint that revoking a delegate would fix it.
|
|
12
|
+
*
|
|
13
|
+
* These are advisory in the sense that the chain enforces them anyway. They are
|
|
14
|
+
* not advisory in the sense that skipping them produces a materially worse
|
|
15
|
+
* product.
|
|
16
|
+
*/
|
|
17
|
+
export declare function preflightShield(params: {
|
|
18
|
+
connection: Connection;
|
|
19
|
+
amount: bigint;
|
|
20
|
+
mint: PublicKey;
|
|
21
|
+
signer: {
|
|
22
|
+
publicKey: PublicKey;
|
|
23
|
+
tokenAccount: PublicKey;
|
|
24
|
+
};
|
|
25
|
+
programId?: PublicKey;
|
|
26
|
+
options?: PreflightOptions;
|
|
27
|
+
cache?: ShieldCachePort;
|
|
28
|
+
computeUnitLimit?: number;
|
|
29
|
+
computeUnitPriceMicroLamports?: number;
|
|
30
|
+
}): Promise<void>;
|