@cloak.dev/sdk 0.2.4 → 0.2.5-staging.4b3a899

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.js CHANGED
@@ -1,8 +1,16 @@
1
1
  import {
2
2
  BN254_MODULUS,
3
3
  CloakError,
4
+ DEFAULT_ADDRESS,
5
+ ED25519_PROGRAM_ADDRESS,
4
6
  InsecureRandomnessError,
5
7
  NATIVE_SOL_MINT,
8
+ SYSTEM_PROGRAM_ADDRESS,
9
+ SYSVAR_INSTRUCTIONS_ADDRESS,
10
+ SYSVAR_SLOT_HASHES_ADDRESS,
11
+ address,
12
+ addressBytes,
13
+ addressFromBytes,
6
14
  bigintToBytes32,
7
15
  bigintToBytes322,
8
16
  bigintToHex,
@@ -21,6 +29,7 @@ import {
21
29
  hexToBigint,
22
30
  hexToBigint2,
23
31
  hexToBytes,
32
+ isAddress,
24
33
  isValidHex,
25
34
  poseidonHash,
26
35
  proofToBytes,
@@ -33,18 +42,17 @@ import {
33
42
  serializeUtxo,
34
43
  splitTo2Limbs,
35
44
  sumUtxoAmounts,
45
+ toAddress,
36
46
  utxoEquals
37
- } from "./chunk-KNM6K5NG.js";
47
+ } from "./chunk-GM3WEXYP.js";
38
48
 
39
49
  // src/program/ids.ts
40
- import { PublicKey } from "@solana/web3.js";
41
- var CLOAK_PROGRAM_ID = new PublicKey("zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW");
50
+ var CLOAK_PROGRAM_ID = address("zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW");
42
51
 
43
52
  // src/shared/validation.ts
44
- import { PublicKey as PublicKey2 } from "@solana/web3.js";
45
- function isValidSolanaAddress(address) {
53
+ function isValidSolanaAddress(address2) {
46
54
  try {
47
- new PublicKey2(address);
55
+ if (!isAddress(address2)) throw new Error(`Invalid address: ${address2}`);
48
56
  return true;
49
57
  } catch {
50
58
  return false;
@@ -133,9 +141,9 @@ function validateTransfers(recipients, totalAmount) {
133
141
  }
134
142
  for (let i = 0; i < recipients.length; i++) {
135
143
  const transfer2 = recipients[i];
136
- const isPublicKeyLike = transfer2.recipient && typeof transfer2.recipient.toBase58 === "function" && typeof transfer2.recipient.toBuffer === "function";
137
- if (!isPublicKeyLike) {
138
- throw new Error(`Recipient ${i} must be a PublicKey (got ${typeof transfer2.recipient})`);
144
+ const isAddressLike = typeof transfer2.recipient === "string" && isAddress(transfer2.recipient);
145
+ if (!isAddressLike) {
146
+ throw new Error(`Recipient ${i} must be an address (got ${typeof transfer2.recipient})`);
139
147
  }
140
148
  if (typeof transfer2.amount !== "number" || transfer2.amount <= 0) {
141
149
  throw new Error(`Recipient ${i} amount must be a positive number`);
@@ -333,9 +341,9 @@ function getExplorerUrl(signature, network = "devnet") {
333
341
  const cluster = network === "mainnet" ? "" : `?cluster=${network}`;
334
342
  return `https://explorer.solana.com/tx/${signature}${cluster}`;
335
343
  }
336
- function getAddressExplorerUrl(address, network = "devnet") {
344
+ function getAddressExplorerUrl(address2, network = "devnet") {
337
345
  const cluster = network === "mainnet" ? "" : `?cluster=${network}`;
338
- return `https://explorer.solana.com/address/${address}${cluster}`;
346
+ return `https://explorer.solana.com/address/${address2}${cluster}`;
339
347
  }
340
348
 
341
349
  // src/shared/fees.ts
@@ -576,8 +584,55 @@ var LocalStorageAdapter = class {
576
584
  }
577
585
  };
578
586
 
587
+ // src/solana/signer.ts
588
+ import {
589
+ createKeyPairSignerFromBytes,
590
+ createKeyPairSignerFromPrivateKeyBytes,
591
+ createSignableMessage,
592
+ generateKeyPairSigner,
593
+ isMessagePartialSigner,
594
+ isMessageModifyingSigner,
595
+ isTransactionSigner
596
+ } from "@solana/kit";
597
+ function isMessageSigner(value) {
598
+ if (!value || typeof value !== "object" || typeof value.address !== "string") return false;
599
+ const candidate = value;
600
+ return isMessagePartialSigner(candidate) || isMessageModifyingSigner(candidate);
601
+ }
602
+ async function signerFromSecretKey(secretKey) {
603
+ if (secretKey.length === 64) return createKeyPairSignerFromBytes(secretKey);
604
+ if (secretKey.length === 32) return createKeyPairSignerFromPrivateKeyBytes(secretKey);
605
+ throw new Error(`A secret key is 64 bytes (or a 32-byte seed), got ${secretKey.length}`);
606
+ }
607
+ async function signMessageBytes(signer, message) {
608
+ const signable = createSignableMessage(message);
609
+ if (isMessagePartialSigner(signer)) {
610
+ const [dictionary] = await signer.signMessages([signable]);
611
+ const signature2 = dictionary[signer.address];
612
+ if (!signature2) throw new Error(`Signer ${signer.address} returned no signature for the message`);
613
+ return new Uint8Array(signature2);
614
+ }
615
+ const [signed] = await signer.modifyAndSignMessages([signable]);
616
+ const signature = signed.signatures[signer.address];
617
+ if (!signature) throw new Error(`Signer ${signer.address} returned no signature for the message`);
618
+ return new Uint8Array(signature);
619
+ }
620
+ function messageSignerFromCallback(address2, signMessage) {
621
+ return {
622
+ address: address2,
623
+ async signMessages(messages) {
624
+ const out = [];
625
+ for (const message of messages) {
626
+ const signature = await signMessage(message.content);
627
+ out.push({ [address2]: signature });
628
+ }
629
+ return out;
630
+ }
631
+ };
632
+ }
633
+
579
634
  // src/scanning/compliance-keys.ts
580
- import nacl3 from "tweetnacl";
635
+ import nacl2 from "tweetnacl";
581
636
  import { blake3 as blake32 } from "@noble/hashes/blake3";
582
637
  import { sha256 as sha2562 } from "@noble/hashes/sha2";
583
638
 
@@ -621,7 +676,7 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
621
676
 
622
677
  // src/config/relay.ts
623
678
  var CLOAK_PRODUCTION_RELAY_URL = "https://api.cloak.ag";
624
- var RELAY_ORIGIN_ALLOWLIST = [CLOAK_PRODUCTION_RELAY_URL];
679
+ var RELAY_ORIGIN_ALLOWLIST = ["https://staging-api.cloak.ag"];
625
680
  var ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
626
681
  var LOOPBACK_IPV4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
627
682
  var THIS_NETWORK_IPV4 = /^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
@@ -759,18 +814,317 @@ function assertAllowedRpcEndpoint(endpoint) {
759
814
  );
760
815
  }
761
816
  function assertAllowedRpcConnection(connection) {
817
+ assertAllowedRpcEndpoint(connection?.endpoint);
762
818
  assertAllowedRpcEndpoint(connection?.rpcEndpoint);
763
819
  assertAllowedRpcEndpoint(connection?._rpcEndpoint);
764
820
  }
765
821
  function connectionRpcEndpoint(connection) {
766
- return connection?._rpcEndpoint ?? connection?.rpcEndpoint;
822
+ return connection?.endpoint ?? connection?._rpcEndpoint ?? connection?.rpcEndpoint;
767
823
  }
768
824
 
769
825
  // src/relay/payload.ts
770
826
  import { sha256 } from "@noble/hashes/sha2";
771
827
  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";
828
+ import { createNoopSigner, getBase58Decoder as getBase58Decoder2 } from "@solana/kit";
829
+ import { getTransferSolInstruction } from "@solana-program/system";
830
+
831
+ // src/solana/transaction.ts
832
+ import {
833
+ addSignersToTransactionMessage,
834
+ appendTransactionMessageInstructions,
835
+ compileTransaction,
836
+ compressTransactionMessageUsingAddressLookupTables,
837
+ createTransactionMessage,
838
+ getBase64EncodedWireTransaction,
839
+ getSignatureFromTransaction,
840
+ getTransactionDecoder,
841
+ getTransactionEncoder,
842
+ partiallySignTransactionMessageWithSigners,
843
+ pipe,
844
+ setTransactionMessageFeePayer,
845
+ setTransactionMessageFeePayerSigner,
846
+ setTransactionMessageLifetimeUsingBlockhash,
847
+ signTransactionMessageWithSigners,
848
+ setTransactionMessageComputeUnitLimit,
849
+ setTransactionMessagePriorityFeeLamports,
850
+ setTransactionMessageLoadedAccountsDataSizeLimit
851
+ } from "@solana/kit";
852
+ import { fetchAddressLookupTable } from "@solana-program/address-lookup-table";
853
+
854
+ // src/solana/rpc.ts
855
+ import {
856
+ createSolanaRpc,
857
+ getBase58Decoder,
858
+ getBase64Decoder,
859
+ getBase64Encoder
860
+ } from "@solana/kit";
861
+ var ENDPOINTS = /* @__PURE__ */ new WeakMap();
862
+ function createCloakRpc(endpoint) {
863
+ const rpc = createSolanaRpc(endpoint);
864
+ const wrapped = new Proxy(rpc, {
865
+ get(target, prop, receiver) {
866
+ if (prop === "endpoint") return endpoint;
867
+ return Reflect.get(target, prop, receiver);
868
+ },
869
+ has(target, prop) {
870
+ return prop === "endpoint" || Reflect.has(target, prop);
871
+ }
872
+ });
873
+ ENDPOINTS.set(wrapped, endpoint);
874
+ return wrapped;
875
+ }
876
+ function rpcEndpoint(rpc) {
877
+ if (rpc && typeof rpc === "object") {
878
+ const known = ENDPOINTS.get(rpc);
879
+ if (known) return known;
880
+ const direct = rpc.endpoint;
881
+ if (typeof direct === "string") return direct;
882
+ }
883
+ return void 0;
884
+ }
885
+ var BASE64 = getBase64Encoder();
886
+ var BASE64_OUT = getBase64Decoder();
887
+ var BASE58_OUT = getBase58Decoder();
888
+ function base64ToBytes(value) {
889
+ return new Uint8Array(BASE64.encode(value));
890
+ }
891
+ function bytesToBase64(bytes) {
892
+ return BASE64_OUT.decode(bytes);
893
+ }
894
+ async function fetchAccountBytes(rpc, address2, commitment = "confirmed") {
895
+ const { value } = await rpc.getAccountInfo(address2, { encoding: "base64", commitment }).send();
896
+ if (!value) return null;
897
+ return {
898
+ address: address2,
899
+ data: base64ToBytes(value.data[0]),
900
+ owner: value.owner,
901
+ lamports: BigInt(value.lamports),
902
+ executable: value.executable
903
+ };
904
+ }
905
+ async function fetchMultipleAccountBytes(rpc, addresses, commitment = "confirmed") {
906
+ if (addresses.length === 0) return [];
907
+ const { value } = await rpc.getMultipleAccounts([...addresses], { encoding: "base64", commitment }).send();
908
+ return value.map(
909
+ (entry, i) => entry ? {
910
+ address: addresses[i],
911
+ data: base64ToBytes(entry.data[0]),
912
+ owner: entry.owner,
913
+ lamports: BigInt(entry.lamports),
914
+ executable: entry.executable
915
+ } : null
916
+ );
917
+ }
918
+ async function fetchLatestBlockhash(rpc, commitment = "confirmed") {
919
+ const { value } = await rpc.getLatestBlockhash({ commitment }).send();
920
+ return { blockhash: value.blockhash, lastValidBlockHeight: BigInt(value.lastValidBlockHeight) };
921
+ }
922
+ async function sendRawTransaction(rpc, wire, options = {}) {
923
+ const signature = await rpc.sendTransaction(bytesToBase64(wire), {
924
+ encoding: "base64",
925
+ skipPreflight: options.skipPreflight ?? false,
926
+ preflightCommitment: options.preflightCommitment ?? "confirmed",
927
+ ...options.maxRetries !== void 0 ? { maxRetries: BigInt(options.maxRetries) } : {}
928
+ }).send();
929
+ return signature;
930
+ }
931
+ async function fetchSignatureStatuses(rpc, signatures, searchTransactionHistory = false) {
932
+ const { value } = await rpc.getSignatureStatuses(signatures, { searchTransactionHistory }).send();
933
+ return value.map(
934
+ (entry) => entry ? {
935
+ slot: BigInt(entry.slot),
936
+ confirmations: entry.confirmations === null ? null : BigInt(entry.confirmations),
937
+ err: entry.err,
938
+ confirmationStatus: entry.confirmationStatus ?? null
939
+ } : null
940
+ );
941
+ }
942
+ var TransactionConfirmationError = class extends Error {
943
+ constructor(message, signature, reason, err) {
944
+ super(message);
945
+ this.signature = signature;
946
+ this.reason = reason;
947
+ this.err = err;
948
+ this.name = "TransactionConfirmationError";
949
+ }
950
+ };
951
+ var RANK = { processed: 0, confirmed: 1, finalized: 2 };
952
+ async function confirmSignature(rpc, signature, options = {}) {
953
+ const commitment = options.commitment ?? "confirmed";
954
+ const timeoutMs = options.timeoutMs ?? 9e4;
955
+ const pollIntervalMs = options.pollIntervalMs ?? 500;
956
+ const deadline = Date.now() + timeoutMs;
957
+ let polls = 0;
958
+ while (true) {
959
+ const [status] = await fetchSignatureStatuses(rpc, [signature], polls > 0 && polls % 10 === 0);
960
+ polls += 1;
961
+ if (status) {
962
+ if (status.err) {
963
+ throw new TransactionConfirmationError(
964
+ `Transaction failed during confirmation: ${JSON.stringify(status.err)}`,
965
+ signature,
966
+ "failed",
967
+ status.err
968
+ );
969
+ }
970
+ const reached = status.confirmationStatus ? RANK[status.confirmationStatus] : -1;
971
+ if (reached >= RANK[commitment]) return { slot: status.slot };
972
+ }
973
+ if (options.lastValidBlockHeight !== void 0) {
974
+ const height = await rpc.getBlockHeight({ commitment }).send();
975
+ if (BigInt(height) > options.lastValidBlockHeight) {
976
+ throw new TransactionConfirmationError(
977
+ `Transaction ${signature} was not confirmed before its blockhash expired`,
978
+ signature,
979
+ "expired"
980
+ );
981
+ }
982
+ }
983
+ if (Date.now() > deadline) {
984
+ throw new TransactionConfirmationError(
985
+ `Transaction ${signature} was not confirmed within ${timeoutMs} ms`,
986
+ signature,
987
+ "timeout"
988
+ );
989
+ }
990
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
991
+ }
992
+ }
993
+ async function fetchSignaturesForAddress(rpc, address2, options = {}) {
994
+ const result = await rpc.getSignaturesForAddress(address2, {
995
+ before: options.before,
996
+ until: options.until,
997
+ limit: options.limit,
998
+ commitment: options.commitment
999
+ }).send();
1000
+ return result.map((entry) => ({
1001
+ signature: entry.signature,
1002
+ slot: Number(entry.slot),
1003
+ err: entry.err,
1004
+ memo: entry.memo ?? null,
1005
+ blockTime: entry.blockTime === null || entry.blockTime === void 0 ? null : Number(entry.blockTime)
1006
+ }));
1007
+ }
1008
+ async function fetchTransactionJson(rpc, signature, options) {
1009
+ const result = await rpc.getTransaction(signature, {
1010
+ encoding: "json",
1011
+ commitment: options.commitment ?? "confirmed",
1012
+ maxSupportedTransactionVersion: options.maxSupportedTransactionVersion
1013
+ }).send();
1014
+ if (!result) return null;
1015
+ const raw = result;
1016
+ return {
1017
+ slot: Number(raw.slot),
1018
+ blockTime: raw.blockTime === null || raw.blockTime === void 0 ? null : Number(raw.blockTime),
1019
+ version: raw.version,
1020
+ meta: raw.meta,
1021
+ transaction: raw.transaction
1022
+ };
1023
+ }
1024
+ async function fetchParsedTransaction(rpc, signature, options) {
1025
+ const result = await rpc.getTransaction(signature, {
1026
+ encoding: "jsonParsed",
1027
+ commitment: options.commitment ?? "confirmed",
1028
+ maxSupportedTransactionVersion: options.maxSupportedTransactionVersion
1029
+ }).send();
1030
+ if (!result) return null;
1031
+ const raw = result;
1032
+ return {
1033
+ slot: Number(raw.slot),
1034
+ blockTime: raw.blockTime === null || raw.blockTime === void 0 ? null : Number(raw.blockTime),
1035
+ version: raw.version,
1036
+ meta: raw.meta,
1037
+ transaction: raw.transaction
1038
+ };
1039
+ }
1040
+ function isRawParsedInstruction(ix) {
1041
+ return "accounts" in ix && "data" in ix;
1042
+ }
1043
+ async function fetchSlot(rpc, commitment = "confirmed") {
1044
+ return Number(await rpc.getSlot({ commitment }).send());
1045
+ }
1046
+
1047
+ // src/solana/transaction.ts
1048
+ async function fetchLookupTables(rpc, addresses) {
1049
+ return Promise.all(
1050
+ addresses.map(async (address2) => {
1051
+ const account = await fetchAddressLookupTable(rpc, address2);
1052
+ return { address: address2, addresses: account.data.addresses };
1053
+ })
1054
+ );
1055
+ }
1056
+ function buildTransactionMessage(params) {
1057
+ const { version = 0, feePayer, lifetime, instructions, lookupTables = [], signers = [], computeConfig } = params;
1058
+ if (computeConfig && version !== 1) {
1059
+ throw new Error(`computeConfig is a v1 message header field; a ${String(version)} message carries ComputeBudget instructions instead`);
1060
+ }
1061
+ const base = pipe(
1062
+ createTransactionMessage({ version }),
1063
+ (m) => typeof feePayer === "string" ? setTransactionMessageFeePayer(feePayer, m) : setTransactionMessageFeePayerSigner(feePayer, m),
1064
+ (m) => setTransactionMessageLifetimeUsingBlockhash(
1065
+ { blockhash: lifetime.blockhash, lastValidBlockHeight: lifetime.lastValidBlockHeight },
1066
+ m
1067
+ ),
1068
+ (m) => appendTransactionMessageInstructions(instructions, m),
1069
+ (m) => signers.length > 0 ? addSignersToTransactionMessage([...signers], m) : m,
1070
+ (m) => computeConfig?.computeUnitLimit !== void 0 ? setTransactionMessageComputeUnitLimit(computeConfig.computeUnitLimit, m) : m,
1071
+ (m) => computeConfig?.priorityFeeLamports !== void 0 ? setTransactionMessagePriorityFeeLamports(computeConfig.priorityFeeLamports, m) : m,
1072
+ (m) => computeConfig?.loadedAccountsDataSizeLimit !== void 0 ? setTransactionMessageLoadedAccountsDataSizeLimit(computeConfig.loadedAccountsDataSizeLimit, m) : m
1073
+ );
1074
+ if (version === 0 && lookupTables.length > 0) {
1075
+ const tables = Object.fromEntries(lookupTables.map((t) => [t.address, [...t.addresses]]));
1076
+ return compressTransactionMessageUsingAddressLookupTables(base, tables);
1077
+ }
1078
+ return base;
1079
+ }
1080
+ function compileUnsigned(message) {
1081
+ return compileTransaction(message);
1082
+ }
1083
+ var TRANSACTION_ENCODER = getTransactionEncoder();
1084
+ var TRANSACTION_DECODER = getTransactionDecoder();
1085
+ function transactionBytes(transaction) {
1086
+ return new Uint8Array(TRANSACTION_ENCODER.encode(transaction));
1087
+ }
1088
+ function transactionWireSize(message) {
1089
+ return transactionBytes(compileUnsigned(message)).length;
1090
+ }
1091
+ function transactionFromBytes(bytes) {
1092
+ return TRANSACTION_DECODER.decode(bytes);
1093
+ }
1094
+ async function signCompiledTransaction(signer, transaction) {
1095
+ const [signatures] = await signer.signTransactions(
1096
+ [transaction]
1097
+ );
1098
+ return { ...transaction, signatures: { ...transaction.signatures, ...signatures } };
1099
+ }
1100
+ function transactionBase64(transaction) {
1101
+ return getBase64EncodedWireTransaction(transaction);
1102
+ }
1103
+ async function signTransaction(message) {
1104
+ return signTransactionMessageWithSigners(message);
1105
+ }
1106
+ async function partiallySignTransaction(message) {
1107
+ return partiallySignTransactionMessageWithSigners(message);
1108
+ }
1109
+ async function sendInstructions(rpc, payer, instructions, options = {}) {
1110
+ const lifetime = await fetchLatestBlockhash(rpc, options.commitment ?? "confirmed");
1111
+ const message = buildTransactionMessage({
1112
+ version: options.version ?? "legacy",
1113
+ feePayer: payer,
1114
+ lifetime,
1115
+ instructions,
1116
+ lookupTables: options.lookupTables
1117
+ });
1118
+ const signed = await signTransaction(message);
1119
+ const signature = await sendRawTransaction(rpc, transactionBytes(signed), { skipPreflight: options.skipPreflight });
1120
+ await confirmSignature(rpc, signature, {
1121
+ commitment: options.commitment ?? "confirmed",
1122
+ lastValidBlockHeight: lifetime.lastValidBlockHeight
1123
+ });
1124
+ return signature;
1125
+ }
1126
+
1127
+ // src/relay/payload.ts
774
1128
  var REQUEST_AUTH_DOMAIN = "CLOAK_RELAY_REQUEST_AUTH_V1";
775
1129
  var REQUEST_AUTH_MAX_AGE_SECONDS = 300;
776
1130
  var REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS = 30;
@@ -892,30 +1246,30 @@ function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request)
892
1246
  return new TextEncoder().encode(
893
1247
  `${REQUEST_AUTH_DOMAIN}
894
1248
  ${endpoint}
895
- ${programId.toBase58()}
1249
+ ${programId}
896
1250
  ${nonce}
897
1251
  ${issuedAt}
898
1252
  ${digest}`
899
1253
  );
900
1254
  }
901
1255
  function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
902
- const senderB58 = sender.toBase58();
1256
+ const senderB58 = sender;
903
1257
  const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
904
1258
  const nonce = randomNonceUuid();
905
1259
  const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
906
1260
  const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
907
1261
  return { sender: senderB58, auth_issued_at: issuedAt, auth_nonce: nonce, message };
908
1262
  }
909
- function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
1263
+ async function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
910
1264
  const preimage = buildRelayAuthPreimage(
911
1265
  endpoint,
912
1266
  programId,
913
1267
  body,
914
- signer.publicKey,
1268
+ signer.address,
915
1269
  nowSeconds,
916
1270
  fields
917
1271
  );
918
- const signature = nacl2.sign.detached(preimage.message, signer.secretKey);
1272
+ const signature = await signMessageBytes(signer, preimage.message);
919
1273
  return {
920
1274
  sender: preimage.sender,
921
1275
  auth_issued_at: preimage.auth_issued_at,
@@ -925,38 +1279,44 @@ function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields
925
1279
  }
926
1280
  function buildAuthTransactionMessage(sender, digest) {
927
1281
  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;
1282
+ const payer = createNoopSigner(sender);
1283
+ return buildTransactionMessage({
1284
+ version: "legacy",
1285
+ feePayer: payer,
1286
+ // 32 raw bytes in the blockhash slot; base58 is just the codec the message type expects.
1287
+ lifetime: { blockhash: getBase58Decoder2().decode(digest), lastValidBlockHeight: 0n },
1288
+ instructions: [getTransferSolInstruction({ source: payer, destination: sender, amount: 0n })]
1289
+ });
933
1290
  }
934
1291
  function serializeAuthTransactionMessage(sender, digest) {
935
- return Uint8Array.from(buildAuthTransactionMessage(sender, digest).compileMessage().serialize());
1292
+ return new Uint8Array(compileUnsigned(buildAuthTransactionMessage(sender, digest)).messageBytes);
936
1293
  }
937
1294
  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);
1295
+ if (isMessageSigner(signer)) {
1296
+ const signature = await signMessageBytes(signer, payload);
943
1297
  assertDetachedSignature(signature, "signMessage");
944
1298
  return { signature, mode: "message" };
945
1299
  }
946
- if (signer.signAuthTransaction) {
1300
+ if (isTransactionSigner(signer)) {
947
1301
  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;
1302
+ const message = buildTransactionMessage({
1303
+ version: "legacy",
1304
+ feePayer: signer,
1305
+ lifetime: { blockhash: getBase58Decoder2().decode(digest), lastValidBlockHeight: 0n },
1306
+ instructions: [getTransferSolInstruction({ source: signer, destination: signer.address, amount: 0n })]
1307
+ });
1308
+ const signed = await signTransaction(message);
1309
+ const own = signed.signatures[signer.address];
950
1310
  if (!own) {
951
1311
  throw new Error(
952
1312
  "The wallet returned no signature for the Cloak auth transaction. Nothing was submitted."
953
1313
  );
954
1314
  }
955
- const signature = Uint8Array.from(own);
1315
+ const signature = new Uint8Array(own);
956
1316
  assertDetachedSignature(signature, "signTransaction");
957
1317
  return { signature, mode: "transaction" };
958
1318
  }
959
- throw new Error("Relay auth signer has neither signMessage nor signAuthTransaction.");
1319
+ throw new Error("Relay auth signer can neither sign messages nor transactions.");
960
1320
  }
961
1321
  function assertDetachedSignature(signature, method) {
962
1322
  if (!(signature instanceof Uint8Array) || signature.length !== 64) {
@@ -1009,7 +1369,7 @@ async function buildRelayAuthFields(endpoint, programId, body, signers, fields =
1009
1369
  endpoint,
1010
1370
  programId,
1011
1371
  body,
1012
- wallet.walletPublicKey,
1372
+ wallet.address,
1013
1373
  void 0,
1014
1374
  fields
1015
1375
  );
@@ -1031,7 +1391,7 @@ function relayRequestDigestHex(preimage) {
1031
1391
  return bytesToHex2(sha256(preimage.message));
1032
1392
  }
1033
1393
  function buildRelayBatchAuthMessage(programId, issuedAt, digests) {
1034
- const lines = [REQUEST_AUTH_BATCH_DOMAIN, programId.toBase58(), issuedAt, String(digests.length)];
1394
+ const lines = [REQUEST_AUTH_BATCH_DOMAIN, programId, issuedAt, String(digests.length)];
1035
1395
  return new TextEncoder().encode([...lines, ...digests].join("\n"));
1036
1396
  }
1037
1397
 
@@ -1072,7 +1432,7 @@ function deriveViewingKeyFromNk(nk) {
1072
1432
  preimage.set(nk, CHAIN_NOTE_VK_DOMAIN.length);
1073
1433
  const derived = blake32(preimage);
1074
1434
  const privateKey = clampX25519Secret(derived);
1075
- const publicKey = nacl3.scalarMult.base(privateKey);
1435
+ const publicKey = nacl2.scalarMult.base(privateKey);
1076
1436
  return { privateKey, publicKey };
1077
1437
  }
1078
1438
  function deriveDiversifier(nk, commitmentHex, outputIndex) {
@@ -1107,7 +1467,7 @@ function deriveDiversifiedViewingKey(nk, diversifier) {
1107
1467
  preimage.set(diversifier, SK_D_DOMAIN.length + nk.length);
1108
1468
  const derived = blake32(preimage);
1109
1469
  const privateKey = clampX25519Secret(derived);
1110
- const publicKey = nacl3.scalarMult.base(privateKey);
1470
+ const publicKey = nacl2.scalarMult.base(privateKey);
1111
1471
  return { privateKey, publicKey };
1112
1472
  }
1113
1473
  function deriveViewingKeyFromSpendKey(skSpend) {
@@ -1160,7 +1520,7 @@ function bigintToScalarLE(value) {
1160
1520
  async function deriveUserComplianceScalar(masterCompliancePublicKey, userPublicKey) {
1161
1521
  assert32Bytes(masterCompliancePublicKey, "masterCompliancePublicKey");
1162
1522
  const masterField = bytesToFieldElement(masterCompliancePublicKey);
1163
- const userField = bytesToFieldElement(userPublicKey.toBytes());
1523
+ const userField = bytesToFieldElement(addressBytes(userPublicKey));
1164
1524
  const factor = await poseidonHash([masterField, userField]);
1165
1525
  return bigintToScalarLE(factor);
1166
1526
  }
@@ -1170,13 +1530,13 @@ async function deriveUserCompliancePublicKey(masterCompliancePublicKey, userPubl
1170
1530
  masterCompliancePublicKey,
1171
1531
  userPublicKey
1172
1532
  );
1173
- return nacl3.scalarMult(factor, masterCompliancePublicKey);
1533
+ return nacl2.scalarMult(factor, masterCompliancePublicKey);
1174
1534
  }
1175
1535
  function bytesToHex3(bytes) {
1176
1536
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1177
1537
  }
1178
1538
  function computeViewingKeyIdentifier(userPubkey, nkHex) {
1179
- const preimage = new TextEncoder().encode(`${userPubkey.toBase58()}${nkHex}`);
1539
+ const preimage = new TextEncoder().encode(`${userPubkey}${nkHex}`);
1180
1540
  return bytesToHex3(sha2562(preimage));
1181
1541
  }
1182
1542
  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.";
@@ -1188,7 +1548,7 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1188
1548
  method: "POST",
1189
1549
  headers: { "Content-Type": "application/json" },
1190
1550
  body: JSON.stringify({
1191
- user_pubkey: userPubkey.toBase58(),
1551
+ user_pubkey: userPubkey,
1192
1552
  viewing_key: nkHex
1193
1553
  })
1194
1554
  });
@@ -1199,12 +1559,12 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1199
1559
  }
1200
1560
  const challenge = parseStrictViewingKeyChallenge(
1201
1561
  await challengeResponse.json(),
1202
- userPubkey.toBase58(),
1562
+ userPubkey,
1203
1563
  nkHex
1204
1564
  );
1205
1565
  const messageBytes = new TextEncoder().encode(challenge.message);
1206
1566
  const signed = await signRelayAuthPayload(
1207
- typeof signMessage === "function" ? { walletPublicKey: userPubkey, signMessage } : signMessage,
1567
+ typeof signMessage === "function" ? messageSignerFromCallback(userPubkey, signMessage) : signMessage,
1208
1568
  messageBytes
1209
1569
  );
1210
1570
  const signature = Buffer.from(signed.signature).toString("base64");
@@ -1212,7 +1572,7 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1212
1572
  method: "POST",
1213
1573
  headers: { "Content-Type": "application/json" },
1214
1574
  body: JSON.stringify({
1215
- user_pubkey: userPubkey.toBase58(),
1575
+ user_pubkey: userPubkey,
1216
1576
  viewing_key: nkHex,
1217
1577
  nonce: challenge.nonce,
1218
1578
  identifier: keyId,
@@ -1226,7 +1586,7 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1226
1586
  }
1227
1587
 
1228
1588
  // src/scanning/metadata-encryption.ts
1229
- import nacl4 from "tweetnacl";
1589
+ import nacl3 from "tweetnacl";
1230
1590
  var AES_GCM_NONCE_LENGTH = 12;
1231
1591
  var AES_GCM_TAG_LENGTH = 16;
1232
1592
  var X25519_KEY_LENGTH2 = 32;
@@ -1323,8 +1683,8 @@ async function aesGcmDecrypt(ciphertext, keyBytes, nonce) {
1323
1683
  }
1324
1684
  async function encryptForRecipient(plaintext, recipientPublicKey) {
1325
1685
  assert32Bytes2(recipientPublicKey, "recipientPublicKey");
1326
- const ephemeral = nacl4.box.keyPair();
1327
- const sharedSecret = nacl4.scalarMult(ephemeral.secretKey, recipientPublicKey);
1686
+ const ephemeral = nacl3.box.keyPair();
1687
+ const sharedSecret = nacl3.scalarMult(ephemeral.secretKey, recipientPublicKey);
1328
1688
  const nonce = randomBytes(AES_GCM_NONCE_LENGTH);
1329
1689
  const ciphertext = await aesGcmEncrypt(plaintext, sharedSecret, nonce);
1330
1690
  return {
@@ -1359,7 +1719,7 @@ function normalizeUserPubkey(userPubkey) {
1359
1719
  if (!userPubkey) {
1360
1720
  return "";
1361
1721
  }
1362
- return typeof userPubkey === "string" ? userPubkey : userPubkey.toBase58();
1722
+ return userPubkey;
1363
1723
  }
1364
1724
  async function encryptTransactionMetadata(metadata, userViewKeyPublic, complianceKeyPublic, context) {
1365
1725
  assert32Bytes2(userViewKeyPublic, "userViewKeyPublic");
@@ -1383,7 +1743,7 @@ async function encryptTransactionMetadataBundle(metadata, viewingKeyPrivate, use
1383
1743
  const plaintext = new TextEncoder().encode(JSON.stringify(metadata));
1384
1744
  const basePoint = new Uint8Array(32);
1385
1745
  basePoint[0] = 9;
1386
- const viewingKeyPublic = nacl4.scalarMult(viewingKeyPrivate, basePoint);
1746
+ const viewingKeyPublic = nacl3.scalarMult(viewingKeyPrivate, basePoint);
1387
1747
  const [userPayload, compliancePayload] = await Promise.all([
1388
1748
  encryptForRecipient(plaintext, viewingKeyPublic),
1389
1749
  encryptForRecipient(plaintext, viewingKeyPublic)
@@ -1391,7 +1751,7 @@ async function encryptTransactionMetadataBundle(metadata, viewingKeyPrivate, use
1391
1751
  return {
1392
1752
  encrypted_user: encodeBase64(JSON.stringify(userPayload)),
1393
1753
  encrypted_compliance: encodeBase64(JSON.stringify(compliancePayload)),
1394
- user_pubkey: userPubkey.toBase58(),
1754
+ user_pubkey: userPubkey,
1395
1755
  commitment: metadata.commitment,
1396
1756
  timestamp: metadata.timestamp,
1397
1757
  tx_type: metadata.txType
@@ -1402,7 +1762,7 @@ async function decryptTransactionMetadata(encrypted, viewKeySecret) {
1402
1762
  const payload = decodePayload(encrypted);
1403
1763
  const ephemeralPk = hexToBytes(payload.ephemeral_pk);
1404
1764
  assert32Bytes2(ephemeralPk, "ephemeral public key");
1405
- const sharedSecret = nacl4.scalarMult(viewKeySecret, ephemeralPk);
1765
+ const sharedSecret = nacl3.scalarMult(viewKeySecret, ephemeralPk);
1406
1766
  return decryptWithSharedSecret(payload, sharedSecret);
1407
1767
  }
1408
1768
  async function decryptComplianceMetadataWithMasterKey(encrypted, masterCompliancePrivateKey, masterCompliancePublicKey, userPublicKey) {
@@ -1415,8 +1775,8 @@ async function decryptComplianceMetadataWithMasterKey(encrypted, masterComplianc
1415
1775
  masterCompliancePublicKey,
1416
1776
  userPublicKey
1417
1777
  );
1418
- const scaledEphemeral = nacl4.scalarMult(userFactor, ephemeralPk);
1419
- const sharedSecret = nacl4.scalarMult(masterCompliancePrivateKey, scaledEphemeral);
1778
+ const scaledEphemeral = nacl3.scalarMult(userFactor, ephemeralPk);
1779
+ const sharedSecret = nacl3.scalarMult(masterCompliancePrivateKey, scaledEphemeral);
1420
1780
  return decryptWithSharedSecret(payload, sharedSecret);
1421
1781
  }
1422
1782
 
@@ -2345,67 +2705,51 @@ function formatErrorForLogging(error) {
2345
2705
  return String(error);
2346
2706
  }
2347
2707
 
2708
+ // src/solana/pda.ts
2709
+ import { getProgramDerivedAddress } from "@solana/kit";
2710
+ async function findProgramAddress(seeds, programAddress) {
2711
+ const [pda2, bump] = await getProgramDerivedAddress({ programAddress, seeds });
2712
+ return [pda2, bump];
2713
+ }
2714
+
2348
2715
  // src/program/pda.ts
2349
- import { PublicKey as PublicKey4 } from "@solana/web3.js";
2350
- function getShieldPoolPDAs(programId, mint = NATIVE_SOL_MINT) {
2716
+ var utf8 = (s) => new TextEncoder().encode(s);
2717
+ async function getShieldPoolPDAs(programId, mint = NATIVE_SOL_MINT) {
2351
2718
  const pid = programId || CLOAK_PROGRAM_ID;
2352
- const [pool] = PublicKey4.findProgramAddressSync(
2353
- [Buffer.from("pool"), mint.toBuffer()],
2354
- pid
2355
- );
2356
- const [merkleTree] = PublicKey4.findProgramAddressSync(
2357
- [Buffer.from("merkle_tree"), mint.toBuffer()],
2358
- pid
2359
- );
2360
- const [treasury] = PublicKey4.findProgramAddressSync(
2361
- [Buffer.from("treasury"), mint.toBuffer()],
2362
- pid
2363
- );
2364
- const [vaultAuthority] = PublicKey4.findProgramAddressSync(
2365
- [Buffer.from("vault_authority"), mint.toBuffer()],
2366
- pid
2367
- );
2368
- return {
2369
- pool,
2370
- merkleTree,
2371
- vaultAuthority,
2372
- treasury
2373
- };
2719
+ const mintSeed = addressBytes(mint);
2720
+ const [[pool], [merkleTree], [treasury], [vaultAuthority]] = await Promise.all([
2721
+ findProgramAddress([utf8("pool"), mintSeed], pid),
2722
+ findProgramAddress([utf8("merkle_tree"), mintSeed], pid),
2723
+ findProgramAddress([utf8("treasury"), mintSeed], pid),
2724
+ findProgramAddress([utf8("vault_authority"), mintSeed], pid)
2725
+ ]);
2726
+ return { pool, merkleTree, vaultAuthority, treasury };
2374
2727
  }
2375
- function getNullifierPDA(poolPubkey, nullifier, programId) {
2728
+ async function getNullifierPDA(poolAddress, nullifier, programId) {
2376
2729
  const pid = programId || CLOAK_PROGRAM_ID;
2377
2730
  if (nullifier.length !== 32) {
2378
2731
  throw new Error(`Nullifier must be 32 bytes, got ${nullifier.length}`);
2379
2732
  }
2380
- return PublicKey4.findProgramAddressSync(
2381
- [Buffer.from("nullifier"), poolPubkey.toBuffer(), Buffer.from(nullifier)],
2382
- pid
2383
- );
2733
+ return findProgramAddress([utf8("nullifier"), addressBytes(poolAddress), new Uint8Array(nullifier)], pid);
2384
2734
  }
2385
- function getSwapStatePDA(poolPubkey, nullifier, programId) {
2735
+ async function getSwapStatePDA(poolAddress, nullifier, programId) {
2386
2736
  const pid = programId || CLOAK_PROGRAM_ID;
2387
2737
  if (nullifier.length !== 32) {
2388
2738
  throw new Error(`Nullifier must be 32 bytes, got ${nullifier.length}`);
2389
2739
  }
2390
- return PublicKey4.findProgramAddressSync(
2391
- [Buffer.from("swap_state"), poolPubkey.toBuffer(), Buffer.from(nullifier)],
2392
- pid
2393
- );
2740
+ return findProgramAddress([utf8("swap_state"), addressBytes(poolAddress), new Uint8Array(nullifier)], pid);
2394
2741
  }
2395
- function getPoolAuthorityConfigPDA(mint = NATIVE_SOL_MINT, programId) {
2742
+ async function getPoolAuthorityConfigPDA(mint = NATIVE_SOL_MINT, programId) {
2396
2743
  const pid = programId || CLOAK_PROGRAM_ID;
2397
- return PublicKey4.findProgramAddressSync(
2398
- [Buffer.from("pool_authority"), mint.toBuffer()],
2399
- pid
2400
- );
2744
+ return findProgramAddress([utf8("pool_authority"), addressBytes(mint)], pid);
2401
2745
  }
2402
- function getDeliveryRegistryPDA(programId) {
2746
+ async function getDeliveryRegistryPDA(programId) {
2403
2747
  const pid = programId || CLOAK_PROGRAM_ID;
2404
- return PublicKey4.findProgramAddressSync([Buffer.from("cloak_delivery_registry")], pid)[0];
2748
+ return (await findProgramAddress([utf8("cloak_delivery_registry")], pid))[0];
2405
2749
  }
2406
- function getChainNoteRegistryPDA(programId) {
2750
+ async function getChainNoteRegistryPDA(programId) {
2407
2751
  const pid = programId || CLOAK_PROGRAM_ID;
2408
- return PublicKey4.findProgramAddressSync([Buffer.from("cloak_chain_note_registry")], pid)[0];
2752
+ return (await findProgramAddress([utf8("cloak_chain_note_registry")], pid))[0];
2409
2753
  }
2410
2754
 
2411
2755
  // src/flows/verify-utxos.ts
@@ -2422,8 +2766,8 @@ async function verifyUtxos(utxos, connection, programId, commitment = "confirmed
2422
2766
  const nullifierBig = await computeNullifier(utxo);
2423
2767
  const nullifierHex = nullifierBig.toString(16).padStart(64, "0");
2424
2768
  const nullifierBytes = Buffer.from(nullifierHex, "hex");
2425
- const { pool } = getShieldPoolPDAs(programId, utxo.mintAddress);
2426
- const [pda2] = getNullifierPDA(pool, nullifierBytes, programId);
2769
+ const { pool } = await getShieldPoolPDAs(programId, utxo.mintAddress);
2770
+ const [pda2] = await getNullifierPDA(pool, nullifierBytes, programId);
2427
2771
  checkable.push({ utxo, pda: pda2 });
2428
2772
  } catch {
2429
2773
  skipped.push(utxo);
@@ -2436,7 +2780,7 @@ async function verifyUtxos(utxos, connection, programId, commitment = "confirmed
2436
2780
  const infos = [];
2437
2781
  for (let i = 0; i < checkable.length; i += CHUNK) {
2438
2782
  const page = checkable.slice(i, i + CHUNK).map((e) => e.pda);
2439
- const pageInfos = await connection.getMultipleAccountsInfo(page, commitment);
2783
+ const pageInfos = await fetchMultipleAccountBytes(connection, page, commitment);
2440
2784
  infos.push(...pageInfos);
2441
2785
  }
2442
2786
  const spent = [];
@@ -2468,6 +2812,19 @@ async function preflightNullifiers(utxos, connection, programId, commitment = "c
2468
2812
  }
2469
2813
 
2470
2814
  // src/flows/settlement.ts
2815
+ function settlementConnectionFromRpc(rpc) {
2816
+ return {
2817
+ endpoint: rpc.endpoint,
2818
+ async getSignatureStatuses(signatures, config) {
2819
+ const { value } = await rpc.getSignatureStatuses(signatures, { searchTransactionHistory: config?.searchTransactionHistory ?? false }).send();
2820
+ return { value: value.map((v) => v ? { err: v.err, confirmationStatus: v.confirmationStatus ?? null } : null) };
2821
+ },
2822
+ async getMultipleAccounts(addresses, commitment) {
2823
+ const { value } = await rpc.getMultipleAccounts(addresses, { encoding: "base64", commitment: commitment ?? "confirmed" }).send();
2824
+ return value;
2825
+ }
2826
+ };
2827
+ }
2471
2828
  var DEFAULT_SETTLEMENT_TIMEOUT_MS = 3e4;
2472
2829
  var DEFAULT_SETTLEMENT_POLL_MS = 1500;
2473
2830
  var MAX_SETTLEMENT_TIMEOUT_MS = 3e5;
@@ -2489,12 +2846,12 @@ function bigintToBytes324(value) {
2489
2846
  }
2490
2847
  return out;
2491
2848
  }
2492
- function deriveInputNullifierPdas(programId, mint, inputNullifiers) {
2493
- const { pool } = getShieldPoolPDAs(programId, mint);
2849
+ async function deriveInputNullifierPdas(programId, mint, inputNullifiers) {
2850
+ const { pool } = await getShieldPoolPDAs(programId, mint);
2494
2851
  const pdas = [];
2495
2852
  for (const nullifier of inputNullifiers) {
2496
2853
  if (nullifier === BigInt(0)) continue;
2497
- const [pda2] = getNullifierPDA(pool, bigintToBytes324(nullifier), programId);
2854
+ const [pda2] = await getNullifierPDA(pool, bigintToBytes324(nullifier), programId);
2498
2855
  pdas.push(pda2);
2499
2856
  }
2500
2857
  return pdas;
@@ -2516,7 +2873,7 @@ async function confirmTransactSettlement(params) {
2516
2873
  const signature = isPlausibleSignature(params.signature) ? params.signature : null;
2517
2874
  const reportedSomething = params.signature !== void 0 && params.signature !== null && params.signature !== "";
2518
2875
  const unusableSignature = reportedSomething && signature === null;
2519
- const pdas = deriveInputNullifierPdas(programId, mint, inputNullifiers);
2876
+ const pdas = await deriveInputNullifierPdas(programId, mint, inputNullifiers);
2520
2877
  const deadline = Date.now() + Math.max(0, timeoutMs);
2521
2878
  let signatureStatus = signature ? "absent" : "unchecked";
2522
2879
  let nullifiersSpent = false;
@@ -2552,7 +2909,7 @@ async function confirmTransactSettlement(params) {
2552
2909
  }
2553
2910
  if (pdas.length > 0) {
2554
2911
  try {
2555
- const infos = await connection.getMultipleAccountsInfo(pdas, "confirmed");
2912
+ const infos = await connection.getMultipleAccounts(pdas, "confirmed");
2556
2913
  nullifiersSpent = Array.isArray(infos) && infos.length === pdas.length && infos.every((info) => info !== null && info !== void 0);
2557
2914
  } catch (error) {
2558
2915
  lastRpcError = error instanceof Error ? error.message : String(error);
@@ -2737,7 +3094,6 @@ var sdkLogger = createLogger("cloak::sdk");
2737
3094
 
2738
3095
  // src/relay/relay-service.ts
2739
3096
  import { sha256 as sha2563 } from "@noble/hashes/sha2";
2740
- import { PublicKey as PublicKey5 } from "@solana/web3.js";
2741
3097
  var RelayService = class {
2742
3098
  /**
2743
3099
  * Create a new Relay Service client
@@ -3054,7 +3410,7 @@ var RelayService = class {
3054
3410
  viewingKey
3055
3411
  );
3056
3412
  const signed = await signRelayAuthPayload(
3057
- typeof signMessage === "function" ? { walletPublicKey: new PublicKey5(userPubkey), signMessage } : signMessage,
3413
+ typeof signMessage === "function" ? messageSignerFromCallback(address(userPubkey), signMessage) : signMessage,
3058
3414
  new TextEncoder().encode(challenge.message)
3059
3415
  );
3060
3416
  const signature = this.bytesToBase64(signed.signature);
@@ -3111,6 +3467,7 @@ var RelayService = class {
3111
3467
  };
3112
3468
 
3113
3469
  // src/relay/risk-quote.ts
3470
+ import { fromLegacyTransactionInstruction } from "@solana/compat";
3114
3471
  function buildRangeRiskScoreJob(OracleJob, walletAddress) {
3115
3472
  return OracleJob.fromObject({
3116
3473
  tasks: [
@@ -3163,7 +3520,7 @@ async function fetchRiskQuoteIx(connection, wallet, rangeApiKey) {
3163
3520
  }
3164
3521
  const feed = {
3165
3522
  name: "Risk Score",
3166
- jobs: [buildRangeRiskScoreJob(OracleJob, wallet.toBase58())],
3523
+ jobs: [buildRangeRiskScoreJob(OracleJob, wallet)],
3167
3524
  minJobResponses: 1,
3168
3525
  minOracleSamples: 1,
3169
3526
  maxJobRangePct: 100
@@ -3177,8 +3534,8 @@ async function fetchRiskQuoteIx(connection, wallet, rangeApiKey) {
3177
3534
  // Must be at transaction index 0 for on-chain verification
3178
3535
  });
3179
3536
  return {
3180
- instruction: sigVerifyIx,
3181
- queue: queue.pubkey
3537
+ instruction: fromLegacyTransactionInstruction(sigVerifyIx),
3538
+ queue: toAddress(queue.pubkey)
3182
3539
  };
3183
3540
  }
3184
3541
 
@@ -3222,86 +3579,67 @@ function encodeNoteSimple(note) {
3222
3579
  }
3223
3580
 
3224
3581
  // src/wallet/adapter.ts
3225
- import {
3226
- Keypair as Keypair2
3227
- } from "@solana/web3.js";
3228
- function validateWalletConnected(wallet) {
3229
- if (wallet instanceof Keypair2) {
3230
- return;
3231
- }
3232
- if (!wallet.publicKey) {
3233
- throw new CloakError(
3234
- "Wallet not connected. Please connect your wallet first.",
3235
- "wallet",
3236
- false
3237
- );
3582
+ function validateWalletConnected(signer) {
3583
+ if (!signer || !isTransactionSigner(signer)) {
3584
+ throw new CloakError("Wallet not connected. Please connect your wallet first.", "wallet", false);
3238
3585
  }
3239
3586
  }
3240
- function getPublicKey(wallet) {
3241
- if (wallet instanceof Keypair2) {
3242
- return wallet.publicKey;
3243
- }
3244
- if (!wallet.publicKey) {
3245
- throw new CloakError(
3246
- "Wallet not connected",
3247
- "wallet",
3248
- false
3249
- );
3250
- }
3251
- return wallet.publicKey;
3587
+ function getPublicKey(signer) {
3588
+ validateWalletConnected(signer);
3589
+ return signer.address;
3252
3590
  }
3253
- async function sendTransaction(transaction, wallet, connection, options) {
3591
+ async function sendTransaction(transaction, connection, options) {
3254
3592
  assertAllowedRpcConnection(connection);
3255
- if (wallet instanceof Keypair2) {
3256
- return await connection.sendTransaction(transaction, [wallet], options);
3257
- }
3258
- if (wallet.sendTransaction) {
3259
- return await wallet.sendTransaction(transaction, connection, options);
3260
- } else if (wallet.signTransaction) {
3261
- const signed = await wallet.signTransaction(transaction);
3262
- return await connection.sendRawTransaction(signed.serialize(), options);
3263
- } else {
3264
- throw new CloakError(
3265
- "Wallet does not support transaction signing",
3266
- "wallet",
3267
- false
3268
- );
3269
- }
3593
+ return sendRawTransaction(connection, transactionBytes(transaction), options);
3270
3594
  }
3271
- async function signTransaction(transaction, wallet) {
3272
- if (wallet instanceof Keypair2) {
3273
- transaction.sign(wallet);
3274
- return transaction;
3275
- }
3276
- if (!wallet.signTransaction) {
3277
- throw new CloakError(
3278
- "Wallet does not support transaction signing",
3279
- "wallet",
3280
- false
3281
- );
3282
- }
3283
- return await wallet.signTransaction(transaction);
3284
- }
3285
- function keypairToAdapter(keypair) {
3286
- return {
3287
- publicKey: keypair.publicKey,
3288
- signTransaction: async (tx) => {
3289
- tx.sign(keypair);
3290
- return tx;
3291
- },
3292
- signAllTransactions: async (txs) => {
3293
- txs.forEach((tx) => tx.sign(keypair));
3294
- return txs;
3295
- }
3296
- };
3595
+
3596
+ // src/solana/instructions.ts
3597
+ import { AccountRole } from "@solana/kit";
3598
+ function accountMeta(address2, options = {}) {
3599
+ const { signer = false, writable: writable2 = false } = options;
3600
+ const role = signer ? writable2 ? AccountRole.WRITABLE_SIGNER : AccountRole.READONLY_SIGNER : writable2 ? AccountRole.WRITABLE : AccountRole.READONLY;
3601
+ return { address: address2, role };
3602
+ }
3603
+ function readonly(address2) {
3604
+ return { address: address2, role: AccountRole.READONLY };
3605
+ }
3606
+ function writable(address2) {
3607
+ return { address: address2, role: AccountRole.WRITABLE };
3608
+ }
3609
+ function writableSigner(address2) {
3610
+ return { address: address2, role: AccountRole.WRITABLE_SIGNER };
3611
+ }
3612
+ function programInstruction(programAddress, accounts, data) {
3613
+ return { programAddress, accounts: [...accounts], data };
3614
+ }
3615
+ var THIS_INSTRUCTION = 65535;
3616
+ var ED25519_HEADER_BYTES = 16;
3617
+ function ed25519VerifyInstruction(params) {
3618
+ const { publicKey, message, signature } = params;
3619
+ if (publicKey.length !== 32) throw new Error(`Public key must be 32 bytes, got ${publicKey.length}`);
3620
+ if (signature.length !== 64) throw new Error(`Signature must be 64 bytes, got ${signature.length}`);
3621
+ const index = params.instructionIndex ?? THIS_INSTRUCTION;
3622
+ const publicKeyOffset = ED25519_HEADER_BYTES;
3623
+ const signatureOffset = publicKeyOffset + publicKey.length;
3624
+ const messageOffset = signatureOffset + signature.length;
3625
+ const data = new Uint8Array(messageOffset + message.length);
3626
+ const view = new DataView(data.buffer);
3627
+ data[0] = 1;
3628
+ data[1] = 0;
3629
+ view.setUint16(2, signatureOffset, true);
3630
+ view.setUint16(4, index, true);
3631
+ view.setUint16(6, publicKeyOffset, true);
3632
+ view.setUint16(8, index, true);
3633
+ view.setUint16(10, messageOffset, true);
3634
+ view.setUint16(12, message.length, true);
3635
+ view.setUint16(14, index, true);
3636
+ data.set(publicKey, publicKeyOffset);
3637
+ data.set(signature, signatureOffset);
3638
+ data.set(message, messageOffset);
3639
+ return { programAddress: ED25519_PROGRAM_ADDRESS, accounts: [], data };
3297
3640
  }
3298
3641
 
3299
3642
  // src/program/instructions.ts
3300
- import {
3301
- PublicKey as PublicKey7,
3302
- SystemProgram as SystemProgram2,
3303
- TransactionInstruction
3304
- } from "@solana/web3.js";
3305
3643
  function createDepositInstruction(params) {
3306
3644
  if (params.commitment.length !== 32) {
3307
3645
  throw new Error(
@@ -3323,33 +3661,33 @@ function createDepositInstruction(params) {
3323
3661
  data.set(discriminant, 0);
3324
3662
  data.set(amountBytes, 1);
3325
3663
  data.set(params.commitment, 9);
3326
- return new TransactionInstruction({
3327
- programId: params.programId,
3328
- keys: [
3664
+ return programInstruction(
3665
+ params.programId,
3666
+ [
3329
3667
  // Account 0: Payer (signer, writable) - pays for transaction
3330
- { pubkey: params.payer, isSigner: true, isWritable: true },
3668
+ writableSigner(params.payer),
3331
3669
  // Account 1: Pool (writable) - receives SOL
3332
- { pubkey: params.pool, isSigner: false, isWritable: true },
3670
+ writable(params.pool),
3333
3671
  // Account 2: System Program (readonly) - for transfers
3334
- { pubkey: SystemProgram2.programId, isSigner: false, isWritable: false },
3672
+ readonly(SYSTEM_PROGRAM_ADDRESS),
3335
3673
  // Account 3: Merkle Tree (writable) - stores on-chain Merkle tree
3336
- { pubkey: params.merkleTree, isSigner: false, isWritable: true }
3674
+ writable(params.merkleTree)
3337
3675
  ],
3338
- data: Buffer.from(data)
3339
- });
3676
+ data
3677
+ );
3340
3678
  }
3341
3679
  function validateDepositParams(params) {
3342
- if (!(params.programId instanceof PublicKey7)) {
3343
- throw new Error("programId must be a PublicKey");
3680
+ if (typeof params.programId !== "string" || !isAddress(params.programId)) {
3681
+ throw new Error("programId must be an address");
3344
3682
  }
3345
- if (!(params.payer instanceof PublicKey7)) {
3346
- throw new Error("payer must be a PublicKey");
3683
+ if (typeof params.payer !== "string" || !isAddress(params.payer)) {
3684
+ throw new Error("payer must be an address");
3347
3685
  }
3348
- if (!(params.pool instanceof PublicKey7)) {
3349
- throw new Error("pool must be a PublicKey");
3686
+ if (typeof params.pool !== "string" || !isAddress(params.pool)) {
3687
+ throw new Error("pool must be an address");
3350
3688
  }
3351
- if (!(params.merkleTree instanceof PublicKey7)) {
3352
- throw new Error("merkleTree must be a PublicKey");
3689
+ if (typeof params.merkleTree !== "string" || !isAddress(params.merkleTree)) {
3690
+ throw new Error("merkleTree must be an address");
3353
3691
  }
3354
3692
  if (typeof params.amount !== "number" || params.amount <= 0) {
3355
3693
  throw new Error("amount must be a positive number");
@@ -3404,7 +3742,7 @@ async function readMerkleTreeState(connection, merkleTreePDA, forceConfirmed = f
3404
3742
  const rootUrl = new URL(relayUrl);
3405
3743
  rootUrl.pathname = rootUrl.pathname.replace(/\/$/, "") + "/merkle-root";
3406
3744
  if (mint) {
3407
- rootUrl.searchParams.set("mint", mint.toBase58());
3745
+ rootUrl.searchParams.set("mint", mint);
3408
3746
  }
3409
3747
  const controller = new AbortController();
3410
3748
  const timeoutId = globalThis.setTimeout(
@@ -3425,13 +3763,11 @@ async function readMerkleTreeState(connection, merkleTreePDA, forceConfirmed = f
3425
3763
  } catch (e) {
3426
3764
  }
3427
3765
  }
3428
- const commitment = forceConfirmed ? "confirmed" : void 0;
3429
- const accountInfo = await connection.getAccountInfo(merkleTreePDA, {
3430
- commitment
3431
- });
3766
+ const commitment = "confirmed";
3767
+ const accountInfo = await fetchAccountBytes(connection, merkleTreePDA, commitment);
3432
3768
  if (!accountInfo) {
3433
3769
  throw new Error(
3434
- `Merkle tree account not found at ${merkleTreePDA.toBase58()} on RPC ${connection.rpcEndpoint}. Ensure the shield pool is initialized for this program/mint on the same chain.`
3770
+ `Merkle tree account not found at ${merkleTreePDA} on RPC ${rpcEndpoint(connection)}. Ensure the shield pool is initialized for this program/mint on the same chain.`
3435
3771
  );
3436
3772
  }
3437
3773
  const data = accountInfo.data;
@@ -3709,8 +4045,10 @@ async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
3709
4045
  return MerkleTree.create(height, commitments);
3710
4046
  }
3711
4047
 
4048
+ // src/config/transaction-version.ts
4049
+ var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
4050
+
3712
4051
  // src/relay/client.ts
3713
- import { PublicKey as PublicKey8 } from "@solana/web3.js";
3714
4052
  import _bs58 from "bs58";
3715
4053
 
3716
4054
  // src/notes/refund-leaf.ts
@@ -3819,9 +4157,6 @@ function isBrowserLike() {
3819
4157
  return typeof globalThis !== "undefined" && (typeof globalThis.window !== "undefined" || typeof globalThis.document !== "undefined");
3820
4158
  }
3821
4159
 
3822
- // src/config/transaction-version.ts
3823
- var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
3824
-
3825
4160
  // src/relay/client.ts
3826
4161
  var bs58 = _bs58.default || _bs58;
3827
4162
  var TRANSACT_TAG = 0;
@@ -3830,7 +4165,7 @@ var CLOSE_SWAP_STATE_TAG = 13;
3830
4165
  var CLOSE_SWAP_STATE_PHASE1_PAYLOAD_LEN = 40;
3831
4166
  var CLOSE_SWAP_STATE_PHASE1_WIRE_LEN = 1 + CLOSE_SWAP_STATE_PHASE1_PAYLOAD_LEN;
3832
4167
  var CLOSE_SWAP_STATE_COMMITMENT_END = 1 + 32;
3833
- var NATIVE_SOL_MINT2 = new PublicKey8("So11111111111111111111111111111111111111112");
4168
+ var NATIVE_SOL_MINT2 = address("So11111111111111111111111111111111111111112");
3834
4169
  var PROOF_LEN = 256;
3835
4170
  var PUBLIC_INPUTS_LEN = 264;
3836
4171
  var COMMITMENTS_OFFSET = 168;
@@ -3886,7 +4221,7 @@ async function fetchCommitments(relayUrl, options = {}) {
3886
4221
  }
3887
4222
  }
3888
4223
  if (options.mint) {
3889
- url.searchParams.set("mint", options.mint.toBase58());
4224
+ url.searchParams.set("mint", options.mint);
3890
4225
  }
3891
4226
  if (options.fromIndex !== void 0) {
3892
4227
  url.searchParams.set("from_index", String(options.fromIndex));
@@ -3985,7 +4320,7 @@ function extractCommitmentsFromInstruction(data, expectedMint) {
3985
4320
  "extractCommitmentsFromInstruction: encountered a CloseSwapState refund leaf but no expectedMint was supplied, so it cannot be established whether the leaf belongs to this tree. Pass the pool mint."
3986
4321
  );
3987
4322
  }
3988
- if (!expectedMint.equals(NATIVE_SOL_MINT2)) return [];
4323
+ if (expectedMint !== NATIVE_SOL_MINT2) return [];
3989
4324
  const commitment = data.slice(1, CLOSE_SWAP_STATE_COMMITMENT_END);
3990
4325
  return isAllZero(commitment) ? [] : [commitment];
3991
4326
  }
@@ -4015,7 +4350,7 @@ async function buildMerkleTreeFromChain(connection, programId, merkleTree, onPro
4015
4350
  let before;
4016
4351
  onProgress?.("Fetching program signatures from chain...");
4017
4352
  while (true) {
4018
- const batch = await connection.getSignaturesForAddress(programId, {
4353
+ const batch = await fetchSignaturesForAddress(connection, programId, {
4019
4354
  before,
4020
4355
  limit: 1e3
4021
4356
  });
@@ -4026,22 +4361,22 @@ async function buildMerkleTreeFromChain(connection, programId, merkleTree, onPro
4026
4361
  }
4027
4362
  signatures.reverse();
4028
4363
  const commitments = [];
4029
- const programIdBase58 = programId.toBase58();
4364
+ const programIdBase58 = programId;
4030
4365
  for (let i = 0; i < signatures.length; i++) {
4031
4366
  if (i % 100 === 0) {
4032
4367
  onProgress?.(`Processing transactions... ${i}/${signatures.length}`);
4033
4368
  }
4034
4369
  const signature = signatures[i];
4035
- const tx = await connection.getParsedTransaction(signature, {
4370
+ const tx = await fetchParsedTransaction(connection, signature, {
4036
4371
  maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION,
4037
4372
  commitment: "confirmed"
4038
4373
  });
4039
4374
  if (!tx || tx.meta?.err) continue;
4040
4375
  for (const ix of tx.transaction.message.instructions) {
4041
- if (!("programId" in ix) || !("data" in ix)) continue;
4042
- if (ix.programId.toBase58() !== programIdBase58) continue;
4376
+ if (!isRawParsedInstruction(ix)) continue;
4377
+ if (ix.programId !== programIdBase58) continue;
4043
4378
  const accounts = ix.accounts;
4044
- if (!accounts || !accounts.some((a) => a.equals(merkleTree))) continue;
4379
+ if (!accounts || !accounts.some((a) => a === merkleTree)) continue;
4045
4380
  const data = bs58.decode(ix.data);
4046
4381
  const extracted = extractCommitmentsFromInstruction(data, mint);
4047
4382
  for (const commitment of extracted) {
@@ -4119,25 +4454,23 @@ async function preflightCheck(relayUrl, rootHex) {
4119
4454
  }
4120
4455
 
4121
4456
  // src/flows/transact.ts
4457
+ import { createNoopSigner as createNoopSigner2, isKeyPairSigner, isSignerRole } from "@solana/kit";
4458
+ import {
4459
+ COMPUTE_BUDGET_PROGRAM_ADDRESS,
4460
+ getSetComputeUnitLimitInstruction,
4461
+ getSetComputeUnitPriceInstruction
4462
+ } from "@solana-program/compute-budget";
4122
4463
  import {
4123
- PublicKey as PublicKey10,
4124
- Transaction as Transaction3,
4125
- TransactionInstruction as TransactionInstruction2,
4126
- sendAndConfirmTransaction,
4127
- SystemProgram as SystemProgram3,
4128
- ComputeBudgetProgram,
4129
- SYSVAR_INSTRUCTIONS_PUBKEY,
4130
- SYSVAR_SLOT_HASHES_PUBKEY,
4131
- VersionedTransaction,
4132
- TransactionMessage,
4133
- AddressLookupTableProgram,
4134
- Ed25519Program
4135
- } from "@solana/web3.js";
4464
+ fetchMaybeAddressLookupTable,
4465
+ findAddressLookupTablePda,
4466
+ getCreateLookupTableInstruction,
4467
+ getExtendLookupTableInstruction
4468
+ } from "@solana-program/address-lookup-table";
4136
4469
  import {
4137
- createAssociatedTokenAccountInstruction,
4138
- getAssociatedTokenAddressSync,
4139
- TOKEN_PROGRAM_ID
4140
- } from "@solana/spl-token";
4470
+ findAssociatedTokenPda,
4471
+ getCreateAssociatedTokenInstruction,
4472
+ TOKEN_PROGRAM_ADDRESS
4473
+ } from "@solana-program/token";
4141
4474
  import * as snarkjs from "snarkjs";
4142
4475
 
4143
4476
  // src/notes/chain-note.ts
@@ -4363,7 +4696,7 @@ function chainNoteFromBase64(base64) {
4363
4696
  }
4364
4697
 
4365
4698
  // src/notes/delivery-note.ts
4366
- import nacl5 from "tweetnacl";
4699
+ import nacl4 from "tweetnacl";
4367
4700
  var RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN = 32;
4368
4701
  var RECIPIENT_DELIVERY_NONCE_LEN = 24;
4369
4702
  var RECIPIENT_DELIVERY_PLAINTEXT_LEN = 40;
@@ -4414,10 +4747,10 @@ function encodeRecipientDeliveryNote(note, recipientViewingPublicKey) {
4414
4747
  const plaintext = new Uint8Array(RECIPIENT_DELIVERY_PLAINTEXT_LEN);
4415
4748
  writeU64LE2(plaintext, 0, note.amount);
4416
4749
  writeU256BE2(plaintext, 8, note.blinding);
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);
4750
+ const ephemeral = nacl4.box.keyPair();
4751
+ const shared = nacl4.box.before(recipientViewingPublicKey, ephemeral.secretKey);
4752
+ const nonce = nacl4.randomBytes(nacl4.secretbox.nonceLength);
4753
+ const ciphertext = nacl4.secretbox(plaintext, nonce, shared);
4421
4754
  if (ciphertext.length !== RECIPIENT_DELIVERY_CIPHERTEXT_LEN) {
4422
4755
  throw new Error(
4423
4756
  `delivery ciphertext must be ${RECIPIENT_DELIVERY_CIPHERTEXT_LEN} bytes, got ${ciphertext.length}`
@@ -4443,8 +4776,8 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
4443
4776
  const ciphertext = envelope.slice(
4444
4777
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
4445
4778
  );
4446
- const shared = nacl5.box.before(ephemeralPk, viewingSecretKey);
4447
- const plaintext = nacl5.secretbox.open(ciphertext, nonce, shared);
4779
+ const shared = nacl4.box.before(ephemeralPk, viewingSecretKey);
4780
+ const plaintext = nacl4.secretbox.open(ciphertext, nonce, shared);
4448
4781
  if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
4449
4782
  return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
4450
4783
  } catch {
@@ -4502,7 +4835,6 @@ function parseDeliveryCarrierMemo(data) {
4502
4835
 
4503
4836
  // src/notes/swap-refund.ts
4504
4837
  import { blake3 as blake33 } from "@noble/hashes/blake3";
4505
- import { PublicKey as PublicKey9 } from "@solana/web3.js";
4506
4838
  import _bs582 from "bs58";
4507
4839
  var bs582 = _bs582.default || _bs582;
4508
4840
  var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
@@ -4646,11 +4978,8 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
4646
4978
  }
4647
4979
  const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
4648
4980
  const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
4649
- const programIdBase58 = programId.toBase58();
4650
- const [pool] = PublicKey9.findProgramAddressSync(
4651
- [Buffer.from("pool"), poolMint.toBuffer()],
4652
- programId
4653
- );
4981
+ const programIdBase58 = programId;
4982
+ const [pool] = await findProgramAddress(["pool", addressBytes(poolMint)], programId);
4654
4983
  onStatus?.("Fetching program signatures...");
4655
4984
  const signatures = [];
4656
4985
  let before;
@@ -4658,7 +4987,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
4658
4987
  for (; ; ) {
4659
4988
  const want = limit > 0 ? Math.min(limit - signatures.length, pageSize) : pageSize;
4660
4989
  if (want <= 0) break;
4661
- const page = await connection.getSignaturesForAddress(programId, { before, limit: want });
4990
+ const page = await fetchSignaturesForAddress(connection, programId, { before, limit: want });
4662
4991
  if (!Array.isArray(page) || page.length === 0) break;
4663
4992
  let stop = false;
4664
4993
  for (const entry of page) {
@@ -4679,7 +5008,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
4679
5008
  const fetched = await Promise.all(
4680
5009
  batch.map(async (signature) => {
4681
5010
  try {
4682
- return await connection.getTransaction(signature, {
5011
+ return await fetchTransactionJson(connection, signature, {
4683
5012
  commitment: "confirmed",
4684
5013
  maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
4685
5014
  });
@@ -4698,11 +5027,11 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
4698
5027
  if (data[0] !== TRANSACT_SWAP_TAG2 || data.length < MIN_TRANSACT_SWAP_LEN) continue;
4699
5028
  const nullifier = data.slice(NULLIFIER_0_OFFSET, NULLIFIER_0_OFFSET + 32);
4700
5029
  if (nullifier.length !== 32) continue;
4701
- const [swapState] = PublicKey9.findProgramAddressSync(
4702
- [Buffer.from("swap_state"), pool.toBuffer(), Buffer.from(nullifier)],
5030
+ const [swapState] = await findProgramAddress(
5031
+ ["swap_state", addressBytes(pool), new Uint8Array(nullifier)],
4703
5032
  programId
4704
5033
  );
4705
- const key = swapState.toBase58();
5034
+ const key = swapState;
4706
5035
  if (!nullifierBySwapState.has(key)) nullifierBySwapState.set(key, { nullifier, signature });
4707
5036
  }
4708
5037
  const logs = tx.meta?.logMessages;
@@ -4923,7 +5252,7 @@ async function matchChangeNote(params) {
4923
5252
 
4924
5253
  // src/flows/transact.ts
4925
5254
  import { buildPoseidon as buildPoseidon2 } from "circomlibjs";
4926
- import nacl6 from "tweetnacl";
5255
+ import nacl5 from "tweetnacl";
4927
5256
 
4928
5257
  // src/proving/artifacts.ts
4929
5258
  import { sha256 as sha2564 } from "@noble/hashes/sha2";
@@ -5241,7 +5570,7 @@ function isRetryableRelayStatus(status) {
5241
5570
  }
5242
5571
  function isBlockhashExpiryError(error) {
5243
5572
  const message = error instanceof Error ? error.message : String(error);
5244
- return /block height exceeded/i.test(message) || /transactionexpiredblockheightexceedederror/i.test(message) || /blockhash not found/i.test(message) || /signature .* has expired/i.test(message);
5573
+ return /block height exceeded/i.test(message) || /transactionexpiredblockheightexceedederror/i.test(message) || /blockhash not found/i.test(message) || /blockhash expired/i.test(message) || /signature .* has expired/i.test(message);
5245
5574
  }
5246
5575
  function isTransientTransportError(error) {
5247
5576
  const message = error instanceof Error ? error.message : String(error);
@@ -5259,7 +5588,7 @@ function nearTipFallbackMaxDistance(connection) {
5259
5588
  if (Number.isFinite(override)) {
5260
5589
  return Math.max(0, Math.floor(override));
5261
5590
  }
5262
- return isLocalRpcEndpoint(connection.rpcEndpoint) ? NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_LOCAL_RPC : NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_DEFAULT;
5591
+ return isLocalRpcEndpoint(rpcEndpoint(connection) ?? "") ? NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_LOCAL_RPC : NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_DEFAULT;
5263
5592
  }
5264
5593
  function shouldUseRelayMerkleByDefault(connection) {
5265
5594
  const forceRelayMerkle = typeof process !== "undefined" && process.env ? process.env.CLOAK_FORCE_RELAY_MERKLE_TREE : void 0;
@@ -5270,7 +5599,7 @@ function shouldUseRelayMerkleByDefault(connection) {
5270
5599
  if (disableRelayMerkle === "1" || disableRelayMerkle === "true") {
5271
5600
  return false;
5272
5601
  }
5273
- return !isLocalRpcEndpoint(connection.rpcEndpoint);
5602
+ return !isLocalRpcEndpoint(rpcEndpoint(connection) ?? "");
5274
5603
  }
5275
5604
  async function fetchAltAddressesFromRelayHealth(relayUrl) {
5276
5605
  try {
@@ -5285,13 +5614,13 @@ async function fetchAltAddressesFromRelayHealth(relayUrl) {
5285
5614
  }
5286
5615
  async function fetchSupplementalAltFromRelay(relayUrl, params) {
5287
5616
  const body = JSON.stringify({
5288
- mint: params.mint.toBase58(),
5617
+ mint: params.mint,
5289
5618
  nullifiers: [
5290
5619
  Buffer.from(params.nullifiers[0]).toString("hex"),
5291
5620
  Buffer.from(params.nullifiers[1]).toString("hex")
5292
5621
  ],
5293
5622
  bind0: Buffer.from(params.bind0).toString("hex"),
5294
- depositor: params.depositor.toBase58()
5623
+ depositor: params.depositor
5295
5624
  });
5296
5625
  let response;
5297
5626
  try {
@@ -5324,38 +5653,36 @@ async function fetchSupplementalAltFromRelay(relayUrl, params) {
5324
5653
  if (typeof table !== "string" || table.length === 0) {
5325
5654
  throw new Error("Supplemental ALT response is missing a 'table' address");
5326
5655
  }
5327
- try {
5328
- return new PublicKey10(table);
5329
- } catch {
5656
+ if (!isAddress(table)) {
5330
5657
  throw new Error(`Supplemental ALT response 'table' is not a valid public key: ${table}`);
5331
5658
  }
5659
+ return address(table);
5332
5660
  }
5333
5661
  async function resolveRelaySupplementalAlt(connection, table, expected, pollOpts) {
5334
5662
  const pollIntervalMs = pollOpts?.pollIntervalMs ?? 150;
5335
5663
  const timeoutMs = pollOpts?.timeoutMs ?? 5e3;
5336
- const expectedB58 = expected.map((pk) => pk.toBase58());
5337
5664
  const deadline = Date.now() + timeoutMs;
5338
5665
  for (; ; ) {
5339
- const result = await connection.getAddressLookupTable(table, { commitment: "confirmed" });
5340
- if (!result.value) {
5341
- throw new Error(`Supplemental ALT ${table.toBase58()} could not be fetched from the RPC.`);
5666
+ const result = await fetchMaybeAddressLookupTable(connection, table, { commitment: "confirmed" });
5667
+ if (!result.exists) {
5668
+ throw new Error(`Supplemental ALT ${table} could not be fetched from the RPC.`);
5342
5669
  }
5343
- const account = result.value;
5344
- const present = new Set(account.state.addresses.map((a) => a.toBase58()));
5345
- const missing = expectedB58.filter((addr) => !present.has(addr));
5670
+ const account = result.data;
5671
+ const present = new Set(account.addresses);
5672
+ const missing = expected.filter((addr) => !present.has(addr));
5346
5673
  if (missing.length === 0) {
5347
- const currentSlot = await connection.getSlot("confirmed");
5348
- if (account.state.lastExtendedSlot < currentSlot) {
5349
- return account;
5674
+ const currentSlot = await fetchSlot(connection, "confirmed");
5675
+ if (Number(account.lastExtendedSlot) < currentSlot) {
5676
+ return { address: table, addresses: account.addresses };
5350
5677
  }
5351
5678
  if (Date.now() >= deadline) {
5352
5679
  throw new Error(
5353
- `Supplemental ALT ${table.toBase58()} did not become resolvable within ${timeoutMs}ms (lastExtendedSlot=${account.state.lastExtendedSlot} never fell behind current slot=${currentSlot}).`
5680
+ `Supplemental ALT ${table} did not become resolvable within ${timeoutMs}ms (lastExtendedSlot=${account.lastExtendedSlot} never fell behind current slot=${currentSlot}).`
5354
5681
  );
5355
5682
  }
5356
5683
  } else if (Date.now() >= deadline) {
5357
5684
  throw new Error(
5358
- `Supplemental ALT ${table.toBase58()} is still missing expected address(es) after ${timeoutMs}ms: ` + missing.join(", ")
5685
+ `Supplemental ALT ${table} is still missing expected address(es) after ${timeoutMs}ms: ` + missing.join(", ")
5359
5686
  );
5360
5687
  }
5361
5688
  await sleep2(pollIntervalMs);
@@ -5384,7 +5711,7 @@ async function resolveAddressLookupTableAccounts(connection, relayUrl, altAddres
5384
5711
  if (altAddresses.length === 0) {
5385
5712
  return void 0;
5386
5713
  }
5387
- const cacheKey = `${connection.rpcEndpoint}|${altAddresses.join(",")}`;
5714
+ const cacheKey = `${rpcEndpoint(connection) ?? ""}|${altAddresses.join(",")}`;
5388
5715
  const cached = _resolvedAltAccountsCache.get(cacheKey);
5389
5716
  if (cached && cached.length > 0) {
5390
5717
  return cached;
@@ -5393,9 +5720,9 @@ async function resolveAddressLookupTableAccounts(connection, relayUrl, altAddres
5393
5720
  const fetched = await Promise.all(
5394
5721
  altAddresses.map(async (addr) => {
5395
5722
  try {
5396
- const pubkey = new PublicKey10(addr);
5397
- const result = await connection.getAddressLookupTable(pubkey);
5398
- return result.value ?? null;
5723
+ const table = address(addr);
5724
+ const result = await fetchMaybeAddressLookupTable(connection, table);
5725
+ return result.exists ? { address: table, addresses: result.data.addresses } : null;
5399
5726
  } catch {
5400
5727
  return null;
5401
5728
  }
@@ -5483,24 +5810,21 @@ function calculateConfiguredProtocolFee(amount, config) {
5483
5810
  return total;
5484
5811
  }
5485
5812
  async function readLiveProtocolFee(connection, programId, mint, amount, requireSwapOpen = false) {
5486
- const [poolConfigPda] = PublicKey10.findProgramAddressSync(
5487
- [Buffer.from("pool_config"), mint.toBuffer()],
5488
- programId
5489
- );
5490
- const account = await connection.getAccountInfo(poolConfigPda, "confirmed");
5813
+ const [poolConfigPda] = await findProgramAddress(["pool_config", addressBytes(mint)], programId);
5814
+ const account = await fetchAccountBytes(connection, poolConfigPda, "confirmed");
5491
5815
  if (!account) {
5492
5816
  throw new Error(
5493
- `PoolConfig ${poolConfigPda.toBase58()} is missing; refusing to build a fee-bearing proof`
5817
+ `PoolConfig ${poolConfigPda} is missing; refusing to build a fee-bearing proof`
5494
5818
  );
5495
5819
  }
5496
- if (!account.owner.equals(programId)) {
5497
- throw new Error(`PoolConfig ${poolConfigPda.toBase58()} has the wrong owner`);
5820
+ if (account.owner !== programId) {
5821
+ throw new Error(`PoolConfig ${poolConfigPda} has the wrong owner`);
5498
5822
  }
5499
5823
  const config = decodePoolProtocolFeeConfig(account.data);
5500
5824
  if (requireSwapOpen && config.swapsPaused) {
5501
5825
  throw new Error("Swap intake is paused for this pool");
5502
5826
  }
5503
- const defaultFixed = mint.equals(NATIVE_SOL_MINT) ? BigInt(5e6) : BigInt(45e4);
5827
+ const defaultFixed = mint === NATIVE_SOL_MINT ? BigInt(5e6) : BigInt(45e4);
5504
5828
  if (config.fixedFee > defaultFixed * BigInt(20)) {
5505
5829
  throw new Error("PoolConfig fixed fee exceeds the protocol cap");
5506
5830
  }
@@ -5538,15 +5862,15 @@ function assertInputMints(inputUtxos, expectedMint) {
5538
5862
  if (funded.length === 0) return;
5539
5863
  const first = funded[0].mintAddress;
5540
5864
  for (const utxo of funded) {
5541
- if (!utxo.mintAddress.equals(first)) {
5865
+ if (utxo.mintAddress !== first) {
5542
5866
  throw new Error(
5543
- `Input notes span more than one mint (${first.toBase58()} and ${utxo.mintAddress.toBase58()}). Every pool holds a single mint, so this cannot be a valid spend of either. Select notes of one mint.`
5867
+ `Input notes span more than one mint (${first} and ${utxo.mintAddress}). Every pool holds a single mint, so this cannot be a valid spend of either. Select notes of one mint.`
5544
5868
  );
5545
5869
  }
5546
5870
  }
5547
- if (expectedMint && !first.equals(expectedMint)) {
5871
+ if (expectedMint && first !== expectedMint) {
5548
5872
  throw new Error(
5549
- `Input notes are ${first.toBase58()} but this transaction expects ${expectedMint.toBase58()}. The notes decide which pool is spent, so proceeding would move the wrong asset \u2014 refusing. This usually means note selection ignored the mint.`
5873
+ `Input notes are ${first} but this transaction expects ${expectedMint}. The notes decide which pool is spent, so proceeding would move the wrong asset \u2014 refusing. This usually means note selection ignored the mint.`
5550
5874
  );
5551
5875
  }
5552
5876
  }
@@ -5601,7 +5925,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
5601
5925
  );
5602
5926
  }
5603
5927
  const viewingKeyHex = toHex(nk);
5604
- const cacheKey = `${relayUrl}|${userPubkey.toBase58()}|${viewingKeyHex}`;
5928
+ const cacheKey = `${relayUrl}|${userPubkey}|${viewingKeyHex}`;
5605
5929
  if (_registeredViewingKeys.has(cacheKey)) {
5606
5930
  return;
5607
5931
  }
@@ -5629,7 +5953,7 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
5629
5953
  method: "POST",
5630
5954
  headers: { "Content-Type": "application/json" },
5631
5955
  body: JSON.stringify({
5632
- user_pubkey: userPubkey.toBase58(),
5956
+ user_pubkey: userPubkey,
5633
5957
  viewing_key: viewingKeyHex
5634
5958
  })
5635
5959
  });
@@ -5641,7 +5965,7 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
5641
5965
  }
5642
5966
  const challenge = parseStrictViewingKeyChallenge(
5643
5967
  await challengeResponse.json(),
5644
- userPubkey.toBase58(),
5968
+ userPubkey,
5645
5969
  viewingKeyHex
5646
5970
  );
5647
5971
  let signatureBase64;
@@ -5651,21 +5975,21 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
5651
5975
  const sig = await options.signMessage(messageBytes);
5652
5976
  signatureBase64 = Buffer.from(sig).toString("base64");
5653
5977
  } else if (options.depositorKeypair) {
5654
- const sig = nacl6.sign.detached(messageBytes, options.depositorKeypair.secretKey);
5978
+ const sig = await signMessageBytes(options.depositorKeypair, messageBytes);
5979
+ signatureBase64 = Buffer.from(sig).toString("base64");
5980
+ } else if (options.signer && isMessageSigner(options.signer)) {
5981
+ const sig = await signMessageBytes(options.signer, messageBytes);
5655
5982
  signatureBase64 = Buffer.from(sig).toString("base64");
5656
- } else if (options.signAuthTransaction) {
5983
+ } else if (options.signer) {
5657
5984
  onProgress?.(
5658
5985
  "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
5986
  );
5660
- const signed = await signRelayAuthPayload(
5661
- { walletPublicKey: userPubkey, signAuthTransaction: options.signAuthTransaction },
5662
- messageBytes
5663
- );
5987
+ const signed = await signRelayAuthPayload(options.signer, messageBytes);
5664
5988
  signatureBase64 = Buffer.from(signed.signature).toString("base64");
5665
5989
  authMode = signed.mode;
5666
5990
  } else {
5667
5991
  throw new Error(
5668
- "Viewing key registration is mandatory: signMessage or signAuthTransaction (wallet) or depositorKeypair is required."
5992
+ "Viewing key registration is mandatory: signMessage or signer (wallet) or depositorKeypair is required."
5669
5993
  );
5670
5994
  }
5671
5995
  onProgress?.("Registering viewing key...");
@@ -5673,7 +5997,7 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
5673
5997
  method: "POST",
5674
5998
  headers: { "Content-Type": "application/json" },
5675
5999
  body: JSON.stringify({
5676
- user_pubkey: userPubkey.toBase58(),
6000
+ user_pubkey: userPubkey,
5677
6001
  viewing_key: viewingKeyHex,
5678
6002
  nonce: challenge.nonce,
5679
6003
  signature: signatureBase64,
@@ -5771,14 +6095,11 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
5771
6095
  var TRANSACT_DISCRIMINATOR = 0;
5772
6096
  var RANGE_QUOTE_TAG_DEPOSIT = 1;
5773
6097
  function deriveRiskNoncePDA(programId, nonce) {
5774
- return PublicKey10.findProgramAddressSync(
5775
- [Buffer.from("risk_nonce"), Buffer.from(nonce)],
5776
- programId
5777
- );
6098
+ return findProgramAddress(["risk_nonce", new Uint8Array(nonce)], programId);
5778
6099
  }
5779
6100
  function extractDepositNonceFromEd25519Ix(ix) {
5780
6101
  try {
5781
- const data = Buffer.from(ix.data);
6102
+ const data = Buffer.from(ix.data ?? new Uint8Array());
5782
6103
  if (data.length < 16) return null;
5783
6104
  const msgOffset = data.readUInt16LE(10);
5784
6105
  const msgSize = data.readUInt16LE(12);
@@ -5790,14 +6111,11 @@ function extractDepositNonceFromEd25519Ix(ix) {
5790
6111
  }
5791
6112
  }
5792
6113
  function deriveNullifierPDA(programId, poolPDA, nullifier) {
5793
- return PublicKey10.findProgramAddressSync(
5794
- [Buffer.from("nullifier"), poolPDA.toBuffer(), Buffer.from(nullifier)],
5795
- programId
5796
- );
6114
+ return findProgramAddress(["nullifier", addressBytes(poolPDA), new Uint8Array(nullifier)], programId);
5797
6115
  }
5798
- function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkleTreePDA, nullifier0, nullifier1, proofBytes, publicInputsBytes, recipient, enableRiskCheck, encryptedNoteBytes, splAccounts, relayer, relayerFee, riskNonce, protocolMaxFee) {
5799
- const [nullifierPDA0] = deriveNullifierPDA(programId, poolPDA, nullifier0);
5800
- const [nullifierPDA1] = deriveNullifierPDA(programId, poolPDA, nullifier1);
6116
+ async function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkleTreePDA, nullifier0, nullifier1, proofBytes, publicInputsBytes, recipient, enableRiskCheck, encryptedNoteBytes, splAccounts, relayer, relayerFee, riskNonce, protocolMaxFee) {
6117
+ const [nullifierPDA0] = await deriveNullifierPDA(programId, poolPDA, nullifier0);
6118
+ const [nullifierPDA1] = await deriveNullifierPDA(programId, poolPDA, nullifier1);
5801
6119
  const directPublicAmount = readBigInt64LE(publicInputsBytes.slice(32, 40), 0);
5802
6120
  const isDepositData = directPublicAmount > BigInt(0);
5803
6121
  const baseLen = 1 + proofBytes.length + publicInputsBytes.length;
@@ -5823,7 +6141,7 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
5823
6141
  }
5824
6142
  if (!isDepositData) {
5825
6143
  data[offset++] = 3;
5826
- data.set((relayer ?? PublicKey10.default).toBytes(), offset);
6144
+ data.set(addressBytes(relayer ?? DEFAULT_ADDRESS), offset);
5827
6145
  offset += 32;
5828
6146
  writeBigUInt64LE(data, relayerFee ?? BigInt(0), offset);
5829
6147
  offset += 8;
@@ -5841,99 +6159,89 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
5841
6159
  }
5842
6160
  const publicAmountForAccounts = readBigInt64LE(publicInputsBytes.slice(32, 40), 0);
5843
6161
  const accounts = [
5844
- { pubkey: payer, isSigner: true, isWritable: true },
6162
+ accountMeta(payer, { signer: true, writable: true }),
5845
6163
  // 0. payer (signer, writable)
5846
- { pubkey: poolPDA, isSigner: false, isWritable: true },
6164
+ accountMeta(poolPDA, { writable: true }),
5847
6165
  // 1. pool (writable)
5848
- { pubkey: treasuryPDA, isSigner: false, isWritable: true },
6166
+ accountMeta(treasuryPDA, { writable: true }),
5849
6167
  // 2. treasury (writable)
5850
- { pubkey: merkleTreePDA, isSigner: false, isWritable: true },
6168
+ accountMeta(merkleTreePDA, { writable: true }),
5851
6169
  // 3. merkle_tree (writable)
5852
- { pubkey: nullifierPDA0, isSigner: false, isWritable: true },
6170
+ accountMeta(nullifierPDA0, { writable: true }),
5853
6171
  // 4. nullifier PDA 0 (writable)
5854
- { pubkey: nullifierPDA1, isSigner: false, isWritable: true },
6172
+ accountMeta(nullifierPDA1, { writable: true }),
5855
6173
  // 5. nullifier PDA 1 (writable)
5856
- { pubkey: SystemProgram3.programId, isSigner: false, isWritable: false }
6174
+ accountMeta(SYSTEM_PROGRAM_ADDRESS)
5857
6175
  // 6. system_program
5858
6176
  ];
5859
6177
  if (splAccounts) {
5860
- accounts.push({ pubkey: splAccounts.vaultAuthority, isSigner: false, isWritable: false });
5861
- accounts.push({ pubkey: splAccounts.poolVaultAta, isSigner: false, isWritable: true });
5862
- accounts.push({ pubkey: splAccounts.tokenProgram, isSigner: false, isWritable: false });
6178
+ accounts.push(accountMeta(splAccounts.vaultAuthority));
6179
+ accounts.push(accountMeta(splAccounts.poolVaultAta, { writable: true }));
6180
+ accounts.push(accountMeta(splAccounts.tokenProgram));
5863
6181
  if (splAccounts.payerAta) {
5864
6182
  if (enableRiskCheck) {
5865
- accounts.push({ pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6183
+ accounts.push(accountMeta(SYSVAR_INSTRUCTIONS_ADDRESS));
5866
6184
  }
5867
- accounts.push({ pubkey: splAccounts.payerAta, isSigner: false, isWritable: true });
6185
+ accounts.push(accountMeta(splAccounts.payerAta, { writable: true }));
5868
6186
  if (riskNonce) {
5869
- accounts.push({ pubkey: riskNonce, isSigner: false, isWritable: true });
6187
+ accounts.push(accountMeta(riskNonce, { writable: true }));
5870
6188
  }
5871
6189
  } else if (enableRiskCheck && !recipient) {
5872
- accounts.push({ pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6190
+ accounts.push(accountMeta(SYSVAR_INSTRUCTIONS_ADDRESS));
5873
6191
  }
5874
6192
  } else {
5875
6193
  if (recipient) {
5876
- accounts.push({ pubkey: recipient, isSigner: false, isWritable: true });
6194
+ accounts.push(accountMeta(recipient, { writable: true }));
5877
6195
  if (enableRiskCheck) {
5878
- accounts.push({ pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6196
+ accounts.push(accountMeta(SYSVAR_INSTRUCTIONS_ADDRESS));
5879
6197
  }
5880
6198
  } else if (enableRiskCheck) {
5881
6199
  if (publicAmountForAccounts === BigInt(0)) {
5882
- accounts.push({ pubkey: payer, isSigner: true, isWritable: false });
5883
- accounts.push({ pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6200
+ accounts.push(accountMeta(payer, { signer: true }));
6201
+ accounts.push(accountMeta(SYSVAR_INSTRUCTIONS_ADDRESS));
5884
6202
  } else {
5885
- accounts.push({ pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6203
+ accounts.push(accountMeta(SYSVAR_INSTRUCTIONS_ADDRESS));
5886
6204
  if (riskNonce) {
5887
- accounts.push({ pubkey: riskNonce, isSigner: false, isWritable: true });
6205
+ accounts.push(accountMeta(riskNonce, { writable: true }));
5888
6206
  }
5889
6207
  }
5890
6208
  }
5891
6209
  }
5892
- return new TransactionInstruction2({
5893
- programId,
5894
- keys: accounts,
5895
- data
5896
- });
6210
+ return programInstruction(programId, accounts, new Uint8Array(data));
5897
6211
  }
5898
- var PACKET_LIMIT_BYTES = 1232;
6212
+ var V1_COMPUTE_CONFIG = {
6213
+ computeUnitLimit: 12e5,
6214
+ // 100,000 micro-lamports per unit over 1,200,000 units: the same priority fee as the v0 path.
6215
+ priorityFeeLamports: 120000n,
6216
+ loadedAccountsDataSizeLimit: 64 * 1024 * 1024
6217
+ };
5899
6218
  function getCommonALTAddresses() {
5900
6219
  return [
5901
- SystemProgram3.programId,
5902
- SYSVAR_SLOT_HASHES_PUBKEY,
5903
- SYSVAR_INSTRUCTIONS_PUBKEY,
5904
- ComputeBudgetProgram.programId
6220
+ SYSTEM_PROGRAM_ADDRESS,
6221
+ SYSVAR_SLOT_HASHES_ADDRESS,
6222
+ SYSVAR_INSTRUCTIONS_ADDRESS,
6223
+ COMPUTE_BUDGET_PROGRAM_ADDRESS
5905
6224
  ];
5906
6225
  }
5907
6226
  function dedupePubkeys(addresses) {
5908
- const seen = /* @__PURE__ */ new Set();
5909
- const deduped = [];
5910
- for (const address of addresses) {
5911
- const key = address.toBase58();
5912
- if (seen.has(key)) continue;
5913
- seen.add(key);
5914
- deduped.push(address);
5915
- }
5916
- return deduped;
6227
+ return [...new Set(addresses)];
5917
6228
  }
5918
6229
  function collectLookupCandidatesFromInstructions(instructions, payer, existingAlts) {
5919
6230
  const existing = /* @__PURE__ */ new Set();
5920
6231
  for (const alt of existingAlts ?? []) {
5921
- for (const address of alt.state.addresses) {
5922
- existing.add(address.toBase58());
6232
+ for (const address2 of alt.addresses) {
6233
+ existing.add(address2);
5923
6234
  }
5924
6235
  }
5925
6236
  const collected = [];
5926
6237
  for (const ix of instructions) {
5927
- collected.push(ix.programId);
5928
- for (const key of ix.keys) {
5929
- if (key.isSigner) continue;
5930
- collected.push(key.pubkey);
6238
+ collected.push(ix.programAddress);
6239
+ for (const account of ix.accounts ?? []) {
6240
+ if (isSignerRole(account.role)) continue;
6241
+ collected.push(account.address);
5931
6242
  }
5932
6243
  }
5933
- return dedupePubkeys(collected).filter((address) => {
5934
- const key = address.toBase58();
5935
- return key !== payer.toBase58() && !existing.has(key);
5936
- });
6244
+ return dedupePubkeys(collected).filter((address2) => address2 !== payer && !existing.has(address2));
5937
6245
  }
5938
6246
  async function createEphemeralALT(connection, depositor, onProgress, additionalAddresses = [], externalFeePayer, allowSupplementalAlt = true) {
5939
6247
  const MAX_ALT_ADDRESSES = 20;
@@ -5941,7 +6249,7 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
5941
6249
  const altAddresses = dedupePubkeys([
5942
6250
  ...getCommonALTAddresses(),
5943
6251
  ...additionalAddresses
5944
- ]).filter((address) => !address.equals(depositor.publicKey));
6252
+ ]).filter((address2) => address2 !== depositor.address);
5945
6253
  const addressesForCreate = altAddresses.slice(0, MAX_ALT_ADDRESSES);
5946
6254
  if (altAddresses.length > MAX_ALT_ADDRESSES) {
5947
6255
  onProgress?.(
@@ -5950,17 +6258,21 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
5950
6258
  }
5951
6259
  for (let altAttempt = 0; altAttempt < MAX_ALT_CREATE_RETRIES; altAttempt++) {
5952
6260
  try {
5953
- const slot = await connection.getSlot("finalized");
5954
- const altPayerPubkey = externalFeePayer ? await externalFeePayer.getPayerPubkey() : depositor.publicKey;
5955
- const [createIx, altAddress] = AddressLookupTableProgram.createLookupTable({
5956
- authority: depositor.publicKey,
5957
- payer: altPayerPubkey,
6261
+ const slot = await fetchSlot(connection, "finalized");
6262
+ const altPayerPubkey = externalFeePayer ? await externalFeePayer.getPayerPubkey() : depositor.address;
6263
+ const altPayer = externalFeePayer ? createNoopSigner2(altPayerPubkey) : depositor;
6264
+ const altPda = await findAddressLookupTablePda({ authority: depositor.address, recentSlot: slot });
6265
+ const [altAddress] = altPda;
6266
+ const createIx = getCreateLookupTableInstruction({
6267
+ address: altPda,
6268
+ authority: depositor.address,
6269
+ payer: altPayer,
5958
6270
  recentSlot: slot
5959
6271
  });
5960
- const extendIx = AddressLookupTableProgram.extendLookupTable({
5961
- payer: altPayerPubkey,
5962
- authority: depositor.publicKey,
5963
- lookupTable: altAddress,
6272
+ const extendIx = getExtendLookupTableInstruction({
6273
+ address: altAddress,
6274
+ authority: depositor,
6275
+ payer: altPayer,
5964
6276
  addresses: addressesForCreate
5965
6277
  });
5966
6278
  if (externalFeePayer) {
@@ -5976,33 +6288,33 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
5976
6288
  allowSupplementalAlt
5977
6289
  );
5978
6290
  } else {
5979
- const tx = new Transaction3().add(createIx).add(extendIx);
5980
- const { blockhash } = await connection.getLatestBlockhash();
5981
- tx.recentBlockhash = blockhash;
5982
- tx.feePayer = depositor.publicKey;
5983
- if (depositor.keypair) {
5984
- await sendAndConfirmTransaction(connection, tx, [depositor.keypair], { commitment: "confirmed" });
5985
- } else if (depositor.signTransaction) {
5986
- const signedTx = await depositor.signTransaction(tx);
5987
- const sig = await connection.sendRawTransaction(signedTx.serialize());
5988
- const latestBH = await connection.getLatestBlockhash();
5989
- await connection.confirmTransaction({ signature: sig, blockhash: latestBH.blockhash, lastValidBlockHeight: latestBH.lastValidBlockHeight }, "confirmed");
5990
- } else {
5991
- throw new Error("Cannot create ALT: no signing method provided");
5992
- }
6291
+ const lifetime = await fetchLatestBlockhash(connection);
6292
+ const message = buildTransactionMessage({
6293
+ version: "legacy",
6294
+ feePayer: depositor,
6295
+ lifetime,
6296
+ instructions: [createIx, extendIx]
6297
+ });
6298
+ onProgress?.(isKeyPairSigner(depositor) ? "Creating lookup table..." : "Waiting for wallet signature (lookup table)...");
6299
+ const signed = await signTransaction(message);
6300
+ const sig = await sendRawTransaction(connection, transactionBytes(signed));
6301
+ await confirmSignature(connection, sig, {
6302
+ commitment: "confirmed",
6303
+ lastValidBlockHeight: lifetime.lastValidBlockHeight
6304
+ });
5993
6305
  }
5994
6306
  for (let i = 0; i < 30; i++) {
5995
6307
  await new Promise((r) => setTimeout(r, 500));
5996
- const result = await connection.getAddressLookupTable(altAddress);
5997
- if (result.value && result.value.isActive()) {
5998
- onProgress?.(`ALT created and active: ${altAddress.toBase58()}`);
5999
- return [result.value];
6308
+ const result = await fetchMaybeAddressLookupTable(connection, altAddress);
6309
+ if (result.exists && isLookupTableActive(result.data.deactivationSlot)) {
6310
+ onProgress?.(`ALT created and active: ${altAddress}`);
6311
+ return [{ address: altAddress, addresses: result.data.addresses }];
6000
6312
  }
6001
6313
  }
6002
- const finalResult = await connection.getAddressLookupTable(altAddress);
6003
- if (finalResult.value) {
6314
+ const finalResult = await fetchMaybeAddressLookupTable(connection, altAddress);
6315
+ if (finalResult.exists) {
6004
6316
  onProgress?.("ALT created (activation pending)");
6005
- return [finalResult.value];
6317
+ return [{ address: altAddress, addresses: finalResult.data.addresses }];
6006
6318
  }
6007
6319
  throw new Error("Failed to create ALT: not active after 15 seconds");
6008
6320
  } catch (err) {
@@ -6017,17 +6329,25 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
6017
6329
  }
6018
6330
  throw new Error(`Failed to create ALT after ${MAX_ALT_CREATE_RETRIES} retries`);
6019
6331
  }
6332
+ function isLookupTableActive(deactivationSlot) {
6333
+ return deactivationSlot === U64_MAX;
6334
+ }
6020
6335
  var SOLANA_PACKET_DATA_SIZE = 1232;
6021
- function estimateV0TransactionSize(payerKey, recentBlockhash, instructions, addressLookupTableAccounts) {
6336
+ var SOLANA_V1_PACKET_DATA_SIZE = 4096;
6337
+ function packetLimitFor(version) {
6338
+ return version === 1 ? SOLANA_V1_PACKET_DATA_SIZE : SOLANA_PACKET_DATA_SIZE;
6339
+ }
6340
+ function estimateV0TransactionSize(payerKey, recentBlockhash, instructions, addressLookupTableAccounts, version = 0, computeConfig) {
6022
6341
  try {
6023
- const messageV0 = new TransactionMessage({
6024
- payerKey,
6025
- recentBlockhash,
6026
- instructions
6027
- }).compileToV0Message(addressLookupTableAccounts);
6028
- const messageLen = messageV0.serialize().length;
6029
- const signaturesLen = 1 + 64;
6030
- const raw = signaturesLen + messageLen;
6342
+ const message = buildTransactionMessage({
6343
+ version,
6344
+ computeConfig,
6345
+ feePayer: payerKey,
6346
+ lifetime: { blockhash: recentBlockhash, lastValidBlockHeight: 0n },
6347
+ instructions,
6348
+ lookupTables: addressLookupTableAccounts
6349
+ });
6350
+ const raw = transactionWireSize(message);
6031
6351
  const encodedBase64 = Math.ceil(raw / 3) * 4;
6032
6352
  return { raw, encodedBase64 };
6033
6353
  } catch (err) {
@@ -6035,17 +6355,17 @@ function estimateV0TransactionSize(payerKey, recentBlockhash, instructions, addr
6035
6355
  return { raw: -1, encodedBase64: -1, error: msg };
6036
6356
  }
6037
6357
  }
6038
- function exceedsPacketLimit(size) {
6039
- return size.error !== void 0 || size.raw > SOLANA_PACKET_DATA_SIZE;
6358
+ function exceedsPacketLimit(size, limit = SOLANA_PACKET_DATA_SIZE) {
6359
+ return size.error !== void 0 || size.raw > limit;
6040
6360
  }
6041
- function describePacketSize(size) {
6042
- return size.error ? `serialize overran the ${SOLANA_PACKET_DATA_SIZE}-byte buffer` : `${size.raw} > ${SOLANA_PACKET_DATA_SIZE} bytes`;
6361
+ function describePacketSize(size, limit = SOLANA_PACKET_DATA_SIZE) {
6362
+ return size.error ? `serialize overran the ${limit}-byte buffer` : `${size.raw} > ${limit} bytes`;
6043
6363
  }
6044
6364
  async function planDirectV0Submission(args) {
6045
- const { estimate, full, compact, minimal, createSupplementalAlt, onProgress } = args;
6365
+ const { estimate, full, compact, minimal, createSupplementalAlt, onProgress, packetLimit = SOLANA_PACKET_DATA_SIZE } = args;
6046
6366
  let minimalSize = estimate(minimal);
6047
6367
  let supplementalAltRequested = false;
6048
- if (exceedsPacketLimit(minimalSize)) {
6368
+ if (exceedsPacketLimit(minimalSize, packetLimit)) {
6049
6369
  supplementalAltRequested = true;
6050
6370
  onProgress?.(
6051
6371
  "Transaction still exceeds packet limit with current ALT set; creating supplemental ALT..."
@@ -6058,50 +6378,59 @@ async function planDirectV0Submission(args) {
6058
6378
  onProgress?.(`Failed to create supplemental ALT: ${altMsg}`);
6059
6379
  }
6060
6380
  }
6061
- if (!minimalSize.error && minimalSize.raw > SOLANA_PACKET_DATA_SIZE) {
6381
+ if (!minimalSize.error && minimalSize.raw > packetLimit) {
6062
6382
  throw new Error(
6063
- `Transaction exceeds Solana packet limit even in minimal mode: raw=${minimalSize.raw} (>${SOLANA_PACKET_DATA_SIZE}), base64=${minimalSize.encodedBase64} (>1644). Try providing a pre-built ALT via options.addressLookupTableAccounts or reduce instruction payload size.`
6383
+ `Transaction exceeds Solana packet limit even in minimal mode: raw=${minimalSize.raw} (>${packetLimit}), base64=${minimalSize.encodedBase64} (>1644). Try providing a pre-built ALT via options.addressLookupTableAccounts or reduce instruction payload size.`
6064
6384
  );
6065
6385
  }
6066
6386
  const fullSize = estimate(full);
6067
- if (!exceedsPacketLimit(fullSize)) {
6387
+ if (!exceedsPacketLimit(fullSize, packetLimit)) {
6068
6388
  return { tier: "full", instructions: full, supplementalAltRequested, fullSize, minimalSize };
6069
6389
  }
6070
6390
  const compactSize = estimate(compact);
6071
- if (!exceedsPacketLimit(compactSize)) {
6391
+ if (!exceedsPacketLimit(compactSize, packetLimit)) {
6072
6392
  onProgress?.(
6073
- `Transaction would exceed the packet limit with a compute-unit price (${describePacketSize(fullSize)}); sending without it.`
6393
+ `Transaction would exceed the packet limit with a compute-unit price (${describePacketSize(fullSize, packetLimit)}); sending without it.`
6074
6394
  );
6075
6395
  return { tier: "compact", instructions: compact, supplementalAltRequested, fullSize, minimalSize };
6076
6396
  }
6077
6397
  onProgress?.(
6078
- `Transaction would exceed the packet limit with compute-budget instructions (${describePacketSize(fullSize)}); sending the minimal set.`
6398
+ `Transaction would exceed the packet limit with compute-budget instructions (${describePacketSize(fullSize, packetLimit)}); sending the minimal set.`
6079
6399
  );
6080
6400
  return { tier: "minimal", instructions: minimal, supplementalAltRequested, fullSize, minimalSize };
6081
6401
  }
6082
- async function submitViaExternalFeePayer(connection, depositor, externalFeePayer, externalFeePayerPubkey, instructions, addressLookupTableAccounts, onProgress, allowSupplementalAlt = true, relayAltAttempt) {
6083
- if (!depositor.signTransaction) {
6402
+ async function submitViaExternalFeePayer(connection, depositor, externalFeePayer, externalFeePayerPubkey, instructions, addressLookupTableAccounts, onProgress, allowSupplementalAlt = true, relayAltAttempt, transactionVersion = 0) {
6403
+ if (isKeyPairSigner(depositor)) {
6084
6404
  throw new Error(
6085
6405
  "externalFeePayer requires wallet-style signTransaction \u2014 keypair-only depositors aren't supported for external fee payment."
6086
6406
  );
6087
6407
  }
6088
6408
  onProgress?.("Requesting fee quote from external fee payer...");
6089
- const { blockhash: quoteBlockhash } = await connection.getLatestBlockhash();
6409
+ const quoteLifetime = await fetchLatestBlockhash(connection);
6410
+ const packetLimit = packetLimitFor(transactionVersion);
6411
+ if (transactionVersion === 1) {
6412
+ addressLookupTableAccounts = [];
6413
+ allowSupplementalAlt = false;
6414
+ }
6415
+ const compile = (instrs, alts, lifetime2) => buildTransactionMessage({
6416
+ version: transactionVersion,
6417
+ computeConfig: transactionVersion === 1 ? V1_COMPUTE_CONFIG : void 0,
6418
+ feePayer: externalFeePayerPubkey,
6419
+ lifetime: lifetime2,
6420
+ instructions: instrs,
6421
+ lookupTables: alts ?? [],
6422
+ signers: [depositor]
6423
+ });
6090
6424
  const measure = (instrs, alts) => {
6091
6425
  try {
6092
- const message = new TransactionMessage({
6093
- payerKey: externalFeePayerPubkey,
6094
- recentBlockhash: quoteBlockhash,
6095
- instructions: instrs
6096
- }).compileToV0Message(alts ?? []);
6097
- return { size: 1 + 2 * 64 + message.serialize().length };
6426
+ return { size: transactionWireSize(compile(instrs, alts, quoteLifetime)) };
6098
6427
  } catch (err) {
6099
6428
  return { size: Infinity, error: err instanceof Error ? err.message : String(err) };
6100
6429
  }
6101
6430
  };
6102
6431
  const failIfOverLimit = (size, error) => {
6103
- if (size <= PACKET_LIMIT_BYTES) return;
6104
- const measured = Number.isFinite(size) ? `raw=${size} (>${PACKET_LIMIT_BYTES})` : `message could not be serialized (${error})`;
6432
+ if (size <= packetLimit) return;
6433
+ const measured = Number.isFinite(size) ? `raw=${size} (>${packetLimit})` : `message could not be serialized (${error})`;
6105
6434
  throw new Error(
6106
6435
  `Transaction exceeds Solana packet limit even after ALT compression: ${measured}. Try providing a pre-built ALT via options.addressLookupTableAccounts or reduce instruction payload size.`
6107
6436
  );
@@ -6111,8 +6440,14 @@ async function submitViaExternalFeePayer(connection, depositor, externalFeePayer
6111
6440
  if (relayAltAttempt) {
6112
6441
  try {
6113
6442
  onProgress?.("Requesting supplemental lookup table from relay...");
6443
+ const before = addressLookupTableAccounts;
6114
6444
  addressLookupTableAccounts = [await relayAltAttempt()];
6115
- return;
6445
+ const withRelay = measure(instrs, addressLookupTableAccounts);
6446
+ if (withRelay.size <= packetLimit) return;
6447
+ onProgress?.(
6448
+ `Relay supplemental table leaves the transaction at ${withRelay.size} bytes; falling back to a depositor-signed table.`
6449
+ );
6450
+ addressLookupTableAccounts = before;
6116
6451
  } catch (err) {
6117
6452
  const msg = err instanceof Error ? err.message : String(err);
6118
6453
  onProgress?.(
@@ -6123,7 +6458,7 @@ async function submitViaExternalFeePayer(connection, depositor, externalFeePayer
6123
6458
  try {
6124
6459
  const supplementalAddresses = dedupePubkeys([
6125
6460
  ...collectLookupCandidatesFromInstructions(instrs, externalFeePayerPubkey, void 0),
6126
- ...extraAddresses.filter((a) => !a.equals(externalFeePayerPubkey))
6461
+ ...extraAddresses.filter((a) => a !== externalFeePayerPubkey)
6127
6462
  ]);
6128
6463
  const supplementalAlt = await createEphemeralALT(
6129
6464
  connection,
@@ -6141,53 +6476,40 @@ async function submitViaExternalFeePayer(connection, depositor, externalFeePayer
6141
6476
  };
6142
6477
  const PAYMENT_IX_COMPRESS_RESERVE_BYTES = 128;
6143
6478
  let pre = measure(instructions, addressLookupTableAccounts);
6144
- if (pre.size + PAYMENT_IX_COMPRESS_RESERVE_BYTES > PACKET_LIMIT_BYTES && allowSupplementalAlt) {
6479
+ if (pre.size + PAYMENT_IX_COMPRESS_RESERVE_BYTES > packetLimit && allowSupplementalAlt) {
6145
6480
  const paymentHints = externalFeePayer.getPaymentAccountHints ? await externalFeePayer.getPaymentAccountHints().catch(() => []) : [];
6146
6481
  await compressWithSupplementalAlt(instructions, paymentHints);
6147
6482
  pre = measure(instructions, addressLookupTableAccounts);
6148
6483
  }
6149
6484
  failIfOverLimit(pre.size, pre.error);
6150
- const quoteMessage = new TransactionMessage({
6151
- payerKey: externalFeePayerPubkey,
6152
- recentBlockhash: quoteBlockhash,
6153
- instructions
6154
- }).compileToV0Message(addressLookupTableAccounts ?? []);
6155
- const quoteTxBase64 = Buffer.from(new VersionedTransaction(quoteMessage).serialize()).toString("base64");
6485
+ const quoteTxBase64 = transactionBase64(compileUnsigned(compile(instructions, addressLookupTableAccounts, quoteLifetime)));
6156
6486
  const paymentInstruction = await externalFeePayer.getPaymentInstruction(quoteTxBase64);
6157
6487
  const finalInstructions = [...instructions, paymentInstruction];
6158
6488
  let post = measure(finalInstructions, addressLookupTableAccounts);
6159
- if (post.size > PACKET_LIMIT_BYTES && allowSupplementalAlt) {
6489
+ if (post.size > packetLimit && allowSupplementalAlt) {
6160
6490
  await compressWithSupplementalAlt(finalInstructions);
6161
6491
  post = measure(finalInstructions, addressLookupTableAccounts);
6162
6492
  }
6163
6493
  failIfOverLimit(post.size, post.error);
6164
6494
  onProgress?.("Building final transaction...");
6165
- const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
6166
- const finalMessage = new TransactionMessage({
6167
- payerKey: externalFeePayerPubkey,
6168
- recentBlockhash: blockhash,
6169
- instructions: finalInstructions
6170
- }).compileToV0Message(addressLookupTableAccounts ?? []);
6171
- const finalTx = new VersionedTransaction(finalMessage);
6495
+ const lifetime = await fetchLatestBlockhash(connection);
6496
+ const finalMessage = compile(finalInstructions, addressLookupTableAccounts, lifetime);
6172
6497
  onProgress?.("Waiting for wallet signature...");
6173
- const partiallySignedTx = await depositor.signTransaction(finalTx);
6174
- const partiallySignedBase64 = Buffer.from(partiallySignedTx.serialize()).toString("base64");
6498
+ const partiallySignedTx = await partiallySignTransaction(finalMessage);
6499
+ const partiallySignedBase64 = transactionBase64(partiallySignedTx);
6175
6500
  onProgress?.("Requesting fee-payer co-signature...");
6176
6501
  const fullySignedBase64 = await externalFeePayer.cosign(partiallySignedBase64);
6177
- const fullySignedBytes = Buffer.from(fullySignedBase64, "base64");
6502
+ const fullySignedBytes = new Uint8Array(Buffer.from(fullySignedBase64, "base64"));
6178
6503
  onProgress?.("Sending transaction...");
6179
- const signature = await connection.sendRawTransaction(fullySignedBytes, { skipPreflight: false });
6504
+ const signature = await sendRawTransaction(connection, fullySignedBytes, { skipPreflight: false });
6180
6505
  onProgress?.("Confirming transaction...");
6181
- const confirmation = await connection.confirmTransaction(
6182
- { signature, blockhash, lastValidBlockHeight },
6183
- "confirmed"
6184
- );
6185
- if (confirmation.value.err) {
6186
- throw new Error(`Transaction failed during confirmation: ${JSON.stringify(confirmation.value.err)}`);
6187
- }
6506
+ await confirmSignature(connection, signature, {
6507
+ commitment: "confirmed",
6508
+ lastValidBlockHeight: lifetime.lastValidBlockHeight
6509
+ });
6188
6510
  return signature;
6189
6511
  }
6190
- async function submitTransactionDirect(connection, programId, depositor, proofBytes, publicInputsBytes, nullifiers, mint, recipient, riskOracleQueue, riskQuoteUrl, getRiskQuoteInstruction, onProgress, addressLookupTableAccounts, rangeApiKey, encryptedNoteBytes, relayUrl, altAddresses, relayer, relayerFee, onTransactProofBuilt, externalFeePayer, relaySupplementalAlt) {
6512
+ async function submitTransactionDirect(connection, programId, depositor, proofBytes, publicInputsBytes, nullifiers, mint, recipient, riskOracleQueue, riskQuoteUrl, getRiskQuoteInstruction, onProgress, addressLookupTableAccounts, rangeApiKey, encryptedNoteBytes, relayUrl, altAddresses, relayer, relayerFee, onTransactProofBuilt, externalFeePayer, relaySupplementalAlt, transactionVersion = 0) {
6191
6513
  onProgress?.("Building transaction...");
6192
6514
  addressLookupTableAccounts = await resolveAddressLookupTableAccounts(
6193
6515
  connection,
@@ -6196,12 +6518,12 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6196
6518
  addressLookupTableAccounts,
6197
6519
  onProgress
6198
6520
  );
6199
- const pdas = getShieldPoolPDAs(programId, mint);
6521
+ const pdas = await getShieldPoolPDAs(programId, mint);
6200
6522
  const treeState = await readMerkleTreeState(connection, pdas.merkleTree, true);
6201
6523
  const nextIndex = treeState.nextIndex;
6202
6524
  let riskQuoteIx = null;
6203
6525
  const isDeposit = recipient === void 0;
6204
- const isSplPool = !mint.equals(NATIVE_SOL_MINT);
6526
+ const isSplPool = mint !== NATIVE_SOL_MINT;
6205
6527
  const riskCheckEnabled = true;
6206
6528
  if (isDeposit && riskCheckEnabled && !getRiskQuoteInstruction && !riskQuoteUrl && rangeApiKey) {
6207
6529
  throw new Error(
@@ -6219,35 +6541,33 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6219
6541
  const preTransactInstructions = [];
6220
6542
  let splAccounts;
6221
6543
  if (isSplPool) {
6222
- const poolVaultAta = getAssociatedTokenAddressSync(
6544
+ const [poolVaultAta] = await findAssociatedTokenPda({
6223
6545
  mint,
6224
- pdas.vaultAuthority,
6225
- true,
6226
- TOKEN_PROGRAM_ID
6227
- );
6546
+ owner: pdas.vaultAuthority,
6547
+ tokenProgram: TOKEN_PROGRAM_ADDRESS
6548
+ });
6228
6549
  splAccounts = {
6229
6550
  vaultAuthority: pdas.vaultAuthority,
6230
6551
  poolVaultAta,
6231
- tokenProgram: TOKEN_PROGRAM_ID
6552
+ tokenProgram: TOKEN_PROGRAM_ADDRESS
6232
6553
  };
6233
6554
  if (publicAmount > BigInt(0)) {
6234
- splAccounts.payerAta = getAssociatedTokenAddressSync(
6555
+ [splAccounts.payerAta] = await findAssociatedTokenPda({
6235
6556
  mint,
6236
- depositor.publicKey,
6237
- false,
6238
- TOKEN_PROGRAM_ID
6239
- );
6240
- const poolVaultAtaInfo = await connection.getAccountInfo(poolVaultAta);
6557
+ owner: depositor.address,
6558
+ tokenProgram: TOKEN_PROGRAM_ADDRESS
6559
+ });
6560
+ const poolVaultAtaInfo = await fetchAccountBytes(connection, poolVaultAta);
6241
6561
  if (!poolVaultAtaInfo) {
6242
6562
  onProgress?.("Creating pool vault ATA for SPL pool...");
6243
6563
  preTransactInstructions.push(
6244
- createAssociatedTokenAccountInstruction(
6245
- depositor.publicKey,
6246
- poolVaultAta,
6247
- pdas.vaultAuthority,
6564
+ getCreateAssociatedTokenInstruction({
6565
+ payer: depositor,
6566
+ ata: poolVaultAta,
6567
+ owner: pdas.vaultAuthority,
6248
6568
  mint,
6249
- TOKEN_PROGRAM_ID
6250
- )
6569
+ tokenProgram: TOKEN_PROGRAM_ADDRESS
6570
+ })
6251
6571
  );
6252
6572
  }
6253
6573
  } else if (publicAmount < BigInt(0)) {
@@ -6262,16 +6582,16 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6262
6582
  let riskNoncePda;
6263
6583
  let depositNonce = null;
6264
6584
  let relaySupplementalAltPromise;
6265
- const requestRelaySupplementalAlt = () => {
6266
- const [nullifierPda0] = deriveNullifierPDA(programId, pdas.pool, nullifiers[0]);
6267
- const [nullifierPda1] = deriveNullifierPDA(programId, pdas.pool, nullifiers[1]);
6268
- const [riskNoncePdaForAlt] = deriveRiskNoncePDA(programId, depositNonce);
6269
- const depositorAta = getAssociatedTokenAddressSync(mint, depositor.publicKey, false, TOKEN_PROGRAM_ID);
6585
+ const requestRelaySupplementalAlt = async () => {
6586
+ const [nullifierPda0] = await deriveNullifierPDA(programId, pdas.pool, nullifiers[0]);
6587
+ const [nullifierPda1] = await deriveNullifierPDA(programId, pdas.pool, nullifiers[1]);
6588
+ const [riskNoncePdaForAlt] = await deriveRiskNoncePDA(programId, depositNonce);
6589
+ const [depositorAta] = await findAssociatedTokenPda({ mint, owner: depositor.address, tokenProgram: TOKEN_PROGRAM_ADDRESS });
6270
6590
  return fetchSupplementalAltFromRelay(relayUrl, {
6271
6591
  mint,
6272
6592
  nullifiers,
6273
6593
  bind0: depositNonce,
6274
- depositor: depositor.publicKey
6594
+ depositor: depositor.address
6275
6595
  }).then(
6276
6596
  (table) => resolveRelaySupplementalAlt(connection, table, [
6277
6597
  nullifierPda0,
@@ -6307,11 +6627,11 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6307
6627
  if ((isDeposit || isSend) && riskCheckEnabled && !riskQuoteIx) {
6308
6628
  if (getRiskQuoteInstruction) {
6309
6629
  onProgress?.("Fetching risk quote (custom)...");
6310
- riskQuoteIx = await getRiskQuoteInstruction(depositor.publicKey);
6630
+ riskQuoteIx = await getRiskQuoteInstruction(depositor.address);
6311
6631
  } else if (riskQuoteUrl) {
6312
6632
  onProgress?.("Fetching risk quote from backend...");
6313
6633
  const isDepositQuote = depositAmount > BigInt(0);
6314
- const quote = await fetchRiskQuote(riskQuoteUrl, depositor.publicKey, {
6634
+ const quote = await fetchRiskQuote(riskQuoteUrl, depositor.address, {
6315
6635
  poolMint: mint,
6316
6636
  amount: depositAmount,
6317
6637
  token: mint,
@@ -6333,7 +6653,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6333
6653
  depositNonce = extractDepositNonceFromEd25519Ix(riskQuoteIx);
6334
6654
  }
6335
6655
  if (depositNonce) {
6336
- [riskNoncePda] = deriveRiskNoncePDA(programId, depositNonce);
6656
+ [riskNoncePda] = await deriveRiskNoncePDA(programId, depositNonce);
6337
6657
  if (relaySupplementalAlt && relayUrl && isSplPool) {
6338
6658
  getRelaySupplementalAlt().catch(() => {
6339
6659
  });
@@ -6345,7 +6665,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6345
6665
  }
6346
6666
  if (!isDeposit && riskCheckEnabled && recipient && riskQuoteUrl && !riskQuoteIx) {
6347
6667
  onProgress?.("Fetching risk quote for recipient...");
6348
- riskQuoteIx = await fetchRiskQuoteInstruction(riskQuoteUrl, depositor.publicKey, {
6668
+ riskQuoteIx = await fetchRiskQuoteInstruction(riskQuoteUrl, depositor.address, {
6349
6669
  poolMint: mint,
6350
6670
  recipient,
6351
6671
  amount: withdrawAmount,
@@ -6355,9 +6675,9 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6355
6675
  nullifier1: nullifier1Hex
6356
6676
  });
6357
6677
  }
6358
- const transactIx = buildTransactInstruction(
6678
+ const transactIx = await buildTransactInstruction(
6359
6679
  programId,
6360
- depositor.publicKey,
6680
+ depositor.address,
6361
6681
  pdas.pool,
6362
6682
  pdas.treasury,
6363
6683
  pdas.merkleTree,
@@ -6389,14 +6709,15 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6389
6709
  baseInstructions.splice(riskQuoteIx ? 1 : 0, 0, ...topUpInstructions);
6390
6710
  }
6391
6711
  }
6392
- const cuLimitIx = ComputeBudgetProgram.setComputeUnitLimit({ units: 12e5 });
6393
- const cuPriceIx = ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1e5 });
6712
+ const cuLimitIx = getSetComputeUnitLimitInstruction({ units: 12e5 });
6713
+ const cuPriceIx = getSetComputeUnitPriceInstruction({ microLamports: 1e5 });
6714
+ const computeConfig = transactionVersion === 1 ? V1_COMPUTE_CONFIG : void 0;
6394
6715
  const fullInstructions = [...baseInstructions, cuLimitIx, cuPriceIx, transactIx];
6395
6716
  const compactInstructions = [...baseInstructions, cuLimitIx, transactIx];
6396
6717
  const minimalInstructions = [...baseInstructions, cuLimitIx, transactIx];
6397
6718
  let instructions = fullInstructions;
6398
- let { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
6399
- const useV0 = addressLookupTableAccounts && addressLookupTableAccounts.length > 0;
6719
+ let { blockhash, lastValidBlockHeight } = await fetchLatestBlockhash(connection);
6720
+ const useV0 = transactionVersion === 1 || addressLookupTableAccounts && addressLookupTableAccounts.length > 0;
6400
6721
  let signature = "";
6401
6722
  if (externalFeePayer) {
6402
6723
  signature = await submitViaExternalFeePayer(
@@ -6413,11 +6734,16 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6413
6734
  // only for submitViaExternalFeePayer's OWN, separate supplemental round — triggered by the
6414
6735
  // external payer's extra signature and payment-instruction accounts pushing an already-ALT'd
6415
6736
  // tx back over the limit — so that round also tries the relay before an ephemeral fallback.
6416
- relayAltEligible() ? getRelaySupplementalAlt : void 0
6737
+ relayAltEligible() ? getRelaySupplementalAlt : void 0,
6738
+ transactionVersion
6417
6739
  );
6418
6740
  } else if (useV0) {
6741
+ if (transactionVersion === 1) {
6742
+ addressLookupTableAccounts = [];
6743
+ }
6419
6744
  const plan = await planDirectV0Submission({
6420
- estimate: (ixs) => estimateV0TransactionSize(depositor.publicKey, blockhash, ixs, addressLookupTableAccounts),
6745
+ packetLimit: packetLimitFor(transactionVersion),
6746
+ estimate: (ixs) => estimateV0TransactionSize(depositor.address, blockhash, ixs, addressLookupTableAccounts, transactionVersion, computeConfig),
6421
6747
  full: fullInstructions,
6422
6748
  compact: compactInstructions,
6423
6749
  minimal: minimalInstructions,
@@ -6427,10 +6753,10 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6427
6753
  onProgress?.("Requesting supplemental lookup table from relay...");
6428
6754
  const relayAlt = await getRelaySupplementalAlt();
6429
6755
  addressLookupTableAccounts = [
6430
- ...(addressLookupTableAccounts ?? []).filter((t) => !t.key.equals(relayAlt.key)),
6756
+ ...(addressLookupTableAccounts ?? []).filter((t) => t.address !== relayAlt.address),
6431
6757
  relayAlt
6432
6758
  ];
6433
- ({ blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash());
6759
+ ({ blockhash, lastValidBlockHeight } = await fetchLatestBlockhash(connection));
6434
6760
  return;
6435
6761
  } catch (err) {
6436
6762
  const msg = err instanceof Error ? err.message : String(err);
@@ -6441,7 +6767,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6441
6767
  }
6442
6768
  const supplementalAddresses = collectLookupCandidatesFromInstructions(
6443
6769
  minimalInstructions,
6444
- depositor.publicKey,
6770
+ depositor.address,
6445
6771
  addressLookupTableAccounts
6446
6772
  );
6447
6773
  const supplementalAlt = await createEphemeralALT(
@@ -6454,7 +6780,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6454
6780
  ...addressLookupTableAccounts ?? [],
6455
6781
  ...supplementalAlt
6456
6782
  ];
6457
- ({ blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash());
6783
+ ({ blockhash, lastValidBlockHeight } = await fetchLatestBlockhash(connection));
6458
6784
  },
6459
6785
  onProgress
6460
6786
  });
@@ -6465,9 +6791,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6465
6791
  if (!sig) return false;
6466
6792
  for (let i = 0; i < 6; i++) {
6467
6793
  try {
6468
- const { value } = await connection.getSignatureStatus(sig, {
6469
- searchTransactionHistory: true
6470
- });
6794
+ const [value] = await fetchSignatureStatuses(connection, [sig], true);
6471
6795
  if (value) {
6472
6796
  if (value.err) return false;
6473
6797
  if (value.confirmationStatus === "confirmed" || value.confirmationStatus === "finalized") {
@@ -6495,59 +6819,37 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6495
6819
  };
6496
6820
  for (let blockhashRetry = 0; blockhashRetry <= maxBlockhashRetries; blockhashRetry++) {
6497
6821
  if (blockhashRetry > 0) {
6498
- ({ blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash());
6822
+ ({ blockhash, lastValidBlockHeight } = await fetchLatestBlockhash(connection));
6499
6823
  onProgress?.(
6500
6824
  `Blockhash expired before confirmation; retrying with fresh blockhash (${blockhashRetry}/${maxBlockhashRetries})...`
6501
6825
  );
6502
6826
  }
6503
6827
  let transportAttempt = 0;
6504
6828
  while (true) {
6505
- const messageV0 = new TransactionMessage({
6506
- payerKey: depositor.publicKey,
6507
- recentBlockhash: blockhash,
6508
- instructions: ixs
6509
- }).compileToV0Message(addressLookupTableAccounts);
6510
- const versionedTx = new VersionedTransaction(messageV0);
6829
+ const message = buildTransactionMessage({
6830
+ version: transactionVersion,
6831
+ computeConfig,
6832
+ feePayer: depositor,
6833
+ lifetime: { blockhash, lastValidBlockHeight },
6834
+ instructions: ixs,
6835
+ lookupTables: addressLookupTableAccounts
6836
+ });
6511
6837
  if (onTransactProofBuilt) {
6512
6838
  await onTransactProofBuilt();
6513
6839
  }
6514
6840
  try {
6515
- if (depositor.keypair) {
6516
- onProgress?.("Signing and sending transaction...");
6517
- versionedTx.sign([depositor.keypair]);
6518
- signature = await connection.sendRawTransaction(versionedTx.serialize(), {
6519
- skipPreflight: options?.skipPreflight ?? false
6520
- });
6521
- sentSigs.push(signature);
6522
- onProgress?.("Confirming transaction...");
6523
- const confirmation = await connection.confirmTransaction({
6524
- signature,
6525
- blockhash,
6526
- lastValidBlockHeight
6527
- }, "confirmed");
6528
- if (confirmation.value.err) {
6529
- throw new Error(`Transaction failed during confirmation: ${JSON.stringify(confirmation.value.err)}`);
6530
- }
6531
- } else if (depositor.signTransaction) {
6532
- onProgress?.("Waiting for wallet signature...");
6533
- const signedTx = await depositor.signTransaction(versionedTx);
6534
- onProgress?.("Sending transaction...");
6535
- signature = await connection.sendRawTransaction(signedTx.serialize(), {
6536
- skipPreflight: options?.skipPreflight ?? false
6537
- });
6538
- sentSigs.push(signature);
6539
- onProgress?.("Confirming transaction...");
6540
- const confirmation = await connection.confirmTransaction({
6541
- signature,
6542
- blockhash,
6543
- lastValidBlockHeight
6544
- }, "confirmed");
6545
- if (confirmation.value.err) {
6546
- throw new Error(`Transaction failed during confirmation: ${JSON.stringify(confirmation.value.err)}`);
6547
- }
6548
- } else {
6549
- throw new Error("No signing method provided (need keypair or signTransaction)");
6550
- }
6841
+ onProgress?.(isKeyPairSigner(depositor) ? "Signing and sending transaction..." : "Waiting for wallet signature...");
6842
+ const signed = await signTransaction(message);
6843
+ if (!isKeyPairSigner(depositor)) onProgress?.("Sending transaction...");
6844
+ signature = await sendRawTransaction(connection, transactionBytes(signed), {
6845
+ skipPreflight: options?.skipPreflight ?? false
6846
+ });
6847
+ sentSigs.push(signature);
6848
+ onProgress?.("Confirming transaction...");
6849
+ await confirmSignature(connection, signature, {
6850
+ commitment: "confirmed",
6851
+ lastValidBlockHeight
6852
+ });
6551
6853
  return signature;
6552
6854
  } catch (error) {
6553
6855
  if (isBlockhashExpiryError(error)) {
@@ -6562,7 +6864,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6562
6864
  `Transient RPC transport error; retrying in ${Math.round(delayMs)}ms (${transportAttempt}/${maxTransportRetries})...`
6563
6865
  );
6564
6866
  await new Promise((r) => setTimeout(r, delayMs));
6565
- ({ blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash());
6867
+ ({ blockhash, lastValidBlockHeight } = await fetchLatestBlockhash(connection));
6566
6868
  continue;
6567
6869
  }
6568
6870
  if (looksLikeDoubleSpend(error)) {
@@ -6637,34 +6939,21 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6637
6939
  let legacyTransportAttempt = 0;
6638
6940
  while (true) {
6639
6941
  try {
6640
- const tx = new Transaction3();
6641
- for (const ix of instructions) {
6642
- tx.add(ix);
6643
- }
6644
- tx.recentBlockhash = blockhash;
6645
- tx.feePayer = depositor.publicKey;
6646
- if (depositor.keypair) {
6647
- onProgress?.("Signing and sending transaction...");
6648
- signature = await sendAndConfirmTransaction(
6649
- connection,
6650
- tx,
6651
- [depositor.keypair],
6652
- { commitment: "confirmed" }
6653
- );
6654
- } else if (depositor.signTransaction) {
6655
- onProgress?.("Waiting for wallet signature...");
6656
- const signedTx = await depositor.signTransaction(tx);
6657
- onProgress?.("Sending transaction...");
6658
- signature = await connection.sendRawTransaction(signedTx.serialize());
6659
- onProgress?.("Confirming transaction...");
6660
- await connection.confirmTransaction({
6661
- signature,
6662
- blockhash,
6663
- lastValidBlockHeight
6664
- }, "confirmed");
6665
- } else {
6666
- throw new Error("No signing method provided (need keypair or signTransaction)");
6667
- }
6942
+ const message = buildTransactionMessage({
6943
+ version: "legacy",
6944
+ feePayer: depositor,
6945
+ lifetime: { blockhash, lastValidBlockHeight },
6946
+ instructions
6947
+ });
6948
+ onProgress?.(isKeyPairSigner(depositor) ? "Signing and sending transaction..." : "Waiting for wallet signature...");
6949
+ const signed = await signTransaction(message);
6950
+ if (!isKeyPairSigner(depositor)) onProgress?.("Sending transaction...");
6951
+ signature = await sendRawTransaction(connection, transactionBytes(signed));
6952
+ onProgress?.("Confirming transaction...");
6953
+ await confirmSignature(connection, signature, {
6954
+ commitment: "confirmed",
6955
+ lastValidBlockHeight
6956
+ });
6668
6957
  break;
6669
6958
  } catch (err) {
6670
6959
  if (isTransientTransportError(err) && legacyTransportAttempt < maxLegacyTransportRetries) {
@@ -6674,7 +6963,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6674
6963
  `Transient RPC transport error; retrying in ${Math.round(delayMs)}ms (${legacyTransportAttempt}/${maxLegacyTransportRetries})...`
6675
6964
  );
6676
6965
  await new Promise((r) => setTimeout(r, delayMs));
6677
- ({ blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash());
6966
+ ({ blockhash, lastValidBlockHeight } = await fetchLatestBlockhash(connection));
6678
6967
  continue;
6679
6968
  }
6680
6969
  const msg = err instanceof Error ? err.message : String(err);
@@ -6694,7 +6983,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6694
6983
  }
6695
6984
  onProgress?.("Verifying the transaction against chain state...");
6696
6985
  await assertDirectSubmissionLanded({
6697
- connection,
6986
+ connection: settlementConnectionFromRpc(connection),
6698
6987
  programId,
6699
6988
  mint,
6700
6989
  nullifiers,
@@ -6819,16 +7108,16 @@ async function fetchRiskQuote(riskQuoteUrl, wallet, options) {
6819
7108
  } catch {
6820
7109
  url = new URL(baseUrl, typeof window !== "undefined" ? window.location.origin : "http://localhost");
6821
7110
  }
6822
- url.searchParams.set("wallet", wallet.toBase58());
6823
- url.searchParams.set("pool_mint", options.poolMint.toBase58());
7111
+ url.searchParams.set("wallet", wallet);
7112
+ url.searchParams.set("pool_mint", options.poolMint);
6824
7113
  if (options?.recipient) {
6825
- url.searchParams.set("recipient", options.recipient.toBase58());
7114
+ url.searchParams.set("recipient", options.recipient);
6826
7115
  }
6827
7116
  if (options?.amount !== void 0) {
6828
7117
  url.searchParams.set("amount", options.amount.toString());
6829
7118
  }
6830
7119
  if (options?.token) {
6831
- url.searchParams.set("token", options.token.toBase58());
7120
+ url.searchParams.set("token", options.token);
6832
7121
  }
6833
7122
  if (options?.commitment) {
6834
7123
  const commitment = typeof options.commitment === "string" ? options.commitment.replace(/^0x/i, "") : Buffer.from(options.commitment).toString("hex");
@@ -6859,19 +7148,16 @@ async function fetchRiskQuote(riskQuoteUrl, wallet, options) {
6859
7148
  }
6860
7149
  const signatureBuf = Buffer.from(signatureB64, "base64");
6861
7150
  const messageArr = hexToBytes2(messageHex);
6862
- let signerPubkey;
6863
- try {
6864
- signerPubkey = new PublicKey10(signerB58);
6865
- } catch {
7151
+ if (!isAddress(signerB58)) {
6866
7152
  throw new Error("Invalid risk quote response: signer_pubkey is not a public key");
6867
7153
  }
6868
- const publicKeyBytes = signerPubkey.toBytes();
7154
+ const publicKeyBytes = addressBytes(signerB58);
6869
7155
  if (signatureBuf.length !== 64 || messageArr.length !== 33 && messageArr.length !== 41 && messageArr.length !== 50 && messageArr.length !== 82 && messageArr.length !== 146 || publicKeyBytes.length !== 32) {
6870
7156
  throw new Error(
6871
7157
  `Invalid risk quote response: invalid lengths (sig=${signatureBuf.length}, msg=${messageArr.length}, pk=${publicKeyBytes.length}; expected msg 33/41/50/82/146)`
6872
7158
  );
6873
7159
  }
6874
- if (!nacl6.sign.detached.verify(messageArr, new Uint8Array(signatureBuf), publicKeyBytes)) {
7160
+ if (!nacl5.sign.detached.verify(messageArr, new Uint8Array(signatureBuf), publicKeyBytes)) {
6875
7161
  throw new Error(
6876
7162
  "Invalid risk quote response: signature does not verify under signer_pubkey"
6877
7163
  );
@@ -6885,11 +7171,7 @@ async function fetchRiskQuote(riskQuoteUrl, wallet, options) {
6885
7171
  const signature = new Uint8Array(signatureBuf);
6886
7172
  const message = new Uint8Array(messageArr);
6887
7173
  const publicKey = new Uint8Array(publicKeyBytes);
6888
- const instruction = Ed25519Program.createInstructionWithPublicKey({
6889
- publicKey,
6890
- message,
6891
- signature
6892
- });
7174
+ const instruction = ed25519VerifyInstruction({ publicKey, message, signature });
6893
7175
  return { instruction, nonce };
6894
7176
  }
6895
7177
  const keys = Object.keys(json).join(", ");
@@ -6919,9 +7201,9 @@ function buildTransactRequestBody(params) {
6919
7201
  const body = {
6920
7202
  proof_bytes: params.proofB64,
6921
7203
  public_inputs: params.publicInputsB64,
6922
- mint: params.mint.toBase58(),
6923
- recipient: params.recipient?.toBase58(),
6924
- relayer: params.relayer?.toBase58(),
7204
+ mint: params.mint,
7205
+ recipient: params.recipient ?? void 0,
7206
+ relayer: params.relayer ?? void 0,
6925
7207
  relayer_fee: params.relayerFee.toString(),
6926
7208
  // R3-M-02: the proof-bound fee ceiling. A decimal string preserves the full u64, and the
6927
7209
  // relay forwards it verbatim into the ext-data envelope — any substitution fails on chain.
@@ -6930,7 +7212,7 @@ function buildTransactRequestBody(params) {
6930
7212
  risk_quote: params.riskQuote
6931
7213
  };
6932
7214
  if (params.externalAmount === BigInt(0) && !params.recipient && params.sender) {
6933
- body.sender = params.sender.toBase58();
7215
+ body.sender = params.sender;
6934
7216
  }
6935
7217
  if (params.recipientDeliveryNotes && params.recipientDeliveryNotes.length > 0 && params.externalAmount === BigInt(0) && !params.recipient) {
6936
7218
  body.recipient_delivery_notes = params.recipientDeliveryNotes;
@@ -6940,7 +7222,10 @@ function buildTransactRequestBody(params) {
6940
7222
  function resolveUserWallet(options) {
6941
7223
  const candidates = [];
6942
7224
  if (options.depositorKeypair) {
6943
- candidates.push({ option: "depositorKeypair", key: options.depositorKeypair.publicKey });
7225
+ candidates.push({ option: "depositorKeypair", key: options.depositorKeypair.address });
7226
+ }
7227
+ if (options.signer) {
7228
+ candidates.push({ option: "signer", key: options.signer.address });
6944
7229
  }
6945
7230
  if (options.walletPublicKey) {
6946
7231
  candidates.push({ option: "walletPublicKey", key: options.walletPublicKey });
@@ -6951,9 +7236,9 @@ function resolveUserWallet(options) {
6951
7236
  if (candidates.length === 0) return void 0;
6952
7237
  const first = candidates[0];
6953
7238
  for (const other of candidates.slice(1)) {
6954
- if (other.key.equals(first.key)) continue;
7239
+ if (other.key === first.key) continue;
6955
7240
  throw new Error(
6956
- `Cloak was given two different wallets: \`${first.option}\` is ${first.key.toBase58()} and \`${other.option}\` is ${other.key.toBase58()}. These option names are alternative ways to name the SAME end user, and the SDK uses that one key for three separate things: the authenticated sender of the relay request, the key screened for sanctions, and the wallet a viewing key is registered against. Splitting them across two keys screens and authenticates different people. Pass one wallet.`
7241
+ `Cloak was given two different wallets: \`${first.option}\` is ${first.key} and \`${other.option}\` is ${other.key}. These option names are alternative ways to name the SAME end user, and the SDK uses that one key for three separate things: the authenticated sender of the relay request, the key screened for sanctions, and the wallet a viewing key is registered against. Splitting them across two keys screens and authenticates different people. Pass one wallet.`
6957
7242
  );
6958
7243
  }
6959
7244
  return first.key;
@@ -6962,22 +7247,22 @@ function planRelayAuth(options) {
6962
7247
  const walletPublicKey = resolveUserWallet(options);
6963
7248
  if (options.depositorKeypair) return { kind: "keypair" };
6964
7249
  const signMessage = options.signMessage;
6965
- const signAuthTransaction = options.signAuthTransaction;
6966
- if (walletPublicKey && signMessage) return { kind: "wallet", signer: { walletPublicKey, signMessage } };
6967
- if (walletPublicKey && signAuthTransaction) {
6968
- return { kind: "wallet", signer: { walletPublicKey, signAuthTransaction } };
7250
+ const signer = options.signer;
7251
+ if (walletPublicKey && signMessage) {
7252
+ return { kind: "wallet", signer: messageSignerFromCallback(walletPublicKey, signMessage) };
6969
7253
  }
6970
- if (!walletPublicKey && !signMessage && !signAuthTransaction) return { kind: "none" };
7254
+ if (signer) return { kind: "wallet", signer };
7255
+ if (!walletPublicKey && !signMessage) return { kind: "none" };
6971
7256
  return {
6972
7257
  kind: "incomplete",
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."
7258
+ detail: signMessage ? "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 `signer`, so nothing can sign. Add `signMessage` from the wallet adapter, or `signer` (the wallet wrapped by `signerFromWalletAdapter`) for a wallet that cannot sign messages."
6974
7259
  };
6975
7260
  }
6976
7261
  function assertRelayAuthAvailable(plan, flow) {
6977
7262
  if (plan.kind === "keypair" || plan.kind === "wallet") return;
6978
7263
  const cause = plan.kind === "none" ? "no signer was provided." : `the signer provided cannot produce one: ${plan.detail}`;
6979
7264
  throw new Error(
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.`
7265
+ `Cloak ${flow} requires an authenticated sender, and ${cause} Pass either \`depositorKeypair\` (a local key pair), or \`signMessage\` (a browser wallet adapter) together with \`walletPublicKey\`, or \`signer\` (the wallet as a kit signer; a hardware wallet that cannot sign messages authenticates by transaction). The sender must be the end user's own wallet. Checked up front, so nothing has been computed or submitted yet.`
6981
7266
  );
6982
7267
  }
6983
7268
  async function submitTransactToRelay(args) {
@@ -7188,7 +7473,7 @@ async function transact(params, options) {
7188
7473
  relayer,
7189
7474
  relayUrl: relayUrlOverride,
7190
7475
  depositorKeypair,
7191
- signTransaction: signTransaction2,
7476
+ signer,
7192
7477
  depositorPublicKey,
7193
7478
  // `walletPublicKey` is deliberately NOT destructured here. Reading it directly is how three
7194
7479
  // different answers to "which key is the user" grew in this file; every reader of it now goes
@@ -7280,7 +7565,7 @@ async function transact(params, options) {
7280
7565
  throw new Error(`Balance mismatch: ${inputSum} + ${externalAmount} != ${outputSum}`);
7281
7566
  }
7282
7567
  if (externalAmount > BigInt(0)) {
7283
- const isNativeDeposit = mint.equals(NATIVE_SOL_MINT);
7568
+ const isNativeDeposit = mint === NATIVE_SOL_MINT;
7284
7569
  if (isNativeDeposit && externalAmount < BigInt(MIN_DEPOSIT_LAMPORTS)) {
7285
7570
  throw new Error(
7286
7571
  `Deposit amount too small: ${externalAmount} lamports. Minimum is ${MIN_DEPOSIT_LAMPORTS} (0.01 SOL).`
@@ -7288,7 +7573,7 @@ async function transact(params, options) {
7288
7573
  }
7289
7574
  } else if (externalAmount < BigInt(0)) {
7290
7575
  const withdrawAmount = -externalAmount;
7291
- const isNativeWithdraw = mint.equals(NATIVE_SOL_MINT);
7576
+ const isNativeWithdraw = mint === NATIVE_SOL_MINT;
7292
7577
  if (isNativeWithdraw && !isWithdrawAmountSufficient(withdrawAmount)) {
7293
7578
  const fee = calculateFeeBigint(withdrawAmount);
7294
7579
  throw new Error(
@@ -7296,7 +7581,7 @@ async function transact(params, options) {
7296
7581
  );
7297
7582
  }
7298
7583
  }
7299
- const pdas = getShieldPoolPDAs(programId, mint);
7584
+ const pdas = await getShieldPoolPDAs(programId, mint);
7300
7585
  const needsTreeForProof = paddedInputs.some(
7301
7586
  (utxo) => utxo.amount > BigInt(0) && utxo.index !== void 0
7302
7587
  );
@@ -7306,7 +7591,7 @@ async function transact(params, options) {
7306
7591
  const chainIndexingEnabled = options.useChainForMerkle === true || typeof process !== "undefined" && !!process.env && (process.env.CLOAK_BUILD_TREE_FROM_CHAIN === "true" || process.env.CLOAK_BUILD_TREE_FROM_CHAIN === "1");
7307
7592
  const nearTipMaxDistance = nearTipFallbackMaxDistance(connection);
7308
7593
  const useRelayMerkleByDefault = shouldUseRelayMerkleByDefault(connection);
7309
- const relayMintKey = mint.toBase58();
7594
+ const relayMintKey = mint;
7310
7595
  let relayTreeDisabledForMint = _relayMerkleDisabledMints.has(relayMintKey) || !useRelayMerkleByDefault;
7311
7596
  const requiredRelayIndex = paddedInputs.reduce((maxIndex, utxo) => {
7312
7597
  if (utxo.amount === BigInt(0) || utxo.index === void 0 || utxo.index < 0) {
@@ -7432,7 +7717,7 @@ async function transact(params, options) {
7432
7717
  if (treeState) {
7433
7718
  const chainRoot = merkleTree.root().toString(16).padStart(64, "0");
7434
7719
  if (chainRoot !== treeState.root) {
7435
- const acct = await connection.getAccountInfo(pdas.merkleTree, "confirmed");
7720
+ const acct = await fetchAccountBytes(connection, pdas.merkleTree, "confirmed");
7436
7721
  const stillAccepted = acct ? isRootAccepted(acct.data, chainRoot) : false;
7437
7722
  if (stillAccepted) {
7438
7723
  onProgress?.(`Chain-built tree is behind the tip but its root is still in the on-chain root history; proving against it.`);
@@ -7676,7 +7961,7 @@ async function transact(params, options) {
7676
7961
  const missingRelayIndex = parseMissingRelayIndexError(errorMsg);
7677
7962
  if (retryableProofError && relayUrl && missingRelayIndex && missingRelayIndex.treeLength === 0 && missingRelayIndex.leafIndex > 0 && submissionAttempts >= RELAY_EMPTY_TREE_FAILFAST_RETRIES) {
7678
7963
  throw new Error(
7679
- `Relay commitment cache stayed empty for mint ${mint.toBase58()} after ${submissionAttempts + 1} proof attempts (missing index ${missingRelayIndex.leafIndex}). Relay sync likely failed or is pointing at the wrong mint/RPC.`
7964
+ `Relay commitment cache stayed empty for mint ${mint} after ${submissionAttempts + 1} proof attempts (missing index ${missingRelayIndex.leafIndex}). Relay sync likely failed or is pointing at the wrong mint/RPC.`
7680
7965
  );
7681
7966
  }
7682
7967
  if (retryableProofError && submissionAttempts < maxRootRetries) {
@@ -7872,18 +8157,17 @@ async function transact(params, options) {
7872
8157
  }
7873
8158
  const isDeposit = externalAmount > BigInt(0);
7874
8159
  if (isDeposit) {
7875
- const hasKeypairSigning2 = !!depositorKeypair;
7876
- const hasWalletSigning2 = !!(signTransaction2 && depositorPublicKey);
7877
- if (!hasKeypairSigning2 && !hasWalletSigning2) {
8160
+ const depositSigner = depositorKeypair ?? signer;
8161
+ if (!depositSigner) {
7878
8162
  throw new Error(
7879
- "Deposits require depositorKeypair or signTransaction + depositorPublicKey. The depositor must sign to transfer SOL into the shielded pool."
8163
+ "Deposits require depositorKeypair or signer. The depositor must sign to transfer SOL into the shielded pool."
7880
8164
  );
7881
8165
  }
7882
8166
  onProgress?.("Submitting deposit transaction (user signs)...");
7883
8167
  try {
7884
8168
  const nullifier0Bytes = bigintToBytes322(inputNullifiers[0]);
7885
8169
  const nullifier1Bytes = bigintToBytes322(inputNullifiers[1]);
7886
- const depositor = hasKeypairSigning2 ? { keypair: depositorKeypair, publicKey: depositorKeypair.publicKey } : { publicKey: depositorPublicKey, signTransaction: signTransaction2 };
8170
+ const depositor = depositSigner;
7887
8171
  const directResult = await submitTransactionDirect(
7888
8172
  connection,
7889
8173
  programId,
@@ -7906,7 +8190,8 @@ async function transact(params, options) {
7906
8190
  relayerFee,
7907
8191
  options.onTransactProofBuilt,
7908
8192
  externalFeePayer,
7909
- options.relaySupplementalAlt
8193
+ options.relaySupplementalAlt,
8194
+ options.transactionVersion
7910
8195
  );
7911
8196
  signature = directResult.signature;
7912
8197
  commitmentIndices = directResult.commitmentIndices;
@@ -7928,14 +8213,14 @@ async function transact(params, options) {
7928
8213
  break;
7929
8214
  }
7930
8215
  }
7931
- const hasKeypairSigning = !!depositorKeypair;
7932
- const hasWalletSigning = !!(signTransaction2 && depositorPublicKey);
7933
- if (!relayUrl && (hasKeypairSigning || hasWalletSigning)) {
8216
+ const directSigner = depositorKeypair ?? signer;
8217
+ void depositorPublicKey;
8218
+ if (!relayUrl && directSigner) {
7934
8219
  onProgress?.("Submitting transaction directly (no relay)...");
7935
8220
  try {
7936
8221
  const nullifier0Bytes = bigintToBytes322(inputNullifiers[0]);
7937
8222
  const nullifier1Bytes = bigintToBytes322(inputNullifiers[1]);
7938
- const depositor = hasKeypairSigning ? { keypair: depositorKeypair, publicKey: depositorKeypair.publicKey } : { publicKey: depositorPublicKey, signTransaction: signTransaction2 };
8223
+ const depositor = directSigner;
7939
8224
  const directResult = await submitTransactionDirect(
7940
8225
  connection,
7941
8226
  programId,
@@ -7958,7 +8243,10 @@ async function transact(params, options) {
7958
8243
  altAddresses,
7959
8244
  relayer ?? null,
7960
8245
  relayerFee,
7961
- options.onTransactProofBuilt
8246
+ options.onTransactProofBuilt,
8247
+ void 0,
8248
+ void 0,
8249
+ options.transactionVersion
7962
8250
  );
7963
8251
  signature = directResult.signature;
7964
8252
  commitmentIndices = directResult.commitmentIndices;
@@ -8004,10 +8292,10 @@ async function transact(params, options) {
8004
8292
  } catch {
8005
8293
  url = new URL(baseUrl, typeof window !== "undefined" ? window.location.origin : "http://localhost");
8006
8294
  }
8007
- url.searchParams.set("wallet", depositorPubkey.toBase58());
8008
- url.searchParams.set("recipient", recipient.toBase58());
8295
+ url.searchParams.set("wallet", depositorPubkey);
8296
+ url.searchParams.set("recipient", recipient);
8009
8297
  url.searchParams.set("context", "withdraw");
8010
- url.searchParams.set("pool_mint", mint.toBase58());
8298
+ url.searchParams.set("pool_mint", mint);
8011
8299
  url.searchParams.set("nullifier0", toHex(bigintToBytes322(inputNullifiers[0])));
8012
8300
  url.searchParams.set("nullifier1", toHex(bigintToBytes322(inputNullifiers[1])));
8013
8301
  const quoteRes = await relayFetch(url.toString());
@@ -8033,9 +8321,9 @@ async function transact(params, options) {
8033
8321
  } catch {
8034
8322
  url = new URL(baseUrl, typeof window !== "undefined" ? window.location.origin : "http://localhost");
8035
8323
  }
8036
- url.searchParams.set("wallet", depositorPubkey.toBase58());
8324
+ url.searchParams.set("wallet", depositorPubkey);
8037
8325
  url.searchParams.set("context", "send");
8038
- url.searchParams.set("pool_mint", mint.toBase58());
8326
+ url.searchParams.set("pool_mint", mint);
8039
8327
  url.searchParams.set(
8040
8328
  "nullifier0",
8041
8329
  inputNullifiers[0].toString(16).padStart(64, "0")
@@ -8102,7 +8390,7 @@ async function transact(params, options) {
8102
8390
  relayAuthSigner: relayAuthPlan.kind === "wallet" ? relayAuthPlan.signer : void 0,
8103
8391
  relayAuthBatch: options.relayAuthBatch,
8104
8392
  settlement: {
8105
- connection,
8393
+ connection: settlementConnectionFromRpc(connection),
8106
8394
  programId,
8107
8395
  mint,
8108
8396
  inputNullifiers
@@ -8146,10 +8434,7 @@ async function transact(params, options) {
8146
8434
  "All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
8147
8435
  );
8148
8436
  try {
8149
- const [merkleTreePda] = PublicKey10.findProgramAddressSync(
8150
- [Buffer.from("merkle_tree"), mint.toBuffer()],
8151
- programId
8152
- );
8437
+ const [merkleTreePda] = await findProgramAddress(["merkle_tree", addressBytes(mint)], programId);
8153
8438
  const chainTree = await buildMerkleTreeFromChain(
8154
8439
  connection,
8155
8440
  programId,
@@ -8522,18 +8807,16 @@ async function swapUtxo(params, options) {
8522
8807
  throw new Error("Maximum 2 input UTXOs allowed");
8523
8808
  }
8524
8809
  assertInputMints(inputUtxos, NATIVE_SOL_MINT);
8525
- if (options.expectedMint && !options.expectedMint.equals(NATIVE_SOL_MINT)) {
8810
+ if (options.expectedMint && options.expectedMint !== NATIVE_SOL_MINT) {
8526
8811
  throw new Error(
8527
- `swapUtxo expects ${NATIVE_SOL_MINT.toBase58()} input notes (a swap always spends from the wSOL pool), but expectedMint was ${options.expectedMint.toBase58()}. Drop expectedMint, or spend the other mint with transact/transfer instead.`
8812
+ `swapUtxo expects ${NATIVE_SOL_MINT} input notes (a swap always spends from the wSOL pool), but expectedMint was ${options.expectedMint}. Drop expectedMint, or spend the other mint with transact/transfer instead.`
8528
8813
  );
8529
8814
  }
8530
8815
  await preflightNullifiers(inputUtxos, connection, programId);
8531
- const outputMintAccount = await connection.getAccountInfo(outputMint, {
8532
- commitment: "confirmed"
8533
- });
8816
+ const outputMintAccount = await fetchAccountBytes(connection, outputMint, "confirmed");
8534
8817
  if (!outputMintAccount) {
8535
8818
  throw new Error(
8536
- `Swap output mint ${outputMint.toBase58()} is not available on current RPC (${connection.rpcEndpoint}). Use a mainnet RPC/fork with that mint, or choose a mint that exists on this validator.`
8819
+ `Swap output mint ${outputMint} is not available on current RPC (${rpcEndpoint(connection)}). Use a mainnet RPC/fork with that mint, or choose a mint that exists on this validator.`
8537
8820
  );
8538
8821
  }
8539
8822
  const totalInputAmount = sumUtxoAmounts(inputUtxos);
@@ -8555,7 +8838,7 @@ async function swapUtxo(params, options) {
8555
8838
  }
8556
8839
  }
8557
8840
  const swapPoolMint = NATIVE_SOL_MINT;
8558
- const pdas = getShieldPoolPDAs(programId, swapPoolMint);
8841
+ const pdas = await getShieldPoolPDAs(programId, swapPoolMint);
8559
8842
  let merkleState = null;
8560
8843
  const paddedInputs = [...inputUtxos];
8561
8844
  while (paddedInputs.length < 2) {
@@ -8620,7 +8903,7 @@ async function swapUtxo(params, options) {
8620
8903
  const chainIndexingEnabled = useChainForMerkle === true || typeof process !== "undefined" && !!process.env && (process.env.CLOAK_BUILD_TREE_FROM_CHAIN === "true" || process.env.CLOAK_BUILD_TREE_FROM_CHAIN === "1");
8621
8904
  const nearTipMaxDistance = nearTipFallbackMaxDistance(connection);
8622
8905
  const useRelayMerkleByDefault = shouldUseRelayMerkleByDefault(connection);
8623
- const relayMintKey = swapPoolMint.toBase58();
8906
+ const relayMintKey = swapPoolMint;
8624
8907
  let relayTreeDisabledForMint = _relayMerkleDisabledMints.has(relayMintKey) || !useRelayMerkleByDefault;
8625
8908
  const hasCachedTree = !!cachedMerkleTree && cachedMerkleTree.length > 0;
8626
8909
  const requiredRelayIndex = paddedInputs.reduce((maxIndex, utxo) => {
@@ -8739,7 +9022,7 @@ async function swapUtxo(params, options) {
8739
9022
  if (merkleState) {
8740
9023
  const chainRoot = merkleTree.root().toString(16).padStart(64, "0");
8741
9024
  if (chainRoot !== merkleState.root) {
8742
- const acct = await connection.getAccountInfo(pdas.merkleTree, "confirmed");
9025
+ const acct = await fetchAccountBytes(connection, pdas.merkleTree, "confirmed");
8743
9026
  if (acct && isRootAccepted(acct.data, chainRoot)) {
8744
9027
  onProgress?.("Chain-built tree is behind the tip but its root is still accepted on chain; proving against it.");
8745
9028
  merkleState = { ...merkleState, root: chainRoot, nextIndex: merkleTree.length };
@@ -8971,7 +9254,7 @@ async function swapUtxo(params, options) {
8971
9254
  const missingRelayIndex = parseMissingRelayIndexError(errorMsg);
8972
9255
  if (retryableProofError && relayUrl && missingRelayIndex && missingRelayIndex.treeLength === 0 && missingRelayIndex.leafIndex > 0 && attempt >= RELAY_EMPTY_TREE_FAILFAST_RETRIES) {
8973
9256
  throw new Error(
8974
- `Relay commitment cache stayed empty for mint ${swapPoolMint.toBase58()} after ${attempt + 1} proof attempts (missing index ${missingRelayIndex.leafIndex}). Relay sync likely failed or is pointing at the wrong mint/RPC.`
9257
+ `Relay commitment cache stayed empty for mint ${swapPoolMint} after ${attempt + 1} proof attempts (missing index ${missingRelayIndex.leafIndex}). Relay sync likely failed or is pointing at the wrong mint/RPC.`
8975
9258
  );
8976
9259
  }
8977
9260
  if (retryableProofError && attempt < maxRootRetries) {
@@ -9132,10 +9415,10 @@ async function swapUtxo(params, options) {
9132
9415
  } catch {
9133
9416
  url = new URL(baseUrl, typeof window !== "undefined" ? window.location.origin : "http://localhost");
9134
9417
  }
9135
- url.searchParams.set("wallet", poolPda.toBase58());
9136
- url.searchParams.set("recipient", recipientWallet.toBase58());
9137
- url.searchParams.set("sender", recipientWallet.toBase58());
9138
- url.searchParams.set("pool_mint", mint.toBase58());
9418
+ url.searchParams.set("wallet", poolPda);
9419
+ url.searchParams.set("recipient", recipientWallet);
9420
+ url.searchParams.set("sender", recipientWallet);
9421
+ url.searchParams.set("pool_mint", mint);
9139
9422
  url.searchParams.set("nullifier0", toHex(bigintToBytes322(inputNullifiers[0])));
9140
9423
  url.searchParams.set("nullifier1", toHex(bigintToBytes322(inputNullifiers[1])));
9141
9424
  const quoteRes = await relayFetch(url.toString());
@@ -9157,18 +9440,15 @@ async function swapUtxo(params, options) {
9157
9440
  }
9158
9441
  if (options.onSwapStatePredicted && inputNullifiers.length > 0) {
9159
9442
  const nBytes = bigintToBytes322(inputNullifiers[0]);
9160
- const [ssp] = PublicKey10.findProgramAddressSync(
9161
- [Buffer.from("swap_state"), pdas.pool.toBuffer(), Buffer.from(nBytes)],
9162
- programId
9163
- );
9164
- await options.onSwapStatePredicted(ssp.toBase58());
9443
+ const [ssp] = await findProgramAddress(["swap_state", addressBytes(pdas.pool), new Uint8Array(nBytes)], programId);
9444
+ await options.onSwapStatePredicted(ssp);
9165
9445
  }
9166
9446
  const requestBody = {
9167
9447
  proof_bytes: proofB64,
9168
9448
  public_inputs: publicInputsB64,
9169
- output_mint: outputMint.toBase58(),
9170
- recipient_ata: recipientAta.toBase58(),
9171
- recipient: recipientWallet?.toBase58(),
9449
+ output_mint: outputMint,
9450
+ recipient_ata: recipientAta,
9451
+ recipient: recipientWallet,
9172
9452
  // The relay parses this as a u64 and rejects a JSON number ("invalid type: integer,
9173
9453
  // expected a string"). A string also removes the old 2^53 ceiling instead of guarding it.
9174
9454
  min_output_amount: minOutputAmount.toString(),
@@ -9577,7 +9857,7 @@ function cleanupStalePendingOperations(maxAgeMs = 24 * 60 * 60 * 1e3) {
9577
9857
  }
9578
9858
 
9579
9859
  // src/relay/batch-auth.ts
9580
- import { Keypair as Keypair4 } from "@solana/web3.js";
9860
+ import { isKeyPairSigner as isKeyPairSigner2 } from "@solana/kit";
9581
9861
  var RelayBatchAuthCoordinator = class {
9582
9862
  constructor(options) {
9583
9863
  this.proofSlotsInUse = 0;
@@ -9600,7 +9880,7 @@ var RelayBatchAuthCoordinator = class {
9600
9880
  throw new Error(`submitConcurrency must be a positive integer (got ${concurrency}).`);
9601
9881
  }
9602
9882
  this.signer = options.signer;
9603
- this.sender = options.signer instanceof Keypair4 ? options.signer.publicKey : options.signer.walletPublicKey;
9883
+ this.sender = options.signer.address;
9604
9884
  this.expectedItems = options.items;
9605
9885
  this.submitConcurrency = concurrency;
9606
9886
  const proofConcurrency = options.proofConcurrency ?? 2;
@@ -9712,7 +9992,7 @@ var RelayBatchAuthCoordinator = class {
9712
9992
  try {
9713
9993
  const programId = waiting[0].programId;
9714
9994
  for (const w of waiting) {
9715
- if (!w.programId.equals(programId)) {
9995
+ if (w.programId !== programId) {
9716
9996
  throw new Error("Every item of a batch must target the same program id.");
9717
9997
  }
9718
9998
  }
@@ -9724,15 +10004,15 @@ var RelayBatchAuthCoordinator = class {
9724
10004
  const issuedAt = preimages[0].auth_issued_at;
9725
10005
  const message = buildRelayBatchAuthMessage(programId, issuedAt, digests);
9726
10006
  this.waves += 1;
9727
- if (!(this.signer instanceof Keypair4)) {
9728
- const asTransaction = !this.signer.signMessage;
10007
+ if (!isKeyPairSigner2(this.signer)) {
10008
+ const asTransaction = !("signMessages" in this.signer || "modifyAndSignMessages" in this.signer);
9729
10009
  this.onProgress?.(
9730
10010
  `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
10011
  );
9732
10012
  }
9733
10013
  const approvalStartedMs = Date.now();
9734
10014
  const { signature, mode } = await signRelayAuthPayload(this.signer, message);
9735
- if (!(this.signer instanceof Keypair4)) {
10015
+ if (!isKeyPairSigner2(this.signer)) {
9736
10016
  assertApprovalWithinFreshnessWindow(
9737
10017
  Date.now() - approvalStartedMs,
9738
10018
  REQUEST_AUTH_BATCH_MAX_AGE_SECONDS
@@ -9799,16 +10079,13 @@ async function transactBatch(items, options) {
9799
10079
  const { proofConcurrency, submitConcurrency, ...shared } = options;
9800
10080
  const signer = shared.depositorKeypair ? shared.depositorKeypair : (() => {
9801
10081
  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
- }
10082
+ if (wallet && shared.signMessage) return messageSignerFromCallback(wallet, shared.signMessage);
10083
+ if (shared.signer) return shared.signer;
9807
10084
  return null;
9808
10085
  })();
9809
10086
  if (!signer) {
9810
10087
  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."
10088
+ "transactBatch requires an authenticated sender: pass `depositorKeypair` (a local key pair), or `walletPublicKey` with `signMessage` (a browser wallet adapter), or `signer` (a hardware wallet). Checked up front, so nothing has been computed or submitted yet."
9812
10089
  );
9813
10090
  }
9814
10091
  const coordinator = createRelayBatchAuthCoordinator({
@@ -9844,10 +10121,7 @@ async function transactBatch(items, options) {
9844
10121
 
9845
10122
  // src/scanning/scan.ts
9846
10123
  import _bs583 from "bs58";
9847
- import {
9848
- PublicKey as PublicKey12
9849
- } from "@solana/web3.js";
9850
- import { getAssociatedTokenAddressSync as getAssociatedTokenAddressSync2 } from "@solana/spl-token";
10124
+ import { findAssociatedTokenPda as findAssociatedTokenPda2, TOKEN_PROGRAM_ADDRESS as TOKEN_PROGRAM_ADDRESS2 } from "@solana-program/token";
9851
10125
  var bs583 = _bs583.default || _bs583;
9852
10126
  var TRANSACT_TAG2 = 0;
9853
10127
  var TRANSACT_SWAP_TAG3 = 1;
@@ -9858,7 +10132,7 @@ var CHAIN_NOTES_OFFSET_TRANSACT = 1 + PROOF_LEN3 + PUBLIC_INPUTS_LEN3;
9858
10132
  var CHAIN_NOTES_OFFSET_TRANSACT_SWAP = 1 + PROOF_LEN3 + PUBLIC_INPUTS_LEN3 + SWAP_PARAMS_LEN;
9859
10133
  var PUBLIC_INPUTS_OFFSET = 1 + PROOF_LEN3;
9860
10134
  var SWAP_OUTPUT_MINT_OFFSET = CHAIN_NOTES_OFFSET_TRANSACT;
9861
- var TOKEN_PROGRAM_ID2 = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
10135
+ var TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
9862
10136
  var SOL_MINT = "So11111111111111111111111111111111111111112";
9863
10137
  var USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
9864
10138
  var USDT_MINT = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
@@ -9933,7 +10207,7 @@ function parseSwapOutputMint(data) {
9933
10207
  const mintBytes = data.slice(SWAP_OUTPUT_MINT_OFFSET, end);
9934
10208
  if (mintBytes.every((byte) => byte === 0)) return void 0;
9935
10209
  try {
9936
- return new PublicKey12(mintBytes).toBase58();
10210
+ return addressFromBytes(mintBytes);
9937
10211
  } catch {
9938
10212
  return void 0;
9939
10213
  }
@@ -9982,7 +10256,7 @@ function inferAssetMeta(meta, accountKeys, ixAccountKeyIndexes) {
9982
10256
  return { mint: SOL_MINT, decimals: 9 };
9983
10257
  }
9984
10258
  const tokenProgramAtLayoutPos = ixAccountKeyIndexes.length > 9 ? accountKeyToBase58(accountKeys[ixAccountKeyIndexes[9]]) : void 0;
9985
- const isSplTransact = tokenProgramAtLayoutPos === TOKEN_PROGRAM_ID2;
10259
+ const isSplTransact = tokenProgramAtLayoutPos === TOKEN_PROGRAM_ID;
9986
10260
  if (!isSplTransact) {
9987
10261
  return { mint: SOL_MINT, decimals: 9 };
9988
10262
  }
@@ -9999,7 +10273,7 @@ function inferSplFeeFromTreasury(meta, accountKeys, ixAccountKeyIndexes) {
9999
10273
  if (!Array.isArray(accountKeys) || !Array.isArray(ixAccountKeyIndexes)) return null;
10000
10274
  if (ixAccountKeyIndexes.length <= 11) return null;
10001
10275
  const tokenProgramAtLayoutPos = ixAccountKeyIndexes.length > 9 ? accountKeyToBase58(accountKeys[ixAccountKeyIndexes[9]]) : void 0;
10002
- if (tokenProgramAtLayoutPos !== TOKEN_PROGRAM_ID2) return null;
10276
+ if (tokenProgramAtLayoutPos !== TOKEN_PROGRAM_ID) return null;
10003
10277
  const treasuryAccountIndex = ixAccountKeyIndexes[11];
10004
10278
  if (!Number.isInteger(treasuryAccountIndex) || treasuryAccountIndex < 0) return null;
10005
10279
  const tokenEntries = collectTokenBalanceEntries(meta);
@@ -10023,7 +10297,7 @@ function parseSwapRecipientAta(data) {
10023
10297
  const recipientAtaBytes = data.slice(recipientAtaStart, recipientAtaEnd);
10024
10298
  if (recipientAtaBytes.every((byte) => byte === 0)) return void 0;
10025
10299
  try {
10026
- return new PublicKey12(recipientAtaBytes).toBase58();
10300
+ return addressFromBytes(recipientAtaBytes);
10027
10301
  } catch {
10028
10302
  return void 0;
10029
10303
  }
@@ -10090,7 +10364,7 @@ function parseTransactIxContext(data, accountKeys, ixAccountKeyIndexes, meta) {
10090
10364
  }
10091
10365
  } else if (tag === TRANSACT_TAG2 && publicAmount < 0n && Array.isArray(ixAccountKeyIndexes) && Array.isArray(accountKeys) && ixAccountKeyIndexes.length >= 8) {
10092
10366
  const tokenProgramAtLayoutPos = ixAccountKeyIndexes.length > 9 ? accountKeyToBase58(accountKeys[ixAccountKeyIndexes[9]]) : void 0;
10093
- if (tokenProgramAtLayoutPos === TOKEN_PROGRAM_ID2 && ixAccountKeyIndexes.length > 10) {
10367
+ if (tokenProgramAtLayoutPos === TOKEN_PROGRAM_ID && ixAccountKeyIndexes.length > 10) {
10094
10368
  const recipientAtaIdx = ixAccountKeyIndexes[10];
10095
10369
  if (Number.isInteger(recipientAtaIdx) && recipientAtaIdx >= 0 && recipientAtaIdx < accountKeys.length) {
10096
10370
  recipient = accountKeyToBase58(accountKeys[recipientAtaIdx]) ?? "unknown";
@@ -10185,10 +10459,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
10185
10459
  let rpcCalls = 0;
10186
10460
  const candidates = Array.from(swapCtxByCommitment.keys());
10187
10461
  if (candidates.length === 0) return { records, rpcCalls };
10188
- const [registry] = PublicKey12.findProgramAddressSync(
10189
- [Buffer.from("cloak_chain_note_registry")],
10190
- programId
10191
- );
10462
+ const [registry] = await findProgramAddress(["cloak_chain_note_registry"], programId);
10192
10463
  onStatus?.("Scanning swap note-carrier registry...");
10193
10464
  const carrierSigs = [];
10194
10465
  let before;
@@ -10196,7 +10467,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
10196
10467
  let batch = [];
10197
10468
  try {
10198
10469
  batch = await withRpcRetry(
10199
- () => connection.getSignaturesForAddress(registry, { before, limit: SIGNATURE_PAGE_SIZE })
10470
+ () => fetchSignaturesForAddress(connection, registry, { before, limit: SIGNATURE_PAGE_SIZE })
10200
10471
  );
10201
10472
  } catch {
10202
10473
  break;
@@ -10214,7 +10485,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
10214
10485
  let tx = null;
10215
10486
  try {
10216
10487
  tx = await withRpcRetry(
10217
- () => connection.getTransaction(si.signature, {
10488
+ () => fetchTransactionJson(connection, si.signature, {
10218
10489
  commitment: "confirmed",
10219
10490
  maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
10220
10491
  })
@@ -10289,7 +10560,7 @@ async function scanRecipientDeliveryNotes(opts) {
10289
10560
  const viewingSecret = deriveViewingKeyFromNk(viewingKeyNk).privateKey;
10290
10561
  const notes = [];
10291
10562
  let rpcCalls = 0;
10292
- const registry = getDeliveryRegistryPDA(programId);
10563
+ const registry = await getDeliveryRegistryPDA(programId);
10293
10564
  onStatus?.("Scanning recipient-delivery registry...");
10294
10565
  const carrierSigs = [];
10295
10566
  let before;
@@ -10297,7 +10568,7 @@ async function scanRecipientDeliveryNotes(opts) {
10297
10568
  let batch = [];
10298
10569
  try {
10299
10570
  batch = await withRpcRetry(
10300
- () => connection.getSignaturesForAddress(registry, { before, limit: SIGNATURE_PAGE_SIZE })
10571
+ () => fetchSignaturesForAddress(connection, registry, { before, limit: SIGNATURE_PAGE_SIZE })
10301
10572
  );
10302
10573
  } catch {
10303
10574
  break;
@@ -10315,7 +10586,7 @@ async function scanRecipientDeliveryNotes(opts) {
10315
10586
  let tx = null;
10316
10587
  try {
10317
10588
  tx = await withRpcRetry(
10318
- () => connection.getTransaction(si.signature, {
10589
+ () => fetchTransactionJson(connection, si.signature, {
10319
10590
  commitment: "confirmed",
10320
10591
  maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
10321
10592
  })
@@ -10356,7 +10627,7 @@ async function scanRecipientDeliveryNotes(opts) {
10356
10627
  });
10357
10628
  if (recomputed.toString(16).padStart(64, "0") === parsed.commitment) {
10358
10629
  commitmentVerified = true;
10359
- matchedMint = mint.toBase58();
10630
+ matchedMint = mint;
10360
10631
  break;
10361
10632
  }
10362
10633
  }
@@ -10421,7 +10692,7 @@ async function scanTransactions(opts) {
10421
10692
  while (true) {
10422
10693
  try {
10423
10694
  rawBatch = await withRpcRetry(
10424
- () => connection.getSignaturesForAddress(programId, {
10695
+ () => fetchSignaturesForAddress(connection, programId, {
10425
10696
  before: beforeSig,
10426
10697
  limit: signaturePageSize
10427
10698
  })
@@ -10486,7 +10757,7 @@ async function scanTransactions(opts) {
10486
10757
  batchSigs.map(async (sigInfo) => {
10487
10758
  try {
10488
10759
  return await withRpcRetry(
10489
- () => connection.getTransaction(sigInfo.signature, {
10760
+ () => fetchTransactionJson(connection, sigInfo.signature, {
10490
10761
  commitment: "confirmed",
10491
10762
  maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
10492
10763
  })
@@ -10509,13 +10780,13 @@ async function scanTransactions(opts) {
10509
10780
  const loadedAddresses = tx.meta?.loadedAddresses;
10510
10781
  let accountKeys;
10511
10782
  if (loadedAddresses) {
10512
- const writable = Array.isArray(loadedAddresses.writable) ? loadedAddresses.writable : [];
10783
+ const writable2 = Array.isArray(loadedAddresses.writable) ? loadedAddresses.writable : [];
10513
10784
  const readonly_ = Array.isArray(loadedAddresses.readonly) ? loadedAddresses.readonly : [];
10514
- accountKeys = [...staticKeys, ...writable, ...readonly_];
10785
+ accountKeys = [...staticKeys, ...writable2, ...readonly_];
10515
10786
  } else {
10516
10787
  accountKeys = staticKeys;
10517
10788
  }
10518
- const programIdStr = programId.toBase58();
10789
+ const programIdStr = programId;
10519
10790
  const allIxs = [];
10520
10791
  const normalizeAccountIndexes = (value) => {
10521
10792
  if (!Array.isArray(value)) return void 0;
@@ -10587,10 +10858,11 @@ async function scanTransactions(opts) {
10587
10858
  const onChainAta = recipientAtaIdx >= 0 && recipientAtaIdx < accountKeys.length ? accountKeyToBase58(accountKeys[recipientAtaIdx]) : void 0;
10588
10859
  if (onChainAta) {
10589
10860
  try {
10590
- const expectedAta = getAssociatedTokenAddressSync2(
10591
- new PublicKey12(asset.mint),
10592
- new PublicKey12(walletPublicKey)
10593
- ).toBase58();
10861
+ const [expectedAta] = await findAssociatedTokenPda2({
10862
+ mint: address(asset.mint),
10863
+ owner: address(walletPublicKey),
10864
+ tokenProgram: TOKEN_PROGRAM_ADDRESS2
10865
+ });
10594
10866
  if (onChainAta === expectedAta) {
10595
10867
  isOurs = true;
10596
10868
  resolvedRecipient = walletPublicKey;
@@ -10803,7 +11075,7 @@ async function scanTransactions(opts) {
10803
11075
  // deposit — that is the public deposit amount. A deposit that also merged inputs
10804
11076
  // carries a larger output 0 and is not recoverable from public data alone.
10805
11077
  amount: grossAmount,
10806
- mintAddress: new PublicKey12(asset.mint),
11078
+ mintAddress: address(asset.mint),
10807
11079
  outputCommitments: ixCtx.outputCommitments ?? []
10808
11080
  });
10809
11081
  if (recoveredDeposit) {
@@ -10829,7 +11101,7 @@ async function scanTransactions(opts) {
10829
11101
  noteSalt: compactNote.noteSalt,
10830
11102
  amount: compactNote.outAmount0,
10831
11103
  keypair: { privateKey: 0n, publicKey: compactNote.outPubkey0 },
10832
- mintAddress: new PublicKey12(asset.mint),
11104
+ mintAddress: address(asset.mint),
10833
11105
  outputIndex: 0,
10834
11106
  // v4 describes output 0, which is where change lands
10835
11107
  outputCommitments: ixCtx.outputCommitments ?? []
@@ -11022,7 +11294,6 @@ function formatComplianceCsv(report) {
11022
11294
  }
11023
11295
 
11024
11296
  // src/wallet/utxo-wallet.ts
11025
- import { PublicKey as PublicKey13 } from "@solana/web3.js";
11026
11297
  var UtxoWallet = class _UtxoWallet {
11027
11298
  constructor(viewingKey) {
11028
11299
  this.wallets = /* @__PURE__ */ new Map();
@@ -11032,7 +11303,7 @@ var UtxoWallet = class _UtxoWallet {
11032
11303
  * Add a UTXO to the wallet (discovered from chain or created)
11033
11304
  */
11034
11305
  addUtxo(utxo, mint = NATIVE_SOL_MINT) {
11035
- const mintKey = mint.toBase58();
11306
+ const mintKey = mint;
11036
11307
  if (!this.wallets.has(mintKey)) {
11037
11308
  this.wallets.set(mintKey, {
11038
11309
  mint,
@@ -11056,7 +11327,7 @@ var UtxoWallet = class _UtxoWallet {
11056
11327
  * Mark a UTXO as spent
11057
11328
  */
11058
11329
  markSpent(utxo, mint = NATIVE_SOL_MINT) {
11059
- const wallet = this.wallets.get(mint.toBase58());
11330
+ const wallet = this.wallets.get(mint);
11060
11331
  if (!wallet) return;
11061
11332
  const walletUtxo = wallet.utxos.find(
11062
11333
  (u) => u.amount === utxo.amount && u.keypair.publicKey === utxo.keypair.publicKey && u.blinding === utxo.blinding && !u.isSpent
@@ -11070,7 +11341,7 @@ var UtxoWallet = class _UtxoWallet {
11070
11341
  * Get total balance (unspent only)
11071
11342
  */
11072
11343
  getBalance(mint = NATIVE_SOL_MINT) {
11073
- const wallet = this.wallets.get(mint.toBase58());
11344
+ const wallet = this.wallets.get(mint);
11074
11345
  if (!wallet) return BigInt(0);
11075
11346
  return wallet.utxos.filter((u) => !u.isSpent).reduce((sum, u) => sum + u.amount, BigInt(0));
11076
11347
  }
@@ -11078,7 +11349,7 @@ var UtxoWallet = class _UtxoWallet {
11078
11349
  * Get all unspent UTXOs
11079
11350
  */
11080
11351
  getUnspentUtxos(mint = NATIVE_SOL_MINT) {
11081
- const wallet = this.wallets.get(mint.toBase58());
11352
+ const wallet = this.wallets.get(mint);
11082
11353
  if (!wallet) return [];
11083
11354
  return wallet.utxos.filter((u) => !u.isSpent);
11084
11355
  }
@@ -11168,7 +11439,7 @@ var UtxoWallet = class _UtxoWallet {
11168
11439
  * Create a UTXO for a recipient
11169
11440
  */
11170
11441
  async createOutputUtxo(amount, _recipient) {
11171
- const { randomFieldElement: randomFieldElement2, derivePublicKey: derivePublicKey2 } = await import("./utxo-XPEGGWZ6.js");
11442
+ const { randomFieldElement: randomFieldElement2, derivePublicKey: derivePublicKey2 } = await import("./utxo-TM7UCHTN.js");
11172
11443
  const privateKey = randomFieldElement2();
11173
11444
  const publicKey = await derivePublicKey2(privateKey);
11174
11445
  const blinding = randomFieldElement2();
@@ -11186,7 +11457,7 @@ var UtxoWallet = class _UtxoWallet {
11186
11457
  * Create change output for self
11187
11458
  */
11188
11459
  async createChangeUtxo(amount, _mint) {
11189
- const { randomFieldElement: randomFieldElement2, derivePublicKey: derivePublicKey2 } = await import("./utxo-XPEGGWZ6.js");
11460
+ const { randomFieldElement: randomFieldElement2, derivePublicKey: derivePublicKey2 } = await import("./utxo-TM7UCHTN.js");
11190
11461
  const privateKey = randomFieldElement2();
11191
11462
  const publicKey = await derivePublicKey2(privateKey);
11192
11463
  const blinding = randomFieldElement2();
@@ -11234,7 +11505,7 @@ var UtxoWallet = class _UtxoWallet {
11234
11505
  data.viewingKey ? new Uint8Array(data.viewingKey) : void 0
11235
11506
  );
11236
11507
  for (const w of data.wallets) {
11237
- const mint = new PublicKey13(w.mint);
11508
+ const mint = address(w.mint);
11238
11509
  for (const u of w.utxos) {
11239
11510
  wallet.addUtxo({
11240
11511
  amount: BigInt(u.amount),
@@ -11266,7 +11537,7 @@ var UtxoWallet = class _UtxoWallet {
11266
11537
  * Get wallet statistics
11267
11538
  */
11268
11539
  getStats(mint = NATIVE_SOL_MINT) {
11269
- const wallet = this.wallets.get(mint.toBase58());
11540
+ const wallet = this.wallets.get(mint);
11270
11541
  if (!wallet) {
11271
11542
  return {
11272
11543
  totalUtxos: 0,
@@ -11316,8 +11587,66 @@ var SimpleWallet = class {
11316
11587
  }
11317
11588
  };
11318
11589
 
11590
+ // src/solana/compat.ts
11591
+ import {
11592
+ createSignerFromKeyPair,
11593
+ createKeyPairSignerFromBytes as createKeyPairSignerFromBytes2
11594
+ } from "@solana/kit";
11595
+ function addressFromPublicKey(publicKey) {
11596
+ return address(publicKey.toBase58());
11597
+ }
11598
+ function signerFromKeypair(keypair) {
11599
+ return createKeyPairSignerFromBytes2(keypair.secretKey);
11600
+ }
11601
+ function signerFromWalletAdapter(adapter, options = {}) {
11602
+ if (!adapter.publicKey) throw new Error("Wallet adapter has no public key (not connected)");
11603
+ const walletAddress = addressFromPublicKey(adapter.publicKey);
11604
+ const signer = {
11605
+ address: walletAddress,
11606
+ async modifyAndSignTransactions(transactions) {
11607
+ if (!adapter.signTransaction) throw new Error("Wallet adapter cannot sign transactions");
11608
+ const web3 = options.web3 ?? await loadWeb3();
11609
+ const out = [];
11610
+ for (const transaction of transactions) {
11611
+ const legacy = web3.VersionedTransaction.deserialize(transactionBytes(transaction));
11612
+ const signed = await adapter.signTransaction(legacy);
11613
+ const decoded = transactionFromBytes(signed.serialize());
11614
+ out.push({ ...transaction, ...decoded });
11615
+ }
11616
+ return out;
11617
+ }
11618
+ };
11619
+ if (adapter.signMessage) {
11620
+ const signMessage = adapter.signMessage.bind(adapter);
11621
+ Object.assign(signer, {
11622
+ async signMessages(messages) {
11623
+ const dictionaries = [];
11624
+ for (const message of messages) {
11625
+ const signature = await signMessage(message.content);
11626
+ dictionaries.push({ [walletAddress]: signature });
11627
+ }
11628
+ return dictionaries;
11629
+ }
11630
+ });
11631
+ }
11632
+ return signer;
11633
+ }
11634
+ async function loadWeb3() {
11635
+ const name = "@solana/web3.js";
11636
+ try {
11637
+ return await import(
11638
+ /* webpackIgnore: true */
11639
+ name
11640
+ );
11641
+ } catch {
11642
+ throw new Error(
11643
+ "signerFromWalletAdapter needs @solana/web3.js to hand a VersionedTransaction to the wallet: pass it in (`signerFromWalletAdapter(adapter, { web3: { VersionedTransaction } })`) or install it where the SDK can import it"
11644
+ );
11645
+ }
11646
+ }
11647
+
11319
11648
  // src/bridge/rail-verify.ts
11320
- import nacl7 from "tweetnacl";
11649
+ import nacl6 from "tweetnacl";
11321
11650
  import { sha256 as sha2565 } from "@noble/hashes/sha256";
11322
11651
  var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
11323
11652
  var b58 = /* @__PURE__ */ (() => {
@@ -11428,7 +11757,7 @@ function verifyQuoteSignature(resp) {
11428
11757
  const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
11429
11758
  const sig = resp.signature.replace(/^ed25519:/, "");
11430
11759
  try {
11431
- return { valid: nacl7.sign.detached.verify(message, b58.decode(sig), b58.decode(ONECLICK_PUBKEY_B58)) };
11760
+ return { valid: nacl6.sign.detached.verify(message, b58.decode(sig), b58.decode(ONECLICK_PUBKEY_B58)) };
11432
11761
  } catch (e) {
11433
11762
  return { valid: false, reason: e instanceof Error ? e.message : String(e) };
11434
11763
  }
@@ -11526,63 +11855,62 @@ function cloakBridgeRail(relayUrl) {
11526
11855
  }
11527
11856
 
11528
11857
  // src/bridge/paymaster-client.ts
11529
- import {
11530
- PublicKey as PublicKey14,
11531
- SystemInstruction,
11532
- SystemProgram as SystemProgram4,
11533
- Transaction as Transaction4
11534
- } from "@solana/web3.js";
11535
- import { TOKEN_PROGRAM_ID as TOKEN_PROGRAM_ID3, decodeTransferInstruction, getAssociatedTokenAddressSync as getAssociatedTokenAddressSync3 } from "@solana/spl-token";
11536
- function validatePaymasterTopUpTransaction(tx, expect) {
11537
- const ixs = tx.instructions;
11858
+ import { getCompiledTransactionMessageDecoder, getInstructionsFromCompiledTransactionMessage } from "@solana/kit";
11859
+ import { parseTransferSolInstruction } from "@solana-program/system";
11860
+ import { TOKEN_PROGRAM_ADDRESS as TOKEN_PROGRAM_ADDRESS3, findAssociatedTokenPda as findAssociatedTokenPda3, parseTransferInstruction } from "@solana-program/token";
11861
+ async function validatePaymasterTopUpTransaction(tx, expect) {
11862
+ const compiledMessage = getCompiledTransactionMessageDecoder().decode(tx.messageBytes);
11863
+ const ixs = getInstructionsFromCompiledTransactionMessage(compiledMessage);
11538
11864
  if (ixs.length !== 1 && ixs.length !== 2) {
11539
11865
  throw new Error(
11540
11866
  `paymaster top-up must be exactly 1 or 2 instructions, got ${ixs.length} \u2014 refusing to sign a transaction whose shape does not match the documented top-up contract`
11541
11867
  );
11542
11868
  }
11543
11869
  const ix0 = ixs[0];
11544
- if (!ix0.programId.equals(SystemProgram4.programId)) {
11870
+ if (ix0.programAddress !== SYSTEM_PROGRAM_ADDRESS) {
11545
11871
  throw new Error(
11546
- `paymaster top-up instruction 0 is owned by ${ix0.programId.toBase58()}, not the System Program \u2014 refusing to sign an unrecognised first instruction`
11872
+ `paymaster top-up instruction 0 is owned by ${ix0.programAddress}, not the System Program \u2014 refusing to sign an unrecognised first instruction`
11547
11873
  );
11548
11874
  }
11549
- const transfer2 = SystemInstruction.decodeTransfer(ix0);
11550
- if (!transfer2.toPubkey.equals(expect.recipient)) {
11875
+ const transfer2 = parseTransferSolInstruction(
11876
+ ix0
11877
+ );
11878
+ if (transfer2.accounts.destination.address !== expect.recipient) {
11551
11879
  throw new Error(
11552
- `paymaster top-up sends SOL to ${transfer2.toPubkey.toBase58()}, which is not our recipient ${expect.recipient.toBase58()} \u2014 refusing to sign a transaction that funds a key we do not control`
11880
+ `paymaster top-up sends SOL to ${transfer2.accounts.destination.address}, which is not our recipient ${expect.recipient} \u2014 refusing to sign a transaction that funds a key we do not control`
11553
11881
  );
11554
11882
  }
11555
- if (BigInt(transfer2.lamports) > expect.maxGrantLamports) {
11883
+ if (transfer2.data.amount > expect.maxGrantLamports) {
11556
11884
  throw new Error(
11557
- `paymaster top-up grants ${transfer2.lamports} lamports, more than the ${expect.maxGrantLamports} we asked for \u2014 refusing a transaction that funds beyond our own request`
11885
+ `paymaster top-up grants ${transfer2.data.amount} lamports, more than the ${expect.maxGrantLamports} we asked for \u2014 refusing a transaction that funds beyond our own request`
11558
11886
  );
11559
11887
  }
11560
11888
  if (ixs.length === 1) return;
11561
11889
  const ix1 = ixs[1];
11562
- if (!ix1.programId.equals(TOKEN_PROGRAM_ID3)) {
11890
+ if (ix1.programAddress !== TOKEN_PROGRAM_ADDRESS3) {
11563
11891
  throw new Error(
11564
- `paymaster top-up instruction 1 is owned by ${ix1.programId.toBase58()}, not the SPL Token program \u2014 refusing to sign an unrecognised second instruction`
11892
+ `paymaster top-up instruction 1 is owned by ${ix1.programAddress}, not the SPL Token program \u2014 refusing to sign an unrecognised second instruction`
11565
11893
  );
11566
11894
  }
11567
- const spl = decodeTransferInstruction(ix1, TOKEN_PROGRAM_ID3);
11568
- const authority = spl.keys.owner.pubkey;
11569
- if (!authority.equals(expect.recipient)) {
11895
+ const spl = parseTransferInstruction(ix1);
11896
+ const authority = spl.accounts.authority.address;
11897
+ if (authority !== expect.recipient) {
11570
11898
  throw new Error(
11571
- `paymaster top-up's fee transfer is authorised by ${authority.toBase58()}, not our recipient ${expect.recipient.toBase58()} \u2014 refusing to sign away tokens from an account we do not control`
11899
+ `paymaster top-up's fee transfer is authorised by ${authority}, not our recipient ${expect.recipient} \u2014 refusing to sign away tokens from an account we do not control`
11572
11900
  );
11573
11901
  }
11574
- const expectedDestination = getAssociatedTokenAddressSync3(
11575
- expect.feeMint,
11576
- expect.paymentAddress,
11577
- false
11578
- );
11579
- const destination = spl.keys.destination.pubkey;
11580
- if (!destination.equals(expectedDestination)) {
11902
+ const [expectedDestination] = await findAssociatedTokenPda3({
11903
+ mint: expect.feeMint,
11904
+ owner: expect.paymentAddress,
11905
+ tokenProgram: TOKEN_PROGRAM_ADDRESS3
11906
+ });
11907
+ const destination = spl.accounts.destination.address;
11908
+ if (destination !== expectedDestination) {
11581
11909
  throw new Error(
11582
- `paymaster top-up's fee transfer is addressed to ${destination.toBase58()}, not the paymaster's own payment ATA ${expectedDestination.toBase58()} \u2014 refusing to sign a payment to an unverified destination`
11910
+ `paymaster top-up's fee transfer is addressed to ${destination}, not the paymaster's own payment ATA ${expectedDestination} \u2014 refusing to sign a payment to an unverified destination`
11583
11911
  );
11584
11912
  }
11585
- const paidAmount = BigInt(spl.data.amount);
11913
+ const paidAmount = spl.data.amount;
11586
11914
  if (paidAmount !== expect.feeTokenAmount) {
11587
11915
  throw new Error(
11588
11916
  `paymaster top-up's fee amount is ${paidAmount}, not the ${expect.feeTokenAmount} Kora quoted at prepare time \u2014 refusing to sign a payment that does not match the quote`
@@ -11615,7 +11943,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
11615
11943
  method: "POST",
11616
11944
  headers: { "Content-Type": "application/json" },
11617
11945
  body: JSON.stringify({
11618
- recipient: receiver.publicKey.toBase58(),
11946
+ recipient: receiver.address,
11619
11947
  grant_lamports: Number(grantLamports)
11620
11948
  })
11621
11949
  });
@@ -11625,29 +11953,29 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
11625
11953
  "paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
11626
11954
  );
11627
11955
  }
11628
- const feeMint = new PublicKey14(prepared.fee_mint);
11629
- const paymentAddress = new PublicKey14(prepared.payment_address);
11956
+ const feeMint = address(prepared.fee_mint);
11957
+ const paymentAddress = address(prepared.payment_address);
11630
11958
  const feeTokenAmount = BigInt(prepared.fee_token_amount);
11631
- const tx = Transaction4.from(Buffer.from(prepared.transaction, "base64"));
11632
- validatePaymasterTopUpTransaction(tx, {
11633
- recipient: receiver.publicKey,
11959
+ const tx = transactionFromBytes(base64ToBytes(prepared.transaction));
11960
+ await validatePaymasterTopUpTransaction(tx, {
11961
+ recipient: receiver.address,
11634
11962
  maxGrantLamports: grantLamports,
11635
11963
  feeMint,
11636
11964
  feeTokenAmount,
11637
11965
  paymentAddress
11638
11966
  });
11639
- tx.partialSign(receiver);
11967
+ const partiallySigned = await signCompiledTransaction(receiver, tx);
11640
11968
  const cosignRes = await relayFetch(`${relayUrl}/bridge/paymaster/cosign`, {
11641
11969
  method: "POST",
11642
11970
  headers: { "Content-Type": "application/json" },
11643
11971
  body: JSON.stringify({
11644
- transaction: tx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString("base64"),
11972
+ transaction: bytesToBase64(transactionBytes(partiallySigned)),
11645
11973
  voucher: prepared.voucher
11646
11974
  })
11647
11975
  });
11648
11976
  const cosigned = await parseBridgeResponse2(cosignRes, "paymaster cosign");
11649
11977
  return {
11650
- transaction: Transaction4.from(Buffer.from(cosigned.transaction, "base64")),
11978
+ transaction: transactionFromBytes(base64ToBytes(cosigned.transaction)),
11651
11979
  feeTokenAmount,
11652
11980
  feeMint: prepared.fee_mint,
11653
11981
  paymentAddress: prepared.payment_address
@@ -11655,12 +11983,11 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
11655
11983
  }
11656
11984
 
11657
11985
  // src/bridge/derive.ts
11658
- import { Keypair as Keypair6 } from "@solana/web3.js";
11659
11986
  import { hmac } from "@noble/hashes/hmac";
11660
11987
  import { sha512 } from "@noble/hashes/sha512";
11661
11988
  var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
11662
11989
  var MAX_RECEIVER_INDEX = 1e4;
11663
- function deriveBridgeReceiver(nk, index) {
11990
+ async function deriveBridgeReceiver(nk, index) {
11664
11991
  if (!Number.isInteger(index) || index < 0) {
11665
11992
  throw new Error(`index must be a non-negative integer, got ${index}`);
11666
11993
  }
@@ -11670,54 +11997,56 @@ function deriveBridgeReceiver(nk, index) {
11670
11997
  );
11671
11998
  }
11672
11999
  const h = hmac(sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
11673
- return Keypair6.fromSeed(h.slice(0, 32));
12000
+ return signerFromSecretKey(h.slice(0, 32));
11674
12001
  }
11675
12002
 
11676
12003
  // src/bridge/discover.ts
11677
- import { SolanaJSONRPCError } from "@solana/web3.js";
11678
- import { getAssociatedTokenAddressSync as getAssociatedTokenAddressSync4 } from "@solana/spl-token";
12004
+ import { isSolanaError } from "@solana/kit";
12005
+ import { TOKEN_PROGRAM_ADDRESS as TOKEN_PROGRAM_ADDRESS4, findAssociatedTokenPda as findAssociatedTokenPda4 } from "@solana-program/token";
11679
12006
  function describeError(err) {
11680
12007
  return err instanceof Error ? err.message : String(err);
11681
12008
  }
11682
- async function listBridgeDeposits(conn, nk, opts) {
12009
+ async function listBridgeDeposits(rpc, nk, opts) {
11683
12010
  const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
11684
12011
  const stopAfterUnused = opts.stopAfterUnused ?? 5;
11685
12012
  const out = [];
11686
12013
  let consecutiveUnused = 0;
11687
12014
  for (let index = 0; index < scanDepth; index++) {
11688
- const kp = deriveBridgeReceiver(nk, index);
11689
- const receiver = kp.publicKey;
11690
- const tokenAccount = getAssociatedTokenAddressSync4(opts.mint, receiver, false);
12015
+ const kp = await deriveBridgeReceiver(nk, index);
12016
+ const receiver = kp.address;
12017
+ const [tokenAccount] = await findAssociatedTokenPda4({
12018
+ mint: opts.mint,
12019
+ owner: receiver,
12020
+ tokenProgram: TOKEN_PROGRAM_ADDRESS4
12021
+ });
11691
12022
  try {
11692
- const [recvInfo, ataInfo] = await conn.getMultipleAccountsInfo([receiver, tokenAccount]);
11693
- const lamports = recvInfo?.lamports ?? 0;
12023
+ const [recvInfo, ataInfo] = await fetchMultipleAccountBytes(rpc, [receiver, tokenAccount]);
12024
+ const lamports = recvInfo?.lamports ?? 0n;
11694
12025
  let tokenBalance = 0n;
11695
12026
  if (ataInfo) {
11696
12027
  try {
11697
- tokenBalance = BigInt((await conn.getTokenAccountBalance(tokenAccount)).value.amount);
12028
+ tokenBalance = BigInt((await rpc.getTokenAccountBalance(tokenAccount).send()).value.amount);
11698
12029
  } catch (err) {
11699
- if (!(err instanceof SolanaJSONRPCError && /could not find account/i.test(err.message))) {
12030
+ if (!(isSolanaError(err) && /could not find account/i.test(err.message))) {
11700
12031
  throw err;
11701
12032
  }
11702
12033
  }
11703
12034
  }
11704
- if (lamports === 0 && !ataInfo) {
12035
+ if (lamports === 0n && !ataInfo) {
11705
12036
  consecutiveUnused++;
11706
12037
  if (consecutiveUnused >= stopAfterUnused) break;
11707
12038
  continue;
11708
12039
  }
11709
12040
  consecutiveUnused = 0;
11710
12041
  const shieldSignatures = [];
11711
- const sigs = await conn.getSignaturesForAddress(receiver, { limit: 20 });
12042
+ const sigs = await fetchSignaturesForAddress(rpc, receiver, { limit: 20 });
11712
12043
  for (const s of sigs) {
11713
12044
  if (s.err) continue;
11714
- const tx = await conn.getTransaction(s.signature, {
12045
+ const tx = await fetchParsedTransaction(rpc, s.signature, {
11715
12046
  maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
11716
12047
  });
11717
- const keys = tx?.transaction.message.getAccountKeys({
11718
- accountKeysFromLookups: tx.meta?.loadedAddresses
11719
- });
11720
- if (keys && [...Array(keys.length).keys()].some((i) => keys.get(i)?.equals(opts.programId))) {
12048
+ const keys = tx?.transaction.message.accountKeys;
12049
+ if (keys && keys.some((k) => k.pubkey === opts.programId)) {
11721
12050
  shieldSignatures.push(s.signature);
11722
12051
  }
11723
12052
  }
@@ -11744,7 +12073,7 @@ async function listBridgeDeposits(conn, nk, opts) {
11744
12073
  tokenAccount,
11745
12074
  state: "unknown",
11746
12075
  tokenBalance: 0n,
11747
- lamports: 0,
12076
+ lamports: 0n,
11748
12077
  error: describeError(err)
11749
12078
  });
11750
12079
  }
@@ -11754,37 +12083,38 @@ async function listBridgeDeposits(conn, nk, opts) {
11754
12083
 
11755
12084
  // src/bridge/deposit-core.ts
11756
12085
  import {
11757
- SystemProgram as SystemProgram5,
11758
- Transaction as Transaction5,
11759
- VersionedTransaction as VersionedTransaction2,
11760
- sendAndConfirmTransaction as sendAndConfirmTransaction2
11761
- } from "@solana/web3.js";
11762
- import nacl8 from "tweetnacl";
12086
+ getCompiledTransactionMessageDecoder as getCompiledTransactionMessageDecoder2,
12087
+ getInstructionsFromCompiledTransactionMessage as getInstructionsFromCompiledTransactionMessage2
12088
+ } from "@solana/kit";
12089
+ import { getTransferSolInstruction as getTransferSolInstruction2 } from "@solana-program/system";
11763
12090
 
11764
12091
  // src/bridge/funder.ts
11765
- import { PublicKey as PublicKey16 } from "@solana/web3.js";
11766
- import { getAssociatedTokenAddressSync as getAssociatedTokenAddressSync5 } from "@solana/spl-token";
12092
+ import { TOKEN_PROGRAM_ADDRESS as TOKEN_PROGRAM_ADDRESS5, findAssociatedTokenPda as findAssociatedTokenPda5 } from "@solana-program/token";
11767
12093
  var MAINNET_RENT_0 = 890880;
11768
12094
  var MAINNET_RENT_1 = 897840;
11769
12095
  var FEE_BUDGET = 13e4;
11770
12096
  var CLEANUP_FEE_BUDGET = 5e3;
11771
- var pda = (seeds, programId) => PublicKey16.findProgramAddressSync(seeds.map((s) => Buffer.from(s)), programId)[0];
11772
- function deriveFundingTargets(d) {
11773
- const pool = pda([Buffer.from("pool"), d.mint.toBuffer()], d.programId);
11774
- return {
11775
- pool,
12097
+ async function pda(seeds, programId) {
12098
+ const [address2] = await findProgramAddress(seeds, programId);
12099
+ return address2;
12100
+ }
12101
+ async function deriveFundingTargets(d) {
12102
+ const pool = await pda(["pool", addressBytes(d.mint)], d.programId);
12103
+ const poolBytes = addressBytes(pool);
12104
+ const [nullifier0, nullifier1, riskNonce, [depositorAta]] = await Promise.all([
11776
12105
  // program: NullifierAccount::derive_pda_with_pool -> [b"nullifier", pool, nullifier]
11777
- nullifier0: pda([Buffer.from("nullifier"), pool.toBuffer(), d.nullifiers[0]], d.programId),
11778
- nullifier1: pda([Buffer.from("nullifier"), pool.toBuffer(), d.nullifiers[1]], d.programId),
12106
+ pda(["nullifier", poolBytes, d.nullifiers[0]], d.programId),
12107
+ pda(["nullifier", poolBytes, d.nullifiers[1]], d.programId),
11779
12108
  // relay: derive_risk_nonce_pda -> [b"risk_nonce", bind0]
11780
- riskNonce: pda([Buffer.from("risk_nonce"), d.bind0], d.programId),
11781
- depositorAta: getAssociatedTokenAddressSync5(d.mint, d.depositor, false)
11782
- };
12109
+ pda(["risk_nonce", d.bind0], d.programId),
12110
+ findAssociatedTokenPda5({ mint: d.mint, owner: d.depositor, tokenProgram: TOKEN_PROGRAM_ADDRESS5 })
12111
+ ]);
12112
+ return { pool, nullifier0, nullifier1, riskNonce, depositorAta };
11783
12113
  }
11784
- async function readRent(conn) {
12114
+ async function readRent(rpc) {
11785
12115
  const [zero, one] = await Promise.all([
11786
- conn.getMinimumBalanceForRentExemption(0),
11787
- conn.getMinimumBalanceForRentExemption(1)
12116
+ rpc.getMinimumBalanceForRentExemption(0n).send(),
12117
+ rpc.getMinimumBalanceForRentExemption(1n).send()
11788
12118
  ]);
11789
12119
  return { zero, one };
11790
12120
  }
@@ -11798,7 +12128,66 @@ var DepositError = class extends Error {
11798
12128
  this.name = "DepositError";
11799
12129
  }
11800
12130
  };
11801
- async function depositFromDerivedKey(conn, R, funder, amount, log = console.log, grantOverride, opts) {
12131
+ async function resolveLoadedAddresses(rpc, compiled) {
12132
+ const lookups = compiled.addressTableLookups ?? [];
12133
+ if (lookups.length === 0) return { writable: [], readonly: [] };
12134
+ const tables = await fetchLookupTables(rpc, lookups.map((l) => l.lookupTableAddress));
12135
+ const writable2 = [];
12136
+ const readonly2 = [];
12137
+ lookups.forEach((lookup, i) => {
12138
+ const addresses = tables[i].addresses;
12139
+ for (const idx of lookup.writableIndexes) writable2.push(addresses[idx]);
12140
+ for (const idx of lookup.readonlyIndexes) readonly2.push(addresses[idx]);
12141
+ });
12142
+ return { writable: writable2, readonly: readonly2 };
12143
+ }
12144
+ function makeDepositSigner(params) {
12145
+ const { rpc, R, funder, programId, log, state } = params;
12146
+ return {
12147
+ address: R.address,
12148
+ signMessages: (messages) => R.signMessages(messages),
12149
+ async signTransactions(transactions) {
12150
+ const out = [];
12151
+ for (const tx of transactions) {
12152
+ state.measuredSize = transactionBytes(tx).length;
12153
+ const compiled = getCompiledTransactionMessageDecoder2().decode(tx.messageBytes);
12154
+ const loadedAddresses = await resolveLoadedAddresses(rpc, compiled);
12155
+ const instructions = getInstructionsFromCompiledTransactionMessage2(compiled, loadedAddresses);
12156
+ const transactIx = instructions.find((i) => i.programAddress === programId);
12157
+ if (!transactIx || !transactIx.accounts) {
12158
+ throw new Error(
12159
+ "deposit transaction has no instruction for the Cloak program \u2014 cannot locate the accounts the funding seam needs to fund"
12160
+ );
12161
+ }
12162
+ const at = (n) => transactIx.accounts[n].address;
12163
+ const targets = [
12164
+ { a: at(12), need: MAINNET_RENT_0, name: "risk_nonce" },
12165
+ { a: at(4), need: MAINNET_RENT_1, name: "nullifier_0" },
12166
+ { a: at(5), need: MAINNET_RENT_1, name: "nullifier_1" }
12167
+ ];
12168
+ const infos = await fetchMultipleAccountBytes(rpc, targets.map((t) => t.a));
12169
+ state.fundedAccounts = targets.map((t, i) => ({
12170
+ name: t.name,
12171
+ address: t.a,
12172
+ lamportsSent: Math.max(0, t.need - Number(infos[i]?.lamports ?? 0n))
12173
+ }));
12174
+ const fundingInstructions = targets.flatMap((t, i) => {
12175
+ const held = infos[i]?.lamports ?? 0n;
12176
+ const need = BigInt(t.need);
12177
+ return held >= need ? [] : [getTransferSolInstruction2({ source: funder, destination: t.a, amount: need - held })];
12178
+ });
12179
+ if (fundingInstructions.length > 0) {
12180
+ const sig = await sendInstructions(rpc, funder, fundingInstructions);
12181
+ log(` seam: funded ${fundingInstructions.length} program accounts read off the built tx \u2014 ${sig.slice(0, 16)}\u2026`);
12182
+ }
12183
+ const [signatures] = await R.signTransactions([tx]);
12184
+ out.push(signatures);
12185
+ }
12186
+ return out;
12187
+ }
12188
+ };
12189
+ }
12190
+ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log, grantOverride, opts) {
11802
12191
  if (!opts.noteSpendKey || opts.noteSpendKey.length !== 32) {
11803
12192
  throw new Error(
11804
12193
  "opts.noteSpendKey (32 bytes) is required. It derives the note's spending key, and a note whose key is not derived from something you can reproduce is unspendable forever. Pass the same Cloak seed you derived the receiving address from."
@@ -11819,77 +12208,43 @@ async function depositFromDerivedKey(conn, R, funder, amount, log = console.log,
11819
12208
  "opts.mint is required. There is no default: a deposit built for the wrong mint produces a note for an asset that never arrived at R, and there is nothing to silently fall back to."
11820
12209
  );
11821
12210
  }
11822
- assertAllowedRpcConnection(conn);
12211
+ assertAllowedRpcConnection(rpc);
11823
12212
  const relayUrl = opts.relayUrl;
11824
12213
  const programId = opts.programId;
11825
12214
  const mint = opts.mint;
11826
12215
  setCircuitsPath(resolveCircuitsBase());
11827
- const grantR = grantOverride ?? MAINNET_RENT_0 + FEE_BUDGET + CLEANUP_FEE_BUDGET;
11828
- const heldByR = await conn.getBalance(R.publicKey);
12216
+ const grantR = BigInt(grantOverride ?? MAINNET_RENT_0 + FEE_BUDGET + CLEANUP_FEE_BUDGET);
12217
+ const heldByR = (await rpc.getBalance(R.address).send()).value;
11829
12218
  if (heldByR >= grantR) {
11830
12219
  log(` R already holds ${heldByR} (>= ${grantR}) \u2014 no top-up needed`);
11831
12220
  } else {
11832
- await sendAndConfirmTransaction2(conn, new Transaction5().add(
11833
- SystemProgram5.transfer({ fromPubkey: funder.publicKey, toPubkey: R.publicKey, lamports: grantR - heldByR })
11834
- ), [funder]);
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"}`);
11836
- }
11837
- let measuredSize = -1;
11838
- let fundedAccounts = [];
11839
- const signTransaction2 = async (tx) => {
11840
- if (tx instanceof VersionedTransaction2) {
11841
- measuredSize = tx.serialize().length;
11842
- const alts = await Promise.all(
11843
- tx.message.addressTableLookups.map(async (l) => (await conn.getAddressLookupTable(l.accountKey)).value)
11844
- );
11845
- const keys = tx.message.getAccountKeys({ addressLookupTableAccounts: alts });
11846
- const ix = tx.message.compiledInstructions.find((i) => keys.get(i.programIdIndex).equals(programId));
11847
- const at = (n) => keys.get(ix.accountKeyIndexes[n]);
11848
- const targets = [
11849
- { a: at(12), need: MAINNET_RENT_0, name: "risk_nonce" },
11850
- { a: at(4), need: MAINNET_RENT_1, name: "nullifier_0" },
11851
- { a: at(5), need: MAINNET_RENT_1, name: "nullifier_1" }
11852
- ];
11853
- const infos = await conn.getMultipleAccountsInfo(targets.map((t) => t.a));
11854
- fundedAccounts = targets.map((t, i) => ({
11855
- name: t.name,
11856
- address: t.a.toBase58(),
11857
- lamportsSent: Math.max(0, t.need - (infos[i]?.lamports ?? 0))
11858
- }));
11859
- const ixs = targets.flatMap((t, i) => (infos[i]?.lamports ?? 0) >= t.need ? [] : [SystemProgram5.transfer({
11860
- fromPubkey: funder.publicKey,
11861
- toPubkey: t.a,
11862
- lamports: t.need - (infos[i]?.lamports ?? 0)
11863
- })]);
11864
- if (ixs.length) {
11865
- const sig = await sendAndConfirmTransaction2(conn, new Transaction5().add(...ixs), [funder]);
11866
- log(` seam: funded ${ixs.length} program accounts read off the built tx \u2014 ${sig.slice(0, 16)}\u2026`);
11867
- }
11868
- tx.sign([R]);
11869
- return tx;
11870
- }
11871
- tx.partialSign(R);
11872
- return tx;
11873
- };
11874
- const signMessage = async (m) => nacl8.sign.detached(m, R.secretKey);
12221
+ const topUp = grantR - heldByR;
12222
+ await sendInstructions(rpc, funder, [
12223
+ getTransferSolInstruction2({ source: funder, destination: R.address, amount: topUp })
12224
+ ]);
12225
+ log(` funder topped R up by ${topUp} to ${grantR}${grantOverride !== void 0 ? " (OVERRIDDEN for a deliberate test)" : " \u2014 floor + deposit fee + cleanup fee, no rent"}`);
12226
+ }
12227
+ const state = { measuredSize: -1, fundedAccounts: [] };
12228
+ const depositSigner = makeDepositSigner({ rpc, R, funder, programId, log, state });
12229
+ const signMessage = (m) => signMessageBytes(R, m);
11875
12230
  const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
11876
12231
  const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
11877
12232
  const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
11878
12233
  const zeroInput = await createZeroUtxo(mint);
11879
- const rBefore = await conn.getBalance(R.publicKey);
12234
+ const rBefore = (await rpc.getBalance(R.address).send()).value;
11880
12235
  let result;
11881
12236
  try {
11882
12237
  result = await transact(
11883
- { inputUtxos: [zeroInput], outputUtxos: [utxo], externalAmount: amount, depositor: R.publicKey },
12238
+ { inputUtxos: [zeroInput], outputUtxos: [utxo], externalAmount: amount, depositor: R.address },
11884
12239
  {
11885
- connection: conn,
12240
+ connection: rpc,
11886
12241
  programId,
11887
12242
  relayUrl,
11888
- // NO depositorKeypair: the SDK branches `if (keypair) … else if (signTransaction)`
11889
- // (transact.ts:2786, :2936), so passing one silently skips the funding seam.
11890
- depositorPublicKey: R.publicKey,
11891
- walletPublicKey: R.publicKey,
11892
- signTransaction: signTransaction2,
12243
+ // NO depositorKeypair: the SDK branches `if (depositorKeypair) … else if (signer)`
12244
+ // (transact.ts), so passing one silently skips the funding seam.
12245
+ depositorPublicKey: R.address,
12246
+ walletPublicKey: R.address,
12247
+ signer: depositSigner,
11893
12248
  signMessage,
11894
12249
  chainNoteViewingKeyNk: nk,
11895
12250
  chainNoteSalt: noteSalt,
@@ -11899,88 +12254,90 @@ async function depositFromDerivedKey(conn, R, funder, amount, log = console.log,
11899
12254
  );
11900
12255
  } catch (e) {
11901
12256
  const msg = e instanceof Error ? e.message : String(e);
11902
- throw new DepositError(msg, fundedAccounts, measuredSize);
12257
+ throw new DepositError(msg, state.fundedAccounts, state.measuredSize);
11903
12258
  }
11904
- const rAfter = await conn.getBalance(R.publicKey);
12259
+ const rAfter = (await rpc.getBalance(R.address).send()).value;
11905
12260
  const noteIndex = result.outputUtxos[0].index;
11906
12261
  if (noteIndex === void 0) throw new Error("deposit landed but the note has no index \u2014 it cannot be discovered later");
11907
12262
  return {
11908
12263
  signature: result.signature,
11909
12264
  noteIndex,
11910
12265
  amount: result.outputUtxos[0].amount,
11911
- txSize: measuredSize,
11912
- rBefore,
11913
- rAfter,
11914
- rentExempt: rAfter >= MAINNET_RENT_0,
12266
+ txSize: state.measuredSize,
12267
+ rBefore: Number(rBefore),
12268
+ rAfter: Number(rAfter),
12269
+ rentExempt: rAfter >= BigInt(MAINNET_RENT_0),
11915
12270
  inputNullifiers: result.inputNullifiers,
11916
- fundedAccounts
12271
+ fundedAccounts: state.fundedAccounts
11917
12272
  };
11918
12273
  }
11919
12274
 
11920
12275
  // src/bridge/cleanup.ts
11921
12276
  import {
11922
- PublicKey as PublicKey18,
11923
- Transaction as Transaction6,
11924
- sendAndConfirmTransaction as sendAndConfirmTransaction3
11925
- } from "@solana/web3.js";
11926
- import {
11927
- getAssociatedTokenAddressSync as getAssociatedTokenAddressSync6,
11928
- createCloseAccountInstruction,
11929
- createTransferInstruction,
11930
- createAssociatedTokenAccountIdempotentInstruction,
11931
- getMinimumBalanceForRentExemptAccount
11932
- } from "@solana/spl-token";
11933
- var DEFAULT_MINT = new PublicKey18("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
11934
- async function cleanupReceivingAddress(conn, R, dustDestination, mint = DEFAULT_MINT) {
11935
- assertAllowedRpcConnection(conn);
11936
- const rAta = getAssociatedTokenAddressSync6(mint, R.publicKey);
11937
- const info = await conn.getAccountInfo(rAta);
12277
+ getCloseAccountInstruction,
12278
+ getCreateAssociatedTokenIdempotentInstruction,
12279
+ getTransferInstruction,
12280
+ getTokenSize,
12281
+ findAssociatedTokenPda as findAssociatedTokenPda6,
12282
+ TOKEN_PROGRAM_ADDRESS as TOKEN_PROGRAM_ADDRESS6
12283
+ } from "@solana-program/token";
12284
+ var DEFAULT_MINT = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
12285
+ async function cleanupReceivingAddress(rpc, R, dustDestination, mint = DEFAULT_MINT) {
12286
+ assertAllowedRpcConnection(rpc);
12287
+ const [rAta] = await findAssociatedTokenPda6({ mint, owner: R.address, tokenProgram: TOKEN_PROGRAM_ADDRESS6 });
12288
+ const info = await fetchAccountBytes(rpc, rAta);
11938
12289
  if (!info) {
11939
12290
  return {
11940
12291
  closed: false,
11941
12292
  dustSwept: 0n,
11942
- rentReturned: 0,
12293
+ rentReturned: 0n,
11943
12294
  destination: null,
11944
12295
  signature: null,
11945
12296
  note: "no token account \u2014 nothing to recover"
11946
12297
  };
11947
12298
  }
11948
- const bal = BigInt((await conn.getTokenAccountBalance(rAta)).value.amount);
12299
+ const bal = BigInt((await rpc.getTokenAccountBalance(rAta).send()).value.amount);
11949
12300
  const rentHeld = info.lamports;
11950
- const before = await conn.getBalance(R.publicKey);
12301
+ const before = (await rpc.getBalance(R.address).send()).value;
11951
12302
  const ixs = [];
11952
12303
  let destination = null;
11953
12304
  if (bal > 0n && !dustDestination) {
11954
12305
  return {
11955
12306
  closed: false,
11956
12307
  dustSwept: 0n,
11957
- rentReturned: 0,
12308
+ rentReturned: 0n,
11958
12309
  destination: null,
11959
12310
  signature: null,
11960
12311
  note: `dusted with ${bal} base units after the deposit; leaving the account open and ${rentHeld.toLocaleString()} lamports of rent unrecovered, because sweeping it would publish a link from this deposit to whoever receives it`
11961
12312
  };
11962
12313
  }
11963
12314
  if (bal > 0n && dustDestination) {
11964
- const destAta = getAssociatedTokenAddressSync6(mint, dustDestination);
11965
- const destInfo = await conn.getAccountInfo(destAta);
12315
+ const [destAta] = await findAssociatedTokenPda6({ mint, owner: dustDestination, tokenProgram: TOKEN_PROGRAM_ADDRESS6 });
12316
+ const destInfo = await fetchAccountBytes(rpc, destAta);
11966
12317
  if (!destInfo) {
11967
- const ataRent = await getMinimumBalanceForRentExemptAccount(conn);
11968
- if (before < ataRent + CLEANUP_FEE_BUDGET) {
12318
+ const ataRent = await rpc.getMinimumBalanceForRentExemption(BigInt(getTokenSize())).send();
12319
+ if (before < ataRent + BigInt(CLEANUP_FEE_BUDGET)) {
11969
12320
  throw new Error(
11970
- `dustDestination ${dustDestination.toBase58()} has no token account for mint ${mint.toBase58()}, and creating one costs ${ataRent} lamports of rent that R does not have: R holds ${before}, which deposit-core.ts reserved only for this transaction's own fee (CLEANUP_FEE_BUDGET = ${CLEANUP_FEE_BUDGET} in funder.ts), not for a fresh account's rent. Fund R with at least ${ataRent + CLEANUP_FEE_BUDGET - before} more lamports first, or choose a destination that already has a token account for this mint.`
12321
+ `dustDestination ${dustDestination} has no token account for mint ${mint}, and creating one costs ${ataRent} lamports of rent that R does not have: R holds ${before}, which deposit-core.ts reserved only for this transaction's own fee (CLEANUP_FEE_BUDGET = ${CLEANUP_FEE_BUDGET} in funder.ts), not for a fresh account's rent. Fund R with at least ${ataRent + BigInt(CLEANUP_FEE_BUDGET) - before} more lamports first, or choose a destination that already has a token account for this mint.`
11971
12322
  );
11972
12323
  }
11973
- ixs.push(createAssociatedTokenAccountIdempotentInstruction(R.publicKey, destAta, dustDestination, mint));
12324
+ ixs.push(
12325
+ getCreateAssociatedTokenIdempotentInstruction({
12326
+ payer: R,
12327
+ ata: destAta,
12328
+ owner: dustDestination,
12329
+ mint,
12330
+ tokenProgram: TOKEN_PROGRAM_ADDRESS6
12331
+ })
12332
+ );
11974
12333
  }
11975
- ixs.push(createTransferInstruction(rAta, destAta, R.publicKey, bal));
11976
- destination = destAta.toBase58();
12334
+ ixs.push(getTransferInstruction({ source: rAta, destination: destAta, authority: R, amount: bal }));
12335
+ destination = destAta;
11977
12336
  }
11978
- ixs.push(createCloseAccountInstruction(rAta, R.publicKey, R.publicKey));
11979
- const signature = await sendAndConfirmTransaction3(conn, new Transaction6().add(...ixs), [R], {
11980
- commitment: "confirmed"
11981
- });
11982
- const after = await conn.getBalance(R.publicKey);
11983
- const gone = await conn.getAccountInfo(rAta) === null;
12337
+ ixs.push(getCloseAccountInstruction({ account: rAta, destination: R.address, owner: R }));
12338
+ const signature = await sendInstructions(rpc, R, ixs, { version: "legacy", commitment: "confirmed" });
12339
+ const after = (await rpc.getBalance(R.address).send()).value;
12340
+ const gone = await fetchAccountBytes(rpc, rAta) === null;
11984
12341
  return {
11985
12342
  closed: gone,
11986
12343
  dustSwept: bal,
@@ -12104,9 +12461,10 @@ async function withShieldRetries(attempt, hooks = {}) {
12104
12461
  }
12105
12462
 
12106
12463
  // src/index.ts
12107
- var VERSION = "0.2.4";
12464
+ var VERSION = "0.2.5";
12108
12465
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
12109
12466
  export {
12467
+ AccountRole,
12110
12468
  BRIDGE_ESCROW_LABEL,
12111
12469
  BUILD_ALLOWS_LOCAL_ENDPOINTS,
12112
12470
  CHAIN_NOTE_SALT_BITS,
@@ -12155,6 +12513,7 @@ export {
12155
12513
  RootNotFoundError,
12156
12514
  SCANNER_SUPPORTS_TRANSACT_SWAP,
12157
12515
  SIGN_IN_MESSAGE,
12516
+ SYSTEM_PROGRAM_ADDRESS,
12158
12517
  SanctionsQuoteError,
12159
12518
  SettlementVerificationError,
12160
12519
  ShieldPoolErrors,
@@ -12163,6 +12522,7 @@ export {
12163
12522
  TRANSACTION_CIRCUITS_VERSION,
12164
12523
  TRANSACT_AUTH_FIELDS,
12165
12524
  TRANSACT_SWAP_AUTH_FIELDS,
12525
+ TransactionConfirmationError,
12166
12526
  UtxoAlreadySpentError,
12167
12527
  UtxoWallet,
12168
12528
  VARIABLE_FEE_DENOMINATOR,
@@ -12171,6 +12531,11 @@ export {
12171
12531
  VERSION,
12172
12532
  WITHDRAW_FEE_BPS,
12173
12533
  WITHDRAW_FIXED_FEE,
12534
+ accountMeta,
12535
+ address,
12536
+ addressBytes,
12537
+ addressFromBytes,
12538
+ addressFromPublicKey,
12174
12539
  assertDirectSubmissionLanded,
12175
12540
  assertInputMints,
12176
12541
  assertTransactionCircuitIntegrity,
@@ -12185,6 +12550,7 @@ export {
12185
12550
  buildRelayAuthPreimage,
12186
12551
  buildRelayBatchAuthMessage,
12187
12552
  buildTransactRequestBody,
12553
+ buildTransactionMessage,
12188
12554
  bytesToHex,
12189
12555
  calculateFee,
12190
12556
  calculateFeeBigint,
@@ -12210,9 +12576,11 @@ export {
12210
12576
  computeSwapRefundCommitment,
12211
12577
  computeCommitment as computeUtxoCommitment,
12212
12578
  computeNullifier as computeUtxoNullifier,
12579
+ confirmSignature,
12213
12580
  confirmTransactSettlement,
12214
12581
  copyNoteToClipboard,
12215
12582
  createCloakError,
12583
+ createCloakRpc,
12216
12584
  createDepositInstruction,
12217
12585
  createLogger,
12218
12586
  createRecoverableChangeUtxo,
@@ -12257,12 +12625,17 @@ export {
12257
12625
  exportKeys,
12258
12626
  exportNote,
12259
12627
  exportWalletKeys,
12628
+ fetchAccountBytes,
12260
12629
  fetchCommitments,
12630
+ fetchLatestBlockhash,
12631
+ fetchLookupTables,
12261
12632
  fetchRiskQuoteInstruction,
12262
12633
  fetchRiskQuoteIx,
12634
+ fetchSignaturesForAddress,
12263
12635
  filterNotesByNetwork,
12264
12636
  filterWithdrawableNotes,
12265
12637
  findNoteByCommitment,
12638
+ findProgramAddress,
12266
12639
  formatAmount,
12267
12640
  formatComplianceCsv,
12268
12641
  formatErrorForLogging,
@@ -12271,6 +12644,7 @@ export {
12271
12644
  fundReceiverViaPaymaster,
12272
12645
  generateCloakKeys,
12273
12646
  generateCommitmentAsync,
12647
+ generateKeyPairSigner,
12274
12648
  generateMasterSeed,
12275
12649
  generateNoteFromWallet,
12276
12650
  generateUtxoKeypair,
@@ -12297,20 +12671,22 @@ export {
12297
12671
  hexToBytes,
12298
12672
  importKeys,
12299
12673
  importWalletKeys,
12674
+ isAddress,
12300
12675
  isBrowser,
12301
12676
  isBrowserLike,
12302
12677
  isDebugEnabled,
12678
+ isMessageSigner,
12303
12679
  isPlausibleSignature,
12304
12680
  isReactNative,
12305
12681
  isRootNotFoundError,
12306
12682
  isSubmissionOutcomeUnknownResponse,
12307
12683
  isTerminalFailure,
12684
+ isTransactionSigner,
12308
12685
  isValidHex,
12309
12686
  isValidRpcUrl,
12310
12687
  isValidSolanaAddress,
12311
12688
  isWithdrawAmountSufficient,
12312
12689
  isWithdrawable,
12313
- keypairToAdapter,
12314
12690
  listBridgeDeposits,
12315
12691
  loadPendingDeposits,
12316
12692
  loadPendingWithdrawals,
@@ -12319,6 +12695,7 @@ export {
12319
12695
  matchDepositNote,
12320
12696
  matchSwapRefundLeaf,
12321
12697
  mayRetry,
12698
+ messageSignerFromCallback,
12322
12699
  openRecipientDeliveryNote,
12323
12700
  parseAmount,
12324
12701
  parseDeliveryCarrierMemo,
@@ -12328,11 +12705,13 @@ export {
12328
12705
  parseRelayErrorSignature,
12329
12706
  parseTransactionError,
12330
12707
  partialWithdraw,
12708
+ partiallySignTransaction,
12331
12709
  poseidonHash,
12332
12710
  preflightCheck,
12333
12711
  preflightNullifiers,
12334
12712
  prepareEncryptedOutput,
12335
12713
  prepareEncryptedOutputForRecipient,
12714
+ programInstruction,
12336
12715
  proofToBytes,
12337
12716
  pubkeyToFieldElement,
12338
12717
  pubkeyToLimbs,
@@ -12357,22 +12736,34 @@ export {
12357
12736
  scanTransactions,
12358
12737
  sdkLogger,
12359
12738
  selectUtxos,
12739
+ sendInstructions,
12740
+ sendRawTransaction,
12360
12741
  sendTransaction,
12361
12742
  serializeAuthTransactionMessage,
12362
12743
  serializeNote,
12363
12744
  serializeUtxo,
12364
12745
  setCircuitsPath,
12365
12746
  setDebugMode,
12747
+ signCompiledTransaction,
12748
+ signMessageBytes,
12366
12749
  signRelayAuthPayload,
12367
12750
  signTransaction,
12751
+ signerFromKeypair,
12752
+ signerFromSecretKey,
12753
+ signerFromWalletAdapter,
12368
12754
  splitTo2Limbs,
12369
12755
  submitTransactToRelay,
12370
12756
  sumUtxoAmounts,
12371
12757
  swapUtxo,
12372
12758
  swapWithChange,
12759
+ toAddress,
12373
12760
  toComplianceReport,
12374
12761
  transact,
12375
12762
  transactBatch,
12763
+ transactionBase64,
12764
+ transactionBytes,
12765
+ transactionFromBytes,
12766
+ transactionWireSize,
12376
12767
  transfer,
12377
12768
  truncate,
12378
12769
  tryDecryptNote,