@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.js
CHANGED
|
@@ -753,6 +753,44 @@ function isLoopbackHost(value) {
|
|
|
753
753
|
}
|
|
754
754
|
var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
|
|
755
755
|
|
|
756
|
+
// src/relay/clock.ts
|
|
757
|
+
var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
|
|
758
|
+
var MAX_CLOCK_DIVERGENCE_MS = 2e3;
|
|
759
|
+
var MAX_PLAUSIBLE_OFFSET_MS = 365 * 24 * 60 * 60 * 1e3;
|
|
760
|
+
var sample = null;
|
|
761
|
+
function monotonicNowMs() {
|
|
762
|
+
const perf = globalThis.performance;
|
|
763
|
+
return typeof perf?.now === "function" ? perf.now() : Date.now();
|
|
764
|
+
}
|
|
765
|
+
function observeRelayClock(response) {
|
|
766
|
+
const raw = response?.headers?.get?.(RELAY_SERVER_TIME_HEADER);
|
|
767
|
+
if (typeof raw !== "string" || !/^\d{1,16}$/.test(raw.trim())) return;
|
|
768
|
+
const serverMs = Number(raw.trim());
|
|
769
|
+
const wallMs = Date.now();
|
|
770
|
+
const offsetMs = serverMs - wallMs;
|
|
771
|
+
if (!Number.isSafeInteger(serverMs) || Math.abs(offsetMs) > MAX_PLAUSIBLE_OFFSET_MS) return;
|
|
772
|
+
sample = { offsetMs, wallAtSampleMs: wallMs, monoAtSampleMs: monotonicNowMs() };
|
|
773
|
+
}
|
|
774
|
+
function relayNowMs() {
|
|
775
|
+
const wallMs = Date.now();
|
|
776
|
+
if (!sample) return wallMs;
|
|
777
|
+
const wallElapsed = wallMs - sample.wallAtSampleMs;
|
|
778
|
+
const monoElapsed = monotonicNowMs() - sample.monoAtSampleMs;
|
|
779
|
+
if (Math.abs(wallElapsed - monoElapsed) > MAX_CLOCK_DIVERGENCE_MS) {
|
|
780
|
+
sample = null;
|
|
781
|
+
return wallMs;
|
|
782
|
+
}
|
|
783
|
+
return wallMs + sample.offsetMs;
|
|
784
|
+
}
|
|
785
|
+
function hasRelayClockSample() {
|
|
786
|
+
if (!sample) return false;
|
|
787
|
+
relayNowMs();
|
|
788
|
+
return sample !== null;
|
|
789
|
+
}
|
|
790
|
+
function relayNowSeconds() {
|
|
791
|
+
return Math.floor(relayNowMs() / 1e3);
|
|
792
|
+
}
|
|
793
|
+
|
|
756
794
|
// src/relay/endpoint.ts
|
|
757
795
|
var ALLOWED_ORIGINS = new Set(
|
|
758
796
|
RELAY_ORIGIN_ALLOWLIST.map((entry) => {
|
|
@@ -804,8 +842,9 @@ function assertAllowedRelayOrigin(value) {
|
|
|
804
842
|
async function relayFetch(url, init, options) {
|
|
805
843
|
assertAllowedRelayOrigin(url);
|
|
806
844
|
const extra = sanitizeExtraHeaders(options?.extraHeaders);
|
|
807
|
-
|
|
808
|
-
|
|
845
|
+
const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
|
|
846
|
+
observeRelayClock(response);
|
|
847
|
+
return response;
|
|
809
848
|
}
|
|
810
849
|
var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
811
850
|
var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
|
|
@@ -1298,7 +1337,7 @@ ${digest}`
|
|
|
1298
1337
|
}
|
|
1299
1338
|
function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
|
|
1300
1339
|
const senderB58 = sender;
|
|
1301
|
-
const issuedAt = String(nowSeconds ??
|
|
1340
|
+
const issuedAt = String(nowSeconds ?? relayNowSeconds());
|
|
1302
1341
|
const nonce = randomNonceUuid();
|
|
1303
1342
|
const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
|
|
1304
1343
|
const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
|
|
@@ -1377,7 +1416,7 @@ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_
|
|
|
1377
1416
|
`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.`
|
|
1378
1417
|
);
|
|
1379
1418
|
}
|
|
1380
|
-
function explainRelayAuthRejection(responseText) {
|
|
1419
|
+
function explainRelayAuthRejection(responseText, context) {
|
|
1381
1420
|
const text = String(responseText);
|
|
1382
1421
|
const has = (needle) => text.includes(needle);
|
|
1383
1422
|
if (has("issued too far in the future")) {
|
|
@@ -1387,7 +1426,9 @@ function explainRelayAuthRejection(responseText) {
|
|
|
1387
1426
|
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.`;
|
|
1388
1427
|
}
|
|
1389
1428
|
if (has("does not match the exact request")) {
|
|
1390
|
-
|
|
1429
|
+
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\`.`;
|
|
1430
|
+
if (!context?.carriedAffiliateCode) return base;
|
|
1431
|
+
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\`.`;
|
|
1391
1432
|
}
|
|
1392
1433
|
if (has("has no registered viewing key")) {
|
|
1393
1434
|
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.`;
|
|
@@ -4236,6 +4277,7 @@ async function fetchWithRetry(url, options = {}) {
|
|
|
4236
4277
|
try {
|
|
4237
4278
|
const response = await fetch(url, { signal: controller.signal });
|
|
4238
4279
|
clearTimeout(timeoutId);
|
|
4280
|
+
observeRelayClock(response);
|
|
4239
4281
|
return response;
|
|
4240
4282
|
} finally {
|
|
4241
4283
|
clearTimeout(timeoutId);
|
|
@@ -4880,9 +4922,41 @@ function parseDeliveryCarrierMemo(data) {
|
|
|
4880
4922
|
// src/notes/swap-refund.ts
|
|
4881
4923
|
import { blake3 as blake33 } from "@noble/hashes/blake3";
|
|
4882
4924
|
import _bs582 from "bs58";
|
|
4925
|
+
|
|
4926
|
+
// src/notes/owner-key.ts
|
|
4927
|
+
var FIELD_MODULUS = BigInt(
|
|
4928
|
+
"21888242871839275222246405745257275088548364400416034343698204186575808495617"
|
|
4929
|
+
);
|
|
4930
|
+
async function assertOwnerUtxoKeypair(keypair, label = "ownerUtxoKeypair") {
|
|
4931
|
+
if (!keypair || typeof keypair !== "object") {
|
|
4932
|
+
throw new Error(
|
|
4933
|
+
`${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.`
|
|
4934
|
+
);
|
|
4935
|
+
}
|
|
4936
|
+
const { privateKey, publicKey } = keypair;
|
|
4937
|
+
if (typeof privateKey !== "bigint" || privateKey <= 0n || privateKey >= FIELD_MODULUS) {
|
|
4938
|
+
throw new Error(`${label}.privateKey must be a non-zero field element (bigint)`);
|
|
4939
|
+
}
|
|
4940
|
+
if (typeof publicKey !== "bigint" || publicKey === 0n) {
|
|
4941
|
+
throw new Error(`${label}.publicKey must be a non-zero bigint`);
|
|
4942
|
+
}
|
|
4943
|
+
if (await derivePublicKey(privateKey) !== publicKey) {
|
|
4944
|
+
throw new Error(`${label}.publicKey is not derived from ${label}.privateKey`);
|
|
4945
|
+
}
|
|
4946
|
+
return { privateKey, publicKey };
|
|
4947
|
+
}
|
|
4948
|
+
function normalizeOwnerPublicKey(publicKey, label) {
|
|
4949
|
+
if (publicKey === void 0 || publicKey === null) return void 0;
|
|
4950
|
+
if (typeof publicKey !== "bigint" || publicKey <= 0n || publicKey >= FIELD_MODULUS) {
|
|
4951
|
+
throw new Error(`${label} must be a non-zero field element (bigint)`);
|
|
4952
|
+
}
|
|
4953
|
+
return publicKey;
|
|
4954
|
+
}
|
|
4955
|
+
|
|
4956
|
+
// src/notes/swap-refund.ts
|
|
4883
4957
|
var bs582 = _bs582.default || _bs582;
|
|
4884
4958
|
var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
|
|
4885
|
-
var
|
|
4959
|
+
var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
|
|
4886
4960
|
var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
|
|
4887
4961
|
function normalizeNullifier(inputNullifier) {
|
|
4888
4962
|
if (inputNullifier instanceof Uint8Array) {
|
|
@@ -4916,13 +4990,29 @@ function derive(nk, nullifier, info) {
|
|
|
4916
4990
|
preimage.set(info, off);
|
|
4917
4991
|
return blake33(preimage);
|
|
4918
4992
|
}
|
|
4919
|
-
|
|
4993
|
+
function assertNk(viewingKeyNk) {
|
|
4920
4994
|
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
4921
4995
|
throw new Error("viewingKeyNk must be 32 bytes");
|
|
4922
4996
|
}
|
|
4997
|
+
return viewingKeyNk;
|
|
4998
|
+
}
|
|
4999
|
+
function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
|
|
5000
|
+
const nk = assertNk(viewingKeyNk);
|
|
5001
|
+
return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
|
|
5002
|
+
}
|
|
5003
|
+
async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
|
|
5004
|
+
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
5005
|
+
const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
5006
|
+
if (owner.publicKey === 0n || blinding === 0n) {
|
|
5007
|
+
throw new Error("refund authorization is degenerate");
|
|
5008
|
+
}
|
|
5009
|
+
return { privateKey: owner.privateKey, publicKey: owner.publicKey, blinding };
|
|
5010
|
+
}
|
|
5011
|
+
async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
|
|
5012
|
+
const nk = assertNk(viewingKeyNk);
|
|
4923
5013
|
const nullifier = normalizeNullifier(inputNullifier);
|
|
4924
|
-
const privateKey = toFieldSecret(derive(
|
|
4925
|
-
const blinding = toFieldSecret(derive(
|
|
5014
|
+
const privateKey = toFieldSecret(derive(nk, nullifier, LEGACY_REFUND_PRIVATE_KEY_INFO));
|
|
5015
|
+
const blinding = toFieldSecret(derive(nk, nullifier, REFUND_BLINDING_INFO));
|
|
4926
5016
|
const publicKey = await derivePublicKey(privateKey);
|
|
4927
5017
|
if (publicKey === 0n || blinding === 0n) {
|
|
4928
5018
|
throw new Error("derived refund authorization is degenerate");
|
|
@@ -4940,19 +5030,39 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
|
|
|
4940
5030
|
async function matchSwapRefundLeaf(params) {
|
|
4941
5031
|
const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
|
|
4942
5032
|
const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
|
|
4943
|
-
let
|
|
5033
|
+
let blinding;
|
|
4944
5034
|
try {
|
|
4945
|
-
|
|
5035
|
+
blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
4946
5036
|
} catch {
|
|
4947
5037
|
return null;
|
|
4948
5038
|
}
|
|
4949
|
-
const
|
|
4950
|
-
if (
|
|
5039
|
+
const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
|
|
5040
|
+
if (ownerPub !== void 0) {
|
|
5041
|
+
const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
|
|
5042
|
+
if (candidate === expected) {
|
|
5043
|
+
return {
|
|
5044
|
+
keypair: { privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n, publicKey: ownerPub },
|
|
5045
|
+
blinding,
|
|
5046
|
+
amount: amountAfterFee,
|
|
5047
|
+
commitment: candidate,
|
|
5048
|
+
legacyExposed: false
|
|
5049
|
+
};
|
|
5050
|
+
}
|
|
5051
|
+
}
|
|
5052
|
+
let legacy;
|
|
5053
|
+
try {
|
|
5054
|
+
legacy = await deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier);
|
|
5055
|
+
} catch {
|
|
5056
|
+
return null;
|
|
5057
|
+
}
|
|
5058
|
+
const legacyCandidate = await computeSwapRefundCommitment(amountAfterFee, legacy.publicKey, legacy.blinding);
|
|
5059
|
+
if (legacyCandidate !== expected) return null;
|
|
4951
5060
|
return {
|
|
4952
|
-
keypair: { privateKey:
|
|
4953
|
-
blinding:
|
|
5061
|
+
keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
|
|
5062
|
+
blinding: legacy.blinding,
|
|
4954
5063
|
amount: amountAfterFee,
|
|
4955
|
-
commitment:
|
|
5064
|
+
commitment: legacyCandidate,
|
|
5065
|
+
legacyExposed: true
|
|
4956
5066
|
};
|
|
4957
5067
|
}
|
|
4958
5068
|
var TRANSACT_SWAP_TAG2 = 1;
|
|
@@ -5016,10 +5126,16 @@ function instructionsForProgram(tx, accountKeys, programIdBase58) {
|
|
|
5016
5126
|
if (Array.isArray(inner)) for (const block of inner) take(block?.instructions);
|
|
5017
5127
|
return out;
|
|
5018
5128
|
}
|
|
5019
|
-
async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
5129
|
+
async function discoverSwapRefunds(connection, programId, viewingKeyNk, options) {
|
|
5020
5130
|
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
5021
5131
|
throw new Error("viewingKeyNk must be 32 bytes");
|
|
5022
5132
|
}
|
|
5133
|
+
if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
|
|
5134
|
+
throw new Error(
|
|
5135
|
+
"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."
|
|
5136
|
+
);
|
|
5137
|
+
}
|
|
5138
|
+
const ownerUtxoKeypair = options.ownerUtxoKeypair;
|
|
5023
5139
|
const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
|
|
5024
5140
|
const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
|
|
5025
5141
|
const programIdBase58 = programId;
|
|
@@ -5094,7 +5210,8 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
|
5094
5210
|
viewingKeyNk,
|
|
5095
5211
|
inputNullifier: candidate.nullifier,
|
|
5096
5212
|
amountAfterFee: event.amountAfterFee,
|
|
5097
|
-
commitment: event.commitmentField
|
|
5213
|
+
commitment: event.commitmentField,
|
|
5214
|
+
ownerUtxoKeypair
|
|
5098
5215
|
});
|
|
5099
5216
|
if (!recovered) continue;
|
|
5100
5217
|
const dedupe = `${close.signature}:${event.leafIndex}`;
|
|
@@ -5118,7 +5235,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
|
5118
5235
|
// src/notes/deposit-note.ts
|
|
5119
5236
|
import { blake3 as blake34 } from "@noble/hashes/blake3";
|
|
5120
5237
|
var DEPOSIT_NOTE_DOMAIN = new TextEncoder().encode("cloak_deposit_note_v1");
|
|
5121
|
-
var
|
|
5238
|
+
var LEGACY_DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
|
|
5122
5239
|
var DEPOSIT_BLINDING_INFO = new TextEncoder().encode("blinding");
|
|
5123
5240
|
var CHAIN_NOTE_SALT_BITS = 96;
|
|
5124
5241
|
var MAX_CHAIN_NOTE_SALT = (1n << BigInt(CHAIN_NOTE_SALT_BITS)) - 1n;
|
|
@@ -5154,30 +5271,47 @@ function derive2(nk, salt, info) {
|
|
|
5154
5271
|
preimage.set(info, off);
|
|
5155
5272
|
return blake34(preimage);
|
|
5156
5273
|
}
|
|
5274
|
+
function assertNk2(viewingKeyNk) {
|
|
5275
|
+
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
5276
|
+
throw new Error("viewingKeyNk must be 32 bytes");
|
|
5277
|
+
}
|
|
5278
|
+
return viewingKeyNk;
|
|
5279
|
+
}
|
|
5157
5280
|
function randomDepositNoteSalt() {
|
|
5158
5281
|
const bytes = randomBytes(12);
|
|
5159
5282
|
let v = 0n;
|
|
5160
5283
|
for (const b of bytes) v = v << 8n | BigInt(b);
|
|
5161
5284
|
return v === 0n ? 1n : v;
|
|
5162
5285
|
}
|
|
5163
|
-
|
|
5164
|
-
|
|
5165
|
-
|
|
5166
|
-
|
|
5286
|
+
function deriveDepositNoteBlinding(viewingKeyNk, noteSalt) {
|
|
5287
|
+
const nk = assertNk2(viewingKeyNk);
|
|
5288
|
+
return toFieldSecret2(derive2(nk, saltToBytes(noteSalt), DEPOSIT_BLINDING_INFO));
|
|
5289
|
+
}
|
|
5290
|
+
async function deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt) {
|
|
5291
|
+
const nk = assertNk2(viewingKeyNk);
|
|
5167
5292
|
const salt = saltToBytes(noteSalt);
|
|
5168
|
-
const privateKey = toFieldSecret2(derive2(
|
|
5169
|
-
const blinding = toFieldSecret2(derive2(
|
|
5293
|
+
const privateKey = toFieldSecret2(derive2(nk, salt, LEGACY_DEPOSIT_PRIVATE_KEY_INFO));
|
|
5294
|
+
const blinding = toFieldSecret2(derive2(nk, salt, DEPOSIT_BLINDING_INFO));
|
|
5170
5295
|
const publicKey = await derivePublicKey(privateKey);
|
|
5171
5296
|
if (publicKey === 0n || blinding === 0n) {
|
|
5172
5297
|
throw new Error("derived deposit note secrets are degenerate");
|
|
5173
5298
|
}
|
|
5174
5299
|
return { keypair: { privateKey, publicKey }, blinding };
|
|
5175
5300
|
}
|
|
5176
|
-
async function createRecoverableDepositUtxo(
|
|
5301
|
+
async function createRecoverableDepositUtxo(params) {
|
|
5302
|
+
if (!params || typeof params !== "object" || params instanceof Uint8Array) {
|
|
5303
|
+
throw new Error(
|
|
5304
|
+
"createRecoverableDepositUtxo takes one options object: { amount, viewingKeyNk, ownerUtxoKeypair, mintAddress?, noteSalt? }"
|
|
5305
|
+
);
|
|
5306
|
+
}
|
|
5307
|
+
const { amount, viewingKeyNk } = params;
|
|
5177
5308
|
if (typeof amount !== "bigint" || amount <= 0n) {
|
|
5178
5309
|
throw new Error("amount must be a positive bigint");
|
|
5179
5310
|
}
|
|
5180
|
-
const
|
|
5311
|
+
const keypair = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
|
|
5312
|
+
const mintAddress = params.mintAddress ?? NATIVE_SOL_MINT;
|
|
5313
|
+
const noteSalt = params.noteSalt ?? randomDepositNoteSalt();
|
|
5314
|
+
const blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
|
|
5181
5315
|
const utxo = { amount, keypair, blinding, mintAddress };
|
|
5182
5316
|
utxo.commitment = await computeCommitment(utxo);
|
|
5183
5317
|
return { utxo, noteSalt };
|
|
@@ -5192,21 +5326,46 @@ function normalizeCommitment(value) {
|
|
|
5192
5326
|
async function matchDepositNote(params) {
|
|
5193
5327
|
const { viewingKeyNk, noteSalt, amount, mintAddress, outputCommitments } = params;
|
|
5194
5328
|
if (typeof amount !== "bigint" || amount <= 0n) return null;
|
|
5195
|
-
let
|
|
5329
|
+
let blinding;
|
|
5330
|
+
try {
|
|
5331
|
+
blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
|
|
5332
|
+
} catch {
|
|
5333
|
+
return null;
|
|
5334
|
+
}
|
|
5335
|
+
const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
|
|
5336
|
+
if (published.length === 0) return null;
|
|
5337
|
+
const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
|
|
5338
|
+
if (ownerPub !== void 0) {
|
|
5339
|
+
const keypair = {
|
|
5340
|
+
privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n,
|
|
5341
|
+
publicKey: ownerPub
|
|
5342
|
+
};
|
|
5343
|
+
const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
|
|
5344
|
+
if (published.some((value) => value === candidate)) {
|
|
5345
|
+
return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed: false };
|
|
5346
|
+
}
|
|
5347
|
+
}
|
|
5348
|
+
let legacy;
|
|
5196
5349
|
try {
|
|
5197
|
-
|
|
5350
|
+
legacy = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
|
|
5198
5351
|
} catch {
|
|
5199
5352
|
return null;
|
|
5200
5353
|
}
|
|
5201
|
-
const
|
|
5354
|
+
const legacyCandidate = await computeCommitment({
|
|
5202
5355
|
amount,
|
|
5203
|
-
keypair:
|
|
5204
|
-
blinding:
|
|
5356
|
+
keypair: legacy.keypair,
|
|
5357
|
+
blinding: legacy.blinding,
|
|
5205
5358
|
mintAddress
|
|
5206
5359
|
});
|
|
5207
|
-
|
|
5208
|
-
|
|
5209
|
-
|
|
5360
|
+
if (!published.some((value) => value === legacyCandidate)) return null;
|
|
5361
|
+
return {
|
|
5362
|
+
...legacy,
|
|
5363
|
+
amount,
|
|
5364
|
+
mintAddress,
|
|
5365
|
+
commitment: legacyCandidate,
|
|
5366
|
+
noteSalt,
|
|
5367
|
+
legacyExposed: true
|
|
5368
|
+
};
|
|
5210
5369
|
}
|
|
5211
5370
|
|
|
5212
5371
|
// src/notes/change-note.ts
|
|
@@ -5262,10 +5421,11 @@ function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
|
|
|
5262
5421
|
preimage.set(CHANGE_BLINDING_INFO, off);
|
|
5263
5422
|
return toFieldSecret3(blake35(preimage));
|
|
5264
5423
|
}
|
|
5265
|
-
async function createRecoverableChangeUtxo(amount,
|
|
5424
|
+
async function createRecoverableChangeUtxo(amount, ownerUtxoKeypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
|
|
5266
5425
|
if (typeof amount !== "bigint" || amount <= 0n) {
|
|
5267
5426
|
throw new Error("amount must be a positive bigint");
|
|
5268
5427
|
}
|
|
5428
|
+
const keypair = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
5269
5429
|
const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
|
|
5270
5430
|
const utxo = { amount, keypair, blinding, mintAddress };
|
|
5271
5431
|
utxo.commitment = await computeCommitment(utxo);
|
|
@@ -5291,13 +5451,27 @@ async function matchChangeNote(params) {
|
|
|
5291
5451
|
const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
|
|
5292
5452
|
const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
|
|
5293
5453
|
if (!published.some((value) => value === candidate)) return null;
|
|
5294
|
-
|
|
5454
|
+
const walletKey = normalizeOwnerPublicKey(params.ownerUtxoPublicKey, "ownerUtxoPublicKey");
|
|
5455
|
+
const legacyExposed = walletKey !== void 0 && keypair.publicKey !== walletKey;
|
|
5456
|
+
return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed };
|
|
5295
5457
|
}
|
|
5296
5458
|
|
|
5297
5459
|
// src/flows/transact.ts
|
|
5298
5460
|
import { buildPoseidon as buildPoseidon2 } from "circomlibjs";
|
|
5299
5461
|
import nacl5 from "tweetnacl";
|
|
5300
5462
|
|
|
5463
|
+
// src/relay/chain-note-time.ts
|
|
5464
|
+
async function relayChainNoteTimestampMs(relayUrl) {
|
|
5465
|
+
if (relayUrl && !hasRelayClockSample()) {
|
|
5466
|
+
try {
|
|
5467
|
+
const response = await relayFetch(`${relayUrl.replace(/\/$/, "")}/health`);
|
|
5468
|
+
await response.body?.cancel?.().catch(() => void 0);
|
|
5469
|
+
} catch {
|
|
5470
|
+
}
|
|
5471
|
+
}
|
|
5472
|
+
return BigInt(relayNowMs());
|
|
5473
|
+
}
|
|
5474
|
+
|
|
5301
5475
|
// src/proving/artifacts.ts
|
|
5302
5476
|
import { sha256 as sha2564 } from "@noble/hashes/sha2";
|
|
5303
5477
|
|
|
@@ -5934,6 +6108,33 @@ function parseNkInput(input) {
|
|
|
5934
6108
|
}
|
|
5935
6109
|
return Uint8Array.from(Buffer.from(clean, "hex"));
|
|
5936
6110
|
}
|
|
6111
|
+
async function resolveWalletNk(options) {
|
|
6112
|
+
const explicit = await resolveChainNoteNk(options);
|
|
6113
|
+
if (explicit) return explicit;
|
|
6114
|
+
if (options.ownerUtxoKeypair) {
|
|
6115
|
+
const owner = await assertOwnerUtxoKeypair(options.ownerUtxoKeypair);
|
|
6116
|
+
return getNkFromUtxoPrivateKey(owner.privateKey);
|
|
6117
|
+
}
|
|
6118
|
+
return null;
|
|
6119
|
+
}
|
|
6120
|
+
function missingWalletNkError(flow) {
|
|
6121
|
+
return new Error(
|
|
6122
|
+
`${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.`
|
|
6123
|
+
);
|
|
6124
|
+
}
|
|
6125
|
+
async function requireWalletNk(options, flow) {
|
|
6126
|
+
const nk = await resolveWalletNk(options);
|
|
6127
|
+
if (nk) return nk;
|
|
6128
|
+
throw missingWalletNkError(flow);
|
|
6129
|
+
}
|
|
6130
|
+
async function requireOwnerUtxoKeypair(options, flow) {
|
|
6131
|
+
if (!options.ownerUtxoKeypair) {
|
|
6132
|
+
throw new Error(
|
|
6133
|
+
`${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].`
|
|
6134
|
+
);
|
|
6135
|
+
}
|
|
6136
|
+
return assertOwnerUtxoKeypair(options.ownerUtxoKeypair, "options.ownerUtxoKeypair");
|
|
6137
|
+
}
|
|
5937
6138
|
async function resolveChainNoteNk(options) {
|
|
5938
6139
|
if (options.chainNoteViewingKeyNk) {
|
|
5939
6140
|
return parseNkInput(options.chainNoteViewingKeyNk);
|
|
@@ -5951,7 +6152,7 @@ function shouldDefaultUseUniqueNullifiers(_connection) {
|
|
|
5951
6152
|
function toHex(bytes) {
|
|
5952
6153
|
return Buffer.from(bytes).toString("hex");
|
|
5953
6154
|
}
|
|
5954
|
-
async function ensureViewingKeyRegistered(options, onProgress,
|
|
6155
|
+
async function ensureViewingKeyRegistered(options, onProgress, walletNk) {
|
|
5955
6156
|
if (options.enforceViewingKeyRegistration === false) {
|
|
5956
6157
|
return;
|
|
5957
6158
|
}
|
|
@@ -5965,7 +6166,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
|
|
|
5965
6166
|
"Viewing key registration is mandatory: walletPublicKey or depositor public key is required."
|
|
5966
6167
|
);
|
|
5967
6168
|
}
|
|
5968
|
-
const nk =
|
|
6169
|
+
const nk = walletNk;
|
|
5969
6170
|
if (!nk || nk.length !== 32) {
|
|
5970
6171
|
throw new Error(
|
|
5971
6172
|
"Viewing key registration is mandatory: provide a chain-note viewing key (nk)."
|
|
@@ -6107,10 +6308,10 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
|
|
|
6107
6308
|
result.set(bigintToBytes322(BigInt(publicSignals[0])), offset);
|
|
6108
6309
|
offset += 32;
|
|
6109
6310
|
let amount = BigInt(publicSignals[1]);
|
|
6110
|
-
const
|
|
6111
|
-
const HALF_FIELD =
|
|
6311
|
+
const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
|
|
6312
|
+
const HALF_FIELD = FIELD_MODULUS2 / BigInt(2);
|
|
6112
6313
|
if (amount > HALF_FIELD) {
|
|
6113
|
-
amount = amount -
|
|
6314
|
+
amount = amount - FIELD_MODULUS2;
|
|
6114
6315
|
}
|
|
6115
6316
|
const amountBytes = new Uint8Array(8);
|
|
6116
6317
|
let amountValue = amount;
|
|
@@ -7057,8 +7258,9 @@ function chargeWalletApproval(used, budget, lastError) {
|
|
|
7057
7258
|
}
|
|
7058
7259
|
return used + 1;
|
|
7059
7260
|
}
|
|
7060
|
-
function relayFailureMessage(prefix, responseText) {
|
|
7061
|
-
const
|
|
7261
|
+
function relayFailureMessage(prefix, responseText, requestBody) {
|
|
7262
|
+
const carriedAffiliateCode = typeof requestBody?.affiliate_code === "string";
|
|
7263
|
+
const explanation = explainRelayAuthRejection(responseText, { carriedAffiliateCode });
|
|
7062
7264
|
return explanation ? `${prefix}: ${responseText}
|
|
7063
7265
|
|
|
7064
7266
|
${explanation}` : `${prefix}: ${responseText}`;
|
|
@@ -7436,6 +7638,7 @@ async function submitTransactToRelay(args) {
|
|
|
7436
7638
|
body: requestPayload,
|
|
7437
7639
|
signal: controller.signal
|
|
7438
7640
|
});
|
|
7641
|
+
observeRelayClock(response);
|
|
7439
7642
|
} finally {
|
|
7440
7643
|
clearTimeout(timeoutId);
|
|
7441
7644
|
}
|
|
@@ -7466,7 +7669,9 @@ async function submitTransactToRelay(args) {
|
|
|
7466
7669
|
onProgress?.("Root not found (stale), will regenerate proof with fresh tree...");
|
|
7467
7670
|
return { kind: "stale-root", error: new Error(`Relay error: ${responseText}`) };
|
|
7468
7671
|
}
|
|
7469
|
-
return await resolveFailure(
|
|
7672
|
+
return await resolveFailure(
|
|
7673
|
+
new Error(relayFailureMessage("Relay error", responseText, requestBody))
|
|
7674
|
+
);
|
|
7470
7675
|
}
|
|
7471
7676
|
const apiResponse = JSON.parse(responseText);
|
|
7472
7677
|
if (!apiResponse.success || !apiResponse.data) {
|
|
@@ -7483,7 +7688,7 @@ async function submitTransactToRelay(args) {
|
|
|
7483
7688
|
return { kind: "stale-root", error: new Error(`Relay returned error: ${errorStr}`) };
|
|
7484
7689
|
}
|
|
7485
7690
|
return await resolveFailure(
|
|
7486
|
-
new Error(relayFailureMessage("Relay returned error", errorStr))
|
|
7691
|
+
new Error(relayFailureMessage("Relay returned error", errorStr, requestBody))
|
|
7487
7692
|
);
|
|
7488
7693
|
}
|
|
7489
7694
|
const result = apiResponse.data;
|
|
@@ -7591,34 +7796,37 @@ async function transact(params, options) {
|
|
|
7591
7796
|
);
|
|
7592
7797
|
}
|
|
7593
7798
|
onProgress?.("Validating transaction parameters...");
|
|
7594
|
-
const
|
|
7595
|
-
const
|
|
7596
|
-
|
|
7597
|
-
const explicitChainNoteNk = await resolveChainNoteNk(options);
|
|
7598
|
-
if (options.chainNoteSalt !== void 0 && !explicitChainNoteNk) {
|
|
7799
|
+
const walletNk = await resolveWalletNk(options);
|
|
7800
|
+
const ownerUtxoKeypair = options.ownerUtxoKeypair ? await assertOwnerUtxoKeypair(options.ownerUtxoKeypair) : void 0;
|
|
7801
|
+
if (options.chainNoteSalt !== void 0 && !walletNk) {
|
|
7599
7802
|
throw new Error(
|
|
7600
|
-
"options.chainNoteSalt requires
|
|
7803
|
+
"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."
|
|
7601
7804
|
);
|
|
7602
7805
|
}
|
|
7603
7806
|
const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
|
|
7604
7807
|
const chainNoteWillCarrySalt = !options.disableChainNotes && !(options.encryptedNotes && options.encryptedNotes.length > 0);
|
|
7605
|
-
if (
|
|
7606
|
-
|
|
7808
|
+
if (!walletNk && (chainNoteWillCarrySalt || options.enforceViewingKeyRegistration !== false)) {
|
|
7809
|
+
throw missingWalletNkError("transact");
|
|
7810
|
+
}
|
|
7811
|
+
if (walletNk && chainNoteWillCarrySalt) {
|
|
7812
|
+
const selfOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
|
|
7813
|
+
if (ownerUtxoKeypair) selfOwners.add(ownerUtxoKeypair.publicKey);
|
|
7814
|
+
const depositBlinding = deriveDepositNoteBlinding(walletNk, chainNoteSalt);
|
|
7607
7815
|
for (let i = 0; i < outputUtxos.length; i++) {
|
|
7608
7816
|
const out = outputUtxos[i];
|
|
7609
7817
|
if (!out || out.amount <= BigInt(0)) continue;
|
|
7610
|
-
if (!
|
|
7611
|
-
if (out.blinding !== deriveChangeNoteBlinding(
|
|
7818
|
+
if (!selfOwners.has(out.keypair.publicKey)) continue;
|
|
7819
|
+
if (out.blinding !== deriveChangeNoteBlinding(walletNk, chainNoteSalt, i) && out.blinding !== depositBlinding) {
|
|
7612
7820
|
throw new Error(
|
|
7613
|
-
`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.`
|
|
7821
|
+
`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.`
|
|
7614
7822
|
);
|
|
7615
7823
|
}
|
|
7616
7824
|
}
|
|
7617
7825
|
}
|
|
7618
7826
|
assertAllowedRpcConnection(connection);
|
|
7619
7827
|
assertInputMints(inputUtxos, options.expectedMint);
|
|
7620
|
-
await ensureViewingKeyRegistered(options, onProgress,
|
|
7621
|
-
const resolvedChainNoteNk =
|
|
7828
|
+
await ensureViewingKeyRegistered(options, onProgress, walletNk);
|
|
7829
|
+
const resolvedChainNoteNk = walletNk;
|
|
7622
7830
|
if (inputUtxos.length > 2) {
|
|
7623
7831
|
throw new Error("Maximum 2 input UTXOs allowed");
|
|
7624
7832
|
}
|
|
@@ -7992,7 +8200,7 @@ async function transact(params, options) {
|
|
|
7992
8200
|
}
|
|
7993
8201
|
const maxFee = isWithdrawal ? protocolFeeSnapshot : BigInt(0);
|
|
7994
8202
|
const extDataHash = await computeExtDataHash(recipient ?? null, relayerFee, relayer ?? null, maxFee);
|
|
7995
|
-
const chainNoteTimestamp =
|
|
8203
|
+
const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
|
|
7996
8204
|
const mintField = pubkeyToFieldElement(mint);
|
|
7997
8205
|
let signature = "pending-" + Date.now().toString();
|
|
7998
8206
|
let commitmentIndices = [-1, -1];
|
|
@@ -8088,9 +8296,9 @@ async function transact(params, options) {
|
|
|
8088
8296
|
]));
|
|
8089
8297
|
const noteTailHash = poseidonHasher.F.toObject(poseidonHasher([chainNoteTimestamp, noteCommitment, chainNoteSalt, noteSemantics]));
|
|
8090
8298
|
const chainNoteHash = poseidonHasher.F.toObject(poseidonHasher([CHAIN_NOTE_DOMAIN_TAG, CHAIN_NOTE_TAG, amountDataHash, noteTailHash]));
|
|
8091
|
-
const
|
|
8092
|
-
if (chainNoteHash >=
|
|
8093
|
-
throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${
|
|
8299
|
+
const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
|
|
8300
|
+
if (chainNoteHash >= FIELD_MODULUS2) {
|
|
8301
|
+
throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS2.toString()}`);
|
|
8094
8302
|
}
|
|
8095
8303
|
const pathElementsTotal = inPathElements.reduce((sum, arr) => sum + arr.length, 0);
|
|
8096
8304
|
const totalInputs = 1 + // root
|
|
@@ -8512,7 +8720,8 @@ async function transact(params, options) {
|
|
|
8512
8720
|
throw lastError;
|
|
8513
8721
|
}
|
|
8514
8722
|
const classified = classifyRelayError(lastError.message);
|
|
8515
|
-
const
|
|
8723
|
+
const isDepositSubmission = externalAmount > BigInt(0);
|
|
8724
|
+
const isMerkleClass = !isDepositSubmission && !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
|
|
8516
8725
|
if (canRebuildMerkleTreeFromChain() && isMerkleClass && relayUrl) {
|
|
8517
8726
|
onProgress?.(
|
|
8518
8727
|
"All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
|
|
@@ -8661,54 +8870,83 @@ async function transact(params, options) {
|
|
|
8661
8870
|
};
|
|
8662
8871
|
}
|
|
8663
8872
|
async function transfer(inputUtxos, recipientPubkey, amount, options) {
|
|
8873
|
+
const owner = await requireOwnerUtxoKeypair(options, "transfer");
|
|
8874
|
+
const transferNk = await requireWalletNk(options, "transfer");
|
|
8664
8875
|
const inputSum = sumUtxoAmounts(inputUtxos);
|
|
8665
8876
|
if (inputSum < amount) {
|
|
8666
8877
|
throw new Error(`Insufficient funds: have ${inputSum}, need ${amount}`);
|
|
8667
8878
|
}
|
|
8668
8879
|
const change = inputSum - amount;
|
|
8669
|
-
const myKeypair = inputUtxos[0].keypair;
|
|
8670
8880
|
const mint = inputUtxos[0].mintAddress;
|
|
8671
|
-
|
|
8672
|
-
|
|
8673
|
-
|
|
8881
|
+
let spendInputs = [
|
|
8882
|
+
...inputUtxos.filter((u) => u.keypair.publicKey === owner.publicKey),
|
|
8883
|
+
...inputUtxos.filter((u) => u.keypair.publicKey !== owner.publicKey)
|
|
8884
|
+
];
|
|
8885
|
+
let spendOptions = options;
|
|
8886
|
+
if (change > BigInt(0) && spendInputs[0].keypair.publicKey !== owner.publicKey) {
|
|
8887
|
+
if (spendInputs.length > 2) {
|
|
8888
|
+
throw new Error(
|
|
8889
|
+
`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.`
|
|
8890
|
+
);
|
|
8891
|
+
}
|
|
8892
|
+
if (options.relayAuthBatch) {
|
|
8893
|
+
throw new Error(
|
|
8894
|
+
"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."
|
|
8895
|
+
);
|
|
8896
|
+
}
|
|
8897
|
+
options.onProgress?.("Moving notes under the wallet key before the transfer...");
|
|
8898
|
+
const migrationSalt = randomChangeNoteSalt();
|
|
8899
|
+
const migrated = (await createRecoverableChangeUtxo(inputSum, owner, transferNk, mint, migrationSalt, 0)).utxo;
|
|
8900
|
+
const { recipientViewingPublicKey: _recipientViewingPublicKey, ...migrationOptions } = options;
|
|
8901
|
+
void _recipientViewingPublicKey;
|
|
8902
|
+
const migration = await transact(
|
|
8903
|
+
{ inputUtxos: spendInputs, outputUtxos: [migrated], externalAmount: BigInt(0) },
|
|
8904
|
+
{ ...migrationOptions, chainNoteSalt: migrationSalt }
|
|
8905
|
+
);
|
|
8906
|
+
const migratedNote = migration.outputUtxos?.[0] ?? migrated;
|
|
8907
|
+
if (migration.commitmentIndices?.[0] >= 0) {
|
|
8908
|
+
migratedNote.index = migration.commitmentIndices[0];
|
|
8909
|
+
}
|
|
8910
|
+
spendInputs = [migratedNote];
|
|
8911
|
+
spendOptions = { ...options, cachedMerkleTree: migration.merkleTree };
|
|
8912
|
+
}
|
|
8913
|
+
const changeNoteSalt = randomChangeNoteSalt();
|
|
8914
|
+
const isSendToSelf = recipientPubkey === owner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
|
|
8674
8915
|
const recipientKeypair = {
|
|
8675
8916
|
privateKey: BigInt(0),
|
|
8676
8917
|
// Recipient's private key unknown
|
|
8677
8918
|
publicKey: recipientPubkey
|
|
8678
8919
|
};
|
|
8679
|
-
const recipientUtxo =
|
|
8920
|
+
const recipientUtxo = isSendToSelf ? (await createRecoverableChangeUtxo(amount, owner, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
|
|
8680
8921
|
const outputUtxos = [recipientUtxo];
|
|
8681
8922
|
if (change > BigInt(0)) {
|
|
8682
|
-
|
|
8683
|
-
|
|
8684
|
-
|
|
8685
|
-
|
|
8686
|
-
|
|
8687
|
-
|
|
8688
|
-
|
|
8689
|
-
|
|
8690
|
-
|
|
8691
|
-
outputUtxos.push(utxo);
|
|
8692
|
-
} else {
|
|
8693
|
-
outputUtxos.push(await createUtxo(change, myKeypair, mint));
|
|
8694
|
-
}
|
|
8923
|
+
const { utxo } = await createRecoverableChangeUtxo(
|
|
8924
|
+
change,
|
|
8925
|
+
owner,
|
|
8926
|
+
transferNk,
|
|
8927
|
+
mint,
|
|
8928
|
+
changeNoteSalt,
|
|
8929
|
+
1
|
|
8930
|
+
);
|
|
8931
|
+
outputUtxos.push(utxo);
|
|
8695
8932
|
}
|
|
8696
8933
|
return transact(
|
|
8697
8934
|
{
|
|
8698
|
-
inputUtxos,
|
|
8935
|
+
inputUtxos: spendInputs,
|
|
8699
8936
|
outputUtxos,
|
|
8700
8937
|
externalAmount: BigInt(0)
|
|
8701
8938
|
// Pure shield-to-shield
|
|
8702
8939
|
},
|
|
8703
|
-
|
|
8940
|
+
{ ...spendOptions, chainNoteSalt: changeNoteSalt }
|
|
8704
8941
|
);
|
|
8705
8942
|
}
|
|
8706
8943
|
async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
8944
|
+
const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
|
|
8945
|
+
const walletNk = await requireWalletNk(options, "partialWithdraw");
|
|
8707
8946
|
const inputSum = sumUtxoAmounts(inputUtxos);
|
|
8708
8947
|
if (inputSum < withdrawAmount) {
|
|
8709
8948
|
throw new Error(`Insufficient funds: have ${inputSum}, need ${withdrawAmount}`);
|
|
8710
8949
|
}
|
|
8711
|
-
const myKeypair = inputUtxos[0].keypair;
|
|
8712
8950
|
const mint = inputUtxos[0].mintAddress;
|
|
8713
8951
|
let utxos = [...inputUtxos];
|
|
8714
8952
|
let cachedTree = options.cachedMerkleTree;
|
|
@@ -8717,9 +8955,8 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
|
8717
8955
|
utxos.sort((a, b) => a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0);
|
|
8718
8956
|
const [small1, small2, ...rest] = utxos;
|
|
8719
8957
|
const mergedAmount = small1.amount + small2.amount;
|
|
8720
|
-
const
|
|
8721
|
-
const
|
|
8722
|
-
const mergedOutput = mergeNk ? (await createRecoverableChangeUtxo(mergedAmount, myKeypair, mergeNk, mint, mergeSalt, 0)).utxo : await createUtxo(mergedAmount, myKeypair, mint);
|
|
8958
|
+
const mergeSalt = randomChangeNoteSalt();
|
|
8959
|
+
const mergedOutput = (await createRecoverableChangeUtxo(mergedAmount, owner, walletNk, mint, mergeSalt, 0)).utxo;
|
|
8723
8960
|
const mergeResult = await transact(
|
|
8724
8961
|
{
|
|
8725
8962
|
inputUtxos: [small1, small2],
|
|
@@ -8730,7 +8967,7 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
|
8730
8967
|
{
|
|
8731
8968
|
...options,
|
|
8732
8969
|
cachedMerkleTree: cachedTree,
|
|
8733
|
-
|
|
8970
|
+
chainNoteSalt: mergeSalt
|
|
8734
8971
|
}
|
|
8735
8972
|
);
|
|
8736
8973
|
cachedTree = mergeResult.merkleTree;
|
|
@@ -8745,23 +8982,18 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
|
8745
8982
|
const outputUtxos = [];
|
|
8746
8983
|
let changeNoteSalt;
|
|
8747
8984
|
if (change > BigInt(0)) {
|
|
8748
|
-
const
|
|
8749
|
-
|
|
8750
|
-
|
|
8751
|
-
|
|
8752
|
-
|
|
8753
|
-
|
|
8754
|
-
|
|
8755
|
-
|
|
8756
|
-
|
|
8757
|
-
|
|
8758
|
-
|
|
8759
|
-
|
|
8760
|
-
outputUtxos.push(utxo);
|
|
8761
|
-
changeNoteSalt = salt;
|
|
8762
|
-
} else {
|
|
8763
|
-
outputUtxos.push(await createUtxo(change, myKeypair, mint));
|
|
8764
|
-
}
|
|
8985
|
+
const salt = randomChangeNoteSalt();
|
|
8986
|
+
const { utxo } = await createRecoverableChangeUtxo(
|
|
8987
|
+
change,
|
|
8988
|
+
owner,
|
|
8989
|
+
walletNk,
|
|
8990
|
+
mint,
|
|
8991
|
+
salt,
|
|
8992
|
+
0
|
|
8993
|
+
// partialWithdraw puts change at output 0
|
|
8994
|
+
);
|
|
8995
|
+
outputUtxos.push(utxo);
|
|
8996
|
+
changeNoteSalt = salt;
|
|
8765
8997
|
}
|
|
8766
8998
|
return transact(
|
|
8767
8999
|
{
|
|
@@ -8884,6 +9116,8 @@ async function swapUtxo(params, options) {
|
|
|
8884
9116
|
if (relayUrl) {
|
|
8885
9117
|
assertRelayAuthAvailable(relayAuthPlan, "private swap");
|
|
8886
9118
|
}
|
|
9119
|
+
const swapOwner = await requireOwnerUtxoKeypair(options, "swapUtxo");
|
|
9120
|
+
const resolvedSwapChainNoteNk = await requireWalletNk(options, "swapUtxo");
|
|
8887
9121
|
if (inputUtxos.length === 0) {
|
|
8888
9122
|
throw new Error("At least one input UTXO required");
|
|
8889
9123
|
}
|
|
@@ -8909,15 +9143,12 @@ async function swapUtxo(params, options) {
|
|
|
8909
9143
|
throw new Error(`Amount mismatch: input(${totalInputAmount}) != swap(${swapAmount}) + change(${changeAmount})`);
|
|
8910
9144
|
}
|
|
8911
9145
|
onProgress?.("Validating transaction parameters...");
|
|
8912
|
-
|
|
8913
|
-
await ensureViewingKeyRegistered(options, onProgress, swapFallbackNk);
|
|
8914
|
-
const explicitSwapChainNoteNk = await resolveChainNoteNk(options);
|
|
8915
|
-
const resolvedSwapChainNoteNk = explicitSwapChainNoteNk ?? swapFallbackNk;
|
|
9146
|
+
await ensureViewingKeyRegistered(options, onProgress, resolvedSwapChainNoteNk);
|
|
8916
9147
|
const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
|
|
8917
|
-
if (
|
|
8918
|
-
if (changeUtxo.blinding !== deriveChangeNoteBlinding(
|
|
9148
|
+
if (changeUtxo && changeUtxo.amount > BigInt(0) && (changeUtxo.keypair.publicKey === swapOwner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey))) {
|
|
9149
|
+
if (changeUtxo.blinding !== deriveChangeNoteBlinding(resolvedSwapChainNoteNk, chainNoteSalt, 0)) {
|
|
8919
9150
|
throw new Error(
|
|
8920
|
-
`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.`
|
|
9151
|
+
`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.`
|
|
8921
9152
|
);
|
|
8922
9153
|
}
|
|
8923
9154
|
}
|
|
@@ -8941,24 +9172,18 @@ async function swapUtxo(params, options) {
|
|
|
8941
9172
|
);
|
|
8942
9173
|
}
|
|
8943
9174
|
const externalAmount = -swapAmount;
|
|
8944
|
-
|
|
8945
|
-
|
|
8946
|
-
|
|
8947
|
-
|
|
8948
|
-
|
|
8949
|
-
|
|
8950
|
-
|
|
8951
|
-
|
|
8952
|
-
|
|
8953
|
-
|
|
8954
|
-
|
|
8955
|
-
|
|
8956
|
-
refundBlinding = randomFieldElement();
|
|
8957
|
-
}
|
|
8958
|
-
} else {
|
|
8959
|
-
refundKeypair = await generateUtxoKeypair();
|
|
8960
|
-
refundBlinding = randomFieldElement();
|
|
8961
|
-
}
|
|
9175
|
+
const refundNullifier = bigintToBytes322(await computeNullifier(paddedInputs[0]));
|
|
9176
|
+
const refundAuthorization = await deriveSwapRefundAuthorization(
|
|
9177
|
+
resolvedSwapChainNoteNk,
|
|
9178
|
+
refundNullifier,
|
|
9179
|
+
swapOwner
|
|
9180
|
+
);
|
|
9181
|
+
const refundKeypair = {
|
|
9182
|
+
privateKey: refundAuthorization.privateKey,
|
|
9183
|
+
publicKey: refundAuthorization.publicKey
|
|
9184
|
+
};
|
|
9185
|
+
const refundBlinding = refundAuthorization.blinding;
|
|
9186
|
+
const refundDerivedFromNk = true;
|
|
8962
9187
|
if (refundKeypair.publicKey === BigInt(0) || refundBlinding === BigInt(0)) {
|
|
8963
9188
|
throw new Error(
|
|
8964
9189
|
"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."
|
|
@@ -9284,7 +9509,7 @@ async function swapUtxo(params, options) {
|
|
|
9284
9509
|
for (const utxo of paddedOutputs) {
|
|
9285
9510
|
outputCommitments.push(await computeCommitment(utxo));
|
|
9286
9511
|
}
|
|
9287
|
-
const chainNoteTimestamp =
|
|
9512
|
+
const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
|
|
9288
9513
|
onProgress?.("Computing external data hash...");
|
|
9289
9514
|
const mint = swapPoolMint;
|
|
9290
9515
|
const mintField = pubkeyToFieldElement(mint);
|
|
@@ -9598,7 +9823,7 @@ async function swapUtxo(params, options) {
|
|
|
9598
9823
|
forceChainIndexing = !relayUrl;
|
|
9599
9824
|
continue;
|
|
9600
9825
|
}
|
|
9601
|
-
throw new Error(relayFailureMessage("Relay error", responseText));
|
|
9826
|
+
throw new Error(relayFailureMessage("Relay error", responseText, requestBody));
|
|
9602
9827
|
}
|
|
9603
9828
|
const apiResponse = JSON.parse(responseText);
|
|
9604
9829
|
if (!apiResponse.success || !apiResponse.data) {
|
|
@@ -9734,7 +9959,6 @@ async function swapUtxo(params, options) {
|
|
|
9734
9959
|
// V3-04: the refund-fallback secret (hex, 32-byte field elements). Persist to claim a timed-out
|
|
9735
9960
|
// swap; see the UtxoSwapResult.refund docs. amountAfterFee is read from on-chain SwapState.
|
|
9736
9961
|
refund: {
|
|
9737
|
-
privateKey: Buffer.from(bigintToBytes322(refundKeypair.privateKey)).toString("hex"),
|
|
9738
9962
|
publicKey: Buffer.from(bigintToBytes322(refundKeypair.publicKey)).toString("hex"),
|
|
9739
9963
|
blinding: Buffer.from(bigintToBytes322(refundBlinding)).toString("hex"),
|
|
9740
9964
|
derivedFromNk: refundDerivedFromNk
|
|
@@ -9742,6 +9966,7 @@ async function swapUtxo(params, options) {
|
|
|
9742
9966
|
};
|
|
9743
9967
|
}
|
|
9744
9968
|
async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
|
|
9969
|
+
const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
|
|
9745
9970
|
const totalInput = sumUtxoAmounts(inputUtxos);
|
|
9746
9971
|
const change = totalInput - swapAmount;
|
|
9747
9972
|
if (change < BigInt(0)) {
|
|
@@ -9750,16 +9975,11 @@ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta,
|
|
|
9750
9975
|
let changeUtxo;
|
|
9751
9976
|
let changeNoteSalt;
|
|
9752
9977
|
if (change > BigInt(0)) {
|
|
9753
|
-
const myKeypair = inputUtxos[0].keypair;
|
|
9754
9978
|
const mint = inputUtxos[0].mintAddress;
|
|
9755
|
-
const changeNk = await
|
|
9756
|
-
|
|
9757
|
-
|
|
9758
|
-
|
|
9759
|
-
changeNoteSalt = salt;
|
|
9760
|
-
} else {
|
|
9761
|
-
changeUtxo = await createUtxo(change, myKeypair, mint);
|
|
9762
|
-
}
|
|
9979
|
+
const changeNk = await requireWalletNk(options, "swapWithChange");
|
|
9980
|
+
const salt = randomChangeNoteSalt();
|
|
9981
|
+
changeUtxo = (await createRecoverableChangeUtxo(change, owner, changeNk, mint, salt, 0)).utxo;
|
|
9982
|
+
changeNoteSalt = salt;
|
|
9763
9983
|
}
|
|
9764
9984
|
return swapUtxo(
|
|
9765
9985
|
{
|
|
@@ -10082,7 +10302,7 @@ var RelayBatchAuthCoordinator = class {
|
|
|
10082
10302
|
throw new Error("Every item of a batch must target the same program id.");
|
|
10083
10303
|
}
|
|
10084
10304
|
}
|
|
10085
|
-
const nowSeconds =
|
|
10305
|
+
const nowSeconds = relayNowSeconds();
|
|
10086
10306
|
const preimages = waiting.map(
|
|
10087
10307
|
(w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
|
|
10088
10308
|
);
|
|
@@ -10520,7 +10740,7 @@ async function deriveDepositCandidate(viewingKeyNk, noteSalt) {
|
|
|
10520
10740
|
const cached = depositSecretsCache.get(key);
|
|
10521
10741
|
if (cached) return cached;
|
|
10522
10742
|
try {
|
|
10523
|
-
const secrets = await
|
|
10743
|
+
const secrets = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
|
|
10524
10744
|
if (depositSecretsCache.size >= 4096) {
|
|
10525
10745
|
const oldest = depositSecretsCache.keys().next();
|
|
10526
10746
|
if (!oldest.done) depositSecretsCache.delete(oldest.value);
|
|
@@ -11103,6 +11323,7 @@ async function scanTransactions(opts) {
|
|
|
11103
11323
|
} else {
|
|
11104
11324
|
const derived = await deriveDepositCandidate(viewingKeyNk, compactNote.noteSalt);
|
|
11105
11325
|
const candidateKeys = [
|
|
11326
|
+
opts.ownerUtxoPublicKey,
|
|
11106
11327
|
derived?.keypair.publicKey,
|
|
11107
11328
|
opts.ownUtxoPublicKey,
|
|
11108
11329
|
BigInt(0)
|
|
@@ -11156,6 +11377,7 @@ async function scanTransactions(opts) {
|
|
|
11156
11377
|
try {
|
|
11157
11378
|
const recoveredDeposit = await matchDepositNote({
|
|
11158
11379
|
viewingKeyNk,
|
|
11380
|
+
ownerUtxoKeypair: opts.ownerUtxoPublicKey !== void 0 ? { privateKey: 0n, publicKey: opts.ownerUtxoPublicKey } : void 0,
|
|
11159
11381
|
noteSalt: compactNote.noteSalt,
|
|
11160
11382
|
// Output 0's amount. For a shield with no inputs — the shape `transact` builds for a
|
|
11161
11383
|
// deposit — that is the public deposit amount. A deposit that also merged inputs
|
|
@@ -11190,7 +11412,8 @@ async function scanTransactions(opts) {
|
|
|
11190
11412
|
mintAddress: address(asset.mint),
|
|
11191
11413
|
outputIndex: 0,
|
|
11192
11414
|
// v4 describes output 0, which is where change lands
|
|
11193
|
-
outputCommitments: ixCtx.outputCommitments ?? []
|
|
11415
|
+
outputCommitments: ixCtx.outputCommitments ?? [],
|
|
11416
|
+
ownerUtxoPublicKey: opts.ownerUtxoPublicKey
|
|
11194
11417
|
});
|
|
11195
11418
|
if (recoveredChange) {
|
|
11196
11419
|
recoveredChangeNotes.push({
|
|
@@ -11300,6 +11523,17 @@ async function scanTransactions(opts) {
|
|
|
11300
11523
|
runningByAsset.set(key, running);
|
|
11301
11524
|
tx.runningBalance = running;
|
|
11302
11525
|
}
|
|
11526
|
+
const legacyKeys = /* @__PURE__ */ new Map();
|
|
11527
|
+
for (const note of recoveredDepositNotes) {
|
|
11528
|
+
if (note.legacyExposed) legacyKeys.set(note.keypair.publicKey, note.keypair.privateKey);
|
|
11529
|
+
}
|
|
11530
|
+
for (const change of recoveredChangeNotes) {
|
|
11531
|
+
const legacyPrivateKey = legacyKeys.get(change.keypair.publicKey);
|
|
11532
|
+
if (legacyPrivateKey !== void 0) {
|
|
11533
|
+
change.keypair = { privateKey: legacyPrivateKey, publicKey: change.keypair.publicKey };
|
|
11534
|
+
change.legacyExposed = true;
|
|
11535
|
+
}
|
|
11536
|
+
}
|
|
11303
11537
|
return {
|
|
11304
11538
|
transactions: txs,
|
|
11305
11539
|
summary: {
|
|
@@ -12034,7 +12268,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
12034
12268
|
})
|
|
12035
12269
|
});
|
|
12036
12270
|
const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
|
|
12037
|
-
if (
|
|
12271
|
+
if (relayNowSeconds() >= prepared.expires_at_unix) {
|
|
12038
12272
|
throw new Error(
|
|
12039
12273
|
"paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
|
|
12040
12274
|
);
|
|
@@ -12071,9 +12305,12 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
12071
12305
|
// src/bridge/derive.ts
|
|
12072
12306
|
import { hmac } from "@noble/hashes/hmac";
|
|
12073
12307
|
import { sha512 } from "@noble/hashes/sha512";
|
|
12308
|
+
import { blake3 as blake36 } from "@noble/hashes/blake3";
|
|
12074
12309
|
var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
|
|
12310
|
+
var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
|
|
12311
|
+
var BRIDGE_RECEIVER_KEY_DOMAIN = new TextEncoder().encode("cloak_bridge_receiver_key_v2");
|
|
12075
12312
|
var MAX_RECEIVER_INDEX = 1e4;
|
|
12076
|
-
|
|
12313
|
+
function assertReceiverIndex(index) {
|
|
12077
12314
|
if (!Number.isInteger(index) || index < 0) {
|
|
12078
12315
|
throw new Error(`index must be a non-negative integer, got ${index}`);
|
|
12079
12316
|
}
|
|
@@ -12082,6 +12319,26 @@ async function deriveBridgeReceiver(nk, index) {
|
|
|
12082
12319
|
`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.`
|
|
12083
12320
|
);
|
|
12084
12321
|
}
|
|
12322
|
+
}
|
|
12323
|
+
async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
|
|
12324
|
+
if (ownerUtxoKeypair instanceof Uint8Array) {
|
|
12325
|
+
throw new Error(
|
|
12326
|
+
"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."
|
|
12327
|
+
);
|
|
12328
|
+
}
|
|
12329
|
+
assertReceiverIndex(index);
|
|
12330
|
+
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
12331
|
+
const priv = bigintToBytes322(owner.privateKey);
|
|
12332
|
+
const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
|
|
12333
|
+
preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
|
|
12334
|
+
preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
|
|
12335
|
+
const key = blake36(preimage);
|
|
12336
|
+
const h = hmac(sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
|
|
12337
|
+
return signerFromSecretKey(h.slice(0, 32));
|
|
12338
|
+
}
|
|
12339
|
+
async function deriveLegacyBridgeReceiver(nk, index) {
|
|
12340
|
+
assertReceiverIndex(index);
|
|
12341
|
+
if (!nk || nk.length !== 32) throw new Error("nk must be 32 bytes");
|
|
12085
12342
|
const h = hmac(sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
|
|
12086
12343
|
return signerFromSecretKey(h.slice(0, 32));
|
|
12087
12344
|
}
|
|
@@ -12092,13 +12349,44 @@ import { TOKEN_PROGRAM_ADDRESS as TOKEN_PROGRAM_ADDRESS4, findAssociatedTokenPda
|
|
|
12092
12349
|
function describeError(err) {
|
|
12093
12350
|
return err instanceof Error ? err.message : String(err);
|
|
12094
12351
|
}
|
|
12095
|
-
async function listBridgeDeposits(rpc,
|
|
12352
|
+
async function listBridgeDeposits(rpc, ownerUtxoKeypair, opts) {
|
|
12353
|
+
if (ownerUtxoKeypair instanceof Uint8Array) {
|
|
12354
|
+
throw new Error(
|
|
12355
|
+
"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)."
|
|
12356
|
+
);
|
|
12357
|
+
}
|
|
12358
|
+
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
12359
|
+
const out = await scanReceivers(rpc, opts, (index) => deriveBridgeReceiver(owner, index), {
|
|
12360
|
+
legacyExposed: false
|
|
12361
|
+
});
|
|
12362
|
+
if (opts.includeLegacy === false) return out;
|
|
12363
|
+
const nks = [];
|
|
12364
|
+
const seen = /* @__PURE__ */ new Set();
|
|
12365
|
+
for (const nk of [getNkFromUtxoPrivateKey(owner.privateKey), ...opts.legacyViewingKeyNks ?? []]) {
|
|
12366
|
+
if (!(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
12367
|
+
throw new Error("legacyViewingKeyNks entries must be 32 bytes");
|
|
12368
|
+
}
|
|
12369
|
+
const key = Array.from(nk, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
12370
|
+
if (seen.has(key)) continue;
|
|
12371
|
+
seen.add(key);
|
|
12372
|
+
nks.push(nk);
|
|
12373
|
+
}
|
|
12374
|
+
for (const nk of nks) {
|
|
12375
|
+
const legacy = await scanReceivers(rpc, opts, (index) => deriveLegacyBridgeReceiver(nk, index), {
|
|
12376
|
+
legacyExposed: true,
|
|
12377
|
+
legacyViewingKeyNk: nk
|
|
12378
|
+
});
|
|
12379
|
+
out.push(...legacy);
|
|
12380
|
+
}
|
|
12381
|
+
return out;
|
|
12382
|
+
}
|
|
12383
|
+
async function scanReceivers(rpc, opts, receiverAt, provenance) {
|
|
12096
12384
|
const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
|
|
12097
12385
|
const stopAfterUnused = opts.stopAfterUnused ?? 5;
|
|
12098
12386
|
const out = [];
|
|
12099
12387
|
let consecutiveUnused = 0;
|
|
12100
12388
|
for (let index = 0; index < scanDepth; index++) {
|
|
12101
|
-
const kp = await
|
|
12389
|
+
const kp = await receiverAt(index);
|
|
12102
12390
|
const receiver = kp.address;
|
|
12103
12391
|
const [tokenAccount] = await findAssociatedTokenPda4({
|
|
12104
12392
|
mint: opts.mint,
|
|
@@ -12150,7 +12438,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
|
|
|
12150
12438
|
tokenBalance,
|
|
12151
12439
|
lamports,
|
|
12152
12440
|
shieldSignature,
|
|
12153
|
-
...indexReused ? { indexReused, shieldSignatures } : {}
|
|
12441
|
+
...indexReused ? { indexReused, shieldSignatures } : {},
|
|
12442
|
+
...provenance
|
|
12154
12443
|
});
|
|
12155
12444
|
} catch (err) {
|
|
12156
12445
|
out.push({
|
|
@@ -12160,7 +12449,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
|
|
|
12160
12449
|
state: "unknown",
|
|
12161
12450
|
tokenBalance: 0n,
|
|
12162
12451
|
lamports: 0n,
|
|
12163
|
-
error: describeError(err)
|
|
12452
|
+
error: describeError(err),
|
|
12453
|
+
...provenance
|
|
12164
12454
|
});
|
|
12165
12455
|
}
|
|
12166
12456
|
}
|
|
@@ -12315,7 +12605,12 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
|
|
|
12315
12605
|
const signMessage = (m) => signMessageBytes(R, m);
|
|
12316
12606
|
const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
|
|
12317
12607
|
const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
|
|
12318
|
-
const { utxo, noteSalt } = await createRecoverableDepositUtxo(
|
|
12608
|
+
const { utxo, noteSalt } = await createRecoverableDepositUtxo({
|
|
12609
|
+
amount,
|
|
12610
|
+
viewingKeyNk: nk,
|
|
12611
|
+
ownerUtxoKeypair: utxoKeypair,
|
|
12612
|
+
mintAddress: mint
|
|
12613
|
+
});
|
|
12319
12614
|
const zeroInput = await createZeroUtxo(mint);
|
|
12320
12615
|
const rBefore = (await rpc.getBalance(R.address).send()).value;
|
|
12321
12616
|
let result;
|
|
@@ -12334,6 +12629,7 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
|
|
|
12334
12629
|
signMessage,
|
|
12335
12630
|
chainNoteViewingKeyNk: nk,
|
|
12336
12631
|
chainNoteSalt: noteSalt,
|
|
12632
|
+
ownerUtxoKeypair: utxoKeypair,
|
|
12337
12633
|
relaySupplementalAlt: true,
|
|
12338
12634
|
onProgress: (s) => log(` \xB7 ${s}`)
|
|
12339
12635
|
}
|
|
@@ -12552,6 +12848,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
12552
12848
|
export {
|
|
12553
12849
|
AccountRole,
|
|
12554
12850
|
BRIDGE_ESCROW_LABEL,
|
|
12851
|
+
BRIDGE_ESCROW_LABEL_V2,
|
|
12555
12852
|
BUILD_ALLOWS_LOCAL_ENDPOINTS,
|
|
12556
12853
|
CHAIN_NOTE_SALT_BITS,
|
|
12557
12854
|
CLEANUP_FEE_BUDGET,
|
|
@@ -12680,14 +12977,18 @@ export {
|
|
|
12680
12977
|
depositFromDerivedKey,
|
|
12681
12978
|
deriveBridgeReceiver,
|
|
12682
12979
|
deriveChangeNoteBlinding,
|
|
12683
|
-
|
|
12980
|
+
deriveDepositNoteBlinding,
|
|
12684
12981
|
deriveDiversifiedViewingKey,
|
|
12685
12982
|
deriveDiversifier,
|
|
12686
12983
|
deriveFundingTargets,
|
|
12687
12984
|
deriveInputNullifierPdas,
|
|
12985
|
+
deriveLegacyBridgeReceiver,
|
|
12986
|
+
deriveLegacyDepositNoteSecrets,
|
|
12987
|
+
deriveLegacySwapRefundAuthorization,
|
|
12688
12988
|
derivePublicKey,
|
|
12689
12989
|
deriveSpendKey,
|
|
12690
12990
|
deriveSwapRefundAuthorization,
|
|
12991
|
+
deriveSwapRefundBlinding,
|
|
12691
12992
|
deriveUserCompliancePublicKey,
|
|
12692
12993
|
deriveUserComplianceScalar,
|
|
12693
12994
|
deriveUtxoKeypairFromSpendKey,
|