@cloak.dev/sdk 0.2.2-staging.33f11a2 → 0.2.2-staging.5dffa29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -8
- package/dist/index.cjs +846 -14
- package/dist/index.d.cts +678 -1
- package/dist/index.d.ts +678 -1
- package/dist/index.js +831 -13
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -2150,8 +2150,8 @@ async function verifyUtxos(utxos, connection, programId, commitment = "confirmed
|
|
|
2150
2150
|
const nullifierHex = nullifierBig.toString(16).padStart(64, "0");
|
|
2151
2151
|
const nullifierBytes = Buffer.from(nullifierHex, "hex");
|
|
2152
2152
|
const { pool } = getShieldPoolPDAs(programId, utxo.mintAddress);
|
|
2153
|
-
const [
|
|
2154
|
-
checkable.push({ utxo, pda });
|
|
2153
|
+
const [pda2] = getNullifierPDA(pool, nullifierBytes, programId);
|
|
2154
|
+
checkable.push({ utxo, pda: pda2 });
|
|
2155
2155
|
} catch {
|
|
2156
2156
|
skipped.push(utxo);
|
|
2157
2157
|
}
|
|
@@ -2221,8 +2221,8 @@ function deriveInputNullifierPdas(programId, mint, inputNullifiers) {
|
|
|
2221
2221
|
const pdas = [];
|
|
2222
2222
|
for (const nullifier of inputNullifiers) {
|
|
2223
2223
|
if (nullifier === BigInt(0)) continue;
|
|
2224
|
-
const [
|
|
2225
|
-
pdas.push(
|
|
2224
|
+
const [pda2] = getNullifierPDA(pool, bigintToBytes324(nullifier), programId);
|
|
2225
|
+
pdas.push(pda2);
|
|
2226
2226
|
}
|
|
2227
2227
|
return pdas;
|
|
2228
2228
|
}
|
|
@@ -3543,7 +3543,7 @@ async function fetchWithRetry(url, options = {}) {
|
|
|
3543
3543
|
const {
|
|
3544
3544
|
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
3545
3545
|
maxRetries = DEFAULT_MAX_RETRIES,
|
|
3546
|
-
retryDelayMs = 1e3
|
|
3546
|
+
retryDelayMs: retryDelayMs2 = 1e3
|
|
3547
3547
|
} = options;
|
|
3548
3548
|
assertAllowedRelayOrigin(url);
|
|
3549
3549
|
let lastError = null;
|
|
@@ -3567,7 +3567,7 @@ async function fetchWithRetry(url, options = {}) {
|
|
|
3567
3567
|
`Relay request failed after ${attempt + 1} attempts: ${lastError.message}`
|
|
3568
3568
|
);
|
|
3569
3569
|
}
|
|
3570
|
-
const delay =
|
|
3570
|
+
const delay = retryDelayMs2 * Math.pow(2, attempt) + Math.random() * 500;
|
|
3571
3571
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
3572
3572
|
}
|
|
3573
3573
|
}
|
|
@@ -7060,7 +7060,7 @@ async function transact(params, options) {
|
|
|
7060
7060
|
// names is refused.
|
|
7061
7061
|
maxRootRetries = 40,
|
|
7062
7062
|
// Increased to handle prolonged relay sync recovery under high concurrency
|
|
7063
|
-
retryDelayMs = 500,
|
|
7063
|
+
retryDelayMs: retryDelayMs2 = 500,
|
|
7064
7064
|
// Start with short delay, will exponentially back off
|
|
7065
7065
|
riskOracleQueue,
|
|
7066
7066
|
riskQuoteUrl: riskQuoteUrlOption,
|
|
@@ -7481,7 +7481,7 @@ async function transact(params, options) {
|
|
|
7481
7481
|
while (submissionAttempts <= maxRootRetries) {
|
|
7482
7482
|
const isRetry = submissionAttempts > 0;
|
|
7483
7483
|
if (isRetry) {
|
|
7484
|
-
const exponentialDelay = Math.min(
|
|
7484
|
+
const exponentialDelay = Math.min(retryDelayMs2 * Math.pow(1.5, submissionAttempts - 1), 5e3);
|
|
7485
7485
|
const jitter = Math.random() * 500;
|
|
7486
7486
|
const totalDelay = Math.floor(exponentialDelay + jitter);
|
|
7487
7487
|
await sleep2(totalDelay);
|
|
@@ -7644,7 +7644,7 @@ async function transact(params, options) {
|
|
|
7644
7644
|
}
|
|
7645
7645
|
treeState = null;
|
|
7646
7646
|
useSiblingInfo = false;
|
|
7647
|
-
const waitMs = Math.min(
|
|
7647
|
+
const waitMs = Math.min(retryDelayMs2 * Math.pow(2, Math.min(submissionAttempts, 4)), 5e3);
|
|
7648
7648
|
if (waitMs > 0) {
|
|
7649
7649
|
onProgress?.(`Waiting ${waitMs}ms for relay sync before retry...`);
|
|
7650
7650
|
await new Promise((r) => setTimeout(r, waitMs));
|
|
@@ -8338,7 +8338,7 @@ async function swapUtxo(params, options) {
|
|
|
8338
8338
|
riskQuoteUrl: riskQuoteUrlOption,
|
|
8339
8339
|
maxRootRetries = 40,
|
|
8340
8340
|
// Increased to handle prolonged relay sync recovery under high concurrency
|
|
8341
|
-
retryDelayMs = 500,
|
|
8341
|
+
retryDelayMs: retryDelayMs2 = 500,
|
|
8342
8342
|
// Start with short delay, will exponentially back off
|
|
8343
8343
|
useUniqueNullifiers,
|
|
8344
8344
|
useChainRootForProof = true
|
|
@@ -8743,7 +8743,7 @@ async function swapUtxo(params, options) {
|
|
|
8743
8743
|
let walletApprovals = 0;
|
|
8744
8744
|
for (let attempt = 0; attempt <= maxRootRetries; attempt++) {
|
|
8745
8745
|
if (attempt > 0) {
|
|
8746
|
-
const exponentialDelay = Math.min(
|
|
8746
|
+
const exponentialDelay = Math.min(retryDelayMs2 * Math.pow(1.5, attempt - 1), 5e3);
|
|
8747
8747
|
const jitter = Math.random() * 500;
|
|
8748
8748
|
const totalDelay = Math.floor(exponentialDelay + jitter);
|
|
8749
8749
|
await sleep2(totalDelay);
|
|
@@ -8881,7 +8881,7 @@ async function swapUtxo(params, options) {
|
|
|
8881
8881
|
}
|
|
8882
8882
|
merkleState = null;
|
|
8883
8883
|
useSiblingInfo = false;
|
|
8884
|
-
const waitMs = Math.min(
|
|
8884
|
+
const waitMs = Math.min(retryDelayMs2 * Math.pow(2, Math.min(attempt, 4)), 5e3);
|
|
8885
8885
|
if (waitMs > 0) {
|
|
8886
8886
|
onProgress?.(`Waiting ${waitMs}ms for relay sync before retry...`);
|
|
8887
8887
|
await new Promise((r) => setTimeout(r, waitMs));
|
|
@@ -10857,12 +10857,799 @@ var SimpleWallet = class {
|
|
|
10857
10857
|
}
|
|
10858
10858
|
};
|
|
10859
10859
|
|
|
10860
|
+
// src/bridge/rail-verify.ts
|
|
10861
|
+
import nacl7 from "tweetnacl";
|
|
10862
|
+
import { sha256 as sha2565 } from "@noble/hashes/sha256";
|
|
10863
|
+
var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
|
|
10864
|
+
var b58 = /* @__PURE__ */ (() => {
|
|
10865
|
+
const A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
10866
|
+
return {
|
|
10867
|
+
decode(s) {
|
|
10868
|
+
let n = 0n;
|
|
10869
|
+
for (const c of s) {
|
|
10870
|
+
const i = A.indexOf(c);
|
|
10871
|
+
if (i < 0) throw new Error("bad base58");
|
|
10872
|
+
n = n * 58n + BigInt(i);
|
|
10873
|
+
}
|
|
10874
|
+
const bytes = [];
|
|
10875
|
+
while (n > 0n) {
|
|
10876
|
+
bytes.unshift(Number(n & 255n));
|
|
10877
|
+
n >>= 8n;
|
|
10878
|
+
}
|
|
10879
|
+
for (const c of s) {
|
|
10880
|
+
if (c === "1") bytes.unshift(0);
|
|
10881
|
+
else break;
|
|
10882
|
+
}
|
|
10883
|
+
return Uint8Array.from(bytes);
|
|
10884
|
+
},
|
|
10885
|
+
encode(b) {
|
|
10886
|
+
let n = 0n;
|
|
10887
|
+
for (const x of b) n = n * 256n + BigInt(x);
|
|
10888
|
+
let s = "";
|
|
10889
|
+
while (n > 0n) {
|
|
10890
|
+
s = A[Number(n % 58n)] + s;
|
|
10891
|
+
n /= 58n;
|
|
10892
|
+
}
|
|
10893
|
+
for (const x of b) {
|
|
10894
|
+
if (x === 0) s = "1" + s;
|
|
10895
|
+
else break;
|
|
10896
|
+
}
|
|
10897
|
+
return s;
|
|
10898
|
+
}
|
|
10899
|
+
};
|
|
10900
|
+
})();
|
|
10901
|
+
function stable(v) {
|
|
10902
|
+
if (v === null || typeof v !== "object") return JSON.stringify(v) ?? "null";
|
|
10903
|
+
if (Array.isArray(v)) return `[${v.map(stable).join(",")}]`;
|
|
10904
|
+
const o = v;
|
|
10905
|
+
const parts = Object.keys(o).sort().filter((k) => o[k] !== void 0).map((k) => `${JSON.stringify(k)}:${stable(o[k])}`);
|
|
10906
|
+
return `{${parts.join(",")}}`;
|
|
10907
|
+
}
|
|
10908
|
+
function signedRequest(r) {
|
|
10909
|
+
const q = r.quoteRequest ?? {};
|
|
10910
|
+
return {
|
|
10911
|
+
dry: q.dry,
|
|
10912
|
+
swapType: q.swapType,
|
|
10913
|
+
slippageTolerance: q.slippageTolerance,
|
|
10914
|
+
originAsset: q.originAsset,
|
|
10915
|
+
depositType: q.depositType,
|
|
10916
|
+
destinationAsset: q.destinationAsset,
|
|
10917
|
+
amount: q.amount,
|
|
10918
|
+
refundTo: q.refundTo,
|
|
10919
|
+
refundType: q.refundType,
|
|
10920
|
+
recipient: q.recipient,
|
|
10921
|
+
recipientType: q.recipientType,
|
|
10922
|
+
deadline: q.deadline,
|
|
10923
|
+
quoteWaitingTimeMs: q.quoteWaitingTimeMs || void 0,
|
|
10924
|
+
referral: q.referral || void 0,
|
|
10925
|
+
virtualChainRecipient: q.virtualChainRecipient || void 0,
|
|
10926
|
+
virtualChainRefundRecipient: q.virtualChainRefundRecipient || void 0,
|
|
10927
|
+
customRecipientMsg: q.customRecipientMsg || void 0
|
|
10928
|
+
// Deliberately unsigned by the rail: sessionId, connectedWallets, correlationId, appFees,
|
|
10929
|
+
// partnerId, userAccountId, depositMode. APP FEES ARE NOT AUTHENTICATED — never display a fee
|
|
10930
|
+
// caption as if the signature vouched for it.
|
|
10931
|
+
};
|
|
10932
|
+
}
|
|
10933
|
+
function signedQuote(r) {
|
|
10934
|
+
const q = r.quote ?? {};
|
|
10935
|
+
const base = {
|
|
10936
|
+
amountIn: q.amountIn,
|
|
10937
|
+
amountInFormatted: q.amountInFormatted,
|
|
10938
|
+
amountInUsd: q.amountInUsd,
|
|
10939
|
+
minAmountIn: q.minAmountIn,
|
|
10940
|
+
amountOut: q.amountOut,
|
|
10941
|
+
amountOutFormatted: q.amountOutFormatted,
|
|
10942
|
+
amountOutUsd: q.amountOutUsd,
|
|
10943
|
+
minAmountOut: q.minAmountOut
|
|
10944
|
+
};
|
|
10945
|
+
if (r.quoteRequest?.dry) return base;
|
|
10946
|
+
return {
|
|
10947
|
+
...base,
|
|
10948
|
+
depositAddress: q.depositAddress || void 0,
|
|
10949
|
+
// <- the field that makes substitution detectable
|
|
10950
|
+
depositMemo: q.depositMemo || void 0,
|
|
10951
|
+
deadline: q.deadline || void 0,
|
|
10952
|
+
// <- a real, SIGNED expiry
|
|
10953
|
+
timeWhenInactive: q.timeWhenInactive || void 0,
|
|
10954
|
+
timeEstimate: q.timeEstimate || void 0,
|
|
10955
|
+
virtualChainRecipient: q.virtualChainRecipient || void 0,
|
|
10956
|
+
virtualChainRefundRecipient: q.virtualChainRefundRecipient || void 0,
|
|
10957
|
+
customRecipientMsg: q.customRecipientMsg || void 0,
|
|
10958
|
+
refundFee: q.refundFee || void 0,
|
|
10959
|
+
withdrawFee: q.withdrawFee || void 0
|
|
10960
|
+
};
|
|
10961
|
+
}
|
|
10962
|
+
function canonicalPayloadString(resp) {
|
|
10963
|
+
return stable({ ...signedRequest(resp), ...signedQuote(resp), timestamp: resp.timestamp });
|
|
10964
|
+
}
|
|
10965
|
+
function verifyQuoteSignature(resp) {
|
|
10966
|
+
if (!resp?.signature) return { valid: false, reason: "no signature on the response" };
|
|
10967
|
+
const payload = { ...signedRequest(resp), ...signedQuote(resp), timestamp: resp.timestamp };
|
|
10968
|
+
const digest = sha2565(new TextEncoder().encode(stable(payload)));
|
|
10969
|
+
const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
|
|
10970
|
+
const sig = resp.signature.replace(/^ed25519:/, "");
|
|
10971
|
+
try {
|
|
10972
|
+
return { valid: nacl7.sign.detached.verify(message, b58.decode(sig), b58.decode(ONECLICK_PUBKEY_B58)) };
|
|
10973
|
+
} catch (e) {
|
|
10974
|
+
return { valid: false, reason: e instanceof Error ? e.message : String(e) };
|
|
10975
|
+
}
|
|
10976
|
+
}
|
|
10977
|
+
|
|
10978
|
+
// src/bridge/rails.ts
|
|
10979
|
+
async function parseBridgeResponse(res, what) {
|
|
10980
|
+
let body;
|
|
10981
|
+
try {
|
|
10982
|
+
body = await res.json();
|
|
10983
|
+
} catch {
|
|
10984
|
+
throw new Error(`${what} failed: ${res.status} ${res.statusText} (response body was not JSON)`);
|
|
10985
|
+
}
|
|
10986
|
+
if (!res.ok) {
|
|
10987
|
+
const b = body ?? {};
|
|
10988
|
+
throw new Error(
|
|
10989
|
+
`${what} failed: ${b.message ?? res.statusText} (${b.code ?? res.status}${b.retryable ? ", retryable" : ""})`
|
|
10990
|
+
);
|
|
10991
|
+
}
|
|
10992
|
+
return body;
|
|
10993
|
+
}
|
|
10994
|
+
function toAttestation(raw) {
|
|
10995
|
+
if (raw.kind === "ed25519") {
|
|
10996
|
+
return { kind: "ed25519", verified: raw.verified ?? false, signer: raw.signer ?? "" };
|
|
10997
|
+
}
|
|
10998
|
+
return { kind: "none", checks: raw.checks ?? [], note: raw.note ?? "" };
|
|
10999
|
+
}
|
|
11000
|
+
async function fetchBridgeQuote(relayUrl, req) {
|
|
11001
|
+
const body = {
|
|
11002
|
+
recipient: req.recipient,
|
|
11003
|
+
origin_chain: req.originChain,
|
|
11004
|
+
amount_base_units: req.amountBaseUnits.toString(),
|
|
11005
|
+
allocate: req.allocate ?? false
|
|
11006
|
+
};
|
|
11007
|
+
if (req.refundTo !== void 0) body.refund_to = req.refundTo;
|
|
11008
|
+
if (req.rails !== void 0) body.rails = req.rails;
|
|
11009
|
+
const res = await relayFetch(`${relayUrl}/bridge/quote`, {
|
|
11010
|
+
method: "POST",
|
|
11011
|
+
headers: { "Content-Type": "application/json" },
|
|
11012
|
+
body: JSON.stringify(body)
|
|
11013
|
+
});
|
|
11014
|
+
const raw = await parseBridgeResponse(res, "bridge quote");
|
|
11015
|
+
const options = [];
|
|
11016
|
+
const unavailable = (raw.unavailable ?? []).map((p) => ({
|
|
11017
|
+
rail: p.rail,
|
|
11018
|
+
reason: p.reason
|
|
11019
|
+
}));
|
|
11020
|
+
for (const opt of raw.options) {
|
|
11021
|
+
const attestation = toAttestation(opt.attestation);
|
|
11022
|
+
if (attestation.kind === "ed25519") {
|
|
11023
|
+
const verdict = opt.rail_response ? verifyQuoteSignature(opt.rail_response) : { valid: false, reason: "no rail_response to verify against" };
|
|
11024
|
+
if (!verdict.valid) {
|
|
11025
|
+
unavailable.push({
|
|
11026
|
+
rail: opt.rail,
|
|
11027
|
+
reason: `deposit address failed independent signature verification, refusing to display it (${verdict.reason ?? "signature did not verify"})`
|
|
11028
|
+
});
|
|
11029
|
+
continue;
|
|
11030
|
+
}
|
|
11031
|
+
}
|
|
11032
|
+
options.push({
|
|
11033
|
+
rail: opt.rail,
|
|
11034
|
+
refunds: opt.refunds,
|
|
11035
|
+
addressLifetime: opt.address_lifetime,
|
|
11036
|
+
amountOut: BigInt(opt.amount_out),
|
|
11037
|
+
minAmountOut: BigInt(opt.min_amount_out),
|
|
11038
|
+
timeEstimateSeconds: opt.time_estimate_s,
|
|
11039
|
+
expiresAt: opt.expires_at,
|
|
11040
|
+
depositAddress: opt.deposit_address,
|
|
11041
|
+
attestation
|
|
11042
|
+
});
|
|
11043
|
+
}
|
|
11044
|
+
return { options, unavailable };
|
|
11045
|
+
}
|
|
11046
|
+
var STATUS_STATES = [
|
|
11047
|
+
"pending",
|
|
11048
|
+
"delivered",
|
|
11049
|
+
"refunded",
|
|
11050
|
+
"expired",
|
|
11051
|
+
"unknown"
|
|
11052
|
+
];
|
|
11053
|
+
async function fetchBridgeStatus(relayUrl, depositAddress, rail) {
|
|
11054
|
+
const qs = new URLSearchParams({ deposit_address: depositAddress, rail });
|
|
11055
|
+
const res = await relayFetch(`${relayUrl}/bridge/status?${qs.toString()}`);
|
|
11056
|
+
const raw = await parseBridgeResponse(res, "bridge status");
|
|
11057
|
+
const state = STATUS_STATES.includes(raw.state ?? "") ? raw.state : "unknown";
|
|
11058
|
+
return { rail: raw.rail ?? rail, state, detail: raw.detail ?? "" };
|
|
11059
|
+
}
|
|
11060
|
+
function cloakBridgeRail(relayUrl) {
|
|
11061
|
+
assertAllowedRelayOrigin(relayUrl);
|
|
11062
|
+
return {
|
|
11063
|
+
id: "cloak-bridge",
|
|
11064
|
+
quote: (req) => fetchBridgeQuote(relayUrl, req),
|
|
11065
|
+
status: (depositAddress, rail) => fetchBridgeStatus(relayUrl, depositAddress, rail)
|
|
11066
|
+
};
|
|
11067
|
+
}
|
|
11068
|
+
|
|
11069
|
+
// src/bridge/paymaster-client.ts
|
|
11070
|
+
import {
|
|
11071
|
+
PublicKey as PublicKey11,
|
|
11072
|
+
SystemInstruction,
|
|
11073
|
+
SystemProgram as SystemProgram3,
|
|
11074
|
+
Transaction as Transaction3
|
|
11075
|
+
} from "@solana/web3.js";
|
|
11076
|
+
import { TOKEN_PROGRAM_ID as TOKEN_PROGRAM_ID3, decodeTransferInstruction, getAssociatedTokenAddressSync as getAssociatedTokenAddressSync3 } from "@solana/spl-token";
|
|
11077
|
+
function validatePaymasterTopUpTransaction(tx, expect) {
|
|
11078
|
+
const ixs = tx.instructions;
|
|
11079
|
+
if (ixs.length !== 1 && ixs.length !== 2) {
|
|
11080
|
+
throw new Error(
|
|
11081
|
+
`paymaster top-up must be exactly 1 or 2 instructions, got ${ixs.length} \u2014 refusing to sign a transaction whose shape does not match the documented top-up contract`
|
|
11082
|
+
);
|
|
11083
|
+
}
|
|
11084
|
+
const ix0 = ixs[0];
|
|
11085
|
+
if (!ix0.programId.equals(SystemProgram3.programId)) {
|
|
11086
|
+
throw new Error(
|
|
11087
|
+
`paymaster top-up instruction 0 is owned by ${ix0.programId.toBase58()}, not the System Program \u2014 refusing to sign an unrecognised first instruction`
|
|
11088
|
+
);
|
|
11089
|
+
}
|
|
11090
|
+
const transfer2 = SystemInstruction.decodeTransfer(ix0);
|
|
11091
|
+
if (!transfer2.toPubkey.equals(expect.recipient)) {
|
|
11092
|
+
throw new Error(
|
|
11093
|
+
`paymaster top-up sends SOL to ${transfer2.toPubkey.toBase58()}, which is not our recipient ${expect.recipient.toBase58()} \u2014 refusing to sign a transaction that funds a key we do not control`
|
|
11094
|
+
);
|
|
11095
|
+
}
|
|
11096
|
+
if (BigInt(transfer2.lamports) > expect.maxGrantLamports) {
|
|
11097
|
+
throw new Error(
|
|
11098
|
+
`paymaster top-up grants ${transfer2.lamports} lamports, more than the ${expect.maxGrantLamports} we asked for \u2014 refusing a transaction that funds beyond our own request`
|
|
11099
|
+
);
|
|
11100
|
+
}
|
|
11101
|
+
if (ixs.length === 1) return;
|
|
11102
|
+
const ix1 = ixs[1];
|
|
11103
|
+
if (!ix1.programId.equals(TOKEN_PROGRAM_ID3)) {
|
|
11104
|
+
throw new Error(
|
|
11105
|
+
`paymaster top-up instruction 1 is owned by ${ix1.programId.toBase58()}, not the SPL Token program \u2014 refusing to sign an unrecognised second instruction`
|
|
11106
|
+
);
|
|
11107
|
+
}
|
|
11108
|
+
const spl = decodeTransferInstruction(ix1, TOKEN_PROGRAM_ID3);
|
|
11109
|
+
const authority = spl.keys.owner.pubkey;
|
|
11110
|
+
if (!authority.equals(expect.recipient)) {
|
|
11111
|
+
throw new Error(
|
|
11112
|
+
`paymaster top-up's fee transfer is authorised by ${authority.toBase58()}, not our recipient ${expect.recipient.toBase58()} \u2014 refusing to sign away tokens from an account we do not control`
|
|
11113
|
+
);
|
|
11114
|
+
}
|
|
11115
|
+
const expectedDestination = getAssociatedTokenAddressSync3(
|
|
11116
|
+
expect.feeMint,
|
|
11117
|
+
expect.paymentAddress,
|
|
11118
|
+
false
|
|
11119
|
+
);
|
|
11120
|
+
const destination = spl.keys.destination.pubkey;
|
|
11121
|
+
if (!destination.equals(expectedDestination)) {
|
|
11122
|
+
throw new Error(
|
|
11123
|
+
`paymaster top-up's fee transfer is addressed to ${destination.toBase58()}, not the paymaster's own payment ATA ${expectedDestination.toBase58()} \u2014 refusing to sign a payment to an unverified destination`
|
|
11124
|
+
);
|
|
11125
|
+
}
|
|
11126
|
+
const paidAmount = BigInt(spl.data.amount);
|
|
11127
|
+
if (paidAmount !== expect.feeTokenAmount) {
|
|
11128
|
+
throw new Error(
|
|
11129
|
+
`paymaster top-up's fee amount is ${paidAmount}, not the ${expect.feeTokenAmount} Kora quoted at prepare time \u2014 refusing to sign a payment that does not match the quote`
|
|
11130
|
+
);
|
|
11131
|
+
}
|
|
11132
|
+
}
|
|
11133
|
+
async function parseBridgeResponse2(res, what) {
|
|
11134
|
+
let body;
|
|
11135
|
+
try {
|
|
11136
|
+
body = await res.json();
|
|
11137
|
+
} catch {
|
|
11138
|
+
throw new Error(`${what} failed: ${res.status} ${res.statusText} (response body was not JSON)`);
|
|
11139
|
+
}
|
|
11140
|
+
if (!res.ok) {
|
|
11141
|
+
const b = body ?? {};
|
|
11142
|
+
throw new Error(
|
|
11143
|
+
`${what} failed: ${b.message ?? res.statusText} (${b.code ?? res.status}${b.retryable ? ", retryable" : ""})`
|
|
11144
|
+
);
|
|
11145
|
+
}
|
|
11146
|
+
return body;
|
|
11147
|
+
}
|
|
11148
|
+
async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
11149
|
+
assertAllowedRelayOrigin(relayUrl);
|
|
11150
|
+
if (grantLamports <= 0n || grantLamports > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
11151
|
+
throw new Error(
|
|
11152
|
+
`grantLamports must be a positive value representable as a JS number, got ${grantLamports}`
|
|
11153
|
+
);
|
|
11154
|
+
}
|
|
11155
|
+
const prepareRes = await relayFetch(`${relayUrl}/bridge/paymaster/prepare`, {
|
|
11156
|
+
method: "POST",
|
|
11157
|
+
headers: { "Content-Type": "application/json" },
|
|
11158
|
+
body: JSON.stringify({
|
|
11159
|
+
recipient: receiver.publicKey.toBase58(),
|
|
11160
|
+
grant_lamports: Number(grantLamports)
|
|
11161
|
+
})
|
|
11162
|
+
});
|
|
11163
|
+
const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
|
|
11164
|
+
if (Math.floor(Date.now() / 1e3) >= prepared.expires_at_unix) {
|
|
11165
|
+
throw new Error(
|
|
11166
|
+
"paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
|
|
11167
|
+
);
|
|
11168
|
+
}
|
|
11169
|
+
const feeMint = new PublicKey11(prepared.fee_mint);
|
|
11170
|
+
const paymentAddress = new PublicKey11(prepared.payment_address);
|
|
11171
|
+
const feeTokenAmount = BigInt(prepared.fee_token_amount);
|
|
11172
|
+
const tx = Transaction3.from(Buffer.from(prepared.transaction, "base64"));
|
|
11173
|
+
validatePaymasterTopUpTransaction(tx, {
|
|
11174
|
+
recipient: receiver.publicKey,
|
|
11175
|
+
maxGrantLamports: grantLamports,
|
|
11176
|
+
feeMint,
|
|
11177
|
+
feeTokenAmount,
|
|
11178
|
+
paymentAddress
|
|
11179
|
+
});
|
|
11180
|
+
tx.partialSign(receiver);
|
|
11181
|
+
const cosignRes = await relayFetch(`${relayUrl}/bridge/paymaster/cosign`, {
|
|
11182
|
+
method: "POST",
|
|
11183
|
+
headers: { "Content-Type": "application/json" },
|
|
11184
|
+
body: JSON.stringify({
|
|
11185
|
+
transaction: tx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString("base64"),
|
|
11186
|
+
voucher: prepared.voucher
|
|
11187
|
+
})
|
|
11188
|
+
});
|
|
11189
|
+
const cosigned = await parseBridgeResponse2(cosignRes, "paymaster cosign");
|
|
11190
|
+
return {
|
|
11191
|
+
transaction: Transaction3.from(Buffer.from(cosigned.transaction, "base64")),
|
|
11192
|
+
feeTokenAmount,
|
|
11193
|
+
feeMint: prepared.fee_mint,
|
|
11194
|
+
paymentAddress: prepared.payment_address
|
|
11195
|
+
};
|
|
11196
|
+
}
|
|
11197
|
+
|
|
11198
|
+
// src/bridge/derive.ts
|
|
11199
|
+
import { Keypair as Keypair4 } from "@solana/web3.js";
|
|
11200
|
+
import { hmac } from "@noble/hashes/hmac";
|
|
11201
|
+
import { sha512 } from "@noble/hashes/sha512";
|
|
11202
|
+
var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
|
|
11203
|
+
var MAX_RECEIVER_INDEX = 1e4;
|
|
11204
|
+
function deriveBridgeReceiver(nk, index) {
|
|
11205
|
+
if (!Number.isInteger(index) || index < 0) {
|
|
11206
|
+
throw new Error(`index must be a non-negative integer, got ${index}`);
|
|
11207
|
+
}
|
|
11208
|
+
if (index > MAX_RECEIVER_INDEX) {
|
|
11209
|
+
throw new Error(
|
|
11210
|
+
`index ${index} exceeds MAX_RECEIVER_INDEX (${MAX_RECEIVER_INDEX}). Indices must be a small sequential counter \u2014 discovery derives 0\u2026N and reads each on chain, so a timestamp index is unreachable by any scan and the deposit would be invisible to every device but this one.`
|
|
11211
|
+
);
|
|
11212
|
+
}
|
|
11213
|
+
const h = hmac(sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
|
|
11214
|
+
return Keypair4.fromSeed(h.slice(0, 32));
|
|
11215
|
+
}
|
|
11216
|
+
|
|
11217
|
+
// src/bridge/discover.ts
|
|
11218
|
+
import { SolanaJSONRPCError } from "@solana/web3.js";
|
|
11219
|
+
import { getAssociatedTokenAddressSync as getAssociatedTokenAddressSync4 } from "@solana/spl-token";
|
|
11220
|
+
function describeError(err) {
|
|
11221
|
+
return err instanceof Error ? err.message : String(err);
|
|
11222
|
+
}
|
|
11223
|
+
async function listBridgeDeposits(conn, nk, opts) {
|
|
11224
|
+
const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
|
|
11225
|
+
const stopAfterUnused = opts.stopAfterUnused ?? 5;
|
|
11226
|
+
const out = [];
|
|
11227
|
+
let consecutiveUnused = 0;
|
|
11228
|
+
for (let index = 0; index < scanDepth; index++) {
|
|
11229
|
+
const kp = deriveBridgeReceiver(nk, index);
|
|
11230
|
+
const receiver = kp.publicKey;
|
|
11231
|
+
const tokenAccount = getAssociatedTokenAddressSync4(opts.mint, receiver, false);
|
|
11232
|
+
try {
|
|
11233
|
+
const [recvInfo, ataInfo] = await conn.getMultipleAccountsInfo([receiver, tokenAccount]);
|
|
11234
|
+
const lamports = recvInfo?.lamports ?? 0;
|
|
11235
|
+
let tokenBalance = 0n;
|
|
11236
|
+
if (ataInfo) {
|
|
11237
|
+
try {
|
|
11238
|
+
tokenBalance = BigInt((await conn.getTokenAccountBalance(tokenAccount)).value.amount);
|
|
11239
|
+
} catch (err) {
|
|
11240
|
+
if (!(err instanceof SolanaJSONRPCError && /could not find account/i.test(err.message))) {
|
|
11241
|
+
throw err;
|
|
11242
|
+
}
|
|
11243
|
+
}
|
|
11244
|
+
}
|
|
11245
|
+
if (lamports === 0 && !ataInfo) {
|
|
11246
|
+
consecutiveUnused++;
|
|
11247
|
+
if (consecutiveUnused >= stopAfterUnused) break;
|
|
11248
|
+
continue;
|
|
11249
|
+
}
|
|
11250
|
+
consecutiveUnused = 0;
|
|
11251
|
+
const shieldSignatures = [];
|
|
11252
|
+
const sigs = await conn.getSignaturesForAddress(receiver, { limit: 20 });
|
|
11253
|
+
for (const s of sigs) {
|
|
11254
|
+
if (s.err) continue;
|
|
11255
|
+
const tx = await conn.getTransaction(s.signature, { maxSupportedTransactionVersion: 0 });
|
|
11256
|
+
const keys = tx?.transaction.message.getAccountKeys({
|
|
11257
|
+
accountKeysFromLookups: tx.meta?.loadedAddresses
|
|
11258
|
+
});
|
|
11259
|
+
if (keys && [...Array(keys.length).keys()].some((i) => keys.get(i)?.equals(opts.programId))) {
|
|
11260
|
+
shieldSignatures.push(s.signature);
|
|
11261
|
+
}
|
|
11262
|
+
}
|
|
11263
|
+
const shieldSignature = shieldSignatures[0];
|
|
11264
|
+
const indexReused = shieldSignatures.length > 1;
|
|
11265
|
+
let state;
|
|
11266
|
+
if (tokenBalance > 0n) state = shieldSignature ? "needs-cleanup" : "arrived";
|
|
11267
|
+
else if (shieldSignature) state = ataInfo ? "needs-cleanup" : "complete";
|
|
11268
|
+
else state = "awaiting";
|
|
11269
|
+
out.push({
|
|
11270
|
+
index,
|
|
11271
|
+
receiver,
|
|
11272
|
+
tokenAccount,
|
|
11273
|
+
state,
|
|
11274
|
+
tokenBalance,
|
|
11275
|
+
lamports,
|
|
11276
|
+
shieldSignature,
|
|
11277
|
+
...indexReused ? { indexReused, shieldSignatures } : {}
|
|
11278
|
+
});
|
|
11279
|
+
} catch (err) {
|
|
11280
|
+
out.push({
|
|
11281
|
+
index,
|
|
11282
|
+
receiver,
|
|
11283
|
+
tokenAccount,
|
|
11284
|
+
state: "unknown",
|
|
11285
|
+
tokenBalance: 0n,
|
|
11286
|
+
lamports: 0,
|
|
11287
|
+
error: describeError(err)
|
|
11288
|
+
});
|
|
11289
|
+
}
|
|
11290
|
+
}
|
|
11291
|
+
return out;
|
|
11292
|
+
}
|
|
11293
|
+
|
|
11294
|
+
// src/bridge/deposit-core.ts
|
|
11295
|
+
import {
|
|
11296
|
+
SystemProgram as SystemProgram4,
|
|
11297
|
+
Transaction as Transaction4,
|
|
11298
|
+
VersionedTransaction as VersionedTransaction2,
|
|
11299
|
+
sendAndConfirmTransaction as sendAndConfirmTransaction2
|
|
11300
|
+
} from "@solana/web3.js";
|
|
11301
|
+
import nacl8 from "tweetnacl";
|
|
11302
|
+
|
|
11303
|
+
// src/bridge/funder.ts
|
|
11304
|
+
import { PublicKey as PublicKey13 } from "@solana/web3.js";
|
|
11305
|
+
import { getAssociatedTokenAddressSync as getAssociatedTokenAddressSync5 } from "@solana/spl-token";
|
|
11306
|
+
var MAINNET_RENT_0 = 890880;
|
|
11307
|
+
var MAINNET_RENT_1 = 897840;
|
|
11308
|
+
var FEE_BUDGET = 13e4;
|
|
11309
|
+
var CLEANUP_FEE_BUDGET = 5e3;
|
|
11310
|
+
var pda = (seeds, programId) => PublicKey13.findProgramAddressSync(seeds.map((s) => Buffer.from(s)), programId)[0];
|
|
11311
|
+
function deriveFundingTargets(d) {
|
|
11312
|
+
const pool = pda([Buffer.from("pool"), d.mint.toBuffer()], d.programId);
|
|
11313
|
+
return {
|
|
11314
|
+
pool,
|
|
11315
|
+
// program: NullifierAccount::derive_pda_with_pool -> [b"nullifier", pool, nullifier]
|
|
11316
|
+
nullifier0: pda([Buffer.from("nullifier"), pool.toBuffer(), d.nullifiers[0]], d.programId),
|
|
11317
|
+
nullifier1: pda([Buffer.from("nullifier"), pool.toBuffer(), d.nullifiers[1]], d.programId),
|
|
11318
|
+
// relay: derive_risk_nonce_pda -> [b"risk_nonce", bind0]
|
|
11319
|
+
riskNonce: pda([Buffer.from("risk_nonce"), d.bind0], d.programId),
|
|
11320
|
+
depositorAta: getAssociatedTokenAddressSync5(d.mint, d.depositor, false)
|
|
11321
|
+
};
|
|
11322
|
+
}
|
|
11323
|
+
async function readRent(conn) {
|
|
11324
|
+
const [zero, one] = await Promise.all([
|
|
11325
|
+
conn.getMinimumBalanceForRentExemption(0),
|
|
11326
|
+
conn.getMinimumBalanceForRentExemption(1)
|
|
11327
|
+
]);
|
|
11328
|
+
return { zero, one };
|
|
11329
|
+
}
|
|
11330
|
+
|
|
11331
|
+
// src/bridge/deposit-core.ts
|
|
11332
|
+
var DepositError = class extends Error {
|
|
11333
|
+
constructor(message, fundedAccounts, measuredTxSize) {
|
|
11334
|
+
super(message);
|
|
11335
|
+
this.fundedAccounts = fundedAccounts;
|
|
11336
|
+
this.measuredTxSize = measuredTxSize;
|
|
11337
|
+
this.name = "DepositError";
|
|
11338
|
+
}
|
|
11339
|
+
};
|
|
11340
|
+
async function depositFromDerivedKey(conn, R, funder, amount, log = console.log, grantOverride, opts) {
|
|
11341
|
+
if (!opts.noteSpendKey || opts.noteSpendKey.length !== 32) {
|
|
11342
|
+
throw new Error(
|
|
11343
|
+
"opts.noteSpendKey (32 bytes) is required. It derives the note's spending key, and a note whose key is not derived from something you can reproduce is unspendable forever. Pass the same Cloak seed you derived the receiving address from."
|
|
11344
|
+
);
|
|
11345
|
+
}
|
|
11346
|
+
if (!opts.relayUrl) {
|
|
11347
|
+
throw new Error(
|
|
11348
|
+
"opts.relayUrl is required. There is no default: a missing relay used to resolve silently to the local stack, which is how a live run built a deposit against infrastructure that only existed on someone's laptop. Say which relay, every call."
|
|
11349
|
+
);
|
|
11350
|
+
}
|
|
11351
|
+
if (!opts.programId) {
|
|
11352
|
+
throw new Error(
|
|
11353
|
+
"opts.programId is required. There is no default: this is the exact field a live mainnet run once inherited from this module's local-stack constant, built a deposit against a program that does not exist on mainnet, and failed hunting a merkle tree that was never there."
|
|
11354
|
+
);
|
|
11355
|
+
}
|
|
11356
|
+
if (!opts.mint) {
|
|
11357
|
+
throw new Error(
|
|
11358
|
+
"opts.mint is required. There is no default: a deposit built for the wrong mint produces a note for an asset that never arrived at R, and there is nothing to silently fall back to."
|
|
11359
|
+
);
|
|
11360
|
+
}
|
|
11361
|
+
assertAllowedRpcConnection(conn);
|
|
11362
|
+
const relayUrl = opts.relayUrl;
|
|
11363
|
+
const programId = opts.programId;
|
|
11364
|
+
const mint = opts.mint;
|
|
11365
|
+
setCircuitsPath(resolveCircuitsBase());
|
|
11366
|
+
const grantR = grantOverride ?? MAINNET_RENT_0 + FEE_BUDGET + CLEANUP_FEE_BUDGET;
|
|
11367
|
+
const heldByR = await conn.getBalance(R.publicKey);
|
|
11368
|
+
if (heldByR >= grantR) {
|
|
11369
|
+
log(` R already holds ${heldByR} (>= ${grantR}) \u2014 no top-up needed`);
|
|
11370
|
+
} else {
|
|
11371
|
+
await sendAndConfirmTransaction2(conn, new Transaction4().add(
|
|
11372
|
+
SystemProgram4.transfer({ fromPubkey: funder.publicKey, toPubkey: R.publicKey, lamports: grantR - heldByR })
|
|
11373
|
+
), [funder]);
|
|
11374
|
+
log(` funder topped R up by ${grantR - heldByR} to ${grantR}${grantOverride !== void 0 ? " (OVERRIDDEN for a deliberate test)" : " \u2014 floor + deposit fee + cleanup fee, no rent"}`);
|
|
11375
|
+
}
|
|
11376
|
+
let measuredSize = -1;
|
|
11377
|
+
let fundedAccounts = [];
|
|
11378
|
+
const signTransaction2 = async (tx) => {
|
|
11379
|
+
if (tx instanceof VersionedTransaction2) {
|
|
11380
|
+
measuredSize = tx.serialize().length;
|
|
11381
|
+
const alts = await Promise.all(
|
|
11382
|
+
tx.message.addressTableLookups.map(async (l) => (await conn.getAddressLookupTable(l.accountKey)).value)
|
|
11383
|
+
);
|
|
11384
|
+
const keys = tx.message.getAccountKeys({ addressLookupTableAccounts: alts });
|
|
11385
|
+
const ix = tx.message.compiledInstructions.find((i) => keys.get(i.programIdIndex).equals(programId));
|
|
11386
|
+
const at = (n) => keys.get(ix.accountKeyIndexes[n]);
|
|
11387
|
+
const targets = [
|
|
11388
|
+
{ a: at(12), need: MAINNET_RENT_0, name: "risk_nonce" },
|
|
11389
|
+
{ a: at(4), need: MAINNET_RENT_1, name: "nullifier_0" },
|
|
11390
|
+
{ a: at(5), need: MAINNET_RENT_1, name: "nullifier_1" }
|
|
11391
|
+
];
|
|
11392
|
+
const infos = await conn.getMultipleAccountsInfo(targets.map((t) => t.a));
|
|
11393
|
+
fundedAccounts = targets.map((t, i) => ({
|
|
11394
|
+
name: t.name,
|
|
11395
|
+
address: t.a.toBase58(),
|
|
11396
|
+
lamportsSent: Math.max(0, t.need - (infos[i]?.lamports ?? 0))
|
|
11397
|
+
}));
|
|
11398
|
+
const ixs = targets.flatMap((t, i) => (infos[i]?.lamports ?? 0) >= t.need ? [] : [SystemProgram4.transfer({
|
|
11399
|
+
fromPubkey: funder.publicKey,
|
|
11400
|
+
toPubkey: t.a,
|
|
11401
|
+
lamports: t.need - (infos[i]?.lamports ?? 0)
|
|
11402
|
+
})]);
|
|
11403
|
+
if (ixs.length) {
|
|
11404
|
+
const sig = await sendAndConfirmTransaction2(conn, new Transaction4().add(...ixs), [funder]);
|
|
11405
|
+
log(` seam: funded ${ixs.length} program accounts read off the built tx \u2014 ${sig.slice(0, 16)}\u2026`);
|
|
11406
|
+
}
|
|
11407
|
+
tx.sign([R]);
|
|
11408
|
+
return tx;
|
|
11409
|
+
}
|
|
11410
|
+
tx.partialSign(R);
|
|
11411
|
+
return tx;
|
|
11412
|
+
};
|
|
11413
|
+
const signMessage = async (m) => nacl8.sign.detached(m, R.secretKey);
|
|
11414
|
+
const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
|
|
11415
|
+
const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
|
|
11416
|
+
const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
|
|
11417
|
+
const zeroInput = await createZeroUtxo(mint);
|
|
11418
|
+
const rBefore = await conn.getBalance(R.publicKey);
|
|
11419
|
+
let result;
|
|
11420
|
+
try {
|
|
11421
|
+
result = await transact(
|
|
11422
|
+
{ inputUtxos: [zeroInput], outputUtxos: [utxo], externalAmount: amount, depositor: R.publicKey },
|
|
11423
|
+
{
|
|
11424
|
+
connection: conn,
|
|
11425
|
+
programId,
|
|
11426
|
+
relayUrl,
|
|
11427
|
+
// NO depositorKeypair: the SDK branches `if (keypair) … else if (signTransaction)`
|
|
11428
|
+
// (transact.ts:2786, :2936), so passing one silently skips the funding seam.
|
|
11429
|
+
depositorPublicKey: R.publicKey,
|
|
11430
|
+
walletPublicKey: R.publicKey,
|
|
11431
|
+
signTransaction: signTransaction2,
|
|
11432
|
+
signMessage,
|
|
11433
|
+
chainNoteViewingKeyNk: nk,
|
|
11434
|
+
chainNoteSalt: noteSalt,
|
|
11435
|
+
relaySupplementalAlt: true,
|
|
11436
|
+
onProgress: (s) => log(` \xB7 ${s}`)
|
|
11437
|
+
}
|
|
11438
|
+
);
|
|
11439
|
+
} catch (e) {
|
|
11440
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
11441
|
+
throw new DepositError(msg, fundedAccounts, measuredSize);
|
|
11442
|
+
}
|
|
11443
|
+
const rAfter = await conn.getBalance(R.publicKey);
|
|
11444
|
+
const noteIndex = result.outputUtxos[0].index;
|
|
11445
|
+
if (noteIndex === void 0) throw new Error("deposit landed but the note has no index \u2014 it cannot be discovered later");
|
|
11446
|
+
return {
|
|
11447
|
+
signature: result.signature,
|
|
11448
|
+
noteIndex,
|
|
11449
|
+
amount: result.outputUtxos[0].amount,
|
|
11450
|
+
txSize: measuredSize,
|
|
11451
|
+
rBefore,
|
|
11452
|
+
rAfter,
|
|
11453
|
+
rentExempt: rAfter >= MAINNET_RENT_0,
|
|
11454
|
+
inputNullifiers: result.inputNullifiers,
|
|
11455
|
+
fundedAccounts
|
|
11456
|
+
};
|
|
11457
|
+
}
|
|
11458
|
+
|
|
11459
|
+
// src/bridge/cleanup.ts
|
|
11460
|
+
import {
|
|
11461
|
+
PublicKey as PublicKey15,
|
|
11462
|
+
Transaction as Transaction5,
|
|
11463
|
+
sendAndConfirmTransaction as sendAndConfirmTransaction3
|
|
11464
|
+
} from "@solana/web3.js";
|
|
11465
|
+
import {
|
|
11466
|
+
getAssociatedTokenAddressSync as getAssociatedTokenAddressSync6,
|
|
11467
|
+
createCloseAccountInstruction,
|
|
11468
|
+
createTransferInstruction,
|
|
11469
|
+
createAssociatedTokenAccountIdempotentInstruction,
|
|
11470
|
+
getMinimumBalanceForRentExemptAccount
|
|
11471
|
+
} from "@solana/spl-token";
|
|
11472
|
+
var DEFAULT_MINT = new PublicKey15("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
|
|
11473
|
+
async function cleanupReceivingAddress(conn, R, dustDestination, mint = DEFAULT_MINT) {
|
|
11474
|
+
assertAllowedRpcConnection(conn);
|
|
11475
|
+
const rAta = getAssociatedTokenAddressSync6(mint, R.publicKey);
|
|
11476
|
+
const info = await conn.getAccountInfo(rAta);
|
|
11477
|
+
if (!info) {
|
|
11478
|
+
return {
|
|
11479
|
+
closed: false,
|
|
11480
|
+
dustSwept: 0n,
|
|
11481
|
+
rentReturned: 0,
|
|
11482
|
+
destination: null,
|
|
11483
|
+
signature: null,
|
|
11484
|
+
note: "no token account \u2014 nothing to recover"
|
|
11485
|
+
};
|
|
11486
|
+
}
|
|
11487
|
+
const bal = BigInt((await conn.getTokenAccountBalance(rAta)).value.amount);
|
|
11488
|
+
const rentHeld = info.lamports;
|
|
11489
|
+
const before = await conn.getBalance(R.publicKey);
|
|
11490
|
+
const ixs = [];
|
|
11491
|
+
let destination = null;
|
|
11492
|
+
if (bal > 0n && !dustDestination) {
|
|
11493
|
+
return {
|
|
11494
|
+
closed: false,
|
|
11495
|
+
dustSwept: 0n,
|
|
11496
|
+
rentReturned: 0,
|
|
11497
|
+
destination: null,
|
|
11498
|
+
signature: null,
|
|
11499
|
+
note: `dusted with ${bal} base units after the deposit; leaving the account open and ${rentHeld.toLocaleString()} lamports of rent unrecovered, because sweeping it would publish a link from this deposit to whoever receives it`
|
|
11500
|
+
};
|
|
11501
|
+
}
|
|
11502
|
+
if (bal > 0n && dustDestination) {
|
|
11503
|
+
const destAta = getAssociatedTokenAddressSync6(mint, dustDestination);
|
|
11504
|
+
const destInfo = await conn.getAccountInfo(destAta);
|
|
11505
|
+
if (!destInfo) {
|
|
11506
|
+
const ataRent = await getMinimumBalanceForRentExemptAccount(conn);
|
|
11507
|
+
if (before < ataRent + CLEANUP_FEE_BUDGET) {
|
|
11508
|
+
throw new Error(
|
|
11509
|
+
`dustDestination ${dustDestination.toBase58()} has no token account for mint ${mint.toBase58()}, and creating one costs ${ataRent} lamports of rent that R does not have: R holds ${before}, which deposit-core.ts reserved only for this transaction's own fee (CLEANUP_FEE_BUDGET = ${CLEANUP_FEE_BUDGET} in funder.ts), not for a fresh account's rent. Fund R with at least ${ataRent + CLEANUP_FEE_BUDGET - before} more lamports first, or choose a destination that already has a token account for this mint.`
|
|
11510
|
+
);
|
|
11511
|
+
}
|
|
11512
|
+
ixs.push(createAssociatedTokenAccountIdempotentInstruction(R.publicKey, destAta, dustDestination, mint));
|
|
11513
|
+
}
|
|
11514
|
+
ixs.push(createTransferInstruction(rAta, destAta, R.publicKey, bal));
|
|
11515
|
+
destination = destAta.toBase58();
|
|
11516
|
+
}
|
|
11517
|
+
ixs.push(createCloseAccountInstruction(rAta, R.publicKey, R.publicKey));
|
|
11518
|
+
const signature = await sendAndConfirmTransaction3(conn, new Transaction5().add(...ixs), [R], {
|
|
11519
|
+
commitment: "confirmed"
|
|
11520
|
+
});
|
|
11521
|
+
const after = await conn.getBalance(R.publicKey);
|
|
11522
|
+
const gone = await conn.getAccountInfo(rAta) === null;
|
|
11523
|
+
return {
|
|
11524
|
+
closed: gone,
|
|
11525
|
+
dustSwept: bal,
|
|
11526
|
+
rentReturned: after - before,
|
|
11527
|
+
destination,
|
|
11528
|
+
signature,
|
|
11529
|
+
note: bal > 0n ? `swept ${bal} base units of dust to the caller-chosen destination and closed, in one transaction \u2014 note this publishes a link from the deposit to that destination` : `closed cleanly, nothing to sweep`
|
|
11530
|
+
};
|
|
11531
|
+
}
|
|
11532
|
+
|
|
11533
|
+
// src/bridge/quote.ts
|
|
11534
|
+
var MIN_DEPOSIT_SPL_BASE_UNITS = 1000000n;
|
|
11535
|
+
var WITHDRAW_FIXED_FEE = 450000n;
|
|
11536
|
+
var WITHDRAW_FEE_BPS = 30n;
|
|
11537
|
+
function withdrawFeeAt(amount, fixedFee, feeBps) {
|
|
11538
|
+
return fixedFee + amount * feeBps / 10000n;
|
|
11539
|
+
}
|
|
11540
|
+
var MAX_FEE_FRACTION = 0.063;
|
|
11541
|
+
var FIXED_ROUND_TRIP = 903000n;
|
|
11542
|
+
var ECONOMIC_MINIMUM = FIXED_ROUND_TRIP * 1000000n / BigInt(Math.round((MAX_FEE_FRACTION - 3e-3) * 1e6));
|
|
11543
|
+
function withdrawFeeFor(amount) {
|
|
11544
|
+
return withdrawFeeAt(amount, WITHDRAW_FIXED_FEE, WITHDRAW_FEE_BPS);
|
|
11545
|
+
}
|
|
11546
|
+
function assessBridgeQuote(q) {
|
|
11547
|
+
if (q.sent < 0n) {
|
|
11548
|
+
throw new Error(`assessBridgeQuote: sent must not be negative (got ${q.sent}).`);
|
|
11549
|
+
}
|
|
11550
|
+
if (q.arrivesMin > q.sent) {
|
|
11551
|
+
throw new Error(
|
|
11552
|
+
`assessBridgeQuote: arrivesMin (${q.arrivesMin}) exceeds sent (${q.sent}) \u2014 no rail returns more than it was given, so this input did not come from a real quote.`
|
|
11553
|
+
);
|
|
11554
|
+
}
|
|
11555
|
+
const shieldedMinRaw = q.arrivesMin - q.paymasterFee;
|
|
11556
|
+
const shieldedTargetRaw = q.arrivesTarget - q.paymasterFee;
|
|
11557
|
+
const shieldedMin = shieldedMinRaw > 0n ? shieldedMinRaw : 0n;
|
|
11558
|
+
const shieldedTarget = shieldedTargetRaw > 0n ? shieldedTargetRaw : 0n;
|
|
11559
|
+
const viable = shieldedMinRaw >= MIN_DEPOSIT_SPL_BASE_UNITS;
|
|
11560
|
+
const economic = q.sent >= ECONOMIC_MINIMUM;
|
|
11561
|
+
const withdrawFee = shieldedMin > 0n ? withdrawFeeAt(shieldedMin, q.liveWithdrawFixedFee ?? WITHDRAW_FIXED_FEE, q.liveWithdrawFeeBps ?? WITHDRAW_FEE_BPS) : 0n;
|
|
11562
|
+
const roundTripCost = q.sent - (shieldedMin > withdrawFee ? shieldedMin - withdrawFee : 0n);
|
|
11563
|
+
const roundTripFraction = q.sent > 0n ? Number(roundTripCost) / Number(q.sent) : 0;
|
|
11564
|
+
const reasons = [];
|
|
11565
|
+
if (!viable) {
|
|
11566
|
+
const short = MIN_DEPOSIT_SPL_BASE_UNITS - shieldedMinRaw;
|
|
11567
|
+
reasons.push(
|
|
11568
|
+
(shieldedMinRaw <= 0n ? `The ${fmt(q.paymasterFee)} paymaster fee alone is ${shieldedMinRaw < 0n ? `${fmt(-shieldedMinRaw)} more than` : "all of"} the ${fmt(q.arrivesMin)} the rail guarantees, so nothing would be left to shield.` : `Only ${fmt(shieldedMinRaw)} would be left to shield after the ${fmt(q.paymasterFee)} paymaster fee.`) + ` The program's minimum deposit is ${fmt(MIN_DEPOSIT_SPL_BASE_UNITS)}. Send at least ${fmt(q.sent + short)} to clear it.`
|
|
11569
|
+
);
|
|
11570
|
+
}
|
|
11571
|
+
if (viable && !economic) {
|
|
11572
|
+
reasons.push(
|
|
11573
|
+
`This works, but ${fmt(roundTripCost)} of ${fmt(q.sent)} goes to fees (${(roundTripFraction * 100).toFixed(0)}%). The costs are almost all fixed, so bridging ${fmt(ECONOMIC_MINIMUM)} or more spreads them much further.`
|
|
11574
|
+
);
|
|
11575
|
+
}
|
|
11576
|
+
return {
|
|
11577
|
+
...q,
|
|
11578
|
+
shieldedMin,
|
|
11579
|
+
shieldedTarget,
|
|
11580
|
+
viable,
|
|
11581
|
+
economic,
|
|
11582
|
+
withdrawFee,
|
|
11583
|
+
roundTripCost,
|
|
11584
|
+
roundTripFraction,
|
|
11585
|
+
reasons
|
|
11586
|
+
};
|
|
11587
|
+
}
|
|
11588
|
+
var fmt = (v) => `${(Number(v) / 1e6).toFixed(6)} USDC`;
|
|
11589
|
+
function renderAssessment(a) {
|
|
11590
|
+
const L = [];
|
|
11591
|
+
L.push(` you send ${fmt(a.sent)}`);
|
|
11592
|
+
L.push(` arrives at least ${fmt(a.arrivesMin)} (target ${fmt(a.arrivesTarget)}, not a promise)`);
|
|
11593
|
+
L.push(` paymaster fee ${fmt(a.paymasterFee)} buys the receiver its SOL, so your wallet stays off chain`);
|
|
11594
|
+
L.push(` SHIELDED ${fmt(a.shieldedMin)} at least \u2014 this is what you end up with`);
|
|
11595
|
+
L.push(` to withdraw later ${fmt(a.withdrawFee)} the program's fee, whenever you take it out`);
|
|
11596
|
+
for (const r of a.reasons) L.push(`
|
|
11597
|
+
${a.viable ? "NOTE" : "REFUSED"}: ${r}`);
|
|
11598
|
+
return L.join("\n");
|
|
11599
|
+
}
|
|
11600
|
+
|
|
11601
|
+
// src/bridge/retry.ts
|
|
11602
|
+
var TERMINAL_FAILURE = /DepositTooSmall|minimum is 1\.000000|insufficient|holds only|below the program|kora wants|over the .* ceiling/i;
|
|
11603
|
+
function isTerminalFailure(message) {
|
|
11604
|
+
return TERMINAL_FAILURE.test(message);
|
|
11605
|
+
}
|
|
11606
|
+
function classifyPostFailure(attempted, after) {
|
|
11607
|
+
if (after === null) return "unknown";
|
|
11608
|
+
if (after === 0n) return "landed";
|
|
11609
|
+
if (after >= attempted) return "did-not-land";
|
|
11610
|
+
return "unknown";
|
|
11611
|
+
}
|
|
11612
|
+
function mayRetry(verdict, message) {
|
|
11613
|
+
return verdict === "did-not-land" && !isTerminalFailure(message);
|
|
11614
|
+
}
|
|
11615
|
+
function retryDelayMs(attempt) {
|
|
11616
|
+
return 15e3 * Math.max(0, attempt - 1);
|
|
11617
|
+
}
|
|
11618
|
+
var DoNotRetry = class extends Error {
|
|
11619
|
+
constructor(message) {
|
|
11620
|
+
super(message);
|
|
11621
|
+
this.name = "DoNotRetry";
|
|
11622
|
+
}
|
|
11623
|
+
};
|
|
11624
|
+
async function withShieldRetries(attempt, hooks = {}) {
|
|
11625
|
+
const attempts = hooks.attempts ?? 3;
|
|
11626
|
+
const sleep4 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
11627
|
+
let last = "";
|
|
11628
|
+
for (let n = 1; n <= attempts; n++) {
|
|
11629
|
+
if (n > 1) {
|
|
11630
|
+
const delay = retryDelayMs(n);
|
|
11631
|
+
hooks.onRetry?.(n, delay, last);
|
|
11632
|
+
await sleep4(delay);
|
|
11633
|
+
}
|
|
11634
|
+
try {
|
|
11635
|
+
return await attempt(n);
|
|
11636
|
+
} catch (e) {
|
|
11637
|
+
if (e instanceof DoNotRetry) throw e;
|
|
11638
|
+
last = e instanceof Error ? e.message : String(e);
|
|
11639
|
+
if (isTerminalFailure(last) || n === attempts) throw e;
|
|
11640
|
+
}
|
|
11641
|
+
}
|
|
11642
|
+
throw new Error("unreachable");
|
|
11643
|
+
}
|
|
11644
|
+
|
|
10860
11645
|
// src/index.ts
|
|
10861
11646
|
var VERSION = "0.2.1";
|
|
10862
11647
|
var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
10863
11648
|
export {
|
|
11649
|
+
BRIDGE_ESCROW_LABEL,
|
|
10864
11650
|
BUILD_ALLOWS_LOCAL_ENDPOINTS,
|
|
10865
11651
|
CHAIN_NOTE_SALT_BITS,
|
|
11652
|
+
CLEANUP_FEE_BUDGET,
|
|
10866
11653
|
CLOAK_PRODUCTION_RELAY_URL,
|
|
10867
11654
|
CLOAK_PROGRAM_ID,
|
|
10868
11655
|
CloakError,
|
|
@@ -10870,16 +11657,25 @@ export {
|
|
|
10870
11657
|
DEFAULT_TRANSACTION_CIRCUITS_URL,
|
|
10871
11658
|
DELIVERY_MEMO_TAG,
|
|
10872
11659
|
DELIVERY_REGISTRY_SEED,
|
|
11660
|
+
DepositError,
|
|
11661
|
+
DoNotRetry,
|
|
11662
|
+
ECONOMIC_MINIMUM,
|
|
10873
11663
|
EXPECTED_CIRCUIT_HASHES,
|
|
11664
|
+
FEE_BUDGET,
|
|
10874
11665
|
FIXED_FEE_LAMPORTS,
|
|
10875
11666
|
InsecureRandomnessError,
|
|
10876
11667
|
LAMPORTS_PER_SOL,
|
|
10877
11668
|
LocalStorageAdapter,
|
|
11669
|
+
MAINNET_RENT_0,
|
|
11670
|
+
MAINNET_RENT_1,
|
|
11671
|
+
MAX_RECEIVER_INDEX,
|
|
10878
11672
|
MERKLE_TREE_HEIGHT2 as MERKLE_TREE_HEIGHT,
|
|
10879
11673
|
MIN_DEPOSIT_LAMPORTS,
|
|
11674
|
+
MIN_DEPOSIT_SPL_BASE_UNITS,
|
|
10880
11675
|
MemoryStorageAdapter,
|
|
10881
11676
|
MerkleTree,
|
|
10882
11677
|
NATIVE_SOL_MINT,
|
|
11678
|
+
ONECLICK_PUBKEY_B58,
|
|
10883
11679
|
RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
|
|
10884
11680
|
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
|
|
10885
11681
|
RECIPIENT_DELIVERY_NONCE_LEN,
|
|
@@ -10898,6 +11694,7 @@ export {
|
|
|
10898
11694
|
SettlementVerificationError,
|
|
10899
11695
|
ShieldPoolErrors,
|
|
10900
11696
|
SimpleWallet,
|
|
11697
|
+
TERMINAL_FAILURE,
|
|
10901
11698
|
TRANSACTION_CIRCUITS_VERSION,
|
|
10902
11699
|
TRANSACT_AUTH_FIELDS,
|
|
10903
11700
|
TRANSACT_SWAP_AUTH_FIELDS,
|
|
@@ -10907,8 +11704,11 @@ export {
|
|
|
10907
11704
|
VARIABLE_FEE_NUMERATOR,
|
|
10908
11705
|
VARIABLE_FEE_RATE,
|
|
10909
11706
|
VERSION,
|
|
11707
|
+
WITHDRAW_FEE_BPS,
|
|
11708
|
+
WITHDRAW_FIXED_FEE,
|
|
10910
11709
|
assertDirectSubmissionLanded,
|
|
10911
11710
|
assertTransactionCircuitIntegrity,
|
|
11711
|
+
assessBridgeQuote,
|
|
10912
11712
|
bigintToBytes32,
|
|
10913
11713
|
bigintToHex,
|
|
10914
11714
|
buildMerkleTree,
|
|
@@ -10923,12 +11723,16 @@ export {
|
|
|
10923
11723
|
calculateRelayFee,
|
|
10924
11724
|
canRebuildMerkleTreeFromChain,
|
|
10925
11725
|
canonicalJson,
|
|
11726
|
+
canonicalPayloadString,
|
|
10926
11727
|
chainNoteFromBase64,
|
|
10927
11728
|
chainNoteToBase64,
|
|
11729
|
+
classifyPostFailure,
|
|
10928
11730
|
classifyRelayError,
|
|
11731
|
+
cleanupReceivingAddress,
|
|
10929
11732
|
cleanupStalePendingOperations,
|
|
10930
11733
|
clearPendingDeposits,
|
|
10931
11734
|
clearPendingWithdrawals,
|
|
11735
|
+
cloakBridgeRail,
|
|
10932
11736
|
computeChainNoteHash,
|
|
10933
11737
|
computeExtDataHash,
|
|
10934
11738
|
computeMerkleRoot,
|
|
@@ -10950,10 +11754,13 @@ export {
|
|
|
10950
11754
|
decryptCompactChainNote,
|
|
10951
11755
|
decryptComplianceMetadataWithMasterKey,
|
|
10952
11756
|
decryptTransactionMetadata,
|
|
11757
|
+
depositFromDerivedKey,
|
|
11758
|
+
deriveBridgeReceiver,
|
|
10953
11759
|
deriveChangeNoteBlinding,
|
|
10954
11760
|
deriveDepositNoteSecrets,
|
|
10955
11761
|
deriveDiversifiedViewingKey,
|
|
10956
11762
|
deriveDiversifier,
|
|
11763
|
+
deriveFundingTargets,
|
|
10957
11764
|
deriveInputNullifierPdas,
|
|
10958
11765
|
derivePublicKey,
|
|
10959
11766
|
deriveSpendKey,
|
|
@@ -10992,6 +11799,7 @@ export {
|
|
|
10992
11799
|
formatErrorForLogging,
|
|
10993
11800
|
formatSol,
|
|
10994
11801
|
fullWithdraw,
|
|
11802
|
+
fundReceiverViaPaymaster,
|
|
10995
11803
|
generateCloakKeys,
|
|
10996
11804
|
generateCommitmentAsync,
|
|
10997
11805
|
generateMasterSeed,
|
|
@@ -11027,18 +11835,21 @@ export {
|
|
|
11027
11835
|
isReactNative,
|
|
11028
11836
|
isRootNotFoundError,
|
|
11029
11837
|
isSubmissionOutcomeUnknownResponse,
|
|
11838
|
+
isTerminalFailure,
|
|
11030
11839
|
isValidHex,
|
|
11031
11840
|
isValidRpcUrl,
|
|
11032
11841
|
isValidSolanaAddress,
|
|
11033
11842
|
isWithdrawAmountSufficient,
|
|
11034
11843
|
isWithdrawable,
|
|
11035
11844
|
keypairToAdapter,
|
|
11845
|
+
listBridgeDeposits,
|
|
11036
11846
|
loadPendingDeposits,
|
|
11037
11847
|
loadPendingWithdrawals,
|
|
11038
11848
|
loadVerifiedCircuitArtifacts,
|
|
11039
11849
|
matchChangeNote,
|
|
11040
11850
|
matchDepositNote,
|
|
11041
11851
|
matchSwapRefundLeaf,
|
|
11852
|
+
mayRetry,
|
|
11042
11853
|
openRecipientDeliveryNote,
|
|
11043
11854
|
parseAmount,
|
|
11044
11855
|
parseDeliveryCarrierMemo,
|
|
@@ -11061,11 +11872,14 @@ export {
|
|
|
11061
11872
|
randomDepositNoteSalt,
|
|
11062
11873
|
randomFieldElement,
|
|
11063
11874
|
readMerkleTreeState,
|
|
11875
|
+
readRent,
|
|
11064
11876
|
recipientDeliveryNoteToBase64,
|
|
11065
11877
|
registerViewingKey,
|
|
11066
11878
|
removePendingDeposit,
|
|
11067
11879
|
removePendingWithdrawal,
|
|
11880
|
+
renderAssessment,
|
|
11068
11881
|
resolveCircuitsBase,
|
|
11882
|
+
retryDelayMs,
|
|
11069
11883
|
savePendingDeposit,
|
|
11070
11884
|
savePendingWithdrawal,
|
|
11071
11885
|
scanNotesForWallet,
|
|
@@ -11098,13 +11912,17 @@ export {
|
|
|
11098
11912
|
validateDepositParams,
|
|
11099
11913
|
validateNote,
|
|
11100
11914
|
validateOutputsSum,
|
|
11915
|
+
validatePaymasterTopUpTransaction,
|
|
11101
11916
|
validateRoot,
|
|
11102
11917
|
validateTransfers,
|
|
11103
11918
|
validateWalletConnected,
|
|
11104
11919
|
validateWithdrawableNote,
|
|
11105
11920
|
verifyAllCircuits,
|
|
11106
11921
|
verifyCircuitIntegrity,
|
|
11922
|
+
verifyQuoteSignature,
|
|
11107
11923
|
verifyUtxos,
|
|
11108
11924
|
waitForRoot,
|
|
11109
|
-
|
|
11925
|
+
withShieldRetries,
|
|
11926
|
+
withTiming,
|
|
11927
|
+
withdrawFeeFor
|
|
11110
11928
|
};
|