@cloak.dev/sdk 0.2.6-staging.abb3ae6 → 0.2.6-staging.d42dbe0
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/dist/index.cjs +164 -25
- package/dist/index.d.cts +78 -29
- package/dist/index.d.ts +78 -29
- package/dist/index.js +162 -25
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -723,6 +723,7 @@ __export(index_exports, {
|
|
|
723
723
|
deriveSpendKey: () => deriveSpendKey,
|
|
724
724
|
deriveSwapRefundAuthorization: () => deriveSwapRefundAuthorization,
|
|
725
725
|
deriveSwapRefundBlinding: () => deriveSwapRefundBlinding,
|
|
726
|
+
deriveSwapRefundKeypair: () => deriveSwapRefundKeypair,
|
|
726
727
|
deriveUserCompliancePublicKey: () => deriveUserCompliancePublicKey,
|
|
727
728
|
deriveUserComplianceScalar: () => deriveUserComplianceScalar,
|
|
728
729
|
deriveUtxoKeypairFromSpendKey: () => deriveUtxoKeypairFromSpendKey,
|
|
@@ -878,6 +879,7 @@ __export(index_exports, {
|
|
|
878
879
|
signTransaction: () => signTransaction,
|
|
879
880
|
signerFromKeypair: () => signerFromKeypair,
|
|
880
881
|
signerFromSecretKey: () => signerFromSecretKey,
|
|
882
|
+
signerFromTransactionBytes: () => signerFromTransactionBytes,
|
|
881
883
|
signerFromWalletAdapter: () => signerFromWalletAdapter,
|
|
882
884
|
splitTo2Limbs: () => splitTo2Limbs,
|
|
883
885
|
submitTransactToRelay: () => submitTransactToRelay,
|
|
@@ -1524,13 +1526,16 @@ init_inputs();
|
|
|
1524
1526
|
|
|
1525
1527
|
// src/relay/viewing-key.ts
|
|
1526
1528
|
var VIEWING_KEY_CHALLENGE_PREFIX = "CLOAK_VIEWING_KEY_REGISTER";
|
|
1529
|
+
var VIEWING_KEY_CHALLENGE_READABLE_HEADER = "Cloak: Enable private transactions\n\nShares your viewing key with Cloak so you can transact privately. Signing this does not move any funds.\n\n";
|
|
1530
|
+
var VIEWING_KEY_CHALLENGE_REQUEST_FORMAT = "readable";
|
|
1527
1531
|
var UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
1528
1532
|
var MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS = 300;
|
|
1529
1533
|
function normalizeViewingKeyHex(viewingKeyHex) {
|
|
1530
1534
|
return viewingKeyHex.replace(/^0x/i, "").toLowerCase();
|
|
1531
1535
|
}
|
|
1532
|
-
function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex) {
|
|
1533
|
-
|
|
1536
|
+
function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format = "legacy") {
|
|
1537
|
+
const header = format === "readable" ? VIEWING_KEY_CHALLENGE_READABLE_HEADER : "";
|
|
1538
|
+
return header + [
|
|
1534
1539
|
VIEWING_KEY_CHALLENGE_PREFIX,
|
|
1535
1540
|
userPubkey,
|
|
1536
1541
|
nonce,
|
|
@@ -1545,17 +1550,16 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
|
|
|
1545
1550
|
const challenge = data;
|
|
1546
1551
|
const nonce = typeof challenge.nonce === "string" ? challenge.nonce : "";
|
|
1547
1552
|
const expiresInSeconds = challenge.expires_in_seconds;
|
|
1548
|
-
const
|
|
1549
|
-
userPubkey,
|
|
1550
|
-
nonce,
|
|
1551
|
-
viewingKeyHex
|
|
1553
|
+
const messageFormat = ["readable", "legacy"].find(
|
|
1554
|
+
(format) => challenge.message === buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format)
|
|
1552
1555
|
);
|
|
1553
|
-
if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS ||
|
|
1556
|
+
if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS || messageFormat === void 0) {
|
|
1554
1557
|
throw new Error("Relay returned an unsafe viewing-key challenge");
|
|
1555
1558
|
}
|
|
1556
1559
|
return {
|
|
1557
1560
|
nonce,
|
|
1558
|
-
message:
|
|
1561
|
+
message: buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, messageFormat),
|
|
1562
|
+
messageFormat,
|
|
1559
1563
|
expiresInSeconds
|
|
1560
1564
|
};
|
|
1561
1565
|
}
|
|
@@ -2497,7 +2501,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
|
2497
2501
|
headers: { "Content-Type": "application/json" },
|
|
2498
2502
|
body: JSON.stringify({
|
|
2499
2503
|
user_pubkey: userPubkey,
|
|
2500
|
-
viewing_key: nkHex
|
|
2504
|
+
viewing_key: nkHex,
|
|
2505
|
+
message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
|
|
2501
2506
|
})
|
|
2502
2507
|
});
|
|
2503
2508
|
if (!challengeResponse.ok) {
|
|
@@ -2525,7 +2530,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
|
2525
2530
|
nonce: challenge.nonce,
|
|
2526
2531
|
identifier: keyId,
|
|
2527
2532
|
signature,
|
|
2528
|
-
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
|
|
2533
|
+
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
|
|
2534
|
+
...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
|
|
2529
2535
|
})
|
|
2530
2536
|
});
|
|
2531
2537
|
if (!response.ok) {
|
|
@@ -4368,7 +4374,11 @@ var RelayService = class {
|
|
|
4368
4374
|
const challengeRes = await relayFetch(`${this.baseUrl}/viewing-key/challenge`, {
|
|
4369
4375
|
method: "POST",
|
|
4370
4376
|
headers: { "Content-Type": "application/json" },
|
|
4371
|
-
body: JSON.stringify({
|
|
4377
|
+
body: JSON.stringify({
|
|
4378
|
+
user_pubkey: userPubkey,
|
|
4379
|
+
viewing_key: viewingKey,
|
|
4380
|
+
message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
|
|
4381
|
+
})
|
|
4372
4382
|
});
|
|
4373
4383
|
if (!challengeRes.ok) {
|
|
4374
4384
|
const error = await challengeRes.text();
|
|
@@ -4393,7 +4403,8 @@ var RelayService = class {
|
|
|
4393
4403
|
nonce: challenge.nonce,
|
|
4394
4404
|
identifier,
|
|
4395
4405
|
signature,
|
|
4396
|
-
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
|
|
4406
|
+
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
|
|
4407
|
+
...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
|
|
4397
4408
|
})
|
|
4398
4409
|
});
|
|
4399
4410
|
if (!response.ok) {
|
|
@@ -6053,6 +6064,8 @@ function normalizeOwnerPublicKey(publicKey, label) {
|
|
|
6053
6064
|
init_inputs();
|
|
6054
6065
|
var bs582 = import_bs582.default.default || import_bs582.default;
|
|
6055
6066
|
var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
|
|
6067
|
+
var REFUND_KEY_DOMAIN_V2 = new TextEncoder().encode("cloak_swap_refund_v2");
|
|
6068
|
+
var REFUND_PRIVATE_KEY_INFO_V2 = new TextEncoder().encode("sk_v2");
|
|
6056
6069
|
var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
|
|
6057
6070
|
var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
|
|
6058
6071
|
function normalizeNullifier(inputNullifier) {
|
|
@@ -6097,13 +6110,35 @@ function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
|
|
|
6097
6110
|
const nk = assertNk(viewingKeyNk);
|
|
6098
6111
|
return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
|
|
6099
6112
|
}
|
|
6100
|
-
|
|
6113
|
+
function privateKeyBytes(privateKey) {
|
|
6114
|
+
return Uint8Array.from(Buffer.from(privateKey.toString(16).padStart(64, "0"), "hex"));
|
|
6115
|
+
}
|
|
6116
|
+
async function deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier) {
|
|
6101
6117
|
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
6118
|
+
const nullifier = normalizeNullifier(inputNullifier);
|
|
6119
|
+
const preimage = new Uint8Array(
|
|
6120
|
+
REFUND_KEY_DOMAIN_V2.length + 32 + nullifier.length + REFUND_PRIVATE_KEY_INFO_V2.length
|
|
6121
|
+
);
|
|
6122
|
+
let off = 0;
|
|
6123
|
+
preimage.set(REFUND_KEY_DOMAIN_V2, off);
|
|
6124
|
+
off += REFUND_KEY_DOMAIN_V2.length;
|
|
6125
|
+
preimage.set(privateKeyBytes(owner.privateKey), off);
|
|
6126
|
+
off += 32;
|
|
6127
|
+
preimage.set(nullifier, off);
|
|
6128
|
+
off += nullifier.length;
|
|
6129
|
+
preimage.set(REFUND_PRIVATE_KEY_INFO_V2, off);
|
|
6130
|
+
const privateKey = toFieldSecret((0, import_blake34.blake3)(preimage));
|
|
6131
|
+
const publicKey = await derivePublicKey(privateKey);
|
|
6132
|
+
if (publicKey === 0n) throw new Error("refund authorization is degenerate");
|
|
6133
|
+
return { privateKey, publicKey };
|
|
6134
|
+
}
|
|
6135
|
+
async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
|
|
6102
6136
|
const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
6103
|
-
|
|
6137
|
+
const keypair = await deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier);
|
|
6138
|
+
if (keypair.publicKey === 0n || blinding === 0n) {
|
|
6104
6139
|
throw new Error("refund authorization is degenerate");
|
|
6105
6140
|
}
|
|
6106
|
-
return { privateKey:
|
|
6141
|
+
return { privateKey: keypair.privateKey, publicKey: keypair.publicKey, blinding };
|
|
6107
6142
|
}
|
|
6108
6143
|
async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
|
|
6109
6144
|
const nk = assertNk(viewingKeyNk);
|
|
@@ -6124,9 +6159,12 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
|
|
|
6124
6159
|
mintAddress: NATIVE_SOL_MINT
|
|
6125
6160
|
});
|
|
6126
6161
|
}
|
|
6162
|
+
function toField(value) {
|
|
6163
|
+
return value instanceof Uint8Array ? BigInt("0x" + Buffer.from(value).toString("hex")) : value;
|
|
6164
|
+
}
|
|
6127
6165
|
async function matchSwapRefundLeaf(params) {
|
|
6128
6166
|
const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
|
|
6129
|
-
const expected =
|
|
6167
|
+
const expected = toField(params.commitment);
|
|
6130
6168
|
let blinding;
|
|
6131
6169
|
try {
|
|
6132
6170
|
blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
@@ -6134,11 +6172,55 @@ async function matchSwapRefundLeaf(params) {
|
|
|
6134
6172
|
return null;
|
|
6135
6173
|
}
|
|
6136
6174
|
const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
|
|
6175
|
+
const ownerPriv = params.ownerUtxoKeypair?.privateKey ?? 0n;
|
|
6176
|
+
let perSwapPub;
|
|
6177
|
+
let perSwapPriv = 0n;
|
|
6178
|
+
if (ownerPriv > 0n && ownerPub !== void 0) {
|
|
6179
|
+
try {
|
|
6180
|
+
const kp = await deriveSwapRefundKeypair({ privateKey: ownerPriv, publicKey: ownerPub }, inputNullifier);
|
|
6181
|
+
perSwapPub = kp.publicKey;
|
|
6182
|
+
perSwapPriv = kp.privateKey;
|
|
6183
|
+
} catch {
|
|
6184
|
+
return null;
|
|
6185
|
+
}
|
|
6186
|
+
}
|
|
6187
|
+
if (params.publishedRefundPubkey !== void 0 && params.publishedRefundBlinding !== void 0) {
|
|
6188
|
+
const published = toField(params.publishedRefundPubkey);
|
|
6189
|
+
const publishedBlinding = toField(params.publishedRefundBlinding);
|
|
6190
|
+
if (published !== 0n && publishedBlinding === blinding) {
|
|
6191
|
+
if (perSwapPub === void 0 || perSwapPub === published) {
|
|
6192
|
+
const candidate = await computeSwapRefundCommitment(amountAfterFee, published, blinding);
|
|
6193
|
+
if (candidate === expected && published !== ownerPub) {
|
|
6194
|
+
return {
|
|
6195
|
+
keypair: { privateKey: perSwapPub === published ? perSwapPriv : 0n, publicKey: published },
|
|
6196
|
+
shape: "per-swap",
|
|
6197
|
+
blinding,
|
|
6198
|
+
amount: amountAfterFee,
|
|
6199
|
+
commitment: candidate,
|
|
6200
|
+
legacyExposed: false
|
|
6201
|
+
};
|
|
6202
|
+
}
|
|
6203
|
+
}
|
|
6204
|
+
}
|
|
6205
|
+
} else if (perSwapPub !== void 0) {
|
|
6206
|
+
const candidate = await computeSwapRefundCommitment(amountAfterFee, perSwapPub, blinding);
|
|
6207
|
+
if (candidate === expected) {
|
|
6208
|
+
return {
|
|
6209
|
+
keypair: { privateKey: perSwapPriv, publicKey: perSwapPub },
|
|
6210
|
+
shape: "per-swap",
|
|
6211
|
+
blinding,
|
|
6212
|
+
amount: amountAfterFee,
|
|
6213
|
+
commitment: candidate,
|
|
6214
|
+
legacyExposed: false
|
|
6215
|
+
};
|
|
6216
|
+
}
|
|
6217
|
+
}
|
|
6137
6218
|
if (ownerPub !== void 0) {
|
|
6138
6219
|
const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
|
|
6139
6220
|
if (candidate === expected) {
|
|
6140
6221
|
return {
|
|
6141
|
-
keypair: { privateKey:
|
|
6222
|
+
keypair: { privateKey: ownerPriv, publicKey: ownerPub },
|
|
6223
|
+
shape: "owner",
|
|
6142
6224
|
blinding,
|
|
6143
6225
|
amount: amountAfterFee,
|
|
6144
6226
|
commitment: candidate,
|
|
@@ -6156,6 +6238,7 @@ async function matchSwapRefundLeaf(params) {
|
|
|
6156
6238
|
if (legacyCandidate !== expected) return null;
|
|
6157
6239
|
return {
|
|
6158
6240
|
keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
|
|
6241
|
+
shape: "legacy-nk",
|
|
6159
6242
|
blinding: legacy.blinding,
|
|
6160
6243
|
amount: amountAfterFee,
|
|
6161
6244
|
commitment: legacyCandidate,
|
|
@@ -6167,6 +6250,9 @@ var PROOF_LEN2 = 256;
|
|
|
6167
6250
|
var NULLIFIER_0_OFFSET = 1 + PROOF_LEN2 + 104;
|
|
6168
6251
|
var PUBLIC_INPUTS_LEN2 = 264;
|
|
6169
6252
|
var MIN_TRANSACT_SWAP_LEN = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2;
|
|
6253
|
+
var REFUND_PUBKEY_OFFSET = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2 + 72;
|
|
6254
|
+
var REFUND_BLINDING_OFFSET = REFUND_PUBKEY_OFFSET + 32;
|
|
6255
|
+
var MIN_TRANSACT_SWAP_WITH_PARAMS_LEN = REFUND_BLINDING_OFFSET + 32;
|
|
6170
6256
|
function toBase58(key) {
|
|
6171
6257
|
if (!key) return void 0;
|
|
6172
6258
|
if (typeof key === "string") return key;
|
|
@@ -6229,7 +6315,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
|
|
|
6229
6315
|
}
|
|
6230
6316
|
if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
|
|
6231
6317
|
throw new Error(
|
|
6232
|
-
"discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): refund leaves are
|
|
6318
|
+
"discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): per-swap and owner-key refund leaves are matched against it, and nk alone can only find legacy refunds."
|
|
6233
6319
|
);
|
|
6234
6320
|
}
|
|
6235
6321
|
const ownerUtxoKeypair = options.ownerUtxoKeypair;
|
|
@@ -6289,7 +6375,15 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
|
|
|
6289
6375
|
programId
|
|
6290
6376
|
);
|
|
6291
6377
|
const key = swapState;
|
|
6292
|
-
|
|
6378
|
+
const hasParams = data.length >= MIN_TRANSACT_SWAP_WITH_PARAMS_LEN;
|
|
6379
|
+
if (!nullifierBySwapState.has(key)) {
|
|
6380
|
+
nullifierBySwapState.set(key, {
|
|
6381
|
+
nullifier,
|
|
6382
|
+
signature,
|
|
6383
|
+
refundPubkey: hasParams ? data.slice(REFUND_PUBKEY_OFFSET, REFUND_PUBKEY_OFFSET + 32) : void 0,
|
|
6384
|
+
refundBlinding: hasParams ? data.slice(REFUND_BLINDING_OFFSET, REFUND_BLINDING_OFFSET + 32) : void 0
|
|
6385
|
+
});
|
|
6386
|
+
}
|
|
6293
6387
|
}
|
|
6294
6388
|
const logs = tx.meta?.logMessages;
|
|
6295
6389
|
const scan = scanRefundLeafEvents(logs, programIdBase58);
|
|
@@ -6308,7 +6402,9 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
|
|
|
6308
6402
|
inputNullifier: candidate.nullifier,
|
|
6309
6403
|
amountAfterFee: event.amountAfterFee,
|
|
6310
6404
|
commitment: event.commitmentField,
|
|
6311
|
-
ownerUtxoKeypair
|
|
6405
|
+
ownerUtxoKeypair,
|
|
6406
|
+
publishedRefundPubkey: candidate.refundPubkey,
|
|
6407
|
+
publishedRefundBlinding: candidate.refundBlinding
|
|
6312
6408
|
});
|
|
6313
6409
|
if (!recovered) continue;
|
|
6314
6410
|
const dedupe = `${close.signature}:${event.leafIndex}`;
|
|
@@ -7312,7 +7408,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
|
|
|
7312
7408
|
headers: { "Content-Type": "application/json" },
|
|
7313
7409
|
body: JSON.stringify({
|
|
7314
7410
|
user_pubkey: userPubkey,
|
|
7315
|
-
viewing_key: viewingKeyHex
|
|
7411
|
+
viewing_key: viewingKeyHex,
|
|
7412
|
+
message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
|
|
7316
7413
|
})
|
|
7317
7414
|
});
|
|
7318
7415
|
if (!challengeResponse.ok) {
|
|
@@ -7359,7 +7456,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
|
|
|
7359
7456
|
viewing_key: viewingKeyHex,
|
|
7360
7457
|
nonce: challenge.nonce,
|
|
7361
7458
|
signature: signatureBase64,
|
|
7362
|
-
...authMode === "transaction" ? { auth_mode: authMode } : {}
|
|
7459
|
+
...authMode === "transaction" ? { auth_mode: authMode } : {},
|
|
7460
|
+
...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
|
|
7363
7461
|
})
|
|
7364
7462
|
});
|
|
7365
7463
|
if (!response.ok) {
|
|
@@ -13641,7 +13739,8 @@ async function matchOwnItems(own, owner, onReject, onSkip) {
|
|
|
13641
13739
|
atRisk: o.refund.legacyExposed,
|
|
13642
13740
|
amount: o.refund.amount,
|
|
13643
13741
|
blinding: o.refund.blinding,
|
|
13644
|
-
|
|
13742
|
+
// per-swap refunds carry their derived keypair; owner-shape ones carry the owner
|
|
13743
|
+
keypair: o.refund.keypair,
|
|
13645
13744
|
mint: NATIVE_SOL_MINT,
|
|
13646
13745
|
commitment: o.refund.commitment,
|
|
13647
13746
|
leaf: Number(item.leaf)
|
|
@@ -14307,7 +14406,8 @@ async function runOnce(ctx, cursor) {
|
|
|
14307
14406
|
for (const c of byLeaf.values()) {
|
|
14308
14407
|
const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
|
|
14309
14408
|
keyChecked.set(c.keypair.privateKey, pubOk);
|
|
14310
|
-
|
|
14409
|
+
const ownerOk = c.keypair.publicKey === owner.publicKey || c.kind === "swap_refund";
|
|
14410
|
+
if (!pubOk || !c.atRisk && !ownerOk) {
|
|
14311
14411
|
stats.dropped++;
|
|
14312
14412
|
tally(c, "rejected");
|
|
14313
14413
|
continue;
|
|
@@ -14316,7 +14416,7 @@ async function runOnce(ctx, cursor) {
|
|
|
14316
14416
|
verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
|
|
14317
14417
|
const utxo = {
|
|
14318
14418
|
amount: c.amount,
|
|
14319
|
-
keypair: c.atRisk ? { ...c.keypair } : owner,
|
|
14419
|
+
keypair: c.atRisk || c.kind === "swap_refund" ? { ...c.keypair } : owner,
|
|
14320
14420
|
blinding: c.blinding,
|
|
14321
14421
|
mintAddress: c.mint,
|
|
14322
14422
|
index: c.leaf,
|
|
@@ -14761,6 +14861,43 @@ function signerFromWalletAdapter(adapter, options = {}) {
|
|
|
14761
14861
|
}
|
|
14762
14862
|
return signer;
|
|
14763
14863
|
}
|
|
14864
|
+
function signerFromTransactionBytes(wallet) {
|
|
14865
|
+
const walletAddress = wallet.address;
|
|
14866
|
+
const signer = {
|
|
14867
|
+
address: walletAddress,
|
|
14868
|
+
async modifyAndSignTransactions(transactions) {
|
|
14869
|
+
const out = [];
|
|
14870
|
+
for (const transaction of transactions) {
|
|
14871
|
+
const signedBytes = await wallet.signTransaction(transactionBytes(transaction));
|
|
14872
|
+
const decoded = transactionFromBytes(signedBytes);
|
|
14873
|
+
if (!bytesEqual2(new Uint8Array(decoded.messageBytes), new Uint8Array(transaction.messageBytes))) {
|
|
14874
|
+
throw new Error("Wallet returned a transaction whose message differs from the one it was asked to sign");
|
|
14875
|
+
}
|
|
14876
|
+
if (!decoded.signatures[walletAddress]) {
|
|
14877
|
+
throw new Error("Wallet returned a transaction without its own signature");
|
|
14878
|
+
}
|
|
14879
|
+
out.push({ ...transaction, signatures: { ...transaction.signatures, ...decoded.signatures } });
|
|
14880
|
+
}
|
|
14881
|
+
return out;
|
|
14882
|
+
}
|
|
14883
|
+
};
|
|
14884
|
+
if (wallet.signMessage) {
|
|
14885
|
+
const signMessage = wallet.signMessage;
|
|
14886
|
+
Object.assign(signer, {
|
|
14887
|
+
async signMessages(messages) {
|
|
14888
|
+
const dictionaries = [];
|
|
14889
|
+
for (const message of messages) dictionaries.push({ [walletAddress]: await signMessage(message.content) });
|
|
14890
|
+
return dictionaries;
|
|
14891
|
+
}
|
|
14892
|
+
});
|
|
14893
|
+
}
|
|
14894
|
+
return signer;
|
|
14895
|
+
}
|
|
14896
|
+
function bytesEqual2(a, b) {
|
|
14897
|
+
if (a.length !== b.length) return false;
|
|
14898
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
14899
|
+
return true;
|
|
14900
|
+
}
|
|
14764
14901
|
async function loadWeb3() {
|
|
14765
14902
|
const name = "@solana/web3.js";
|
|
14766
14903
|
try {
|
|
@@ -15800,6 +15937,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
15800
15937
|
deriveSpendKey,
|
|
15801
15938
|
deriveSwapRefundAuthorization,
|
|
15802
15939
|
deriveSwapRefundBlinding,
|
|
15940
|
+
deriveSwapRefundKeypair,
|
|
15803
15941
|
deriveUserCompliancePublicKey,
|
|
15804
15942
|
deriveUserComplianceScalar,
|
|
15805
15943
|
deriveUtxoKeypairFromSpendKey,
|
|
@@ -15955,6 +16093,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
15955
16093
|
signTransaction,
|
|
15956
16094
|
signerFromKeypair,
|
|
15957
16095
|
signerFromSecretKey,
|
|
16096
|
+
signerFromTransactionBytes,
|
|
15958
16097
|
signerFromWalletAdapter,
|
|
15959
16098
|
splitTo2Limbs,
|
|
15960
16099
|
submitTransactToRelay,
|
package/dist/index.d.cts
CHANGED
|
@@ -3872,8 +3872,10 @@ interface UtxoSwapResult extends TransactResult {
|
|
|
3872
3872
|
* `SwapState.sol_amount`, = gross swap amount minus the on-chain swap fee). R_fb is an ordinary
|
|
3873
3873
|
* leaf of the main pool tree, spent with the ordinary `transact()` path. All values are hex.
|
|
3874
3874
|
*
|
|
3875
|
-
* `publicKey` is
|
|
3876
|
-
*
|
|
3875
|
+
* `publicKey` is a PER-SWAP public key, derived from `options.ownerUtxoKeypair`'s private key and
|
|
3876
|
+
* the swap's first input nullifier, so no two swaps from one wallet share it and it is not the
|
|
3877
|
+
* wallet's UTXO public key. Spend R_fb with `deriveSwapRefundKeypair(owner, nullifier)`; the
|
|
3878
|
+
* private key is deliberately not repeated here and `nk` cannot produce it. The
|
|
3877
3879
|
* blinding is derived from the wallet's `nk` and the swap's public first input nullifier
|
|
3878
3880
|
* (`derivedFromNk` is always true), so `discoverSwapRefunds` finds the leaf again from key
|
|
3879
3881
|
* material if this object is lost.
|
|
@@ -4658,26 +4660,34 @@ declare function matchChangeNote(params: MatchChangeNoteParams): Promise<Recover
|
|
|
4658
4660
|
* viewing key and the swap creator's, and found nothing under either.
|
|
4659
4661
|
*
|
|
4660
4662
|
* ── The fix, and why it is SDK-only ───────────────────────────────────────────────────────────
|
|
4661
|
-
* The refund leaf is
|
|
4662
|
-
* its
|
|
4663
|
+
* The refund leaf's BLINDING is derived as a PRF of the owner's `nk` and the swap's own first input
|
|
4664
|
+
* nullifier, and its OWNER KEY is derived per swap from the wallet's UTXO private key:
|
|
4663
4665
|
*
|
|
4664
|
-
* blinding = BLAKE3("cloak_swap_refund_v1" || nk || nullifier0 || "blinding")
|
|
4665
|
-
*
|
|
4666
|
+
* blinding = BLAKE3("cloak_swap_refund_v1" || nk || nullifier0 || "blinding") -> field
|
|
4667
|
+
* priv = BLAKE3("cloak_swap_refund_v2" || ownerPrivateKey || nullifier0 || "sk_v2") -> field
|
|
4668
|
+
* pub = derivePublicKey(priv)
|
|
4666
4669
|
*
|
|
4667
|
-
* `nullifier0` is published in the TransactSwap public inputs, so a scanner holding `nk`
|
|
4668
|
-
*
|
|
4669
|
-
*
|
|
4670
|
-
*
|
|
4671
|
-
* blinding
|
|
4670
|
+
* `nullifier0` is published in the TransactSwap public inputs, so a scanner holding `nk` can replay
|
|
4671
|
+
* the blinding for every swap it sees. `refund_pubkey` and `refund_blinding` are ALSO published, in
|
|
4672
|
+
* plain text, in the TransactSwap instruction data (and in SwapState), so a view-only scanner (nk
|
|
4673
|
+
* plus the owner PUBLIC key) reads the per-swap pubkey from there, checks that the published
|
|
4674
|
+
* blinding equals the nk-derived one, and checks that the commitment matches. Spending R_fb needs
|
|
4675
|
+
* `priv`, which needs the owner's private key: `nk` cannot produce it, so the viewing key stays
|
|
4676
|
+
* view-only, and the owner re-derives the spend key from its own private key plus the nullifier.
|
|
4677
|
+
*
|
|
4678
|
+
* Why not the owner key itself (0.2.6 - 0.2.8)? That shape published the wallet's permanent UTXO
|
|
4679
|
+
* public key as `refund_pubkey` on every swap, so anyone holding a user's receiving key could list
|
|
4680
|
+
* all of that wallet's swaps. A different public key per swap removes the link.
|
|
4672
4681
|
*
|
|
4673
4682
|
* This changes NOTHING on chain or in the relay. `refund_pubkey` / `refund_blinding` remain
|
|
4674
4683
|
* caller-supplied values bound into `computeSwapExtDataHash`; only their provenance changes.
|
|
4675
4684
|
*
|
|
4676
|
-
* ──
|
|
4677
|
-
*
|
|
4678
|
-
*
|
|
4679
|
-
*
|
|
4680
|
-
*
|
|
4685
|
+
* ── Three refund shapes, all still recognised ─────────────────────────────────────────────────
|
|
4686
|
+
* "per-swap" (0.2.9+) owner = per-swap key from the owner private key (above)
|
|
4687
|
+
* "owner" (0.2.6 - 0.2.8) owner = the wallet's permanent UTXO keypair; linkable across swaps
|
|
4688
|
+
* "legacy-nk" (< 0.2.6) owner key AND blinding from nk; `legacyExposed: true`, because anyone
|
|
4689
|
+
* holding `nk` can spend it. An app should migrate those refunds.
|
|
4690
|
+
* No API builds a refund in the last two shapes any more.
|
|
4681
4691
|
*
|
|
4682
4692
|
* ── Guardrails preserved ──────────────────────────────────────────────────────────────────────
|
|
4683
4693
|
* [H-04 / DD-01] the authorization is rejected unless publicKey and blinding are both non-zero.
|
|
@@ -4698,14 +4708,20 @@ interface SwapRefundAuthorization {
|
|
|
4698
4708
|
publicKey: bigint;
|
|
4699
4709
|
blinding: bigint;
|
|
4700
4710
|
}
|
|
4711
|
+
/** Which key shape owns a refund leaf; see the file header. */
|
|
4712
|
+
type SwapRefundShape = "per-swap" | "owner" | "legacy-nk";
|
|
4701
4713
|
/** A refund leaf matched back to its owner. */
|
|
4702
4714
|
interface RecoveredSwapRefund {
|
|
4703
4715
|
/**
|
|
4704
|
-
* The
|
|
4705
|
-
* (`privateKey` is `0n`
|
|
4706
|
-
*
|
|
4716
|
+
* The key that owns the leaf. `per-swap`: the key derived from the owner private key and the
|
|
4717
|
+
* swap nullifier (`privateKey` is `0n` for a view-only match: the public key is real, but the
|
|
4718
|
+
* spend key needs the owner private key, see {@link deriveSwapRefundKeypair}). `owner`: the
|
|
4719
|
+
* `ownerUtxoKeypair` the matcher was given (`privateKey` `0n` if only the public key was
|
|
4720
|
+
* supplied). `legacy-nk`: the nk-derived keypair, complete and spendable.
|
|
4707
4721
|
*/
|
|
4708
4722
|
keypair: UtxoKeypair;
|
|
4723
|
+
/** Which of the three shapes matched. */
|
|
4724
|
+
shape: SwapRefundShape;
|
|
4709
4725
|
blinding: bigint;
|
|
4710
4726
|
amount: bigint;
|
|
4711
4727
|
/** R_fb as a field element, identical to the commitment `CloseSwapState` appended. */
|
|
@@ -4724,8 +4740,15 @@ interface RecoveredSwapRefund {
|
|
|
4724
4740
|
*/
|
|
4725
4741
|
declare function deriveSwapRefundBlinding(viewingKeyNk: Uint8Array, inputNullifier: Uint8Array | bigint): bigint;
|
|
4726
4742
|
/**
|
|
4727
|
-
* The refund
|
|
4728
|
-
*
|
|
4743
|
+
* The per-swap refund KEYPAIR: a different key for every swap, derived from the owner's private key
|
|
4744
|
+
* and the swap's first input nullifier. `nk` cannot reproduce it. Use this to spend a refund the
|
|
4745
|
+
* swap result reported, or any `per-swap` refund a view-only scan found.
|
|
4746
|
+
*/
|
|
4747
|
+
declare function deriveSwapRefundKeypair(ownerUtxoKeypair: UtxoKeypair, inputNullifier: Uint8Array | bigint): Promise<UtxoKeypair>;
|
|
4748
|
+
/**
|
|
4749
|
+
* The refund authorization `swapUtxo` binds into the swap ext-data hash: a per-swap keypair derived
|
|
4750
|
+
* from the wallet's UTXO private key and the swap's first input nullifier, plus the nk-derived
|
|
4751
|
+
* blinding. The public key differs for every swap and differs from the wallet's UTXO public key.
|
|
4729
4752
|
*
|
|
4730
4753
|
* `ownerUtxoKeypair` is required and validated. The refund key is never derived from `nk`.
|
|
4731
4754
|
*/
|
|
@@ -4752,16 +4775,28 @@ interface MatchSwapRefundLeafParams {
|
|
|
4752
4775
|
commitment: bigint | Uint8Array;
|
|
4753
4776
|
/**
|
|
4754
4777
|
* The wallet's long-lived UTXO keypair (`privateKey: 0n` is fine for a view-only match). Without
|
|
4755
|
-
* it only legacy refunds can be matched.
|
|
4778
|
+
* it only legacy-nk refunds can be matched.
|
|
4756
4779
|
*/
|
|
4757
4780
|
ownerUtxoKeypair?: UtxoKeypair;
|
|
4781
|
+
/**
|
|
4782
|
+
* `refund_pubkey` as published in the swap's TransactSwap instruction data (bytes 593-624) or its
|
|
4783
|
+
* SwapState. A view-only scanner needs it to match a `per-swap` refund, because it cannot derive
|
|
4784
|
+
* the key. Pass it together with {@link publishedRefundBlinding}.
|
|
4785
|
+
*/
|
|
4786
|
+
publishedRefundPubkey?: bigint | Uint8Array;
|
|
4787
|
+
/** `refund_blinding` as published in the same place (bytes 625-656). */
|
|
4788
|
+
publishedRefundBlinding?: bigint | Uint8Array;
|
|
4758
4789
|
}
|
|
4759
4790
|
/**
|
|
4760
4791
|
* Decide whether a public refund leaf belongs to this wallet, and if so return it. Returns `null`
|
|
4761
4792
|
* for every leaf that is not ours; a scanner runs this against every close it can see.
|
|
4762
4793
|
*
|
|
4763
|
-
* Tries the
|
|
4764
|
-
*
|
|
4794
|
+
* Tries, in order: the per-swap shape (published pubkey, or re-derived when the owner private key
|
|
4795
|
+
* is present), the 0.2.6 - 0.2.8 owner-key shape, then the legacy nk shape (`legacyExposed`).
|
|
4796
|
+
* `shape` on the result says which one matched.
|
|
4797
|
+
*
|
|
4798
|
+
* A per-swap match from a view-only scan returns `keypair.privateKey === 0n`; the caller spends it
|
|
4799
|
+
* with {@link deriveSwapRefundKeypair} once it holds the owner private key.
|
|
4765
4800
|
*/
|
|
4766
4801
|
declare function matchSwapRefundLeaf(params: MatchSwapRefundLeafParams): Promise<RecoveredSwapRefund | null>;
|
|
4767
4802
|
/** One recovered refund leaf, with the chain coordinates that produced it. */
|
|
@@ -4777,9 +4812,11 @@ interface DiscoveredSwapRefund extends RecoveredSwapRefund {
|
|
|
4777
4812
|
}
|
|
4778
4813
|
interface DiscoverSwapRefundsOptions {
|
|
4779
4814
|
/**
|
|
4780
|
-
* The wallet's long-lived UTXO keypair
|
|
4781
|
-
*
|
|
4782
|
-
* for a view-only scan
|
|
4815
|
+
* The wallet's long-lived UTXO keypair. Required. Pass the real keypair to get spendable
|
|
4816
|
+
* results (per-swap refunds come back with their derived keypair), or `{ privateKey: 0n,
|
|
4817
|
+
* publicKey }` for a view-only scan: per-swap refunds are then matched from the `refund_pubkey`
|
|
4818
|
+
* published in the swap instruction and come back with `privateKey: 0n` (re-derive it with
|
|
4819
|
+
* `deriveSwapRefundKeypair`). Legacy (nk-owned) refunds are found either way and flagged
|
|
4783
4820
|
* `legacyExposed`.
|
|
4784
4821
|
*/
|
|
4785
4822
|
ownerUtxoKeypair: UtxoKeypair;
|
|
@@ -4807,7 +4844,7 @@ interface DiscoverSwapRefundsOptions {
|
|
|
4807
4844
|
* its owner could not see it under any key they held.
|
|
4808
4845
|
*
|
|
4809
4846
|
* FORWARD-LOOKING ONLY. This finds refunds whose blinding was DERIVED from (nk, nullifier0), owned
|
|
4810
|
-
*
|
|
4847
|
+
* by a per-swap key (0.2.9+), the wallet UTXO key (0.2.6-0.2.8) or an nk-derived key (legacy, flagged).
|
|
4811
4848
|
* A swap whose refund keypair and blinding were drawn from raw randomness (every swap submitted
|
|
4812
4849
|
* before that derivation shipped) has no derivation to replay,
|
|
4813
4850
|
* and no key-only scan can ever recover it. Those secrets existed solely in the caller's in-memory
|
|
@@ -5754,6 +5791,18 @@ interface WalletAdapterBridgeOptions {
|
|
|
5754
5791
|
web3?: Web3Module;
|
|
5755
5792
|
}
|
|
5756
5793
|
declare function signerFromWalletAdapter(adapter: LegacyWalletAdapter, options?: WalletAdapterBridgeOptions): WalletSigner;
|
|
5794
|
+
/**
|
|
5795
|
+
* A wallet that signs a transaction given its wire bytes and returns the signed wire bytes: the
|
|
5796
|
+
* shape of the Wallet Standard `solana:signTransaction` feature. This is the bridge to use for a
|
|
5797
|
+
* Transaction V1 message, which `@solana/web3.js` 1.x cannot serialize; it works for v0 and legacy
|
|
5798
|
+
* messages too, and needs no web3.js at all.
|
|
5799
|
+
*/
|
|
5800
|
+
interface TransactionBytesWallet {
|
|
5801
|
+
address: Address;
|
|
5802
|
+
signTransaction(transactionBytes: Uint8Array): Promise<Uint8Array>;
|
|
5803
|
+
signMessage?: (message: Uint8Array) => Promise<Uint8Array>;
|
|
5804
|
+
}
|
|
5805
|
+
declare function signerFromTransactionBytes(wallet: TransactionBytesWallet): WalletSigner;
|
|
5757
5806
|
type Web3Module = {
|
|
5758
5807
|
VersionedTransaction: {
|
|
5759
5808
|
deserialize(bytes: Uint8Array): unknown;
|
|
@@ -6421,4 +6470,4 @@ declare const VERSION = "0.2.6";
|
|
|
6421
6470
|
/** True when scanner supports TransactSwap (tag 1). Check this to verify the correct SDK bundle is loaded. */
|
|
6422
6471
|
declare const SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
6423
6472
|
|
|
6424
|
-
export { BRIDGE_ESCROW_LABEL, BRIDGE_ESCROW_LABEL_V2, BUILD_ALLOWS_LOCAL_ENDPOINTS, type BridgeDeliveryState, type BridgeDeposit, type BridgeDepositState, type BridgeQuoteAssessment, type BridgeQuoteInput, type BridgeRail, type BridgeRailAttestation, type BridgeRailProblem, type BridgeRailQuoteOption, type BridgeRailQuoteRequest, type BridgeRailQuoteResponse, type BridgeRailStatusResult, type BuildRecipientDeliveryNotesParams, CHAIN_NOTE_SALT_BITS, CLEANUP_FEE_BUDGET, CLOAK_PRODUCTION_RELAY_URL, CLOAK_PROGRAM_ID, type ChainNoteTxType, type CircuitVerificationResult, type CleanupResult, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, type CloakRpc, type CommitmentEntry, type CommitmentsResponse, type CompactChainNote, type ComplianceReport, type ComplianceTxType, type ConfirmSettlementParams, type CreateRecoverableDepositUtxoParams, DEFAULT_CIRCUITS_URL, DEFAULT_TRANSACTION_CIRCUITS_URL, DELIVERY_MEMO_TAG, DELIVERY_REGISTRY_SEED, type DeliveredNote, DepositError, type DepositInstructionParams, type DepositNoteSecrets, type DepositOptions, type DepositOutcome, type DepositRef, type DepositResult, type DepositStatus, type DiscoverOptions, type DiscoverSwapRefundsOptions, type DiscoveredSwapRefund, DoNotRetry, ECONOMIC_MINIMUM, EXPECTED_CIRCUIT_HASHES, type EncodeNoteIndexPageParams, type EncryptedMetadataBundle, type EncryptedNote$1 as EncryptedNote, type ErrorCategory, type ExpandedSpendKey, type ExternalFeePayerAdapter, FEE_BUDGET, FIXED_FEE_LAMPORTS, type FundingPlan, type Groth16Proof, type IndexedRecoveredNote, type IndexedRecoveredNoteKind, InsecureRandomnessError, LAMPORTS_PER_SOL, type LegacyWalletAdapter, type WalletSigner as LegacyWalletSigner, LocalStorageAdapter, type LogLevel, type Logger, type LookupTable, MAINNET_RENT_0, MAINNET_RENT_1, MAX_RECEIVER_INDEX, MERKLE_TREE_HEIGHT, MIN_DEPOSIT_LAMPORTS, MIN_DEPOSIT_SPL_BASE_UNITS, type MasterKey, type MatchChangeNoteParams, type MatchDepositNoteParams, type MatchSwapRefundLeafParams, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, MerkleTree, type MessageSigner, NATIVE_SOL_MINT, NOTE_INDEX_NO_LEAF, NOTE_INDEX_PAGE_SIZE, type Network, type NoteData, type NoteIndexCursor, type NoteIndexDeliveryItem, type NoteIndexFetchOptions, NoteIndexFormatError, type NoteIndexHead, NoteIndexHeadBehindError, type NoteIndexItem, type NoteIndexPage, type NoteIndexRecoveryStats, type NoteIndexSwapRefundItem, type NoteIndexTxItem, ONECLICK_PUBKEY_B58, type OnchainMerkleProof, type ParseNoteIndexPageOptions, type ParsedDeliveryCarrier, type PaymasterTopUpExpectation, type PaymasterTopUpResult, type PendingDeposit, type PendingWithdrawal, type PostFailureVerdict, RECIPIENT_DELIVERY_CIPHERTEXT_LEN, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN, RECIPIENT_DELIVERY_NONCE_LEN, RECIPIENT_DELIVERY_NOTE_BYTES, RECIPIENT_DELIVERY_PLAINTEXT_LEN, RECIPIENT_DELIVERY_TAG_LEN, RELAY_BATCH_AUTH_MAX_ITEMS, RELAY_ORIGIN_ALLOWLIST, REQUEST_AUTH_BATCH_DOMAIN, REQUEST_AUTH_BATCH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS, type RecipientDeliveryNote, type RecoverNotesFromIndexParams, type RecoverNotesFromIndexResult, type RecoveredChangeNote, type RecoveredChangeNoteRecord, type RecoveredDepositNote, type RecoveredDepositNoteRecord, type RecoveredSwapRefund, type RelayAuthMode, type RelayAuthPreimage, type RelayAuthSigner, RelayBatchAuthCoordinator, type RelayBatchAuthCoordinatorOptions, type RelayBatchAuthEnvelope, type RelayBatchAuthFields, type RelayBatchAuthItemHandle, RelayInternalError, RelayService, type RelaySubmissionResult, type RentRates, type RetryHooks, type RiskQuoteInstructionResponse, RootNotFoundError, SCANNER_SUPPORTS_TRANSACT_SWAP, SIGN_IN_MESSAGE, SanctionsQuoteError, type ScanOptions, type ScanRecipientDeliveryOptions, type ScanResult, type ScanSummary, type ScannedTransaction, type SettlementConnection, type SettlementContext, type SettlementStatus, type SettlementVerdict, SettlementVerificationError, ShieldPoolErrors, type ShieldPoolPDAs, SimpleWallet, type SpendKey, type SpendOptions, type StorageAdapter, type SubmitTransactToRelayArgs, type SwapOptions, type SwapParams, type SwapRefundAuthorization, type SwapResult, TERMINAL_FAILURE, TRANSACTION_CIRCUITS_VERSION, TRANSACT_AUTH_FIELDS, TRANSACT_SWAP_AUTH_FIELDS, type TransactBatchItem, type TransactBatchItemOutcome, type TransactBatchOptions, type TransactBatchResult, type TransactOptions, type TransactParams, type TransactRequestBodyParams, type TransactResult, TransactionConfirmationError, type TransactionMetadata, type Transfer, type TransferOptions, type TransferResult, type TxStatus, type UserFriendlyError, type Utxo, UtxoAlreadySpentError, type EncryptedNote as UtxoEncryptedNote, type UtxoKeypair, type UtxoSwapParams, type UtxoSwapResult, UtxoWallet, VARIABLE_FEE_DENOMINATOR, VARIABLE_FEE_NUMERATOR, VARIABLE_FEE_RATE, VERSION, type VerifyUtxosResult, type ViewKey, type ViewingKeyPair, WITHDRAW_FEE_BPS, WITHDRAW_FIXED_FEE, type WalletAdapterBridgeOptions, type WalletSigner$1 as WalletSigner, type WalletUtxo, type Web3Module, type WithdrawOptions, type WithdrawSubmissionResult, accountMeta, addressBytes, addressFromBytes, addressFromPublicKey, assertDirectSubmissionLanded, assertInputMints, assertTransactionCircuitIntegrity, assessBridgeQuote, bigintToBytes32$1 as bigintToBytes32, bigintToHex, buildAuthTransactionMessage, buildMerkleTree, buildMerkleTreeFromChain, buildMerkleTreeFromRelay, buildRecipientDeliveryNotes, buildRelayAuthPreimage, buildRelayBatchAuthMessage, buildTransactRequestBody, buildTransactionMessage, bytesToHex, calculateFee, calculateFeeBigint, calculateRelayFee, canRebuildMerkleTreeFromChain, canonicalJson, canonicalPayloadString, chainNoteFromBase64, chainNoteToBase64, classifyPostFailure, classifyRelayError, cleanupReceivingAddress, cleanupStalePendingOperations, clearPendingDeposits, clearPendingWithdrawals, cloakBridgeRail, computeChainNoteHash, computeExtDataHash, computeMerkleRoot, computeNoteIndexChain, computeProofForLatestDeposit, computeProofFromChain, computeSignature, computeSwapRefundCommitment, computeCommitment as computeUtxoCommitment, computeNullifier as computeUtxoNullifier, confirmSignature, confirmTransactSettlement, copyNoteToClipboard, createCloakError, createCloakRpc, createDepositInstruction, createLogger, createRecoverableChangeUtxo, createRecoverableDepositUtxo, createRelayBatchAuthCoordinator, createUtxo, createZeroUtxo, decryptCompactChainNote, decryptComplianceMetadataWithMasterKey, decryptTransactionMetadata, depositFromDerivedKey, deriveBridgeReceiver, deriveChangeNoteBlinding, deriveDepositNoteBlinding, deriveDiversifiedViewingKey, deriveDiversifier, deriveFundingTargets, deriveInputNullifierPdas, deriveLegacyBridgeReceiver, deriveLegacyDepositNoteSecrets, deriveLegacySwapRefundAuthorization, derivePublicKey, deriveSpendKey, deriveSwapRefundAuthorization, deriveSwapRefundBlinding, deriveUserCompliancePublicKey, deriveUserComplianceScalar, deriveUtxoKeypairFromSpendKey, deriveViewKey, deriveViewingKeyFromNk, deriveViewingKeyFromSpendKey, deriveViewingKeyFromUtxoPrivateKey, deserializeUtxo, detectNetworkFromRpcUrl, discoverSwapRefunds, downloadNote, encodeDeliveryCarrierMemo, encodeNoteIndexItem, encodeNoteIndexPage, encodeNoteSimple, encodeRecipientDeliveryNote, encryptCompactChainNote, encryptNoteForRecipient, encryptTransactionMetadata, encryptTransactionMetadataBundle, expandSpendKey, explainRelayAuthRejection, exportKeys, exportNote, exportWalletKeys, fetchAccountBytes, fetchCommitments, fetchLatestBlockhash, fetchLookupTables, fetchNoteIndexHead, fetchNoteIndexPage, fetchRiskQuoteInstruction, fetchRiskQuoteIx, fetchSignaturesForAddress, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, findProgramAddress, formatAmount, formatComplianceCsv, formatErrorForLogging, formatSol, fullWithdraw, fundReceiverViaPaymaster, generateCloakKeys, generateCommitmentAsync, generateMasterSeed, generateNoteFromWallet, generateUtxoKeypair, generateViewingKeyPair, getAddressExplorerUrl, getChainNoteRegistryPDA, getCircuitsPath, getDeliveryRegistryPDA, getDistributableAmount, getExplorerUrl, getNkFromUtxoPrivateKey, getNullifierPDA, getPendingOperationsSummary, getPoolAuthorityConfigPDA, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getSwapStatePDA, getViewKey, hasPendingOperations, hexToBigint$1 as hexToBigint, hexToBytes, importKeys, importWalletKeys, isBrowser, isBrowserLike, isDebugEnabled, isMessageSigner, isPlausibleSignature, isReactNative, isRootNotFoundError, isSubmissionOutcomeUnknownResponse, isTerminalFailure, isValidHex, isValidRpcUrl, isValidSolanaAddress, isWithdrawAmountSufficient, isWithdrawable, listBridgeDeposits, loadPendingDeposits, loadPendingWithdrawals, loadVerifiedCircuitArtifacts, matchChangeNote, matchDepositNote, matchSwapRefundLeaf, mayRetry, messageSignerFromCallback, openRecipientDeliveryNote, parseAmount, parseDeliveryCarrierMemo, parseError, parseNote, parseNoteIndexItem, parseNoteIndexPage, parseRelayErrorResponse, parseRelayErrorSignature, parseTransactionError, partialWithdraw, partiallySignTransaction, poseidonHash, preflightCheck, preflightNullifiers, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, programInstruction, proofToBytes, pubkeyToFieldElement, pubkeyToLimbs, randomBytes, randomChangeNoteSalt, randomDepositNoteSalt, randomFieldElement, readMerkleTreeState, readRent, recipientDeliveryNoteToBase64, recoverNotesFromIndex, registerViewingKey, relayRequestDigestHex, removePendingDeposit, removePendingWithdrawal, renderAssessment, resolveCircuitsBase, retryDelayMs, savePendingDeposit, savePendingWithdrawal, scanNotesForWallet, scanRecipientDeliveryNotes, scanTransactions, sdkLogger, selectUtxos, sendInstructions, sendRawTransaction, sendTransaction, serializeAuthTransactionMessage, serializeNote, serializeUtxo, setCircuitsPath, setDebugMode, signCompiledTransaction, signMessageBytes, signRelayAuthPayload, signTransaction, signerFromKeypair, signerFromSecretKey, signerFromWalletAdapter, splitTo2Limbs, submitTransactToRelay, sumUtxoAmounts, swapUtxo, swapWithChange, toAddress, toComplianceReport, transact, transactBatch, transactionBase64, transactionBytes, transactionFromBytes, transactionWireSize, transfer, truncate, tryDecryptNote, updateNoteWithDeposit, updatePendingDeposit, updatePendingWithdrawal, bigintToBytes32 as utxoBigintToBytes32, utxoEquals, hexToBigint as utxoHexToBigint, validateDepositParams, validateNote, validateOutputsSum, validatePaymasterTopUpTransaction, validateRoot, validateTransfers, validateWalletConnected, validateWithdrawableNote, verifyAllCircuits, verifyCircuitIntegrity, verifyQuoteSignature, verifyUtxos, waitForRoot, withShieldRetries, withTiming, withdrawFeeFor };
|
|
6473
|
+
export { BRIDGE_ESCROW_LABEL, BRIDGE_ESCROW_LABEL_V2, BUILD_ALLOWS_LOCAL_ENDPOINTS, type BridgeDeliveryState, type BridgeDeposit, type BridgeDepositState, type BridgeQuoteAssessment, type BridgeQuoteInput, type BridgeRail, type BridgeRailAttestation, type BridgeRailProblem, type BridgeRailQuoteOption, type BridgeRailQuoteRequest, type BridgeRailQuoteResponse, type BridgeRailStatusResult, type BuildRecipientDeliveryNotesParams, CHAIN_NOTE_SALT_BITS, CLEANUP_FEE_BUDGET, CLOAK_PRODUCTION_RELAY_URL, CLOAK_PROGRAM_ID, type ChainNoteTxType, type CircuitVerificationResult, type CleanupResult, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, type CloakRpc, type CommitmentEntry, type CommitmentsResponse, type CompactChainNote, type ComplianceReport, type ComplianceTxType, type ConfirmSettlementParams, type CreateRecoverableDepositUtxoParams, DEFAULT_CIRCUITS_URL, DEFAULT_TRANSACTION_CIRCUITS_URL, DELIVERY_MEMO_TAG, DELIVERY_REGISTRY_SEED, type DeliveredNote, DepositError, type DepositInstructionParams, type DepositNoteSecrets, type DepositOptions, type DepositOutcome, type DepositRef, type DepositResult, type DepositStatus, type DiscoverOptions, type DiscoverSwapRefundsOptions, type DiscoveredSwapRefund, DoNotRetry, ECONOMIC_MINIMUM, EXPECTED_CIRCUIT_HASHES, type EncodeNoteIndexPageParams, type EncryptedMetadataBundle, type EncryptedNote$1 as EncryptedNote, type ErrorCategory, type ExpandedSpendKey, type ExternalFeePayerAdapter, FEE_BUDGET, FIXED_FEE_LAMPORTS, type FundingPlan, type Groth16Proof, type IndexedRecoveredNote, type IndexedRecoveredNoteKind, InsecureRandomnessError, LAMPORTS_PER_SOL, type LegacyWalletAdapter, type WalletSigner as LegacyWalletSigner, LocalStorageAdapter, type LogLevel, type Logger, type LookupTable, MAINNET_RENT_0, MAINNET_RENT_1, MAX_RECEIVER_INDEX, MERKLE_TREE_HEIGHT, MIN_DEPOSIT_LAMPORTS, MIN_DEPOSIT_SPL_BASE_UNITS, type MasterKey, type MatchChangeNoteParams, type MatchDepositNoteParams, type MatchSwapRefundLeafParams, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, MerkleTree, type MessageSigner, NATIVE_SOL_MINT, NOTE_INDEX_NO_LEAF, NOTE_INDEX_PAGE_SIZE, type Network, type NoteData, type NoteIndexCursor, type NoteIndexDeliveryItem, type NoteIndexFetchOptions, NoteIndexFormatError, type NoteIndexHead, NoteIndexHeadBehindError, type NoteIndexItem, type NoteIndexPage, type NoteIndexRecoveryStats, type NoteIndexSwapRefundItem, type NoteIndexTxItem, ONECLICK_PUBKEY_B58, type OnchainMerkleProof, type ParseNoteIndexPageOptions, type ParsedDeliveryCarrier, type PaymasterTopUpExpectation, type PaymasterTopUpResult, type PendingDeposit, type PendingWithdrawal, type PostFailureVerdict, RECIPIENT_DELIVERY_CIPHERTEXT_LEN, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN, RECIPIENT_DELIVERY_NONCE_LEN, RECIPIENT_DELIVERY_NOTE_BYTES, RECIPIENT_DELIVERY_PLAINTEXT_LEN, RECIPIENT_DELIVERY_TAG_LEN, RELAY_BATCH_AUTH_MAX_ITEMS, RELAY_ORIGIN_ALLOWLIST, REQUEST_AUTH_BATCH_DOMAIN, REQUEST_AUTH_BATCH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS, type RecipientDeliveryNote, type RecoverNotesFromIndexParams, type RecoverNotesFromIndexResult, type RecoveredChangeNote, type RecoveredChangeNoteRecord, type RecoveredDepositNote, type RecoveredDepositNoteRecord, type RecoveredSwapRefund, type RelayAuthMode, type RelayAuthPreimage, type RelayAuthSigner, RelayBatchAuthCoordinator, type RelayBatchAuthCoordinatorOptions, type RelayBatchAuthEnvelope, type RelayBatchAuthFields, type RelayBatchAuthItemHandle, RelayInternalError, RelayService, type RelaySubmissionResult, type RentRates, type RetryHooks, type RiskQuoteInstructionResponse, RootNotFoundError, SCANNER_SUPPORTS_TRANSACT_SWAP, SIGN_IN_MESSAGE, SanctionsQuoteError, type ScanOptions, type ScanRecipientDeliveryOptions, type ScanResult, type ScanSummary, type ScannedTransaction, type SettlementConnection, type SettlementContext, type SettlementStatus, type SettlementVerdict, SettlementVerificationError, ShieldPoolErrors, type ShieldPoolPDAs, SimpleWallet, type SpendKey, type SpendOptions, type StorageAdapter, type SubmitTransactToRelayArgs, type SwapOptions, type SwapParams, type SwapRefundAuthorization, type SwapRefundShape, type SwapResult, TERMINAL_FAILURE, TRANSACTION_CIRCUITS_VERSION, TRANSACT_AUTH_FIELDS, TRANSACT_SWAP_AUTH_FIELDS, type TransactBatchItem, type TransactBatchItemOutcome, type TransactBatchOptions, type TransactBatchResult, type TransactOptions, type TransactParams, type TransactRequestBodyParams, type TransactResult, type TransactionBytesWallet, TransactionConfirmationError, type TransactionMetadata, type Transfer, type TransferOptions, type TransferResult, type TxStatus, type UserFriendlyError, type Utxo, UtxoAlreadySpentError, type EncryptedNote as UtxoEncryptedNote, type UtxoKeypair, type UtxoSwapParams, type UtxoSwapResult, UtxoWallet, VARIABLE_FEE_DENOMINATOR, VARIABLE_FEE_NUMERATOR, VARIABLE_FEE_RATE, VERSION, type VerifyUtxosResult, type ViewKey, type ViewingKeyPair, WITHDRAW_FEE_BPS, WITHDRAW_FIXED_FEE, type WalletAdapterBridgeOptions, type WalletSigner$1 as WalletSigner, type WalletUtxo, type Web3Module, type WithdrawOptions, type WithdrawSubmissionResult, accountMeta, addressBytes, addressFromBytes, addressFromPublicKey, assertDirectSubmissionLanded, assertInputMints, assertTransactionCircuitIntegrity, assessBridgeQuote, bigintToBytes32$1 as bigintToBytes32, bigintToHex, buildAuthTransactionMessage, buildMerkleTree, buildMerkleTreeFromChain, buildMerkleTreeFromRelay, buildRecipientDeliveryNotes, buildRelayAuthPreimage, buildRelayBatchAuthMessage, buildTransactRequestBody, buildTransactionMessage, bytesToHex, calculateFee, calculateFeeBigint, calculateRelayFee, canRebuildMerkleTreeFromChain, canonicalJson, canonicalPayloadString, chainNoteFromBase64, chainNoteToBase64, classifyPostFailure, classifyRelayError, cleanupReceivingAddress, cleanupStalePendingOperations, clearPendingDeposits, clearPendingWithdrawals, cloakBridgeRail, computeChainNoteHash, computeExtDataHash, computeMerkleRoot, computeNoteIndexChain, computeProofForLatestDeposit, computeProofFromChain, computeSignature, computeSwapRefundCommitment, computeCommitment as computeUtxoCommitment, computeNullifier as computeUtxoNullifier, confirmSignature, confirmTransactSettlement, copyNoteToClipboard, createCloakError, createCloakRpc, createDepositInstruction, createLogger, createRecoverableChangeUtxo, createRecoverableDepositUtxo, createRelayBatchAuthCoordinator, createUtxo, createZeroUtxo, decryptCompactChainNote, decryptComplianceMetadataWithMasterKey, decryptTransactionMetadata, depositFromDerivedKey, deriveBridgeReceiver, deriveChangeNoteBlinding, deriveDepositNoteBlinding, deriveDiversifiedViewingKey, deriveDiversifier, deriveFundingTargets, deriveInputNullifierPdas, deriveLegacyBridgeReceiver, deriveLegacyDepositNoteSecrets, deriveLegacySwapRefundAuthorization, derivePublicKey, deriveSpendKey, deriveSwapRefundAuthorization, deriveSwapRefundBlinding, deriveSwapRefundKeypair, deriveUserCompliancePublicKey, deriveUserComplianceScalar, deriveUtxoKeypairFromSpendKey, deriveViewKey, deriveViewingKeyFromNk, deriveViewingKeyFromSpendKey, deriveViewingKeyFromUtxoPrivateKey, deserializeUtxo, detectNetworkFromRpcUrl, discoverSwapRefunds, downloadNote, encodeDeliveryCarrierMemo, encodeNoteIndexItem, encodeNoteIndexPage, encodeNoteSimple, encodeRecipientDeliveryNote, encryptCompactChainNote, encryptNoteForRecipient, encryptTransactionMetadata, encryptTransactionMetadataBundle, expandSpendKey, explainRelayAuthRejection, exportKeys, exportNote, exportWalletKeys, fetchAccountBytes, fetchCommitments, fetchLatestBlockhash, fetchLookupTables, fetchNoteIndexHead, fetchNoteIndexPage, fetchRiskQuoteInstruction, fetchRiskQuoteIx, fetchSignaturesForAddress, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, findProgramAddress, formatAmount, formatComplianceCsv, formatErrorForLogging, formatSol, fullWithdraw, fundReceiverViaPaymaster, generateCloakKeys, generateCommitmentAsync, generateMasterSeed, generateNoteFromWallet, generateUtxoKeypair, generateViewingKeyPair, getAddressExplorerUrl, getChainNoteRegistryPDA, getCircuitsPath, getDeliveryRegistryPDA, getDistributableAmount, getExplorerUrl, getNkFromUtxoPrivateKey, getNullifierPDA, getPendingOperationsSummary, getPoolAuthorityConfigPDA, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getSwapStatePDA, getViewKey, hasPendingOperations, hexToBigint$1 as hexToBigint, hexToBytes, importKeys, importWalletKeys, isBrowser, isBrowserLike, isDebugEnabled, isMessageSigner, isPlausibleSignature, isReactNative, isRootNotFoundError, isSubmissionOutcomeUnknownResponse, isTerminalFailure, isValidHex, isValidRpcUrl, isValidSolanaAddress, isWithdrawAmountSufficient, isWithdrawable, listBridgeDeposits, loadPendingDeposits, loadPendingWithdrawals, loadVerifiedCircuitArtifacts, matchChangeNote, matchDepositNote, matchSwapRefundLeaf, mayRetry, messageSignerFromCallback, openRecipientDeliveryNote, parseAmount, parseDeliveryCarrierMemo, parseError, parseNote, parseNoteIndexItem, parseNoteIndexPage, parseRelayErrorResponse, parseRelayErrorSignature, parseTransactionError, partialWithdraw, partiallySignTransaction, poseidonHash, preflightCheck, preflightNullifiers, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, programInstruction, proofToBytes, pubkeyToFieldElement, pubkeyToLimbs, randomBytes, randomChangeNoteSalt, randomDepositNoteSalt, randomFieldElement, readMerkleTreeState, readRent, recipientDeliveryNoteToBase64, recoverNotesFromIndex, registerViewingKey, relayRequestDigestHex, removePendingDeposit, removePendingWithdrawal, renderAssessment, resolveCircuitsBase, retryDelayMs, savePendingDeposit, savePendingWithdrawal, scanNotesForWallet, scanRecipientDeliveryNotes, scanTransactions, sdkLogger, selectUtxos, sendInstructions, sendRawTransaction, sendTransaction, serializeAuthTransactionMessage, serializeNote, serializeUtxo, setCircuitsPath, setDebugMode, signCompiledTransaction, signMessageBytes, signRelayAuthPayload, signTransaction, signerFromKeypair, signerFromSecretKey, signerFromTransactionBytes, signerFromWalletAdapter, splitTo2Limbs, submitTransactToRelay, sumUtxoAmounts, swapUtxo, swapWithChange, toAddress, toComplianceReport, transact, transactBatch, transactionBase64, transactionBytes, transactionFromBytes, transactionWireSize, transfer, truncate, tryDecryptNote, updateNoteWithDeposit, updatePendingDeposit, updatePendingWithdrawal, bigintToBytes32 as utxoBigintToBytes32, utxoEquals, hexToBigint as utxoHexToBigint, validateDepositParams, validateNote, validateOutputsSum, validatePaymasterTopUpTransaction, validateRoot, validateTransfers, validateWalletConnected, validateWithdrawableNote, verifyAllCircuits, verifyCircuitIntegrity, verifyQuoteSignature, verifyUtxos, waitForRoot, withShieldRetries, withTiming, withdrawFeeFor };
|
package/dist/index.d.ts
CHANGED
|
@@ -3872,8 +3872,10 @@ interface UtxoSwapResult extends TransactResult {
|
|
|
3872
3872
|
* `SwapState.sol_amount`, = gross swap amount minus the on-chain swap fee). R_fb is an ordinary
|
|
3873
3873
|
* leaf of the main pool tree, spent with the ordinary `transact()` path. All values are hex.
|
|
3874
3874
|
*
|
|
3875
|
-
* `publicKey` is
|
|
3876
|
-
*
|
|
3875
|
+
* `publicKey` is a PER-SWAP public key, derived from `options.ownerUtxoKeypair`'s private key and
|
|
3876
|
+
* the swap's first input nullifier, so no two swaps from one wallet share it and it is not the
|
|
3877
|
+
* wallet's UTXO public key. Spend R_fb with `deriveSwapRefundKeypair(owner, nullifier)`; the
|
|
3878
|
+
* private key is deliberately not repeated here and `nk` cannot produce it. The
|
|
3877
3879
|
* blinding is derived from the wallet's `nk` and the swap's public first input nullifier
|
|
3878
3880
|
* (`derivedFromNk` is always true), so `discoverSwapRefunds` finds the leaf again from key
|
|
3879
3881
|
* material if this object is lost.
|
|
@@ -4658,26 +4660,34 @@ declare function matchChangeNote(params: MatchChangeNoteParams): Promise<Recover
|
|
|
4658
4660
|
* viewing key and the swap creator's, and found nothing under either.
|
|
4659
4661
|
*
|
|
4660
4662
|
* ── The fix, and why it is SDK-only ───────────────────────────────────────────────────────────
|
|
4661
|
-
* The refund leaf is
|
|
4662
|
-
* its
|
|
4663
|
+
* The refund leaf's BLINDING is derived as a PRF of the owner's `nk` and the swap's own first input
|
|
4664
|
+
* nullifier, and its OWNER KEY is derived per swap from the wallet's UTXO private key:
|
|
4663
4665
|
*
|
|
4664
|
-
* blinding = BLAKE3("cloak_swap_refund_v1" || nk || nullifier0 || "blinding")
|
|
4665
|
-
*
|
|
4666
|
+
* blinding = BLAKE3("cloak_swap_refund_v1" || nk || nullifier0 || "blinding") -> field
|
|
4667
|
+
* priv = BLAKE3("cloak_swap_refund_v2" || ownerPrivateKey || nullifier0 || "sk_v2") -> field
|
|
4668
|
+
* pub = derivePublicKey(priv)
|
|
4666
4669
|
*
|
|
4667
|
-
* `nullifier0` is published in the TransactSwap public inputs, so a scanner holding `nk`
|
|
4668
|
-
*
|
|
4669
|
-
*
|
|
4670
|
-
*
|
|
4671
|
-
* blinding
|
|
4670
|
+
* `nullifier0` is published in the TransactSwap public inputs, so a scanner holding `nk` can replay
|
|
4671
|
+
* the blinding for every swap it sees. `refund_pubkey` and `refund_blinding` are ALSO published, in
|
|
4672
|
+
* plain text, in the TransactSwap instruction data (and in SwapState), so a view-only scanner (nk
|
|
4673
|
+
* plus the owner PUBLIC key) reads the per-swap pubkey from there, checks that the published
|
|
4674
|
+
* blinding equals the nk-derived one, and checks that the commitment matches. Spending R_fb needs
|
|
4675
|
+
* `priv`, which needs the owner's private key: `nk` cannot produce it, so the viewing key stays
|
|
4676
|
+
* view-only, and the owner re-derives the spend key from its own private key plus the nullifier.
|
|
4677
|
+
*
|
|
4678
|
+
* Why not the owner key itself (0.2.6 - 0.2.8)? That shape published the wallet's permanent UTXO
|
|
4679
|
+
* public key as `refund_pubkey` on every swap, so anyone holding a user's receiving key could list
|
|
4680
|
+
* all of that wallet's swaps. A different public key per swap removes the link.
|
|
4672
4681
|
*
|
|
4673
4682
|
* This changes NOTHING on chain or in the relay. `refund_pubkey` / `refund_blinding` remain
|
|
4674
4683
|
* caller-supplied values bound into `computeSwapExtDataHash`; only their provenance changes.
|
|
4675
4684
|
*
|
|
4676
|
-
* ──
|
|
4677
|
-
*
|
|
4678
|
-
*
|
|
4679
|
-
*
|
|
4680
|
-
*
|
|
4685
|
+
* ── Three refund shapes, all still recognised ─────────────────────────────────────────────────
|
|
4686
|
+
* "per-swap" (0.2.9+) owner = per-swap key from the owner private key (above)
|
|
4687
|
+
* "owner" (0.2.6 - 0.2.8) owner = the wallet's permanent UTXO keypair; linkable across swaps
|
|
4688
|
+
* "legacy-nk" (< 0.2.6) owner key AND blinding from nk; `legacyExposed: true`, because anyone
|
|
4689
|
+
* holding `nk` can spend it. An app should migrate those refunds.
|
|
4690
|
+
* No API builds a refund in the last two shapes any more.
|
|
4681
4691
|
*
|
|
4682
4692
|
* ── Guardrails preserved ──────────────────────────────────────────────────────────────────────
|
|
4683
4693
|
* [H-04 / DD-01] the authorization is rejected unless publicKey and blinding are both non-zero.
|
|
@@ -4698,14 +4708,20 @@ interface SwapRefundAuthorization {
|
|
|
4698
4708
|
publicKey: bigint;
|
|
4699
4709
|
blinding: bigint;
|
|
4700
4710
|
}
|
|
4711
|
+
/** Which key shape owns a refund leaf; see the file header. */
|
|
4712
|
+
type SwapRefundShape = "per-swap" | "owner" | "legacy-nk";
|
|
4701
4713
|
/** A refund leaf matched back to its owner. */
|
|
4702
4714
|
interface RecoveredSwapRefund {
|
|
4703
4715
|
/**
|
|
4704
|
-
* The
|
|
4705
|
-
* (`privateKey` is `0n`
|
|
4706
|
-
*
|
|
4716
|
+
* The key that owns the leaf. `per-swap`: the key derived from the owner private key and the
|
|
4717
|
+
* swap nullifier (`privateKey` is `0n` for a view-only match: the public key is real, but the
|
|
4718
|
+
* spend key needs the owner private key, see {@link deriveSwapRefundKeypair}). `owner`: the
|
|
4719
|
+
* `ownerUtxoKeypair` the matcher was given (`privateKey` `0n` if only the public key was
|
|
4720
|
+
* supplied). `legacy-nk`: the nk-derived keypair, complete and spendable.
|
|
4707
4721
|
*/
|
|
4708
4722
|
keypair: UtxoKeypair;
|
|
4723
|
+
/** Which of the three shapes matched. */
|
|
4724
|
+
shape: SwapRefundShape;
|
|
4709
4725
|
blinding: bigint;
|
|
4710
4726
|
amount: bigint;
|
|
4711
4727
|
/** R_fb as a field element, identical to the commitment `CloseSwapState` appended. */
|
|
@@ -4724,8 +4740,15 @@ interface RecoveredSwapRefund {
|
|
|
4724
4740
|
*/
|
|
4725
4741
|
declare function deriveSwapRefundBlinding(viewingKeyNk: Uint8Array, inputNullifier: Uint8Array | bigint): bigint;
|
|
4726
4742
|
/**
|
|
4727
|
-
* The refund
|
|
4728
|
-
*
|
|
4743
|
+
* The per-swap refund KEYPAIR: a different key for every swap, derived from the owner's private key
|
|
4744
|
+
* and the swap's first input nullifier. `nk` cannot reproduce it. Use this to spend a refund the
|
|
4745
|
+
* swap result reported, or any `per-swap` refund a view-only scan found.
|
|
4746
|
+
*/
|
|
4747
|
+
declare function deriveSwapRefundKeypair(ownerUtxoKeypair: UtxoKeypair, inputNullifier: Uint8Array | bigint): Promise<UtxoKeypair>;
|
|
4748
|
+
/**
|
|
4749
|
+
* The refund authorization `swapUtxo` binds into the swap ext-data hash: a per-swap keypair derived
|
|
4750
|
+
* from the wallet's UTXO private key and the swap's first input nullifier, plus the nk-derived
|
|
4751
|
+
* blinding. The public key differs for every swap and differs from the wallet's UTXO public key.
|
|
4729
4752
|
*
|
|
4730
4753
|
* `ownerUtxoKeypair` is required and validated. The refund key is never derived from `nk`.
|
|
4731
4754
|
*/
|
|
@@ -4752,16 +4775,28 @@ interface MatchSwapRefundLeafParams {
|
|
|
4752
4775
|
commitment: bigint | Uint8Array;
|
|
4753
4776
|
/**
|
|
4754
4777
|
* The wallet's long-lived UTXO keypair (`privateKey: 0n` is fine for a view-only match). Without
|
|
4755
|
-
* it only legacy refunds can be matched.
|
|
4778
|
+
* it only legacy-nk refunds can be matched.
|
|
4756
4779
|
*/
|
|
4757
4780
|
ownerUtxoKeypair?: UtxoKeypair;
|
|
4781
|
+
/**
|
|
4782
|
+
* `refund_pubkey` as published in the swap's TransactSwap instruction data (bytes 593-624) or its
|
|
4783
|
+
* SwapState. A view-only scanner needs it to match a `per-swap` refund, because it cannot derive
|
|
4784
|
+
* the key. Pass it together with {@link publishedRefundBlinding}.
|
|
4785
|
+
*/
|
|
4786
|
+
publishedRefundPubkey?: bigint | Uint8Array;
|
|
4787
|
+
/** `refund_blinding` as published in the same place (bytes 625-656). */
|
|
4788
|
+
publishedRefundBlinding?: bigint | Uint8Array;
|
|
4758
4789
|
}
|
|
4759
4790
|
/**
|
|
4760
4791
|
* Decide whether a public refund leaf belongs to this wallet, and if so return it. Returns `null`
|
|
4761
4792
|
* for every leaf that is not ours; a scanner runs this against every close it can see.
|
|
4762
4793
|
*
|
|
4763
|
-
* Tries the
|
|
4764
|
-
*
|
|
4794
|
+
* Tries, in order: the per-swap shape (published pubkey, or re-derived when the owner private key
|
|
4795
|
+
* is present), the 0.2.6 - 0.2.8 owner-key shape, then the legacy nk shape (`legacyExposed`).
|
|
4796
|
+
* `shape` on the result says which one matched.
|
|
4797
|
+
*
|
|
4798
|
+
* A per-swap match from a view-only scan returns `keypair.privateKey === 0n`; the caller spends it
|
|
4799
|
+
* with {@link deriveSwapRefundKeypair} once it holds the owner private key.
|
|
4765
4800
|
*/
|
|
4766
4801
|
declare function matchSwapRefundLeaf(params: MatchSwapRefundLeafParams): Promise<RecoveredSwapRefund | null>;
|
|
4767
4802
|
/** One recovered refund leaf, with the chain coordinates that produced it. */
|
|
@@ -4777,9 +4812,11 @@ interface DiscoveredSwapRefund extends RecoveredSwapRefund {
|
|
|
4777
4812
|
}
|
|
4778
4813
|
interface DiscoverSwapRefundsOptions {
|
|
4779
4814
|
/**
|
|
4780
|
-
* The wallet's long-lived UTXO keypair
|
|
4781
|
-
*
|
|
4782
|
-
* for a view-only scan
|
|
4815
|
+
* The wallet's long-lived UTXO keypair. Required. Pass the real keypair to get spendable
|
|
4816
|
+
* results (per-swap refunds come back with their derived keypair), or `{ privateKey: 0n,
|
|
4817
|
+
* publicKey }` for a view-only scan: per-swap refunds are then matched from the `refund_pubkey`
|
|
4818
|
+
* published in the swap instruction and come back with `privateKey: 0n` (re-derive it with
|
|
4819
|
+
* `deriveSwapRefundKeypair`). Legacy (nk-owned) refunds are found either way and flagged
|
|
4783
4820
|
* `legacyExposed`.
|
|
4784
4821
|
*/
|
|
4785
4822
|
ownerUtxoKeypair: UtxoKeypair;
|
|
@@ -4807,7 +4844,7 @@ interface DiscoverSwapRefundsOptions {
|
|
|
4807
4844
|
* its owner could not see it under any key they held.
|
|
4808
4845
|
*
|
|
4809
4846
|
* FORWARD-LOOKING ONLY. This finds refunds whose blinding was DERIVED from (nk, nullifier0), owned
|
|
4810
|
-
*
|
|
4847
|
+
* by a per-swap key (0.2.9+), the wallet UTXO key (0.2.6-0.2.8) or an nk-derived key (legacy, flagged).
|
|
4811
4848
|
* A swap whose refund keypair and blinding were drawn from raw randomness (every swap submitted
|
|
4812
4849
|
* before that derivation shipped) has no derivation to replay,
|
|
4813
4850
|
* and no key-only scan can ever recover it. Those secrets existed solely in the caller's in-memory
|
|
@@ -5754,6 +5791,18 @@ interface WalletAdapterBridgeOptions {
|
|
|
5754
5791
|
web3?: Web3Module;
|
|
5755
5792
|
}
|
|
5756
5793
|
declare function signerFromWalletAdapter(adapter: LegacyWalletAdapter, options?: WalletAdapterBridgeOptions): WalletSigner;
|
|
5794
|
+
/**
|
|
5795
|
+
* A wallet that signs a transaction given its wire bytes and returns the signed wire bytes: the
|
|
5796
|
+
* shape of the Wallet Standard `solana:signTransaction` feature. This is the bridge to use for a
|
|
5797
|
+
* Transaction V1 message, which `@solana/web3.js` 1.x cannot serialize; it works for v0 and legacy
|
|
5798
|
+
* messages too, and needs no web3.js at all.
|
|
5799
|
+
*/
|
|
5800
|
+
interface TransactionBytesWallet {
|
|
5801
|
+
address: Address;
|
|
5802
|
+
signTransaction(transactionBytes: Uint8Array): Promise<Uint8Array>;
|
|
5803
|
+
signMessage?: (message: Uint8Array) => Promise<Uint8Array>;
|
|
5804
|
+
}
|
|
5805
|
+
declare function signerFromTransactionBytes(wallet: TransactionBytesWallet): WalletSigner;
|
|
5757
5806
|
type Web3Module = {
|
|
5758
5807
|
VersionedTransaction: {
|
|
5759
5808
|
deserialize(bytes: Uint8Array): unknown;
|
|
@@ -6421,4 +6470,4 @@ declare const VERSION = "0.2.6";
|
|
|
6421
6470
|
/** True when scanner supports TransactSwap (tag 1). Check this to verify the correct SDK bundle is loaded. */
|
|
6422
6471
|
declare const SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
6423
6472
|
|
|
6424
|
-
export { BRIDGE_ESCROW_LABEL, BRIDGE_ESCROW_LABEL_V2, BUILD_ALLOWS_LOCAL_ENDPOINTS, type BridgeDeliveryState, type BridgeDeposit, type BridgeDepositState, type BridgeQuoteAssessment, type BridgeQuoteInput, type BridgeRail, type BridgeRailAttestation, type BridgeRailProblem, type BridgeRailQuoteOption, type BridgeRailQuoteRequest, type BridgeRailQuoteResponse, type BridgeRailStatusResult, type BuildRecipientDeliveryNotesParams, CHAIN_NOTE_SALT_BITS, CLEANUP_FEE_BUDGET, CLOAK_PRODUCTION_RELAY_URL, CLOAK_PROGRAM_ID, type ChainNoteTxType, type CircuitVerificationResult, type CleanupResult, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, type CloakRpc, type CommitmentEntry, type CommitmentsResponse, type CompactChainNote, type ComplianceReport, type ComplianceTxType, type ConfirmSettlementParams, type CreateRecoverableDepositUtxoParams, DEFAULT_CIRCUITS_URL, DEFAULT_TRANSACTION_CIRCUITS_URL, DELIVERY_MEMO_TAG, DELIVERY_REGISTRY_SEED, type DeliveredNote, DepositError, type DepositInstructionParams, type DepositNoteSecrets, type DepositOptions, type DepositOutcome, type DepositRef, type DepositResult, type DepositStatus, type DiscoverOptions, type DiscoverSwapRefundsOptions, type DiscoveredSwapRefund, DoNotRetry, ECONOMIC_MINIMUM, EXPECTED_CIRCUIT_HASHES, type EncodeNoteIndexPageParams, type EncryptedMetadataBundle, type EncryptedNote$1 as EncryptedNote, type ErrorCategory, type ExpandedSpendKey, type ExternalFeePayerAdapter, FEE_BUDGET, FIXED_FEE_LAMPORTS, type FundingPlan, type Groth16Proof, type IndexedRecoveredNote, type IndexedRecoveredNoteKind, InsecureRandomnessError, LAMPORTS_PER_SOL, type LegacyWalletAdapter, type WalletSigner as LegacyWalletSigner, LocalStorageAdapter, type LogLevel, type Logger, type LookupTable, MAINNET_RENT_0, MAINNET_RENT_1, MAX_RECEIVER_INDEX, MERKLE_TREE_HEIGHT, MIN_DEPOSIT_LAMPORTS, MIN_DEPOSIT_SPL_BASE_UNITS, type MasterKey, type MatchChangeNoteParams, type MatchDepositNoteParams, type MatchSwapRefundLeafParams, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, MerkleTree, type MessageSigner, NATIVE_SOL_MINT, NOTE_INDEX_NO_LEAF, NOTE_INDEX_PAGE_SIZE, type Network, type NoteData, type NoteIndexCursor, type NoteIndexDeliveryItem, type NoteIndexFetchOptions, NoteIndexFormatError, type NoteIndexHead, NoteIndexHeadBehindError, type NoteIndexItem, type NoteIndexPage, type NoteIndexRecoveryStats, type NoteIndexSwapRefundItem, type NoteIndexTxItem, ONECLICK_PUBKEY_B58, type OnchainMerkleProof, type ParseNoteIndexPageOptions, type ParsedDeliveryCarrier, type PaymasterTopUpExpectation, type PaymasterTopUpResult, type PendingDeposit, type PendingWithdrawal, type PostFailureVerdict, RECIPIENT_DELIVERY_CIPHERTEXT_LEN, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN, RECIPIENT_DELIVERY_NONCE_LEN, RECIPIENT_DELIVERY_NOTE_BYTES, RECIPIENT_DELIVERY_PLAINTEXT_LEN, RECIPIENT_DELIVERY_TAG_LEN, RELAY_BATCH_AUTH_MAX_ITEMS, RELAY_ORIGIN_ALLOWLIST, REQUEST_AUTH_BATCH_DOMAIN, REQUEST_AUTH_BATCH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS, type RecipientDeliveryNote, type RecoverNotesFromIndexParams, type RecoverNotesFromIndexResult, type RecoveredChangeNote, type RecoveredChangeNoteRecord, type RecoveredDepositNote, type RecoveredDepositNoteRecord, type RecoveredSwapRefund, type RelayAuthMode, type RelayAuthPreimage, type RelayAuthSigner, RelayBatchAuthCoordinator, type RelayBatchAuthCoordinatorOptions, type RelayBatchAuthEnvelope, type RelayBatchAuthFields, type RelayBatchAuthItemHandle, RelayInternalError, RelayService, type RelaySubmissionResult, type RentRates, type RetryHooks, type RiskQuoteInstructionResponse, RootNotFoundError, SCANNER_SUPPORTS_TRANSACT_SWAP, SIGN_IN_MESSAGE, SanctionsQuoteError, type ScanOptions, type ScanRecipientDeliveryOptions, type ScanResult, type ScanSummary, type ScannedTransaction, type SettlementConnection, type SettlementContext, type SettlementStatus, type SettlementVerdict, SettlementVerificationError, ShieldPoolErrors, type ShieldPoolPDAs, SimpleWallet, type SpendKey, type SpendOptions, type StorageAdapter, type SubmitTransactToRelayArgs, type SwapOptions, type SwapParams, type SwapRefundAuthorization, type SwapResult, TERMINAL_FAILURE, TRANSACTION_CIRCUITS_VERSION, TRANSACT_AUTH_FIELDS, TRANSACT_SWAP_AUTH_FIELDS, type TransactBatchItem, type TransactBatchItemOutcome, type TransactBatchOptions, type TransactBatchResult, type TransactOptions, type TransactParams, type TransactRequestBodyParams, type TransactResult, TransactionConfirmationError, type TransactionMetadata, type Transfer, type TransferOptions, type TransferResult, type TxStatus, type UserFriendlyError, type Utxo, UtxoAlreadySpentError, type EncryptedNote as UtxoEncryptedNote, type UtxoKeypair, type UtxoSwapParams, type UtxoSwapResult, UtxoWallet, VARIABLE_FEE_DENOMINATOR, VARIABLE_FEE_NUMERATOR, VARIABLE_FEE_RATE, VERSION, type VerifyUtxosResult, type ViewKey, type ViewingKeyPair, WITHDRAW_FEE_BPS, WITHDRAW_FIXED_FEE, type WalletAdapterBridgeOptions, type WalletSigner$1 as WalletSigner, type WalletUtxo, type Web3Module, type WithdrawOptions, type WithdrawSubmissionResult, accountMeta, addressBytes, addressFromBytes, addressFromPublicKey, assertDirectSubmissionLanded, assertInputMints, assertTransactionCircuitIntegrity, assessBridgeQuote, bigintToBytes32$1 as bigintToBytes32, bigintToHex, buildAuthTransactionMessage, buildMerkleTree, buildMerkleTreeFromChain, buildMerkleTreeFromRelay, buildRecipientDeliveryNotes, buildRelayAuthPreimage, buildRelayBatchAuthMessage, buildTransactRequestBody, buildTransactionMessage, bytesToHex, calculateFee, calculateFeeBigint, calculateRelayFee, canRebuildMerkleTreeFromChain, canonicalJson, canonicalPayloadString, chainNoteFromBase64, chainNoteToBase64, classifyPostFailure, classifyRelayError, cleanupReceivingAddress, cleanupStalePendingOperations, clearPendingDeposits, clearPendingWithdrawals, cloakBridgeRail, computeChainNoteHash, computeExtDataHash, computeMerkleRoot, computeNoteIndexChain, computeProofForLatestDeposit, computeProofFromChain, computeSignature, computeSwapRefundCommitment, computeCommitment as computeUtxoCommitment, computeNullifier as computeUtxoNullifier, confirmSignature, confirmTransactSettlement, copyNoteToClipboard, createCloakError, createCloakRpc, createDepositInstruction, createLogger, createRecoverableChangeUtxo, createRecoverableDepositUtxo, createRelayBatchAuthCoordinator, createUtxo, createZeroUtxo, decryptCompactChainNote, decryptComplianceMetadataWithMasterKey, decryptTransactionMetadata, depositFromDerivedKey, deriveBridgeReceiver, deriveChangeNoteBlinding, deriveDepositNoteBlinding, deriveDiversifiedViewingKey, deriveDiversifier, deriveFundingTargets, deriveInputNullifierPdas, deriveLegacyBridgeReceiver, deriveLegacyDepositNoteSecrets, deriveLegacySwapRefundAuthorization, derivePublicKey, deriveSpendKey, deriveSwapRefundAuthorization, deriveSwapRefundBlinding, deriveUserCompliancePublicKey, deriveUserComplianceScalar, deriveUtxoKeypairFromSpendKey, deriveViewKey, deriveViewingKeyFromNk, deriveViewingKeyFromSpendKey, deriveViewingKeyFromUtxoPrivateKey, deserializeUtxo, detectNetworkFromRpcUrl, discoverSwapRefunds, downloadNote, encodeDeliveryCarrierMemo, encodeNoteIndexItem, encodeNoteIndexPage, encodeNoteSimple, encodeRecipientDeliveryNote, encryptCompactChainNote, encryptNoteForRecipient, encryptTransactionMetadata, encryptTransactionMetadataBundle, expandSpendKey, explainRelayAuthRejection, exportKeys, exportNote, exportWalletKeys, fetchAccountBytes, fetchCommitments, fetchLatestBlockhash, fetchLookupTables, fetchNoteIndexHead, fetchNoteIndexPage, fetchRiskQuoteInstruction, fetchRiskQuoteIx, fetchSignaturesForAddress, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, findProgramAddress, formatAmount, formatComplianceCsv, formatErrorForLogging, formatSol, fullWithdraw, fundReceiverViaPaymaster, generateCloakKeys, generateCommitmentAsync, generateMasterSeed, generateNoteFromWallet, generateUtxoKeypair, generateViewingKeyPair, getAddressExplorerUrl, getChainNoteRegistryPDA, getCircuitsPath, getDeliveryRegistryPDA, getDistributableAmount, getExplorerUrl, getNkFromUtxoPrivateKey, getNullifierPDA, getPendingOperationsSummary, getPoolAuthorityConfigPDA, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getSwapStatePDA, getViewKey, hasPendingOperations, hexToBigint$1 as hexToBigint, hexToBytes, importKeys, importWalletKeys, isBrowser, isBrowserLike, isDebugEnabled, isMessageSigner, isPlausibleSignature, isReactNative, isRootNotFoundError, isSubmissionOutcomeUnknownResponse, isTerminalFailure, isValidHex, isValidRpcUrl, isValidSolanaAddress, isWithdrawAmountSufficient, isWithdrawable, listBridgeDeposits, loadPendingDeposits, loadPendingWithdrawals, loadVerifiedCircuitArtifacts, matchChangeNote, matchDepositNote, matchSwapRefundLeaf, mayRetry, messageSignerFromCallback, openRecipientDeliveryNote, parseAmount, parseDeliveryCarrierMemo, parseError, parseNote, parseNoteIndexItem, parseNoteIndexPage, parseRelayErrorResponse, parseRelayErrorSignature, parseTransactionError, partialWithdraw, partiallySignTransaction, poseidonHash, preflightCheck, preflightNullifiers, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, programInstruction, proofToBytes, pubkeyToFieldElement, pubkeyToLimbs, randomBytes, randomChangeNoteSalt, randomDepositNoteSalt, randomFieldElement, readMerkleTreeState, readRent, recipientDeliveryNoteToBase64, recoverNotesFromIndex, registerViewingKey, relayRequestDigestHex, removePendingDeposit, removePendingWithdrawal, renderAssessment, resolveCircuitsBase, retryDelayMs, savePendingDeposit, savePendingWithdrawal, scanNotesForWallet, scanRecipientDeliveryNotes, scanTransactions, sdkLogger, selectUtxos, sendInstructions, sendRawTransaction, sendTransaction, serializeAuthTransactionMessage, serializeNote, serializeUtxo, setCircuitsPath, setDebugMode, signCompiledTransaction, signMessageBytes, signRelayAuthPayload, signTransaction, signerFromKeypair, signerFromSecretKey, signerFromWalletAdapter, splitTo2Limbs, submitTransactToRelay, sumUtxoAmounts, swapUtxo, swapWithChange, toAddress, toComplianceReport, transact, transactBatch, transactionBase64, transactionBytes, transactionFromBytes, transactionWireSize, transfer, truncate, tryDecryptNote, updateNoteWithDeposit, updatePendingDeposit, updatePendingWithdrawal, bigintToBytes32 as utxoBigintToBytes32, utxoEquals, hexToBigint as utxoHexToBigint, validateDepositParams, validateNote, validateOutputsSum, validatePaymasterTopUpTransaction, validateRoot, validateTransfers, validateWalletConnected, validateWithdrawableNote, verifyAllCircuits, verifyCircuitIntegrity, verifyQuoteSignature, verifyUtxos, waitForRoot, withShieldRetries, withTiming, withdrawFeeFor };
|
|
6473
|
+
export { BRIDGE_ESCROW_LABEL, BRIDGE_ESCROW_LABEL_V2, BUILD_ALLOWS_LOCAL_ENDPOINTS, type BridgeDeliveryState, type BridgeDeposit, type BridgeDepositState, type BridgeQuoteAssessment, type BridgeQuoteInput, type BridgeRail, type BridgeRailAttestation, type BridgeRailProblem, type BridgeRailQuoteOption, type BridgeRailQuoteRequest, type BridgeRailQuoteResponse, type BridgeRailStatusResult, type BuildRecipientDeliveryNotesParams, CHAIN_NOTE_SALT_BITS, CLEANUP_FEE_BUDGET, CLOAK_PRODUCTION_RELAY_URL, CLOAK_PROGRAM_ID, type ChainNoteTxType, type CircuitVerificationResult, type CleanupResult, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, type CloakRpc, type CommitmentEntry, type CommitmentsResponse, type CompactChainNote, type ComplianceReport, type ComplianceTxType, type ConfirmSettlementParams, type CreateRecoverableDepositUtxoParams, DEFAULT_CIRCUITS_URL, DEFAULT_TRANSACTION_CIRCUITS_URL, DELIVERY_MEMO_TAG, DELIVERY_REGISTRY_SEED, type DeliveredNote, DepositError, type DepositInstructionParams, type DepositNoteSecrets, type DepositOptions, type DepositOutcome, type DepositRef, type DepositResult, type DepositStatus, type DiscoverOptions, type DiscoverSwapRefundsOptions, type DiscoveredSwapRefund, DoNotRetry, ECONOMIC_MINIMUM, EXPECTED_CIRCUIT_HASHES, type EncodeNoteIndexPageParams, type EncryptedMetadataBundle, type EncryptedNote$1 as EncryptedNote, type ErrorCategory, type ExpandedSpendKey, type ExternalFeePayerAdapter, FEE_BUDGET, FIXED_FEE_LAMPORTS, type FundingPlan, type Groth16Proof, type IndexedRecoveredNote, type IndexedRecoveredNoteKind, InsecureRandomnessError, LAMPORTS_PER_SOL, type LegacyWalletAdapter, type WalletSigner as LegacyWalletSigner, LocalStorageAdapter, type LogLevel, type Logger, type LookupTable, MAINNET_RENT_0, MAINNET_RENT_1, MAX_RECEIVER_INDEX, MERKLE_TREE_HEIGHT, MIN_DEPOSIT_LAMPORTS, MIN_DEPOSIT_SPL_BASE_UNITS, type MasterKey, type MatchChangeNoteParams, type MatchDepositNoteParams, type MatchSwapRefundLeafParams, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, MerkleTree, type MessageSigner, NATIVE_SOL_MINT, NOTE_INDEX_NO_LEAF, NOTE_INDEX_PAGE_SIZE, type Network, type NoteData, type NoteIndexCursor, type NoteIndexDeliveryItem, type NoteIndexFetchOptions, NoteIndexFormatError, type NoteIndexHead, NoteIndexHeadBehindError, type NoteIndexItem, type NoteIndexPage, type NoteIndexRecoveryStats, type NoteIndexSwapRefundItem, type NoteIndexTxItem, ONECLICK_PUBKEY_B58, type OnchainMerkleProof, type ParseNoteIndexPageOptions, type ParsedDeliveryCarrier, type PaymasterTopUpExpectation, type PaymasterTopUpResult, type PendingDeposit, type PendingWithdrawal, type PostFailureVerdict, RECIPIENT_DELIVERY_CIPHERTEXT_LEN, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN, RECIPIENT_DELIVERY_NONCE_LEN, RECIPIENT_DELIVERY_NOTE_BYTES, RECIPIENT_DELIVERY_PLAINTEXT_LEN, RECIPIENT_DELIVERY_TAG_LEN, RELAY_BATCH_AUTH_MAX_ITEMS, RELAY_ORIGIN_ALLOWLIST, REQUEST_AUTH_BATCH_DOMAIN, REQUEST_AUTH_BATCH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS, type RecipientDeliveryNote, type RecoverNotesFromIndexParams, type RecoverNotesFromIndexResult, type RecoveredChangeNote, type RecoveredChangeNoteRecord, type RecoveredDepositNote, type RecoveredDepositNoteRecord, type RecoveredSwapRefund, type RelayAuthMode, type RelayAuthPreimage, type RelayAuthSigner, RelayBatchAuthCoordinator, type RelayBatchAuthCoordinatorOptions, type RelayBatchAuthEnvelope, type RelayBatchAuthFields, type RelayBatchAuthItemHandle, RelayInternalError, RelayService, type RelaySubmissionResult, type RentRates, type RetryHooks, type RiskQuoteInstructionResponse, RootNotFoundError, SCANNER_SUPPORTS_TRANSACT_SWAP, SIGN_IN_MESSAGE, SanctionsQuoteError, type ScanOptions, type ScanRecipientDeliveryOptions, type ScanResult, type ScanSummary, type ScannedTransaction, type SettlementConnection, type SettlementContext, type SettlementStatus, type SettlementVerdict, SettlementVerificationError, ShieldPoolErrors, type ShieldPoolPDAs, SimpleWallet, type SpendKey, type SpendOptions, type StorageAdapter, type SubmitTransactToRelayArgs, type SwapOptions, type SwapParams, type SwapRefundAuthorization, type SwapRefundShape, type SwapResult, TERMINAL_FAILURE, TRANSACTION_CIRCUITS_VERSION, TRANSACT_AUTH_FIELDS, TRANSACT_SWAP_AUTH_FIELDS, type TransactBatchItem, type TransactBatchItemOutcome, type TransactBatchOptions, type TransactBatchResult, type TransactOptions, type TransactParams, type TransactRequestBodyParams, type TransactResult, type TransactionBytesWallet, TransactionConfirmationError, type TransactionMetadata, type Transfer, type TransferOptions, type TransferResult, type TxStatus, type UserFriendlyError, type Utxo, UtxoAlreadySpentError, type EncryptedNote as UtxoEncryptedNote, type UtxoKeypair, type UtxoSwapParams, type UtxoSwapResult, UtxoWallet, VARIABLE_FEE_DENOMINATOR, VARIABLE_FEE_NUMERATOR, VARIABLE_FEE_RATE, VERSION, type VerifyUtxosResult, type ViewKey, type ViewingKeyPair, WITHDRAW_FEE_BPS, WITHDRAW_FIXED_FEE, type WalletAdapterBridgeOptions, type WalletSigner$1 as WalletSigner, type WalletUtxo, type Web3Module, type WithdrawOptions, type WithdrawSubmissionResult, accountMeta, addressBytes, addressFromBytes, addressFromPublicKey, assertDirectSubmissionLanded, assertInputMints, assertTransactionCircuitIntegrity, assessBridgeQuote, bigintToBytes32$1 as bigintToBytes32, bigintToHex, buildAuthTransactionMessage, buildMerkleTree, buildMerkleTreeFromChain, buildMerkleTreeFromRelay, buildRecipientDeliveryNotes, buildRelayAuthPreimage, buildRelayBatchAuthMessage, buildTransactRequestBody, buildTransactionMessage, bytesToHex, calculateFee, calculateFeeBigint, calculateRelayFee, canRebuildMerkleTreeFromChain, canonicalJson, canonicalPayloadString, chainNoteFromBase64, chainNoteToBase64, classifyPostFailure, classifyRelayError, cleanupReceivingAddress, cleanupStalePendingOperations, clearPendingDeposits, clearPendingWithdrawals, cloakBridgeRail, computeChainNoteHash, computeExtDataHash, computeMerkleRoot, computeNoteIndexChain, computeProofForLatestDeposit, computeProofFromChain, computeSignature, computeSwapRefundCommitment, computeCommitment as computeUtxoCommitment, computeNullifier as computeUtxoNullifier, confirmSignature, confirmTransactSettlement, copyNoteToClipboard, createCloakError, createCloakRpc, createDepositInstruction, createLogger, createRecoverableChangeUtxo, createRecoverableDepositUtxo, createRelayBatchAuthCoordinator, createUtxo, createZeroUtxo, decryptCompactChainNote, decryptComplianceMetadataWithMasterKey, decryptTransactionMetadata, depositFromDerivedKey, deriveBridgeReceiver, deriveChangeNoteBlinding, deriveDepositNoteBlinding, deriveDiversifiedViewingKey, deriveDiversifier, deriveFundingTargets, deriveInputNullifierPdas, deriveLegacyBridgeReceiver, deriveLegacyDepositNoteSecrets, deriveLegacySwapRefundAuthorization, derivePublicKey, deriveSpendKey, deriveSwapRefundAuthorization, deriveSwapRefundBlinding, deriveSwapRefundKeypair, deriveUserCompliancePublicKey, deriveUserComplianceScalar, deriveUtxoKeypairFromSpendKey, deriveViewKey, deriveViewingKeyFromNk, deriveViewingKeyFromSpendKey, deriveViewingKeyFromUtxoPrivateKey, deserializeUtxo, detectNetworkFromRpcUrl, discoverSwapRefunds, downloadNote, encodeDeliveryCarrierMemo, encodeNoteIndexItem, encodeNoteIndexPage, encodeNoteSimple, encodeRecipientDeliveryNote, encryptCompactChainNote, encryptNoteForRecipient, encryptTransactionMetadata, encryptTransactionMetadataBundle, expandSpendKey, explainRelayAuthRejection, exportKeys, exportNote, exportWalletKeys, fetchAccountBytes, fetchCommitments, fetchLatestBlockhash, fetchLookupTables, fetchNoteIndexHead, fetchNoteIndexPage, fetchRiskQuoteInstruction, fetchRiskQuoteIx, fetchSignaturesForAddress, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, findProgramAddress, formatAmount, formatComplianceCsv, formatErrorForLogging, formatSol, fullWithdraw, fundReceiverViaPaymaster, generateCloakKeys, generateCommitmentAsync, generateMasterSeed, generateNoteFromWallet, generateUtxoKeypair, generateViewingKeyPair, getAddressExplorerUrl, getChainNoteRegistryPDA, getCircuitsPath, getDeliveryRegistryPDA, getDistributableAmount, getExplorerUrl, getNkFromUtxoPrivateKey, getNullifierPDA, getPendingOperationsSummary, getPoolAuthorityConfigPDA, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getSwapStatePDA, getViewKey, hasPendingOperations, hexToBigint$1 as hexToBigint, hexToBytes, importKeys, importWalletKeys, isBrowser, isBrowserLike, isDebugEnabled, isMessageSigner, isPlausibleSignature, isReactNative, isRootNotFoundError, isSubmissionOutcomeUnknownResponse, isTerminalFailure, isValidHex, isValidRpcUrl, isValidSolanaAddress, isWithdrawAmountSufficient, isWithdrawable, listBridgeDeposits, loadPendingDeposits, loadPendingWithdrawals, loadVerifiedCircuitArtifacts, matchChangeNote, matchDepositNote, matchSwapRefundLeaf, mayRetry, messageSignerFromCallback, openRecipientDeliveryNote, parseAmount, parseDeliveryCarrierMemo, parseError, parseNote, parseNoteIndexItem, parseNoteIndexPage, parseRelayErrorResponse, parseRelayErrorSignature, parseTransactionError, partialWithdraw, partiallySignTransaction, poseidonHash, preflightCheck, preflightNullifiers, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, programInstruction, proofToBytes, pubkeyToFieldElement, pubkeyToLimbs, randomBytes, randomChangeNoteSalt, randomDepositNoteSalt, randomFieldElement, readMerkleTreeState, readRent, recipientDeliveryNoteToBase64, recoverNotesFromIndex, registerViewingKey, relayRequestDigestHex, removePendingDeposit, removePendingWithdrawal, renderAssessment, resolveCircuitsBase, retryDelayMs, savePendingDeposit, savePendingWithdrawal, scanNotesForWallet, scanRecipientDeliveryNotes, scanTransactions, sdkLogger, selectUtxos, sendInstructions, sendRawTransaction, sendTransaction, serializeAuthTransactionMessage, serializeNote, serializeUtxo, setCircuitsPath, setDebugMode, signCompiledTransaction, signMessageBytes, signRelayAuthPayload, signTransaction, signerFromKeypair, signerFromSecretKey, signerFromTransactionBytes, signerFromWalletAdapter, splitTo2Limbs, submitTransactToRelay, sumUtxoAmounts, swapUtxo, swapWithChange, toAddress, toComplianceReport, transact, transactBatch, transactionBase64, transactionBytes, transactionFromBytes, transactionWireSize, transfer, truncate, tryDecryptNote, updateNoteWithDeposit, updatePendingDeposit, updatePendingWithdrawal, bigintToBytes32 as utxoBigintToBytes32, utxoEquals, hexToBigint as utxoHexToBigint, validateDepositParams, validateNote, validateOutputsSum, validatePaymasterTopUpTransaction, validateRoot, validateTransfers, validateWalletConnected, validateWithdrawableNote, verifyAllCircuits, verifyCircuitIntegrity, verifyQuoteSignature, verifyUtxos, waitForRoot, withShieldRetries, withTiming, withdrawFeeFor };
|
package/dist/index.js
CHANGED
|
@@ -638,13 +638,16 @@ import { sha256 as sha2562 } from "@noble/hashes/sha2";
|
|
|
638
638
|
|
|
639
639
|
// src/relay/viewing-key.ts
|
|
640
640
|
var VIEWING_KEY_CHALLENGE_PREFIX = "CLOAK_VIEWING_KEY_REGISTER";
|
|
641
|
+
var VIEWING_KEY_CHALLENGE_READABLE_HEADER = "Cloak: Enable private transactions\n\nShares your viewing key with Cloak so you can transact privately. Signing this does not move any funds.\n\n";
|
|
642
|
+
var VIEWING_KEY_CHALLENGE_REQUEST_FORMAT = "readable";
|
|
641
643
|
var UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
642
644
|
var MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS = 300;
|
|
643
645
|
function normalizeViewingKeyHex(viewingKeyHex) {
|
|
644
646
|
return viewingKeyHex.replace(/^0x/i, "").toLowerCase();
|
|
645
647
|
}
|
|
646
|
-
function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex) {
|
|
647
|
-
|
|
648
|
+
function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format = "legacy") {
|
|
649
|
+
const header = format === "readable" ? VIEWING_KEY_CHALLENGE_READABLE_HEADER : "";
|
|
650
|
+
return header + [
|
|
648
651
|
VIEWING_KEY_CHALLENGE_PREFIX,
|
|
649
652
|
userPubkey,
|
|
650
653
|
nonce,
|
|
@@ -659,17 +662,16 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
|
|
|
659
662
|
const challenge = data;
|
|
660
663
|
const nonce = typeof challenge.nonce === "string" ? challenge.nonce : "";
|
|
661
664
|
const expiresInSeconds = challenge.expires_in_seconds;
|
|
662
|
-
const
|
|
663
|
-
userPubkey,
|
|
664
|
-
nonce,
|
|
665
|
-
viewingKeyHex
|
|
665
|
+
const messageFormat = ["readable", "legacy"].find(
|
|
666
|
+
(format) => challenge.message === buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format)
|
|
666
667
|
);
|
|
667
|
-
if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS ||
|
|
668
|
+
if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS || messageFormat === void 0) {
|
|
668
669
|
throw new Error("Relay returned an unsafe viewing-key challenge");
|
|
669
670
|
}
|
|
670
671
|
return {
|
|
671
672
|
nonce,
|
|
672
|
-
message:
|
|
673
|
+
message: buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, messageFormat),
|
|
674
|
+
messageFormat,
|
|
673
675
|
expiresInSeconds
|
|
674
676
|
};
|
|
675
677
|
}
|
|
@@ -1634,7 +1636,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
|
1634
1636
|
headers: { "Content-Type": "application/json" },
|
|
1635
1637
|
body: JSON.stringify({
|
|
1636
1638
|
user_pubkey: userPubkey,
|
|
1637
|
-
viewing_key: nkHex
|
|
1639
|
+
viewing_key: nkHex,
|
|
1640
|
+
message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
|
|
1638
1641
|
})
|
|
1639
1642
|
});
|
|
1640
1643
|
if (!challengeResponse.ok) {
|
|
@@ -1662,7 +1665,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
|
1662
1665
|
nonce: challenge.nonce,
|
|
1663
1666
|
identifier: keyId,
|
|
1664
1667
|
signature,
|
|
1665
|
-
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
|
|
1668
|
+
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
|
|
1669
|
+
...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
|
|
1666
1670
|
})
|
|
1667
1671
|
});
|
|
1668
1672
|
if (!response.ok) {
|
|
@@ -3491,7 +3495,11 @@ var RelayService = class {
|
|
|
3491
3495
|
const challengeRes = await relayFetch(`${this.baseUrl}/viewing-key/challenge`, {
|
|
3492
3496
|
method: "POST",
|
|
3493
3497
|
headers: { "Content-Type": "application/json" },
|
|
3494
|
-
body: JSON.stringify({
|
|
3498
|
+
body: JSON.stringify({
|
|
3499
|
+
user_pubkey: userPubkey,
|
|
3500
|
+
viewing_key: viewingKey,
|
|
3501
|
+
message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
|
|
3502
|
+
})
|
|
3495
3503
|
});
|
|
3496
3504
|
if (!challengeRes.ok) {
|
|
3497
3505
|
const error = await challengeRes.text();
|
|
@@ -3516,7 +3524,8 @@ var RelayService = class {
|
|
|
3516
3524
|
nonce: challenge.nonce,
|
|
3517
3525
|
identifier,
|
|
3518
3526
|
signature,
|
|
3519
|
-
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
|
|
3527
|
+
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
|
|
3528
|
+
...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
|
|
3520
3529
|
})
|
|
3521
3530
|
});
|
|
3522
3531
|
if (!response.ok) {
|
|
@@ -5172,6 +5181,8 @@ function normalizeOwnerPublicKey(publicKey, label) {
|
|
|
5172
5181
|
// src/notes/swap-refund.ts
|
|
5173
5182
|
var bs582 = _bs582.default || _bs582;
|
|
5174
5183
|
var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
|
|
5184
|
+
var REFUND_KEY_DOMAIN_V2 = new TextEncoder().encode("cloak_swap_refund_v2");
|
|
5185
|
+
var REFUND_PRIVATE_KEY_INFO_V2 = new TextEncoder().encode("sk_v2");
|
|
5175
5186
|
var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
|
|
5176
5187
|
var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
|
|
5177
5188
|
function normalizeNullifier(inputNullifier) {
|
|
@@ -5216,13 +5227,35 @@ function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
|
|
|
5216
5227
|
const nk = assertNk(viewingKeyNk);
|
|
5217
5228
|
return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
|
|
5218
5229
|
}
|
|
5219
|
-
|
|
5230
|
+
function privateKeyBytes(privateKey) {
|
|
5231
|
+
return Uint8Array.from(Buffer.from(privateKey.toString(16).padStart(64, "0"), "hex"));
|
|
5232
|
+
}
|
|
5233
|
+
async function deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier) {
|
|
5220
5234
|
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
5235
|
+
const nullifier = normalizeNullifier(inputNullifier);
|
|
5236
|
+
const preimage = new Uint8Array(
|
|
5237
|
+
REFUND_KEY_DOMAIN_V2.length + 32 + nullifier.length + REFUND_PRIVATE_KEY_INFO_V2.length
|
|
5238
|
+
);
|
|
5239
|
+
let off = 0;
|
|
5240
|
+
preimage.set(REFUND_KEY_DOMAIN_V2, off);
|
|
5241
|
+
off += REFUND_KEY_DOMAIN_V2.length;
|
|
5242
|
+
preimage.set(privateKeyBytes(owner.privateKey), off);
|
|
5243
|
+
off += 32;
|
|
5244
|
+
preimage.set(nullifier, off);
|
|
5245
|
+
off += nullifier.length;
|
|
5246
|
+
preimage.set(REFUND_PRIVATE_KEY_INFO_V2, off);
|
|
5247
|
+
const privateKey = toFieldSecret(blake33(preimage));
|
|
5248
|
+
const publicKey = await derivePublicKey(privateKey);
|
|
5249
|
+
if (publicKey === 0n) throw new Error("refund authorization is degenerate");
|
|
5250
|
+
return { privateKey, publicKey };
|
|
5251
|
+
}
|
|
5252
|
+
async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
|
|
5221
5253
|
const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
5222
|
-
|
|
5254
|
+
const keypair = await deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier);
|
|
5255
|
+
if (keypair.publicKey === 0n || blinding === 0n) {
|
|
5223
5256
|
throw new Error("refund authorization is degenerate");
|
|
5224
5257
|
}
|
|
5225
|
-
return { privateKey:
|
|
5258
|
+
return { privateKey: keypair.privateKey, publicKey: keypair.publicKey, blinding };
|
|
5226
5259
|
}
|
|
5227
5260
|
async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
|
|
5228
5261
|
const nk = assertNk(viewingKeyNk);
|
|
@@ -5243,9 +5276,12 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
|
|
|
5243
5276
|
mintAddress: NATIVE_SOL_MINT
|
|
5244
5277
|
});
|
|
5245
5278
|
}
|
|
5279
|
+
function toField(value) {
|
|
5280
|
+
return value instanceof Uint8Array ? BigInt("0x" + Buffer.from(value).toString("hex")) : value;
|
|
5281
|
+
}
|
|
5246
5282
|
async function matchSwapRefundLeaf(params) {
|
|
5247
5283
|
const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
|
|
5248
|
-
const expected =
|
|
5284
|
+
const expected = toField(params.commitment);
|
|
5249
5285
|
let blinding;
|
|
5250
5286
|
try {
|
|
5251
5287
|
blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
@@ -5253,11 +5289,55 @@ async function matchSwapRefundLeaf(params) {
|
|
|
5253
5289
|
return null;
|
|
5254
5290
|
}
|
|
5255
5291
|
const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
|
|
5292
|
+
const ownerPriv = params.ownerUtxoKeypair?.privateKey ?? 0n;
|
|
5293
|
+
let perSwapPub;
|
|
5294
|
+
let perSwapPriv = 0n;
|
|
5295
|
+
if (ownerPriv > 0n && ownerPub !== void 0) {
|
|
5296
|
+
try {
|
|
5297
|
+
const kp = await deriveSwapRefundKeypair({ privateKey: ownerPriv, publicKey: ownerPub }, inputNullifier);
|
|
5298
|
+
perSwapPub = kp.publicKey;
|
|
5299
|
+
perSwapPriv = kp.privateKey;
|
|
5300
|
+
} catch {
|
|
5301
|
+
return null;
|
|
5302
|
+
}
|
|
5303
|
+
}
|
|
5304
|
+
if (params.publishedRefundPubkey !== void 0 && params.publishedRefundBlinding !== void 0) {
|
|
5305
|
+
const published = toField(params.publishedRefundPubkey);
|
|
5306
|
+
const publishedBlinding = toField(params.publishedRefundBlinding);
|
|
5307
|
+
if (published !== 0n && publishedBlinding === blinding) {
|
|
5308
|
+
if (perSwapPub === void 0 || perSwapPub === published) {
|
|
5309
|
+
const candidate = await computeSwapRefundCommitment(amountAfterFee, published, blinding);
|
|
5310
|
+
if (candidate === expected && published !== ownerPub) {
|
|
5311
|
+
return {
|
|
5312
|
+
keypair: { privateKey: perSwapPub === published ? perSwapPriv : 0n, publicKey: published },
|
|
5313
|
+
shape: "per-swap",
|
|
5314
|
+
blinding,
|
|
5315
|
+
amount: amountAfterFee,
|
|
5316
|
+
commitment: candidate,
|
|
5317
|
+
legacyExposed: false
|
|
5318
|
+
};
|
|
5319
|
+
}
|
|
5320
|
+
}
|
|
5321
|
+
}
|
|
5322
|
+
} else if (perSwapPub !== void 0) {
|
|
5323
|
+
const candidate = await computeSwapRefundCommitment(amountAfterFee, perSwapPub, blinding);
|
|
5324
|
+
if (candidate === expected) {
|
|
5325
|
+
return {
|
|
5326
|
+
keypair: { privateKey: perSwapPriv, publicKey: perSwapPub },
|
|
5327
|
+
shape: "per-swap",
|
|
5328
|
+
blinding,
|
|
5329
|
+
amount: amountAfterFee,
|
|
5330
|
+
commitment: candidate,
|
|
5331
|
+
legacyExposed: false
|
|
5332
|
+
};
|
|
5333
|
+
}
|
|
5334
|
+
}
|
|
5256
5335
|
if (ownerPub !== void 0) {
|
|
5257
5336
|
const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
|
|
5258
5337
|
if (candidate === expected) {
|
|
5259
5338
|
return {
|
|
5260
|
-
keypair: { privateKey:
|
|
5339
|
+
keypair: { privateKey: ownerPriv, publicKey: ownerPub },
|
|
5340
|
+
shape: "owner",
|
|
5261
5341
|
blinding,
|
|
5262
5342
|
amount: amountAfterFee,
|
|
5263
5343
|
commitment: candidate,
|
|
@@ -5275,6 +5355,7 @@ async function matchSwapRefundLeaf(params) {
|
|
|
5275
5355
|
if (legacyCandidate !== expected) return null;
|
|
5276
5356
|
return {
|
|
5277
5357
|
keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
|
|
5358
|
+
shape: "legacy-nk",
|
|
5278
5359
|
blinding: legacy.blinding,
|
|
5279
5360
|
amount: amountAfterFee,
|
|
5280
5361
|
commitment: legacyCandidate,
|
|
@@ -5286,6 +5367,9 @@ var PROOF_LEN2 = 256;
|
|
|
5286
5367
|
var NULLIFIER_0_OFFSET = 1 + PROOF_LEN2 + 104;
|
|
5287
5368
|
var PUBLIC_INPUTS_LEN2 = 264;
|
|
5288
5369
|
var MIN_TRANSACT_SWAP_LEN = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2;
|
|
5370
|
+
var REFUND_PUBKEY_OFFSET = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2 + 72;
|
|
5371
|
+
var REFUND_BLINDING_OFFSET = REFUND_PUBKEY_OFFSET + 32;
|
|
5372
|
+
var MIN_TRANSACT_SWAP_WITH_PARAMS_LEN = REFUND_BLINDING_OFFSET + 32;
|
|
5289
5373
|
function toBase58(key) {
|
|
5290
5374
|
if (!key) return void 0;
|
|
5291
5375
|
if (typeof key === "string") return key;
|
|
@@ -5348,7 +5432,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
|
|
|
5348
5432
|
}
|
|
5349
5433
|
if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
|
|
5350
5434
|
throw new Error(
|
|
5351
|
-
"discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): refund leaves are
|
|
5435
|
+
"discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): per-swap and owner-key refund leaves are matched against it, and nk alone can only find legacy refunds."
|
|
5352
5436
|
);
|
|
5353
5437
|
}
|
|
5354
5438
|
const ownerUtxoKeypair = options.ownerUtxoKeypair;
|
|
@@ -5408,7 +5492,15 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
|
|
|
5408
5492
|
programId
|
|
5409
5493
|
);
|
|
5410
5494
|
const key = swapState;
|
|
5411
|
-
|
|
5495
|
+
const hasParams = data.length >= MIN_TRANSACT_SWAP_WITH_PARAMS_LEN;
|
|
5496
|
+
if (!nullifierBySwapState.has(key)) {
|
|
5497
|
+
nullifierBySwapState.set(key, {
|
|
5498
|
+
nullifier,
|
|
5499
|
+
signature,
|
|
5500
|
+
refundPubkey: hasParams ? data.slice(REFUND_PUBKEY_OFFSET, REFUND_PUBKEY_OFFSET + 32) : void 0,
|
|
5501
|
+
refundBlinding: hasParams ? data.slice(REFUND_BLINDING_OFFSET, REFUND_BLINDING_OFFSET + 32) : void 0
|
|
5502
|
+
});
|
|
5503
|
+
}
|
|
5412
5504
|
}
|
|
5413
5505
|
const logs = tx.meta?.logMessages;
|
|
5414
5506
|
const scan = scanRefundLeafEvents(logs, programIdBase58);
|
|
@@ -5427,7 +5519,9 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
|
|
|
5427
5519
|
inputNullifier: candidate.nullifier,
|
|
5428
5520
|
amountAfterFee: event.amountAfterFee,
|
|
5429
5521
|
commitment: event.commitmentField,
|
|
5430
|
-
ownerUtxoKeypair
|
|
5522
|
+
ownerUtxoKeypair,
|
|
5523
|
+
publishedRefundPubkey: candidate.refundPubkey,
|
|
5524
|
+
publishedRefundBlinding: candidate.refundBlinding
|
|
5431
5525
|
});
|
|
5432
5526
|
if (!recovered) continue;
|
|
5433
5527
|
const dedupe = `${close.signature}:${event.leafIndex}`;
|
|
@@ -6424,7 +6518,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
|
|
|
6424
6518
|
headers: { "Content-Type": "application/json" },
|
|
6425
6519
|
body: JSON.stringify({
|
|
6426
6520
|
user_pubkey: userPubkey,
|
|
6427
|
-
viewing_key: viewingKeyHex
|
|
6521
|
+
viewing_key: viewingKeyHex,
|
|
6522
|
+
message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
|
|
6428
6523
|
})
|
|
6429
6524
|
});
|
|
6430
6525
|
if (!challengeResponse.ok) {
|
|
@@ -6471,7 +6566,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
|
|
|
6471
6566
|
viewing_key: viewingKeyHex,
|
|
6472
6567
|
nonce: challenge.nonce,
|
|
6473
6568
|
signature: signatureBase64,
|
|
6474
|
-
...authMode === "transaction" ? { auth_mode: authMode } : {}
|
|
6569
|
+
...authMode === "transaction" ? { auth_mode: authMode } : {},
|
|
6570
|
+
...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
|
|
6475
6571
|
})
|
|
6476
6572
|
});
|
|
6477
6573
|
if (!response.ok) {
|
|
@@ -12743,7 +12839,8 @@ async function matchOwnItems(own, owner, onReject, onSkip) {
|
|
|
12743
12839
|
atRisk: o.refund.legacyExposed,
|
|
12744
12840
|
amount: o.refund.amount,
|
|
12745
12841
|
blinding: o.refund.blinding,
|
|
12746
|
-
|
|
12842
|
+
// per-swap refunds carry their derived keypair; owner-shape ones carry the owner
|
|
12843
|
+
keypair: o.refund.keypair,
|
|
12747
12844
|
mint: NATIVE_SOL_MINT,
|
|
12748
12845
|
commitment: o.refund.commitment,
|
|
12749
12846
|
leaf: Number(item.leaf)
|
|
@@ -13409,7 +13506,8 @@ async function runOnce(ctx, cursor) {
|
|
|
13409
13506
|
for (const c of byLeaf.values()) {
|
|
13410
13507
|
const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
|
|
13411
13508
|
keyChecked.set(c.keypair.privateKey, pubOk);
|
|
13412
|
-
|
|
13509
|
+
const ownerOk = c.keypair.publicKey === owner.publicKey || c.kind === "swap_refund";
|
|
13510
|
+
if (!pubOk || !c.atRisk && !ownerOk) {
|
|
13413
13511
|
stats.dropped++;
|
|
13414
13512
|
tally(c, "rejected");
|
|
13415
13513
|
continue;
|
|
@@ -13418,7 +13516,7 @@ async function runOnce(ctx, cursor) {
|
|
|
13418
13516
|
verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
|
|
13419
13517
|
const utxo = {
|
|
13420
13518
|
amount: c.amount,
|
|
13421
|
-
keypair: c.atRisk ? { ...c.keypair } : owner,
|
|
13519
|
+
keypair: c.atRisk || c.kind === "swap_refund" ? { ...c.keypair } : owner,
|
|
13422
13520
|
blinding: c.blinding,
|
|
13423
13521
|
mintAddress: c.mint,
|
|
13424
13522
|
index: c.leaf,
|
|
@@ -13860,6 +13958,43 @@ function signerFromWalletAdapter(adapter, options = {}) {
|
|
|
13860
13958
|
}
|
|
13861
13959
|
return signer;
|
|
13862
13960
|
}
|
|
13961
|
+
function signerFromTransactionBytes(wallet) {
|
|
13962
|
+
const walletAddress = wallet.address;
|
|
13963
|
+
const signer = {
|
|
13964
|
+
address: walletAddress,
|
|
13965
|
+
async modifyAndSignTransactions(transactions) {
|
|
13966
|
+
const out = [];
|
|
13967
|
+
for (const transaction of transactions) {
|
|
13968
|
+
const signedBytes = await wallet.signTransaction(transactionBytes(transaction));
|
|
13969
|
+
const decoded = transactionFromBytes(signedBytes);
|
|
13970
|
+
if (!bytesEqual2(new Uint8Array(decoded.messageBytes), new Uint8Array(transaction.messageBytes))) {
|
|
13971
|
+
throw new Error("Wallet returned a transaction whose message differs from the one it was asked to sign");
|
|
13972
|
+
}
|
|
13973
|
+
if (!decoded.signatures[walletAddress]) {
|
|
13974
|
+
throw new Error("Wallet returned a transaction without its own signature");
|
|
13975
|
+
}
|
|
13976
|
+
out.push({ ...transaction, signatures: { ...transaction.signatures, ...decoded.signatures } });
|
|
13977
|
+
}
|
|
13978
|
+
return out;
|
|
13979
|
+
}
|
|
13980
|
+
};
|
|
13981
|
+
if (wallet.signMessage) {
|
|
13982
|
+
const signMessage = wallet.signMessage;
|
|
13983
|
+
Object.assign(signer, {
|
|
13984
|
+
async signMessages(messages) {
|
|
13985
|
+
const dictionaries = [];
|
|
13986
|
+
for (const message of messages) dictionaries.push({ [walletAddress]: await signMessage(message.content) });
|
|
13987
|
+
return dictionaries;
|
|
13988
|
+
}
|
|
13989
|
+
});
|
|
13990
|
+
}
|
|
13991
|
+
return signer;
|
|
13992
|
+
}
|
|
13993
|
+
function bytesEqual2(a, b) {
|
|
13994
|
+
if (a.length !== b.length) return false;
|
|
13995
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
13996
|
+
return true;
|
|
13997
|
+
}
|
|
13863
13998
|
async function loadWeb3() {
|
|
13864
13999
|
const name = "@solana/web3.js";
|
|
13865
14000
|
try {
|
|
@@ -14903,6 +15038,7 @@ export {
|
|
|
14903
15038
|
deriveSpendKey,
|
|
14904
15039
|
deriveSwapRefundAuthorization,
|
|
14905
15040
|
deriveSwapRefundBlinding,
|
|
15041
|
+
deriveSwapRefundKeypair,
|
|
14906
15042
|
deriveUserCompliancePublicKey,
|
|
14907
15043
|
deriveUserComplianceScalar,
|
|
14908
15044
|
deriveUtxoKeypairFromSpendKey,
|
|
@@ -15058,6 +15194,7 @@ export {
|
|
|
15058
15194
|
signTransaction,
|
|
15059
15195
|
signerFromKeypair,
|
|
15060
15196
|
signerFromSecretKey,
|
|
15197
|
+
signerFromTransactionBytes,
|
|
15061
15198
|
signerFromWalletAdapter,
|
|
15062
15199
|
splitTo2Limbs,
|
|
15063
15200
|
submitTransactToRelay,
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cloak.dev/sdk",
|
|
3
3
|
"description": "Shield, send, and swap on Solana privately — TypeScript SDK with UTXO-based zero-knowledge transactions",
|
|
4
|
-
"version": "0.2.6-staging.
|
|
4
|
+
"version": "0.2.6-staging.d42dbe0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
7
7
|
"module": "dist/index.js",
|