@cloak.dev/sdk 0.2.6-staging.6c85601 → 0.2.6-staging.af2dfc0
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/CHANGELOG.md +101 -0
- package/README.md +88 -39
- package/dist/index.cjs +465 -155
- package/dist/index.d.cts +317 -154
- package/dist/index.d.ts +317 -154
- package/dist/index.js +455 -154
- package/package.json +2 -1
package/dist/index.cjs
CHANGED
|
@@ -577,6 +577,7 @@ var index_exports = {};
|
|
|
577
577
|
__export(index_exports, {
|
|
578
578
|
AccountRole: () => import_kit7.AccountRole,
|
|
579
579
|
BRIDGE_ESCROW_LABEL: () => BRIDGE_ESCROW_LABEL,
|
|
580
|
+
BRIDGE_ESCROW_LABEL_V2: () => BRIDGE_ESCROW_LABEL_V2,
|
|
580
581
|
BUILD_ALLOWS_LOCAL_ENDPOINTS: () => BUILD_ALLOWS_LOCAL_ENDPOINTS,
|
|
581
582
|
CHAIN_NOTE_SALT_BITS: () => CHAIN_NOTE_SALT_BITS,
|
|
582
583
|
CLEANUP_FEE_BUDGET: () => CLEANUP_FEE_BUDGET,
|
|
@@ -705,14 +706,18 @@ __export(index_exports, {
|
|
|
705
706
|
depositFromDerivedKey: () => depositFromDerivedKey,
|
|
706
707
|
deriveBridgeReceiver: () => deriveBridgeReceiver,
|
|
707
708
|
deriveChangeNoteBlinding: () => deriveChangeNoteBlinding,
|
|
708
|
-
|
|
709
|
+
deriveDepositNoteBlinding: () => deriveDepositNoteBlinding,
|
|
709
710
|
deriveDiversifiedViewingKey: () => deriveDiversifiedViewingKey,
|
|
710
711
|
deriveDiversifier: () => deriveDiversifier,
|
|
711
712
|
deriveFundingTargets: () => deriveFundingTargets,
|
|
712
713
|
deriveInputNullifierPdas: () => deriveInputNullifierPdas,
|
|
714
|
+
deriveLegacyBridgeReceiver: () => deriveLegacyBridgeReceiver,
|
|
715
|
+
deriveLegacyDepositNoteSecrets: () => deriveLegacyDepositNoteSecrets,
|
|
716
|
+
deriveLegacySwapRefundAuthorization: () => deriveLegacySwapRefundAuthorization,
|
|
713
717
|
derivePublicKey: () => derivePublicKey,
|
|
714
718
|
deriveSpendKey: () => deriveSpendKey,
|
|
715
719
|
deriveSwapRefundAuthorization: () => deriveSwapRefundAuthorization,
|
|
720
|
+
deriveSwapRefundBlinding: () => deriveSwapRefundBlinding,
|
|
716
721
|
deriveUserCompliancePublicKey: () => deriveUserCompliancePublicKey,
|
|
717
722
|
deriveUserComplianceScalar: () => deriveUserComplianceScalar,
|
|
718
723
|
deriveUtxoKeypairFromSpendKey: () => deriveUtxoKeypairFromSpendKey,
|
|
@@ -1622,6 +1627,44 @@ function isLoopbackHost(value) {
|
|
|
1622
1627
|
}
|
|
1623
1628
|
var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
|
|
1624
1629
|
|
|
1630
|
+
// src/relay/clock.ts
|
|
1631
|
+
var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
|
|
1632
|
+
var MAX_CLOCK_DIVERGENCE_MS = 2e3;
|
|
1633
|
+
var MAX_PLAUSIBLE_OFFSET_MS = 365 * 24 * 60 * 60 * 1e3;
|
|
1634
|
+
var sample = null;
|
|
1635
|
+
function monotonicNowMs() {
|
|
1636
|
+
const perf = globalThis.performance;
|
|
1637
|
+
return typeof perf?.now === "function" ? perf.now() : Date.now();
|
|
1638
|
+
}
|
|
1639
|
+
function observeRelayClock(response) {
|
|
1640
|
+
const raw = response?.headers?.get?.(RELAY_SERVER_TIME_HEADER);
|
|
1641
|
+
if (typeof raw !== "string" || !/^\d{1,16}$/.test(raw.trim())) return;
|
|
1642
|
+
const serverMs = Number(raw.trim());
|
|
1643
|
+
const wallMs = Date.now();
|
|
1644
|
+
const offsetMs = serverMs - wallMs;
|
|
1645
|
+
if (!Number.isSafeInteger(serverMs) || Math.abs(offsetMs) > MAX_PLAUSIBLE_OFFSET_MS) return;
|
|
1646
|
+
sample = { offsetMs, wallAtSampleMs: wallMs, monoAtSampleMs: monotonicNowMs() };
|
|
1647
|
+
}
|
|
1648
|
+
function relayNowMs() {
|
|
1649
|
+
const wallMs = Date.now();
|
|
1650
|
+
if (!sample) return wallMs;
|
|
1651
|
+
const wallElapsed = wallMs - sample.wallAtSampleMs;
|
|
1652
|
+
const monoElapsed = monotonicNowMs() - sample.monoAtSampleMs;
|
|
1653
|
+
if (Math.abs(wallElapsed - monoElapsed) > MAX_CLOCK_DIVERGENCE_MS) {
|
|
1654
|
+
sample = null;
|
|
1655
|
+
return wallMs;
|
|
1656
|
+
}
|
|
1657
|
+
return wallMs + sample.offsetMs;
|
|
1658
|
+
}
|
|
1659
|
+
function hasRelayClockSample() {
|
|
1660
|
+
if (!sample) return false;
|
|
1661
|
+
relayNowMs();
|
|
1662
|
+
return sample !== null;
|
|
1663
|
+
}
|
|
1664
|
+
function relayNowSeconds() {
|
|
1665
|
+
return Math.floor(relayNowMs() / 1e3);
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1625
1668
|
// src/relay/endpoint.ts
|
|
1626
1669
|
var ALLOWED_ORIGINS = new Set(
|
|
1627
1670
|
RELAY_ORIGIN_ALLOWLIST.map((entry) => {
|
|
@@ -1673,8 +1716,9 @@ function assertAllowedRelayOrigin(value) {
|
|
|
1673
1716
|
async function relayFetch(url, init, options) {
|
|
1674
1717
|
assertAllowedRelayOrigin(url);
|
|
1675
1718
|
const extra = sanitizeExtraHeaders(options?.extraHeaders);
|
|
1676
|
-
|
|
1677
|
-
|
|
1719
|
+
const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
|
|
1720
|
+
observeRelayClock(response);
|
|
1721
|
+
return response;
|
|
1678
1722
|
}
|
|
1679
1723
|
var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
1680
1724
|
var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
|
|
@@ -2144,7 +2188,7 @@ ${digest}`
|
|
|
2144
2188
|
}
|
|
2145
2189
|
function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
|
|
2146
2190
|
const senderB58 = sender;
|
|
2147
|
-
const issuedAt = String(nowSeconds ??
|
|
2191
|
+
const issuedAt = String(nowSeconds ?? relayNowSeconds());
|
|
2148
2192
|
const nonce = randomNonceUuid();
|
|
2149
2193
|
const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
|
|
2150
2194
|
const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
|
|
@@ -2223,7 +2267,7 @@ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_
|
|
|
2223
2267
|
`The wallet approval took ${Math.round(elapsedSeconds)} seconds, and Cloak requests stay valid for ${maxAgeSeconds} seconds from the moment they are signed (${RELAY_AUTH_APPROVAL_MARGIN_SECONDS} of those are held back for the request to reach the network). The timestamp is inside the signature, so it cannot be refreshed without your approval again. NOTHING WAS SUBMITTED and no funds moved. Start the same operation again and approve the prompt when it appears.`
|
|
2224
2268
|
);
|
|
2225
2269
|
}
|
|
2226
|
-
function explainRelayAuthRejection(responseText) {
|
|
2270
|
+
function explainRelayAuthRejection(responseText, context) {
|
|
2227
2271
|
const text = String(responseText);
|
|
2228
2272
|
const has = (needle) => text.includes(needle);
|
|
2229
2273
|
if (has("issued too far in the future")) {
|
|
@@ -2233,7 +2277,9 @@ function explainRelayAuthRejection(responseText) {
|
|
|
2233
2277
|
return `The request was signed more than ${REQUEST_AUTH_MAX_AGE_SECONDS} seconds before it arrived, usually because a wallet approval was left waiting, or because this computer's clock is running behind. The signed timestamp cannot be refreshed on its own. Start the operation again. Nothing was submitted.`;
|
|
2234
2278
|
}
|
|
2235
2279
|
if (has("does not match the exact request")) {
|
|
2236
|
-
|
|
2280
|
+
const base = `The request body changed after it was signed, so the relay's digest and this one disagree. Sign the exact body that is POSTed, and re-POST a retry byte for byte rather than rebuilding it. If this is a hand-built swap call, check that every field in TRANSACT_SWAP_AUTH_FIELDS is present, including \`slippage_bps\`.`;
|
|
2281
|
+
if (!context?.carriedAffiliateCode) return base;
|
|
2282
|
+
return `${base} This request carried \`affiliate_code\`, which is signed with the rest of the body. A relay that predates the affiliate release (REL-010/REL-011) ignores that field and leaves it out of its digest, which produces exactly this mismatch. Upgrade the relay, or send the request without \`affiliateCode\`.`;
|
|
2237
2283
|
}
|
|
2238
2284
|
if (has("has no registered viewing key")) {
|
|
2239
2285
|
return `The signature was accepted, so this is not a signing problem: the wallet that signed has no viewing key registered with Cloak yet. Register one first, or let the SDK do it by leaving \`enforceViewingKeyRegistration\` on and supplying the viewing key.`;
|
|
@@ -5107,6 +5153,7 @@ async function fetchWithRetry(url, options = {}) {
|
|
|
5107
5153
|
try {
|
|
5108
5154
|
const response = await fetch(url, { signal: controller.signal });
|
|
5109
5155
|
clearTimeout(timeoutId);
|
|
5156
|
+
observeRelayClock(response);
|
|
5110
5157
|
return response;
|
|
5111
5158
|
} finally {
|
|
5112
5159
|
clearTimeout(timeoutId);
|
|
@@ -5742,10 +5789,43 @@ var import_blake34 = require("@noble/hashes/blake3");
|
|
|
5742
5789
|
init_address();
|
|
5743
5790
|
var import_bs582 = __toESM(require("bs58"), 1);
|
|
5744
5791
|
init_utxo();
|
|
5792
|
+
|
|
5793
|
+
// src/notes/owner-key.ts
|
|
5794
|
+
init_utxo();
|
|
5795
|
+
var FIELD_MODULUS2 = BigInt(
|
|
5796
|
+
"21888242871839275222246405745257275088548364400416034343698204186575808495617"
|
|
5797
|
+
);
|
|
5798
|
+
async function assertOwnerUtxoKeypair(keypair, label = "ownerUtxoKeypair") {
|
|
5799
|
+
if (!keypair || typeof keypair !== "object") {
|
|
5800
|
+
throw new Error(
|
|
5801
|
+
`${label} is required: pass the wallet's long-lived UTXO keypair (deriveUtxoKeypairFromSpendKey(skSpend)). Self-owned notes are never owned by a key derived from the viewing key nk.`
|
|
5802
|
+
);
|
|
5803
|
+
}
|
|
5804
|
+
const { privateKey, publicKey } = keypair;
|
|
5805
|
+
if (typeof privateKey !== "bigint" || privateKey <= 0n || privateKey >= FIELD_MODULUS2) {
|
|
5806
|
+
throw new Error(`${label}.privateKey must be a non-zero field element (bigint)`);
|
|
5807
|
+
}
|
|
5808
|
+
if (typeof publicKey !== "bigint" || publicKey === 0n) {
|
|
5809
|
+
throw new Error(`${label}.publicKey must be a non-zero bigint`);
|
|
5810
|
+
}
|
|
5811
|
+
if (await derivePublicKey(privateKey) !== publicKey) {
|
|
5812
|
+
throw new Error(`${label}.publicKey is not derived from ${label}.privateKey`);
|
|
5813
|
+
}
|
|
5814
|
+
return { privateKey, publicKey };
|
|
5815
|
+
}
|
|
5816
|
+
function normalizeOwnerPublicKey(publicKey, label) {
|
|
5817
|
+
if (publicKey === void 0 || publicKey === null) return void 0;
|
|
5818
|
+
if (typeof publicKey !== "bigint" || publicKey <= 0n || publicKey >= FIELD_MODULUS2) {
|
|
5819
|
+
throw new Error(`${label} must be a non-zero field element (bigint)`);
|
|
5820
|
+
}
|
|
5821
|
+
return publicKey;
|
|
5822
|
+
}
|
|
5823
|
+
|
|
5824
|
+
// src/notes/swap-refund.ts
|
|
5745
5825
|
init_inputs();
|
|
5746
5826
|
var bs582 = import_bs582.default.default || import_bs582.default;
|
|
5747
5827
|
var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
|
|
5748
|
-
var
|
|
5828
|
+
var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
|
|
5749
5829
|
var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
|
|
5750
5830
|
function normalizeNullifier(inputNullifier) {
|
|
5751
5831
|
if (inputNullifier instanceof Uint8Array) {
|
|
@@ -5779,13 +5859,29 @@ function derive(nk, nullifier, info) {
|
|
|
5779
5859
|
preimage.set(info, off);
|
|
5780
5860
|
return (0, import_blake34.blake3)(preimage);
|
|
5781
5861
|
}
|
|
5782
|
-
|
|
5862
|
+
function assertNk(viewingKeyNk) {
|
|
5783
5863
|
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
5784
5864
|
throw new Error("viewingKeyNk must be 32 bytes");
|
|
5785
5865
|
}
|
|
5866
|
+
return viewingKeyNk;
|
|
5867
|
+
}
|
|
5868
|
+
function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
|
|
5869
|
+
const nk = assertNk(viewingKeyNk);
|
|
5870
|
+
return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
|
|
5871
|
+
}
|
|
5872
|
+
async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
|
|
5873
|
+
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
5874
|
+
const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
5875
|
+
if (owner.publicKey === 0n || blinding === 0n) {
|
|
5876
|
+
throw new Error("refund authorization is degenerate");
|
|
5877
|
+
}
|
|
5878
|
+
return { privateKey: owner.privateKey, publicKey: owner.publicKey, blinding };
|
|
5879
|
+
}
|
|
5880
|
+
async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
|
|
5881
|
+
const nk = assertNk(viewingKeyNk);
|
|
5786
5882
|
const nullifier = normalizeNullifier(inputNullifier);
|
|
5787
|
-
const privateKey = toFieldSecret(derive(
|
|
5788
|
-
const blinding = toFieldSecret(derive(
|
|
5883
|
+
const privateKey = toFieldSecret(derive(nk, nullifier, LEGACY_REFUND_PRIVATE_KEY_INFO));
|
|
5884
|
+
const blinding = toFieldSecret(derive(nk, nullifier, REFUND_BLINDING_INFO));
|
|
5789
5885
|
const publicKey = await derivePublicKey(privateKey);
|
|
5790
5886
|
if (publicKey === 0n || blinding === 0n) {
|
|
5791
5887
|
throw new Error("derived refund authorization is degenerate");
|
|
@@ -5803,19 +5899,39 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
|
|
|
5803
5899
|
async function matchSwapRefundLeaf(params) {
|
|
5804
5900
|
const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
|
|
5805
5901
|
const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
|
|
5806
|
-
let
|
|
5902
|
+
let blinding;
|
|
5903
|
+
try {
|
|
5904
|
+
blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
5905
|
+
} catch {
|
|
5906
|
+
return null;
|
|
5907
|
+
}
|
|
5908
|
+
const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
|
|
5909
|
+
if (ownerPub !== void 0) {
|
|
5910
|
+
const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
|
|
5911
|
+
if (candidate === expected) {
|
|
5912
|
+
return {
|
|
5913
|
+
keypair: { privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n, publicKey: ownerPub },
|
|
5914
|
+
blinding,
|
|
5915
|
+
amount: amountAfterFee,
|
|
5916
|
+
commitment: candidate,
|
|
5917
|
+
legacyExposed: false
|
|
5918
|
+
};
|
|
5919
|
+
}
|
|
5920
|
+
}
|
|
5921
|
+
let legacy;
|
|
5807
5922
|
try {
|
|
5808
|
-
|
|
5923
|
+
legacy = await deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier);
|
|
5809
5924
|
} catch {
|
|
5810
5925
|
return null;
|
|
5811
5926
|
}
|
|
5812
|
-
const
|
|
5813
|
-
if (
|
|
5927
|
+
const legacyCandidate = await computeSwapRefundCommitment(amountAfterFee, legacy.publicKey, legacy.blinding);
|
|
5928
|
+
if (legacyCandidate !== expected) return null;
|
|
5814
5929
|
return {
|
|
5815
|
-
keypair: { privateKey:
|
|
5816
|
-
blinding:
|
|
5930
|
+
keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
|
|
5931
|
+
blinding: legacy.blinding,
|
|
5817
5932
|
amount: amountAfterFee,
|
|
5818
|
-
commitment:
|
|
5933
|
+
commitment: legacyCandidate,
|
|
5934
|
+
legacyExposed: true
|
|
5819
5935
|
};
|
|
5820
5936
|
}
|
|
5821
5937
|
var TRANSACT_SWAP_TAG2 = 1;
|
|
@@ -5879,10 +5995,16 @@ function instructionsForProgram(tx, accountKeys, programIdBase58) {
|
|
|
5879
5995
|
if (Array.isArray(inner)) for (const block of inner) take(block?.instructions);
|
|
5880
5996
|
return out;
|
|
5881
5997
|
}
|
|
5882
|
-
async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
5998
|
+
async function discoverSwapRefunds(connection, programId, viewingKeyNk, options) {
|
|
5883
5999
|
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
5884
6000
|
throw new Error("viewingKeyNk must be 32 bytes");
|
|
5885
6001
|
}
|
|
6002
|
+
if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
|
|
6003
|
+
throw new Error(
|
|
6004
|
+
"discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): refund leaves are owned by it, and nk alone can only find legacy refunds."
|
|
6005
|
+
);
|
|
6006
|
+
}
|
|
6007
|
+
const ownerUtxoKeypair = options.ownerUtxoKeypair;
|
|
5886
6008
|
const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
|
|
5887
6009
|
const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
|
|
5888
6010
|
const programIdBase58 = programId;
|
|
@@ -5957,7 +6079,8 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
|
5957
6079
|
viewingKeyNk,
|
|
5958
6080
|
inputNullifier: candidate.nullifier,
|
|
5959
6081
|
amountAfterFee: event.amountAfterFee,
|
|
5960
|
-
commitment: event.commitmentField
|
|
6082
|
+
commitment: event.commitmentField,
|
|
6083
|
+
ownerUtxoKeypair
|
|
5961
6084
|
});
|
|
5962
6085
|
if (!recovered) continue;
|
|
5963
6086
|
const dedupe = `${close.signature}:${event.leafIndex}`;
|
|
@@ -5983,7 +6106,7 @@ var import_blake35 = require("@noble/hashes/blake3");
|
|
|
5983
6106
|
init_utxo();
|
|
5984
6107
|
init_inputs();
|
|
5985
6108
|
var DEPOSIT_NOTE_DOMAIN = new TextEncoder().encode("cloak_deposit_note_v1");
|
|
5986
|
-
var
|
|
6109
|
+
var LEGACY_DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
|
|
5987
6110
|
var DEPOSIT_BLINDING_INFO = new TextEncoder().encode("blinding");
|
|
5988
6111
|
var CHAIN_NOTE_SALT_BITS = 96;
|
|
5989
6112
|
var MAX_CHAIN_NOTE_SALT = (1n << BigInt(CHAIN_NOTE_SALT_BITS)) - 1n;
|
|
@@ -6019,30 +6142,47 @@ function derive2(nk, salt, info) {
|
|
|
6019
6142
|
preimage.set(info, off);
|
|
6020
6143
|
return (0, import_blake35.blake3)(preimage);
|
|
6021
6144
|
}
|
|
6145
|
+
function assertNk2(viewingKeyNk) {
|
|
6146
|
+
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
6147
|
+
throw new Error("viewingKeyNk must be 32 bytes");
|
|
6148
|
+
}
|
|
6149
|
+
return viewingKeyNk;
|
|
6150
|
+
}
|
|
6022
6151
|
function randomDepositNoteSalt() {
|
|
6023
6152
|
const bytes = randomBytes(12);
|
|
6024
6153
|
let v = 0n;
|
|
6025
6154
|
for (const b of bytes) v = v << 8n | BigInt(b);
|
|
6026
6155
|
return v === 0n ? 1n : v;
|
|
6027
6156
|
}
|
|
6028
|
-
|
|
6029
|
-
|
|
6030
|
-
|
|
6031
|
-
|
|
6157
|
+
function deriveDepositNoteBlinding(viewingKeyNk, noteSalt) {
|
|
6158
|
+
const nk = assertNk2(viewingKeyNk);
|
|
6159
|
+
return toFieldSecret2(derive2(nk, saltToBytes(noteSalt), DEPOSIT_BLINDING_INFO));
|
|
6160
|
+
}
|
|
6161
|
+
async function deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt) {
|
|
6162
|
+
const nk = assertNk2(viewingKeyNk);
|
|
6032
6163
|
const salt = saltToBytes(noteSalt);
|
|
6033
|
-
const privateKey = toFieldSecret2(derive2(
|
|
6034
|
-
const blinding = toFieldSecret2(derive2(
|
|
6164
|
+
const privateKey = toFieldSecret2(derive2(nk, salt, LEGACY_DEPOSIT_PRIVATE_KEY_INFO));
|
|
6165
|
+
const blinding = toFieldSecret2(derive2(nk, salt, DEPOSIT_BLINDING_INFO));
|
|
6035
6166
|
const publicKey = await derivePublicKey(privateKey);
|
|
6036
6167
|
if (publicKey === 0n || blinding === 0n) {
|
|
6037
6168
|
throw new Error("derived deposit note secrets are degenerate");
|
|
6038
6169
|
}
|
|
6039
6170
|
return { keypair: { privateKey, publicKey }, blinding };
|
|
6040
6171
|
}
|
|
6041
|
-
async function createRecoverableDepositUtxo(
|
|
6172
|
+
async function createRecoverableDepositUtxo(params) {
|
|
6173
|
+
if (!params || typeof params !== "object" || params instanceof Uint8Array) {
|
|
6174
|
+
throw new Error(
|
|
6175
|
+
"createRecoverableDepositUtxo takes one options object: { amount, viewingKeyNk, ownerUtxoKeypair, mintAddress?, noteSalt? }"
|
|
6176
|
+
);
|
|
6177
|
+
}
|
|
6178
|
+
const { amount, viewingKeyNk } = params;
|
|
6042
6179
|
if (typeof amount !== "bigint" || amount <= 0n) {
|
|
6043
6180
|
throw new Error("amount must be a positive bigint");
|
|
6044
6181
|
}
|
|
6045
|
-
const
|
|
6182
|
+
const keypair = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
|
|
6183
|
+
const mintAddress = params.mintAddress ?? NATIVE_SOL_MINT;
|
|
6184
|
+
const noteSalt = params.noteSalt ?? randomDepositNoteSalt();
|
|
6185
|
+
const blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
|
|
6046
6186
|
const utxo = { amount, keypair, blinding, mintAddress };
|
|
6047
6187
|
utxo.commitment = await computeCommitment2(utxo);
|
|
6048
6188
|
return { utxo, noteSalt };
|
|
@@ -6057,21 +6197,46 @@ function normalizeCommitment(value) {
|
|
|
6057
6197
|
async function matchDepositNote(params) {
|
|
6058
6198
|
const { viewingKeyNk, noteSalt, amount, mintAddress, outputCommitments } = params;
|
|
6059
6199
|
if (typeof amount !== "bigint" || amount <= 0n) return null;
|
|
6060
|
-
let
|
|
6200
|
+
let blinding;
|
|
6061
6201
|
try {
|
|
6062
|
-
|
|
6202
|
+
blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
|
|
6063
6203
|
} catch {
|
|
6064
6204
|
return null;
|
|
6065
6205
|
}
|
|
6066
|
-
const
|
|
6206
|
+
const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
|
|
6207
|
+
if (published.length === 0) return null;
|
|
6208
|
+
const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
|
|
6209
|
+
if (ownerPub !== void 0) {
|
|
6210
|
+
const keypair = {
|
|
6211
|
+
privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n,
|
|
6212
|
+
publicKey: ownerPub
|
|
6213
|
+
};
|
|
6214
|
+
const candidate = await computeCommitment2({ amount, keypair, blinding, mintAddress });
|
|
6215
|
+
if (published.some((value) => value === candidate)) {
|
|
6216
|
+
return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed: false };
|
|
6217
|
+
}
|
|
6218
|
+
}
|
|
6219
|
+
let legacy;
|
|
6220
|
+
try {
|
|
6221
|
+
legacy = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
|
|
6222
|
+
} catch {
|
|
6223
|
+
return null;
|
|
6224
|
+
}
|
|
6225
|
+
const legacyCandidate = await computeCommitment2({
|
|
6067
6226
|
amount,
|
|
6068
|
-
keypair:
|
|
6069
|
-
blinding:
|
|
6227
|
+
keypair: legacy.keypair,
|
|
6228
|
+
blinding: legacy.blinding,
|
|
6070
6229
|
mintAddress
|
|
6071
6230
|
});
|
|
6072
|
-
|
|
6073
|
-
|
|
6074
|
-
|
|
6231
|
+
if (!published.some((value) => value === legacyCandidate)) return null;
|
|
6232
|
+
return {
|
|
6233
|
+
...legacy,
|
|
6234
|
+
amount,
|
|
6235
|
+
mintAddress,
|
|
6236
|
+
commitment: legacyCandidate,
|
|
6237
|
+
noteSalt,
|
|
6238
|
+
legacyExposed: true
|
|
6239
|
+
};
|
|
6075
6240
|
}
|
|
6076
6241
|
|
|
6077
6242
|
// src/notes/change-note.ts
|
|
@@ -6129,10 +6294,11 @@ function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
|
|
|
6129
6294
|
preimage.set(CHANGE_BLINDING_INFO, off);
|
|
6130
6295
|
return toFieldSecret3((0, import_blake36.blake3)(preimage));
|
|
6131
6296
|
}
|
|
6132
|
-
async function createRecoverableChangeUtxo(amount,
|
|
6297
|
+
async function createRecoverableChangeUtxo(amount, ownerUtxoKeypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
|
|
6133
6298
|
if (typeof amount !== "bigint" || amount <= 0n) {
|
|
6134
6299
|
throw new Error("amount must be a positive bigint");
|
|
6135
6300
|
}
|
|
6301
|
+
const keypair = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
6136
6302
|
const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
|
|
6137
6303
|
const utxo = { amount, keypair, blinding, mintAddress };
|
|
6138
6304
|
utxo.commitment = await computeCommitment2(utxo);
|
|
@@ -6158,12 +6324,28 @@ async function matchChangeNote(params) {
|
|
|
6158
6324
|
const candidate = await computeCommitment2({ amount, keypair, blinding, mintAddress });
|
|
6159
6325
|
const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
|
|
6160
6326
|
if (!published.some((value) => value === candidate)) return null;
|
|
6161
|
-
|
|
6327
|
+
const walletKey = normalizeOwnerPublicKey(params.ownerUtxoPublicKey, "ownerUtxoPublicKey");
|
|
6328
|
+
const legacyExposed = walletKey !== void 0 && keypair.publicKey !== walletKey;
|
|
6329
|
+
return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed };
|
|
6162
6330
|
}
|
|
6163
6331
|
|
|
6164
6332
|
// src/flows/transact.ts
|
|
6165
6333
|
var import_circomlibjs4 = require("circomlibjs");
|
|
6166
6334
|
var import_tweetnacl5 = __toESM(require("tweetnacl"), 1);
|
|
6335
|
+
|
|
6336
|
+
// src/relay/chain-note-time.ts
|
|
6337
|
+
async function relayChainNoteTimestampMs(relayUrl) {
|
|
6338
|
+
if (relayUrl && !hasRelayClockSample()) {
|
|
6339
|
+
try {
|
|
6340
|
+
const response = await relayFetch(`${relayUrl.replace(/\/$/, "")}/health`);
|
|
6341
|
+
await response.body?.cancel?.().catch(() => void 0);
|
|
6342
|
+
} catch {
|
|
6343
|
+
}
|
|
6344
|
+
}
|
|
6345
|
+
return BigInt(relayNowMs());
|
|
6346
|
+
}
|
|
6347
|
+
|
|
6348
|
+
// src/flows/transact.ts
|
|
6167
6349
|
init_inputs();
|
|
6168
6350
|
|
|
6169
6351
|
// src/proving/artifacts.ts
|
|
@@ -6802,6 +6984,33 @@ function parseNkInput(input) {
|
|
|
6802
6984
|
}
|
|
6803
6985
|
return Uint8Array.from(Buffer.from(clean, "hex"));
|
|
6804
6986
|
}
|
|
6987
|
+
async function resolveWalletNk(options) {
|
|
6988
|
+
const explicit = await resolveChainNoteNk(options);
|
|
6989
|
+
if (explicit) return explicit;
|
|
6990
|
+
if (options.ownerUtxoKeypair) {
|
|
6991
|
+
const owner = await assertOwnerUtxoKeypair(options.ownerUtxoKeypair);
|
|
6992
|
+
return getNkFromUtxoPrivateKey(owner.privateKey);
|
|
6993
|
+
}
|
|
6994
|
+
return null;
|
|
6995
|
+
}
|
|
6996
|
+
function missingWalletNkError(flow) {
|
|
6997
|
+
return new Error(
|
|
6998
|
+
`${flow} requires the wallet's viewing key: pass chainNoteViewingKeyNk (or getChainNoteViewingKeyNk), or ownerUtxoKeypair to use its canonical nk. The SDK no longer infers nk from a note's own key.`
|
|
6999
|
+
);
|
|
7000
|
+
}
|
|
7001
|
+
async function requireWalletNk(options, flow) {
|
|
7002
|
+
const nk = await resolveWalletNk(options);
|
|
7003
|
+
if (nk) return nk;
|
|
7004
|
+
throw missingWalletNkError(flow);
|
|
7005
|
+
}
|
|
7006
|
+
async function requireOwnerUtxoKeypair(options, flow) {
|
|
7007
|
+
if (!options.ownerUtxoKeypair) {
|
|
7008
|
+
throw new Error(
|
|
7009
|
+
`${flow} requires options.ownerUtxoKeypair, the wallet's long-lived UTXO keypair (deriveUtxoKeypairFromSpendKey(skSpend)). It owns the change and refund notes this flow creates; the SDK no longer inherits that owner from inputUtxos[0].`
|
|
7010
|
+
);
|
|
7011
|
+
}
|
|
7012
|
+
return assertOwnerUtxoKeypair(options.ownerUtxoKeypair, "options.ownerUtxoKeypair");
|
|
7013
|
+
}
|
|
6805
7014
|
async function resolveChainNoteNk(options) {
|
|
6806
7015
|
if (options.chainNoteViewingKeyNk) {
|
|
6807
7016
|
return parseNkInput(options.chainNoteViewingKeyNk);
|
|
@@ -6819,7 +7028,7 @@ function shouldDefaultUseUniqueNullifiers(_connection) {
|
|
|
6819
7028
|
function toHex(bytes) {
|
|
6820
7029
|
return Buffer.from(bytes).toString("hex");
|
|
6821
7030
|
}
|
|
6822
|
-
async function ensureViewingKeyRegistered(options, onProgress,
|
|
7031
|
+
async function ensureViewingKeyRegistered(options, onProgress, walletNk) {
|
|
6823
7032
|
if (options.enforceViewingKeyRegistration === false) {
|
|
6824
7033
|
return;
|
|
6825
7034
|
}
|
|
@@ -6833,7 +7042,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
|
|
|
6833
7042
|
"Viewing key registration is mandatory: walletPublicKey or depositor public key is required."
|
|
6834
7043
|
);
|
|
6835
7044
|
}
|
|
6836
|
-
const nk =
|
|
7045
|
+
const nk = walletNk;
|
|
6837
7046
|
if (!nk || nk.length !== 32) {
|
|
6838
7047
|
throw new Error(
|
|
6839
7048
|
"Viewing key registration is mandatory: provide a chain-note viewing key (nk)."
|
|
@@ -6975,10 +7184,10 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
|
|
|
6975
7184
|
result.set(bigintToBytes323(BigInt(publicSignals[0])), offset);
|
|
6976
7185
|
offset += 32;
|
|
6977
7186
|
let amount = BigInt(publicSignals[1]);
|
|
6978
|
-
const
|
|
6979
|
-
const HALF_FIELD =
|
|
7187
|
+
const FIELD_MODULUS3 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
|
|
7188
|
+
const HALF_FIELD = FIELD_MODULUS3 / BigInt(2);
|
|
6980
7189
|
if (amount > HALF_FIELD) {
|
|
6981
|
-
amount = amount -
|
|
7190
|
+
amount = amount - FIELD_MODULUS3;
|
|
6982
7191
|
}
|
|
6983
7192
|
const amountBytes = new Uint8Array(8);
|
|
6984
7193
|
let amountValue = amount;
|
|
@@ -7925,8 +8134,9 @@ function chargeWalletApproval(used, budget, lastError) {
|
|
|
7925
8134
|
}
|
|
7926
8135
|
return used + 1;
|
|
7927
8136
|
}
|
|
7928
|
-
function relayFailureMessage(prefix, responseText) {
|
|
7929
|
-
const
|
|
8137
|
+
function relayFailureMessage(prefix, responseText, requestBody) {
|
|
8138
|
+
const carriedAffiliateCode = typeof requestBody?.affiliate_code === "string";
|
|
8139
|
+
const explanation = explainRelayAuthRejection(responseText, { carriedAffiliateCode });
|
|
7930
8140
|
return explanation ? `${prefix}: ${responseText}
|
|
7931
8141
|
|
|
7932
8142
|
${explanation}` : `${prefix}: ${responseText}`;
|
|
@@ -8304,6 +8514,7 @@ async function submitTransactToRelay(args) {
|
|
|
8304
8514
|
body: requestPayload,
|
|
8305
8515
|
signal: controller.signal
|
|
8306
8516
|
});
|
|
8517
|
+
observeRelayClock(response);
|
|
8307
8518
|
} finally {
|
|
8308
8519
|
clearTimeout(timeoutId);
|
|
8309
8520
|
}
|
|
@@ -8334,7 +8545,9 @@ async function submitTransactToRelay(args) {
|
|
|
8334
8545
|
onProgress?.("Root not found (stale), will regenerate proof with fresh tree...");
|
|
8335
8546
|
return { kind: "stale-root", error: new Error(`Relay error: ${responseText}`) };
|
|
8336
8547
|
}
|
|
8337
|
-
return await resolveFailure(
|
|
8548
|
+
return await resolveFailure(
|
|
8549
|
+
new Error(relayFailureMessage("Relay error", responseText, requestBody))
|
|
8550
|
+
);
|
|
8338
8551
|
}
|
|
8339
8552
|
const apiResponse = JSON.parse(responseText);
|
|
8340
8553
|
if (!apiResponse.success || !apiResponse.data) {
|
|
@@ -8351,7 +8564,7 @@ async function submitTransactToRelay(args) {
|
|
|
8351
8564
|
return { kind: "stale-root", error: new Error(`Relay returned error: ${errorStr}`) };
|
|
8352
8565
|
}
|
|
8353
8566
|
return await resolveFailure(
|
|
8354
|
-
new Error(relayFailureMessage("Relay returned error", errorStr))
|
|
8567
|
+
new Error(relayFailureMessage("Relay returned error", errorStr, requestBody))
|
|
8355
8568
|
);
|
|
8356
8569
|
}
|
|
8357
8570
|
const result = apiResponse.data;
|
|
@@ -8459,34 +8672,37 @@ async function transact(params, options) {
|
|
|
8459
8672
|
);
|
|
8460
8673
|
}
|
|
8461
8674
|
onProgress?.("Validating transaction parameters...");
|
|
8462
|
-
const
|
|
8463
|
-
const
|
|
8464
|
-
|
|
8465
|
-
const explicitChainNoteNk = await resolveChainNoteNk(options);
|
|
8466
|
-
if (options.chainNoteSalt !== void 0 && !explicitChainNoteNk) {
|
|
8675
|
+
const walletNk = await resolveWalletNk(options);
|
|
8676
|
+
const ownerUtxoKeypair = options.ownerUtxoKeypair ? await assertOwnerUtxoKeypair(options.ownerUtxoKeypair) : void 0;
|
|
8677
|
+
if (options.chainNoteSalt !== void 0 && !walletNk) {
|
|
8467
8678
|
throw new Error(
|
|
8468
|
-
"options.chainNoteSalt requires
|
|
8679
|
+
"options.chainNoteSalt requires the wallet's viewing key: chainNoteViewingKeyNk (or getChainNoteViewingKeyNk), or ownerUtxoKeypair. The salt anchors a note derived from that nk, and the chain note has to be encrypted under the same key or the note is undiscoverable."
|
|
8469
8680
|
);
|
|
8470
8681
|
}
|
|
8471
8682
|
const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
|
|
8472
8683
|
const chainNoteWillCarrySalt = !options.disableChainNotes && !(options.encryptedNotes && options.encryptedNotes.length > 0);
|
|
8473
|
-
if (
|
|
8474
|
-
|
|
8684
|
+
if (!walletNk && (chainNoteWillCarrySalt || options.enforceViewingKeyRegistration !== false)) {
|
|
8685
|
+
throw missingWalletNkError("transact");
|
|
8686
|
+
}
|
|
8687
|
+
if (walletNk && chainNoteWillCarrySalt) {
|
|
8688
|
+
const selfOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
|
|
8689
|
+
if (ownerUtxoKeypair) selfOwners.add(ownerUtxoKeypair.publicKey);
|
|
8690
|
+
const depositBlinding = deriveDepositNoteBlinding(walletNk, chainNoteSalt);
|
|
8475
8691
|
for (let i = 0; i < outputUtxos.length; i++) {
|
|
8476
8692
|
const out = outputUtxos[i];
|
|
8477
8693
|
if (!out || out.amount <= BigInt(0)) continue;
|
|
8478
|
-
if (!
|
|
8479
|
-
if (out.blinding !== deriveChangeNoteBlinding(
|
|
8694
|
+
if (!selfOwners.has(out.keypair.publicKey)) continue;
|
|
8695
|
+
if (out.blinding !== deriveChangeNoteBlinding(walletNk, chainNoteSalt, i) && out.blinding !== depositBlinding) {
|
|
8480
8696
|
throw new Error(
|
|
8481
|
-
`Output ${i} is change (amount ${out.amount}, owned by an input's keypair) but its blinding is not the one derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build change with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, outputIndex)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`partialWithdraw\` / \`transfer\` / \`swapWithChange\`, which do it for you.`
|
|
8697
|
+
`Output ${i} is change (amount ${out.amount}, owned by an input's or the wallet's keypair) but its blinding is not the one derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build change with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, outputIndex)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`partialWithdraw\` / \`transfer\` / \`swapWithChange\`, which do it for you.`
|
|
8482
8698
|
);
|
|
8483
8699
|
}
|
|
8484
8700
|
}
|
|
8485
8701
|
}
|
|
8486
8702
|
assertAllowedRpcConnection(connection);
|
|
8487
8703
|
assertInputMints(inputUtxos, options.expectedMint);
|
|
8488
|
-
await ensureViewingKeyRegistered(options, onProgress,
|
|
8489
|
-
const resolvedChainNoteNk =
|
|
8704
|
+
await ensureViewingKeyRegistered(options, onProgress, walletNk);
|
|
8705
|
+
const resolvedChainNoteNk = walletNk;
|
|
8490
8706
|
if (inputUtxos.length > 2) {
|
|
8491
8707
|
throw new Error("Maximum 2 input UTXOs allowed");
|
|
8492
8708
|
}
|
|
@@ -8860,7 +9076,7 @@ async function transact(params, options) {
|
|
|
8860
9076
|
}
|
|
8861
9077
|
const maxFee = isWithdrawal ? protocolFeeSnapshot : BigInt(0);
|
|
8862
9078
|
const extDataHash = await computeExtDataHash(recipient ?? null, relayerFee, relayer ?? null, maxFee);
|
|
8863
|
-
const chainNoteTimestamp =
|
|
9079
|
+
const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
|
|
8864
9080
|
const mintField = pubkeyToFieldElement(mint);
|
|
8865
9081
|
let signature = "pending-" + Date.now().toString();
|
|
8866
9082
|
let commitmentIndices = [-1, -1];
|
|
@@ -8956,9 +9172,9 @@ async function transact(params, options) {
|
|
|
8956
9172
|
]));
|
|
8957
9173
|
const noteTailHash = poseidonHasher.F.toObject(poseidonHasher([chainNoteTimestamp, noteCommitment, chainNoteSalt, noteSemantics]));
|
|
8958
9174
|
const chainNoteHash = poseidonHasher.F.toObject(poseidonHasher([CHAIN_NOTE_DOMAIN_TAG, CHAIN_NOTE_TAG, amountDataHash, noteTailHash]));
|
|
8959
|
-
const
|
|
8960
|
-
if (chainNoteHash >=
|
|
8961
|
-
throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${
|
|
9175
|
+
const FIELD_MODULUS3 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
|
|
9176
|
+
if (chainNoteHash >= FIELD_MODULUS3) {
|
|
9177
|
+
throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS3.toString()}`);
|
|
8962
9178
|
}
|
|
8963
9179
|
const pathElementsTotal = inPathElements.reduce((sum, arr) => sum + arr.length, 0);
|
|
8964
9180
|
const totalInputs = 1 + // root
|
|
@@ -9380,7 +9596,8 @@ async function transact(params, options) {
|
|
|
9380
9596
|
throw lastError;
|
|
9381
9597
|
}
|
|
9382
9598
|
const classified = classifyRelayError(lastError.message);
|
|
9383
|
-
const
|
|
9599
|
+
const isDepositSubmission = externalAmount > BigInt(0);
|
|
9600
|
+
const isMerkleClass = !isDepositSubmission && !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
|
|
9384
9601
|
if (canRebuildMerkleTreeFromChain() && isMerkleClass && relayUrl) {
|
|
9385
9602
|
onProgress?.(
|
|
9386
9603
|
"All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
|
|
@@ -9529,54 +9746,83 @@ async function transact(params, options) {
|
|
|
9529
9746
|
};
|
|
9530
9747
|
}
|
|
9531
9748
|
async function transfer(inputUtxos, recipientPubkey, amount, options) {
|
|
9749
|
+
const owner = await requireOwnerUtxoKeypair(options, "transfer");
|
|
9750
|
+
const transferNk = await requireWalletNk(options, "transfer");
|
|
9532
9751
|
const inputSum = sumUtxoAmounts(inputUtxos);
|
|
9533
9752
|
if (inputSum < amount) {
|
|
9534
9753
|
throw new Error(`Insufficient funds: have ${inputSum}, need ${amount}`);
|
|
9535
9754
|
}
|
|
9536
9755
|
const change = inputSum - amount;
|
|
9537
|
-
const myKeypair = inputUtxos[0].keypair;
|
|
9538
9756
|
const mint = inputUtxos[0].mintAddress;
|
|
9539
|
-
|
|
9540
|
-
|
|
9541
|
-
|
|
9757
|
+
let spendInputs = [
|
|
9758
|
+
...inputUtxos.filter((u) => u.keypair.publicKey === owner.publicKey),
|
|
9759
|
+
...inputUtxos.filter((u) => u.keypair.publicKey !== owner.publicKey)
|
|
9760
|
+
];
|
|
9761
|
+
let spendOptions = options;
|
|
9762
|
+
if (change > BigInt(0) && spendInputs[0].keypair.publicKey !== owner.publicKey) {
|
|
9763
|
+
if (spendInputs.length > 2) {
|
|
9764
|
+
throw new Error(
|
|
9765
|
+
`transfer: none of the ${spendInputs.length} inputs is owned by ownerUtxoKeypair (they are notes from before SDK 0.2.6), so they must first be moved under the wallet key, and one transaction moves at most 2 notes. Consolidate the older notes first (send them to yourself, ownerUtxoKeypair.publicKey, at most 2 per transfer) or withdraw them, then retry this transfer with at most 2 inputs.`
|
|
9766
|
+
);
|
|
9767
|
+
}
|
|
9768
|
+
if (options.relayAuthBatch) {
|
|
9769
|
+
throw new Error(
|
|
9770
|
+
"transfer: no input is owned by ownerUtxoKeypair, so the inputs must first be moved under the wallet key in a separate transaction, which a single batch item cannot carry. Spend them to yourself first, or run this transfer outside the batch."
|
|
9771
|
+
);
|
|
9772
|
+
}
|
|
9773
|
+
options.onProgress?.("Moving notes under the wallet key before the transfer...");
|
|
9774
|
+
const migrationSalt = randomChangeNoteSalt();
|
|
9775
|
+
const migrated = (await createRecoverableChangeUtxo(inputSum, owner, transferNk, mint, migrationSalt, 0)).utxo;
|
|
9776
|
+
const { recipientViewingPublicKey: _recipientViewingPublicKey, ...migrationOptions } = options;
|
|
9777
|
+
void _recipientViewingPublicKey;
|
|
9778
|
+
const migration = await transact(
|
|
9779
|
+
{ inputUtxos: spendInputs, outputUtxos: [migrated], externalAmount: BigInt(0) },
|
|
9780
|
+
{ ...migrationOptions, chainNoteSalt: migrationSalt }
|
|
9781
|
+
);
|
|
9782
|
+
const migratedNote = migration.outputUtxos?.[0] ?? migrated;
|
|
9783
|
+
if (migration.commitmentIndices?.[0] >= 0) {
|
|
9784
|
+
migratedNote.index = migration.commitmentIndices[0];
|
|
9785
|
+
}
|
|
9786
|
+
spendInputs = [migratedNote];
|
|
9787
|
+
spendOptions = { ...options, cachedMerkleTree: migration.merkleTree };
|
|
9788
|
+
}
|
|
9789
|
+
const changeNoteSalt = randomChangeNoteSalt();
|
|
9790
|
+
const isSendToSelf = recipientPubkey === owner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
|
|
9542
9791
|
const recipientKeypair = {
|
|
9543
9792
|
privateKey: BigInt(0),
|
|
9544
9793
|
// Recipient's private key unknown
|
|
9545
9794
|
publicKey: recipientPubkey
|
|
9546
9795
|
};
|
|
9547
|
-
const recipientUtxo =
|
|
9796
|
+
const recipientUtxo = isSendToSelf ? (await createRecoverableChangeUtxo(amount, owner, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
|
|
9548
9797
|
const outputUtxos = [recipientUtxo];
|
|
9549
9798
|
if (change > BigInt(0)) {
|
|
9550
|
-
|
|
9551
|
-
|
|
9552
|
-
|
|
9553
|
-
|
|
9554
|
-
|
|
9555
|
-
|
|
9556
|
-
|
|
9557
|
-
|
|
9558
|
-
|
|
9559
|
-
outputUtxos.push(utxo);
|
|
9560
|
-
} else {
|
|
9561
|
-
outputUtxos.push(await createUtxo(change, myKeypair, mint));
|
|
9562
|
-
}
|
|
9799
|
+
const { utxo } = await createRecoverableChangeUtxo(
|
|
9800
|
+
change,
|
|
9801
|
+
owner,
|
|
9802
|
+
transferNk,
|
|
9803
|
+
mint,
|
|
9804
|
+
changeNoteSalt,
|
|
9805
|
+
1
|
|
9806
|
+
);
|
|
9807
|
+
outputUtxos.push(utxo);
|
|
9563
9808
|
}
|
|
9564
9809
|
return transact(
|
|
9565
9810
|
{
|
|
9566
|
-
inputUtxos,
|
|
9811
|
+
inputUtxos: spendInputs,
|
|
9567
9812
|
outputUtxos,
|
|
9568
9813
|
externalAmount: BigInt(0)
|
|
9569
9814
|
// Pure shield-to-shield
|
|
9570
9815
|
},
|
|
9571
|
-
|
|
9816
|
+
{ ...spendOptions, chainNoteSalt: changeNoteSalt }
|
|
9572
9817
|
);
|
|
9573
9818
|
}
|
|
9574
9819
|
async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
9820
|
+
const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
|
|
9821
|
+
const walletNk = await requireWalletNk(options, "partialWithdraw");
|
|
9575
9822
|
const inputSum = sumUtxoAmounts(inputUtxos);
|
|
9576
9823
|
if (inputSum < withdrawAmount) {
|
|
9577
9824
|
throw new Error(`Insufficient funds: have ${inputSum}, need ${withdrawAmount}`);
|
|
9578
9825
|
}
|
|
9579
|
-
const myKeypair = inputUtxos[0].keypair;
|
|
9580
9826
|
const mint = inputUtxos[0].mintAddress;
|
|
9581
9827
|
let utxos = [...inputUtxos];
|
|
9582
9828
|
let cachedTree = options.cachedMerkleTree;
|
|
@@ -9585,9 +9831,8 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
|
9585
9831
|
utxos.sort((a, b) => a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0);
|
|
9586
9832
|
const [small1, small2, ...rest] = utxos;
|
|
9587
9833
|
const mergedAmount = small1.amount + small2.amount;
|
|
9588
|
-
const
|
|
9589
|
-
const
|
|
9590
|
-
const mergedOutput = mergeNk ? (await createRecoverableChangeUtxo(mergedAmount, myKeypair, mergeNk, mint, mergeSalt, 0)).utxo : await createUtxo(mergedAmount, myKeypair, mint);
|
|
9834
|
+
const mergeSalt = randomChangeNoteSalt();
|
|
9835
|
+
const mergedOutput = (await createRecoverableChangeUtxo(mergedAmount, owner, walletNk, mint, mergeSalt, 0)).utxo;
|
|
9591
9836
|
const mergeResult = await transact(
|
|
9592
9837
|
{
|
|
9593
9838
|
inputUtxos: [small1, small2],
|
|
@@ -9598,7 +9843,7 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
|
9598
9843
|
{
|
|
9599
9844
|
...options,
|
|
9600
9845
|
cachedMerkleTree: cachedTree,
|
|
9601
|
-
|
|
9846
|
+
chainNoteSalt: mergeSalt
|
|
9602
9847
|
}
|
|
9603
9848
|
);
|
|
9604
9849
|
cachedTree = mergeResult.merkleTree;
|
|
@@ -9613,23 +9858,18 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
|
9613
9858
|
const outputUtxos = [];
|
|
9614
9859
|
let changeNoteSalt;
|
|
9615
9860
|
if (change > BigInt(0)) {
|
|
9616
|
-
const
|
|
9617
|
-
|
|
9618
|
-
|
|
9619
|
-
|
|
9620
|
-
|
|
9621
|
-
|
|
9622
|
-
|
|
9623
|
-
|
|
9624
|
-
|
|
9625
|
-
|
|
9626
|
-
|
|
9627
|
-
|
|
9628
|
-
outputUtxos.push(utxo);
|
|
9629
|
-
changeNoteSalt = salt;
|
|
9630
|
-
} else {
|
|
9631
|
-
outputUtxos.push(await createUtxo(change, myKeypair, mint));
|
|
9632
|
-
}
|
|
9861
|
+
const salt = randomChangeNoteSalt();
|
|
9862
|
+
const { utxo } = await createRecoverableChangeUtxo(
|
|
9863
|
+
change,
|
|
9864
|
+
owner,
|
|
9865
|
+
walletNk,
|
|
9866
|
+
mint,
|
|
9867
|
+
salt,
|
|
9868
|
+
0
|
|
9869
|
+
// partialWithdraw puts change at output 0
|
|
9870
|
+
);
|
|
9871
|
+
outputUtxos.push(utxo);
|
|
9872
|
+
changeNoteSalt = salt;
|
|
9633
9873
|
}
|
|
9634
9874
|
return transact(
|
|
9635
9875
|
{
|
|
@@ -9752,6 +9992,8 @@ async function swapUtxo(params, options) {
|
|
|
9752
9992
|
if (relayUrl) {
|
|
9753
9993
|
assertRelayAuthAvailable(relayAuthPlan, "private swap");
|
|
9754
9994
|
}
|
|
9995
|
+
const swapOwner = await requireOwnerUtxoKeypair(options, "swapUtxo");
|
|
9996
|
+
const resolvedSwapChainNoteNk = await requireWalletNk(options, "swapUtxo");
|
|
9755
9997
|
if (inputUtxos.length === 0) {
|
|
9756
9998
|
throw new Error("At least one input UTXO required");
|
|
9757
9999
|
}
|
|
@@ -9777,15 +10019,12 @@ async function swapUtxo(params, options) {
|
|
|
9777
10019
|
throw new Error(`Amount mismatch: input(${totalInputAmount}) != swap(${swapAmount}) + change(${changeAmount})`);
|
|
9778
10020
|
}
|
|
9779
10021
|
onProgress?.("Validating transaction parameters...");
|
|
9780
|
-
|
|
9781
|
-
await ensureViewingKeyRegistered(options, onProgress, swapFallbackNk);
|
|
9782
|
-
const explicitSwapChainNoteNk = await resolveChainNoteNk(options);
|
|
9783
|
-
const resolvedSwapChainNoteNk = explicitSwapChainNoteNk ?? swapFallbackNk;
|
|
10022
|
+
await ensureViewingKeyRegistered(options, onProgress, resolvedSwapChainNoteNk);
|
|
9784
10023
|
const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
|
|
9785
|
-
if (
|
|
9786
|
-
if (changeUtxo.blinding !== deriveChangeNoteBlinding(
|
|
10024
|
+
if (changeUtxo && changeUtxo.amount > BigInt(0) && (changeUtxo.keypair.publicKey === swapOwner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey))) {
|
|
10025
|
+
if (changeUtxo.blinding !== deriveChangeNoteBlinding(resolvedSwapChainNoteNk, chainNoteSalt, 0)) {
|
|
9787
10026
|
throw new Error(
|
|
9788
|
-
`Swap change (amount ${changeUtxo.amount}, owned by an input's keypair) has a blinding that is not derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build it with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, 0)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`swapWithChange\`, which does it for you.`
|
|
10027
|
+
`Swap change (amount ${changeUtxo.amount}, owned by an input's or the wallet's keypair) has a blinding that is not derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build it with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, 0)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`swapWithChange\`, which does it for you.`
|
|
9789
10028
|
);
|
|
9790
10029
|
}
|
|
9791
10030
|
}
|
|
@@ -9809,24 +10048,18 @@ async function swapUtxo(params, options) {
|
|
|
9809
10048
|
);
|
|
9810
10049
|
}
|
|
9811
10050
|
const externalAmount = -swapAmount;
|
|
9812
|
-
|
|
9813
|
-
|
|
9814
|
-
|
|
9815
|
-
|
|
9816
|
-
|
|
9817
|
-
|
|
9818
|
-
|
|
9819
|
-
|
|
9820
|
-
|
|
9821
|
-
|
|
9822
|
-
|
|
9823
|
-
|
|
9824
|
-
refundBlinding = randomFieldElement();
|
|
9825
|
-
}
|
|
9826
|
-
} else {
|
|
9827
|
-
refundKeypair = await generateUtxoKeypair();
|
|
9828
|
-
refundBlinding = randomFieldElement();
|
|
9829
|
-
}
|
|
10051
|
+
const refundNullifier = bigintToBytes323(await computeNullifier(paddedInputs[0]));
|
|
10052
|
+
const refundAuthorization = await deriveSwapRefundAuthorization(
|
|
10053
|
+
resolvedSwapChainNoteNk,
|
|
10054
|
+
refundNullifier,
|
|
10055
|
+
swapOwner
|
|
10056
|
+
);
|
|
10057
|
+
const refundKeypair = {
|
|
10058
|
+
privateKey: refundAuthorization.privateKey,
|
|
10059
|
+
publicKey: refundAuthorization.publicKey
|
|
10060
|
+
};
|
|
10061
|
+
const refundBlinding = refundAuthorization.blinding;
|
|
10062
|
+
const refundDerivedFromNk = true;
|
|
9830
10063
|
if (refundKeypair.publicKey === BigInt(0) || refundBlinding === BigInt(0)) {
|
|
9831
10064
|
throw new Error(
|
|
9832
10065
|
"Refund authorization derivation produced a zero pubkey/blinding \u2014 aborting swap to avoid an unclaimable timeout refund. Retry; a persistent failure indicates a keygen/RNG fault."
|
|
@@ -10152,7 +10385,7 @@ async function swapUtxo(params, options) {
|
|
|
10152
10385
|
for (const utxo of paddedOutputs) {
|
|
10153
10386
|
outputCommitments.push(await computeCommitment2(utxo));
|
|
10154
10387
|
}
|
|
10155
|
-
const chainNoteTimestamp =
|
|
10388
|
+
const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
|
|
10156
10389
|
onProgress?.("Computing external data hash...");
|
|
10157
10390
|
const mint = swapPoolMint;
|
|
10158
10391
|
const mintField = pubkeyToFieldElement(mint);
|
|
@@ -10466,7 +10699,7 @@ async function swapUtxo(params, options) {
|
|
|
10466
10699
|
forceChainIndexing = !relayUrl;
|
|
10467
10700
|
continue;
|
|
10468
10701
|
}
|
|
10469
|
-
throw new Error(relayFailureMessage("Relay error", responseText));
|
|
10702
|
+
throw new Error(relayFailureMessage("Relay error", responseText, requestBody));
|
|
10470
10703
|
}
|
|
10471
10704
|
const apiResponse = JSON.parse(responseText);
|
|
10472
10705
|
if (!apiResponse.success || !apiResponse.data) {
|
|
@@ -10602,7 +10835,6 @@ async function swapUtxo(params, options) {
|
|
|
10602
10835
|
// V3-04: the refund-fallback secret (hex, 32-byte field elements). Persist to claim a timed-out
|
|
10603
10836
|
// swap; see the UtxoSwapResult.refund docs. amountAfterFee is read from on-chain SwapState.
|
|
10604
10837
|
refund: {
|
|
10605
|
-
privateKey: Buffer.from(bigintToBytes323(refundKeypair.privateKey)).toString("hex"),
|
|
10606
10838
|
publicKey: Buffer.from(bigintToBytes323(refundKeypair.publicKey)).toString("hex"),
|
|
10607
10839
|
blinding: Buffer.from(bigintToBytes323(refundBlinding)).toString("hex"),
|
|
10608
10840
|
derivedFromNk: refundDerivedFromNk
|
|
@@ -10610,6 +10842,7 @@ async function swapUtxo(params, options) {
|
|
|
10610
10842
|
};
|
|
10611
10843
|
}
|
|
10612
10844
|
async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
|
|
10845
|
+
const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
|
|
10613
10846
|
const totalInput = sumUtxoAmounts(inputUtxos);
|
|
10614
10847
|
const change = totalInput - swapAmount;
|
|
10615
10848
|
if (change < BigInt(0)) {
|
|
@@ -10618,16 +10851,11 @@ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta,
|
|
|
10618
10851
|
let changeUtxo;
|
|
10619
10852
|
let changeNoteSalt;
|
|
10620
10853
|
if (change > BigInt(0)) {
|
|
10621
|
-
const myKeypair = inputUtxos[0].keypair;
|
|
10622
10854
|
const mint = inputUtxos[0].mintAddress;
|
|
10623
|
-
const changeNk = await
|
|
10624
|
-
|
|
10625
|
-
|
|
10626
|
-
|
|
10627
|
-
changeNoteSalt = salt;
|
|
10628
|
-
} else {
|
|
10629
|
-
changeUtxo = await createUtxo(change, myKeypair, mint);
|
|
10630
|
-
}
|
|
10855
|
+
const changeNk = await requireWalletNk(options, "swapWithChange");
|
|
10856
|
+
const salt = randomChangeNoteSalt();
|
|
10857
|
+
changeUtxo = (await createRecoverableChangeUtxo(change, owner, changeNk, mint, salt, 0)).utxo;
|
|
10858
|
+
changeNoteSalt = salt;
|
|
10631
10859
|
}
|
|
10632
10860
|
return swapUtxo(
|
|
10633
10861
|
{
|
|
@@ -10953,7 +11181,7 @@ var RelayBatchAuthCoordinator = class {
|
|
|
10953
11181
|
throw new Error("Every item of a batch must target the same program id.");
|
|
10954
11182
|
}
|
|
10955
11183
|
}
|
|
10956
|
-
const nowSeconds =
|
|
11184
|
+
const nowSeconds = relayNowSeconds();
|
|
10957
11185
|
const preimages = waiting.map(
|
|
10958
11186
|
(w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
|
|
10959
11187
|
);
|
|
@@ -11394,7 +11622,7 @@ async function deriveDepositCandidate(viewingKeyNk, noteSalt) {
|
|
|
11394
11622
|
const cached = depositSecretsCache.get(key);
|
|
11395
11623
|
if (cached) return cached;
|
|
11396
11624
|
try {
|
|
11397
|
-
const secrets = await
|
|
11625
|
+
const secrets = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
|
|
11398
11626
|
if (depositSecretsCache.size >= 4096) {
|
|
11399
11627
|
const oldest = depositSecretsCache.keys().next();
|
|
11400
11628
|
if (!oldest.done) depositSecretsCache.delete(oldest.value);
|
|
@@ -11977,6 +12205,7 @@ async function scanTransactions(opts) {
|
|
|
11977
12205
|
} else {
|
|
11978
12206
|
const derived = await deriveDepositCandidate(viewingKeyNk, compactNote.noteSalt);
|
|
11979
12207
|
const candidateKeys = [
|
|
12208
|
+
opts.ownerUtxoPublicKey,
|
|
11980
12209
|
derived?.keypair.publicKey,
|
|
11981
12210
|
opts.ownUtxoPublicKey,
|
|
11982
12211
|
BigInt(0)
|
|
@@ -12030,6 +12259,7 @@ async function scanTransactions(opts) {
|
|
|
12030
12259
|
try {
|
|
12031
12260
|
const recoveredDeposit = await matchDepositNote({
|
|
12032
12261
|
viewingKeyNk,
|
|
12262
|
+
ownerUtxoKeypair: opts.ownerUtxoPublicKey !== void 0 ? { privateKey: 0n, publicKey: opts.ownerUtxoPublicKey } : void 0,
|
|
12033
12263
|
noteSalt: compactNote.noteSalt,
|
|
12034
12264
|
// Output 0's amount. For a shield with no inputs — the shape `transact` builds for a
|
|
12035
12265
|
// deposit — that is the public deposit amount. A deposit that also merged inputs
|
|
@@ -12064,7 +12294,8 @@ async function scanTransactions(opts) {
|
|
|
12064
12294
|
mintAddress: (0, import_kit.address)(asset.mint),
|
|
12065
12295
|
outputIndex: 0,
|
|
12066
12296
|
// v4 describes output 0, which is where change lands
|
|
12067
|
-
outputCommitments: ixCtx.outputCommitments ?? []
|
|
12297
|
+
outputCommitments: ixCtx.outputCommitments ?? [],
|
|
12298
|
+
ownerUtxoPublicKey: opts.ownerUtxoPublicKey
|
|
12068
12299
|
});
|
|
12069
12300
|
if (recoveredChange) {
|
|
12070
12301
|
recoveredChangeNotes.push({
|
|
@@ -12174,6 +12405,17 @@ async function scanTransactions(opts) {
|
|
|
12174
12405
|
runningByAsset.set(key, running);
|
|
12175
12406
|
tx.runningBalance = running;
|
|
12176
12407
|
}
|
|
12408
|
+
const legacyKeys = /* @__PURE__ */ new Map();
|
|
12409
|
+
for (const note of recoveredDepositNotes) {
|
|
12410
|
+
if (note.legacyExposed) legacyKeys.set(note.keypair.publicKey, note.keypair.privateKey);
|
|
12411
|
+
}
|
|
12412
|
+
for (const change of recoveredChangeNotes) {
|
|
12413
|
+
const legacyPrivateKey = legacyKeys.get(change.keypair.publicKey);
|
|
12414
|
+
if (legacyPrivateKey !== void 0) {
|
|
12415
|
+
change.keypair = { privateKey: legacyPrivateKey, publicKey: change.keypair.publicKey };
|
|
12416
|
+
change.legacyExposed = true;
|
|
12417
|
+
}
|
|
12418
|
+
}
|
|
12177
12419
|
return {
|
|
12178
12420
|
transactions: txs,
|
|
12179
12421
|
summary: {
|
|
@@ -12912,7 +13154,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
12912
13154
|
})
|
|
12913
13155
|
});
|
|
12914
13156
|
const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
|
|
12915
|
-
if (
|
|
13157
|
+
if (relayNowSeconds() >= prepared.expires_at_unix) {
|
|
12916
13158
|
throw new Error(
|
|
12917
13159
|
"paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
|
|
12918
13160
|
);
|
|
@@ -12949,9 +13191,13 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
12949
13191
|
// src/bridge/derive.ts
|
|
12950
13192
|
var import_hmac = require("@noble/hashes/hmac");
|
|
12951
13193
|
var import_sha512 = require("@noble/hashes/sha512");
|
|
13194
|
+
var import_blake37 = require("@noble/hashes/blake3");
|
|
13195
|
+
init_utxo();
|
|
12952
13196
|
var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
|
|
13197
|
+
var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
|
|
13198
|
+
var BRIDGE_RECEIVER_KEY_DOMAIN = new TextEncoder().encode("cloak_bridge_receiver_key_v2");
|
|
12953
13199
|
var MAX_RECEIVER_INDEX = 1e4;
|
|
12954
|
-
|
|
13200
|
+
function assertReceiverIndex(index) {
|
|
12955
13201
|
if (!Number.isInteger(index) || index < 0) {
|
|
12956
13202
|
throw new Error(`index must be a non-negative integer, got ${index}`);
|
|
12957
13203
|
}
|
|
@@ -12960,6 +13206,26 @@ async function deriveBridgeReceiver(nk, index) {
|
|
|
12960
13206
|
`index ${index} exceeds MAX_RECEIVER_INDEX (${MAX_RECEIVER_INDEX}). Indices must be a small sequential counter \u2014 discovery derives 0\u2026N and reads each on chain, so a timestamp index is unreachable by any scan and the deposit would be invisible to every device but this one.`
|
|
12961
13207
|
);
|
|
12962
13208
|
}
|
|
13209
|
+
}
|
|
13210
|
+
async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
|
|
13211
|
+
if (ownerUtxoKeypair instanceof Uint8Array) {
|
|
13212
|
+
throw new Error(
|
|
13213
|
+
"deriveBridgeReceiver takes the wallet's UTXO keypair, not a byte key. Receivers are no longer derived from nk; use deriveLegacyBridgeReceiver(nk, index) only to find old deposits."
|
|
13214
|
+
);
|
|
13215
|
+
}
|
|
13216
|
+
assertReceiverIndex(index);
|
|
13217
|
+
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
13218
|
+
const priv = bigintToBytes323(owner.privateKey);
|
|
13219
|
+
const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
|
|
13220
|
+
preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
|
|
13221
|
+
preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
|
|
13222
|
+
const key = (0, import_blake37.blake3)(preimage);
|
|
13223
|
+
const h = (0, import_hmac.hmac)(import_sha512.sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
|
|
13224
|
+
return signerFromSecretKey(h.slice(0, 32));
|
|
13225
|
+
}
|
|
13226
|
+
async function deriveLegacyBridgeReceiver(nk, index) {
|
|
13227
|
+
assertReceiverIndex(index);
|
|
13228
|
+
if (!nk || nk.length !== 32) throw new Error("nk must be 32 bytes");
|
|
12963
13229
|
const h = (0, import_hmac.hmac)(import_sha512.sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
|
|
12964
13230
|
return signerFromSecretKey(h.slice(0, 32));
|
|
12965
13231
|
}
|
|
@@ -12970,13 +13236,44 @@ var import_token4 = require("@solana-program/token");
|
|
|
12970
13236
|
function describeError(err) {
|
|
12971
13237
|
return err instanceof Error ? err.message : String(err);
|
|
12972
13238
|
}
|
|
12973
|
-
async function listBridgeDeposits(rpc,
|
|
13239
|
+
async function listBridgeDeposits(rpc, ownerUtxoKeypair, opts) {
|
|
13240
|
+
if (ownerUtxoKeypair instanceof Uint8Array) {
|
|
13241
|
+
throw new Error(
|
|
13242
|
+
"listBridgeDeposits takes the wallet's UTXO keypair, not nk. Receivers are no longer derived from nk; legacy nk receivers are scanned automatically (see DiscoverOptions.includeLegacy)."
|
|
13243
|
+
);
|
|
13244
|
+
}
|
|
13245
|
+
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
13246
|
+
const out = await scanReceivers(rpc, opts, (index) => deriveBridgeReceiver(owner, index), {
|
|
13247
|
+
legacyExposed: false
|
|
13248
|
+
});
|
|
13249
|
+
if (opts.includeLegacy === false) return out;
|
|
13250
|
+
const nks = [];
|
|
13251
|
+
const seen = /* @__PURE__ */ new Set();
|
|
13252
|
+
for (const nk of [getNkFromUtxoPrivateKey(owner.privateKey), ...opts.legacyViewingKeyNks ?? []]) {
|
|
13253
|
+
if (!(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
13254
|
+
throw new Error("legacyViewingKeyNks entries must be 32 bytes");
|
|
13255
|
+
}
|
|
13256
|
+
const key = Array.from(nk, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
13257
|
+
if (seen.has(key)) continue;
|
|
13258
|
+
seen.add(key);
|
|
13259
|
+
nks.push(nk);
|
|
13260
|
+
}
|
|
13261
|
+
for (const nk of nks) {
|
|
13262
|
+
const legacy = await scanReceivers(rpc, opts, (index) => deriveLegacyBridgeReceiver(nk, index), {
|
|
13263
|
+
legacyExposed: true,
|
|
13264
|
+
legacyViewingKeyNk: nk
|
|
13265
|
+
});
|
|
13266
|
+
out.push(...legacy);
|
|
13267
|
+
}
|
|
13268
|
+
return out;
|
|
13269
|
+
}
|
|
13270
|
+
async function scanReceivers(rpc, opts, receiverAt, provenance) {
|
|
12974
13271
|
const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
|
|
12975
13272
|
const stopAfterUnused = opts.stopAfterUnused ?? 5;
|
|
12976
13273
|
const out = [];
|
|
12977
13274
|
let consecutiveUnused = 0;
|
|
12978
13275
|
for (let index = 0; index < scanDepth; index++) {
|
|
12979
|
-
const kp = await
|
|
13276
|
+
const kp = await receiverAt(index);
|
|
12980
13277
|
const receiver = kp.address;
|
|
12981
13278
|
const [tokenAccount] = await (0, import_token4.findAssociatedTokenPda)({
|
|
12982
13279
|
mint: opts.mint,
|
|
@@ -13028,7 +13325,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
|
|
|
13028
13325
|
tokenBalance,
|
|
13029
13326
|
lamports,
|
|
13030
13327
|
shieldSignature,
|
|
13031
|
-
...indexReused ? { indexReused, shieldSignatures } : {}
|
|
13328
|
+
...indexReused ? { indexReused, shieldSignatures } : {},
|
|
13329
|
+
...provenance
|
|
13032
13330
|
});
|
|
13033
13331
|
} catch (err) {
|
|
13034
13332
|
out.push({
|
|
@@ -13038,7 +13336,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
|
|
|
13038
13336
|
state: "unknown",
|
|
13039
13337
|
tokenBalance: 0n,
|
|
13040
13338
|
lamports: 0n,
|
|
13041
|
-
error: describeError(err)
|
|
13339
|
+
error: describeError(err),
|
|
13340
|
+
...provenance
|
|
13042
13341
|
});
|
|
13043
13342
|
}
|
|
13044
13343
|
}
|
|
@@ -13192,7 +13491,12 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
|
|
|
13192
13491
|
const signMessage = (m) => signMessageBytes(R, m);
|
|
13193
13492
|
const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
|
|
13194
13493
|
const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
|
|
13195
|
-
const { utxo, noteSalt } = await createRecoverableDepositUtxo(
|
|
13494
|
+
const { utxo, noteSalt } = await createRecoverableDepositUtxo({
|
|
13495
|
+
amount,
|
|
13496
|
+
viewingKeyNk: nk,
|
|
13497
|
+
ownerUtxoKeypair: utxoKeypair,
|
|
13498
|
+
mintAddress: mint
|
|
13499
|
+
});
|
|
13196
13500
|
const zeroInput = await createZeroUtxo(mint);
|
|
13197
13501
|
const rBefore = (await rpc.getBalance(R.address).send()).value;
|
|
13198
13502
|
let result;
|
|
@@ -13211,6 +13515,7 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
|
|
|
13211
13515
|
signMessage,
|
|
13212
13516
|
chainNoteViewingKeyNk: nk,
|
|
13213
13517
|
chainNoteSalt: noteSalt,
|
|
13518
|
+
ownerUtxoKeypair: utxoKeypair,
|
|
13214
13519
|
relaySupplementalAlt: true,
|
|
13215
13520
|
onProgress: (s) => log(` \xB7 ${s}`)
|
|
13216
13521
|
}
|
|
@@ -13424,6 +13729,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13424
13729
|
0 && (module.exports = {
|
|
13425
13730
|
AccountRole,
|
|
13426
13731
|
BRIDGE_ESCROW_LABEL,
|
|
13732
|
+
BRIDGE_ESCROW_LABEL_V2,
|
|
13427
13733
|
BUILD_ALLOWS_LOCAL_ENDPOINTS,
|
|
13428
13734
|
CHAIN_NOTE_SALT_BITS,
|
|
13429
13735
|
CLEANUP_FEE_BUDGET,
|
|
@@ -13552,14 +13858,18 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13552
13858
|
depositFromDerivedKey,
|
|
13553
13859
|
deriveBridgeReceiver,
|
|
13554
13860
|
deriveChangeNoteBlinding,
|
|
13555
|
-
|
|
13861
|
+
deriveDepositNoteBlinding,
|
|
13556
13862
|
deriveDiversifiedViewingKey,
|
|
13557
13863
|
deriveDiversifier,
|
|
13558
13864
|
deriveFundingTargets,
|
|
13559
13865
|
deriveInputNullifierPdas,
|
|
13866
|
+
deriveLegacyBridgeReceiver,
|
|
13867
|
+
deriveLegacyDepositNoteSecrets,
|
|
13868
|
+
deriveLegacySwapRefundAuthorization,
|
|
13560
13869
|
derivePublicKey,
|
|
13561
13870
|
deriveSpendKey,
|
|
13562
13871
|
deriveSwapRefundAuthorization,
|
|
13872
|
+
deriveSwapRefundBlinding,
|
|
13563
13873
|
deriveUserCompliancePublicKey,
|
|
13564
13874
|
deriveUserComplianceScalar,
|
|
13565
13875
|
deriveUtxoKeypairFromSpendKey,
|