@cloak.dev/sdk 0.2.3-staging.f2d7f2a → 0.2.3-staging.fdea6cd
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 +889 -432
- package/dist/index.d.cts +361 -127
- package/dist/index.d.ts +361 -127
- package/dist/index.js +856 -408
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -577,9 +577,9 @@ var LocalStorageAdapter = class {
|
|
|
577
577
|
};
|
|
578
578
|
|
|
579
579
|
// src/scanning/compliance-keys.ts
|
|
580
|
-
import
|
|
580
|
+
import nacl3 from "tweetnacl";
|
|
581
581
|
import { blake3 as blake32 } from "@noble/hashes/blake3";
|
|
582
|
-
import { sha256 } from "@noble/hashes/sha2";
|
|
582
|
+
import { sha256 as sha2562 } from "@noble/hashes/sha2";
|
|
583
583
|
|
|
584
584
|
// src/relay/viewing-key.ts
|
|
585
585
|
var VIEWING_KEY_CHALLENGE_PREFIX = "CLOAK_VIEWING_KEY_REGISTER";
|
|
@@ -766,6 +766,275 @@ function connectionRpcEndpoint(connection) {
|
|
|
766
766
|
return connection?._rpcEndpoint ?? connection?.rpcEndpoint;
|
|
767
767
|
}
|
|
768
768
|
|
|
769
|
+
// src/relay/payload.ts
|
|
770
|
+
import { sha256 } from "@noble/hashes/sha2";
|
|
771
|
+
import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils";
|
|
772
|
+
import nacl2 from "tweetnacl";
|
|
773
|
+
import { Keypair, PublicKey as PublicKey3, SystemProgram, Transaction } from "@solana/web3.js";
|
|
774
|
+
var REQUEST_AUTH_DOMAIN = "CLOAK_RELAY_REQUEST_AUTH_V1";
|
|
775
|
+
var REQUEST_AUTH_MAX_AGE_SECONDS = 300;
|
|
776
|
+
var REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS = 30;
|
|
777
|
+
var RELAY_AUTH_APPROVAL_MARGIN_SECONDS = 15;
|
|
778
|
+
function sha256Hex(text) {
|
|
779
|
+
return bytesToHex2(sha256(new TextEncoder().encode(text)));
|
|
780
|
+
}
|
|
781
|
+
function randomNonceUuid() {
|
|
782
|
+
const webCrypto = globalThis?.crypto;
|
|
783
|
+
if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
|
|
784
|
+
const proc = globalThis?.process;
|
|
785
|
+
const nodeCrypto = typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule("node:crypto") : void 0;
|
|
786
|
+
if (typeof nodeCrypto?.randomUUID === "function") return nodeCrypto.randomUUID();
|
|
787
|
+
const bytes = randomBytes(16);
|
|
788
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
789
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
790
|
+
const hex = bytesToHex2(bytes);
|
|
791
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
|
792
|
+
}
|
|
793
|
+
var TRANSACT_AUTH_FIELDS = [
|
|
794
|
+
"encrypted_notes",
|
|
795
|
+
"max_fee",
|
|
796
|
+
"mint",
|
|
797
|
+
"proof_bytes",
|
|
798
|
+
"public_inputs",
|
|
799
|
+
"recipient",
|
|
800
|
+
"recipient_delivery_notes",
|
|
801
|
+
"risk_quote",
|
|
802
|
+
"sender"
|
|
803
|
+
];
|
|
804
|
+
var TRANSACT_SWAP_AUTH_FIELDS = [
|
|
805
|
+
"close_timed_out",
|
|
806
|
+
"dexes",
|
|
807
|
+
"encrypted_notes",
|
|
808
|
+
"exclude_dexes",
|
|
809
|
+
"max_fee",
|
|
810
|
+
"min_output_amount",
|
|
811
|
+
"output_mint",
|
|
812
|
+
"proof_bytes",
|
|
813
|
+
"public_inputs",
|
|
814
|
+
"recipient",
|
|
815
|
+
"recipient_ata",
|
|
816
|
+
"refund_blinding",
|
|
817
|
+
"refund_pubkey",
|
|
818
|
+
"retry_request_id",
|
|
819
|
+
"risk_quote",
|
|
820
|
+
"route_retry_attempts",
|
|
821
|
+
"sender",
|
|
822
|
+
"slippage_bps",
|
|
823
|
+
"swap_max_retries"
|
|
824
|
+
];
|
|
825
|
+
var UTF8 = new TextEncoder();
|
|
826
|
+
function compareKeysBytewise(a, b) {
|
|
827
|
+
if (a === b) return 0;
|
|
828
|
+
const ab = UTF8.encode(a);
|
|
829
|
+
const bb = UTF8.encode(b);
|
|
830
|
+
const shared = Math.min(ab.length, bb.length);
|
|
831
|
+
for (let i = 0; i < shared; i++) {
|
|
832
|
+
if (ab[i] !== bb[i]) return ab[i] - bb[i];
|
|
833
|
+
}
|
|
834
|
+
return ab.length - bb.length;
|
|
835
|
+
}
|
|
836
|
+
function canonicalJson(value) {
|
|
837
|
+
if (value === null || value === void 0) return "null";
|
|
838
|
+
if (typeof value === "boolean") return value ? "true" : "false";
|
|
839
|
+
if (typeof value === "number") {
|
|
840
|
+
if (!Number.isFinite(value) || !Number.isInteger(value) || !Number.isSafeInteger(value)) {
|
|
841
|
+
throw new Error(
|
|
842
|
+
`canonicalJson: refusing to sign the number ${String(value)}. The relay renders numbers with serde_json, which spells non-integer, non-finite and very large values differently from JavaScript, so the two digests would differ and the request would be rejected with an unexplained 401. Send it as a decimal string instead, which is how every amount in this schema travels.`
|
|
843
|
+
);
|
|
844
|
+
}
|
|
845
|
+
return String(value);
|
|
846
|
+
}
|
|
847
|
+
if (typeof value === "bigint") return value.toString();
|
|
848
|
+
if (typeof value === "string") return JSON.stringify(value);
|
|
849
|
+
if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
|
|
850
|
+
if (typeof value === "object") {
|
|
851
|
+
const obj = value;
|
|
852
|
+
const keys = Object.keys(obj).sort(compareKeysBytewise);
|
|
853
|
+
return "{" + keys.map((k) => {
|
|
854
|
+
const v = obj[k];
|
|
855
|
+
if (typeof v === "function" || typeof v === "symbol") {
|
|
856
|
+
throw new Error(
|
|
857
|
+
`canonicalJson: the key "${k}" holds a ${typeof v}, which has no JSON representation. JSON.stringify would drop it from the wire body while it stayed in the signed view, so the relay's digest could never match this one.`
|
|
858
|
+
);
|
|
859
|
+
}
|
|
860
|
+
return `${JSON.stringify(k)}:${canonicalJson(v)}`;
|
|
861
|
+
}).join(",") + "}";
|
|
862
|
+
}
|
|
863
|
+
throw new Error(`canonicalJson: unsupported value of type ${typeof value}`);
|
|
864
|
+
}
|
|
865
|
+
var FIELDS_WITHOUT_NULL_ENCODING = {
|
|
866
|
+
slippage_bps: "500 (`default_slippage_bps` in api/transact_swap.rs)"
|
|
867
|
+
};
|
|
868
|
+
function buildAuthRequest(body, sender, fields) {
|
|
869
|
+
const out = {};
|
|
870
|
+
for (const k of fields) {
|
|
871
|
+
if (k === "sender") {
|
|
872
|
+
out[k] = sender;
|
|
873
|
+
continue;
|
|
874
|
+
}
|
|
875
|
+
const value = body[k];
|
|
876
|
+
if (value === void 0 || value === null) {
|
|
877
|
+
const relayDefault = FIELDS_WITHOUT_NULL_ENCODING[k];
|
|
878
|
+
if (relayDefault) {
|
|
879
|
+
throw new Error(
|
|
880
|
+
`Relay request auth: \`${k}\` must be present in the body. It is the one field in this schema that is not optional on the relay side: when it is missing the relay signs its default, ${relayDefault}, while this request would sign null. The two digests differ and the relay answers 401 "Relay request signature does not match the exact request", which points at nothing. Set \`${k}\` explicitly, to the same value the body will carry.`
|
|
881
|
+
);
|
|
882
|
+
}
|
|
883
|
+
out[k] = null;
|
|
884
|
+
continue;
|
|
885
|
+
}
|
|
886
|
+
out[k] = value;
|
|
887
|
+
}
|
|
888
|
+
return out;
|
|
889
|
+
}
|
|
890
|
+
function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request) {
|
|
891
|
+
const digest = sha256Hex(canonicalJson(request));
|
|
892
|
+
return new TextEncoder().encode(
|
|
893
|
+
`${REQUEST_AUTH_DOMAIN}
|
|
894
|
+
${endpoint}
|
|
895
|
+
${programId.toBase58()}
|
|
896
|
+
${nonce}
|
|
897
|
+
${issuedAt}
|
|
898
|
+
${digest}`
|
|
899
|
+
);
|
|
900
|
+
}
|
|
901
|
+
function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
|
|
902
|
+
const senderB58 = sender.toBase58();
|
|
903
|
+
const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
|
|
904
|
+
const nonce = randomNonceUuid();
|
|
905
|
+
const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
|
|
906
|
+
const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
|
|
907
|
+
return { sender: senderB58, auth_issued_at: issuedAt, auth_nonce: nonce, message };
|
|
908
|
+
}
|
|
909
|
+
function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
|
|
910
|
+
const preimage = buildRelayAuthPreimage(
|
|
911
|
+
endpoint,
|
|
912
|
+
programId,
|
|
913
|
+
body,
|
|
914
|
+
signer.publicKey,
|
|
915
|
+
nowSeconds,
|
|
916
|
+
fields
|
|
917
|
+
);
|
|
918
|
+
const signature = nacl2.sign.detached(preimage.message, signer.secretKey);
|
|
919
|
+
return {
|
|
920
|
+
sender: preimage.sender,
|
|
921
|
+
auth_issued_at: preimage.auth_issued_at,
|
|
922
|
+
auth_nonce: preimage.auth_nonce,
|
|
923
|
+
auth_signature: Buffer.from(signature).toString("base64")
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
function buildAuthTransactionMessage(sender, digest) {
|
|
927
|
+
if (digest.length !== 32) throw new Error(`auth transaction digest must be 32 bytes (got ${digest.length})`);
|
|
928
|
+
const tx = new Transaction();
|
|
929
|
+
tx.add(SystemProgram.transfer({ fromPubkey: sender, toPubkey: sender, lamports: 0 }));
|
|
930
|
+
tx.feePayer = sender;
|
|
931
|
+
tx.recentBlockhash = new PublicKey3(digest).toBase58();
|
|
932
|
+
return tx;
|
|
933
|
+
}
|
|
934
|
+
function serializeAuthTransactionMessage(sender, digest) {
|
|
935
|
+
return Uint8Array.from(buildAuthTransactionMessage(sender, digest).compileMessage().serialize());
|
|
936
|
+
}
|
|
937
|
+
async function signRelayAuthPayload(signer, payload) {
|
|
938
|
+
if (signer instanceof Keypair) {
|
|
939
|
+
return { signature: nacl2.sign.detached(payload, signer.secretKey), mode: "message" };
|
|
940
|
+
}
|
|
941
|
+
if (signer.signMessage) {
|
|
942
|
+
const signature = await signer.signMessage(payload);
|
|
943
|
+
assertDetachedSignature(signature, "signMessage");
|
|
944
|
+
return { signature, mode: "message" };
|
|
945
|
+
}
|
|
946
|
+
if (signer.signAuthTransaction) {
|
|
947
|
+
const digest = sha256(payload);
|
|
948
|
+
const signed = await signer.signAuthTransaction(buildAuthTransactionMessage(signer.walletPublicKey, digest));
|
|
949
|
+
const own = signed.signatures.find((s) => s.publicKey.equals(signer.walletPublicKey))?.signature;
|
|
950
|
+
if (!own) {
|
|
951
|
+
throw new Error(
|
|
952
|
+
"The wallet returned no signature for the Cloak auth transaction. Nothing was submitted."
|
|
953
|
+
);
|
|
954
|
+
}
|
|
955
|
+
const signature = Uint8Array.from(own);
|
|
956
|
+
assertDetachedSignature(signature, "signTransaction");
|
|
957
|
+
return { signature, mode: "transaction" };
|
|
958
|
+
}
|
|
959
|
+
throw new Error("Relay auth signer has neither signMessage nor signAuthTransaction.");
|
|
960
|
+
}
|
|
961
|
+
function assertDetachedSignature(signature, method) {
|
|
962
|
+
if (!(signature instanceof Uint8Array) || signature.length !== 64) {
|
|
963
|
+
throw new Error(
|
|
964
|
+
`The wallet's ${method} did not return a 64-byte ed25519 detached signature (got ${signature instanceof Uint8Array ? `${signature.length} bytes` : typeof signature}). Cloak signs with a raw detached signature over the bytes it hands the wallet; adapters that wrap or re-encode the result cannot be used here.`
|
|
965
|
+
);
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_AUTH_MAX_AGE_SECONDS) {
|
|
969
|
+
const elapsedSeconds = elapsedMs / 1e3;
|
|
970
|
+
const budget = maxAgeSeconds - RELAY_AUTH_APPROVAL_MARGIN_SECONDS;
|
|
971
|
+
if (elapsedSeconds <= budget) return;
|
|
972
|
+
throw new Error(
|
|
973
|
+
`The wallet approval took ${Math.round(elapsedSeconds)} seconds, and Cloak requests stay valid for ${maxAgeSeconds} seconds from the moment they are signed (${RELAY_AUTH_APPROVAL_MARGIN_SECONDS} of those are held back for the request to reach the network). The timestamp is inside the signature, so it cannot be refreshed without your approval again. NOTHING WAS SUBMITTED and no funds moved. Start the same operation again and approve the prompt when it appears.`
|
|
974
|
+
);
|
|
975
|
+
}
|
|
976
|
+
function explainRelayAuthRejection(responseText) {
|
|
977
|
+
const text = String(responseText);
|
|
978
|
+
const has = (needle) => text.includes(needle);
|
|
979
|
+
if (has("issued too far in the future")) {
|
|
980
|
+
return `This computer's clock is more than ${REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS} seconds ahead of the network's, so the request looks like it was signed in the future and is refused before anything else happens. Turn on automatic date and time (or resynchronise the clock) and try again. Nothing was submitted.`;
|
|
981
|
+
}
|
|
982
|
+
if (has("signature expired")) {
|
|
983
|
+
return `The request was signed more than ${REQUEST_AUTH_MAX_AGE_SECONDS} seconds before it arrived, usually because a wallet approval was left waiting, or because this computer's clock is running behind. The signed timestamp cannot be refreshed on its own. Start the operation again. Nothing was submitted.`;
|
|
984
|
+
}
|
|
985
|
+
if (has("does not match the exact request")) {
|
|
986
|
+
return `The request body changed after it was signed, so the relay's digest and this one disagree. Sign the exact body that is POSTed, and re-POST a retry byte for byte rather than rebuilding it. If this is a hand-built swap call, check that every field in TRANSACT_SWAP_AUTH_FIELDS is present, including \`slippage_bps\`.`;
|
|
987
|
+
}
|
|
988
|
+
if (has("has no registered viewing key")) {
|
|
989
|
+
return `The signature was accepted, so this is not a signing problem: the wallet that signed has no viewing key registered with Cloak yet. Register one first, or let the SDK do it by leaving \`enforceViewingKeyRegistration\` on and supplying the viewing key.`;
|
|
990
|
+
}
|
|
991
|
+
if (has("Authenticated sender is required") || has("auth_issued_at is required") || has("auth_nonce is required") || has("auth_signature is required")) {
|
|
992
|
+
return `The request reached the relay without its authentication fields. Pass \`depositorKeypair\`, or \`signMessage\` together with \`walletPublicKey\`, so the request can be signed.`;
|
|
993
|
+
}
|
|
994
|
+
if (has("auth_nonce must be a canonical UUID")) {
|
|
995
|
+
return `\`auth_nonce\` must be a canonical lowercase UUID. Reuse the one from the preimage.`;
|
|
996
|
+
}
|
|
997
|
+
if (has("Relay request signature must be exactly 64 bytes") || has("Invalid relay request signature encoding")) {
|
|
998
|
+
return `\`auth_signature\` must be the raw 64-byte ed25519 detached signature, base64 encoded. Wallet adapters that wrap or re-encode what \`signMessage\` returns cannot be used here.`;
|
|
999
|
+
}
|
|
1000
|
+
return null;
|
|
1001
|
+
}
|
|
1002
|
+
async function buildRelayAuthFields(endpoint, programId, body, signers, fields = TRANSACT_AUTH_FIELDS) {
|
|
1003
|
+
if (signers.depositorKeypair) {
|
|
1004
|
+
return signRelayRequest(endpoint, programId, body, signers.depositorKeypair, void 0, fields);
|
|
1005
|
+
}
|
|
1006
|
+
const wallet = signers.relayAuthSigner;
|
|
1007
|
+
if (!wallet) return null;
|
|
1008
|
+
const preimage = buildRelayAuthPreimage(
|
|
1009
|
+
endpoint,
|
|
1010
|
+
programId,
|
|
1011
|
+
body,
|
|
1012
|
+
wallet.walletPublicKey,
|
|
1013
|
+
void 0,
|
|
1014
|
+
fields
|
|
1015
|
+
);
|
|
1016
|
+
const approvalStartedMs = Date.now();
|
|
1017
|
+
const { signature, mode } = await signRelayAuthPayload(wallet, preimage.message);
|
|
1018
|
+
assertApprovalWithinFreshnessWindow(Date.now() - approvalStartedMs);
|
|
1019
|
+
return {
|
|
1020
|
+
sender: preimage.sender,
|
|
1021
|
+
auth_issued_at: preimage.auth_issued_at,
|
|
1022
|
+
auth_nonce: preimage.auth_nonce,
|
|
1023
|
+
auth_signature: Buffer.from(signature).toString("base64"),
|
|
1024
|
+
...mode === "transaction" ? { auth_mode: mode } : {}
|
|
1025
|
+
};
|
|
1026
|
+
}
|
|
1027
|
+
var REQUEST_AUTH_BATCH_DOMAIN = "CLOAK_RELAY_BATCH_AUTH_V1";
|
|
1028
|
+
var REQUEST_AUTH_BATCH_MAX_AGE_SECONDS = 600;
|
|
1029
|
+
var RELAY_BATCH_AUTH_MAX_ITEMS = 64;
|
|
1030
|
+
function relayRequestDigestHex(preimage) {
|
|
1031
|
+
return bytesToHex2(sha256(preimage.message));
|
|
1032
|
+
}
|
|
1033
|
+
function buildRelayBatchAuthMessage(programId, issuedAt, digests) {
|
|
1034
|
+
const lines = [REQUEST_AUTH_BATCH_DOMAIN, programId.toBase58(), issuedAt, String(digests.length)];
|
|
1035
|
+
return new TextEncoder().encode([...lines, ...digests].join("\n"));
|
|
1036
|
+
}
|
|
1037
|
+
|
|
769
1038
|
// src/scanning/compliance-keys.ts
|
|
770
1039
|
var X25519_KEY_LENGTH = 32;
|
|
771
1040
|
var DIVERSIFIER_LENGTH = 11;
|
|
@@ -803,7 +1072,7 @@ function deriveViewingKeyFromNk(nk) {
|
|
|
803
1072
|
preimage.set(nk, CHAIN_NOTE_VK_DOMAIN.length);
|
|
804
1073
|
const derived = blake32(preimage);
|
|
805
1074
|
const privateKey = clampX25519Secret(derived);
|
|
806
|
-
const publicKey =
|
|
1075
|
+
const publicKey = nacl3.scalarMult.base(privateKey);
|
|
807
1076
|
return { privateKey, publicKey };
|
|
808
1077
|
}
|
|
809
1078
|
function deriveDiversifier(nk, commitmentHex, outputIndex) {
|
|
@@ -838,7 +1107,7 @@ function deriveDiversifiedViewingKey(nk, diversifier) {
|
|
|
838
1107
|
preimage.set(diversifier, SK_D_DOMAIN.length + nk.length);
|
|
839
1108
|
const derived = blake32(preimage);
|
|
840
1109
|
const privateKey = clampX25519Secret(derived);
|
|
841
|
-
const publicKey =
|
|
1110
|
+
const publicKey = nacl3.scalarMult.base(privateKey);
|
|
842
1111
|
return { privateKey, publicKey };
|
|
843
1112
|
}
|
|
844
1113
|
function deriveViewingKeyFromSpendKey(skSpend) {
|
|
@@ -901,19 +1170,19 @@ async function deriveUserCompliancePublicKey(masterCompliancePublicKey, userPubl
|
|
|
901
1170
|
masterCompliancePublicKey,
|
|
902
1171
|
userPublicKey
|
|
903
1172
|
);
|
|
904
|
-
return
|
|
1173
|
+
return nacl3.scalarMult(factor, masterCompliancePublicKey);
|
|
905
1174
|
}
|
|
906
|
-
function
|
|
1175
|
+
function bytesToHex3(bytes) {
|
|
907
1176
|
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
908
1177
|
}
|
|
909
1178
|
function computeViewingKeyIdentifier(userPubkey, nkHex) {
|
|
910
1179
|
const preimage = new TextEncoder().encode(`${userPubkey.toBase58()}${nkHex}`);
|
|
911
|
-
return
|
|
1180
|
+
return bytesToHex3(sha2562(preimage));
|
|
912
1181
|
}
|
|
913
1182
|
var SIGN_IN_MESSAGE = "Cloak: Sign in\n\nSign this message to securely access your Cloak account.\nThis does NOT authorize any transaction or spend any funds.";
|
|
914
1183
|
async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
915
1184
|
assert32Bytes(nk, "nk");
|
|
916
|
-
const nkHex =
|
|
1185
|
+
const nkHex = bytesToHex3(nk);
|
|
917
1186
|
const keyId = computeViewingKeyIdentifier(userPubkey, nkHex);
|
|
918
1187
|
const challengeResponse = await relayFetch(`${relayUrl}/viewing-key/challenge`, {
|
|
919
1188
|
method: "POST",
|
|
@@ -934,8 +1203,11 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
|
934
1203
|
nkHex
|
|
935
1204
|
);
|
|
936
1205
|
const messageBytes = new TextEncoder().encode(challenge.message);
|
|
937
|
-
const
|
|
938
|
-
|
|
1206
|
+
const signed = await signRelayAuthPayload(
|
|
1207
|
+
typeof signMessage === "function" ? { walletPublicKey: userPubkey, signMessage } : signMessage,
|
|
1208
|
+
messageBytes
|
|
1209
|
+
);
|
|
1210
|
+
const signature = Buffer.from(signed.signature).toString("base64");
|
|
939
1211
|
const response = await relayFetch(`${relayUrl}/viewing-key/register`, {
|
|
940
1212
|
method: "POST",
|
|
941
1213
|
headers: { "Content-Type": "application/json" },
|
|
@@ -944,7 +1216,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
|
944
1216
|
viewing_key: nkHex,
|
|
945
1217
|
nonce: challenge.nonce,
|
|
946
1218
|
identifier: keyId,
|
|
947
|
-
signature
|
|
1219
|
+
signature,
|
|
1220
|
+
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
|
|
948
1221
|
})
|
|
949
1222
|
});
|
|
950
1223
|
if (!response.ok) {
|
|
@@ -953,7 +1226,7 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
|
953
1226
|
}
|
|
954
1227
|
|
|
955
1228
|
// src/scanning/metadata-encryption.ts
|
|
956
|
-
import
|
|
1229
|
+
import nacl4 from "tweetnacl";
|
|
957
1230
|
var AES_GCM_NONCE_LENGTH = 12;
|
|
958
1231
|
var AES_GCM_TAG_LENGTH = 16;
|
|
959
1232
|
var X25519_KEY_LENGTH2 = 32;
|
|
@@ -1050,8 +1323,8 @@ async function aesGcmDecrypt(ciphertext, keyBytes, nonce) {
|
|
|
1050
1323
|
}
|
|
1051
1324
|
async function encryptForRecipient(plaintext, recipientPublicKey) {
|
|
1052
1325
|
assert32Bytes2(recipientPublicKey, "recipientPublicKey");
|
|
1053
|
-
const ephemeral =
|
|
1054
|
-
const sharedSecret =
|
|
1326
|
+
const ephemeral = nacl4.box.keyPair();
|
|
1327
|
+
const sharedSecret = nacl4.scalarMult(ephemeral.secretKey, recipientPublicKey);
|
|
1055
1328
|
const nonce = randomBytes(AES_GCM_NONCE_LENGTH);
|
|
1056
1329
|
const ciphertext = await aesGcmEncrypt(plaintext, sharedSecret, nonce);
|
|
1057
1330
|
return {
|
|
@@ -1110,7 +1383,7 @@ async function encryptTransactionMetadataBundle(metadata, viewingKeyPrivate, use
|
|
|
1110
1383
|
const plaintext = new TextEncoder().encode(JSON.stringify(metadata));
|
|
1111
1384
|
const basePoint = new Uint8Array(32);
|
|
1112
1385
|
basePoint[0] = 9;
|
|
1113
|
-
const viewingKeyPublic =
|
|
1386
|
+
const viewingKeyPublic = nacl4.scalarMult(viewingKeyPrivate, basePoint);
|
|
1114
1387
|
const [userPayload, compliancePayload] = await Promise.all([
|
|
1115
1388
|
encryptForRecipient(plaintext, viewingKeyPublic),
|
|
1116
1389
|
encryptForRecipient(plaintext, viewingKeyPublic)
|
|
@@ -1129,7 +1402,7 @@ async function decryptTransactionMetadata(encrypted, viewKeySecret) {
|
|
|
1129
1402
|
const payload = decodePayload(encrypted);
|
|
1130
1403
|
const ephemeralPk = hexToBytes(payload.ephemeral_pk);
|
|
1131
1404
|
assert32Bytes2(ephemeralPk, "ephemeral public key");
|
|
1132
|
-
const sharedSecret =
|
|
1405
|
+
const sharedSecret = nacl4.scalarMult(viewKeySecret, ephemeralPk);
|
|
1133
1406
|
return decryptWithSharedSecret(payload, sharedSecret);
|
|
1134
1407
|
}
|
|
1135
1408
|
async function decryptComplianceMetadataWithMasterKey(encrypted, masterCompliancePrivateKey, masterCompliancePublicKey, userPublicKey) {
|
|
@@ -1142,8 +1415,8 @@ async function decryptComplianceMetadataWithMasterKey(encrypted, masterComplianc
|
|
|
1142
1415
|
masterCompliancePublicKey,
|
|
1143
1416
|
userPublicKey
|
|
1144
1417
|
);
|
|
1145
|
-
const scaledEphemeral =
|
|
1146
|
-
const sharedSecret =
|
|
1418
|
+
const scaledEphemeral = nacl4.scalarMult(userFactor, ephemeralPk);
|
|
1419
|
+
const sharedSecret = nacl4.scalarMult(masterCompliancePrivateKey, scaledEphemeral);
|
|
1147
1420
|
return decryptWithSharedSecret(payload, sharedSecret);
|
|
1148
1421
|
}
|
|
1149
1422
|
|
|
@@ -2073,22 +2346,22 @@ function formatErrorForLogging(error) {
|
|
|
2073
2346
|
}
|
|
2074
2347
|
|
|
2075
2348
|
// src/program/pda.ts
|
|
2076
|
-
import { PublicKey as
|
|
2349
|
+
import { PublicKey as PublicKey4 } from "@solana/web3.js";
|
|
2077
2350
|
function getShieldPoolPDAs(programId, mint = NATIVE_SOL_MINT) {
|
|
2078
2351
|
const pid = programId || CLOAK_PROGRAM_ID;
|
|
2079
|
-
const [pool] =
|
|
2352
|
+
const [pool] = PublicKey4.findProgramAddressSync(
|
|
2080
2353
|
[Buffer.from("pool"), mint.toBuffer()],
|
|
2081
2354
|
pid
|
|
2082
2355
|
);
|
|
2083
|
-
const [merkleTree] =
|
|
2356
|
+
const [merkleTree] = PublicKey4.findProgramAddressSync(
|
|
2084
2357
|
[Buffer.from("merkle_tree"), mint.toBuffer()],
|
|
2085
2358
|
pid
|
|
2086
2359
|
);
|
|
2087
|
-
const [treasury] =
|
|
2360
|
+
const [treasury] = PublicKey4.findProgramAddressSync(
|
|
2088
2361
|
[Buffer.from("treasury"), mint.toBuffer()],
|
|
2089
2362
|
pid
|
|
2090
2363
|
);
|
|
2091
|
-
const [vaultAuthority] =
|
|
2364
|
+
const [vaultAuthority] = PublicKey4.findProgramAddressSync(
|
|
2092
2365
|
[Buffer.from("vault_authority"), mint.toBuffer()],
|
|
2093
2366
|
pid
|
|
2094
2367
|
);
|
|
@@ -2104,7 +2377,7 @@ function getNullifierPDA(poolPubkey, nullifier, programId) {
|
|
|
2104
2377
|
if (nullifier.length !== 32) {
|
|
2105
2378
|
throw new Error(`Nullifier must be 32 bytes, got ${nullifier.length}`);
|
|
2106
2379
|
}
|
|
2107
|
-
return
|
|
2380
|
+
return PublicKey4.findProgramAddressSync(
|
|
2108
2381
|
[Buffer.from("nullifier"), poolPubkey.toBuffer(), Buffer.from(nullifier)],
|
|
2109
2382
|
pid
|
|
2110
2383
|
);
|
|
@@ -2114,25 +2387,25 @@ function getSwapStatePDA(poolPubkey, nullifier, programId) {
|
|
|
2114
2387
|
if (nullifier.length !== 32) {
|
|
2115
2388
|
throw new Error(`Nullifier must be 32 bytes, got ${nullifier.length}`);
|
|
2116
2389
|
}
|
|
2117
|
-
return
|
|
2390
|
+
return PublicKey4.findProgramAddressSync(
|
|
2118
2391
|
[Buffer.from("swap_state"), poolPubkey.toBuffer(), Buffer.from(nullifier)],
|
|
2119
2392
|
pid
|
|
2120
2393
|
);
|
|
2121
2394
|
}
|
|
2122
2395
|
function getPoolAuthorityConfigPDA(mint = NATIVE_SOL_MINT, programId) {
|
|
2123
2396
|
const pid = programId || CLOAK_PROGRAM_ID;
|
|
2124
|
-
return
|
|
2397
|
+
return PublicKey4.findProgramAddressSync(
|
|
2125
2398
|
[Buffer.from("pool_authority"), mint.toBuffer()],
|
|
2126
2399
|
pid
|
|
2127
2400
|
);
|
|
2128
2401
|
}
|
|
2129
2402
|
function getDeliveryRegistryPDA(programId) {
|
|
2130
2403
|
const pid = programId || CLOAK_PROGRAM_ID;
|
|
2131
|
-
return
|
|
2404
|
+
return PublicKey4.findProgramAddressSync([Buffer.from("cloak_delivery_registry")], pid)[0];
|
|
2132
2405
|
}
|
|
2133
2406
|
function getChainNoteRegistryPDA(programId) {
|
|
2134
2407
|
const pid = programId || CLOAK_PROGRAM_ID;
|
|
2135
|
-
return
|
|
2408
|
+
return PublicKey4.findProgramAddressSync([Buffer.from("cloak_chain_note_registry")], pid)[0];
|
|
2136
2409
|
}
|
|
2137
2410
|
|
|
2138
2411
|
// src/flows/verify-utxos.ts
|
|
@@ -2463,7 +2736,8 @@ function truncate(str, len = 20) {
|
|
|
2463
2736
|
var sdkLogger = createLogger("cloak::sdk");
|
|
2464
2737
|
|
|
2465
2738
|
// src/relay/relay-service.ts
|
|
2466
|
-
import { sha256 as
|
|
2739
|
+
import { sha256 as sha2563 } from "@noble/hashes/sha2";
|
|
2740
|
+
import { PublicKey as PublicKey5 } from "@solana/web3.js";
|
|
2467
2741
|
var RelayService = class {
|
|
2468
2742
|
/**
|
|
2469
2743
|
* Create a new Relay Service client
|
|
@@ -2779,8 +3053,11 @@ var RelayService = class {
|
|
|
2779
3053
|
userPubkey,
|
|
2780
3054
|
viewingKey
|
|
2781
3055
|
);
|
|
2782
|
-
const
|
|
2783
|
-
|
|
3056
|
+
const signed = await signRelayAuthPayload(
|
|
3057
|
+
typeof signMessage === "function" ? { walletPublicKey: new PublicKey5(userPubkey), signMessage } : signMessage,
|
|
3058
|
+
new TextEncoder().encode(challenge.message)
|
|
3059
|
+
);
|
|
3060
|
+
const signature = this.bytesToBase64(signed.signature);
|
|
2784
3061
|
const response = await relayFetch(`${this.baseUrl}/viewing-key/register`, {
|
|
2785
3062
|
method: "POST",
|
|
2786
3063
|
headers: { "Content-Type": "application/json" },
|
|
@@ -2789,7 +3066,8 @@ var RelayService = class {
|
|
|
2789
3066
|
viewing_key: viewingKey,
|
|
2790
3067
|
nonce: challenge.nonce,
|
|
2791
3068
|
identifier,
|
|
2792
|
-
signature
|
|
3069
|
+
signature,
|
|
3070
|
+
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
|
|
2793
3071
|
})
|
|
2794
3072
|
});
|
|
2795
3073
|
if (!response.ok) {
|
|
@@ -2827,7 +3105,7 @@ var RelayService = class {
|
|
|
2827
3105
|
}
|
|
2828
3106
|
computeViewingKeyIdentifier(userPubkey, viewingKeyHex) {
|
|
2829
3107
|
const preimage = new TextEncoder().encode(`${userPubkey}${viewingKeyHex}`);
|
|
2830
|
-
const hash =
|
|
3108
|
+
const hash = sha2563(preimage);
|
|
2831
3109
|
return Array.from(hash).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
2832
3110
|
}
|
|
2833
3111
|
};
|
|
@@ -2945,10 +3223,10 @@ function encodeNoteSimple(note) {
|
|
|
2945
3223
|
|
|
2946
3224
|
// src/wallet/adapter.ts
|
|
2947
3225
|
import {
|
|
2948
|
-
Keypair
|
|
3226
|
+
Keypair as Keypair2
|
|
2949
3227
|
} from "@solana/web3.js";
|
|
2950
3228
|
function validateWalletConnected(wallet) {
|
|
2951
|
-
if (wallet instanceof
|
|
3229
|
+
if (wallet instanceof Keypair2) {
|
|
2952
3230
|
return;
|
|
2953
3231
|
}
|
|
2954
3232
|
if (!wallet.publicKey) {
|
|
@@ -2960,7 +3238,7 @@ function validateWalletConnected(wallet) {
|
|
|
2960
3238
|
}
|
|
2961
3239
|
}
|
|
2962
3240
|
function getPublicKey(wallet) {
|
|
2963
|
-
if (wallet instanceof
|
|
3241
|
+
if (wallet instanceof Keypair2) {
|
|
2964
3242
|
return wallet.publicKey;
|
|
2965
3243
|
}
|
|
2966
3244
|
if (!wallet.publicKey) {
|
|
@@ -2974,7 +3252,7 @@ function getPublicKey(wallet) {
|
|
|
2974
3252
|
}
|
|
2975
3253
|
async function sendTransaction(transaction, wallet, connection, options) {
|
|
2976
3254
|
assertAllowedRpcConnection(connection);
|
|
2977
|
-
if (wallet instanceof
|
|
3255
|
+
if (wallet instanceof Keypair2) {
|
|
2978
3256
|
return await connection.sendTransaction(transaction, [wallet], options);
|
|
2979
3257
|
}
|
|
2980
3258
|
if (wallet.sendTransaction) {
|
|
@@ -2991,7 +3269,7 @@ async function sendTransaction(transaction, wallet, connection, options) {
|
|
|
2991
3269
|
}
|
|
2992
3270
|
}
|
|
2993
3271
|
async function signTransaction(transaction, wallet) {
|
|
2994
|
-
if (wallet instanceof
|
|
3272
|
+
if (wallet instanceof Keypair2) {
|
|
2995
3273
|
transaction.sign(wallet);
|
|
2996
3274
|
return transaction;
|
|
2997
3275
|
}
|
|
@@ -3020,8 +3298,8 @@ function keypairToAdapter(keypair) {
|
|
|
3020
3298
|
|
|
3021
3299
|
// src/program/instructions.ts
|
|
3022
3300
|
import {
|
|
3023
|
-
PublicKey as
|
|
3024
|
-
SystemProgram,
|
|
3301
|
+
PublicKey as PublicKey7,
|
|
3302
|
+
SystemProgram as SystemProgram2,
|
|
3025
3303
|
TransactionInstruction
|
|
3026
3304
|
} from "@solana/web3.js";
|
|
3027
3305
|
function createDepositInstruction(params) {
|
|
@@ -3053,7 +3331,7 @@ function createDepositInstruction(params) {
|
|
|
3053
3331
|
// Account 1: Pool (writable) - receives SOL
|
|
3054
3332
|
{ pubkey: params.pool, isSigner: false, isWritable: true },
|
|
3055
3333
|
// Account 2: System Program (readonly) - for transfers
|
|
3056
|
-
{ pubkey:
|
|
3334
|
+
{ pubkey: SystemProgram2.programId, isSigner: false, isWritable: false },
|
|
3057
3335
|
// Account 3: Merkle Tree (writable) - stores on-chain Merkle tree
|
|
3058
3336
|
{ pubkey: params.merkleTree, isSigner: false, isWritable: true }
|
|
3059
3337
|
],
|
|
@@ -3061,16 +3339,16 @@ function createDepositInstruction(params) {
|
|
|
3061
3339
|
});
|
|
3062
3340
|
}
|
|
3063
3341
|
function validateDepositParams(params) {
|
|
3064
|
-
if (!(params.programId instanceof
|
|
3342
|
+
if (!(params.programId instanceof PublicKey7)) {
|
|
3065
3343
|
throw new Error("programId must be a PublicKey");
|
|
3066
3344
|
}
|
|
3067
|
-
if (!(params.payer instanceof
|
|
3345
|
+
if (!(params.payer instanceof PublicKey7)) {
|
|
3068
3346
|
throw new Error("payer must be a PublicKey");
|
|
3069
3347
|
}
|
|
3070
|
-
if (!(params.pool instanceof
|
|
3348
|
+
if (!(params.pool instanceof PublicKey7)) {
|
|
3071
3349
|
throw new Error("pool must be a PublicKey");
|
|
3072
3350
|
}
|
|
3073
|
-
if (!(params.merkleTree instanceof
|
|
3351
|
+
if (!(params.merkleTree instanceof PublicKey7)) {
|
|
3074
3352
|
throw new Error("merkleTree must be a PublicKey");
|
|
3075
3353
|
}
|
|
3076
3354
|
if (typeof params.amount !== "number" || params.amount <= 0) {
|
|
@@ -3168,6 +3446,23 @@ async function readMerkleTreeState(connection, merkleTreePDA, forceConfirmed = f
|
|
|
3168
3446
|
const finalRoot = root || rpcRoot;
|
|
3169
3447
|
return { nextIndex, root: finalRoot, subtrees };
|
|
3170
3448
|
}
|
|
3449
|
+
function nearTipProofUndecidableLevels(leafIndex, nextIndex, height = MERKLE_TREE_HEIGHT) {
|
|
3450
|
+
if (!Number.isInteger(leafIndex) || !Number.isInteger(nextIndex) || !Number.isInteger(height)) {
|
|
3451
|
+
throw new Error(`nearTipProofUndecidableLevels: integers required (leafIndex=${leafIndex}, nextIndex=${nextIndex}, height=${height})`);
|
|
3452
|
+
}
|
|
3453
|
+
if (leafIndex < 0 || leafIndex >= nextIndex) {
|
|
3454
|
+
throw new Error(`Leaf index ${leafIndex} is not below next_index ${nextIndex}`);
|
|
3455
|
+
}
|
|
3456
|
+
const levels = [];
|
|
3457
|
+
for (let level = 0; level < height; level++) {
|
|
3458
|
+
const width = 2 ** level;
|
|
3459
|
+
const ancestor = Math.floor(leafIndex / width);
|
|
3460
|
+
if (ancestor % 2 === 1 && (ancestor + 1) * width < nextIndex) {
|
|
3461
|
+
levels.push(level);
|
|
3462
|
+
}
|
|
3463
|
+
}
|
|
3464
|
+
return levels;
|
|
3465
|
+
}
|
|
3171
3466
|
async function computeProofFromChain(connection, merkleTreePDA, leafIndex, forceConfirmed = false) {
|
|
3172
3467
|
assertAllowedRpcConnection(connection);
|
|
3173
3468
|
await ensureZeroValues();
|
|
@@ -3200,7 +3495,12 @@ async function computeProofFromChain(connection, merkleTreePDA, leafIndex, force
|
|
|
3200
3495
|
}
|
|
3201
3496
|
index = Math.floor(index / 2);
|
|
3202
3497
|
}
|
|
3203
|
-
return {
|
|
3498
|
+
return {
|
|
3499
|
+
pathElements,
|
|
3500
|
+
pathIndices,
|
|
3501
|
+
root,
|
|
3502
|
+
undecidableLevels: nearTipProofUndecidableLevels(leafIndex, nextIndex)
|
|
3503
|
+
};
|
|
3204
3504
|
}
|
|
3205
3505
|
async function computeProofForLatestDeposit(connection, merkleTreePDA) {
|
|
3206
3506
|
assertAllowedRpcConnection(connection);
|
|
@@ -3211,7 +3511,7 @@ async function computeProofForLatestDeposit(connection, merkleTreePDA) {
|
|
|
3211
3511
|
}
|
|
3212
3512
|
const leafIndex = nextIndex - 1;
|
|
3213
3513
|
const proof = await computeProofInternal(leafIndex, nextIndex, subtrees);
|
|
3214
|
-
return { ...proof, root, leafIndex };
|
|
3514
|
+
return { ...proof, root, leafIndex, undecidableLevels: [] };
|
|
3215
3515
|
}
|
|
3216
3516
|
async function computeProofInternal(leafIndex, _nextIndex, subtrees) {
|
|
3217
3517
|
const pathElements = [];
|
|
@@ -3410,7 +3710,7 @@ async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
|
|
|
3410
3710
|
}
|
|
3411
3711
|
|
|
3412
3712
|
// src/relay/client.ts
|
|
3413
|
-
import { PublicKey as
|
|
3713
|
+
import { PublicKey as PublicKey8 } from "@solana/web3.js";
|
|
3414
3714
|
import _bs58 from "bs58";
|
|
3415
3715
|
|
|
3416
3716
|
// src/notes/refund-leaf.ts
|
|
@@ -3519,6 +3819,9 @@ function isBrowserLike() {
|
|
|
3519
3819
|
return typeof globalThis !== "undefined" && (typeof globalThis.window !== "undefined" || typeof globalThis.document !== "undefined");
|
|
3520
3820
|
}
|
|
3521
3821
|
|
|
3822
|
+
// src/config/transaction-version.ts
|
|
3823
|
+
var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
|
|
3824
|
+
|
|
3522
3825
|
// src/relay/client.ts
|
|
3523
3826
|
var bs58 = _bs58.default || _bs58;
|
|
3524
3827
|
var TRANSACT_TAG = 0;
|
|
@@ -3527,7 +3830,7 @@ var CLOSE_SWAP_STATE_TAG = 13;
|
|
|
3527
3830
|
var CLOSE_SWAP_STATE_PHASE1_PAYLOAD_LEN = 40;
|
|
3528
3831
|
var CLOSE_SWAP_STATE_PHASE1_WIRE_LEN = 1 + CLOSE_SWAP_STATE_PHASE1_PAYLOAD_LEN;
|
|
3529
3832
|
var CLOSE_SWAP_STATE_COMMITMENT_END = 1 + 32;
|
|
3530
|
-
var NATIVE_SOL_MINT2 = new
|
|
3833
|
+
var NATIVE_SOL_MINT2 = new PublicKey8("So11111111111111111111111111111111111111112");
|
|
3531
3834
|
var PROOF_LEN = 256;
|
|
3532
3835
|
var PUBLIC_INPUTS_LEN = 264;
|
|
3533
3836
|
var COMMITMENTS_OFFSET = 168;
|
|
@@ -3730,7 +4033,7 @@ async function buildMerkleTreeFromChain(connection, programId, merkleTree, onPro
|
|
|
3730
4033
|
}
|
|
3731
4034
|
const signature = signatures[i];
|
|
3732
4035
|
const tx = await connection.getParsedTransaction(signature, {
|
|
3733
|
-
maxSupportedTransactionVersion:
|
|
4036
|
+
maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION,
|
|
3734
4037
|
commitment: "confirmed"
|
|
3735
4038
|
});
|
|
3736
4039
|
if (!tx || tx.meta?.err) continue;
|
|
@@ -3817,11 +4120,11 @@ async function preflightCheck(relayUrl, rootHex) {
|
|
|
3817
4120
|
|
|
3818
4121
|
// src/flows/transact.ts
|
|
3819
4122
|
import {
|
|
3820
|
-
PublicKey as
|
|
3821
|
-
Transaction as
|
|
4123
|
+
PublicKey as PublicKey10,
|
|
4124
|
+
Transaction as Transaction3,
|
|
3822
4125
|
TransactionInstruction as TransactionInstruction2,
|
|
3823
4126
|
sendAndConfirmTransaction,
|
|
3824
|
-
SystemProgram as
|
|
4127
|
+
SystemProgram as SystemProgram3,
|
|
3825
4128
|
ComputeBudgetProgram,
|
|
3826
4129
|
SYSVAR_INSTRUCTIONS_PUBKEY,
|
|
3827
4130
|
SYSVAR_SLOT_HASHES_PUBKEY,
|
|
@@ -4060,7 +4363,7 @@ function chainNoteFromBase64(base64) {
|
|
|
4060
4363
|
}
|
|
4061
4364
|
|
|
4062
4365
|
// src/notes/delivery-note.ts
|
|
4063
|
-
import
|
|
4366
|
+
import nacl5 from "tweetnacl";
|
|
4064
4367
|
var RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN = 32;
|
|
4065
4368
|
var RECIPIENT_DELIVERY_NONCE_LEN = 24;
|
|
4066
4369
|
var RECIPIENT_DELIVERY_PLAINTEXT_LEN = 40;
|
|
@@ -4111,10 +4414,10 @@ function encodeRecipientDeliveryNote(note, recipientViewingPublicKey) {
|
|
|
4111
4414
|
const plaintext = new Uint8Array(RECIPIENT_DELIVERY_PLAINTEXT_LEN);
|
|
4112
4415
|
writeU64LE2(plaintext, 0, note.amount);
|
|
4113
4416
|
writeU256BE2(plaintext, 8, note.blinding);
|
|
4114
|
-
const ephemeral =
|
|
4115
|
-
const shared =
|
|
4116
|
-
const nonce =
|
|
4117
|
-
const ciphertext =
|
|
4417
|
+
const ephemeral = nacl5.box.keyPair();
|
|
4418
|
+
const shared = nacl5.box.before(recipientViewingPublicKey, ephemeral.secretKey);
|
|
4419
|
+
const nonce = nacl5.randomBytes(nacl5.secretbox.nonceLength);
|
|
4420
|
+
const ciphertext = nacl5.secretbox(plaintext, nonce, shared);
|
|
4118
4421
|
if (ciphertext.length !== RECIPIENT_DELIVERY_CIPHERTEXT_LEN) {
|
|
4119
4422
|
throw new Error(
|
|
4120
4423
|
`delivery ciphertext must be ${RECIPIENT_DELIVERY_CIPHERTEXT_LEN} bytes, got ${ciphertext.length}`
|
|
@@ -4140,8 +4443,8 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
|
|
|
4140
4443
|
const ciphertext = envelope.slice(
|
|
4141
4444
|
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
|
|
4142
4445
|
);
|
|
4143
|
-
const shared =
|
|
4144
|
-
const plaintext =
|
|
4446
|
+
const shared = nacl5.box.before(ephemeralPk, viewingSecretKey);
|
|
4447
|
+
const plaintext = nacl5.secretbox.open(ciphertext, nonce, shared);
|
|
4145
4448
|
if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
|
|
4146
4449
|
return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
|
|
4147
4450
|
} catch {
|
|
@@ -4199,7 +4502,7 @@ function parseDeliveryCarrierMemo(data) {
|
|
|
4199
4502
|
|
|
4200
4503
|
// src/notes/swap-refund.ts
|
|
4201
4504
|
import { blake3 as blake33 } from "@noble/hashes/blake3";
|
|
4202
|
-
import { PublicKey as
|
|
4505
|
+
import { PublicKey as PublicKey9 } from "@solana/web3.js";
|
|
4203
4506
|
import _bs582 from "bs58";
|
|
4204
4507
|
var bs582 = _bs582.default || _bs582;
|
|
4205
4508
|
var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
|
|
@@ -4344,7 +4647,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
|
4344
4647
|
const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
|
|
4345
4648
|
const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
|
|
4346
4649
|
const programIdBase58 = programId.toBase58();
|
|
4347
|
-
const [pool] =
|
|
4650
|
+
const [pool] = PublicKey9.findProgramAddressSync(
|
|
4348
4651
|
[Buffer.from("pool"), poolMint.toBuffer()],
|
|
4349
4652
|
programId
|
|
4350
4653
|
);
|
|
@@ -4378,7 +4681,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
|
4378
4681
|
try {
|
|
4379
4682
|
return await connection.getTransaction(signature, {
|
|
4380
4683
|
commitment: "confirmed",
|
|
4381
|
-
maxSupportedTransactionVersion:
|
|
4684
|
+
maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
|
|
4382
4685
|
});
|
|
4383
4686
|
} catch {
|
|
4384
4687
|
return null;
|
|
@@ -4395,7 +4698,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
|
4395
4698
|
if (data[0] !== TRANSACT_SWAP_TAG2 || data.length < MIN_TRANSACT_SWAP_LEN) continue;
|
|
4396
4699
|
const nullifier = data.slice(NULLIFIER_0_OFFSET, NULLIFIER_0_OFFSET + 32);
|
|
4397
4700
|
if (nullifier.length !== 32) continue;
|
|
4398
|
-
const [swapState] =
|
|
4701
|
+
const [swapState] = PublicKey9.findProgramAddressSync(
|
|
4399
4702
|
[Buffer.from("swap_state"), pool.toBuffer(), Buffer.from(nullifier)],
|
|
4400
4703
|
programId
|
|
4401
4704
|
);
|
|
@@ -4544,304 +4847,84 @@ function saltToBytes2(noteSalt) {
|
|
|
4544
4847
|
throw new Error(`noteSalt must be a positive ${CHAIN_NOTE_SALT_BITS}-bit value`);
|
|
4545
4848
|
}
|
|
4546
4849
|
const out = new Uint8Array(32);
|
|
4547
|
-
let v = noteSalt;
|
|
4548
|
-
for (let i = 31; i >= 0; i--) {
|
|
4549
|
-
out[i] = Number(v & 0xffn);
|
|
4550
|
-
v >>= 8n;
|
|
4551
|
-
}
|
|
4552
|
-
return out;
|
|
4553
|
-
}
|
|
4554
|
-
function toFieldSecret3(bytes) {
|
|
4555
|
-
let value = 0n;
|
|
4556
|
-
for (let i = 0; i < 32; i++) value = value << 8n | BigInt(bytes[i]);
|
|
4557
|
-
const reduced = value % (BN254_MODULUS >> 4n);
|
|
4558
|
-
return reduced === 0n ? 1n : reduced;
|
|
4559
|
-
}
|
|
4560
|
-
function randomChangeNoteSalt() {
|
|
4561
|
-
const bytes = randomBytes(12);
|
|
4562
|
-
let v = 0n;
|
|
4563
|
-
for (const b of bytes) v = v << 8n | BigInt(b);
|
|
4564
|
-
return v === 0n ? 1n : v;
|
|
4565
|
-
}
|
|
4566
|
-
function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
|
|
4567
|
-
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
4568
|
-
throw new Error("viewingKeyNk must be 32 bytes");
|
|
4569
|
-
}
|
|
4570
|
-
if (!Number.isInteger(outputIndex) || outputIndex < 0 || outputIndex > MAX_OUTPUT_INDEX) {
|
|
4571
|
-
throw new Error(`outputIndex must be 0..${MAX_OUTPUT_INDEX}`);
|
|
4572
|
-
}
|
|
4573
|
-
const salt = saltToBytes2(noteSalt);
|
|
4574
|
-
const preimage = new Uint8Array(
|
|
4575
|
-
CHANGE_NOTE_DOMAIN.length + viewingKeyNk.length + salt.length + 1 + CHANGE_BLINDING_INFO.length
|
|
4576
|
-
);
|
|
4577
|
-
let off = 0;
|
|
4578
|
-
preimage.set(CHANGE_NOTE_DOMAIN, off);
|
|
4579
|
-
off += CHANGE_NOTE_DOMAIN.length;
|
|
4580
|
-
preimage.set(viewingKeyNk, off);
|
|
4581
|
-
off += viewingKeyNk.length;
|
|
4582
|
-
preimage.set(salt, off);
|
|
4583
|
-
off += salt.length;
|
|
4584
|
-
preimage[off] = outputIndex;
|
|
4585
|
-
off += 1;
|
|
4586
|
-
preimage.set(CHANGE_BLINDING_INFO, off);
|
|
4587
|
-
return toFieldSecret3(blake35(preimage));
|
|
4588
|
-
}
|
|
4589
|
-
async function createRecoverableChangeUtxo(amount, keypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
|
|
4590
|
-
if (typeof amount !== "bigint" || amount <= 0n) {
|
|
4591
|
-
throw new Error("amount must be a positive bigint");
|
|
4592
|
-
}
|
|
4593
|
-
const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
|
|
4594
|
-
const utxo = { amount, keypair, blinding, mintAddress };
|
|
4595
|
-
utxo.commitment = await computeCommitment(utxo);
|
|
4596
|
-
return { utxo, noteSalt };
|
|
4597
|
-
}
|
|
4598
|
-
function normalizeCommitment2(value) {
|
|
4599
|
-
if (typeof value === "bigint") return value;
|
|
4600
|
-
if (typeof value !== "string") return null;
|
|
4601
|
-
const clean = value.startsWith("0x") ? value.slice(2) : value;
|
|
4602
|
-
if (!/^[0-9a-fA-F]{1,64}$/.test(clean)) return null;
|
|
4603
|
-
return BigInt("0x" + clean);
|
|
4604
|
-
}
|
|
4605
|
-
async function matchChangeNote(params) {
|
|
4606
|
-
const { viewingKeyNk, noteSalt, amount, keypair, mintAddress, outputIndex, outputCommitments } = params;
|
|
4607
|
-
if (typeof amount !== "bigint" || amount <= 0n) return null;
|
|
4608
|
-
if (!keypair || typeof keypair.publicKey !== "bigint" || keypair.publicKey === 0n) return null;
|
|
4609
|
-
let blinding;
|
|
4610
|
-
try {
|
|
4611
|
-
blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
|
|
4612
|
-
} catch {
|
|
4613
|
-
return null;
|
|
4614
|
-
}
|
|
4615
|
-
const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
|
|
4616
|
-
const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
|
|
4617
|
-
if (!published.some((value) => value === candidate)) return null;
|
|
4618
|
-
return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt };
|
|
4619
|
-
}
|
|
4620
|
-
|
|
4621
|
-
// src/flows/transact.ts
|
|
4622
|
-
import { buildPoseidon as buildPoseidon2 } from "circomlibjs";
|
|
4623
|
-
import nacl6 from "tweetnacl";
|
|
4624
|
-
|
|
4625
|
-
// src/relay/payload.ts
|
|
4626
|
-
import { sha256 as sha2563 } from "@noble/hashes/sha2";
|
|
4627
|
-
import { bytesToHex as bytesToHex3 } from "@noble/hashes/utils";
|
|
4628
|
-
import nacl5 from "tweetnacl";
|
|
4629
|
-
var REQUEST_AUTH_DOMAIN = "CLOAK_RELAY_REQUEST_AUTH_V1";
|
|
4630
|
-
var REQUEST_AUTH_MAX_AGE_SECONDS = 300;
|
|
4631
|
-
var REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS = 30;
|
|
4632
|
-
var RELAY_AUTH_APPROVAL_MARGIN_SECONDS = 15;
|
|
4633
|
-
function sha256Hex(text) {
|
|
4634
|
-
return bytesToHex3(sha2563(new TextEncoder().encode(text)));
|
|
4635
|
-
}
|
|
4636
|
-
function randomNonceUuid() {
|
|
4637
|
-
const webCrypto = globalThis?.crypto;
|
|
4638
|
-
if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
|
|
4639
|
-
const proc = globalThis?.process;
|
|
4640
|
-
const nodeCrypto = typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule("node:crypto") : void 0;
|
|
4641
|
-
if (typeof nodeCrypto?.randomUUID === "function") return nodeCrypto.randomUUID();
|
|
4642
|
-
const bytes = randomBytes(16);
|
|
4643
|
-
bytes[6] = bytes[6] & 15 | 64;
|
|
4644
|
-
bytes[8] = bytes[8] & 63 | 128;
|
|
4645
|
-
const hex = bytesToHex3(bytes);
|
|
4646
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
|
4647
|
-
}
|
|
4648
|
-
var TRANSACT_AUTH_FIELDS = [
|
|
4649
|
-
"encrypted_notes",
|
|
4650
|
-
"max_fee",
|
|
4651
|
-
"mint",
|
|
4652
|
-
"proof_bytes",
|
|
4653
|
-
"public_inputs",
|
|
4654
|
-
"recipient",
|
|
4655
|
-
"recipient_delivery_notes",
|
|
4656
|
-
"risk_quote",
|
|
4657
|
-
"sender"
|
|
4658
|
-
];
|
|
4659
|
-
var TRANSACT_SWAP_AUTH_FIELDS = [
|
|
4660
|
-
"close_timed_out",
|
|
4661
|
-
"dexes",
|
|
4662
|
-
"encrypted_notes",
|
|
4663
|
-
"exclude_dexes",
|
|
4664
|
-
"max_fee",
|
|
4665
|
-
"min_output_amount",
|
|
4666
|
-
"output_mint",
|
|
4667
|
-
"proof_bytes",
|
|
4668
|
-
"public_inputs",
|
|
4669
|
-
"recipient",
|
|
4670
|
-
"recipient_ata",
|
|
4671
|
-
"refund_blinding",
|
|
4672
|
-
"refund_pubkey",
|
|
4673
|
-
"retry_request_id",
|
|
4674
|
-
"risk_quote",
|
|
4675
|
-
"route_retry_attempts",
|
|
4676
|
-
"sender",
|
|
4677
|
-
"slippage_bps",
|
|
4678
|
-
"swap_max_retries"
|
|
4679
|
-
];
|
|
4680
|
-
var UTF8 = new TextEncoder();
|
|
4681
|
-
function compareKeysBytewise(a, b) {
|
|
4682
|
-
if (a === b) return 0;
|
|
4683
|
-
const ab = UTF8.encode(a);
|
|
4684
|
-
const bb = UTF8.encode(b);
|
|
4685
|
-
const shared = Math.min(ab.length, bb.length);
|
|
4686
|
-
for (let i = 0; i < shared; i++) {
|
|
4687
|
-
if (ab[i] !== bb[i]) return ab[i] - bb[i];
|
|
4688
|
-
}
|
|
4689
|
-
return ab.length - bb.length;
|
|
4690
|
-
}
|
|
4691
|
-
function canonicalJson(value) {
|
|
4692
|
-
if (value === null || value === void 0) return "null";
|
|
4693
|
-
if (typeof value === "boolean") return value ? "true" : "false";
|
|
4694
|
-
if (typeof value === "number") {
|
|
4695
|
-
if (!Number.isFinite(value) || !Number.isInteger(value) || !Number.isSafeInteger(value)) {
|
|
4696
|
-
throw new Error(
|
|
4697
|
-
`canonicalJson: refusing to sign the number ${String(value)}. The relay renders numbers with serde_json, which spells non-integer, non-finite and very large values differently from JavaScript, so the two digests would differ and the request would be rejected with an unexplained 401. Send it as a decimal string instead, which is how every amount in this schema travels.`
|
|
4698
|
-
);
|
|
4699
|
-
}
|
|
4700
|
-
return String(value);
|
|
4701
|
-
}
|
|
4702
|
-
if (typeof value === "bigint") return value.toString();
|
|
4703
|
-
if (typeof value === "string") return JSON.stringify(value);
|
|
4704
|
-
if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
|
|
4705
|
-
if (typeof value === "object") {
|
|
4706
|
-
const obj = value;
|
|
4707
|
-
const keys = Object.keys(obj).sort(compareKeysBytewise);
|
|
4708
|
-
return "{" + keys.map((k) => {
|
|
4709
|
-
const v = obj[k];
|
|
4710
|
-
if (typeof v === "function" || typeof v === "symbol") {
|
|
4711
|
-
throw new Error(
|
|
4712
|
-
`canonicalJson: the key "${k}" holds a ${typeof v}, which has no JSON representation. JSON.stringify would drop it from the wire body while it stayed in the signed view, so the relay's digest could never match this one.`
|
|
4713
|
-
);
|
|
4714
|
-
}
|
|
4715
|
-
return `${JSON.stringify(k)}:${canonicalJson(v)}`;
|
|
4716
|
-
}).join(",") + "}";
|
|
4717
|
-
}
|
|
4718
|
-
throw new Error(`canonicalJson: unsupported value of type ${typeof value}`);
|
|
4719
|
-
}
|
|
4720
|
-
var FIELDS_WITHOUT_NULL_ENCODING = {
|
|
4721
|
-
slippage_bps: "500 (`default_slippage_bps` in api/transact_swap.rs)"
|
|
4722
|
-
};
|
|
4723
|
-
function buildAuthRequest(body, sender, fields) {
|
|
4724
|
-
const out = {};
|
|
4725
|
-
for (const k of fields) {
|
|
4726
|
-
if (k === "sender") {
|
|
4727
|
-
out[k] = sender;
|
|
4728
|
-
continue;
|
|
4729
|
-
}
|
|
4730
|
-
const value = body[k];
|
|
4731
|
-
if (value === void 0 || value === null) {
|
|
4732
|
-
const relayDefault = FIELDS_WITHOUT_NULL_ENCODING[k];
|
|
4733
|
-
if (relayDefault) {
|
|
4734
|
-
throw new Error(
|
|
4735
|
-
`Relay request auth: \`${k}\` must be present in the body. It is the one field in this schema that is not optional on the relay side: when it is missing the relay signs its default, ${relayDefault}, while this request would sign null. The two digests differ and the relay answers 401 "Relay request signature does not match the exact request", which points at nothing. Set \`${k}\` explicitly, to the same value the body will carry.`
|
|
4736
|
-
);
|
|
4737
|
-
}
|
|
4738
|
-
out[k] = null;
|
|
4739
|
-
continue;
|
|
4740
|
-
}
|
|
4741
|
-
out[k] = value;
|
|
4850
|
+
let v = noteSalt;
|
|
4851
|
+
for (let i = 31; i >= 0; i--) {
|
|
4852
|
+
out[i] = Number(v & 0xffn);
|
|
4853
|
+
v >>= 8n;
|
|
4742
4854
|
}
|
|
4743
4855
|
return out;
|
|
4744
4856
|
}
|
|
4745
|
-
function
|
|
4746
|
-
|
|
4747
|
-
|
|
4748
|
-
|
|
4749
|
-
|
|
4750
|
-
${programId.toBase58()}
|
|
4751
|
-
${nonce}
|
|
4752
|
-
${issuedAt}
|
|
4753
|
-
${digest}`
|
|
4754
|
-
);
|
|
4755
|
-
}
|
|
4756
|
-
function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
|
|
4757
|
-
const senderB58 = sender.toBase58();
|
|
4758
|
-
const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
|
|
4759
|
-
const nonce = randomNonceUuid();
|
|
4760
|
-
const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
|
|
4761
|
-
const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
|
|
4762
|
-
return { sender: senderB58, auth_issued_at: issuedAt, auth_nonce: nonce, message };
|
|
4763
|
-
}
|
|
4764
|
-
function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
|
|
4765
|
-
const preimage = buildRelayAuthPreimage(
|
|
4766
|
-
endpoint,
|
|
4767
|
-
programId,
|
|
4768
|
-
body,
|
|
4769
|
-
signer.publicKey,
|
|
4770
|
-
nowSeconds,
|
|
4771
|
-
fields
|
|
4772
|
-
);
|
|
4773
|
-
const signature = nacl5.sign.detached(preimage.message, signer.secretKey);
|
|
4774
|
-
return {
|
|
4775
|
-
sender: preimage.sender,
|
|
4776
|
-
auth_issued_at: preimage.auth_issued_at,
|
|
4777
|
-
auth_nonce: preimage.auth_nonce,
|
|
4778
|
-
auth_signature: Buffer.from(signature).toString("base64")
|
|
4779
|
-
};
|
|
4857
|
+
function toFieldSecret3(bytes) {
|
|
4858
|
+
let value = 0n;
|
|
4859
|
+
for (let i = 0; i < 32; i++) value = value << 8n | BigInt(bytes[i]);
|
|
4860
|
+
const reduced = value % (BN254_MODULUS >> 4n);
|
|
4861
|
+
return reduced === 0n ? 1n : reduced;
|
|
4780
4862
|
}
|
|
4781
|
-
function
|
|
4782
|
-
const
|
|
4783
|
-
|
|
4784
|
-
|
|
4785
|
-
|
|
4786
|
-
`The wallet approval took ${Math.round(elapsedSeconds)} seconds, and Cloak requests stay valid for ${REQUEST_AUTH_MAX_AGE_SECONDS} seconds from the moment they are signed (${RELAY_AUTH_APPROVAL_MARGIN_SECONDS} of those are held back for the request to reach the network). The timestamp is inside the signature, so it cannot be refreshed without your approval again. NOTHING WAS SUBMITTED and no funds moved. Start the same operation again and approve the prompt when it appears.`
|
|
4787
|
-
);
|
|
4863
|
+
function randomChangeNoteSalt() {
|
|
4864
|
+
const bytes = randomBytes(12);
|
|
4865
|
+
let v = 0n;
|
|
4866
|
+
for (const b of bytes) v = v << 8n | BigInt(b);
|
|
4867
|
+
return v === 0n ? 1n : v;
|
|
4788
4868
|
}
|
|
4789
|
-
function
|
|
4790
|
-
|
|
4791
|
-
|
|
4792
|
-
if (has("issued too far in the future")) {
|
|
4793
|
-
return `This computer's clock is more than ${REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS} seconds ahead of the network's, so the request looks like it was signed in the future and is refused before anything else happens. Turn on automatic date and time (or resynchronise the clock) and try again. Nothing was submitted.`;
|
|
4794
|
-
}
|
|
4795
|
-
if (has("signature expired")) {
|
|
4796
|
-
return `The request was signed more than ${REQUEST_AUTH_MAX_AGE_SECONDS} seconds before it arrived, usually because a wallet approval was left waiting, or because this computer's clock is running behind. The signed timestamp cannot be refreshed on its own. Start the operation again. Nothing was submitted.`;
|
|
4797
|
-
}
|
|
4798
|
-
if (has("does not match the exact request")) {
|
|
4799
|
-
return `The request body changed after it was signed, so the relay's digest and this one disagree. Sign the exact body that is POSTed, and re-POST a retry byte for byte rather than rebuilding it. If this is a hand-built swap call, check that every field in TRANSACT_SWAP_AUTH_FIELDS is present, including \`slippage_bps\`.`;
|
|
4800
|
-
}
|
|
4801
|
-
if (has("has no registered viewing key")) {
|
|
4802
|
-
return `The signature was accepted, so this is not a signing problem: the wallet that signed has no viewing key registered with Cloak yet. Register one first, or let the SDK do it by leaving \`enforceViewingKeyRegistration\` on and supplying the viewing key.`;
|
|
4803
|
-
}
|
|
4804
|
-
if (has("Authenticated sender is required") || has("auth_issued_at is required") || has("auth_nonce is required") || has("auth_signature is required")) {
|
|
4805
|
-
return `The request reached the relay without its authentication fields. Pass \`depositorKeypair\`, or \`signMessage\` together with \`walletPublicKey\`, so the request can be signed.`;
|
|
4806
|
-
}
|
|
4807
|
-
if (has("auth_nonce must be a canonical UUID")) {
|
|
4808
|
-
return `\`auth_nonce\` must be a canonical lowercase UUID. Reuse the one from the preimage.`;
|
|
4869
|
+
function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
|
|
4870
|
+
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
4871
|
+
throw new Error("viewingKeyNk must be 32 bytes");
|
|
4809
4872
|
}
|
|
4810
|
-
if (
|
|
4811
|
-
|
|
4873
|
+
if (!Number.isInteger(outputIndex) || outputIndex < 0 || outputIndex > MAX_OUTPUT_INDEX) {
|
|
4874
|
+
throw new Error(`outputIndex must be 0..${MAX_OUTPUT_INDEX}`);
|
|
4812
4875
|
}
|
|
4813
|
-
|
|
4876
|
+
const salt = saltToBytes2(noteSalt);
|
|
4877
|
+
const preimage = new Uint8Array(
|
|
4878
|
+
CHANGE_NOTE_DOMAIN.length + viewingKeyNk.length + salt.length + 1 + CHANGE_BLINDING_INFO.length
|
|
4879
|
+
);
|
|
4880
|
+
let off = 0;
|
|
4881
|
+
preimage.set(CHANGE_NOTE_DOMAIN, off);
|
|
4882
|
+
off += CHANGE_NOTE_DOMAIN.length;
|
|
4883
|
+
preimage.set(viewingKeyNk, off);
|
|
4884
|
+
off += viewingKeyNk.length;
|
|
4885
|
+
preimage.set(salt, off);
|
|
4886
|
+
off += salt.length;
|
|
4887
|
+
preimage[off] = outputIndex;
|
|
4888
|
+
off += 1;
|
|
4889
|
+
preimage.set(CHANGE_BLINDING_INFO, off);
|
|
4890
|
+
return toFieldSecret3(blake35(preimage));
|
|
4814
4891
|
}
|
|
4815
|
-
async function
|
|
4816
|
-
if (
|
|
4817
|
-
|
|
4892
|
+
async function createRecoverableChangeUtxo(amount, keypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
|
|
4893
|
+
if (typeof amount !== "bigint" || amount <= 0n) {
|
|
4894
|
+
throw new Error("amount must be a positive bigint");
|
|
4818
4895
|
}
|
|
4819
|
-
const
|
|
4820
|
-
|
|
4821
|
-
|
|
4822
|
-
|
|
4823
|
-
|
|
4824
|
-
|
|
4825
|
-
|
|
4826
|
-
|
|
4827
|
-
|
|
4828
|
-
);
|
|
4829
|
-
|
|
4830
|
-
|
|
4831
|
-
|
|
4832
|
-
|
|
4833
|
-
|
|
4834
|
-
|
|
4835
|
-
|
|
4896
|
+
const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
|
|
4897
|
+
const utxo = { amount, keypair, blinding, mintAddress };
|
|
4898
|
+
utxo.commitment = await computeCommitment(utxo);
|
|
4899
|
+
return { utxo, noteSalt };
|
|
4900
|
+
}
|
|
4901
|
+
function normalizeCommitment2(value) {
|
|
4902
|
+
if (typeof value === "bigint") return value;
|
|
4903
|
+
if (typeof value !== "string") return null;
|
|
4904
|
+
const clean = value.startsWith("0x") ? value.slice(2) : value;
|
|
4905
|
+
if (!/^[0-9a-fA-F]{1,64}$/.test(clean)) return null;
|
|
4906
|
+
return BigInt("0x" + clean);
|
|
4907
|
+
}
|
|
4908
|
+
async function matchChangeNote(params) {
|
|
4909
|
+
const { viewingKeyNk, noteSalt, amount, keypair, mintAddress, outputIndex, outputCommitments } = params;
|
|
4910
|
+
if (typeof amount !== "bigint" || amount <= 0n) return null;
|
|
4911
|
+
if (!keypair || typeof keypair.publicKey !== "bigint" || keypair.publicKey === 0n) return null;
|
|
4912
|
+
let blinding;
|
|
4913
|
+
try {
|
|
4914
|
+
blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
|
|
4915
|
+
} catch {
|
|
4916
|
+
return null;
|
|
4836
4917
|
}
|
|
4837
|
-
|
|
4838
|
-
|
|
4839
|
-
|
|
4840
|
-
|
|
4841
|
-
auth_signature: Buffer.from(signature).toString("base64")
|
|
4842
|
-
};
|
|
4918
|
+
const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
|
|
4919
|
+
const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
|
|
4920
|
+
if (!published.some((value) => value === candidate)) return null;
|
|
4921
|
+
return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt };
|
|
4843
4922
|
}
|
|
4844
4923
|
|
|
4924
|
+
// src/flows/transact.ts
|
|
4925
|
+
import { buildPoseidon as buildPoseidon2 } from "circomlibjs";
|
|
4926
|
+
import nacl6 from "tweetnacl";
|
|
4927
|
+
|
|
4845
4928
|
// src/proving/artifacts.ts
|
|
4846
4929
|
import { sha256 as sha2564 } from "@noble/hashes/sha2";
|
|
4847
4930
|
|
|
@@ -5117,6 +5200,7 @@ async function resolveTransactionCircuitFiles() {
|
|
|
5117
5200
|
}
|
|
5118
5201
|
var _transactPaddingSaltCounter = 0;
|
|
5119
5202
|
var _registeredViewingKeys = /* @__PURE__ */ new Set();
|
|
5203
|
+
var _viewingKeyRegistrationsInFlight = /* @__PURE__ */ new Map();
|
|
5120
5204
|
var _resolvedAltAccountsCache = /* @__PURE__ */ new Map();
|
|
5121
5205
|
var _relayMerkleDisabledMints = /* @__PURE__ */ new Set();
|
|
5122
5206
|
var _relayMerkleFallbackNotifiedMints = /* @__PURE__ */ new Set();
|
|
@@ -5241,7 +5325,7 @@ async function fetchSupplementalAltFromRelay(relayUrl, params) {
|
|
|
5241
5325
|
throw new Error("Supplemental ALT response is missing a 'table' address");
|
|
5242
5326
|
}
|
|
5243
5327
|
try {
|
|
5244
|
-
return new
|
|
5328
|
+
return new PublicKey10(table);
|
|
5245
5329
|
} catch {
|
|
5246
5330
|
throw new Error(`Supplemental ALT response 'table' is not a valid public key: ${table}`);
|
|
5247
5331
|
}
|
|
@@ -5309,7 +5393,7 @@ async function resolveAddressLookupTableAccounts(connection, relayUrl, altAddres
|
|
|
5309
5393
|
const fetched = await Promise.all(
|
|
5310
5394
|
altAddresses.map(async (addr) => {
|
|
5311
5395
|
try {
|
|
5312
|
-
const pubkey = new
|
|
5396
|
+
const pubkey = new PublicKey10(addr);
|
|
5313
5397
|
const result = await connection.getAddressLookupTable(pubkey);
|
|
5314
5398
|
return result.value ?? null;
|
|
5315
5399
|
} catch {
|
|
@@ -5399,7 +5483,7 @@ function calculateConfiguredProtocolFee(amount, config) {
|
|
|
5399
5483
|
return total;
|
|
5400
5484
|
}
|
|
5401
5485
|
async function readLiveProtocolFee(connection, programId, mint, amount, requireSwapOpen = false) {
|
|
5402
|
-
const [poolConfigPda] =
|
|
5486
|
+
const [poolConfigPda] = PublicKey10.findProgramAddressSync(
|
|
5403
5487
|
[Buffer.from("pool_config"), mint.toBuffer()],
|
|
5404
5488
|
programId
|
|
5405
5489
|
);
|
|
@@ -5521,6 +5605,26 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
|
|
|
5521
5605
|
if (_registeredViewingKeys.has(cacheKey)) {
|
|
5522
5606
|
return;
|
|
5523
5607
|
}
|
|
5608
|
+
const inFlight = _viewingKeyRegistrationsInFlight.get(cacheKey);
|
|
5609
|
+
if (inFlight) {
|
|
5610
|
+
return inFlight;
|
|
5611
|
+
}
|
|
5612
|
+
const registration = registerViewingKeyOnce(
|
|
5613
|
+
relayUrl,
|
|
5614
|
+
userPubkey,
|
|
5615
|
+
viewingKeyHex,
|
|
5616
|
+
cacheKey,
|
|
5617
|
+
options,
|
|
5618
|
+
onProgress
|
|
5619
|
+
);
|
|
5620
|
+
_viewingKeyRegistrationsInFlight.set(cacheKey, registration);
|
|
5621
|
+
try {
|
|
5622
|
+
await registration;
|
|
5623
|
+
} finally {
|
|
5624
|
+
_viewingKeyRegistrationsInFlight.delete(cacheKey);
|
|
5625
|
+
}
|
|
5626
|
+
}
|
|
5627
|
+
async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cacheKey, options, onProgress) {
|
|
5524
5628
|
const challengeResponse = await relayFetch(`${relayUrl}/viewing-key/challenge`, {
|
|
5525
5629
|
method: "POST",
|
|
5526
5630
|
headers: { "Content-Type": "application/json" },
|
|
@@ -5541,17 +5645,27 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
|
|
|
5541
5645
|
viewingKeyHex
|
|
5542
5646
|
);
|
|
5543
5647
|
let signatureBase64;
|
|
5648
|
+
let authMode = "message";
|
|
5649
|
+
const messageBytes = new TextEncoder().encode(challenge.message);
|
|
5544
5650
|
if (options.signMessage) {
|
|
5545
|
-
const messageBytes = new TextEncoder().encode(challenge.message);
|
|
5546
5651
|
const sig = await options.signMessage(messageBytes);
|
|
5547
5652
|
signatureBase64 = Buffer.from(sig).toString("base64");
|
|
5548
5653
|
} else if (options.depositorKeypair) {
|
|
5549
|
-
const messageBytes = new TextEncoder().encode(challenge.message);
|
|
5550
5654
|
const sig = nacl6.sign.detached(messageBytes, options.depositorKeypair.secretKey);
|
|
5551
5655
|
signatureBase64 = Buffer.from(sig).toString("base64");
|
|
5656
|
+
} else if (options.signAuthTransaction) {
|
|
5657
|
+
onProgress?.(
|
|
5658
|
+
"Approve the viewing-key registration in your wallet. It shows as a 0 SOL transfer to yourself and is never sent to the network."
|
|
5659
|
+
);
|
|
5660
|
+
const signed = await signRelayAuthPayload(
|
|
5661
|
+
{ walletPublicKey: userPubkey, signAuthTransaction: options.signAuthTransaction },
|
|
5662
|
+
messageBytes
|
|
5663
|
+
);
|
|
5664
|
+
signatureBase64 = Buffer.from(signed.signature).toString("base64");
|
|
5665
|
+
authMode = signed.mode;
|
|
5552
5666
|
} else {
|
|
5553
5667
|
throw new Error(
|
|
5554
|
-
"Viewing key registration is mandatory: signMessage (wallet) or depositorKeypair is required."
|
|
5668
|
+
"Viewing key registration is mandatory: signMessage or signAuthTransaction (wallet) or depositorKeypair is required."
|
|
5555
5669
|
);
|
|
5556
5670
|
}
|
|
5557
5671
|
onProgress?.("Registering viewing key...");
|
|
@@ -5562,7 +5676,8 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
|
|
|
5562
5676
|
user_pubkey: userPubkey.toBase58(),
|
|
5563
5677
|
viewing_key: viewingKeyHex,
|
|
5564
5678
|
nonce: challenge.nonce,
|
|
5565
|
-
signature: signatureBase64
|
|
5679
|
+
signature: signatureBase64,
|
|
5680
|
+
...authMode === "transaction" ? { auth_mode: authMode } : {}
|
|
5566
5681
|
})
|
|
5567
5682
|
});
|
|
5568
5683
|
if (!response.ok) {
|
|
@@ -5656,7 +5771,7 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
|
|
|
5656
5771
|
var TRANSACT_DISCRIMINATOR = 0;
|
|
5657
5772
|
var RANGE_QUOTE_TAG_DEPOSIT = 1;
|
|
5658
5773
|
function deriveRiskNoncePDA(programId, nonce) {
|
|
5659
|
-
return
|
|
5774
|
+
return PublicKey10.findProgramAddressSync(
|
|
5660
5775
|
[Buffer.from("risk_nonce"), Buffer.from(nonce)],
|
|
5661
5776
|
programId
|
|
5662
5777
|
);
|
|
@@ -5675,7 +5790,7 @@ function extractDepositNonceFromEd25519Ix(ix) {
|
|
|
5675
5790
|
}
|
|
5676
5791
|
}
|
|
5677
5792
|
function deriveNullifierPDA(programId, poolPDA, nullifier) {
|
|
5678
|
-
return
|
|
5793
|
+
return PublicKey10.findProgramAddressSync(
|
|
5679
5794
|
[Buffer.from("nullifier"), poolPDA.toBuffer(), Buffer.from(nullifier)],
|
|
5680
5795
|
programId
|
|
5681
5796
|
);
|
|
@@ -5708,7 +5823,7 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
|
|
|
5708
5823
|
}
|
|
5709
5824
|
if (!isDepositData) {
|
|
5710
5825
|
data[offset++] = 3;
|
|
5711
|
-
data.set((relayer ??
|
|
5826
|
+
data.set((relayer ?? PublicKey10.default).toBytes(), offset);
|
|
5712
5827
|
offset += 32;
|
|
5713
5828
|
writeBigUInt64LE(data, relayerFee ?? BigInt(0), offset);
|
|
5714
5829
|
offset += 8;
|
|
@@ -5738,7 +5853,7 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
|
|
|
5738
5853
|
// 4. nullifier PDA 0 (writable)
|
|
5739
5854
|
{ pubkey: nullifierPDA1, isSigner: false, isWritable: true },
|
|
5740
5855
|
// 5. nullifier PDA 1 (writable)
|
|
5741
|
-
{ pubkey:
|
|
5856
|
+
{ pubkey: SystemProgram3.programId, isSigner: false, isWritable: false }
|
|
5742
5857
|
// 6. system_program
|
|
5743
5858
|
];
|
|
5744
5859
|
if (splAccounts) {
|
|
@@ -5783,7 +5898,7 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
|
|
|
5783
5898
|
var PACKET_LIMIT_BYTES = 1232;
|
|
5784
5899
|
function getCommonALTAddresses() {
|
|
5785
5900
|
return [
|
|
5786
|
-
|
|
5901
|
+
SystemProgram3.programId,
|
|
5787
5902
|
SYSVAR_SLOT_HASHES_PUBKEY,
|
|
5788
5903
|
SYSVAR_INSTRUCTIONS_PUBKEY,
|
|
5789
5904
|
ComputeBudgetProgram.programId
|
|
@@ -5861,7 +5976,7 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
|
|
|
5861
5976
|
allowSupplementalAlt
|
|
5862
5977
|
);
|
|
5863
5978
|
} else {
|
|
5864
|
-
const tx = new
|
|
5979
|
+
const tx = new Transaction3().add(createIx).add(extendIx);
|
|
5865
5980
|
const { blockhash } = await connection.getLatestBlockhash();
|
|
5866
5981
|
tx.recentBlockhash = blockhash;
|
|
5867
5982
|
tx.feePayer = depositor.publicKey;
|
|
@@ -6522,7 +6637,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
6522
6637
|
let legacyTransportAttempt = 0;
|
|
6523
6638
|
while (true) {
|
|
6524
6639
|
try {
|
|
6525
|
-
const tx = new
|
|
6640
|
+
const tx = new Transaction3();
|
|
6526
6641
|
for (const ix of instructions) {
|
|
6527
6642
|
tx.add(ix);
|
|
6528
6643
|
}
|
|
@@ -6746,7 +6861,7 @@ async function fetchRiskQuote(riskQuoteUrl, wallet, options) {
|
|
|
6746
6861
|
const messageArr = hexToBytes2(messageHex);
|
|
6747
6862
|
let signerPubkey;
|
|
6748
6863
|
try {
|
|
6749
|
-
signerPubkey = new
|
|
6864
|
+
signerPubkey = new PublicKey10(signerB58);
|
|
6750
6865
|
} catch {
|
|
6751
6866
|
throw new Error("Invalid risk quote response: signer_pubkey is not a public key");
|
|
6752
6867
|
}
|
|
@@ -6847,18 +6962,22 @@ function planRelayAuth(options) {
|
|
|
6847
6962
|
const walletPublicKey = resolveUserWallet(options);
|
|
6848
6963
|
if (options.depositorKeypair) return { kind: "keypair" };
|
|
6849
6964
|
const signMessage = options.signMessage;
|
|
6965
|
+
const signAuthTransaction = options.signAuthTransaction;
|
|
6850
6966
|
if (walletPublicKey && signMessage) return { kind: "wallet", signer: { walletPublicKey, signMessage } };
|
|
6851
|
-
if (
|
|
6967
|
+
if (walletPublicKey && signAuthTransaction) {
|
|
6968
|
+
return { kind: "wallet", signer: { walletPublicKey, signAuthTransaction } };
|
|
6969
|
+
}
|
|
6970
|
+
if (!walletPublicKey && !signMessage && !signAuthTransaction) return { kind: "none" };
|
|
6852
6971
|
return {
|
|
6853
6972
|
kind: "incomplete",
|
|
6854
|
-
detail: signMessage ? "
|
|
6973
|
+
detail: signMessage || signAuthTransaction ? "a signer was provided but no wallet public key, so the request has no sender to authenticate as. Add `walletPublicKey` (or `depositorPublicKey`)." : "a wallet public key was provided but no `signMessage` and no `signAuthTransaction`, so nothing can sign. Add `signMessage` from the wallet adapter, or `signAuthTransaction` (its `signTransaction`) for a wallet that cannot sign messages."
|
|
6855
6974
|
};
|
|
6856
6975
|
}
|
|
6857
6976
|
function assertRelayAuthAvailable(plan, flow) {
|
|
6858
6977
|
if (plan.kind === "keypair" || plan.kind === "wallet") return;
|
|
6859
6978
|
const cause = plan.kind === "none" ? "no signer was provided." : `the signer provided cannot produce one: ${plan.detail}`;
|
|
6860
6979
|
throw new Error(
|
|
6861
|
-
`Cloak ${flow} requires an authenticated sender, and ${cause} Pass either \`depositorKeypair\` (a local Keypair) or \`signMessage\`
|
|
6980
|
+
`Cloak ${flow} requires an authenticated sender, and ${cause} Pass either \`depositorKeypair\` (a local Keypair), or \`signMessage\` (a browser wallet adapter) or \`signAuthTransaction\` (a hardware wallet that cannot sign messages) together with \`walletPublicKey\`. The sender must be the end user's own wallet. Checked up front, so nothing has been computed or submitted yet.`
|
|
6862
6981
|
);
|
|
6863
6982
|
}
|
|
6864
6983
|
async function submitTransactToRelay(args) {
|
|
@@ -6876,12 +6995,12 @@ async function submitTransactToRelay(args) {
|
|
|
6876
6995
|
const doFetch = args.fetchImpl ?? fetch;
|
|
6877
6996
|
const maxNetworkRetries = args.maxNetworkRetries ?? relayNetworkRetries();
|
|
6878
6997
|
const requestTimeoutMs = args.requestTimeoutMs ?? relayRequestTimeoutMs();
|
|
6879
|
-
if (!depositorKeypair && args.relayAuthSigner) {
|
|
6998
|
+
if (!depositorKeypair && args.relayAuthSigner && !args.relayAuthBatch) {
|
|
6880
6999
|
onProgress?.(
|
|
6881
7000
|
"Approve the request in your wallet. This signs the request for the relay, not a transaction, and it must be approved within a few minutes to stay valid."
|
|
6882
7001
|
);
|
|
6883
7002
|
}
|
|
6884
|
-
const authFields = await buildRelayAuthFields("/transact", programId, requestBody, {
|
|
7003
|
+
const authFields = args.relayAuthBatch ? await args.relayAuthBatch.authorize("/transact", programId, requestBody, TRANSACT_AUTH_FIELDS) : await buildRelayAuthFields("/transact", programId, requestBody, {
|
|
6885
7004
|
depositorKeypair,
|
|
6886
7005
|
relayAuthSigner: args.relayAuthSigner
|
|
6887
7006
|
});
|
|
@@ -7334,6 +7453,29 @@ async function transact(params, options) {
|
|
|
7334
7453
|
"Merkle tree unavailable from relay/indexer; using on-chain proof fallback (may require retries under high churn)"
|
|
7335
7454
|
);
|
|
7336
7455
|
}
|
|
7456
|
+
if (needsTreeForProof && treeState) {
|
|
7457
|
+
const tip = treeState.nextIndex;
|
|
7458
|
+
const unprovable = paddedInputs.filter((utxo) => {
|
|
7459
|
+
if (utxo.amount === BigInt(0) || utxo.index === void 0 || utxo.index < 0) return false;
|
|
7460
|
+
if (merkleTree && utxo.index < merkleTree.length) return false;
|
|
7461
|
+
if (utxo.index >= tip) return false;
|
|
7462
|
+
const canFillLevel0 = useSiblingInfo && (!!utxo.siblingCommitment || !!utxo.leftSiblingCommitment);
|
|
7463
|
+
return nearTipProofUndecidableLevels(utxo.index, tip).some((level) => level !== 0 || !canFillLevel0);
|
|
7464
|
+
});
|
|
7465
|
+
if (unprovable.length > 0) {
|
|
7466
|
+
onProgress?.(
|
|
7467
|
+
`On-chain frontier can no longer prove leaf ${unprovable.map((u) => u.index).join(", ")} (a later leaf overwrote a frontier level on its path); rebuilding the full tree from chain...`
|
|
7468
|
+
);
|
|
7469
|
+
forceChainIndexing = true;
|
|
7470
|
+
try {
|
|
7471
|
+
merkleTree = await buildMerkleTreeFromChain(connection, programId, pdas.merkleTree, onProgress, mint);
|
|
7472
|
+
} catch (e) {
|
|
7473
|
+
onProgress?.(
|
|
7474
|
+
`Failed to rebuild the tree from chain (${e instanceof Error ? e.message : String(e)}); continuing with the on-chain proof fallback.`
|
|
7475
|
+
);
|
|
7476
|
+
}
|
|
7477
|
+
}
|
|
7478
|
+
}
|
|
7337
7479
|
const merkleProofs = [];
|
|
7338
7480
|
let resolvedRootHex = treeState?.root ?? "0";
|
|
7339
7481
|
let proofRootHex = null;
|
|
@@ -7638,11 +7780,14 @@ async function transact(params, options) {
|
|
|
7638
7780
|
}
|
|
7639
7781
|
let proof;
|
|
7640
7782
|
let publicSignals;
|
|
7783
|
+
const releaseProofSlot = options.relayAuthBatch ? await options.relayAuthBatch.proofSlot() : void 0;
|
|
7641
7784
|
try {
|
|
7642
7785
|
const result = await generateTransactionProof(circuitInputs, onProofProgress);
|
|
7643
7786
|
proof = result.proof;
|
|
7644
7787
|
publicSignals = result.publicSignals;
|
|
7788
|
+
releaseProofSlot?.();
|
|
7645
7789
|
} catch (proofError) {
|
|
7790
|
+
releaseProofSlot?.();
|
|
7646
7791
|
const errorMsg = proofError?.message || String(proofError);
|
|
7647
7792
|
if ((errorMsg.includes("ForceEqual") || errorMsg.includes("Assert Failed")) && submissionAttempts < maxRootRetries) {
|
|
7648
7793
|
onProgress?.(`Merkle proof error (stale sibling data), will regenerate with fresh tree...`);
|
|
@@ -7955,6 +8100,7 @@ async function transact(params, options) {
|
|
|
7955
8100
|
// point where they reach the relay submission instead of stopping at viewing-key
|
|
7956
8101
|
// registration. The keypair still wins when both are present.
|
|
7957
8102
|
relayAuthSigner: relayAuthPlan.kind === "wallet" ? relayAuthPlan.signer : void 0,
|
|
8103
|
+
relayAuthBatch: options.relayAuthBatch,
|
|
7958
8104
|
settlement: {
|
|
7959
8105
|
connection,
|
|
7960
8106
|
programId,
|
|
@@ -8000,7 +8146,7 @@ async function transact(params, options) {
|
|
|
8000
8146
|
"All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
|
|
8001
8147
|
);
|
|
8002
8148
|
try {
|
|
8003
|
-
const [merkleTreePda] =
|
|
8149
|
+
const [merkleTreePda] = PublicKey10.findProgramAddressSync(
|
|
8004
8150
|
[Buffer.from("merkle_tree"), mint.toBuffer()],
|
|
8005
8151
|
programId
|
|
8006
8152
|
);
|
|
@@ -8614,6 +8760,29 @@ async function swapUtxo(params, options) {
|
|
|
8614
8760
|
"Merkle tree unavailable from relay/indexer; using on-chain proof fallback (may require retries under high churn)"
|
|
8615
8761
|
);
|
|
8616
8762
|
}
|
|
8763
|
+
if (needsTreeForProof && merkleState) {
|
|
8764
|
+
const tip = merkleState.nextIndex;
|
|
8765
|
+
const unprovable = paddedInputs.filter((utxo) => {
|
|
8766
|
+
if (utxo.amount === BigInt(0) || utxo.index === void 0 || utxo.index < 0) return false;
|
|
8767
|
+
if (merkleTree && utxo.index < merkleTree.length) return false;
|
|
8768
|
+
if (utxo.index >= tip) return false;
|
|
8769
|
+
const canFillLevel0 = useSiblingInfo && (!!utxo.siblingCommitment || !!utxo.leftSiblingCommitment);
|
|
8770
|
+
return nearTipProofUndecidableLevels(utxo.index, tip).some((level) => level !== 0 || !canFillLevel0);
|
|
8771
|
+
});
|
|
8772
|
+
if (unprovable.length > 0) {
|
|
8773
|
+
onProgress?.(
|
|
8774
|
+
`On-chain frontier can no longer prove leaf ${unprovable.map((u) => u.index).join(", ")} (a later leaf overwrote a frontier level on its path); rebuilding the full tree from chain...`
|
|
8775
|
+
);
|
|
8776
|
+
forceChainIndexing = true;
|
|
8777
|
+
try {
|
|
8778
|
+
merkleTree = await buildMerkleTreeFromChain(connection, programId, pdas.merkleTree, onProgress, NATIVE_SOL_MINT);
|
|
8779
|
+
} catch (e) {
|
|
8780
|
+
onProgress?.(
|
|
8781
|
+
`Failed to rebuild the tree from chain (${e instanceof Error ? e.message : String(e)}); continuing with the on-chain proof fallback.`
|
|
8782
|
+
);
|
|
8783
|
+
}
|
|
8784
|
+
}
|
|
8785
|
+
}
|
|
8617
8786
|
const merkleProofs = [];
|
|
8618
8787
|
let resolvedRootHex = merkleState?.root ?? "0";
|
|
8619
8788
|
let proofRootHex = null;
|
|
@@ -8988,7 +9157,7 @@ async function swapUtxo(params, options) {
|
|
|
8988
9157
|
}
|
|
8989
9158
|
if (options.onSwapStatePredicted && inputNullifiers.length > 0) {
|
|
8990
9159
|
const nBytes = bigintToBytes322(inputNullifiers[0]);
|
|
8991
|
-
const [ssp] =
|
|
9160
|
+
const [ssp] = PublicKey10.findProgramAddressSync(
|
|
8992
9161
|
[Buffer.from("swap_state"), pdas.pool.toBuffer(), Buffer.from(nBytes)],
|
|
8993
9162
|
programId
|
|
8994
9163
|
);
|
|
@@ -9407,10 +9576,276 @@ function cleanupStalePendingOperations(maxAgeMs = 24 * 60 * 60 * 1e3) {
|
|
|
9407
9576
|
return { removedDeposits, removedWithdrawals };
|
|
9408
9577
|
}
|
|
9409
9578
|
|
|
9579
|
+
// src/relay/batch-auth.ts
|
|
9580
|
+
import { Keypair as Keypair4 } from "@solana/web3.js";
|
|
9581
|
+
var RelayBatchAuthCoordinator = class {
|
|
9582
|
+
constructor(options) {
|
|
9583
|
+
this.proofSlotsInUse = 0;
|
|
9584
|
+
this.proofQueue = [];
|
|
9585
|
+
this.items = [];
|
|
9586
|
+
this.signing = false;
|
|
9587
|
+
this.slotsInUse = 0;
|
|
9588
|
+
this.ready = [];
|
|
9589
|
+
this.waves = 0;
|
|
9590
|
+
if (!Number.isInteger(options.items) || options.items < 1) {
|
|
9591
|
+
throw new Error(`A batch needs at least one item (got ${options.items}).`);
|
|
9592
|
+
}
|
|
9593
|
+
if (options.items > RELAY_BATCH_AUTH_MAX_ITEMS) {
|
|
9594
|
+
throw new Error(
|
|
9595
|
+
`A batch may cover at most ${RELAY_BATCH_AUTH_MAX_ITEMS} requests (got ${options.items}); the relay refuses longer digest lists. Chunk the payout. The practical bound is lower still: each spend appends two roots to the on-chain ring of 100, so a batch proved against one root evicts it by itself before 50 items.`
|
|
9596
|
+
);
|
|
9597
|
+
}
|
|
9598
|
+
const concurrency = options.submitConcurrency ?? 3;
|
|
9599
|
+
if (!Number.isInteger(concurrency) || concurrency < 1) {
|
|
9600
|
+
throw new Error(`submitConcurrency must be a positive integer (got ${concurrency}).`);
|
|
9601
|
+
}
|
|
9602
|
+
this.signer = options.signer;
|
|
9603
|
+
this.sender = options.signer instanceof Keypair4 ? options.signer.publicKey : options.signer.walletPublicKey;
|
|
9604
|
+
this.expectedItems = options.items;
|
|
9605
|
+
this.submitConcurrency = concurrency;
|
|
9606
|
+
const proofConcurrency = options.proofConcurrency ?? 2;
|
|
9607
|
+
if (!Number.isInteger(proofConcurrency) || proofConcurrency < 1) {
|
|
9608
|
+
throw new Error(`proofConcurrency must be a positive integer (got ${proofConcurrency}).`);
|
|
9609
|
+
}
|
|
9610
|
+
this.proofConcurrency = proofConcurrency;
|
|
9611
|
+
this.onProgress = options.onProgress;
|
|
9612
|
+
}
|
|
9613
|
+
/** The wallet that signs and is every item's authenticated `sender`. */
|
|
9614
|
+
get walletPublicKey() {
|
|
9615
|
+
return this.sender;
|
|
9616
|
+
}
|
|
9617
|
+
/** How many times the signer has been asked so far: one per wave. */
|
|
9618
|
+
get approvals() {
|
|
9619
|
+
return this.waves;
|
|
9620
|
+
}
|
|
9621
|
+
/** Where every item is right now. For progress UIs and for diagnosing a batch that never signs. */
|
|
9622
|
+
snapshot() {
|
|
9623
|
+
const count = (state) => this.items.filter((i) => i.state === state).length;
|
|
9624
|
+
return {
|
|
9625
|
+
building: count("building"),
|
|
9626
|
+
waiting: count("waiting"),
|
|
9627
|
+
submitting: count("submitting"),
|
|
9628
|
+
done: count("done"),
|
|
9629
|
+
proving: this.proofSlotsInUse,
|
|
9630
|
+
proofQueue: this.proofQueue.length,
|
|
9631
|
+
registered: this.items.length,
|
|
9632
|
+
expected: this.expectedItems
|
|
9633
|
+
};
|
|
9634
|
+
}
|
|
9635
|
+
/** Register one item. Throws past `items`: the wave condition would never be reachable. */
|
|
9636
|
+
item() {
|
|
9637
|
+
if (this.items.length >= this.expectedItems) {
|
|
9638
|
+
throw new Error(
|
|
9639
|
+
`This batch was created for ${this.expectedItems} item(s) and all of them are registered.`
|
|
9640
|
+
);
|
|
9641
|
+
}
|
|
9642
|
+
const item = { state: "building", waiting: null, holdsSlot: false };
|
|
9643
|
+
this.items.push(item);
|
|
9644
|
+
return {
|
|
9645
|
+
proofSlot: () => this.acquireProofSlot(),
|
|
9646
|
+
authorize: (endpoint, programId, body, fields) => this.authorize(item, endpoint, programId, body, fields),
|
|
9647
|
+
finish: () => this.finish(item)
|
|
9648
|
+
};
|
|
9649
|
+
}
|
|
9650
|
+
acquireProofSlot() {
|
|
9651
|
+
return new Promise((resolve) => {
|
|
9652
|
+
const grant = () => {
|
|
9653
|
+
this.proofSlotsInUse += 1;
|
|
9654
|
+
let released = false;
|
|
9655
|
+
resolve(() => {
|
|
9656
|
+
if (released) return;
|
|
9657
|
+
released = true;
|
|
9658
|
+
this.proofSlotsInUse -= 1;
|
|
9659
|
+
const next = this.proofQueue.shift();
|
|
9660
|
+
if (next) next();
|
|
9661
|
+
});
|
|
9662
|
+
};
|
|
9663
|
+
if (this.proofSlotsInUse < this.proofConcurrency) grant();
|
|
9664
|
+
else this.proofQueue.push(grant);
|
|
9665
|
+
});
|
|
9666
|
+
}
|
|
9667
|
+
authorize(item, endpoint, programId, body, fields) {
|
|
9668
|
+
if (item.state === "done") {
|
|
9669
|
+
return Promise.reject(new Error("This batch item already finished; it cannot authorize."));
|
|
9670
|
+
}
|
|
9671
|
+
if (item.state === "waiting") {
|
|
9672
|
+
return Promise.reject(new Error("This batch item is already waiting for a signature."));
|
|
9673
|
+
}
|
|
9674
|
+
this.releaseSlot(item);
|
|
9675
|
+
return new Promise((resolve, reject) => {
|
|
9676
|
+
item.state = "waiting";
|
|
9677
|
+
item.waiting = { endpoint, programId, body, fields, resolve, reject };
|
|
9678
|
+
this.maybeSign();
|
|
9679
|
+
});
|
|
9680
|
+
}
|
|
9681
|
+
finish(item) {
|
|
9682
|
+
if (item.state === "done") return;
|
|
9683
|
+
if (item.state === "waiting" && item.waiting) {
|
|
9684
|
+
item.waiting.reject(new Error("Batch item finished before it was signed."));
|
|
9685
|
+
item.waiting = null;
|
|
9686
|
+
}
|
|
9687
|
+
this.releaseSlot(item);
|
|
9688
|
+
item.state = "done";
|
|
9689
|
+
this.maybeSign();
|
|
9690
|
+
this.pump();
|
|
9691
|
+
}
|
|
9692
|
+
releaseSlot(item) {
|
|
9693
|
+
if (!item.holdsSlot) return;
|
|
9694
|
+
item.holdsSlot = false;
|
|
9695
|
+
this.slotsInUse -= 1;
|
|
9696
|
+
}
|
|
9697
|
+
/** Sign when every registered item is either waiting here or finished, and nothing is building. */
|
|
9698
|
+
maybeSign() {
|
|
9699
|
+
if (this.signing) return;
|
|
9700
|
+
if (this.items.length < this.expectedItems) return;
|
|
9701
|
+
if (this.items.some((item) => item.state === "building" || item.state === "submitting")) return;
|
|
9702
|
+
const wave = this.items.filter((item) => item.state === "waiting");
|
|
9703
|
+
if (wave.length === 0) return;
|
|
9704
|
+
this.signing = true;
|
|
9705
|
+
void this.signWave(wave).finally(() => {
|
|
9706
|
+
this.signing = false;
|
|
9707
|
+
this.maybeSign();
|
|
9708
|
+
});
|
|
9709
|
+
}
|
|
9710
|
+
async signWave(wave) {
|
|
9711
|
+
const waiting = wave.map((item) => item.waiting);
|
|
9712
|
+
try {
|
|
9713
|
+
const programId = waiting[0].programId;
|
|
9714
|
+
for (const w of waiting) {
|
|
9715
|
+
if (!w.programId.equals(programId)) {
|
|
9716
|
+
throw new Error("Every item of a batch must target the same program id.");
|
|
9717
|
+
}
|
|
9718
|
+
}
|
|
9719
|
+
const nowSeconds = Math.floor(Date.now() / 1e3);
|
|
9720
|
+
const preimages = waiting.map(
|
|
9721
|
+
(w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
|
|
9722
|
+
);
|
|
9723
|
+
const digests = preimages.map(relayRequestDigestHex);
|
|
9724
|
+
const issuedAt = preimages[0].auth_issued_at;
|
|
9725
|
+
const message = buildRelayBatchAuthMessage(programId, issuedAt, digests);
|
|
9726
|
+
this.waves += 1;
|
|
9727
|
+
if (!(this.signer instanceof Keypair4)) {
|
|
9728
|
+
const asTransaction = !this.signer.signMessage;
|
|
9729
|
+
this.onProgress?.(
|
|
9730
|
+
`Approve ${waiting.length} request(s) in your wallet` + (this.waves > 1 ? ` (approval ${this.waves}, for the rows that had to re-prove)` : "") + (asTransaction ? `. Your wallet shows this as a 0 SOL transfer to yourself: it is how a wallet that cannot sign messages authorizes the requests for the relay, and it is never sent to the network. Approve it on the device within a few minutes.` : `. This signs the requests for the relay, not a transaction, and must be approved within a few minutes to stay valid.`)
|
|
9731
|
+
);
|
|
9732
|
+
}
|
|
9733
|
+
const approvalStartedMs = Date.now();
|
|
9734
|
+
const { signature, mode } = await signRelayAuthPayload(this.signer, message);
|
|
9735
|
+
if (!(this.signer instanceof Keypair4)) {
|
|
9736
|
+
assertApprovalWithinFreshnessWindow(
|
|
9737
|
+
Date.now() - approvalStartedMs,
|
|
9738
|
+
REQUEST_AUTH_BATCH_MAX_AGE_SECONDS
|
|
9739
|
+
);
|
|
9740
|
+
}
|
|
9741
|
+
const signatureB64 = Buffer.from(signature).toString("base64");
|
|
9742
|
+
wave.forEach((item, i) => {
|
|
9743
|
+
const preimage = preimages[i];
|
|
9744
|
+
this.ready.push({
|
|
9745
|
+
item,
|
|
9746
|
+
fields: {
|
|
9747
|
+
sender: preimage.sender,
|
|
9748
|
+
auth_issued_at: preimage.auth_issued_at,
|
|
9749
|
+
auth_nonce: preimage.auth_nonce,
|
|
9750
|
+
auth_signature: signatureB64,
|
|
9751
|
+
...mode === "transaction" ? { auth_mode: mode } : {},
|
|
9752
|
+
// A fresh array per item: `Object.assign` puts this on the wire body, and the body is
|
|
9753
|
+
// serialized again on every network retry.
|
|
9754
|
+
auth_batch: { digests: [...digests] }
|
|
9755
|
+
}
|
|
9756
|
+
});
|
|
9757
|
+
});
|
|
9758
|
+
this.pump();
|
|
9759
|
+
} catch (error) {
|
|
9760
|
+
for (const item of wave) {
|
|
9761
|
+
const w = item.waiting;
|
|
9762
|
+
item.waiting = null;
|
|
9763
|
+
item.state = "done";
|
|
9764
|
+
w?.reject(error);
|
|
9765
|
+
}
|
|
9766
|
+
}
|
|
9767
|
+
}
|
|
9768
|
+
/** Release signed items to submit, `submitConcurrency` at a time, in signing order. */
|
|
9769
|
+
pump() {
|
|
9770
|
+
while (this.ready.length > 0 && this.slotsInUse < this.submitConcurrency) {
|
|
9771
|
+
const next = this.ready.shift();
|
|
9772
|
+
const w = next.item.waiting;
|
|
9773
|
+
next.item.waiting = null;
|
|
9774
|
+
if (next.item.state !== "waiting" || !w) continue;
|
|
9775
|
+
next.item.state = "submitting";
|
|
9776
|
+
next.item.holdsSlot = true;
|
|
9777
|
+
this.slotsInUse += 1;
|
|
9778
|
+
w.resolve(next.fields);
|
|
9779
|
+
}
|
|
9780
|
+
}
|
|
9781
|
+
};
|
|
9782
|
+
function createRelayBatchAuthCoordinator(options) {
|
|
9783
|
+
return new RelayBatchAuthCoordinator(options);
|
|
9784
|
+
}
|
|
9785
|
+
|
|
9786
|
+
// src/flows/transact-batch.ts
|
|
9787
|
+
async function transactBatch(items, options) {
|
|
9788
|
+
if (items.length === 0) {
|
|
9789
|
+
return { results: [], approvals: 0 };
|
|
9790
|
+
}
|
|
9791
|
+
if (items.length > RELAY_BATCH_AUTH_MAX_ITEMS) {
|
|
9792
|
+
throw new Error(
|
|
9793
|
+
`transactBatch accepts at most ${RELAY_BATCH_AUTH_MAX_ITEMS} items per call (got ${items.length}). Chunk the payout; see RELAY_BATCH_AUTH_MAX_ITEMS for why the practical bound is lower.`
|
|
9794
|
+
);
|
|
9795
|
+
}
|
|
9796
|
+
if (!options.relayUrl) {
|
|
9797
|
+
throw new Error("transactBatch requires relayUrl: batch approval is a relay authentication scheme.");
|
|
9798
|
+
}
|
|
9799
|
+
const { proofConcurrency, submitConcurrency, ...shared } = options;
|
|
9800
|
+
const signer = shared.depositorKeypair ? shared.depositorKeypair : (() => {
|
|
9801
|
+
const wallet = shared.walletPublicKey ?? shared.depositorPublicKey;
|
|
9802
|
+
if (!wallet) return null;
|
|
9803
|
+
if (shared.signMessage) return { walletPublicKey: wallet, signMessage: shared.signMessage };
|
|
9804
|
+
if (shared.signAuthTransaction) {
|
|
9805
|
+
return { walletPublicKey: wallet, signAuthTransaction: shared.signAuthTransaction };
|
|
9806
|
+
}
|
|
9807
|
+
return null;
|
|
9808
|
+
})();
|
|
9809
|
+
if (!signer) {
|
|
9810
|
+
throw new Error(
|
|
9811
|
+
"transactBatch requires an authenticated sender: pass `depositorKeypair` (a local Keypair), or `walletPublicKey` with `signMessage` (a browser wallet adapter) or `signAuthTransaction` (a hardware wallet). Checked up front, so nothing has been computed or submitted yet."
|
|
9812
|
+
);
|
|
9813
|
+
}
|
|
9814
|
+
const coordinator = createRelayBatchAuthCoordinator({
|
|
9815
|
+
signer,
|
|
9816
|
+
items: items.length,
|
|
9817
|
+
proofConcurrency,
|
|
9818
|
+
submitConcurrency,
|
|
9819
|
+
onProgress: shared.onProgress
|
|
9820
|
+
});
|
|
9821
|
+
const handles = items.map(() => coordinator.item());
|
|
9822
|
+
const results = new Array(items.length);
|
|
9823
|
+
const runOne = async (index) => {
|
|
9824
|
+
const item = items[index];
|
|
9825
|
+
const handle = handles[index];
|
|
9826
|
+
const label = `[batch ${index + 1}/${items.length}]`;
|
|
9827
|
+
try {
|
|
9828
|
+
const value = await transact(item.params, {
|
|
9829
|
+
...shared,
|
|
9830
|
+
...item.options,
|
|
9831
|
+
relayAuthBatch: handle,
|
|
9832
|
+
onProgress: shared.onProgress ? (status) => shared.onProgress?.(`${label} ${status}`) : void 0
|
|
9833
|
+
});
|
|
9834
|
+
results[index] = { status: "fulfilled", value };
|
|
9835
|
+
} catch (reason) {
|
|
9836
|
+
results[index] = { status: "rejected", reason };
|
|
9837
|
+
} finally {
|
|
9838
|
+
handle.finish();
|
|
9839
|
+
}
|
|
9840
|
+
};
|
|
9841
|
+
await Promise.all(items.map((_, index) => runOne(index)));
|
|
9842
|
+
return { results, approvals: coordinator.approvals };
|
|
9843
|
+
}
|
|
9844
|
+
|
|
9410
9845
|
// src/scanning/scan.ts
|
|
9411
9846
|
import _bs583 from "bs58";
|
|
9412
9847
|
import {
|
|
9413
|
-
PublicKey as
|
|
9848
|
+
PublicKey as PublicKey12
|
|
9414
9849
|
} from "@solana/web3.js";
|
|
9415
9850
|
import { getAssociatedTokenAddressSync as getAssociatedTokenAddressSync2 } from "@solana/spl-token";
|
|
9416
9851
|
var bs583 = _bs583.default || _bs583;
|
|
@@ -9498,7 +9933,7 @@ function parseSwapOutputMint(data) {
|
|
|
9498
9933
|
const mintBytes = data.slice(SWAP_OUTPUT_MINT_OFFSET, end);
|
|
9499
9934
|
if (mintBytes.every((byte) => byte === 0)) return void 0;
|
|
9500
9935
|
try {
|
|
9501
|
-
return new
|
|
9936
|
+
return new PublicKey12(mintBytes).toBase58();
|
|
9502
9937
|
} catch {
|
|
9503
9938
|
return void 0;
|
|
9504
9939
|
}
|
|
@@ -9588,7 +10023,7 @@ function parseSwapRecipientAta(data) {
|
|
|
9588
10023
|
const recipientAtaBytes = data.slice(recipientAtaStart, recipientAtaEnd);
|
|
9589
10024
|
if (recipientAtaBytes.every((byte) => byte === 0)) return void 0;
|
|
9590
10025
|
try {
|
|
9591
|
-
return new
|
|
10026
|
+
return new PublicKey12(recipientAtaBytes).toBase58();
|
|
9592
10027
|
} catch {
|
|
9593
10028
|
return void 0;
|
|
9594
10029
|
}
|
|
@@ -9750,7 +10185,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
|
|
|
9750
10185
|
let rpcCalls = 0;
|
|
9751
10186
|
const candidates = Array.from(swapCtxByCommitment.keys());
|
|
9752
10187
|
if (candidates.length === 0) return { records, rpcCalls };
|
|
9753
|
-
const [registry] =
|
|
10188
|
+
const [registry] = PublicKey12.findProgramAddressSync(
|
|
9754
10189
|
[Buffer.from("cloak_chain_note_registry")],
|
|
9755
10190
|
programId
|
|
9756
10191
|
);
|
|
@@ -9781,7 +10216,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
|
|
|
9781
10216
|
tx = await withRpcRetry(
|
|
9782
10217
|
() => connection.getTransaction(si.signature, {
|
|
9783
10218
|
commitment: "confirmed",
|
|
9784
|
-
maxSupportedTransactionVersion:
|
|
10219
|
+
maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
|
|
9785
10220
|
})
|
|
9786
10221
|
);
|
|
9787
10222
|
} catch {
|
|
@@ -9882,7 +10317,7 @@ async function scanRecipientDeliveryNotes(opts) {
|
|
|
9882
10317
|
tx = await withRpcRetry(
|
|
9883
10318
|
() => connection.getTransaction(si.signature, {
|
|
9884
10319
|
commitment: "confirmed",
|
|
9885
|
-
maxSupportedTransactionVersion:
|
|
10320
|
+
maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
|
|
9886
10321
|
})
|
|
9887
10322
|
);
|
|
9888
10323
|
} catch {
|
|
@@ -10053,7 +10488,7 @@ async function scanTransactions(opts) {
|
|
|
10053
10488
|
return await withRpcRetry(
|
|
10054
10489
|
() => connection.getTransaction(sigInfo.signature, {
|
|
10055
10490
|
commitment: "confirmed",
|
|
10056
|
-
maxSupportedTransactionVersion:
|
|
10491
|
+
maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
|
|
10057
10492
|
})
|
|
10058
10493
|
);
|
|
10059
10494
|
} catch {
|
|
@@ -10153,8 +10588,8 @@ async function scanTransactions(opts) {
|
|
|
10153
10588
|
if (onChainAta) {
|
|
10154
10589
|
try {
|
|
10155
10590
|
const expectedAta = getAssociatedTokenAddressSync2(
|
|
10156
|
-
new
|
|
10157
|
-
new
|
|
10591
|
+
new PublicKey12(asset.mint),
|
|
10592
|
+
new PublicKey12(walletPublicKey)
|
|
10158
10593
|
).toBase58();
|
|
10159
10594
|
if (onChainAta === expectedAta) {
|
|
10160
10595
|
isOurs = true;
|
|
@@ -10368,7 +10803,7 @@ async function scanTransactions(opts) {
|
|
|
10368
10803
|
// deposit — that is the public deposit amount. A deposit that also merged inputs
|
|
10369
10804
|
// carries a larger output 0 and is not recoverable from public data alone.
|
|
10370
10805
|
amount: grossAmount,
|
|
10371
|
-
mintAddress: new
|
|
10806
|
+
mintAddress: new PublicKey12(asset.mint),
|
|
10372
10807
|
outputCommitments: ixCtx.outputCommitments ?? []
|
|
10373
10808
|
});
|
|
10374
10809
|
if (recoveredDeposit) {
|
|
@@ -10394,7 +10829,7 @@ async function scanTransactions(opts) {
|
|
|
10394
10829
|
noteSalt: compactNote.noteSalt,
|
|
10395
10830
|
amount: compactNote.outAmount0,
|
|
10396
10831
|
keypair: { privateKey: 0n, publicKey: compactNote.outPubkey0 },
|
|
10397
|
-
mintAddress: new
|
|
10832
|
+
mintAddress: new PublicKey12(asset.mint),
|
|
10398
10833
|
outputIndex: 0,
|
|
10399
10834
|
// v4 describes output 0, which is where change lands
|
|
10400
10835
|
outputCommitments: ixCtx.outputCommitments ?? []
|
|
@@ -10587,7 +11022,7 @@ function formatComplianceCsv(report) {
|
|
|
10587
11022
|
}
|
|
10588
11023
|
|
|
10589
11024
|
// src/wallet/utxo-wallet.ts
|
|
10590
|
-
import { PublicKey as
|
|
11025
|
+
import { PublicKey as PublicKey13 } from "@solana/web3.js";
|
|
10591
11026
|
var UtxoWallet = class _UtxoWallet {
|
|
10592
11027
|
constructor(viewingKey) {
|
|
10593
11028
|
this.wallets = /* @__PURE__ */ new Map();
|
|
@@ -10799,7 +11234,7 @@ var UtxoWallet = class _UtxoWallet {
|
|
|
10799
11234
|
data.viewingKey ? new Uint8Array(data.viewingKey) : void 0
|
|
10800
11235
|
);
|
|
10801
11236
|
for (const w of data.wallets) {
|
|
10802
|
-
const mint = new
|
|
11237
|
+
const mint = new PublicKey13(w.mint);
|
|
10803
11238
|
for (const u of w.utxos) {
|
|
10804
11239
|
wallet.addUtxo({
|
|
10805
11240
|
amount: BigInt(u.amount),
|
|
@@ -11092,10 +11527,10 @@ function cloakBridgeRail(relayUrl) {
|
|
|
11092
11527
|
|
|
11093
11528
|
// src/bridge/paymaster-client.ts
|
|
11094
11529
|
import {
|
|
11095
|
-
PublicKey as
|
|
11530
|
+
PublicKey as PublicKey14,
|
|
11096
11531
|
SystemInstruction,
|
|
11097
|
-
SystemProgram as
|
|
11098
|
-
Transaction as
|
|
11532
|
+
SystemProgram as SystemProgram4,
|
|
11533
|
+
Transaction as Transaction4
|
|
11099
11534
|
} from "@solana/web3.js";
|
|
11100
11535
|
import { TOKEN_PROGRAM_ID as TOKEN_PROGRAM_ID3, decodeTransferInstruction, getAssociatedTokenAddressSync as getAssociatedTokenAddressSync3 } from "@solana/spl-token";
|
|
11101
11536
|
function validatePaymasterTopUpTransaction(tx, expect) {
|
|
@@ -11106,7 +11541,7 @@ function validatePaymasterTopUpTransaction(tx, expect) {
|
|
|
11106
11541
|
);
|
|
11107
11542
|
}
|
|
11108
11543
|
const ix0 = ixs[0];
|
|
11109
|
-
if (!ix0.programId.equals(
|
|
11544
|
+
if (!ix0.programId.equals(SystemProgram4.programId)) {
|
|
11110
11545
|
throw new Error(
|
|
11111
11546
|
`paymaster top-up instruction 0 is owned by ${ix0.programId.toBase58()}, not the System Program \u2014 refusing to sign an unrecognised first instruction`
|
|
11112
11547
|
);
|
|
@@ -11190,10 +11625,10 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
11190
11625
|
"paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
|
|
11191
11626
|
);
|
|
11192
11627
|
}
|
|
11193
|
-
const feeMint = new
|
|
11194
|
-
const paymentAddress = new
|
|
11628
|
+
const feeMint = new PublicKey14(prepared.fee_mint);
|
|
11629
|
+
const paymentAddress = new PublicKey14(prepared.payment_address);
|
|
11195
11630
|
const feeTokenAmount = BigInt(prepared.fee_token_amount);
|
|
11196
|
-
const tx =
|
|
11631
|
+
const tx = Transaction4.from(Buffer.from(prepared.transaction, "base64"));
|
|
11197
11632
|
validatePaymasterTopUpTransaction(tx, {
|
|
11198
11633
|
recipient: receiver.publicKey,
|
|
11199
11634
|
maxGrantLamports: grantLamports,
|
|
@@ -11212,7 +11647,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
11212
11647
|
});
|
|
11213
11648
|
const cosigned = await parseBridgeResponse2(cosignRes, "paymaster cosign");
|
|
11214
11649
|
return {
|
|
11215
|
-
transaction:
|
|
11650
|
+
transaction: Transaction4.from(Buffer.from(cosigned.transaction, "base64")),
|
|
11216
11651
|
feeTokenAmount,
|
|
11217
11652
|
feeMint: prepared.fee_mint,
|
|
11218
11653
|
paymentAddress: prepared.payment_address
|
|
@@ -11220,7 +11655,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
11220
11655
|
}
|
|
11221
11656
|
|
|
11222
11657
|
// src/bridge/derive.ts
|
|
11223
|
-
import { Keypair as
|
|
11658
|
+
import { Keypair as Keypair6 } from "@solana/web3.js";
|
|
11224
11659
|
import { hmac } from "@noble/hashes/hmac";
|
|
11225
11660
|
import { sha512 } from "@noble/hashes/sha512";
|
|
11226
11661
|
var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
|
|
@@ -11235,7 +11670,7 @@ function deriveBridgeReceiver(nk, index) {
|
|
|
11235
11670
|
);
|
|
11236
11671
|
}
|
|
11237
11672
|
const h = hmac(sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
|
|
11238
|
-
return
|
|
11673
|
+
return Keypair6.fromSeed(h.slice(0, 32));
|
|
11239
11674
|
}
|
|
11240
11675
|
|
|
11241
11676
|
// src/bridge/discover.ts
|
|
@@ -11276,7 +11711,9 @@ async function listBridgeDeposits(conn, nk, opts) {
|
|
|
11276
11711
|
const sigs = await conn.getSignaturesForAddress(receiver, { limit: 20 });
|
|
11277
11712
|
for (const s of sigs) {
|
|
11278
11713
|
if (s.err) continue;
|
|
11279
|
-
const tx = await conn.getTransaction(s.signature, {
|
|
11714
|
+
const tx = await conn.getTransaction(s.signature, {
|
|
11715
|
+
maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
|
|
11716
|
+
});
|
|
11280
11717
|
const keys = tx?.transaction.message.getAccountKeys({
|
|
11281
11718
|
accountKeysFromLookups: tx.meta?.loadedAddresses
|
|
11282
11719
|
});
|
|
@@ -11317,21 +11754,21 @@ async function listBridgeDeposits(conn, nk, opts) {
|
|
|
11317
11754
|
|
|
11318
11755
|
// src/bridge/deposit-core.ts
|
|
11319
11756
|
import {
|
|
11320
|
-
SystemProgram as
|
|
11321
|
-
Transaction as
|
|
11757
|
+
SystemProgram as SystemProgram5,
|
|
11758
|
+
Transaction as Transaction5,
|
|
11322
11759
|
VersionedTransaction as VersionedTransaction2,
|
|
11323
11760
|
sendAndConfirmTransaction as sendAndConfirmTransaction2
|
|
11324
11761
|
} from "@solana/web3.js";
|
|
11325
11762
|
import nacl8 from "tweetnacl";
|
|
11326
11763
|
|
|
11327
11764
|
// src/bridge/funder.ts
|
|
11328
|
-
import { PublicKey as
|
|
11765
|
+
import { PublicKey as PublicKey16 } from "@solana/web3.js";
|
|
11329
11766
|
import { getAssociatedTokenAddressSync as getAssociatedTokenAddressSync5 } from "@solana/spl-token";
|
|
11330
11767
|
var MAINNET_RENT_0 = 890880;
|
|
11331
11768
|
var MAINNET_RENT_1 = 897840;
|
|
11332
11769
|
var FEE_BUDGET = 13e4;
|
|
11333
11770
|
var CLEANUP_FEE_BUDGET = 5e3;
|
|
11334
|
-
var pda = (seeds, programId) =>
|
|
11771
|
+
var pda = (seeds, programId) => PublicKey16.findProgramAddressSync(seeds.map((s) => Buffer.from(s)), programId)[0];
|
|
11335
11772
|
function deriveFundingTargets(d) {
|
|
11336
11773
|
const pool = pda([Buffer.from("pool"), d.mint.toBuffer()], d.programId);
|
|
11337
11774
|
return {
|
|
@@ -11392,8 +11829,8 @@ async function depositFromDerivedKey(conn, R, funder, amount, log = console.log,
|
|
|
11392
11829
|
if (heldByR >= grantR) {
|
|
11393
11830
|
log(` R already holds ${heldByR} (>= ${grantR}) \u2014 no top-up needed`);
|
|
11394
11831
|
} else {
|
|
11395
|
-
await sendAndConfirmTransaction2(conn, new
|
|
11396
|
-
|
|
11832
|
+
await sendAndConfirmTransaction2(conn, new Transaction5().add(
|
|
11833
|
+
SystemProgram5.transfer({ fromPubkey: funder.publicKey, toPubkey: R.publicKey, lamports: grantR - heldByR })
|
|
11397
11834
|
), [funder]);
|
|
11398
11835
|
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"}`);
|
|
11399
11836
|
}
|
|
@@ -11419,13 +11856,13 @@ async function depositFromDerivedKey(conn, R, funder, amount, log = console.log,
|
|
|
11419
11856
|
address: t.a.toBase58(),
|
|
11420
11857
|
lamportsSent: Math.max(0, t.need - (infos[i]?.lamports ?? 0))
|
|
11421
11858
|
}));
|
|
11422
|
-
const ixs = targets.flatMap((t, i) => (infos[i]?.lamports ?? 0) >= t.need ? [] : [
|
|
11859
|
+
const ixs = targets.flatMap((t, i) => (infos[i]?.lamports ?? 0) >= t.need ? [] : [SystemProgram5.transfer({
|
|
11423
11860
|
fromPubkey: funder.publicKey,
|
|
11424
11861
|
toPubkey: t.a,
|
|
11425
11862
|
lamports: t.need - (infos[i]?.lamports ?? 0)
|
|
11426
11863
|
})]);
|
|
11427
11864
|
if (ixs.length) {
|
|
11428
|
-
const sig = await sendAndConfirmTransaction2(conn, new
|
|
11865
|
+
const sig = await sendAndConfirmTransaction2(conn, new Transaction5().add(...ixs), [funder]);
|
|
11429
11866
|
log(` seam: funded ${ixs.length} program accounts read off the built tx \u2014 ${sig.slice(0, 16)}\u2026`);
|
|
11430
11867
|
}
|
|
11431
11868
|
tx.sign([R]);
|
|
@@ -11482,8 +11919,8 @@ async function depositFromDerivedKey(conn, R, funder, amount, log = console.log,
|
|
|
11482
11919
|
|
|
11483
11920
|
// src/bridge/cleanup.ts
|
|
11484
11921
|
import {
|
|
11485
|
-
PublicKey as
|
|
11486
|
-
Transaction as
|
|
11922
|
+
PublicKey as PublicKey18,
|
|
11923
|
+
Transaction as Transaction6,
|
|
11487
11924
|
sendAndConfirmTransaction as sendAndConfirmTransaction3
|
|
11488
11925
|
} from "@solana/web3.js";
|
|
11489
11926
|
import {
|
|
@@ -11493,7 +11930,7 @@ import {
|
|
|
11493
11930
|
createAssociatedTokenAccountIdempotentInstruction,
|
|
11494
11931
|
getMinimumBalanceForRentExemptAccount
|
|
11495
11932
|
} from "@solana/spl-token";
|
|
11496
|
-
var DEFAULT_MINT = new
|
|
11933
|
+
var DEFAULT_MINT = new PublicKey18("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
|
|
11497
11934
|
async function cleanupReceivingAddress(conn, R, dustDestination, mint = DEFAULT_MINT) {
|
|
11498
11935
|
assertAllowedRpcConnection(conn);
|
|
11499
11936
|
const rAta = getAssociatedTokenAddressSync6(mint, R.publicKey);
|
|
@@ -11539,7 +11976,7 @@ async function cleanupReceivingAddress(conn, R, dustDestination, mint = DEFAULT_
|
|
|
11539
11976
|
destination = destAta.toBase58();
|
|
11540
11977
|
}
|
|
11541
11978
|
ixs.push(createCloseAccountInstruction(rAta, R.publicKey, R.publicKey));
|
|
11542
|
-
const signature = await sendAndConfirmTransaction3(conn, new
|
|
11979
|
+
const signature = await sendAndConfirmTransaction3(conn, new Transaction6().add(...ixs), [R], {
|
|
11543
11980
|
commitment: "confirmed"
|
|
11544
11981
|
});
|
|
11545
11982
|
const after = await conn.getBalance(R.publicKey);
|
|
@@ -11706,9 +12143,13 @@ export {
|
|
|
11706
12143
|
RECIPIENT_DELIVERY_NOTE_BYTES,
|
|
11707
12144
|
RECIPIENT_DELIVERY_PLAINTEXT_LEN,
|
|
11708
12145
|
RECIPIENT_DELIVERY_TAG_LEN,
|
|
12146
|
+
RELAY_BATCH_AUTH_MAX_ITEMS,
|
|
11709
12147
|
RELAY_ORIGIN_ALLOWLIST,
|
|
12148
|
+
REQUEST_AUTH_BATCH_DOMAIN,
|
|
12149
|
+
REQUEST_AUTH_BATCH_MAX_AGE_SECONDS,
|
|
11710
12150
|
REQUEST_AUTH_MAX_AGE_SECONDS,
|
|
11711
12151
|
REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS,
|
|
12152
|
+
RelayBatchAuthCoordinator,
|
|
11712
12153
|
RelayInternalError,
|
|
11713
12154
|
RelayService,
|
|
11714
12155
|
RootNotFoundError,
|
|
@@ -11736,11 +12177,13 @@ export {
|
|
|
11736
12177
|
assessBridgeQuote,
|
|
11737
12178
|
bigintToBytes32,
|
|
11738
12179
|
bigintToHex,
|
|
12180
|
+
buildAuthTransactionMessage,
|
|
11739
12181
|
buildMerkleTree,
|
|
11740
12182
|
buildMerkleTreeFromChain,
|
|
11741
12183
|
buildMerkleTreeFromRelay,
|
|
11742
12184
|
buildRecipientDeliveryNotes,
|
|
11743
12185
|
buildRelayAuthPreimage,
|
|
12186
|
+
buildRelayBatchAuthMessage,
|
|
11744
12187
|
buildTransactRequestBody,
|
|
11745
12188
|
bytesToHex,
|
|
11746
12189
|
calculateFee,
|
|
@@ -11774,6 +12217,7 @@ export {
|
|
|
11774
12217
|
createLogger,
|
|
11775
12218
|
createRecoverableChangeUtxo,
|
|
11776
12219
|
createRecoverableDepositUtxo,
|
|
12220
|
+
createRelayBatchAuthCoordinator,
|
|
11777
12221
|
createUtxo,
|
|
11778
12222
|
createZeroUtxo,
|
|
11779
12223
|
decryptCompactChainNote,
|
|
@@ -11900,6 +12344,7 @@ export {
|
|
|
11900
12344
|
readRent,
|
|
11901
12345
|
recipientDeliveryNoteToBase64,
|
|
11902
12346
|
registerViewingKey,
|
|
12347
|
+
relayRequestDigestHex,
|
|
11903
12348
|
removePendingDeposit,
|
|
11904
12349
|
removePendingWithdrawal,
|
|
11905
12350
|
renderAssessment,
|
|
@@ -11913,10 +12358,12 @@ export {
|
|
|
11913
12358
|
sdkLogger,
|
|
11914
12359
|
selectUtxos,
|
|
11915
12360
|
sendTransaction,
|
|
12361
|
+
serializeAuthTransactionMessage,
|
|
11916
12362
|
serializeNote,
|
|
11917
12363
|
serializeUtxo,
|
|
11918
12364
|
setCircuitsPath,
|
|
11919
12365
|
setDebugMode,
|
|
12366
|
+
signRelayAuthPayload,
|
|
11920
12367
|
signTransaction,
|
|
11921
12368
|
splitTo2Limbs,
|
|
11922
12369
|
submitTransactToRelay,
|
|
@@ -11925,6 +12372,7 @@ export {
|
|
|
11925
12372
|
swapWithChange,
|
|
11926
12373
|
toComplianceReport,
|
|
11927
12374
|
transact,
|
|
12375
|
+
transactBatch,
|
|
11928
12376
|
transfer,
|
|
11929
12377
|
truncate,
|
|
11930
12378
|
tryDecryptNote,
|