@cloak.dev/sdk 0.2.4 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -31
- package/dist/{chunk-KNM6K5NG.js → chunk-GM3WEXYP.js} +48 -7
- package/dist/index.cjs +1318 -855
- package/dist/index.d.cts +500 -383
- package/dist/index.d.ts +500 -383
- package/dist/index.js +1281 -890
- package/dist/{utxo-XPEGGWZ6.js → utxo-TM7UCHTN.js} +1 -1
- package/package.json +10 -5
package/dist/index.cjs
CHANGED
|
@@ -30,6 +30,36 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
30
30
|
));
|
|
31
31
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
32
32
|
|
|
33
|
+
// src/solana/address.ts
|
|
34
|
+
function addressBytes(value) {
|
|
35
|
+
return new Uint8Array(ADDRESS_ENCODER.encode((0, import_kit.address)(value)));
|
|
36
|
+
}
|
|
37
|
+
function addressFromBytes(bytes) {
|
|
38
|
+
const u8 = bytes instanceof Uint8Array ? bytes : Uint8Array.from(bytes);
|
|
39
|
+
if (u8.length !== 32) throw new Error(`An address is 32 bytes, got ${u8.length}`);
|
|
40
|
+
return ADDRESS_DECODER.decode(u8);
|
|
41
|
+
}
|
|
42
|
+
function toAddress(value) {
|
|
43
|
+
if (typeof value === "string") return (0, import_kit.address)(value);
|
|
44
|
+
return (0, import_kit.address)(value.toBase58());
|
|
45
|
+
}
|
|
46
|
+
var import_kit, import_system, ADDRESS_ENCODER, ADDRESS_DECODER, DEFAULT_ADDRESS, SYSVAR_INSTRUCTIONS_ADDRESS, SYSVAR_SLOT_HASHES_ADDRESS, SYSVAR_RENT_ADDRESS, SYSVAR_CLOCK_ADDRESS, ED25519_PROGRAM_ADDRESS;
|
|
47
|
+
var init_address = __esm({
|
|
48
|
+
"src/solana/address.ts"() {
|
|
49
|
+
"use strict";
|
|
50
|
+
import_kit = require("@solana/kit");
|
|
51
|
+
import_system = require("@solana-program/system");
|
|
52
|
+
ADDRESS_ENCODER = (0, import_kit.getAddressEncoder)();
|
|
53
|
+
ADDRESS_DECODER = (0, import_kit.getAddressDecoder)();
|
|
54
|
+
DEFAULT_ADDRESS = (0, import_kit.address)("11111111111111111111111111111111");
|
|
55
|
+
SYSVAR_INSTRUCTIONS_ADDRESS = (0, import_kit.address)("Sysvar1nstructions1111111111111111111111111");
|
|
56
|
+
SYSVAR_SLOT_HASHES_ADDRESS = (0, import_kit.address)("SysvarS1otHashes111111111111111111111111111");
|
|
57
|
+
SYSVAR_RENT_ADDRESS = (0, import_kit.address)("SysvarRent111111111111111111111111111111111");
|
|
58
|
+
SYSVAR_CLOCK_ADDRESS = (0, import_kit.address)("SysvarC1ock11111111111111111111111111111111");
|
|
59
|
+
ED25519_PROGRAM_ADDRESS = (0, import_kit.address)("Ed25519SigVerify111111111111111111111111111");
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
|
|
33
63
|
// src/shared/types.ts
|
|
34
64
|
var CloakError;
|
|
35
65
|
var init_types = __esm({
|
|
@@ -66,7 +96,9 @@ function splitTo2Limbs(value) {
|
|
|
66
96
|
return [lo, hi];
|
|
67
97
|
}
|
|
68
98
|
function pubkeyToLimbs(pubkey) {
|
|
69
|
-
const bytes = typeof pubkey
|
|
99
|
+
const bytes = typeof pubkey === "string" ? (0, import_kit.isAddress)(pubkey) ? addressBytes(pubkey) : (() => {
|
|
100
|
+
throw new Error(`Invalid address: ${pubkey}`);
|
|
101
|
+
})() : typeof pubkey.toBytes === "function" ? pubkey.toBytes() : pubkey;
|
|
70
102
|
const value = BigInt("0x" + Buffer.from(bytes).toString("hex"));
|
|
71
103
|
return splitTo2Limbs(value);
|
|
72
104
|
}
|
|
@@ -265,6 +297,7 @@ var import_circomlibjs, poseidon, InsecureRandomnessError, GET_RANDOM_VALUES_MAX
|
|
|
265
297
|
var init_inputs = __esm({
|
|
266
298
|
"src/proving/inputs.ts"() {
|
|
267
299
|
"use strict";
|
|
300
|
+
init_address();
|
|
268
301
|
import_circomlibjs = require("circomlibjs");
|
|
269
302
|
init_types();
|
|
270
303
|
poseidon = null;
|
|
@@ -373,7 +406,7 @@ async function createZeroUtxo(mintAddress = NATIVE_SOL_MINT, salt) {
|
|
|
373
406
|
return utxo;
|
|
374
407
|
}
|
|
375
408
|
function pubkeyToFieldElement(pubkey) {
|
|
376
|
-
const bytes = pubkey
|
|
409
|
+
const bytes = addressBytes(pubkey);
|
|
377
410
|
let value = BigInt(0);
|
|
378
411
|
for (let i = 0; i < 32; i++) {
|
|
379
412
|
value = value << BigInt(8) | BigInt(bytes[i]);
|
|
@@ -381,7 +414,7 @@ function pubkeyToFieldElement(pubkey) {
|
|
|
381
414
|
return value % FIELD_MODULUS;
|
|
382
415
|
}
|
|
383
416
|
function pubkeyToFieldLimbs(pubkey) {
|
|
384
|
-
const bytes = pubkey
|
|
417
|
+
const bytes = addressBytes(pubkey);
|
|
385
418
|
let hi = BigInt(0);
|
|
386
419
|
let lo = BigInt(0);
|
|
387
420
|
for (let i = 0; i < 16; i++) {
|
|
@@ -438,7 +471,7 @@ function serializeUtxo(utxo) {
|
|
|
438
471
|
for (let i = 0; i < 32; i++) {
|
|
439
472
|
view.setUint8(40 + i, blindingBytes[i]);
|
|
440
473
|
}
|
|
441
|
-
const mintBytes = utxo.mintAddress
|
|
474
|
+
const mintBytes = addressBytes(utxo.mintAddress);
|
|
442
475
|
for (let i = 0; i < 32; i++) {
|
|
443
476
|
view.setUint8(72 + i, mintBytes[i]);
|
|
444
477
|
}
|
|
@@ -455,7 +488,7 @@ async function deserializeUtxo(bytes) {
|
|
|
455
488
|
const blindingBytes = bytes.slice(40, 72);
|
|
456
489
|
const blinding = bytesToBigint2(blindingBytes);
|
|
457
490
|
const mintBytes = bytes.slice(72, 104);
|
|
458
|
-
const mintAddress =
|
|
491
|
+
const mintAddress = addressFromBytes(mintBytes);
|
|
459
492
|
const index = view.getUint32(104, true);
|
|
460
493
|
const utxo = {
|
|
461
494
|
amount,
|
|
@@ -523,18 +556,18 @@ function selectUtxos(available, targetAmount) {
|
|
|
523
556
|
}
|
|
524
557
|
return selected;
|
|
525
558
|
}
|
|
526
|
-
var
|
|
559
|
+
var import_circomlibjs2, import_blake33, FIELD_MODULUS, KEYPAIR_DOMAIN_TAG, UTXO_KEY_DOMAIN, NATIVE_SOL_MINT, poseidonInstance;
|
|
527
560
|
var init_utxo = __esm({
|
|
528
561
|
"src/notes/utxo.ts"() {
|
|
529
562
|
"use strict";
|
|
530
|
-
|
|
563
|
+
init_address();
|
|
531
564
|
import_circomlibjs2 = require("circomlibjs");
|
|
532
565
|
import_blake33 = require("@noble/hashes/blake3");
|
|
533
566
|
init_inputs();
|
|
534
567
|
FIELD_MODULUS = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
|
|
535
568
|
KEYPAIR_DOMAIN_TAG = BigInt("5423839527465210463");
|
|
536
569
|
UTXO_KEY_DOMAIN = new TextEncoder().encode("cloak_utxo_priv_v1");
|
|
537
|
-
NATIVE_SOL_MINT =
|
|
570
|
+
NATIVE_SOL_MINT = (0, import_kit.address)("So11111111111111111111111111111111111111112");
|
|
538
571
|
poseidonInstance = null;
|
|
539
572
|
}
|
|
540
573
|
});
|
|
@@ -542,6 +575,7 @@ var init_utxo = __esm({
|
|
|
542
575
|
// src/index.ts
|
|
543
576
|
var index_exports = {};
|
|
544
577
|
__export(index_exports, {
|
|
578
|
+
AccountRole: () => import_kit7.AccountRole,
|
|
545
579
|
BRIDGE_ESCROW_LABEL: () => BRIDGE_ESCROW_LABEL,
|
|
546
580
|
BUILD_ALLOWS_LOCAL_ENDPOINTS: () => BUILD_ALLOWS_LOCAL_ENDPOINTS,
|
|
547
581
|
CHAIN_NOTE_SALT_BITS: () => CHAIN_NOTE_SALT_BITS,
|
|
@@ -590,6 +624,7 @@ __export(index_exports, {
|
|
|
590
624
|
RootNotFoundError: () => RootNotFoundError,
|
|
591
625
|
SCANNER_SUPPORTS_TRANSACT_SWAP: () => SCANNER_SUPPORTS_TRANSACT_SWAP,
|
|
592
626
|
SIGN_IN_MESSAGE: () => SIGN_IN_MESSAGE,
|
|
627
|
+
SYSTEM_PROGRAM_ADDRESS: () => import_system.SYSTEM_PROGRAM_ADDRESS,
|
|
593
628
|
SanctionsQuoteError: () => SanctionsQuoteError,
|
|
594
629
|
SettlementVerificationError: () => SettlementVerificationError,
|
|
595
630
|
ShieldPoolErrors: () => ShieldPoolErrors,
|
|
@@ -598,6 +633,7 @@ __export(index_exports, {
|
|
|
598
633
|
TRANSACTION_CIRCUITS_VERSION: () => TRANSACTION_CIRCUITS_VERSION,
|
|
599
634
|
TRANSACT_AUTH_FIELDS: () => TRANSACT_AUTH_FIELDS,
|
|
600
635
|
TRANSACT_SWAP_AUTH_FIELDS: () => TRANSACT_SWAP_AUTH_FIELDS,
|
|
636
|
+
TransactionConfirmationError: () => TransactionConfirmationError,
|
|
601
637
|
UtxoAlreadySpentError: () => UtxoAlreadySpentError,
|
|
602
638
|
UtxoWallet: () => UtxoWallet,
|
|
603
639
|
VARIABLE_FEE_DENOMINATOR: () => VARIABLE_FEE_DENOMINATOR,
|
|
@@ -606,6 +642,11 @@ __export(index_exports, {
|
|
|
606
642
|
VERSION: () => VERSION,
|
|
607
643
|
WITHDRAW_FEE_BPS: () => WITHDRAW_FEE_BPS,
|
|
608
644
|
WITHDRAW_FIXED_FEE: () => WITHDRAW_FIXED_FEE,
|
|
645
|
+
accountMeta: () => accountMeta,
|
|
646
|
+
address: () => import_kit.address,
|
|
647
|
+
addressBytes: () => addressBytes,
|
|
648
|
+
addressFromBytes: () => addressFromBytes,
|
|
649
|
+
addressFromPublicKey: () => addressFromPublicKey,
|
|
609
650
|
assertDirectSubmissionLanded: () => assertDirectSubmissionLanded,
|
|
610
651
|
assertInputMints: () => assertInputMints,
|
|
611
652
|
assertTransactionCircuitIntegrity: () => assertTransactionCircuitIntegrity,
|
|
@@ -620,6 +661,7 @@ __export(index_exports, {
|
|
|
620
661
|
buildRelayAuthPreimage: () => buildRelayAuthPreimage,
|
|
621
662
|
buildRelayBatchAuthMessage: () => buildRelayBatchAuthMessage,
|
|
622
663
|
buildTransactRequestBody: () => buildTransactRequestBody,
|
|
664
|
+
buildTransactionMessage: () => buildTransactionMessage,
|
|
623
665
|
bytesToHex: () => bytesToHex,
|
|
624
666
|
calculateFee: () => calculateFee,
|
|
625
667
|
calculateFeeBigint: () => calculateFeeBigint,
|
|
@@ -645,9 +687,11 @@ __export(index_exports, {
|
|
|
645
687
|
computeSwapRefundCommitment: () => computeSwapRefundCommitment,
|
|
646
688
|
computeUtxoCommitment: () => computeCommitment2,
|
|
647
689
|
computeUtxoNullifier: () => computeNullifier,
|
|
690
|
+
confirmSignature: () => confirmSignature,
|
|
648
691
|
confirmTransactSettlement: () => confirmTransactSettlement,
|
|
649
692
|
copyNoteToClipboard: () => copyNoteToClipboard,
|
|
650
693
|
createCloakError: () => createCloakError,
|
|
694
|
+
createCloakRpc: () => createCloakRpc,
|
|
651
695
|
createDepositInstruction: () => createDepositInstruction,
|
|
652
696
|
createLogger: () => createLogger,
|
|
653
697
|
createRecoverableChangeUtxo: () => createRecoverableChangeUtxo,
|
|
@@ -692,12 +736,17 @@ __export(index_exports, {
|
|
|
692
736
|
exportKeys: () => exportKeys,
|
|
693
737
|
exportNote: () => exportNote,
|
|
694
738
|
exportWalletKeys: () => exportWalletKeys,
|
|
739
|
+
fetchAccountBytes: () => fetchAccountBytes,
|
|
695
740
|
fetchCommitments: () => fetchCommitments,
|
|
741
|
+
fetchLatestBlockhash: () => fetchLatestBlockhash,
|
|
742
|
+
fetchLookupTables: () => fetchLookupTables,
|
|
696
743
|
fetchRiskQuoteInstruction: () => fetchRiskQuoteInstruction,
|
|
697
744
|
fetchRiskQuoteIx: () => fetchRiskQuoteIx,
|
|
745
|
+
fetchSignaturesForAddress: () => fetchSignaturesForAddress,
|
|
698
746
|
filterNotesByNetwork: () => filterNotesByNetwork,
|
|
699
747
|
filterWithdrawableNotes: () => filterWithdrawableNotes,
|
|
700
748
|
findNoteByCommitment: () => findNoteByCommitment,
|
|
749
|
+
findProgramAddress: () => findProgramAddress,
|
|
701
750
|
formatAmount: () => formatAmount,
|
|
702
751
|
formatComplianceCsv: () => formatComplianceCsv,
|
|
703
752
|
formatErrorForLogging: () => formatErrorForLogging,
|
|
@@ -706,6 +755,7 @@ __export(index_exports, {
|
|
|
706
755
|
fundReceiverViaPaymaster: () => fundReceiverViaPaymaster,
|
|
707
756
|
generateCloakKeys: () => generateCloakKeys,
|
|
708
757
|
generateCommitmentAsync: () => generateCommitmentAsync,
|
|
758
|
+
generateKeyPairSigner: () => import_kit2.generateKeyPairSigner,
|
|
709
759
|
generateMasterSeed: () => generateMasterSeed,
|
|
710
760
|
generateNoteFromWallet: () => generateNoteFromWallet,
|
|
711
761
|
generateUtxoKeypair: () => generateUtxoKeypair,
|
|
@@ -732,20 +782,22 @@ __export(index_exports, {
|
|
|
732
782
|
hexToBytes: () => hexToBytes,
|
|
733
783
|
importKeys: () => importKeys,
|
|
734
784
|
importWalletKeys: () => importWalletKeys,
|
|
785
|
+
isAddress: () => import_kit.isAddress,
|
|
735
786
|
isBrowser: () => isBrowser,
|
|
736
787
|
isBrowserLike: () => isBrowserLike,
|
|
737
788
|
isDebugEnabled: () => isDebugEnabled,
|
|
789
|
+
isMessageSigner: () => isMessageSigner,
|
|
738
790
|
isPlausibleSignature: () => isPlausibleSignature,
|
|
739
791
|
isReactNative: () => isReactNative,
|
|
740
792
|
isRootNotFoundError: () => isRootNotFoundError,
|
|
741
793
|
isSubmissionOutcomeUnknownResponse: () => isSubmissionOutcomeUnknownResponse,
|
|
742
794
|
isTerminalFailure: () => isTerminalFailure,
|
|
795
|
+
isTransactionSigner: () => import_kit2.isTransactionSigner,
|
|
743
796
|
isValidHex: () => isValidHex,
|
|
744
797
|
isValidRpcUrl: () => isValidRpcUrl,
|
|
745
798
|
isValidSolanaAddress: () => isValidSolanaAddress,
|
|
746
799
|
isWithdrawAmountSufficient: () => isWithdrawAmountSufficient,
|
|
747
800
|
isWithdrawable: () => isWithdrawable,
|
|
748
|
-
keypairToAdapter: () => keypairToAdapter,
|
|
749
801
|
listBridgeDeposits: () => listBridgeDeposits,
|
|
750
802
|
loadPendingDeposits: () => loadPendingDeposits,
|
|
751
803
|
loadPendingWithdrawals: () => loadPendingWithdrawals,
|
|
@@ -754,6 +806,7 @@ __export(index_exports, {
|
|
|
754
806
|
matchDepositNote: () => matchDepositNote,
|
|
755
807
|
matchSwapRefundLeaf: () => matchSwapRefundLeaf,
|
|
756
808
|
mayRetry: () => mayRetry,
|
|
809
|
+
messageSignerFromCallback: () => messageSignerFromCallback,
|
|
757
810
|
openRecipientDeliveryNote: () => openRecipientDeliveryNote,
|
|
758
811
|
parseAmount: () => parseAmount,
|
|
759
812
|
parseDeliveryCarrierMemo: () => parseDeliveryCarrierMemo,
|
|
@@ -763,11 +816,13 @@ __export(index_exports, {
|
|
|
763
816
|
parseRelayErrorSignature: () => parseRelayErrorSignature,
|
|
764
817
|
parseTransactionError: () => parseTransactionError,
|
|
765
818
|
partialWithdraw: () => partialWithdraw,
|
|
819
|
+
partiallySignTransaction: () => partiallySignTransaction,
|
|
766
820
|
poseidonHash: () => poseidonHash,
|
|
767
821
|
preflightCheck: () => preflightCheck,
|
|
768
822
|
preflightNullifiers: () => preflightNullifiers,
|
|
769
823
|
prepareEncryptedOutput: () => prepareEncryptedOutput,
|
|
770
824
|
prepareEncryptedOutputForRecipient: () => prepareEncryptedOutputForRecipient,
|
|
825
|
+
programInstruction: () => programInstruction,
|
|
771
826
|
proofToBytes: () => proofToBytes,
|
|
772
827
|
pubkeyToFieldElement: () => pubkeyToFieldElement,
|
|
773
828
|
pubkeyToLimbs: () => pubkeyToLimbs,
|
|
@@ -792,22 +847,34 @@ __export(index_exports, {
|
|
|
792
847
|
scanTransactions: () => scanTransactions,
|
|
793
848
|
sdkLogger: () => sdkLogger,
|
|
794
849
|
selectUtxos: () => selectUtxos,
|
|
850
|
+
sendInstructions: () => sendInstructions,
|
|
851
|
+
sendRawTransaction: () => sendRawTransaction,
|
|
795
852
|
sendTransaction: () => sendTransaction,
|
|
796
853
|
serializeAuthTransactionMessage: () => serializeAuthTransactionMessage,
|
|
797
854
|
serializeNote: () => serializeNote,
|
|
798
855
|
serializeUtxo: () => serializeUtxo,
|
|
799
856
|
setCircuitsPath: () => setCircuitsPath,
|
|
800
857
|
setDebugMode: () => setDebugMode,
|
|
858
|
+
signCompiledTransaction: () => signCompiledTransaction,
|
|
859
|
+
signMessageBytes: () => signMessageBytes,
|
|
801
860
|
signRelayAuthPayload: () => signRelayAuthPayload,
|
|
802
861
|
signTransaction: () => signTransaction,
|
|
862
|
+
signerFromKeypair: () => signerFromKeypair,
|
|
863
|
+
signerFromSecretKey: () => signerFromSecretKey,
|
|
864
|
+
signerFromWalletAdapter: () => signerFromWalletAdapter,
|
|
803
865
|
splitTo2Limbs: () => splitTo2Limbs,
|
|
804
866
|
submitTransactToRelay: () => submitTransactToRelay,
|
|
805
867
|
sumUtxoAmounts: () => sumUtxoAmounts,
|
|
806
868
|
swapUtxo: () => swapUtxo,
|
|
807
869
|
swapWithChange: () => swapWithChange,
|
|
870
|
+
toAddress: () => toAddress,
|
|
808
871
|
toComplianceReport: () => toComplianceReport,
|
|
809
872
|
transact: () => transact,
|
|
810
873
|
transactBatch: () => transactBatch,
|
|
874
|
+
transactionBase64: () => transactionBase64,
|
|
875
|
+
transactionBytes: () => transactionBytes,
|
|
876
|
+
transactionFromBytes: () => transactionFromBytes,
|
|
877
|
+
transactionWireSize: () => transactionWireSize,
|
|
811
878
|
transfer: () => transfer,
|
|
812
879
|
truncate: () => truncate,
|
|
813
880
|
tryDecryptNote: () => tryDecryptNote,
|
|
@@ -837,8 +904,8 @@ __export(index_exports, {
|
|
|
837
904
|
module.exports = __toCommonJS(index_exports);
|
|
838
905
|
|
|
839
906
|
// src/program/ids.ts
|
|
840
|
-
|
|
841
|
-
var CLOAK_PROGRAM_ID =
|
|
907
|
+
init_address();
|
|
908
|
+
var CLOAK_PROGRAM_ID = (0, import_kit.address)("zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW");
|
|
842
909
|
|
|
843
910
|
// src/index.ts
|
|
844
911
|
init_types();
|
|
@@ -847,11 +914,11 @@ init_types();
|
|
|
847
914
|
init_inputs();
|
|
848
915
|
|
|
849
916
|
// src/shared/validation.ts
|
|
850
|
-
|
|
917
|
+
init_address();
|
|
851
918
|
init_inputs();
|
|
852
|
-
function isValidSolanaAddress(
|
|
919
|
+
function isValidSolanaAddress(address2) {
|
|
853
920
|
try {
|
|
854
|
-
|
|
921
|
+
if (!(0, import_kit.isAddress)(address2)) throw new Error(`Invalid address: ${address2}`);
|
|
855
922
|
return true;
|
|
856
923
|
} catch {
|
|
857
924
|
return false;
|
|
@@ -940,9 +1007,9 @@ function validateTransfers(recipients, totalAmount) {
|
|
|
940
1007
|
}
|
|
941
1008
|
for (let i = 0; i < recipients.length; i++) {
|
|
942
1009
|
const transfer2 = recipients[i];
|
|
943
|
-
const
|
|
944
|
-
if (!
|
|
945
|
-
throw new Error(`Recipient ${i} must be
|
|
1010
|
+
const isAddressLike = typeof transfer2.recipient === "string" && (0, import_kit.isAddress)(transfer2.recipient);
|
|
1011
|
+
if (!isAddressLike) {
|
|
1012
|
+
throw new Error(`Recipient ${i} must be an address (got ${typeof transfer2.recipient})`);
|
|
946
1013
|
}
|
|
947
1014
|
if (typeof transfer2.amount !== "number" || transfer2.amount <= 0) {
|
|
948
1015
|
throw new Error(`Recipient ${i} amount must be a positive number`);
|
|
@@ -1144,9 +1211,9 @@ function getExplorerUrl(signature, network = "devnet") {
|
|
|
1144
1211
|
const cluster = network === "mainnet" ? "" : `?cluster=${network}`;
|
|
1145
1212
|
return `https://explorer.solana.com/tx/${signature}${cluster}`;
|
|
1146
1213
|
}
|
|
1147
|
-
function getAddressExplorerUrl(
|
|
1214
|
+
function getAddressExplorerUrl(address2, network = "devnet") {
|
|
1148
1215
|
const cluster = network === "mainnet" ? "" : `?cluster=${network}`;
|
|
1149
|
-
return `https://explorer.solana.com/address/${
|
|
1216
|
+
return `https://explorer.solana.com/address/${address2}${cluster}`;
|
|
1150
1217
|
}
|
|
1151
1218
|
|
|
1152
1219
|
// src/notes/note-manager.ts
|
|
@@ -1391,7 +1458,49 @@ var LocalStorageAdapter = class {
|
|
|
1391
1458
|
};
|
|
1392
1459
|
|
|
1393
1460
|
// src/scanning/compliance-keys.ts
|
|
1394
|
-
|
|
1461
|
+
init_address();
|
|
1462
|
+
|
|
1463
|
+
// src/solana/signer.ts
|
|
1464
|
+
var import_kit2 = require("@solana/kit");
|
|
1465
|
+
function isMessageSigner(value) {
|
|
1466
|
+
if (!value || typeof value !== "object" || typeof value.address !== "string") return false;
|
|
1467
|
+
const candidate = value;
|
|
1468
|
+
return (0, import_kit2.isMessagePartialSigner)(candidate) || (0, import_kit2.isMessageModifyingSigner)(candidate);
|
|
1469
|
+
}
|
|
1470
|
+
async function signerFromSecretKey(secretKey) {
|
|
1471
|
+
if (secretKey.length === 64) return (0, import_kit2.createKeyPairSignerFromBytes)(secretKey);
|
|
1472
|
+
if (secretKey.length === 32) return (0, import_kit2.createKeyPairSignerFromPrivateKeyBytes)(secretKey);
|
|
1473
|
+
throw new Error(`A secret key is 64 bytes (or a 32-byte seed), got ${secretKey.length}`);
|
|
1474
|
+
}
|
|
1475
|
+
async function signMessageBytes(signer, message) {
|
|
1476
|
+
const signable = (0, import_kit2.createSignableMessage)(message);
|
|
1477
|
+
if ((0, import_kit2.isMessagePartialSigner)(signer)) {
|
|
1478
|
+
const [dictionary] = await signer.signMessages([signable]);
|
|
1479
|
+
const signature2 = dictionary[signer.address];
|
|
1480
|
+
if (!signature2) throw new Error(`Signer ${signer.address} returned no signature for the message`);
|
|
1481
|
+
return new Uint8Array(signature2);
|
|
1482
|
+
}
|
|
1483
|
+
const [signed] = await signer.modifyAndSignMessages([signable]);
|
|
1484
|
+
const signature = signed.signatures[signer.address];
|
|
1485
|
+
if (!signature) throw new Error(`Signer ${signer.address} returned no signature for the message`);
|
|
1486
|
+
return new Uint8Array(signature);
|
|
1487
|
+
}
|
|
1488
|
+
function messageSignerFromCallback(address2, signMessage) {
|
|
1489
|
+
return {
|
|
1490
|
+
address: address2,
|
|
1491
|
+
async signMessages(messages) {
|
|
1492
|
+
const out = [];
|
|
1493
|
+
for (const message of messages) {
|
|
1494
|
+
const signature = await signMessage(message.content);
|
|
1495
|
+
out.push({ [address2]: signature });
|
|
1496
|
+
}
|
|
1497
|
+
return out;
|
|
1498
|
+
}
|
|
1499
|
+
};
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
// src/scanning/compliance-keys.ts
|
|
1503
|
+
var import_tweetnacl2 = __toESM(require("tweetnacl"), 1);
|
|
1395
1504
|
var import_blake32 = require("@noble/hashes/blake3");
|
|
1396
1505
|
var import_sha22 = require("@noble/hashes/sha2");
|
|
1397
1506
|
init_inputs();
|
|
@@ -1574,18 +1683,293 @@ function assertAllowedRpcEndpoint(endpoint) {
|
|
|
1574
1683
|
);
|
|
1575
1684
|
}
|
|
1576
1685
|
function assertAllowedRpcConnection(connection) {
|
|
1686
|
+
assertAllowedRpcEndpoint(connection?.endpoint);
|
|
1577
1687
|
assertAllowedRpcEndpoint(connection?.rpcEndpoint);
|
|
1578
1688
|
assertAllowedRpcEndpoint(connection?._rpcEndpoint);
|
|
1579
1689
|
}
|
|
1580
1690
|
function connectionRpcEndpoint(connection) {
|
|
1581
|
-
return connection?._rpcEndpoint ?? connection?.rpcEndpoint;
|
|
1691
|
+
return connection?.endpoint ?? connection?._rpcEndpoint ?? connection?.rpcEndpoint;
|
|
1582
1692
|
}
|
|
1583
1693
|
|
|
1584
1694
|
// src/relay/payload.ts
|
|
1585
1695
|
var import_sha2 = require("@noble/hashes/sha2");
|
|
1586
1696
|
var import_utils = require("@noble/hashes/utils");
|
|
1587
|
-
var
|
|
1588
|
-
var
|
|
1697
|
+
var import_kit5 = require("@solana/kit");
|
|
1698
|
+
var import_system2 = require("@solana-program/system");
|
|
1699
|
+
|
|
1700
|
+
// src/solana/transaction.ts
|
|
1701
|
+
var import_kit4 = require("@solana/kit");
|
|
1702
|
+
var import_address_lookup_table = require("@solana-program/address-lookup-table");
|
|
1703
|
+
|
|
1704
|
+
// src/solana/rpc.ts
|
|
1705
|
+
var import_kit3 = require("@solana/kit");
|
|
1706
|
+
var ENDPOINTS = /* @__PURE__ */ new WeakMap();
|
|
1707
|
+
function createCloakRpc(endpoint) {
|
|
1708
|
+
const rpc = (0, import_kit3.createSolanaRpc)(endpoint);
|
|
1709
|
+
const wrapped = new Proxy(rpc, {
|
|
1710
|
+
get(target, prop, receiver) {
|
|
1711
|
+
if (prop === "endpoint") return endpoint;
|
|
1712
|
+
return Reflect.get(target, prop, receiver);
|
|
1713
|
+
},
|
|
1714
|
+
has(target, prop) {
|
|
1715
|
+
return prop === "endpoint" || Reflect.has(target, prop);
|
|
1716
|
+
}
|
|
1717
|
+
});
|
|
1718
|
+
ENDPOINTS.set(wrapped, endpoint);
|
|
1719
|
+
return wrapped;
|
|
1720
|
+
}
|
|
1721
|
+
function rpcEndpoint(rpc) {
|
|
1722
|
+
if (rpc && typeof rpc === "object") {
|
|
1723
|
+
const known = ENDPOINTS.get(rpc);
|
|
1724
|
+
if (known) return known;
|
|
1725
|
+
const direct = rpc.endpoint;
|
|
1726
|
+
if (typeof direct === "string") return direct;
|
|
1727
|
+
}
|
|
1728
|
+
return void 0;
|
|
1729
|
+
}
|
|
1730
|
+
var BASE64 = (0, import_kit3.getBase64Encoder)();
|
|
1731
|
+
var BASE64_OUT = (0, import_kit3.getBase64Decoder)();
|
|
1732
|
+
var BASE58_OUT = (0, import_kit3.getBase58Decoder)();
|
|
1733
|
+
function base64ToBytes(value) {
|
|
1734
|
+
return new Uint8Array(BASE64.encode(value));
|
|
1735
|
+
}
|
|
1736
|
+
function bytesToBase64(bytes) {
|
|
1737
|
+
return BASE64_OUT.decode(bytes);
|
|
1738
|
+
}
|
|
1739
|
+
async function fetchAccountBytes(rpc, address2, commitment = "confirmed") {
|
|
1740
|
+
const { value } = await rpc.getAccountInfo(address2, { encoding: "base64", commitment }).send();
|
|
1741
|
+
if (!value) return null;
|
|
1742
|
+
return {
|
|
1743
|
+
address: address2,
|
|
1744
|
+
data: base64ToBytes(value.data[0]),
|
|
1745
|
+
owner: value.owner,
|
|
1746
|
+
lamports: BigInt(value.lamports),
|
|
1747
|
+
executable: value.executable
|
|
1748
|
+
};
|
|
1749
|
+
}
|
|
1750
|
+
async function fetchMultipleAccountBytes(rpc, addresses, commitment = "confirmed") {
|
|
1751
|
+
if (addresses.length === 0) return [];
|
|
1752
|
+
const { value } = await rpc.getMultipleAccounts([...addresses], { encoding: "base64", commitment }).send();
|
|
1753
|
+
return value.map(
|
|
1754
|
+
(entry, i) => entry ? {
|
|
1755
|
+
address: addresses[i],
|
|
1756
|
+
data: base64ToBytes(entry.data[0]),
|
|
1757
|
+
owner: entry.owner,
|
|
1758
|
+
lamports: BigInt(entry.lamports),
|
|
1759
|
+
executable: entry.executable
|
|
1760
|
+
} : null
|
|
1761
|
+
);
|
|
1762
|
+
}
|
|
1763
|
+
async function fetchLatestBlockhash(rpc, commitment = "confirmed") {
|
|
1764
|
+
const { value } = await rpc.getLatestBlockhash({ commitment }).send();
|
|
1765
|
+
return { blockhash: value.blockhash, lastValidBlockHeight: BigInt(value.lastValidBlockHeight) };
|
|
1766
|
+
}
|
|
1767
|
+
async function sendRawTransaction(rpc, wire, options = {}) {
|
|
1768
|
+
const signature = await rpc.sendTransaction(bytesToBase64(wire), {
|
|
1769
|
+
encoding: "base64",
|
|
1770
|
+
skipPreflight: options.skipPreflight ?? false,
|
|
1771
|
+
preflightCommitment: options.preflightCommitment ?? "confirmed",
|
|
1772
|
+
...options.maxRetries !== void 0 ? { maxRetries: BigInt(options.maxRetries) } : {}
|
|
1773
|
+
}).send();
|
|
1774
|
+
return signature;
|
|
1775
|
+
}
|
|
1776
|
+
async function fetchSignatureStatuses(rpc, signatures, searchTransactionHistory = false) {
|
|
1777
|
+
const { value } = await rpc.getSignatureStatuses(signatures, { searchTransactionHistory }).send();
|
|
1778
|
+
return value.map(
|
|
1779
|
+
(entry) => entry ? {
|
|
1780
|
+
slot: BigInt(entry.slot),
|
|
1781
|
+
confirmations: entry.confirmations === null ? null : BigInt(entry.confirmations),
|
|
1782
|
+
err: entry.err,
|
|
1783
|
+
confirmationStatus: entry.confirmationStatus ?? null
|
|
1784
|
+
} : null
|
|
1785
|
+
);
|
|
1786
|
+
}
|
|
1787
|
+
var TransactionConfirmationError = class extends Error {
|
|
1788
|
+
constructor(message, signature, reason, err) {
|
|
1789
|
+
super(message);
|
|
1790
|
+
this.signature = signature;
|
|
1791
|
+
this.reason = reason;
|
|
1792
|
+
this.err = err;
|
|
1793
|
+
this.name = "TransactionConfirmationError";
|
|
1794
|
+
}
|
|
1795
|
+
};
|
|
1796
|
+
var RANK = { processed: 0, confirmed: 1, finalized: 2 };
|
|
1797
|
+
async function confirmSignature(rpc, signature, options = {}) {
|
|
1798
|
+
const commitment = options.commitment ?? "confirmed";
|
|
1799
|
+
const timeoutMs = options.timeoutMs ?? 9e4;
|
|
1800
|
+
const pollIntervalMs = options.pollIntervalMs ?? 500;
|
|
1801
|
+
const deadline = Date.now() + timeoutMs;
|
|
1802
|
+
let polls = 0;
|
|
1803
|
+
while (true) {
|
|
1804
|
+
const [status] = await fetchSignatureStatuses(rpc, [signature], polls > 0 && polls % 10 === 0);
|
|
1805
|
+
polls += 1;
|
|
1806
|
+
if (status) {
|
|
1807
|
+
if (status.err) {
|
|
1808
|
+
throw new TransactionConfirmationError(
|
|
1809
|
+
`Transaction failed during confirmation: ${JSON.stringify(status.err)}`,
|
|
1810
|
+
signature,
|
|
1811
|
+
"failed",
|
|
1812
|
+
status.err
|
|
1813
|
+
);
|
|
1814
|
+
}
|
|
1815
|
+
const reached = status.confirmationStatus ? RANK[status.confirmationStatus] : -1;
|
|
1816
|
+
if (reached >= RANK[commitment]) return { slot: status.slot };
|
|
1817
|
+
}
|
|
1818
|
+
if (options.lastValidBlockHeight !== void 0) {
|
|
1819
|
+
const height = await rpc.getBlockHeight({ commitment }).send();
|
|
1820
|
+
if (BigInt(height) > options.lastValidBlockHeight) {
|
|
1821
|
+
throw new TransactionConfirmationError(
|
|
1822
|
+
`Transaction ${signature} was not confirmed before its blockhash expired`,
|
|
1823
|
+
signature,
|
|
1824
|
+
"expired"
|
|
1825
|
+
);
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
if (Date.now() > deadline) {
|
|
1829
|
+
throw new TransactionConfirmationError(
|
|
1830
|
+
`Transaction ${signature} was not confirmed within ${timeoutMs} ms`,
|
|
1831
|
+
signature,
|
|
1832
|
+
"timeout"
|
|
1833
|
+
);
|
|
1834
|
+
}
|
|
1835
|
+
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
async function fetchSignaturesForAddress(rpc, address2, options = {}) {
|
|
1839
|
+
const result = await rpc.getSignaturesForAddress(address2, {
|
|
1840
|
+
before: options.before,
|
|
1841
|
+
until: options.until,
|
|
1842
|
+
limit: options.limit,
|
|
1843
|
+
commitment: options.commitment
|
|
1844
|
+
}).send();
|
|
1845
|
+
return result.map((entry) => ({
|
|
1846
|
+
signature: entry.signature,
|
|
1847
|
+
slot: Number(entry.slot),
|
|
1848
|
+
err: entry.err,
|
|
1849
|
+
memo: entry.memo ?? null,
|
|
1850
|
+
blockTime: entry.blockTime === null || entry.blockTime === void 0 ? null : Number(entry.blockTime)
|
|
1851
|
+
}));
|
|
1852
|
+
}
|
|
1853
|
+
async function fetchTransactionJson(rpc, signature, options) {
|
|
1854
|
+
const result = await rpc.getTransaction(signature, {
|
|
1855
|
+
encoding: "json",
|
|
1856
|
+
commitment: options.commitment ?? "confirmed",
|
|
1857
|
+
maxSupportedTransactionVersion: options.maxSupportedTransactionVersion
|
|
1858
|
+
}).send();
|
|
1859
|
+
if (!result) return null;
|
|
1860
|
+
const raw = result;
|
|
1861
|
+
return {
|
|
1862
|
+
slot: Number(raw.slot),
|
|
1863
|
+
blockTime: raw.blockTime === null || raw.blockTime === void 0 ? null : Number(raw.blockTime),
|
|
1864
|
+
version: raw.version,
|
|
1865
|
+
meta: raw.meta,
|
|
1866
|
+
transaction: raw.transaction
|
|
1867
|
+
};
|
|
1868
|
+
}
|
|
1869
|
+
async function fetchParsedTransaction(rpc, signature, options) {
|
|
1870
|
+
const result = await rpc.getTransaction(signature, {
|
|
1871
|
+
encoding: "jsonParsed",
|
|
1872
|
+
commitment: options.commitment ?? "confirmed",
|
|
1873
|
+
maxSupportedTransactionVersion: options.maxSupportedTransactionVersion
|
|
1874
|
+
}).send();
|
|
1875
|
+
if (!result) return null;
|
|
1876
|
+
const raw = result;
|
|
1877
|
+
return {
|
|
1878
|
+
slot: Number(raw.slot),
|
|
1879
|
+
blockTime: raw.blockTime === null || raw.blockTime === void 0 ? null : Number(raw.blockTime),
|
|
1880
|
+
version: raw.version,
|
|
1881
|
+
meta: raw.meta,
|
|
1882
|
+
transaction: raw.transaction
|
|
1883
|
+
};
|
|
1884
|
+
}
|
|
1885
|
+
function isRawParsedInstruction(ix) {
|
|
1886
|
+
return "accounts" in ix && "data" in ix;
|
|
1887
|
+
}
|
|
1888
|
+
async function fetchSlot(rpc, commitment = "confirmed") {
|
|
1889
|
+
return Number(await rpc.getSlot({ commitment }).send());
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
// src/solana/transaction.ts
|
|
1893
|
+
async function fetchLookupTables(rpc, addresses) {
|
|
1894
|
+
return Promise.all(
|
|
1895
|
+
addresses.map(async (address2) => {
|
|
1896
|
+
const account = await (0, import_address_lookup_table.fetchAddressLookupTable)(rpc, address2);
|
|
1897
|
+
return { address: address2, addresses: account.data.addresses };
|
|
1898
|
+
})
|
|
1899
|
+
);
|
|
1900
|
+
}
|
|
1901
|
+
function buildTransactionMessage(params) {
|
|
1902
|
+
const { version = 0, feePayer, lifetime, instructions, lookupTables = [], signers = [], computeConfig } = params;
|
|
1903
|
+
if (computeConfig && version !== 1) {
|
|
1904
|
+
throw new Error(`computeConfig is a v1 message header field; a ${String(version)} message carries ComputeBudget instructions instead`);
|
|
1905
|
+
}
|
|
1906
|
+
const base = (0, import_kit4.pipe)(
|
|
1907
|
+
(0, import_kit4.createTransactionMessage)({ version }),
|
|
1908
|
+
(m) => typeof feePayer === "string" ? (0, import_kit4.setTransactionMessageFeePayer)(feePayer, m) : (0, import_kit4.setTransactionMessageFeePayerSigner)(feePayer, m),
|
|
1909
|
+
(m) => (0, import_kit4.setTransactionMessageLifetimeUsingBlockhash)(
|
|
1910
|
+
{ blockhash: lifetime.blockhash, lastValidBlockHeight: lifetime.lastValidBlockHeight },
|
|
1911
|
+
m
|
|
1912
|
+
),
|
|
1913
|
+
(m) => (0, import_kit4.appendTransactionMessageInstructions)(instructions, m),
|
|
1914
|
+
(m) => signers.length > 0 ? (0, import_kit4.addSignersToTransactionMessage)([...signers], m) : m,
|
|
1915
|
+
(m) => computeConfig?.computeUnitLimit !== void 0 ? (0, import_kit4.setTransactionMessageComputeUnitLimit)(computeConfig.computeUnitLimit, m) : m,
|
|
1916
|
+
(m) => computeConfig?.priorityFeeLamports !== void 0 ? (0, import_kit4.setTransactionMessagePriorityFeeLamports)(computeConfig.priorityFeeLamports, m) : m,
|
|
1917
|
+
(m) => computeConfig?.loadedAccountsDataSizeLimit !== void 0 ? (0, import_kit4.setTransactionMessageLoadedAccountsDataSizeLimit)(computeConfig.loadedAccountsDataSizeLimit, m) : m
|
|
1918
|
+
);
|
|
1919
|
+
if (version === 0 && lookupTables.length > 0) {
|
|
1920
|
+
const tables = Object.fromEntries(lookupTables.map((t) => [t.address, [...t.addresses]]));
|
|
1921
|
+
return (0, import_kit4.compressTransactionMessageUsingAddressLookupTables)(base, tables);
|
|
1922
|
+
}
|
|
1923
|
+
return base;
|
|
1924
|
+
}
|
|
1925
|
+
function compileUnsigned(message) {
|
|
1926
|
+
return (0, import_kit4.compileTransaction)(message);
|
|
1927
|
+
}
|
|
1928
|
+
var TRANSACTION_ENCODER = (0, import_kit4.getTransactionEncoder)();
|
|
1929
|
+
var TRANSACTION_DECODER = (0, import_kit4.getTransactionDecoder)();
|
|
1930
|
+
function transactionBytes(transaction) {
|
|
1931
|
+
return new Uint8Array(TRANSACTION_ENCODER.encode(transaction));
|
|
1932
|
+
}
|
|
1933
|
+
function transactionWireSize(message) {
|
|
1934
|
+
return transactionBytes(compileUnsigned(message)).length;
|
|
1935
|
+
}
|
|
1936
|
+
function transactionFromBytes(bytes) {
|
|
1937
|
+
return TRANSACTION_DECODER.decode(bytes);
|
|
1938
|
+
}
|
|
1939
|
+
async function signCompiledTransaction(signer, transaction) {
|
|
1940
|
+
const [signatures] = await signer.signTransactions(
|
|
1941
|
+
[transaction]
|
|
1942
|
+
);
|
|
1943
|
+
return { ...transaction, signatures: { ...transaction.signatures, ...signatures } };
|
|
1944
|
+
}
|
|
1945
|
+
function transactionBase64(transaction) {
|
|
1946
|
+
return (0, import_kit4.getBase64EncodedWireTransaction)(transaction);
|
|
1947
|
+
}
|
|
1948
|
+
async function signTransaction(message) {
|
|
1949
|
+
return (0, import_kit4.signTransactionMessageWithSigners)(message);
|
|
1950
|
+
}
|
|
1951
|
+
async function partiallySignTransaction(message) {
|
|
1952
|
+
return (0, import_kit4.partiallySignTransactionMessageWithSigners)(message);
|
|
1953
|
+
}
|
|
1954
|
+
async function sendInstructions(rpc, payer, instructions, options = {}) {
|
|
1955
|
+
const lifetime = await fetchLatestBlockhash(rpc, options.commitment ?? "confirmed");
|
|
1956
|
+
const message = buildTransactionMessage({
|
|
1957
|
+
version: options.version ?? "legacy",
|
|
1958
|
+
feePayer: payer,
|
|
1959
|
+
lifetime,
|
|
1960
|
+
instructions,
|
|
1961
|
+
lookupTables: options.lookupTables
|
|
1962
|
+
});
|
|
1963
|
+
const signed = await signTransaction(message);
|
|
1964
|
+
const signature = await sendRawTransaction(rpc, transactionBytes(signed), { skipPreflight: options.skipPreflight });
|
|
1965
|
+
await confirmSignature(rpc, signature, {
|
|
1966
|
+
commitment: options.commitment ?? "confirmed",
|
|
1967
|
+
lastValidBlockHeight: lifetime.lastValidBlockHeight
|
|
1968
|
+
});
|
|
1969
|
+
return signature;
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
// src/relay/payload.ts
|
|
1589
1973
|
init_inputs();
|
|
1590
1974
|
var REQUEST_AUTH_DOMAIN = "CLOAK_RELAY_REQUEST_AUTH_V1";
|
|
1591
1975
|
var REQUEST_AUTH_MAX_AGE_SECONDS = 300;
|
|
@@ -1708,30 +2092,30 @@ function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request)
|
|
|
1708
2092
|
return new TextEncoder().encode(
|
|
1709
2093
|
`${REQUEST_AUTH_DOMAIN}
|
|
1710
2094
|
${endpoint}
|
|
1711
|
-
${programId
|
|
2095
|
+
${programId}
|
|
1712
2096
|
${nonce}
|
|
1713
2097
|
${issuedAt}
|
|
1714
2098
|
${digest}`
|
|
1715
2099
|
);
|
|
1716
2100
|
}
|
|
1717
2101
|
function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
|
|
1718
|
-
const senderB58 = sender
|
|
2102
|
+
const senderB58 = sender;
|
|
1719
2103
|
const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
|
|
1720
2104
|
const nonce = randomNonceUuid();
|
|
1721
2105
|
const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
|
|
1722
2106
|
const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
|
|
1723
2107
|
return { sender: senderB58, auth_issued_at: issuedAt, auth_nonce: nonce, message };
|
|
1724
2108
|
}
|
|
1725
|
-
function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
|
|
2109
|
+
async function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
|
|
1726
2110
|
const preimage = buildRelayAuthPreimage(
|
|
1727
2111
|
endpoint,
|
|
1728
2112
|
programId,
|
|
1729
2113
|
body,
|
|
1730
|
-
signer.
|
|
2114
|
+
signer.address,
|
|
1731
2115
|
nowSeconds,
|
|
1732
2116
|
fields
|
|
1733
2117
|
);
|
|
1734
|
-
const signature =
|
|
2118
|
+
const signature = await signMessageBytes(signer, preimage.message);
|
|
1735
2119
|
return {
|
|
1736
2120
|
sender: preimage.sender,
|
|
1737
2121
|
auth_issued_at: preimage.auth_issued_at,
|
|
@@ -1741,38 +2125,44 @@ function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields
|
|
|
1741
2125
|
}
|
|
1742
2126
|
function buildAuthTransactionMessage(sender, digest) {
|
|
1743
2127
|
if (digest.length !== 32) throw new Error(`auth transaction digest must be 32 bytes (got ${digest.length})`);
|
|
1744
|
-
const
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
2128
|
+
const payer = (0, import_kit5.createNoopSigner)(sender);
|
|
2129
|
+
return buildTransactionMessage({
|
|
2130
|
+
version: "legacy",
|
|
2131
|
+
feePayer: payer,
|
|
2132
|
+
// 32 raw bytes in the blockhash slot; base58 is just the codec the message type expects.
|
|
2133
|
+
lifetime: { blockhash: (0, import_kit5.getBase58Decoder)().decode(digest), lastValidBlockHeight: 0n },
|
|
2134
|
+
instructions: [(0, import_system2.getTransferSolInstruction)({ source: payer, destination: sender, amount: 0n })]
|
|
2135
|
+
});
|
|
1749
2136
|
}
|
|
1750
2137
|
function serializeAuthTransactionMessage(sender, digest) {
|
|
1751
|
-
return Uint8Array
|
|
2138
|
+
return new Uint8Array(compileUnsigned(buildAuthTransactionMessage(sender, digest)).messageBytes);
|
|
1752
2139
|
}
|
|
1753
2140
|
async function signRelayAuthPayload(signer, payload) {
|
|
1754
|
-
if (signer
|
|
1755
|
-
|
|
1756
|
-
}
|
|
1757
|
-
if (signer.signMessage) {
|
|
1758
|
-
const signature = await signer.signMessage(payload);
|
|
2141
|
+
if (isMessageSigner(signer)) {
|
|
2142
|
+
const signature = await signMessageBytes(signer, payload);
|
|
1759
2143
|
assertDetachedSignature(signature, "signMessage");
|
|
1760
2144
|
return { signature, mode: "message" };
|
|
1761
2145
|
}
|
|
1762
|
-
if (
|
|
2146
|
+
if ((0, import_kit2.isTransactionSigner)(signer)) {
|
|
1763
2147
|
const digest = (0, import_sha2.sha256)(payload);
|
|
1764
|
-
const
|
|
1765
|
-
|
|
2148
|
+
const message = buildTransactionMessage({
|
|
2149
|
+
version: "legacy",
|
|
2150
|
+
feePayer: signer,
|
|
2151
|
+
lifetime: { blockhash: (0, import_kit5.getBase58Decoder)().decode(digest), lastValidBlockHeight: 0n },
|
|
2152
|
+
instructions: [(0, import_system2.getTransferSolInstruction)({ source: signer, destination: signer.address, amount: 0n })]
|
|
2153
|
+
});
|
|
2154
|
+
const signed = await signTransaction(message);
|
|
2155
|
+
const own = signed.signatures[signer.address];
|
|
1766
2156
|
if (!own) {
|
|
1767
2157
|
throw new Error(
|
|
1768
2158
|
"The wallet returned no signature for the Cloak auth transaction. Nothing was submitted."
|
|
1769
2159
|
);
|
|
1770
2160
|
}
|
|
1771
|
-
const signature = Uint8Array
|
|
2161
|
+
const signature = new Uint8Array(own);
|
|
1772
2162
|
assertDetachedSignature(signature, "signTransaction");
|
|
1773
2163
|
return { signature, mode: "transaction" };
|
|
1774
2164
|
}
|
|
1775
|
-
throw new Error("Relay auth signer
|
|
2165
|
+
throw new Error("Relay auth signer can neither sign messages nor transactions.");
|
|
1776
2166
|
}
|
|
1777
2167
|
function assertDetachedSignature(signature, method) {
|
|
1778
2168
|
if (!(signature instanceof Uint8Array) || signature.length !== 64) {
|
|
@@ -1825,7 +2215,7 @@ async function buildRelayAuthFields(endpoint, programId, body, signers, fields =
|
|
|
1825
2215
|
endpoint,
|
|
1826
2216
|
programId,
|
|
1827
2217
|
body,
|
|
1828
|
-
wallet.
|
|
2218
|
+
wallet.address,
|
|
1829
2219
|
void 0,
|
|
1830
2220
|
fields
|
|
1831
2221
|
);
|
|
@@ -1847,7 +2237,7 @@ function relayRequestDigestHex(preimage) {
|
|
|
1847
2237
|
return (0, import_utils.bytesToHex)((0, import_sha2.sha256)(preimage.message));
|
|
1848
2238
|
}
|
|
1849
2239
|
function buildRelayBatchAuthMessage(programId, issuedAt, digests) {
|
|
1850
|
-
const lines = [REQUEST_AUTH_BATCH_DOMAIN, programId
|
|
2240
|
+
const lines = [REQUEST_AUTH_BATCH_DOMAIN, programId, issuedAt, String(digests.length)];
|
|
1851
2241
|
return new TextEncoder().encode([...lines, ...digests].join("\n"));
|
|
1852
2242
|
}
|
|
1853
2243
|
|
|
@@ -1888,7 +2278,7 @@ function deriveViewingKeyFromNk(nk) {
|
|
|
1888
2278
|
preimage.set(nk, CHAIN_NOTE_VK_DOMAIN.length);
|
|
1889
2279
|
const derived = (0, import_blake32.blake3)(preimage);
|
|
1890
2280
|
const privateKey = clampX25519Secret(derived);
|
|
1891
|
-
const publicKey =
|
|
2281
|
+
const publicKey = import_tweetnacl2.default.scalarMult.base(privateKey);
|
|
1892
2282
|
return { privateKey, publicKey };
|
|
1893
2283
|
}
|
|
1894
2284
|
function deriveDiversifier(nk, commitmentHex, outputIndex) {
|
|
@@ -1923,7 +2313,7 @@ function deriveDiversifiedViewingKey(nk, diversifier) {
|
|
|
1923
2313
|
preimage.set(diversifier, SK_D_DOMAIN.length + nk.length);
|
|
1924
2314
|
const derived = (0, import_blake32.blake3)(preimage);
|
|
1925
2315
|
const privateKey = clampX25519Secret(derived);
|
|
1926
|
-
const publicKey =
|
|
2316
|
+
const publicKey = import_tweetnacl2.default.scalarMult.base(privateKey);
|
|
1927
2317
|
return { privateKey, publicKey };
|
|
1928
2318
|
}
|
|
1929
2319
|
function deriveViewingKeyFromSpendKey(skSpend) {
|
|
@@ -1976,7 +2366,7 @@ function bigintToScalarLE(value) {
|
|
|
1976
2366
|
async function deriveUserComplianceScalar(masterCompliancePublicKey, userPublicKey) {
|
|
1977
2367
|
assert32Bytes(masterCompliancePublicKey, "masterCompliancePublicKey");
|
|
1978
2368
|
const masterField = bytesToFieldElement(masterCompliancePublicKey);
|
|
1979
|
-
const userField = bytesToFieldElement(userPublicKey
|
|
2369
|
+
const userField = bytesToFieldElement(addressBytes(userPublicKey));
|
|
1980
2370
|
const factor = await poseidonHash([masterField, userField]);
|
|
1981
2371
|
return bigintToScalarLE(factor);
|
|
1982
2372
|
}
|
|
@@ -1986,13 +2376,13 @@ async function deriveUserCompliancePublicKey(masterCompliancePublicKey, userPubl
|
|
|
1986
2376
|
masterCompliancePublicKey,
|
|
1987
2377
|
userPublicKey
|
|
1988
2378
|
);
|
|
1989
|
-
return
|
|
2379
|
+
return import_tweetnacl2.default.scalarMult(factor, masterCompliancePublicKey);
|
|
1990
2380
|
}
|
|
1991
2381
|
function bytesToHex3(bytes) {
|
|
1992
2382
|
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1993
2383
|
}
|
|
1994
2384
|
function computeViewingKeyIdentifier(userPubkey, nkHex) {
|
|
1995
|
-
const preimage = new TextEncoder().encode(`${userPubkey
|
|
2385
|
+
const preimage = new TextEncoder().encode(`${userPubkey}${nkHex}`);
|
|
1996
2386
|
return bytesToHex3((0, import_sha22.sha256)(preimage));
|
|
1997
2387
|
}
|
|
1998
2388
|
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.";
|
|
@@ -2004,7 +2394,7 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
|
2004
2394
|
method: "POST",
|
|
2005
2395
|
headers: { "Content-Type": "application/json" },
|
|
2006
2396
|
body: JSON.stringify({
|
|
2007
|
-
user_pubkey: userPubkey
|
|
2397
|
+
user_pubkey: userPubkey,
|
|
2008
2398
|
viewing_key: nkHex
|
|
2009
2399
|
})
|
|
2010
2400
|
});
|
|
@@ -2015,12 +2405,12 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
|
2015
2405
|
}
|
|
2016
2406
|
const challenge = parseStrictViewingKeyChallenge(
|
|
2017
2407
|
await challengeResponse.json(),
|
|
2018
|
-
userPubkey
|
|
2408
|
+
userPubkey,
|
|
2019
2409
|
nkHex
|
|
2020
2410
|
);
|
|
2021
2411
|
const messageBytes = new TextEncoder().encode(challenge.message);
|
|
2022
2412
|
const signed = await signRelayAuthPayload(
|
|
2023
|
-
typeof signMessage === "function" ?
|
|
2413
|
+
typeof signMessage === "function" ? messageSignerFromCallback(userPubkey, signMessage) : signMessage,
|
|
2024
2414
|
messageBytes
|
|
2025
2415
|
);
|
|
2026
2416
|
const signature = Buffer.from(signed.signature).toString("base64");
|
|
@@ -2028,7 +2418,7 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
|
2028
2418
|
method: "POST",
|
|
2029
2419
|
headers: { "Content-Type": "application/json" },
|
|
2030
2420
|
body: JSON.stringify({
|
|
2031
|
-
user_pubkey: userPubkey
|
|
2421
|
+
user_pubkey: userPubkey,
|
|
2032
2422
|
viewing_key: nkHex,
|
|
2033
2423
|
nonce: challenge.nonce,
|
|
2034
2424
|
identifier: keyId,
|
|
@@ -2042,7 +2432,7 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
|
2042
2432
|
}
|
|
2043
2433
|
|
|
2044
2434
|
// src/scanning/metadata-encryption.ts
|
|
2045
|
-
var
|
|
2435
|
+
var import_tweetnacl3 = __toESM(require("tweetnacl"), 1);
|
|
2046
2436
|
init_inputs();
|
|
2047
2437
|
var AES_GCM_NONCE_LENGTH = 12;
|
|
2048
2438
|
var AES_GCM_TAG_LENGTH = 16;
|
|
@@ -2140,8 +2530,8 @@ async function aesGcmDecrypt(ciphertext, keyBytes, nonce) {
|
|
|
2140
2530
|
}
|
|
2141
2531
|
async function encryptForRecipient(plaintext, recipientPublicKey) {
|
|
2142
2532
|
assert32Bytes2(recipientPublicKey, "recipientPublicKey");
|
|
2143
|
-
const ephemeral =
|
|
2144
|
-
const sharedSecret =
|
|
2533
|
+
const ephemeral = import_tweetnacl3.default.box.keyPair();
|
|
2534
|
+
const sharedSecret = import_tweetnacl3.default.scalarMult(ephemeral.secretKey, recipientPublicKey);
|
|
2145
2535
|
const nonce = randomBytes(AES_GCM_NONCE_LENGTH);
|
|
2146
2536
|
const ciphertext = await aesGcmEncrypt(plaintext, sharedSecret, nonce);
|
|
2147
2537
|
return {
|
|
@@ -2176,7 +2566,7 @@ function normalizeUserPubkey(userPubkey) {
|
|
|
2176
2566
|
if (!userPubkey) {
|
|
2177
2567
|
return "";
|
|
2178
2568
|
}
|
|
2179
|
-
return
|
|
2569
|
+
return userPubkey;
|
|
2180
2570
|
}
|
|
2181
2571
|
async function encryptTransactionMetadata(metadata, userViewKeyPublic, complianceKeyPublic, context) {
|
|
2182
2572
|
assert32Bytes2(userViewKeyPublic, "userViewKeyPublic");
|
|
@@ -2200,7 +2590,7 @@ async function encryptTransactionMetadataBundle(metadata, viewingKeyPrivate, use
|
|
|
2200
2590
|
const plaintext = new TextEncoder().encode(JSON.stringify(metadata));
|
|
2201
2591
|
const basePoint = new Uint8Array(32);
|
|
2202
2592
|
basePoint[0] = 9;
|
|
2203
|
-
const viewingKeyPublic =
|
|
2593
|
+
const viewingKeyPublic = import_tweetnacl3.default.scalarMult(viewingKeyPrivate, basePoint);
|
|
2204
2594
|
const [userPayload, compliancePayload] = await Promise.all([
|
|
2205
2595
|
encryptForRecipient(plaintext, viewingKeyPublic),
|
|
2206
2596
|
encryptForRecipient(plaintext, viewingKeyPublic)
|
|
@@ -2208,7 +2598,7 @@ async function encryptTransactionMetadataBundle(metadata, viewingKeyPrivate, use
|
|
|
2208
2598
|
return {
|
|
2209
2599
|
encrypted_user: encodeBase64(JSON.stringify(userPayload)),
|
|
2210
2600
|
encrypted_compliance: encodeBase64(JSON.stringify(compliancePayload)),
|
|
2211
|
-
user_pubkey: userPubkey
|
|
2601
|
+
user_pubkey: userPubkey,
|
|
2212
2602
|
commitment: metadata.commitment,
|
|
2213
2603
|
timestamp: metadata.timestamp,
|
|
2214
2604
|
tx_type: metadata.txType
|
|
@@ -2219,7 +2609,7 @@ async function decryptTransactionMetadata(encrypted, viewKeySecret) {
|
|
|
2219
2609
|
const payload = decodePayload(encrypted);
|
|
2220
2610
|
const ephemeralPk = hexToBytes(payload.ephemeral_pk);
|
|
2221
2611
|
assert32Bytes2(ephemeralPk, "ephemeral public key");
|
|
2222
|
-
const sharedSecret =
|
|
2612
|
+
const sharedSecret = import_tweetnacl3.default.scalarMult(viewKeySecret, ephemeralPk);
|
|
2223
2613
|
return decryptWithSharedSecret(payload, sharedSecret);
|
|
2224
2614
|
}
|
|
2225
2615
|
async function decryptComplianceMetadataWithMasterKey(encrypted, masterCompliancePrivateKey, masterCompliancePublicKey, userPublicKey) {
|
|
@@ -2232,8 +2622,8 @@ async function decryptComplianceMetadataWithMasterKey(encrypted, masterComplianc
|
|
|
2232
2622
|
masterCompliancePublicKey,
|
|
2233
2623
|
userPublicKey
|
|
2234
2624
|
);
|
|
2235
|
-
const scaledEphemeral =
|
|
2236
|
-
const sharedSecret =
|
|
2625
|
+
const scaledEphemeral = import_tweetnacl3.default.scalarMult(userFactor, ephemeralPk);
|
|
2626
|
+
const sharedSecret = import_tweetnacl3.default.scalarMult(masterCompliancePrivateKey, scaledEphemeral);
|
|
2237
2627
|
return decryptWithSharedSecret(payload, sharedSecret);
|
|
2238
2628
|
}
|
|
2239
2629
|
|
|
@@ -3170,67 +3560,54 @@ function formatErrorForLogging(error) {
|
|
|
3170
3560
|
init_utxo();
|
|
3171
3561
|
|
|
3172
3562
|
// src/program/pda.ts
|
|
3173
|
-
|
|
3563
|
+
init_address();
|
|
3564
|
+
|
|
3565
|
+
// src/solana/pda.ts
|
|
3566
|
+
var import_kit6 = require("@solana/kit");
|
|
3567
|
+
async function findProgramAddress(seeds, programAddress) {
|
|
3568
|
+
const [pda2, bump] = await (0, import_kit6.getProgramDerivedAddress)({ programAddress, seeds });
|
|
3569
|
+
return [pda2, bump];
|
|
3570
|
+
}
|
|
3571
|
+
|
|
3572
|
+
// src/program/pda.ts
|
|
3174
3573
|
init_utxo();
|
|
3175
|
-
|
|
3574
|
+
var utf8 = (s) => new TextEncoder().encode(s);
|
|
3575
|
+
async function getShieldPoolPDAs(programId, mint = NATIVE_SOL_MINT) {
|
|
3176
3576
|
const pid = programId || CLOAK_PROGRAM_ID;
|
|
3177
|
-
const
|
|
3178
|
-
|
|
3179
|
-
pid
|
|
3180
|
-
|
|
3181
|
-
|
|
3182
|
-
[
|
|
3183
|
-
|
|
3184
|
-
|
|
3185
|
-
const [treasury] = import_web35.PublicKey.findProgramAddressSync(
|
|
3186
|
-
[Buffer.from("treasury"), mint.toBuffer()],
|
|
3187
|
-
pid
|
|
3188
|
-
);
|
|
3189
|
-
const [vaultAuthority] = import_web35.PublicKey.findProgramAddressSync(
|
|
3190
|
-
[Buffer.from("vault_authority"), mint.toBuffer()],
|
|
3191
|
-
pid
|
|
3192
|
-
);
|
|
3193
|
-
return {
|
|
3194
|
-
pool,
|
|
3195
|
-
merkleTree,
|
|
3196
|
-
vaultAuthority,
|
|
3197
|
-
treasury
|
|
3198
|
-
};
|
|
3577
|
+
const mintSeed = addressBytes(mint);
|
|
3578
|
+
const [[pool], [merkleTree], [treasury], [vaultAuthority]] = await Promise.all([
|
|
3579
|
+
findProgramAddress([utf8("pool"), mintSeed], pid),
|
|
3580
|
+
findProgramAddress([utf8("merkle_tree"), mintSeed], pid),
|
|
3581
|
+
findProgramAddress([utf8("treasury"), mintSeed], pid),
|
|
3582
|
+
findProgramAddress([utf8("vault_authority"), mintSeed], pid)
|
|
3583
|
+
]);
|
|
3584
|
+
return { pool, merkleTree, vaultAuthority, treasury };
|
|
3199
3585
|
}
|
|
3200
|
-
function getNullifierPDA(
|
|
3586
|
+
async function getNullifierPDA(poolAddress, nullifier, programId) {
|
|
3201
3587
|
const pid = programId || CLOAK_PROGRAM_ID;
|
|
3202
3588
|
if (nullifier.length !== 32) {
|
|
3203
3589
|
throw new Error(`Nullifier must be 32 bytes, got ${nullifier.length}`);
|
|
3204
3590
|
}
|
|
3205
|
-
return
|
|
3206
|
-
[Buffer.from("nullifier"), poolPubkey.toBuffer(), Buffer.from(nullifier)],
|
|
3207
|
-
pid
|
|
3208
|
-
);
|
|
3591
|
+
return findProgramAddress([utf8("nullifier"), addressBytes(poolAddress), new Uint8Array(nullifier)], pid);
|
|
3209
3592
|
}
|
|
3210
|
-
function getSwapStatePDA(
|
|
3593
|
+
async function getSwapStatePDA(poolAddress, nullifier, programId) {
|
|
3211
3594
|
const pid = programId || CLOAK_PROGRAM_ID;
|
|
3212
3595
|
if (nullifier.length !== 32) {
|
|
3213
3596
|
throw new Error(`Nullifier must be 32 bytes, got ${nullifier.length}`);
|
|
3214
3597
|
}
|
|
3215
|
-
return
|
|
3216
|
-
[Buffer.from("swap_state"), poolPubkey.toBuffer(), Buffer.from(nullifier)],
|
|
3217
|
-
pid
|
|
3218
|
-
);
|
|
3598
|
+
return findProgramAddress([utf8("swap_state"), addressBytes(poolAddress), new Uint8Array(nullifier)], pid);
|
|
3219
3599
|
}
|
|
3220
|
-
function getPoolAuthorityConfigPDA(mint = NATIVE_SOL_MINT, programId) {
|
|
3600
|
+
async function getPoolAuthorityConfigPDA(mint = NATIVE_SOL_MINT, programId) {
|
|
3221
3601
|
const pid = programId || CLOAK_PROGRAM_ID;
|
|
3222
|
-
return
|
|
3223
|
-
[Buffer.from("pool_authority"), mint.toBuffer()],
|
|
3224
|
-
pid
|
|
3225
|
-
);
|
|
3602
|
+
return findProgramAddress([utf8("pool_authority"), addressBytes(mint)], pid);
|
|
3226
3603
|
}
|
|
3227
|
-
function getDeliveryRegistryPDA(programId) {
|
|
3604
|
+
async function getDeliveryRegistryPDA(programId) {
|
|
3228
3605
|
const pid = programId || CLOAK_PROGRAM_ID;
|
|
3229
|
-
return
|
|
3606
|
+
return (await findProgramAddress([utf8("cloak_delivery_registry")], pid))[0];
|
|
3230
3607
|
}
|
|
3231
|
-
function getChainNoteRegistryPDA(programId) {
|
|
3608
|
+
async function getChainNoteRegistryPDA(programId) {
|
|
3232
3609
|
const pid = programId || CLOAK_PROGRAM_ID;
|
|
3233
|
-
return
|
|
3610
|
+
return (await findProgramAddress([utf8("cloak_chain_note_registry")], pid))[0];
|
|
3234
3611
|
}
|
|
3235
3612
|
|
|
3236
3613
|
// src/flows/verify-utxos.ts
|
|
@@ -3247,8 +3624,8 @@ async function verifyUtxos(utxos, connection, programId, commitment = "confirmed
|
|
|
3247
3624
|
const nullifierBig = await computeNullifier(utxo);
|
|
3248
3625
|
const nullifierHex = nullifierBig.toString(16).padStart(64, "0");
|
|
3249
3626
|
const nullifierBytes = Buffer.from(nullifierHex, "hex");
|
|
3250
|
-
const { pool } = getShieldPoolPDAs(programId, utxo.mintAddress);
|
|
3251
|
-
const [pda2] = getNullifierPDA(pool, nullifierBytes, programId);
|
|
3627
|
+
const { pool } = await getShieldPoolPDAs(programId, utxo.mintAddress);
|
|
3628
|
+
const [pda2] = await getNullifierPDA(pool, nullifierBytes, programId);
|
|
3252
3629
|
checkable.push({ utxo, pda: pda2 });
|
|
3253
3630
|
} catch {
|
|
3254
3631
|
skipped.push(utxo);
|
|
@@ -3261,7 +3638,7 @@ async function verifyUtxos(utxos, connection, programId, commitment = "confirmed
|
|
|
3261
3638
|
const infos = [];
|
|
3262
3639
|
for (let i = 0; i < checkable.length; i += CHUNK) {
|
|
3263
3640
|
const page = checkable.slice(i, i + CHUNK).map((e) => e.pda);
|
|
3264
|
-
const pageInfos = await connection
|
|
3641
|
+
const pageInfos = await fetchMultipleAccountBytes(connection, page, commitment);
|
|
3265
3642
|
infos.push(...pageInfos);
|
|
3266
3643
|
}
|
|
3267
3644
|
const spent = [];
|
|
@@ -3293,6 +3670,19 @@ async function preflightNullifiers(utxos, connection, programId, commitment = "c
|
|
|
3293
3670
|
}
|
|
3294
3671
|
|
|
3295
3672
|
// src/flows/settlement.ts
|
|
3673
|
+
function settlementConnectionFromRpc(rpc) {
|
|
3674
|
+
return {
|
|
3675
|
+
endpoint: rpc.endpoint,
|
|
3676
|
+
async getSignatureStatuses(signatures, config) {
|
|
3677
|
+
const { value } = await rpc.getSignatureStatuses(signatures, { searchTransactionHistory: config?.searchTransactionHistory ?? false }).send();
|
|
3678
|
+
return { value: value.map((v) => v ? { err: v.err, confirmationStatus: v.confirmationStatus ?? null } : null) };
|
|
3679
|
+
},
|
|
3680
|
+
async getMultipleAccounts(addresses, commitment) {
|
|
3681
|
+
const { value } = await rpc.getMultipleAccounts(addresses, { encoding: "base64", commitment: commitment ?? "confirmed" }).send();
|
|
3682
|
+
return value;
|
|
3683
|
+
}
|
|
3684
|
+
};
|
|
3685
|
+
}
|
|
3296
3686
|
var DEFAULT_SETTLEMENT_TIMEOUT_MS = 3e4;
|
|
3297
3687
|
var DEFAULT_SETTLEMENT_POLL_MS = 1500;
|
|
3298
3688
|
var MAX_SETTLEMENT_TIMEOUT_MS = 3e5;
|
|
@@ -3314,12 +3704,12 @@ function bigintToBytes324(value) {
|
|
|
3314
3704
|
}
|
|
3315
3705
|
return out;
|
|
3316
3706
|
}
|
|
3317
|
-
function deriveInputNullifierPdas(programId, mint, inputNullifiers) {
|
|
3318
|
-
const { pool } = getShieldPoolPDAs(programId, mint);
|
|
3707
|
+
async function deriveInputNullifierPdas(programId, mint, inputNullifiers) {
|
|
3708
|
+
const { pool } = await getShieldPoolPDAs(programId, mint);
|
|
3319
3709
|
const pdas = [];
|
|
3320
3710
|
for (const nullifier of inputNullifiers) {
|
|
3321
3711
|
if (nullifier === BigInt(0)) continue;
|
|
3322
|
-
const [pda2] = getNullifierPDA(pool, bigintToBytes324(nullifier), programId);
|
|
3712
|
+
const [pda2] = await getNullifierPDA(pool, bigintToBytes324(nullifier), programId);
|
|
3323
3713
|
pdas.push(pda2);
|
|
3324
3714
|
}
|
|
3325
3715
|
return pdas;
|
|
@@ -3341,7 +3731,7 @@ async function confirmTransactSettlement(params) {
|
|
|
3341
3731
|
const signature = isPlausibleSignature(params.signature) ? params.signature : null;
|
|
3342
3732
|
const reportedSomething = params.signature !== void 0 && params.signature !== null && params.signature !== "";
|
|
3343
3733
|
const unusableSignature = reportedSomething && signature === null;
|
|
3344
|
-
const pdas = deriveInputNullifierPdas(programId, mint, inputNullifiers);
|
|
3734
|
+
const pdas = await deriveInputNullifierPdas(programId, mint, inputNullifiers);
|
|
3345
3735
|
const deadline = Date.now() + Math.max(0, timeoutMs);
|
|
3346
3736
|
let signatureStatus = signature ? "absent" : "unchecked";
|
|
3347
3737
|
let nullifiersSpent = false;
|
|
@@ -3377,7 +3767,7 @@ async function confirmTransactSettlement(params) {
|
|
|
3377
3767
|
}
|
|
3378
3768
|
if (pdas.length > 0) {
|
|
3379
3769
|
try {
|
|
3380
|
-
const infos = await connection.
|
|
3770
|
+
const infos = await connection.getMultipleAccounts(pdas, "confirmed");
|
|
3381
3771
|
nullifiersSpent = Array.isArray(infos) && infos.length === pdas.length && infos.every((info) => info !== null && info !== void 0);
|
|
3382
3772
|
} catch (error) {
|
|
3383
3773
|
lastRpcError = error instanceof Error ? error.message : String(error);
|
|
@@ -3563,7 +3953,7 @@ var sdkLogger = createLogger("cloak::sdk");
|
|
|
3563
3953
|
// src/relay/relay-service.ts
|
|
3564
3954
|
var import_sha23 = require("@noble/hashes/sha2");
|
|
3565
3955
|
init_inputs();
|
|
3566
|
-
|
|
3956
|
+
init_address();
|
|
3567
3957
|
var RelayService = class {
|
|
3568
3958
|
/**
|
|
3569
3959
|
* Create a new Relay Service client
|
|
@@ -3880,7 +4270,7 @@ var RelayService = class {
|
|
|
3880
4270
|
viewingKey
|
|
3881
4271
|
);
|
|
3882
4272
|
const signed = await signRelayAuthPayload(
|
|
3883
|
-
typeof signMessage === "function" ?
|
|
4273
|
+
typeof signMessage === "function" ? messageSignerFromCallback((0, import_kit.address)(userPubkey), signMessage) : signMessage,
|
|
3884
4274
|
new TextEncoder().encode(challenge.message)
|
|
3885
4275
|
);
|
|
3886
4276
|
const signature = this.bytesToBase64(signed.signature);
|
|
@@ -3937,6 +4327,8 @@ var RelayService = class {
|
|
|
3937
4327
|
};
|
|
3938
4328
|
|
|
3939
4329
|
// src/relay/risk-quote.ts
|
|
4330
|
+
var import_compat = require("@solana/compat");
|
|
4331
|
+
init_address();
|
|
3940
4332
|
function buildRangeRiskScoreJob(OracleJob, walletAddress) {
|
|
3941
4333
|
return OracleJob.fromObject({
|
|
3942
4334
|
tasks: [
|
|
@@ -3989,7 +4381,7 @@ async function fetchRiskQuoteIx(connection, wallet, rangeApiKey) {
|
|
|
3989
4381
|
}
|
|
3990
4382
|
const feed = {
|
|
3991
4383
|
name: "Risk Score",
|
|
3992
|
-
jobs: [buildRangeRiskScoreJob(OracleJob, wallet
|
|
4384
|
+
jobs: [buildRangeRiskScoreJob(OracleJob, wallet)],
|
|
3993
4385
|
minJobResponses: 1,
|
|
3994
4386
|
minOracleSamples: 1,
|
|
3995
4387
|
maxJobRangePct: 100
|
|
@@ -4003,8 +4395,8 @@ async function fetchRiskQuoteIx(connection, wallet, rangeApiKey) {
|
|
|
4003
4395
|
// Must be at transaction index 0 for on-chain verification
|
|
4004
4396
|
});
|
|
4005
4397
|
return {
|
|
4006
|
-
instruction: sigVerifyIx,
|
|
4007
|
-
queue: queue.pubkey
|
|
4398
|
+
instruction: (0, import_compat.fromLegacyTransactionInstruction)(sigVerifyIx),
|
|
4399
|
+
queue: toAddress(queue.pubkey)
|
|
4008
4400
|
};
|
|
4009
4401
|
}
|
|
4010
4402
|
|
|
@@ -4049,81 +4441,72 @@ function encodeNoteSimple(note) {
|
|
|
4049
4441
|
}
|
|
4050
4442
|
|
|
4051
4443
|
// src/wallet/adapter.ts
|
|
4052
|
-
var import_web37 = require("@solana/web3.js");
|
|
4053
4444
|
init_types();
|
|
4054
|
-
function validateWalletConnected(
|
|
4055
|
-
if (
|
|
4056
|
-
|
|
4057
|
-
}
|
|
4058
|
-
if (!wallet.publicKey) {
|
|
4059
|
-
throw new CloakError(
|
|
4060
|
-
"Wallet not connected. Please connect your wallet first.",
|
|
4061
|
-
"wallet",
|
|
4062
|
-
false
|
|
4063
|
-
);
|
|
4445
|
+
function validateWalletConnected(signer) {
|
|
4446
|
+
if (!signer || !(0, import_kit2.isTransactionSigner)(signer)) {
|
|
4447
|
+
throw new CloakError("Wallet not connected. Please connect your wallet first.", "wallet", false);
|
|
4064
4448
|
}
|
|
4065
4449
|
}
|
|
4066
|
-
function getPublicKey(
|
|
4067
|
-
|
|
4068
|
-
|
|
4069
|
-
}
|
|
4070
|
-
if (!wallet.publicKey) {
|
|
4071
|
-
throw new CloakError(
|
|
4072
|
-
"Wallet not connected",
|
|
4073
|
-
"wallet",
|
|
4074
|
-
false
|
|
4075
|
-
);
|
|
4076
|
-
}
|
|
4077
|
-
return wallet.publicKey;
|
|
4450
|
+
function getPublicKey(signer) {
|
|
4451
|
+
validateWalletConnected(signer);
|
|
4452
|
+
return signer.address;
|
|
4078
4453
|
}
|
|
4079
|
-
async function sendTransaction(transaction,
|
|
4454
|
+
async function sendTransaction(transaction, connection, options) {
|
|
4080
4455
|
assertAllowedRpcConnection(connection);
|
|
4081
|
-
|
|
4082
|
-
return await connection.sendTransaction(transaction, [wallet], options);
|
|
4083
|
-
}
|
|
4084
|
-
if (wallet.sendTransaction) {
|
|
4085
|
-
return await wallet.sendTransaction(transaction, connection, options);
|
|
4086
|
-
} else if (wallet.signTransaction) {
|
|
4087
|
-
const signed = await wallet.signTransaction(transaction);
|
|
4088
|
-
return await connection.sendRawTransaction(signed.serialize(), options);
|
|
4089
|
-
} else {
|
|
4090
|
-
throw new CloakError(
|
|
4091
|
-
"Wallet does not support transaction signing",
|
|
4092
|
-
"wallet",
|
|
4093
|
-
false
|
|
4094
|
-
);
|
|
4095
|
-
}
|
|
4456
|
+
return sendRawTransaction(connection, transactionBytes(transaction), options);
|
|
4096
4457
|
}
|
|
4097
|
-
|
|
4098
|
-
|
|
4099
|
-
|
|
4100
|
-
|
|
4101
|
-
|
|
4102
|
-
|
|
4103
|
-
|
|
4104
|
-
|
|
4105
|
-
|
|
4106
|
-
|
|
4107
|
-
|
|
4108
|
-
|
|
4109
|
-
|
|
4110
|
-
}
|
|
4111
|
-
|
|
4112
|
-
|
|
4113
|
-
|
|
4114
|
-
|
|
4115
|
-
|
|
4116
|
-
|
|
4117
|
-
|
|
4118
|
-
|
|
4119
|
-
|
|
4120
|
-
|
|
4121
|
-
|
|
4122
|
-
|
|
4458
|
+
|
|
4459
|
+
// src/program/instructions.ts
|
|
4460
|
+
init_address();
|
|
4461
|
+
|
|
4462
|
+
// src/solana/instructions.ts
|
|
4463
|
+
var import_kit7 = require("@solana/kit");
|
|
4464
|
+
init_address();
|
|
4465
|
+
function accountMeta(address2, options = {}) {
|
|
4466
|
+
const { signer = false, writable: writable2 = false } = options;
|
|
4467
|
+
const role = signer ? writable2 ? import_kit7.AccountRole.WRITABLE_SIGNER : import_kit7.AccountRole.READONLY_SIGNER : writable2 ? import_kit7.AccountRole.WRITABLE : import_kit7.AccountRole.READONLY;
|
|
4468
|
+
return { address: address2, role };
|
|
4469
|
+
}
|
|
4470
|
+
function readonly(address2) {
|
|
4471
|
+
return { address: address2, role: import_kit7.AccountRole.READONLY };
|
|
4472
|
+
}
|
|
4473
|
+
function writable(address2) {
|
|
4474
|
+
return { address: address2, role: import_kit7.AccountRole.WRITABLE };
|
|
4475
|
+
}
|
|
4476
|
+
function writableSigner(address2) {
|
|
4477
|
+
return { address: address2, role: import_kit7.AccountRole.WRITABLE_SIGNER };
|
|
4478
|
+
}
|
|
4479
|
+
function programInstruction(programAddress, accounts, data) {
|
|
4480
|
+
return { programAddress, accounts: [...accounts], data };
|
|
4481
|
+
}
|
|
4482
|
+
var THIS_INSTRUCTION = 65535;
|
|
4483
|
+
var ED25519_HEADER_BYTES = 16;
|
|
4484
|
+
function ed25519VerifyInstruction(params) {
|
|
4485
|
+
const { publicKey, message, signature } = params;
|
|
4486
|
+
if (publicKey.length !== 32) throw new Error(`Public key must be 32 bytes, got ${publicKey.length}`);
|
|
4487
|
+
if (signature.length !== 64) throw new Error(`Signature must be 64 bytes, got ${signature.length}`);
|
|
4488
|
+
const index = params.instructionIndex ?? THIS_INSTRUCTION;
|
|
4489
|
+
const publicKeyOffset = ED25519_HEADER_BYTES;
|
|
4490
|
+
const signatureOffset = publicKeyOffset + publicKey.length;
|
|
4491
|
+
const messageOffset = signatureOffset + signature.length;
|
|
4492
|
+
const data = new Uint8Array(messageOffset + message.length);
|
|
4493
|
+
const view = new DataView(data.buffer);
|
|
4494
|
+
data[0] = 1;
|
|
4495
|
+
data[1] = 0;
|
|
4496
|
+
view.setUint16(2, signatureOffset, true);
|
|
4497
|
+
view.setUint16(4, index, true);
|
|
4498
|
+
view.setUint16(6, publicKeyOffset, true);
|
|
4499
|
+
view.setUint16(8, index, true);
|
|
4500
|
+
view.setUint16(10, messageOffset, true);
|
|
4501
|
+
view.setUint16(12, message.length, true);
|
|
4502
|
+
view.setUint16(14, index, true);
|
|
4503
|
+
data.set(publicKey, publicKeyOffset);
|
|
4504
|
+
data.set(signature, signatureOffset);
|
|
4505
|
+
data.set(message, messageOffset);
|
|
4506
|
+
return { programAddress: ED25519_PROGRAM_ADDRESS, accounts: [], data };
|
|
4123
4507
|
}
|
|
4124
4508
|
|
|
4125
4509
|
// src/program/instructions.ts
|
|
4126
|
-
var import_web38 = require("@solana/web3.js");
|
|
4127
4510
|
function createDepositInstruction(params) {
|
|
4128
4511
|
if (params.commitment.length !== 32) {
|
|
4129
4512
|
throw new Error(
|
|
@@ -4145,33 +4528,33 @@ function createDepositInstruction(params) {
|
|
|
4145
4528
|
data.set(discriminant, 0);
|
|
4146
4529
|
data.set(amountBytes, 1);
|
|
4147
4530
|
data.set(params.commitment, 9);
|
|
4148
|
-
return
|
|
4149
|
-
|
|
4150
|
-
|
|
4531
|
+
return programInstruction(
|
|
4532
|
+
params.programId,
|
|
4533
|
+
[
|
|
4151
4534
|
// Account 0: Payer (signer, writable) - pays for transaction
|
|
4152
|
-
|
|
4535
|
+
writableSigner(params.payer),
|
|
4153
4536
|
// Account 1: Pool (writable) - receives SOL
|
|
4154
|
-
|
|
4537
|
+
writable(params.pool),
|
|
4155
4538
|
// Account 2: System Program (readonly) - for transfers
|
|
4156
|
-
|
|
4539
|
+
readonly(import_system.SYSTEM_PROGRAM_ADDRESS),
|
|
4157
4540
|
// Account 3: Merkle Tree (writable) - stores on-chain Merkle tree
|
|
4158
|
-
|
|
4541
|
+
writable(params.merkleTree)
|
|
4159
4542
|
],
|
|
4160
|
-
data
|
|
4161
|
-
|
|
4543
|
+
data
|
|
4544
|
+
);
|
|
4162
4545
|
}
|
|
4163
4546
|
function validateDepositParams(params) {
|
|
4164
|
-
if (
|
|
4165
|
-
throw new Error("programId must be
|
|
4547
|
+
if (typeof params.programId !== "string" || !(0, import_kit.isAddress)(params.programId)) {
|
|
4548
|
+
throw new Error("programId must be an address");
|
|
4166
4549
|
}
|
|
4167
|
-
if (
|
|
4168
|
-
throw new Error("payer must be
|
|
4550
|
+
if (typeof params.payer !== "string" || !(0, import_kit.isAddress)(params.payer)) {
|
|
4551
|
+
throw new Error("payer must be an address");
|
|
4169
4552
|
}
|
|
4170
|
-
if (
|
|
4171
|
-
throw new Error("pool must be
|
|
4553
|
+
if (typeof params.pool !== "string" || !(0, import_kit.isAddress)(params.pool)) {
|
|
4554
|
+
throw new Error("pool must be an address");
|
|
4172
4555
|
}
|
|
4173
|
-
if (
|
|
4174
|
-
throw new Error("merkleTree must be
|
|
4556
|
+
if (typeof params.merkleTree !== "string" || !(0, import_kit.isAddress)(params.merkleTree)) {
|
|
4557
|
+
throw new Error("merkleTree must be an address");
|
|
4175
4558
|
}
|
|
4176
4559
|
if (typeof params.amount !== "number" || params.amount <= 0) {
|
|
4177
4560
|
throw new Error("amount must be a positive number");
|
|
@@ -4227,7 +4610,7 @@ async function readMerkleTreeState(connection, merkleTreePDA, forceConfirmed = f
|
|
|
4227
4610
|
const rootUrl = new URL(relayUrl);
|
|
4228
4611
|
rootUrl.pathname = rootUrl.pathname.replace(/\/$/, "") + "/merkle-root";
|
|
4229
4612
|
if (mint) {
|
|
4230
|
-
rootUrl.searchParams.set("mint", mint
|
|
4613
|
+
rootUrl.searchParams.set("mint", mint);
|
|
4231
4614
|
}
|
|
4232
4615
|
const controller = new AbortController();
|
|
4233
4616
|
const timeoutId = globalThis.setTimeout(
|
|
@@ -4248,13 +4631,11 @@ async function readMerkleTreeState(connection, merkleTreePDA, forceConfirmed = f
|
|
|
4248
4631
|
} catch (e) {
|
|
4249
4632
|
}
|
|
4250
4633
|
}
|
|
4251
|
-
const commitment =
|
|
4252
|
-
const accountInfo = await connection
|
|
4253
|
-
commitment
|
|
4254
|
-
});
|
|
4634
|
+
const commitment = "confirmed";
|
|
4635
|
+
const accountInfo = await fetchAccountBytes(connection, merkleTreePDA, commitment);
|
|
4255
4636
|
if (!accountInfo) {
|
|
4256
4637
|
throw new Error(
|
|
4257
|
-
`Merkle tree account not found at ${merkleTreePDA
|
|
4638
|
+
`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.`
|
|
4258
4639
|
);
|
|
4259
4640
|
}
|
|
4260
4641
|
const data = accountInfo.data;
|
|
@@ -4533,7 +4914,12 @@ async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
|
|
|
4533
4914
|
}
|
|
4534
4915
|
|
|
4535
4916
|
// src/relay/client.ts
|
|
4536
|
-
|
|
4917
|
+
init_address();
|
|
4918
|
+
|
|
4919
|
+
// src/config/transaction-version.ts
|
|
4920
|
+
var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
|
|
4921
|
+
|
|
4922
|
+
// src/relay/client.ts
|
|
4537
4923
|
var import_bs58 = __toESM(require("bs58"), 1);
|
|
4538
4924
|
|
|
4539
4925
|
// src/notes/refund-leaf.ts
|
|
@@ -4642,9 +5028,6 @@ function isBrowserLike() {
|
|
|
4642
5028
|
return typeof globalThis !== "undefined" && (typeof globalThis.window !== "undefined" || typeof globalThis.document !== "undefined");
|
|
4643
5029
|
}
|
|
4644
5030
|
|
|
4645
|
-
// src/config/transaction-version.ts
|
|
4646
|
-
var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
|
|
4647
|
-
|
|
4648
5031
|
// src/relay/client.ts
|
|
4649
5032
|
var bs58 = import_bs58.default.default || import_bs58.default;
|
|
4650
5033
|
var TRANSACT_TAG = 0;
|
|
@@ -4653,7 +5036,7 @@ var CLOSE_SWAP_STATE_TAG = 13;
|
|
|
4653
5036
|
var CLOSE_SWAP_STATE_PHASE1_PAYLOAD_LEN = 40;
|
|
4654
5037
|
var CLOSE_SWAP_STATE_PHASE1_WIRE_LEN = 1 + CLOSE_SWAP_STATE_PHASE1_PAYLOAD_LEN;
|
|
4655
5038
|
var CLOSE_SWAP_STATE_COMMITMENT_END = 1 + 32;
|
|
4656
|
-
var NATIVE_SOL_MINT2 =
|
|
5039
|
+
var NATIVE_SOL_MINT2 = (0, import_kit.address)("So11111111111111111111111111111111111111112");
|
|
4657
5040
|
var PROOF_LEN = 256;
|
|
4658
5041
|
var PUBLIC_INPUTS_LEN = 264;
|
|
4659
5042
|
var COMMITMENTS_OFFSET = 168;
|
|
@@ -4709,7 +5092,7 @@ async function fetchCommitments(relayUrl, options = {}) {
|
|
|
4709
5092
|
}
|
|
4710
5093
|
}
|
|
4711
5094
|
if (options.mint) {
|
|
4712
|
-
url.searchParams.set("mint", options.mint
|
|
5095
|
+
url.searchParams.set("mint", options.mint);
|
|
4713
5096
|
}
|
|
4714
5097
|
if (options.fromIndex !== void 0) {
|
|
4715
5098
|
url.searchParams.set("from_index", String(options.fromIndex));
|
|
@@ -4808,7 +5191,7 @@ function extractCommitmentsFromInstruction(data, expectedMint) {
|
|
|
4808
5191
|
"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."
|
|
4809
5192
|
);
|
|
4810
5193
|
}
|
|
4811
|
-
if (
|
|
5194
|
+
if (expectedMint !== NATIVE_SOL_MINT2) return [];
|
|
4812
5195
|
const commitment = data.slice(1, CLOSE_SWAP_STATE_COMMITMENT_END);
|
|
4813
5196
|
return isAllZero(commitment) ? [] : [commitment];
|
|
4814
5197
|
}
|
|
@@ -4838,7 +5221,7 @@ async function buildMerkleTreeFromChain(connection, programId, merkleTree, onPro
|
|
|
4838
5221
|
let before;
|
|
4839
5222
|
onProgress?.("Fetching program signatures from chain...");
|
|
4840
5223
|
while (true) {
|
|
4841
|
-
const batch = await connection
|
|
5224
|
+
const batch = await fetchSignaturesForAddress(connection, programId, {
|
|
4842
5225
|
before,
|
|
4843
5226
|
limit: 1e3
|
|
4844
5227
|
});
|
|
@@ -4849,22 +5232,22 @@ async function buildMerkleTreeFromChain(connection, programId, merkleTree, onPro
|
|
|
4849
5232
|
}
|
|
4850
5233
|
signatures.reverse();
|
|
4851
5234
|
const commitments = [];
|
|
4852
|
-
const programIdBase58 = programId
|
|
5235
|
+
const programIdBase58 = programId;
|
|
4853
5236
|
for (let i = 0; i < signatures.length; i++) {
|
|
4854
5237
|
if (i % 100 === 0) {
|
|
4855
5238
|
onProgress?.(`Processing transactions... ${i}/${signatures.length}`);
|
|
4856
5239
|
}
|
|
4857
5240
|
const signature = signatures[i];
|
|
4858
|
-
const tx = await connection
|
|
5241
|
+
const tx = await fetchParsedTransaction(connection, signature, {
|
|
4859
5242
|
maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION,
|
|
4860
5243
|
commitment: "confirmed"
|
|
4861
5244
|
});
|
|
4862
5245
|
if (!tx || tx.meta?.err) continue;
|
|
4863
5246
|
for (const ix of tx.transaction.message.instructions) {
|
|
4864
|
-
if (!(
|
|
4865
|
-
if (ix.programId
|
|
5247
|
+
if (!isRawParsedInstruction(ix)) continue;
|
|
5248
|
+
if (ix.programId !== programIdBase58) continue;
|
|
4866
5249
|
const accounts = ix.accounts;
|
|
4867
|
-
if (!accounts || !accounts.some((a) => a
|
|
5250
|
+
if (!accounts || !accounts.some((a) => a === merkleTree)) continue;
|
|
4868
5251
|
const data = bs58.decode(ix.data);
|
|
4869
5252
|
const extracted = extractCommitmentsFromInstruction(data, mint);
|
|
4870
5253
|
for (const commitment of extracted) {
|
|
@@ -4942,8 +5325,11 @@ async function preflightCheck(relayUrl, rootHex) {
|
|
|
4942
5325
|
}
|
|
4943
5326
|
|
|
4944
5327
|
// src/flows/transact.ts
|
|
4945
|
-
var
|
|
4946
|
-
var
|
|
5328
|
+
var import_kit8 = require("@solana/kit");
|
|
5329
|
+
var import_compute_budget = require("@solana-program/compute-budget");
|
|
5330
|
+
var import_address_lookup_table2 = require("@solana-program/address-lookup-table");
|
|
5331
|
+
var import_token = require("@solana-program/token");
|
|
5332
|
+
init_address();
|
|
4947
5333
|
var snarkjs = __toESM(require("snarkjs"), 1);
|
|
4948
5334
|
init_utxo();
|
|
4949
5335
|
|
|
@@ -5170,7 +5556,7 @@ function chainNoteFromBase64(base64) {
|
|
|
5170
5556
|
}
|
|
5171
5557
|
|
|
5172
5558
|
// src/notes/delivery-note.ts
|
|
5173
|
-
var
|
|
5559
|
+
var import_tweetnacl4 = __toESM(require("tweetnacl"), 1);
|
|
5174
5560
|
var RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN = 32;
|
|
5175
5561
|
var RECIPIENT_DELIVERY_NONCE_LEN = 24;
|
|
5176
5562
|
var RECIPIENT_DELIVERY_PLAINTEXT_LEN = 40;
|
|
@@ -5221,10 +5607,10 @@ function encodeRecipientDeliveryNote(note, recipientViewingPublicKey) {
|
|
|
5221
5607
|
const plaintext = new Uint8Array(RECIPIENT_DELIVERY_PLAINTEXT_LEN);
|
|
5222
5608
|
writeU64LE2(plaintext, 0, note.amount);
|
|
5223
5609
|
writeU256BE2(plaintext, 8, note.blinding);
|
|
5224
|
-
const ephemeral =
|
|
5225
|
-
const shared =
|
|
5226
|
-
const nonce =
|
|
5227
|
-
const ciphertext =
|
|
5610
|
+
const ephemeral = import_tweetnacl4.default.box.keyPair();
|
|
5611
|
+
const shared = import_tweetnacl4.default.box.before(recipientViewingPublicKey, ephemeral.secretKey);
|
|
5612
|
+
const nonce = import_tweetnacl4.default.randomBytes(import_tweetnacl4.default.secretbox.nonceLength);
|
|
5613
|
+
const ciphertext = import_tweetnacl4.default.secretbox(plaintext, nonce, shared);
|
|
5228
5614
|
if (ciphertext.length !== RECIPIENT_DELIVERY_CIPHERTEXT_LEN) {
|
|
5229
5615
|
throw new Error(
|
|
5230
5616
|
`delivery ciphertext must be ${RECIPIENT_DELIVERY_CIPHERTEXT_LEN} bytes, got ${ciphertext.length}`
|
|
@@ -5250,8 +5636,8 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
|
|
|
5250
5636
|
const ciphertext = envelope.slice(
|
|
5251
5637
|
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
|
|
5252
5638
|
);
|
|
5253
|
-
const shared =
|
|
5254
|
-
const plaintext =
|
|
5639
|
+
const shared = import_tweetnacl4.default.box.before(ephemeralPk, viewingSecretKey);
|
|
5640
|
+
const plaintext = import_tweetnacl4.default.secretbox.open(ciphertext, nonce, shared);
|
|
5255
5641
|
if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
|
|
5256
5642
|
return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
|
|
5257
5643
|
} catch {
|
|
@@ -5309,7 +5695,7 @@ function parseDeliveryCarrierMemo(data) {
|
|
|
5309
5695
|
|
|
5310
5696
|
// src/notes/swap-refund.ts
|
|
5311
5697
|
var import_blake34 = require("@noble/hashes/blake3");
|
|
5312
|
-
|
|
5698
|
+
init_address();
|
|
5313
5699
|
var import_bs582 = __toESM(require("bs58"), 1);
|
|
5314
5700
|
init_utxo();
|
|
5315
5701
|
init_inputs();
|
|
@@ -5455,11 +5841,8 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
|
5455
5841
|
}
|
|
5456
5842
|
const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
|
|
5457
5843
|
const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
|
|
5458
|
-
const programIdBase58 = programId
|
|
5459
|
-
const [pool] =
|
|
5460
|
-
[Buffer.from("pool"), poolMint.toBuffer()],
|
|
5461
|
-
programId
|
|
5462
|
-
);
|
|
5844
|
+
const programIdBase58 = programId;
|
|
5845
|
+
const [pool] = await findProgramAddress(["pool", addressBytes(poolMint)], programId);
|
|
5463
5846
|
onStatus?.("Fetching program signatures...");
|
|
5464
5847
|
const signatures = [];
|
|
5465
5848
|
let before;
|
|
@@ -5467,7 +5850,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
|
5467
5850
|
for (; ; ) {
|
|
5468
5851
|
const want = limit > 0 ? Math.min(limit - signatures.length, pageSize) : pageSize;
|
|
5469
5852
|
if (want <= 0) break;
|
|
5470
|
-
const page = await connection
|
|
5853
|
+
const page = await fetchSignaturesForAddress(connection, programId, { before, limit: want });
|
|
5471
5854
|
if (!Array.isArray(page) || page.length === 0) break;
|
|
5472
5855
|
let stop = false;
|
|
5473
5856
|
for (const entry of page) {
|
|
@@ -5488,7 +5871,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
|
5488
5871
|
const fetched = await Promise.all(
|
|
5489
5872
|
batch.map(async (signature) => {
|
|
5490
5873
|
try {
|
|
5491
|
-
return await connection
|
|
5874
|
+
return await fetchTransactionJson(connection, signature, {
|
|
5492
5875
|
commitment: "confirmed",
|
|
5493
5876
|
maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
|
|
5494
5877
|
});
|
|
@@ -5507,11 +5890,11 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
|
5507
5890
|
if (data[0] !== TRANSACT_SWAP_TAG2 || data.length < MIN_TRANSACT_SWAP_LEN) continue;
|
|
5508
5891
|
const nullifier = data.slice(NULLIFIER_0_OFFSET, NULLIFIER_0_OFFSET + 32);
|
|
5509
5892
|
if (nullifier.length !== 32) continue;
|
|
5510
|
-
const [swapState] =
|
|
5511
|
-
[
|
|
5893
|
+
const [swapState] = await findProgramAddress(
|
|
5894
|
+
["swap_state", addressBytes(pool), new Uint8Array(nullifier)],
|
|
5512
5895
|
programId
|
|
5513
5896
|
);
|
|
5514
|
-
const key = swapState
|
|
5897
|
+
const key = swapState;
|
|
5515
5898
|
if (!nullifierBySwapState.has(key)) nullifierBySwapState.set(key, { nullifier, signature });
|
|
5516
5899
|
}
|
|
5517
5900
|
const logs = tx.meta?.logMessages;
|
|
@@ -5736,7 +6119,7 @@ async function matchChangeNote(params) {
|
|
|
5736
6119
|
|
|
5737
6120
|
// src/flows/transact.ts
|
|
5738
6121
|
var import_circomlibjs4 = require("circomlibjs");
|
|
5739
|
-
var
|
|
6122
|
+
var import_tweetnacl5 = __toESM(require("tweetnacl"), 1);
|
|
5740
6123
|
init_inputs();
|
|
5741
6124
|
|
|
5742
6125
|
// src/proving/artifacts.ts
|
|
@@ -6055,7 +6438,7 @@ function isRetryableRelayStatus(status) {
|
|
|
6055
6438
|
}
|
|
6056
6439
|
function isBlockhashExpiryError(error) {
|
|
6057
6440
|
const message = error instanceof Error ? error.message : String(error);
|
|
6058
|
-
return /block height exceeded/i.test(message) || /transactionexpiredblockheightexceedederror/i.test(message) || /blockhash not found/i.test(message) || /signature .* has expired/i.test(message);
|
|
6441
|
+
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);
|
|
6059
6442
|
}
|
|
6060
6443
|
function isTransientTransportError(error) {
|
|
6061
6444
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -6073,7 +6456,7 @@ function nearTipFallbackMaxDistance(connection) {
|
|
|
6073
6456
|
if (Number.isFinite(override)) {
|
|
6074
6457
|
return Math.max(0, Math.floor(override));
|
|
6075
6458
|
}
|
|
6076
|
-
return isLocalRpcEndpoint(connection
|
|
6459
|
+
return isLocalRpcEndpoint(rpcEndpoint(connection) ?? "") ? NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_LOCAL_RPC : NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_DEFAULT;
|
|
6077
6460
|
}
|
|
6078
6461
|
function shouldUseRelayMerkleByDefault(connection) {
|
|
6079
6462
|
const forceRelayMerkle = typeof process !== "undefined" && process.env ? process.env.CLOAK_FORCE_RELAY_MERKLE_TREE : void 0;
|
|
@@ -6084,7 +6467,7 @@ function shouldUseRelayMerkleByDefault(connection) {
|
|
|
6084
6467
|
if (disableRelayMerkle === "1" || disableRelayMerkle === "true") {
|
|
6085
6468
|
return false;
|
|
6086
6469
|
}
|
|
6087
|
-
return !isLocalRpcEndpoint(connection
|
|
6470
|
+
return !isLocalRpcEndpoint(rpcEndpoint(connection) ?? "");
|
|
6088
6471
|
}
|
|
6089
6472
|
async function fetchAltAddressesFromRelayHealth(relayUrl) {
|
|
6090
6473
|
try {
|
|
@@ -6099,13 +6482,13 @@ async function fetchAltAddressesFromRelayHealth(relayUrl) {
|
|
|
6099
6482
|
}
|
|
6100
6483
|
async function fetchSupplementalAltFromRelay(relayUrl, params) {
|
|
6101
6484
|
const body = JSON.stringify({
|
|
6102
|
-
mint: params.mint
|
|
6485
|
+
mint: params.mint,
|
|
6103
6486
|
nullifiers: [
|
|
6104
6487
|
Buffer.from(params.nullifiers[0]).toString("hex"),
|
|
6105
6488
|
Buffer.from(params.nullifiers[1]).toString("hex")
|
|
6106
6489
|
],
|
|
6107
6490
|
bind0: Buffer.from(params.bind0).toString("hex"),
|
|
6108
|
-
depositor: params.depositor
|
|
6491
|
+
depositor: params.depositor
|
|
6109
6492
|
});
|
|
6110
6493
|
let response;
|
|
6111
6494
|
try {
|
|
@@ -6138,38 +6521,36 @@ async function fetchSupplementalAltFromRelay(relayUrl, params) {
|
|
|
6138
6521
|
if (typeof table !== "string" || table.length === 0) {
|
|
6139
6522
|
throw new Error("Supplemental ALT response is missing a 'table' address");
|
|
6140
6523
|
}
|
|
6141
|
-
|
|
6142
|
-
return new import_web311.PublicKey(table);
|
|
6143
|
-
} catch {
|
|
6524
|
+
if (!(0, import_kit.isAddress)(table)) {
|
|
6144
6525
|
throw new Error(`Supplemental ALT response 'table' is not a valid public key: ${table}`);
|
|
6145
6526
|
}
|
|
6527
|
+
return (0, import_kit.address)(table);
|
|
6146
6528
|
}
|
|
6147
6529
|
async function resolveRelaySupplementalAlt(connection, table, expected, pollOpts) {
|
|
6148
6530
|
const pollIntervalMs = pollOpts?.pollIntervalMs ?? 150;
|
|
6149
6531
|
const timeoutMs = pollOpts?.timeoutMs ?? 5e3;
|
|
6150
|
-
const expectedB58 = expected.map((pk) => pk.toBase58());
|
|
6151
6532
|
const deadline = Date.now() + timeoutMs;
|
|
6152
6533
|
for (; ; ) {
|
|
6153
|
-
const result = await
|
|
6154
|
-
if (!result.
|
|
6155
|
-
throw new Error(`Supplemental ALT ${table
|
|
6534
|
+
const result = await (0, import_address_lookup_table2.fetchMaybeAddressLookupTable)(connection, table, { commitment: "confirmed" });
|
|
6535
|
+
if (!result.exists) {
|
|
6536
|
+
throw new Error(`Supplemental ALT ${table} could not be fetched from the RPC.`);
|
|
6156
6537
|
}
|
|
6157
|
-
const account = result.
|
|
6158
|
-
const present = new Set(account.
|
|
6159
|
-
const missing =
|
|
6538
|
+
const account = result.data;
|
|
6539
|
+
const present = new Set(account.addresses);
|
|
6540
|
+
const missing = expected.filter((addr) => !present.has(addr));
|
|
6160
6541
|
if (missing.length === 0) {
|
|
6161
|
-
const currentSlot = await connection
|
|
6162
|
-
if (account.
|
|
6163
|
-
return account;
|
|
6542
|
+
const currentSlot = await fetchSlot(connection, "confirmed");
|
|
6543
|
+
if (Number(account.lastExtendedSlot) < currentSlot) {
|
|
6544
|
+
return { address: table, addresses: account.addresses };
|
|
6164
6545
|
}
|
|
6165
6546
|
if (Date.now() >= deadline) {
|
|
6166
6547
|
throw new Error(
|
|
6167
|
-
`Supplemental ALT ${table
|
|
6548
|
+
`Supplemental ALT ${table} did not become resolvable within ${timeoutMs}ms (lastExtendedSlot=${account.lastExtendedSlot} never fell behind current slot=${currentSlot}).`
|
|
6168
6549
|
);
|
|
6169
6550
|
}
|
|
6170
6551
|
} else if (Date.now() >= deadline) {
|
|
6171
6552
|
throw new Error(
|
|
6172
|
-
`Supplemental ALT ${table
|
|
6553
|
+
`Supplemental ALT ${table} is still missing expected address(es) after ${timeoutMs}ms: ` + missing.join(", ")
|
|
6173
6554
|
);
|
|
6174
6555
|
}
|
|
6175
6556
|
await sleep2(pollIntervalMs);
|
|
@@ -6198,7 +6579,7 @@ async function resolveAddressLookupTableAccounts(connection, relayUrl, altAddres
|
|
|
6198
6579
|
if (altAddresses.length === 0) {
|
|
6199
6580
|
return void 0;
|
|
6200
6581
|
}
|
|
6201
|
-
const cacheKey = `${connection
|
|
6582
|
+
const cacheKey = `${rpcEndpoint(connection) ?? ""}|${altAddresses.join(",")}`;
|
|
6202
6583
|
const cached = _resolvedAltAccountsCache.get(cacheKey);
|
|
6203
6584
|
if (cached && cached.length > 0) {
|
|
6204
6585
|
return cached;
|
|
@@ -6207,9 +6588,9 @@ async function resolveAddressLookupTableAccounts(connection, relayUrl, altAddres
|
|
|
6207
6588
|
const fetched = await Promise.all(
|
|
6208
6589
|
altAddresses.map(async (addr) => {
|
|
6209
6590
|
try {
|
|
6210
|
-
const
|
|
6211
|
-
const result = await
|
|
6212
|
-
return result.
|
|
6591
|
+
const table = (0, import_kit.address)(addr);
|
|
6592
|
+
const result = await (0, import_address_lookup_table2.fetchMaybeAddressLookupTable)(connection, table);
|
|
6593
|
+
return result.exists ? { address: table, addresses: result.data.addresses } : null;
|
|
6213
6594
|
} catch {
|
|
6214
6595
|
return null;
|
|
6215
6596
|
}
|
|
@@ -6297,24 +6678,21 @@ function calculateConfiguredProtocolFee(amount, config) {
|
|
|
6297
6678
|
return total;
|
|
6298
6679
|
}
|
|
6299
6680
|
async function readLiveProtocolFee(connection, programId, mint, amount, requireSwapOpen = false) {
|
|
6300
|
-
const [poolConfigPda] =
|
|
6301
|
-
|
|
6302
|
-
programId
|
|
6303
|
-
);
|
|
6304
|
-
const account = await connection.getAccountInfo(poolConfigPda, "confirmed");
|
|
6681
|
+
const [poolConfigPda] = await findProgramAddress(["pool_config", addressBytes(mint)], programId);
|
|
6682
|
+
const account = await fetchAccountBytes(connection, poolConfigPda, "confirmed");
|
|
6305
6683
|
if (!account) {
|
|
6306
6684
|
throw new Error(
|
|
6307
|
-
`PoolConfig ${poolConfigPda
|
|
6685
|
+
`PoolConfig ${poolConfigPda} is missing; refusing to build a fee-bearing proof`
|
|
6308
6686
|
);
|
|
6309
6687
|
}
|
|
6310
|
-
if (
|
|
6311
|
-
throw new Error(`PoolConfig ${poolConfigPda
|
|
6688
|
+
if (account.owner !== programId) {
|
|
6689
|
+
throw new Error(`PoolConfig ${poolConfigPda} has the wrong owner`);
|
|
6312
6690
|
}
|
|
6313
6691
|
const config = decodePoolProtocolFeeConfig(account.data);
|
|
6314
6692
|
if (requireSwapOpen && config.swapsPaused) {
|
|
6315
6693
|
throw new Error("Swap intake is paused for this pool");
|
|
6316
6694
|
}
|
|
6317
|
-
const defaultFixed = mint
|
|
6695
|
+
const defaultFixed = mint === NATIVE_SOL_MINT ? BigInt(5e6) : BigInt(45e4);
|
|
6318
6696
|
if (config.fixedFee > defaultFixed * BigInt(20)) {
|
|
6319
6697
|
throw new Error("PoolConfig fixed fee exceeds the protocol cap");
|
|
6320
6698
|
}
|
|
@@ -6352,15 +6730,15 @@ function assertInputMints(inputUtxos, expectedMint) {
|
|
|
6352
6730
|
if (funded.length === 0) return;
|
|
6353
6731
|
const first = funded[0].mintAddress;
|
|
6354
6732
|
for (const utxo of funded) {
|
|
6355
|
-
if (
|
|
6733
|
+
if (utxo.mintAddress !== first) {
|
|
6356
6734
|
throw new Error(
|
|
6357
|
-
`Input notes span more than one mint (${first
|
|
6735
|
+
`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.`
|
|
6358
6736
|
);
|
|
6359
6737
|
}
|
|
6360
6738
|
}
|
|
6361
|
-
if (expectedMint &&
|
|
6739
|
+
if (expectedMint && first !== expectedMint) {
|
|
6362
6740
|
throw new Error(
|
|
6363
|
-
`Input notes are ${first
|
|
6741
|
+
`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.`
|
|
6364
6742
|
);
|
|
6365
6743
|
}
|
|
6366
6744
|
}
|
|
@@ -6415,7 +6793,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
|
|
|
6415
6793
|
);
|
|
6416
6794
|
}
|
|
6417
6795
|
const viewingKeyHex = toHex(nk);
|
|
6418
|
-
const cacheKey = `${relayUrl}|${userPubkey
|
|
6796
|
+
const cacheKey = `${relayUrl}|${userPubkey}|${viewingKeyHex}`;
|
|
6419
6797
|
if (_registeredViewingKeys.has(cacheKey)) {
|
|
6420
6798
|
return;
|
|
6421
6799
|
}
|
|
@@ -6443,7 +6821,7 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
|
|
|
6443
6821
|
method: "POST",
|
|
6444
6822
|
headers: { "Content-Type": "application/json" },
|
|
6445
6823
|
body: JSON.stringify({
|
|
6446
|
-
user_pubkey: userPubkey
|
|
6824
|
+
user_pubkey: userPubkey,
|
|
6447
6825
|
viewing_key: viewingKeyHex
|
|
6448
6826
|
})
|
|
6449
6827
|
});
|
|
@@ -6455,7 +6833,7 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
|
|
|
6455
6833
|
}
|
|
6456
6834
|
const challenge = parseStrictViewingKeyChallenge(
|
|
6457
6835
|
await challengeResponse.json(),
|
|
6458
|
-
userPubkey
|
|
6836
|
+
userPubkey,
|
|
6459
6837
|
viewingKeyHex
|
|
6460
6838
|
);
|
|
6461
6839
|
let signatureBase64;
|
|
@@ -6465,21 +6843,21 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
|
|
|
6465
6843
|
const sig = await options.signMessage(messageBytes);
|
|
6466
6844
|
signatureBase64 = Buffer.from(sig).toString("base64");
|
|
6467
6845
|
} else if (options.depositorKeypair) {
|
|
6468
|
-
const sig =
|
|
6846
|
+
const sig = await signMessageBytes(options.depositorKeypair, messageBytes);
|
|
6847
|
+
signatureBase64 = Buffer.from(sig).toString("base64");
|
|
6848
|
+
} else if (options.signer && isMessageSigner(options.signer)) {
|
|
6849
|
+
const sig = await signMessageBytes(options.signer, messageBytes);
|
|
6469
6850
|
signatureBase64 = Buffer.from(sig).toString("base64");
|
|
6470
|
-
} else if (options.
|
|
6851
|
+
} else if (options.signer) {
|
|
6471
6852
|
onProgress?.(
|
|
6472
6853
|
"Approve the viewing-key registration in your wallet. It shows as a 0 SOL transfer to yourself and is never sent to the network."
|
|
6473
6854
|
);
|
|
6474
|
-
const signed = await signRelayAuthPayload(
|
|
6475
|
-
{ walletPublicKey: userPubkey, signAuthTransaction: options.signAuthTransaction },
|
|
6476
|
-
messageBytes
|
|
6477
|
-
);
|
|
6855
|
+
const signed = await signRelayAuthPayload(options.signer, messageBytes);
|
|
6478
6856
|
signatureBase64 = Buffer.from(signed.signature).toString("base64");
|
|
6479
6857
|
authMode = signed.mode;
|
|
6480
6858
|
} else {
|
|
6481
6859
|
throw new Error(
|
|
6482
|
-
"Viewing key registration is mandatory: signMessage or
|
|
6860
|
+
"Viewing key registration is mandatory: signMessage or signer (wallet) or depositorKeypair is required."
|
|
6483
6861
|
);
|
|
6484
6862
|
}
|
|
6485
6863
|
onProgress?.("Registering viewing key...");
|
|
@@ -6487,7 +6865,7 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
|
|
|
6487
6865
|
method: "POST",
|
|
6488
6866
|
headers: { "Content-Type": "application/json" },
|
|
6489
6867
|
body: JSON.stringify({
|
|
6490
|
-
user_pubkey: userPubkey
|
|
6868
|
+
user_pubkey: userPubkey,
|
|
6491
6869
|
viewing_key: viewingKeyHex,
|
|
6492
6870
|
nonce: challenge.nonce,
|
|
6493
6871
|
signature: signatureBase64,
|
|
@@ -6585,14 +6963,11 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
|
|
|
6585
6963
|
var TRANSACT_DISCRIMINATOR = 0;
|
|
6586
6964
|
var RANGE_QUOTE_TAG_DEPOSIT = 1;
|
|
6587
6965
|
function deriveRiskNoncePDA(programId, nonce) {
|
|
6588
|
-
return
|
|
6589
|
-
[Buffer.from("risk_nonce"), Buffer.from(nonce)],
|
|
6590
|
-
programId
|
|
6591
|
-
);
|
|
6966
|
+
return findProgramAddress(["risk_nonce", new Uint8Array(nonce)], programId);
|
|
6592
6967
|
}
|
|
6593
6968
|
function extractDepositNonceFromEd25519Ix(ix) {
|
|
6594
6969
|
try {
|
|
6595
|
-
const data = Buffer.from(ix.data);
|
|
6970
|
+
const data = Buffer.from(ix.data ?? new Uint8Array());
|
|
6596
6971
|
if (data.length < 16) return null;
|
|
6597
6972
|
const msgOffset = data.readUInt16LE(10);
|
|
6598
6973
|
const msgSize = data.readUInt16LE(12);
|
|
@@ -6604,14 +6979,11 @@ function extractDepositNonceFromEd25519Ix(ix) {
|
|
|
6604
6979
|
}
|
|
6605
6980
|
}
|
|
6606
6981
|
function deriveNullifierPDA(programId, poolPDA, nullifier) {
|
|
6607
|
-
return
|
|
6608
|
-
[Buffer.from("nullifier"), poolPDA.toBuffer(), Buffer.from(nullifier)],
|
|
6609
|
-
programId
|
|
6610
|
-
);
|
|
6982
|
+
return findProgramAddress(["nullifier", addressBytes(poolPDA), new Uint8Array(nullifier)], programId);
|
|
6611
6983
|
}
|
|
6612
|
-
function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkleTreePDA, nullifier0, nullifier1, proofBytes, publicInputsBytes, recipient, enableRiskCheck, encryptedNoteBytes, splAccounts, relayer, relayerFee, riskNonce, protocolMaxFee) {
|
|
6613
|
-
const [nullifierPDA0] = deriveNullifierPDA(programId, poolPDA, nullifier0);
|
|
6614
|
-
const [nullifierPDA1] = deriveNullifierPDA(programId, poolPDA, nullifier1);
|
|
6984
|
+
async function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkleTreePDA, nullifier0, nullifier1, proofBytes, publicInputsBytes, recipient, enableRiskCheck, encryptedNoteBytes, splAccounts, relayer, relayerFee, riskNonce, protocolMaxFee) {
|
|
6985
|
+
const [nullifierPDA0] = await deriveNullifierPDA(programId, poolPDA, nullifier0);
|
|
6986
|
+
const [nullifierPDA1] = await deriveNullifierPDA(programId, poolPDA, nullifier1);
|
|
6615
6987
|
const directPublicAmount = readBigInt64LE(publicInputsBytes.slice(32, 40), 0);
|
|
6616
6988
|
const isDepositData = directPublicAmount > BigInt(0);
|
|
6617
6989
|
const baseLen = 1 + proofBytes.length + publicInputsBytes.length;
|
|
@@ -6637,7 +7009,7 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
|
|
|
6637
7009
|
}
|
|
6638
7010
|
if (!isDepositData) {
|
|
6639
7011
|
data[offset++] = 3;
|
|
6640
|
-
data.set((relayer ??
|
|
7012
|
+
data.set(addressBytes(relayer ?? DEFAULT_ADDRESS), offset);
|
|
6641
7013
|
offset += 32;
|
|
6642
7014
|
writeBigUInt64LE(data, relayerFee ?? BigInt(0), offset);
|
|
6643
7015
|
offset += 8;
|
|
@@ -6655,99 +7027,89 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
|
|
|
6655
7027
|
}
|
|
6656
7028
|
const publicAmountForAccounts = readBigInt64LE(publicInputsBytes.slice(32, 40), 0);
|
|
6657
7029
|
const accounts = [
|
|
6658
|
-
|
|
7030
|
+
accountMeta(payer, { signer: true, writable: true }),
|
|
6659
7031
|
// 0. payer (signer, writable)
|
|
6660
|
-
|
|
7032
|
+
accountMeta(poolPDA, { writable: true }),
|
|
6661
7033
|
// 1. pool (writable)
|
|
6662
|
-
|
|
7034
|
+
accountMeta(treasuryPDA, { writable: true }),
|
|
6663
7035
|
// 2. treasury (writable)
|
|
6664
|
-
|
|
7036
|
+
accountMeta(merkleTreePDA, { writable: true }),
|
|
6665
7037
|
// 3. merkle_tree (writable)
|
|
6666
|
-
|
|
7038
|
+
accountMeta(nullifierPDA0, { writable: true }),
|
|
6667
7039
|
// 4. nullifier PDA 0 (writable)
|
|
6668
|
-
|
|
7040
|
+
accountMeta(nullifierPDA1, { writable: true }),
|
|
6669
7041
|
// 5. nullifier PDA 1 (writable)
|
|
6670
|
-
|
|
7042
|
+
accountMeta(import_system.SYSTEM_PROGRAM_ADDRESS)
|
|
6671
7043
|
// 6. system_program
|
|
6672
7044
|
];
|
|
6673
7045
|
if (splAccounts) {
|
|
6674
|
-
accounts.push(
|
|
6675
|
-
accounts.push(
|
|
6676
|
-
accounts.push(
|
|
7046
|
+
accounts.push(accountMeta(splAccounts.vaultAuthority));
|
|
7047
|
+
accounts.push(accountMeta(splAccounts.poolVaultAta, { writable: true }));
|
|
7048
|
+
accounts.push(accountMeta(splAccounts.tokenProgram));
|
|
6677
7049
|
if (splAccounts.payerAta) {
|
|
6678
7050
|
if (enableRiskCheck) {
|
|
6679
|
-
accounts.push(
|
|
7051
|
+
accounts.push(accountMeta(SYSVAR_INSTRUCTIONS_ADDRESS));
|
|
6680
7052
|
}
|
|
6681
|
-
accounts.push(
|
|
7053
|
+
accounts.push(accountMeta(splAccounts.payerAta, { writable: true }));
|
|
6682
7054
|
if (riskNonce) {
|
|
6683
|
-
accounts.push(
|
|
7055
|
+
accounts.push(accountMeta(riskNonce, { writable: true }));
|
|
6684
7056
|
}
|
|
6685
7057
|
} else if (enableRiskCheck && !recipient) {
|
|
6686
|
-
accounts.push(
|
|
7058
|
+
accounts.push(accountMeta(SYSVAR_INSTRUCTIONS_ADDRESS));
|
|
6687
7059
|
}
|
|
6688
7060
|
} else {
|
|
6689
7061
|
if (recipient) {
|
|
6690
|
-
accounts.push(
|
|
7062
|
+
accounts.push(accountMeta(recipient, { writable: true }));
|
|
6691
7063
|
if (enableRiskCheck) {
|
|
6692
|
-
accounts.push(
|
|
7064
|
+
accounts.push(accountMeta(SYSVAR_INSTRUCTIONS_ADDRESS));
|
|
6693
7065
|
}
|
|
6694
7066
|
} else if (enableRiskCheck) {
|
|
6695
7067
|
if (publicAmountForAccounts === BigInt(0)) {
|
|
6696
|
-
accounts.push(
|
|
6697
|
-
accounts.push(
|
|
7068
|
+
accounts.push(accountMeta(payer, { signer: true }));
|
|
7069
|
+
accounts.push(accountMeta(SYSVAR_INSTRUCTIONS_ADDRESS));
|
|
6698
7070
|
} else {
|
|
6699
|
-
accounts.push(
|
|
7071
|
+
accounts.push(accountMeta(SYSVAR_INSTRUCTIONS_ADDRESS));
|
|
6700
7072
|
if (riskNonce) {
|
|
6701
|
-
accounts.push(
|
|
7073
|
+
accounts.push(accountMeta(riskNonce, { writable: true }));
|
|
6702
7074
|
}
|
|
6703
7075
|
}
|
|
6704
7076
|
}
|
|
6705
7077
|
}
|
|
6706
|
-
return new
|
|
6707
|
-
programId,
|
|
6708
|
-
keys: accounts,
|
|
6709
|
-
data
|
|
6710
|
-
});
|
|
7078
|
+
return programInstruction(programId, accounts, new Uint8Array(data));
|
|
6711
7079
|
}
|
|
6712
|
-
var
|
|
7080
|
+
var V1_COMPUTE_CONFIG = {
|
|
7081
|
+
computeUnitLimit: 12e5,
|
|
7082
|
+
// 100,000 micro-lamports per unit over 1,200,000 units: the same priority fee as the v0 path.
|
|
7083
|
+
priorityFeeLamports: 120000n,
|
|
7084
|
+
loadedAccountsDataSizeLimit: 64 * 1024 * 1024
|
|
7085
|
+
};
|
|
6713
7086
|
function getCommonALTAddresses() {
|
|
6714
7087
|
return [
|
|
6715
|
-
|
|
6716
|
-
|
|
6717
|
-
|
|
6718
|
-
|
|
7088
|
+
import_system.SYSTEM_PROGRAM_ADDRESS,
|
|
7089
|
+
SYSVAR_SLOT_HASHES_ADDRESS,
|
|
7090
|
+
SYSVAR_INSTRUCTIONS_ADDRESS,
|
|
7091
|
+
import_compute_budget.COMPUTE_BUDGET_PROGRAM_ADDRESS
|
|
6719
7092
|
];
|
|
6720
7093
|
}
|
|
6721
7094
|
function dedupePubkeys(addresses) {
|
|
6722
|
-
|
|
6723
|
-
const deduped = [];
|
|
6724
|
-
for (const address of addresses) {
|
|
6725
|
-
const key = address.toBase58();
|
|
6726
|
-
if (seen.has(key)) continue;
|
|
6727
|
-
seen.add(key);
|
|
6728
|
-
deduped.push(address);
|
|
6729
|
-
}
|
|
6730
|
-
return deduped;
|
|
7095
|
+
return [...new Set(addresses)];
|
|
6731
7096
|
}
|
|
6732
7097
|
function collectLookupCandidatesFromInstructions(instructions, payer, existingAlts) {
|
|
6733
7098
|
const existing = /* @__PURE__ */ new Set();
|
|
6734
7099
|
for (const alt of existingAlts ?? []) {
|
|
6735
|
-
for (const
|
|
6736
|
-
existing.add(
|
|
7100
|
+
for (const address2 of alt.addresses) {
|
|
7101
|
+
existing.add(address2);
|
|
6737
7102
|
}
|
|
6738
7103
|
}
|
|
6739
7104
|
const collected = [];
|
|
6740
7105
|
for (const ix of instructions) {
|
|
6741
|
-
collected.push(ix.
|
|
6742
|
-
for (const
|
|
6743
|
-
if (
|
|
6744
|
-
collected.push(
|
|
7106
|
+
collected.push(ix.programAddress);
|
|
7107
|
+
for (const account of ix.accounts ?? []) {
|
|
7108
|
+
if ((0, import_kit8.isSignerRole)(account.role)) continue;
|
|
7109
|
+
collected.push(account.address);
|
|
6745
7110
|
}
|
|
6746
7111
|
}
|
|
6747
|
-
return dedupePubkeys(collected).filter((
|
|
6748
|
-
const key = address.toBase58();
|
|
6749
|
-
return key !== payer.toBase58() && !existing.has(key);
|
|
6750
|
-
});
|
|
7112
|
+
return dedupePubkeys(collected).filter((address2) => address2 !== payer && !existing.has(address2));
|
|
6751
7113
|
}
|
|
6752
7114
|
async function createEphemeralALT(connection, depositor, onProgress, additionalAddresses = [], externalFeePayer, allowSupplementalAlt = true) {
|
|
6753
7115
|
const MAX_ALT_ADDRESSES = 20;
|
|
@@ -6755,7 +7117,7 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
|
|
|
6755
7117
|
const altAddresses = dedupePubkeys([
|
|
6756
7118
|
...getCommonALTAddresses(),
|
|
6757
7119
|
...additionalAddresses
|
|
6758
|
-
]).filter((
|
|
7120
|
+
]).filter((address2) => address2 !== depositor.address);
|
|
6759
7121
|
const addressesForCreate = altAddresses.slice(0, MAX_ALT_ADDRESSES);
|
|
6760
7122
|
if (altAddresses.length > MAX_ALT_ADDRESSES) {
|
|
6761
7123
|
onProgress?.(
|
|
@@ -6764,17 +7126,21 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
|
|
|
6764
7126
|
}
|
|
6765
7127
|
for (let altAttempt = 0; altAttempt < MAX_ALT_CREATE_RETRIES; altAttempt++) {
|
|
6766
7128
|
try {
|
|
6767
|
-
const slot = await connection
|
|
6768
|
-
const altPayerPubkey = externalFeePayer ? await externalFeePayer.getPayerPubkey() : depositor.
|
|
6769
|
-
const
|
|
6770
|
-
|
|
6771
|
-
|
|
7129
|
+
const slot = await fetchSlot(connection, "finalized");
|
|
7130
|
+
const altPayerPubkey = externalFeePayer ? await externalFeePayer.getPayerPubkey() : depositor.address;
|
|
7131
|
+
const altPayer = externalFeePayer ? (0, import_kit8.createNoopSigner)(altPayerPubkey) : depositor;
|
|
7132
|
+
const altPda = await (0, import_address_lookup_table2.findAddressLookupTablePda)({ authority: depositor.address, recentSlot: slot });
|
|
7133
|
+
const [altAddress] = altPda;
|
|
7134
|
+
const createIx = (0, import_address_lookup_table2.getCreateLookupTableInstruction)({
|
|
7135
|
+
address: altPda,
|
|
7136
|
+
authority: depositor.address,
|
|
7137
|
+
payer: altPayer,
|
|
6772
7138
|
recentSlot: slot
|
|
6773
7139
|
});
|
|
6774
|
-
const extendIx =
|
|
6775
|
-
|
|
6776
|
-
authority: depositor
|
|
6777
|
-
|
|
7140
|
+
const extendIx = (0, import_address_lookup_table2.getExtendLookupTableInstruction)({
|
|
7141
|
+
address: altAddress,
|
|
7142
|
+
authority: depositor,
|
|
7143
|
+
payer: altPayer,
|
|
6778
7144
|
addresses: addressesForCreate
|
|
6779
7145
|
});
|
|
6780
7146
|
if (externalFeePayer) {
|
|
@@ -6790,33 +7156,33 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
|
|
|
6790
7156
|
allowSupplementalAlt
|
|
6791
7157
|
);
|
|
6792
7158
|
} else {
|
|
6793
|
-
const
|
|
6794
|
-
const
|
|
6795
|
-
|
|
6796
|
-
|
|
6797
|
-
|
|
6798
|
-
|
|
6799
|
-
}
|
|
6800
|
-
|
|
6801
|
-
|
|
6802
|
-
|
|
6803
|
-
|
|
6804
|
-
|
|
6805
|
-
|
|
6806
|
-
}
|
|
7159
|
+
const lifetime = await fetchLatestBlockhash(connection);
|
|
7160
|
+
const message = buildTransactionMessage({
|
|
7161
|
+
version: "legacy",
|
|
7162
|
+
feePayer: depositor,
|
|
7163
|
+
lifetime,
|
|
7164
|
+
instructions: [createIx, extendIx]
|
|
7165
|
+
});
|
|
7166
|
+
onProgress?.((0, import_kit8.isKeyPairSigner)(depositor) ? "Creating lookup table..." : "Waiting for wallet signature (lookup table)...");
|
|
7167
|
+
const signed = await signTransaction(message);
|
|
7168
|
+
const sig = await sendRawTransaction(connection, transactionBytes(signed));
|
|
7169
|
+
await confirmSignature(connection, sig, {
|
|
7170
|
+
commitment: "confirmed",
|
|
7171
|
+
lastValidBlockHeight: lifetime.lastValidBlockHeight
|
|
7172
|
+
});
|
|
6807
7173
|
}
|
|
6808
7174
|
for (let i = 0; i < 30; i++) {
|
|
6809
7175
|
await new Promise((r) => setTimeout(r, 500));
|
|
6810
|
-
const result = await
|
|
6811
|
-
if (result.
|
|
6812
|
-
onProgress?.(`ALT created and active: ${altAddress
|
|
6813
|
-
return [result.
|
|
7176
|
+
const result = await (0, import_address_lookup_table2.fetchMaybeAddressLookupTable)(connection, altAddress);
|
|
7177
|
+
if (result.exists && isLookupTableActive(result.data.deactivationSlot)) {
|
|
7178
|
+
onProgress?.(`ALT created and active: ${altAddress}`);
|
|
7179
|
+
return [{ address: altAddress, addresses: result.data.addresses }];
|
|
6814
7180
|
}
|
|
6815
7181
|
}
|
|
6816
|
-
const finalResult = await
|
|
6817
|
-
if (finalResult.
|
|
7182
|
+
const finalResult = await (0, import_address_lookup_table2.fetchMaybeAddressLookupTable)(connection, altAddress);
|
|
7183
|
+
if (finalResult.exists) {
|
|
6818
7184
|
onProgress?.("ALT created (activation pending)");
|
|
6819
|
-
return [finalResult.
|
|
7185
|
+
return [{ address: altAddress, addresses: finalResult.data.addresses }];
|
|
6820
7186
|
}
|
|
6821
7187
|
throw new Error("Failed to create ALT: not active after 15 seconds");
|
|
6822
7188
|
} catch (err) {
|
|
@@ -6831,17 +7197,25 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
|
|
|
6831
7197
|
}
|
|
6832
7198
|
throw new Error(`Failed to create ALT after ${MAX_ALT_CREATE_RETRIES} retries`);
|
|
6833
7199
|
}
|
|
7200
|
+
function isLookupTableActive(deactivationSlot) {
|
|
7201
|
+
return deactivationSlot === U64_MAX;
|
|
7202
|
+
}
|
|
6834
7203
|
var SOLANA_PACKET_DATA_SIZE = 1232;
|
|
6835
|
-
|
|
7204
|
+
var SOLANA_V1_PACKET_DATA_SIZE = 4096;
|
|
7205
|
+
function packetLimitFor(version) {
|
|
7206
|
+
return version === 1 ? SOLANA_V1_PACKET_DATA_SIZE : SOLANA_PACKET_DATA_SIZE;
|
|
7207
|
+
}
|
|
7208
|
+
function estimateV0TransactionSize(payerKey, recentBlockhash, instructions, addressLookupTableAccounts, version = 0, computeConfig) {
|
|
6836
7209
|
try {
|
|
6837
|
-
const
|
|
6838
|
-
|
|
6839
|
-
|
|
6840
|
-
|
|
6841
|
-
|
|
6842
|
-
|
|
6843
|
-
|
|
6844
|
-
|
|
7210
|
+
const message = buildTransactionMessage({
|
|
7211
|
+
version,
|
|
7212
|
+
computeConfig,
|
|
7213
|
+
feePayer: payerKey,
|
|
7214
|
+
lifetime: { blockhash: recentBlockhash, lastValidBlockHeight: 0n },
|
|
7215
|
+
instructions,
|
|
7216
|
+
lookupTables: addressLookupTableAccounts
|
|
7217
|
+
});
|
|
7218
|
+
const raw = transactionWireSize(message);
|
|
6845
7219
|
const encodedBase64 = Math.ceil(raw / 3) * 4;
|
|
6846
7220
|
return { raw, encodedBase64 };
|
|
6847
7221
|
} catch (err) {
|
|
@@ -6849,17 +7223,17 @@ function estimateV0TransactionSize(payerKey, recentBlockhash, instructions, addr
|
|
|
6849
7223
|
return { raw: -1, encodedBase64: -1, error: msg };
|
|
6850
7224
|
}
|
|
6851
7225
|
}
|
|
6852
|
-
function exceedsPacketLimit(size) {
|
|
6853
|
-
return size.error !== void 0 || size.raw >
|
|
7226
|
+
function exceedsPacketLimit(size, limit = SOLANA_PACKET_DATA_SIZE) {
|
|
7227
|
+
return size.error !== void 0 || size.raw > limit;
|
|
6854
7228
|
}
|
|
6855
|
-
function describePacketSize(size) {
|
|
6856
|
-
return size.error ? `serialize overran the ${
|
|
7229
|
+
function describePacketSize(size, limit = SOLANA_PACKET_DATA_SIZE) {
|
|
7230
|
+
return size.error ? `serialize overran the ${limit}-byte buffer` : `${size.raw} > ${limit} bytes`;
|
|
6857
7231
|
}
|
|
6858
7232
|
async function planDirectV0Submission(args) {
|
|
6859
|
-
const { estimate, full, compact, minimal, createSupplementalAlt, onProgress } = args;
|
|
7233
|
+
const { estimate, full, compact, minimal, createSupplementalAlt, onProgress, packetLimit = SOLANA_PACKET_DATA_SIZE } = args;
|
|
6860
7234
|
let minimalSize = estimate(minimal);
|
|
6861
7235
|
let supplementalAltRequested = false;
|
|
6862
|
-
if (exceedsPacketLimit(minimalSize)) {
|
|
7236
|
+
if (exceedsPacketLimit(minimalSize, packetLimit)) {
|
|
6863
7237
|
supplementalAltRequested = true;
|
|
6864
7238
|
onProgress?.(
|
|
6865
7239
|
"Transaction still exceeds packet limit with current ALT set; creating supplemental ALT..."
|
|
@@ -6872,50 +7246,59 @@ async function planDirectV0Submission(args) {
|
|
|
6872
7246
|
onProgress?.(`Failed to create supplemental ALT: ${altMsg}`);
|
|
6873
7247
|
}
|
|
6874
7248
|
}
|
|
6875
|
-
if (!minimalSize.error && minimalSize.raw >
|
|
7249
|
+
if (!minimalSize.error && minimalSize.raw > packetLimit) {
|
|
6876
7250
|
throw new Error(
|
|
6877
|
-
`Transaction exceeds Solana packet limit even in minimal mode: raw=${minimalSize.raw} (>${
|
|
7251
|
+
`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.`
|
|
6878
7252
|
);
|
|
6879
7253
|
}
|
|
6880
7254
|
const fullSize = estimate(full);
|
|
6881
|
-
if (!exceedsPacketLimit(fullSize)) {
|
|
7255
|
+
if (!exceedsPacketLimit(fullSize, packetLimit)) {
|
|
6882
7256
|
return { tier: "full", instructions: full, supplementalAltRequested, fullSize, minimalSize };
|
|
6883
7257
|
}
|
|
6884
7258
|
const compactSize = estimate(compact);
|
|
6885
|
-
if (!exceedsPacketLimit(compactSize)) {
|
|
7259
|
+
if (!exceedsPacketLimit(compactSize, packetLimit)) {
|
|
6886
7260
|
onProgress?.(
|
|
6887
|
-
`Transaction would exceed the packet limit with a compute-unit price (${describePacketSize(fullSize)}); sending without it.`
|
|
7261
|
+
`Transaction would exceed the packet limit with a compute-unit price (${describePacketSize(fullSize, packetLimit)}); sending without it.`
|
|
6888
7262
|
);
|
|
6889
7263
|
return { tier: "compact", instructions: compact, supplementalAltRequested, fullSize, minimalSize };
|
|
6890
7264
|
}
|
|
6891
7265
|
onProgress?.(
|
|
6892
|
-
`Transaction would exceed the packet limit with compute-budget instructions (${describePacketSize(fullSize)}); sending the minimal set.`
|
|
7266
|
+
`Transaction would exceed the packet limit with compute-budget instructions (${describePacketSize(fullSize, packetLimit)}); sending the minimal set.`
|
|
6893
7267
|
);
|
|
6894
7268
|
return { tier: "minimal", instructions: minimal, supplementalAltRequested, fullSize, minimalSize };
|
|
6895
7269
|
}
|
|
6896
|
-
async function submitViaExternalFeePayer(connection, depositor, externalFeePayer, externalFeePayerPubkey, instructions, addressLookupTableAccounts, onProgress, allowSupplementalAlt = true, relayAltAttempt) {
|
|
6897
|
-
if (
|
|
7270
|
+
async function submitViaExternalFeePayer(connection, depositor, externalFeePayer, externalFeePayerPubkey, instructions, addressLookupTableAccounts, onProgress, allowSupplementalAlt = true, relayAltAttempt, transactionVersion = 0) {
|
|
7271
|
+
if ((0, import_kit8.isKeyPairSigner)(depositor)) {
|
|
6898
7272
|
throw new Error(
|
|
6899
7273
|
"externalFeePayer requires wallet-style signTransaction \u2014 keypair-only depositors aren't supported for external fee payment."
|
|
6900
7274
|
);
|
|
6901
7275
|
}
|
|
6902
7276
|
onProgress?.("Requesting fee quote from external fee payer...");
|
|
6903
|
-
const
|
|
7277
|
+
const quoteLifetime = await fetchLatestBlockhash(connection);
|
|
7278
|
+
const packetLimit = packetLimitFor(transactionVersion);
|
|
7279
|
+
if (transactionVersion === 1) {
|
|
7280
|
+
addressLookupTableAccounts = [];
|
|
7281
|
+
allowSupplementalAlt = false;
|
|
7282
|
+
}
|
|
7283
|
+
const compile = (instrs, alts, lifetime2) => buildTransactionMessage({
|
|
7284
|
+
version: transactionVersion,
|
|
7285
|
+
computeConfig: transactionVersion === 1 ? V1_COMPUTE_CONFIG : void 0,
|
|
7286
|
+
feePayer: externalFeePayerPubkey,
|
|
7287
|
+
lifetime: lifetime2,
|
|
7288
|
+
instructions: instrs,
|
|
7289
|
+
lookupTables: alts ?? [],
|
|
7290
|
+
signers: [depositor]
|
|
7291
|
+
});
|
|
6904
7292
|
const measure = (instrs, alts) => {
|
|
6905
7293
|
try {
|
|
6906
|
-
|
|
6907
|
-
payerKey: externalFeePayerPubkey,
|
|
6908
|
-
recentBlockhash: quoteBlockhash,
|
|
6909
|
-
instructions: instrs
|
|
6910
|
-
}).compileToV0Message(alts ?? []);
|
|
6911
|
-
return { size: 1 + 2 * 64 + message.serialize().length };
|
|
7294
|
+
return { size: transactionWireSize(compile(instrs, alts, quoteLifetime)) };
|
|
6912
7295
|
} catch (err) {
|
|
6913
7296
|
return { size: Infinity, error: err instanceof Error ? err.message : String(err) };
|
|
6914
7297
|
}
|
|
6915
7298
|
};
|
|
6916
7299
|
const failIfOverLimit = (size, error) => {
|
|
6917
|
-
if (size <=
|
|
6918
|
-
const measured = Number.isFinite(size) ? `raw=${size} (>${
|
|
7300
|
+
if (size <= packetLimit) return;
|
|
7301
|
+
const measured = Number.isFinite(size) ? `raw=${size} (>${packetLimit})` : `message could not be serialized (${error})`;
|
|
6919
7302
|
throw new Error(
|
|
6920
7303
|
`Transaction exceeds Solana packet limit even after ALT compression: ${measured}. Try providing a pre-built ALT via options.addressLookupTableAccounts or reduce instruction payload size.`
|
|
6921
7304
|
);
|
|
@@ -6925,8 +7308,14 @@ async function submitViaExternalFeePayer(connection, depositor, externalFeePayer
|
|
|
6925
7308
|
if (relayAltAttempt) {
|
|
6926
7309
|
try {
|
|
6927
7310
|
onProgress?.("Requesting supplemental lookup table from relay...");
|
|
7311
|
+
const before = addressLookupTableAccounts;
|
|
6928
7312
|
addressLookupTableAccounts = [await relayAltAttempt()];
|
|
6929
|
-
|
|
7313
|
+
const withRelay = measure(instrs, addressLookupTableAccounts);
|
|
7314
|
+
if (withRelay.size <= packetLimit) return;
|
|
7315
|
+
onProgress?.(
|
|
7316
|
+
`Relay supplemental table leaves the transaction at ${withRelay.size} bytes; falling back to a depositor-signed table.`
|
|
7317
|
+
);
|
|
7318
|
+
addressLookupTableAccounts = before;
|
|
6930
7319
|
} catch (err) {
|
|
6931
7320
|
const msg = err instanceof Error ? err.message : String(err);
|
|
6932
7321
|
onProgress?.(
|
|
@@ -6937,7 +7326,7 @@ async function submitViaExternalFeePayer(connection, depositor, externalFeePayer
|
|
|
6937
7326
|
try {
|
|
6938
7327
|
const supplementalAddresses = dedupePubkeys([
|
|
6939
7328
|
...collectLookupCandidatesFromInstructions(instrs, externalFeePayerPubkey, void 0),
|
|
6940
|
-
...extraAddresses.filter((a) =>
|
|
7329
|
+
...extraAddresses.filter((a) => a !== externalFeePayerPubkey)
|
|
6941
7330
|
]);
|
|
6942
7331
|
const supplementalAlt = await createEphemeralALT(
|
|
6943
7332
|
connection,
|
|
@@ -6955,53 +7344,40 @@ async function submitViaExternalFeePayer(connection, depositor, externalFeePayer
|
|
|
6955
7344
|
};
|
|
6956
7345
|
const PAYMENT_IX_COMPRESS_RESERVE_BYTES = 128;
|
|
6957
7346
|
let pre = measure(instructions, addressLookupTableAccounts);
|
|
6958
|
-
if (pre.size + PAYMENT_IX_COMPRESS_RESERVE_BYTES >
|
|
7347
|
+
if (pre.size + PAYMENT_IX_COMPRESS_RESERVE_BYTES > packetLimit && allowSupplementalAlt) {
|
|
6959
7348
|
const paymentHints = externalFeePayer.getPaymentAccountHints ? await externalFeePayer.getPaymentAccountHints().catch(() => []) : [];
|
|
6960
7349
|
await compressWithSupplementalAlt(instructions, paymentHints);
|
|
6961
7350
|
pre = measure(instructions, addressLookupTableAccounts);
|
|
6962
7351
|
}
|
|
6963
7352
|
failIfOverLimit(pre.size, pre.error);
|
|
6964
|
-
const
|
|
6965
|
-
payerKey: externalFeePayerPubkey,
|
|
6966
|
-
recentBlockhash: quoteBlockhash,
|
|
6967
|
-
instructions
|
|
6968
|
-
}).compileToV0Message(addressLookupTableAccounts ?? []);
|
|
6969
|
-
const quoteTxBase64 = Buffer.from(new import_web311.VersionedTransaction(quoteMessage).serialize()).toString("base64");
|
|
7353
|
+
const quoteTxBase64 = transactionBase64(compileUnsigned(compile(instructions, addressLookupTableAccounts, quoteLifetime)));
|
|
6970
7354
|
const paymentInstruction = await externalFeePayer.getPaymentInstruction(quoteTxBase64);
|
|
6971
7355
|
const finalInstructions = [...instructions, paymentInstruction];
|
|
6972
7356
|
let post = measure(finalInstructions, addressLookupTableAccounts);
|
|
6973
|
-
if (post.size >
|
|
7357
|
+
if (post.size > packetLimit && allowSupplementalAlt) {
|
|
6974
7358
|
await compressWithSupplementalAlt(finalInstructions);
|
|
6975
7359
|
post = measure(finalInstructions, addressLookupTableAccounts);
|
|
6976
7360
|
}
|
|
6977
7361
|
failIfOverLimit(post.size, post.error);
|
|
6978
7362
|
onProgress?.("Building final transaction...");
|
|
6979
|
-
const
|
|
6980
|
-
const finalMessage =
|
|
6981
|
-
payerKey: externalFeePayerPubkey,
|
|
6982
|
-
recentBlockhash: blockhash,
|
|
6983
|
-
instructions: finalInstructions
|
|
6984
|
-
}).compileToV0Message(addressLookupTableAccounts ?? []);
|
|
6985
|
-
const finalTx = new import_web311.VersionedTransaction(finalMessage);
|
|
7363
|
+
const lifetime = await fetchLatestBlockhash(connection);
|
|
7364
|
+
const finalMessage = compile(finalInstructions, addressLookupTableAccounts, lifetime);
|
|
6986
7365
|
onProgress?.("Waiting for wallet signature...");
|
|
6987
|
-
const partiallySignedTx = await
|
|
6988
|
-
const partiallySignedBase64 =
|
|
7366
|
+
const partiallySignedTx = await partiallySignTransaction(finalMessage);
|
|
7367
|
+
const partiallySignedBase64 = transactionBase64(partiallySignedTx);
|
|
6989
7368
|
onProgress?.("Requesting fee-payer co-signature...");
|
|
6990
7369
|
const fullySignedBase64 = await externalFeePayer.cosign(partiallySignedBase64);
|
|
6991
|
-
const fullySignedBytes = Buffer.from(fullySignedBase64, "base64");
|
|
7370
|
+
const fullySignedBytes = new Uint8Array(Buffer.from(fullySignedBase64, "base64"));
|
|
6992
7371
|
onProgress?.("Sending transaction...");
|
|
6993
|
-
const signature = await
|
|
7372
|
+
const signature = await sendRawTransaction(connection, fullySignedBytes, { skipPreflight: false });
|
|
6994
7373
|
onProgress?.("Confirming transaction...");
|
|
6995
|
-
|
|
6996
|
-
|
|
6997
|
-
|
|
6998
|
-
);
|
|
6999
|
-
if (confirmation.value.err) {
|
|
7000
|
-
throw new Error(`Transaction failed during confirmation: ${JSON.stringify(confirmation.value.err)}`);
|
|
7001
|
-
}
|
|
7374
|
+
await confirmSignature(connection, signature, {
|
|
7375
|
+
commitment: "confirmed",
|
|
7376
|
+
lastValidBlockHeight: lifetime.lastValidBlockHeight
|
|
7377
|
+
});
|
|
7002
7378
|
return signature;
|
|
7003
7379
|
}
|
|
7004
|
-
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) {
|
|
7380
|
+
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) {
|
|
7005
7381
|
onProgress?.("Building transaction...");
|
|
7006
7382
|
addressLookupTableAccounts = await resolveAddressLookupTableAccounts(
|
|
7007
7383
|
connection,
|
|
@@ -7010,12 +7386,12 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7010
7386
|
addressLookupTableAccounts,
|
|
7011
7387
|
onProgress
|
|
7012
7388
|
);
|
|
7013
|
-
const pdas = getShieldPoolPDAs(programId, mint);
|
|
7389
|
+
const pdas = await getShieldPoolPDAs(programId, mint);
|
|
7014
7390
|
const treeState = await readMerkleTreeState(connection, pdas.merkleTree, true);
|
|
7015
7391
|
const nextIndex = treeState.nextIndex;
|
|
7016
7392
|
let riskQuoteIx = null;
|
|
7017
7393
|
const isDeposit = recipient === void 0;
|
|
7018
|
-
const isSplPool =
|
|
7394
|
+
const isSplPool = mint !== NATIVE_SOL_MINT;
|
|
7019
7395
|
const riskCheckEnabled = true;
|
|
7020
7396
|
if (isDeposit && riskCheckEnabled && !getRiskQuoteInstruction && !riskQuoteUrl && rangeApiKey) {
|
|
7021
7397
|
throw new Error(
|
|
@@ -7033,35 +7409,33 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7033
7409
|
const preTransactInstructions = [];
|
|
7034
7410
|
let splAccounts;
|
|
7035
7411
|
if (isSplPool) {
|
|
7036
|
-
const poolVaultAta = (0,
|
|
7412
|
+
const [poolVaultAta] = await (0, import_token.findAssociatedTokenPda)({
|
|
7037
7413
|
mint,
|
|
7038
|
-
pdas.vaultAuthority,
|
|
7039
|
-
|
|
7040
|
-
|
|
7041
|
-
);
|
|
7414
|
+
owner: pdas.vaultAuthority,
|
|
7415
|
+
tokenProgram: import_token.TOKEN_PROGRAM_ADDRESS
|
|
7416
|
+
});
|
|
7042
7417
|
splAccounts = {
|
|
7043
7418
|
vaultAuthority: pdas.vaultAuthority,
|
|
7044
7419
|
poolVaultAta,
|
|
7045
|
-
tokenProgram:
|
|
7420
|
+
tokenProgram: import_token.TOKEN_PROGRAM_ADDRESS
|
|
7046
7421
|
};
|
|
7047
7422
|
if (publicAmount > BigInt(0)) {
|
|
7048
|
-
splAccounts.payerAta = (0,
|
|
7423
|
+
[splAccounts.payerAta] = await (0, import_token.findAssociatedTokenPda)({
|
|
7049
7424
|
mint,
|
|
7050
|
-
depositor.
|
|
7051
|
-
|
|
7052
|
-
|
|
7053
|
-
);
|
|
7054
|
-
const poolVaultAtaInfo = await connection.getAccountInfo(poolVaultAta);
|
|
7425
|
+
owner: depositor.address,
|
|
7426
|
+
tokenProgram: import_token.TOKEN_PROGRAM_ADDRESS
|
|
7427
|
+
});
|
|
7428
|
+
const poolVaultAtaInfo = await fetchAccountBytes(connection, poolVaultAta);
|
|
7055
7429
|
if (!poolVaultAtaInfo) {
|
|
7056
7430
|
onProgress?.("Creating pool vault ATA for SPL pool...");
|
|
7057
7431
|
preTransactInstructions.push(
|
|
7058
|
-
(0,
|
|
7059
|
-
depositor
|
|
7060
|
-
poolVaultAta,
|
|
7061
|
-
pdas.vaultAuthority,
|
|
7432
|
+
(0, import_token.getCreateAssociatedTokenInstruction)({
|
|
7433
|
+
payer: depositor,
|
|
7434
|
+
ata: poolVaultAta,
|
|
7435
|
+
owner: pdas.vaultAuthority,
|
|
7062
7436
|
mint,
|
|
7063
|
-
|
|
7064
|
-
)
|
|
7437
|
+
tokenProgram: import_token.TOKEN_PROGRAM_ADDRESS
|
|
7438
|
+
})
|
|
7065
7439
|
);
|
|
7066
7440
|
}
|
|
7067
7441
|
} else if (publicAmount < BigInt(0)) {
|
|
@@ -7076,16 +7450,16 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7076
7450
|
let riskNoncePda;
|
|
7077
7451
|
let depositNonce = null;
|
|
7078
7452
|
let relaySupplementalAltPromise;
|
|
7079
|
-
const requestRelaySupplementalAlt = () => {
|
|
7080
|
-
const [nullifierPda0] = deriveNullifierPDA(programId, pdas.pool, nullifiers[0]);
|
|
7081
|
-
const [nullifierPda1] = deriveNullifierPDA(programId, pdas.pool, nullifiers[1]);
|
|
7082
|
-
const [riskNoncePdaForAlt] = deriveRiskNoncePDA(programId, depositNonce);
|
|
7083
|
-
const depositorAta = (0,
|
|
7453
|
+
const requestRelaySupplementalAlt = async () => {
|
|
7454
|
+
const [nullifierPda0] = await deriveNullifierPDA(programId, pdas.pool, nullifiers[0]);
|
|
7455
|
+
const [nullifierPda1] = await deriveNullifierPDA(programId, pdas.pool, nullifiers[1]);
|
|
7456
|
+
const [riskNoncePdaForAlt] = await deriveRiskNoncePDA(programId, depositNonce);
|
|
7457
|
+
const [depositorAta] = await (0, import_token.findAssociatedTokenPda)({ mint, owner: depositor.address, tokenProgram: import_token.TOKEN_PROGRAM_ADDRESS });
|
|
7084
7458
|
return fetchSupplementalAltFromRelay(relayUrl, {
|
|
7085
7459
|
mint,
|
|
7086
7460
|
nullifiers,
|
|
7087
7461
|
bind0: depositNonce,
|
|
7088
|
-
depositor: depositor.
|
|
7462
|
+
depositor: depositor.address
|
|
7089
7463
|
}).then(
|
|
7090
7464
|
(table) => resolveRelaySupplementalAlt(connection, table, [
|
|
7091
7465
|
nullifierPda0,
|
|
@@ -7121,11 +7495,11 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7121
7495
|
if ((isDeposit || isSend) && riskCheckEnabled && !riskQuoteIx) {
|
|
7122
7496
|
if (getRiskQuoteInstruction) {
|
|
7123
7497
|
onProgress?.("Fetching risk quote (custom)...");
|
|
7124
|
-
riskQuoteIx = await getRiskQuoteInstruction(depositor.
|
|
7498
|
+
riskQuoteIx = await getRiskQuoteInstruction(depositor.address);
|
|
7125
7499
|
} else if (riskQuoteUrl) {
|
|
7126
7500
|
onProgress?.("Fetching risk quote from backend...");
|
|
7127
7501
|
const isDepositQuote = depositAmount > BigInt(0);
|
|
7128
|
-
const quote = await fetchRiskQuote(riskQuoteUrl, depositor.
|
|
7502
|
+
const quote = await fetchRiskQuote(riskQuoteUrl, depositor.address, {
|
|
7129
7503
|
poolMint: mint,
|
|
7130
7504
|
amount: depositAmount,
|
|
7131
7505
|
token: mint,
|
|
@@ -7147,7 +7521,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7147
7521
|
depositNonce = extractDepositNonceFromEd25519Ix(riskQuoteIx);
|
|
7148
7522
|
}
|
|
7149
7523
|
if (depositNonce) {
|
|
7150
|
-
[riskNoncePda] = deriveRiskNoncePDA(programId, depositNonce);
|
|
7524
|
+
[riskNoncePda] = await deriveRiskNoncePDA(programId, depositNonce);
|
|
7151
7525
|
if (relaySupplementalAlt && relayUrl && isSplPool) {
|
|
7152
7526
|
getRelaySupplementalAlt().catch(() => {
|
|
7153
7527
|
});
|
|
@@ -7159,7 +7533,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7159
7533
|
}
|
|
7160
7534
|
if (!isDeposit && riskCheckEnabled && recipient && riskQuoteUrl && !riskQuoteIx) {
|
|
7161
7535
|
onProgress?.("Fetching risk quote for recipient...");
|
|
7162
|
-
riskQuoteIx = await fetchRiskQuoteInstruction(riskQuoteUrl, depositor.
|
|
7536
|
+
riskQuoteIx = await fetchRiskQuoteInstruction(riskQuoteUrl, depositor.address, {
|
|
7163
7537
|
poolMint: mint,
|
|
7164
7538
|
recipient,
|
|
7165
7539
|
amount: withdrawAmount,
|
|
@@ -7169,9 +7543,9 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7169
7543
|
nullifier1: nullifier1Hex
|
|
7170
7544
|
});
|
|
7171
7545
|
}
|
|
7172
|
-
const transactIx = buildTransactInstruction(
|
|
7546
|
+
const transactIx = await buildTransactInstruction(
|
|
7173
7547
|
programId,
|
|
7174
|
-
depositor.
|
|
7548
|
+
depositor.address,
|
|
7175
7549
|
pdas.pool,
|
|
7176
7550
|
pdas.treasury,
|
|
7177
7551
|
pdas.merkleTree,
|
|
@@ -7203,14 +7577,15 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7203
7577
|
baseInstructions.splice(riskQuoteIx ? 1 : 0, 0, ...topUpInstructions);
|
|
7204
7578
|
}
|
|
7205
7579
|
}
|
|
7206
|
-
const cuLimitIx =
|
|
7207
|
-
const cuPriceIx =
|
|
7580
|
+
const cuLimitIx = (0, import_compute_budget.getSetComputeUnitLimitInstruction)({ units: 12e5 });
|
|
7581
|
+
const cuPriceIx = (0, import_compute_budget.getSetComputeUnitPriceInstruction)({ microLamports: 1e5 });
|
|
7582
|
+
const computeConfig = transactionVersion === 1 ? V1_COMPUTE_CONFIG : void 0;
|
|
7208
7583
|
const fullInstructions = [...baseInstructions, cuLimitIx, cuPriceIx, transactIx];
|
|
7209
7584
|
const compactInstructions = [...baseInstructions, cuLimitIx, transactIx];
|
|
7210
7585
|
const minimalInstructions = [...baseInstructions, cuLimitIx, transactIx];
|
|
7211
7586
|
let instructions = fullInstructions;
|
|
7212
|
-
let { blockhash, lastValidBlockHeight } = await connection
|
|
7213
|
-
const useV0 = addressLookupTableAccounts && addressLookupTableAccounts.length > 0;
|
|
7587
|
+
let { blockhash, lastValidBlockHeight } = await fetchLatestBlockhash(connection);
|
|
7588
|
+
const useV0 = transactionVersion === 1 || addressLookupTableAccounts && addressLookupTableAccounts.length > 0;
|
|
7214
7589
|
let signature = "";
|
|
7215
7590
|
if (externalFeePayer) {
|
|
7216
7591
|
signature = await submitViaExternalFeePayer(
|
|
@@ -7227,11 +7602,16 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7227
7602
|
// only for submitViaExternalFeePayer's OWN, separate supplemental round — triggered by the
|
|
7228
7603
|
// external payer's extra signature and payment-instruction accounts pushing an already-ALT'd
|
|
7229
7604
|
// tx back over the limit — so that round also tries the relay before an ephemeral fallback.
|
|
7230
|
-
relayAltEligible() ? getRelaySupplementalAlt : void 0
|
|
7605
|
+
relayAltEligible() ? getRelaySupplementalAlt : void 0,
|
|
7606
|
+
transactionVersion
|
|
7231
7607
|
);
|
|
7232
7608
|
} else if (useV0) {
|
|
7609
|
+
if (transactionVersion === 1) {
|
|
7610
|
+
addressLookupTableAccounts = [];
|
|
7611
|
+
}
|
|
7233
7612
|
const plan = await planDirectV0Submission({
|
|
7234
|
-
|
|
7613
|
+
packetLimit: packetLimitFor(transactionVersion),
|
|
7614
|
+
estimate: (ixs) => estimateV0TransactionSize(depositor.address, blockhash, ixs, addressLookupTableAccounts, transactionVersion, computeConfig),
|
|
7235
7615
|
full: fullInstructions,
|
|
7236
7616
|
compact: compactInstructions,
|
|
7237
7617
|
minimal: minimalInstructions,
|
|
@@ -7241,10 +7621,10 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7241
7621
|
onProgress?.("Requesting supplemental lookup table from relay...");
|
|
7242
7622
|
const relayAlt = await getRelaySupplementalAlt();
|
|
7243
7623
|
addressLookupTableAccounts = [
|
|
7244
|
-
...(addressLookupTableAccounts ?? []).filter((t) =>
|
|
7624
|
+
...(addressLookupTableAccounts ?? []).filter((t) => t.address !== relayAlt.address),
|
|
7245
7625
|
relayAlt
|
|
7246
7626
|
];
|
|
7247
|
-
({ blockhash, lastValidBlockHeight } = await connection
|
|
7627
|
+
({ blockhash, lastValidBlockHeight } = await fetchLatestBlockhash(connection));
|
|
7248
7628
|
return;
|
|
7249
7629
|
} catch (err) {
|
|
7250
7630
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -7255,7 +7635,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7255
7635
|
}
|
|
7256
7636
|
const supplementalAddresses = collectLookupCandidatesFromInstructions(
|
|
7257
7637
|
minimalInstructions,
|
|
7258
|
-
depositor.
|
|
7638
|
+
depositor.address,
|
|
7259
7639
|
addressLookupTableAccounts
|
|
7260
7640
|
);
|
|
7261
7641
|
const supplementalAlt = await createEphemeralALT(
|
|
@@ -7268,7 +7648,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7268
7648
|
...addressLookupTableAccounts ?? [],
|
|
7269
7649
|
...supplementalAlt
|
|
7270
7650
|
];
|
|
7271
|
-
({ blockhash, lastValidBlockHeight } = await connection
|
|
7651
|
+
({ blockhash, lastValidBlockHeight } = await fetchLatestBlockhash(connection));
|
|
7272
7652
|
},
|
|
7273
7653
|
onProgress
|
|
7274
7654
|
});
|
|
@@ -7279,9 +7659,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7279
7659
|
if (!sig) return false;
|
|
7280
7660
|
for (let i = 0; i < 6; i++) {
|
|
7281
7661
|
try {
|
|
7282
|
-
const
|
|
7283
|
-
searchTransactionHistory: true
|
|
7284
|
-
});
|
|
7662
|
+
const [value] = await fetchSignatureStatuses(connection, [sig], true);
|
|
7285
7663
|
if (value) {
|
|
7286
7664
|
if (value.err) return false;
|
|
7287
7665
|
if (value.confirmationStatus === "confirmed" || value.confirmationStatus === "finalized") {
|
|
@@ -7309,59 +7687,37 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7309
7687
|
};
|
|
7310
7688
|
for (let blockhashRetry = 0; blockhashRetry <= maxBlockhashRetries; blockhashRetry++) {
|
|
7311
7689
|
if (blockhashRetry > 0) {
|
|
7312
|
-
({ blockhash, lastValidBlockHeight } = await connection
|
|
7690
|
+
({ blockhash, lastValidBlockHeight } = await fetchLatestBlockhash(connection));
|
|
7313
7691
|
onProgress?.(
|
|
7314
7692
|
`Blockhash expired before confirmation; retrying with fresh blockhash (${blockhashRetry}/${maxBlockhashRetries})...`
|
|
7315
7693
|
);
|
|
7316
7694
|
}
|
|
7317
7695
|
let transportAttempt = 0;
|
|
7318
7696
|
while (true) {
|
|
7319
|
-
const
|
|
7320
|
-
|
|
7321
|
-
|
|
7322
|
-
|
|
7323
|
-
|
|
7324
|
-
|
|
7697
|
+
const message = buildTransactionMessage({
|
|
7698
|
+
version: transactionVersion,
|
|
7699
|
+
computeConfig,
|
|
7700
|
+
feePayer: depositor,
|
|
7701
|
+
lifetime: { blockhash, lastValidBlockHeight },
|
|
7702
|
+
instructions: ixs,
|
|
7703
|
+
lookupTables: addressLookupTableAccounts
|
|
7704
|
+
});
|
|
7325
7705
|
if (onTransactProofBuilt) {
|
|
7326
7706
|
await onTransactProofBuilt();
|
|
7327
7707
|
}
|
|
7328
7708
|
try {
|
|
7329
|
-
|
|
7330
|
-
|
|
7331
|
-
|
|
7332
|
-
|
|
7333
|
-
|
|
7334
|
-
|
|
7335
|
-
|
|
7336
|
-
|
|
7337
|
-
|
|
7338
|
-
|
|
7339
|
-
|
|
7340
|
-
|
|
7341
|
-
}, "confirmed");
|
|
7342
|
-
if (confirmation.value.err) {
|
|
7343
|
-
throw new Error(`Transaction failed during confirmation: ${JSON.stringify(confirmation.value.err)}`);
|
|
7344
|
-
}
|
|
7345
|
-
} else if (depositor.signTransaction) {
|
|
7346
|
-
onProgress?.("Waiting for wallet signature...");
|
|
7347
|
-
const signedTx = await depositor.signTransaction(versionedTx);
|
|
7348
|
-
onProgress?.("Sending transaction...");
|
|
7349
|
-
signature = await connection.sendRawTransaction(signedTx.serialize(), {
|
|
7350
|
-
skipPreflight: options?.skipPreflight ?? false
|
|
7351
|
-
});
|
|
7352
|
-
sentSigs.push(signature);
|
|
7353
|
-
onProgress?.("Confirming transaction...");
|
|
7354
|
-
const confirmation = await connection.confirmTransaction({
|
|
7355
|
-
signature,
|
|
7356
|
-
blockhash,
|
|
7357
|
-
lastValidBlockHeight
|
|
7358
|
-
}, "confirmed");
|
|
7359
|
-
if (confirmation.value.err) {
|
|
7360
|
-
throw new Error(`Transaction failed during confirmation: ${JSON.stringify(confirmation.value.err)}`);
|
|
7361
|
-
}
|
|
7362
|
-
} else {
|
|
7363
|
-
throw new Error("No signing method provided (need keypair or signTransaction)");
|
|
7364
|
-
}
|
|
7709
|
+
onProgress?.((0, import_kit8.isKeyPairSigner)(depositor) ? "Signing and sending transaction..." : "Waiting for wallet signature...");
|
|
7710
|
+
const signed = await signTransaction(message);
|
|
7711
|
+
if (!(0, import_kit8.isKeyPairSigner)(depositor)) onProgress?.("Sending transaction...");
|
|
7712
|
+
signature = await sendRawTransaction(connection, transactionBytes(signed), {
|
|
7713
|
+
skipPreflight: options?.skipPreflight ?? false
|
|
7714
|
+
});
|
|
7715
|
+
sentSigs.push(signature);
|
|
7716
|
+
onProgress?.("Confirming transaction...");
|
|
7717
|
+
await confirmSignature(connection, signature, {
|
|
7718
|
+
commitment: "confirmed",
|
|
7719
|
+
lastValidBlockHeight
|
|
7720
|
+
});
|
|
7365
7721
|
return signature;
|
|
7366
7722
|
} catch (error) {
|
|
7367
7723
|
if (isBlockhashExpiryError(error)) {
|
|
@@ -7376,7 +7732,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7376
7732
|
`Transient RPC transport error; retrying in ${Math.round(delayMs)}ms (${transportAttempt}/${maxTransportRetries})...`
|
|
7377
7733
|
);
|
|
7378
7734
|
await new Promise((r) => setTimeout(r, delayMs));
|
|
7379
|
-
({ blockhash, lastValidBlockHeight } = await connection
|
|
7735
|
+
({ blockhash, lastValidBlockHeight } = await fetchLatestBlockhash(connection));
|
|
7380
7736
|
continue;
|
|
7381
7737
|
}
|
|
7382
7738
|
if (looksLikeDoubleSpend(error)) {
|
|
@@ -7451,34 +7807,21 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7451
7807
|
let legacyTransportAttempt = 0;
|
|
7452
7808
|
while (true) {
|
|
7453
7809
|
try {
|
|
7454
|
-
const
|
|
7455
|
-
|
|
7456
|
-
|
|
7457
|
-
|
|
7458
|
-
|
|
7459
|
-
|
|
7460
|
-
|
|
7461
|
-
|
|
7462
|
-
|
|
7463
|
-
|
|
7464
|
-
|
|
7465
|
-
|
|
7466
|
-
|
|
7467
|
-
|
|
7468
|
-
}
|
|
7469
|
-
onProgress?.("Waiting for wallet signature...");
|
|
7470
|
-
const signedTx = await depositor.signTransaction(tx);
|
|
7471
|
-
onProgress?.("Sending transaction...");
|
|
7472
|
-
signature = await connection.sendRawTransaction(signedTx.serialize());
|
|
7473
|
-
onProgress?.("Confirming transaction...");
|
|
7474
|
-
await connection.confirmTransaction({
|
|
7475
|
-
signature,
|
|
7476
|
-
blockhash,
|
|
7477
|
-
lastValidBlockHeight
|
|
7478
|
-
}, "confirmed");
|
|
7479
|
-
} else {
|
|
7480
|
-
throw new Error("No signing method provided (need keypair or signTransaction)");
|
|
7481
|
-
}
|
|
7810
|
+
const message = buildTransactionMessage({
|
|
7811
|
+
version: "legacy",
|
|
7812
|
+
feePayer: depositor,
|
|
7813
|
+
lifetime: { blockhash, lastValidBlockHeight },
|
|
7814
|
+
instructions
|
|
7815
|
+
});
|
|
7816
|
+
onProgress?.((0, import_kit8.isKeyPairSigner)(depositor) ? "Signing and sending transaction..." : "Waiting for wallet signature...");
|
|
7817
|
+
const signed = await signTransaction(message);
|
|
7818
|
+
if (!(0, import_kit8.isKeyPairSigner)(depositor)) onProgress?.("Sending transaction...");
|
|
7819
|
+
signature = await sendRawTransaction(connection, transactionBytes(signed));
|
|
7820
|
+
onProgress?.("Confirming transaction...");
|
|
7821
|
+
await confirmSignature(connection, signature, {
|
|
7822
|
+
commitment: "confirmed",
|
|
7823
|
+
lastValidBlockHeight
|
|
7824
|
+
});
|
|
7482
7825
|
break;
|
|
7483
7826
|
} catch (err) {
|
|
7484
7827
|
if (isTransientTransportError(err) && legacyTransportAttempt < maxLegacyTransportRetries) {
|
|
@@ -7488,7 +7831,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7488
7831
|
`Transient RPC transport error; retrying in ${Math.round(delayMs)}ms (${legacyTransportAttempt}/${maxLegacyTransportRetries})...`
|
|
7489
7832
|
);
|
|
7490
7833
|
await new Promise((r) => setTimeout(r, delayMs));
|
|
7491
|
-
({ blockhash, lastValidBlockHeight } = await connection
|
|
7834
|
+
({ blockhash, lastValidBlockHeight } = await fetchLatestBlockhash(connection));
|
|
7492
7835
|
continue;
|
|
7493
7836
|
}
|
|
7494
7837
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -7508,7 +7851,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
|
|
|
7508
7851
|
}
|
|
7509
7852
|
onProgress?.("Verifying the transaction against chain state...");
|
|
7510
7853
|
await assertDirectSubmissionLanded({
|
|
7511
|
-
connection,
|
|
7854
|
+
connection: settlementConnectionFromRpc(connection),
|
|
7512
7855
|
programId,
|
|
7513
7856
|
mint,
|
|
7514
7857
|
nullifiers,
|
|
@@ -7633,16 +7976,16 @@ async function fetchRiskQuote(riskQuoteUrl, wallet, options) {
|
|
|
7633
7976
|
} catch {
|
|
7634
7977
|
url = new URL(baseUrl, typeof window !== "undefined" ? window.location.origin : "http://localhost");
|
|
7635
7978
|
}
|
|
7636
|
-
url.searchParams.set("wallet", wallet
|
|
7637
|
-
url.searchParams.set("pool_mint", options.poolMint
|
|
7979
|
+
url.searchParams.set("wallet", wallet);
|
|
7980
|
+
url.searchParams.set("pool_mint", options.poolMint);
|
|
7638
7981
|
if (options?.recipient) {
|
|
7639
|
-
url.searchParams.set("recipient", options.recipient
|
|
7982
|
+
url.searchParams.set("recipient", options.recipient);
|
|
7640
7983
|
}
|
|
7641
7984
|
if (options?.amount !== void 0) {
|
|
7642
7985
|
url.searchParams.set("amount", options.amount.toString());
|
|
7643
7986
|
}
|
|
7644
7987
|
if (options?.token) {
|
|
7645
|
-
url.searchParams.set("token", options.token
|
|
7988
|
+
url.searchParams.set("token", options.token);
|
|
7646
7989
|
}
|
|
7647
7990
|
if (options?.commitment) {
|
|
7648
7991
|
const commitment = typeof options.commitment === "string" ? options.commitment.replace(/^0x/i, "") : Buffer.from(options.commitment).toString("hex");
|
|
@@ -7673,19 +8016,16 @@ async function fetchRiskQuote(riskQuoteUrl, wallet, options) {
|
|
|
7673
8016
|
}
|
|
7674
8017
|
const signatureBuf = Buffer.from(signatureB64, "base64");
|
|
7675
8018
|
const messageArr = hexToBytes2(messageHex);
|
|
7676
|
-
|
|
7677
|
-
try {
|
|
7678
|
-
signerPubkey = new import_web311.PublicKey(signerB58);
|
|
7679
|
-
} catch {
|
|
8019
|
+
if (!(0, import_kit.isAddress)(signerB58)) {
|
|
7680
8020
|
throw new Error("Invalid risk quote response: signer_pubkey is not a public key");
|
|
7681
8021
|
}
|
|
7682
|
-
const publicKeyBytes =
|
|
8022
|
+
const publicKeyBytes = addressBytes(signerB58);
|
|
7683
8023
|
if (signatureBuf.length !== 64 || messageArr.length !== 33 && messageArr.length !== 41 && messageArr.length !== 50 && messageArr.length !== 82 && messageArr.length !== 146 || publicKeyBytes.length !== 32) {
|
|
7684
8024
|
throw new Error(
|
|
7685
8025
|
`Invalid risk quote response: invalid lengths (sig=${signatureBuf.length}, msg=${messageArr.length}, pk=${publicKeyBytes.length}; expected msg 33/41/50/82/146)`
|
|
7686
8026
|
);
|
|
7687
8027
|
}
|
|
7688
|
-
if (!
|
|
8028
|
+
if (!import_tweetnacl5.default.sign.detached.verify(messageArr, new Uint8Array(signatureBuf), publicKeyBytes)) {
|
|
7689
8029
|
throw new Error(
|
|
7690
8030
|
"Invalid risk quote response: signature does not verify under signer_pubkey"
|
|
7691
8031
|
);
|
|
@@ -7699,11 +8039,7 @@ async function fetchRiskQuote(riskQuoteUrl, wallet, options) {
|
|
|
7699
8039
|
const signature = new Uint8Array(signatureBuf);
|
|
7700
8040
|
const message = new Uint8Array(messageArr);
|
|
7701
8041
|
const publicKey = new Uint8Array(publicKeyBytes);
|
|
7702
|
-
const instruction =
|
|
7703
|
-
publicKey,
|
|
7704
|
-
message,
|
|
7705
|
-
signature
|
|
7706
|
-
});
|
|
8042
|
+
const instruction = ed25519VerifyInstruction({ publicKey, message, signature });
|
|
7707
8043
|
return { instruction, nonce };
|
|
7708
8044
|
}
|
|
7709
8045
|
const keys = Object.keys(json).join(", ");
|
|
@@ -7733,9 +8069,9 @@ function buildTransactRequestBody(params) {
|
|
|
7733
8069
|
const body = {
|
|
7734
8070
|
proof_bytes: params.proofB64,
|
|
7735
8071
|
public_inputs: params.publicInputsB64,
|
|
7736
|
-
mint: params.mint
|
|
7737
|
-
recipient: params.recipient
|
|
7738
|
-
relayer: params.relayer
|
|
8072
|
+
mint: params.mint,
|
|
8073
|
+
recipient: params.recipient ?? void 0,
|
|
8074
|
+
relayer: params.relayer ?? void 0,
|
|
7739
8075
|
relayer_fee: params.relayerFee.toString(),
|
|
7740
8076
|
// R3-M-02: the proof-bound fee ceiling. A decimal string preserves the full u64, and the
|
|
7741
8077
|
// relay forwards it verbatim into the ext-data envelope — any substitution fails on chain.
|
|
@@ -7744,7 +8080,7 @@ function buildTransactRequestBody(params) {
|
|
|
7744
8080
|
risk_quote: params.riskQuote
|
|
7745
8081
|
};
|
|
7746
8082
|
if (params.externalAmount === BigInt(0) && !params.recipient && params.sender) {
|
|
7747
|
-
body.sender = params.sender
|
|
8083
|
+
body.sender = params.sender;
|
|
7748
8084
|
}
|
|
7749
8085
|
if (params.recipientDeliveryNotes && params.recipientDeliveryNotes.length > 0 && params.externalAmount === BigInt(0) && !params.recipient) {
|
|
7750
8086
|
body.recipient_delivery_notes = params.recipientDeliveryNotes;
|
|
@@ -7754,7 +8090,10 @@ function buildTransactRequestBody(params) {
|
|
|
7754
8090
|
function resolveUserWallet(options) {
|
|
7755
8091
|
const candidates = [];
|
|
7756
8092
|
if (options.depositorKeypair) {
|
|
7757
|
-
candidates.push({ option: "depositorKeypair", key: options.depositorKeypair.
|
|
8093
|
+
candidates.push({ option: "depositorKeypair", key: options.depositorKeypair.address });
|
|
8094
|
+
}
|
|
8095
|
+
if (options.signer) {
|
|
8096
|
+
candidates.push({ option: "signer", key: options.signer.address });
|
|
7758
8097
|
}
|
|
7759
8098
|
if (options.walletPublicKey) {
|
|
7760
8099
|
candidates.push({ option: "walletPublicKey", key: options.walletPublicKey });
|
|
@@ -7765,9 +8104,9 @@ function resolveUserWallet(options) {
|
|
|
7765
8104
|
if (candidates.length === 0) return void 0;
|
|
7766
8105
|
const first = candidates[0];
|
|
7767
8106
|
for (const other of candidates.slice(1)) {
|
|
7768
|
-
if (other.key
|
|
8107
|
+
if (other.key === first.key) continue;
|
|
7769
8108
|
throw new Error(
|
|
7770
|
-
`Cloak was given two different wallets: \`${first.option}\` is ${first.key
|
|
8109
|
+
`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.`
|
|
7771
8110
|
);
|
|
7772
8111
|
}
|
|
7773
8112
|
return first.key;
|
|
@@ -7776,22 +8115,22 @@ function planRelayAuth(options) {
|
|
|
7776
8115
|
const walletPublicKey = resolveUserWallet(options);
|
|
7777
8116
|
if (options.depositorKeypair) return { kind: "keypair" };
|
|
7778
8117
|
const signMessage = options.signMessage;
|
|
7779
|
-
const
|
|
7780
|
-
if (walletPublicKey && signMessage)
|
|
7781
|
-
|
|
7782
|
-
return { kind: "wallet", signer: { walletPublicKey, signAuthTransaction } };
|
|
8118
|
+
const signer = options.signer;
|
|
8119
|
+
if (walletPublicKey && signMessage) {
|
|
8120
|
+
return { kind: "wallet", signer: messageSignerFromCallback(walletPublicKey, signMessage) };
|
|
7783
8121
|
}
|
|
7784
|
-
if (
|
|
8122
|
+
if (signer) return { kind: "wallet", signer };
|
|
8123
|
+
if (!walletPublicKey && !signMessage) return { kind: "none" };
|
|
7785
8124
|
return {
|
|
7786
8125
|
kind: "incomplete",
|
|
7787
|
-
detail: signMessage
|
|
8126
|
+
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."
|
|
7788
8127
|
};
|
|
7789
8128
|
}
|
|
7790
8129
|
function assertRelayAuthAvailable(plan, flow) {
|
|
7791
8130
|
if (plan.kind === "keypair" || plan.kind === "wallet") return;
|
|
7792
8131
|
const cause = plan.kind === "none" ? "no signer was provided." : `the signer provided cannot produce one: ${plan.detail}`;
|
|
7793
8132
|
throw new Error(
|
|
7794
|
-
`Cloak ${flow} requires an authenticated sender, and ${cause} Pass either \`depositorKeypair\` (a local
|
|
8133
|
+
`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.`
|
|
7795
8134
|
);
|
|
7796
8135
|
}
|
|
7797
8136
|
async function submitTransactToRelay(args) {
|
|
@@ -8002,7 +8341,7 @@ async function transact(params, options) {
|
|
|
8002
8341
|
relayer,
|
|
8003
8342
|
relayUrl: relayUrlOverride,
|
|
8004
8343
|
depositorKeypair,
|
|
8005
|
-
|
|
8344
|
+
signer,
|
|
8006
8345
|
depositorPublicKey,
|
|
8007
8346
|
// `walletPublicKey` is deliberately NOT destructured here. Reading it directly is how three
|
|
8008
8347
|
// different answers to "which key is the user" grew in this file; every reader of it now goes
|
|
@@ -8094,7 +8433,7 @@ async function transact(params, options) {
|
|
|
8094
8433
|
throw new Error(`Balance mismatch: ${inputSum} + ${externalAmount} != ${outputSum}`);
|
|
8095
8434
|
}
|
|
8096
8435
|
if (externalAmount > BigInt(0)) {
|
|
8097
|
-
const isNativeDeposit = mint
|
|
8436
|
+
const isNativeDeposit = mint === NATIVE_SOL_MINT;
|
|
8098
8437
|
if (isNativeDeposit && externalAmount < BigInt(MIN_DEPOSIT_LAMPORTS)) {
|
|
8099
8438
|
throw new Error(
|
|
8100
8439
|
`Deposit amount too small: ${externalAmount} lamports. Minimum is ${MIN_DEPOSIT_LAMPORTS} (0.01 SOL).`
|
|
@@ -8102,7 +8441,7 @@ async function transact(params, options) {
|
|
|
8102
8441
|
}
|
|
8103
8442
|
} else if (externalAmount < BigInt(0)) {
|
|
8104
8443
|
const withdrawAmount = -externalAmount;
|
|
8105
|
-
const isNativeWithdraw = mint
|
|
8444
|
+
const isNativeWithdraw = mint === NATIVE_SOL_MINT;
|
|
8106
8445
|
if (isNativeWithdraw && !isWithdrawAmountSufficient(withdrawAmount)) {
|
|
8107
8446
|
const fee = calculateFeeBigint(withdrawAmount);
|
|
8108
8447
|
throw new Error(
|
|
@@ -8110,7 +8449,7 @@ async function transact(params, options) {
|
|
|
8110
8449
|
);
|
|
8111
8450
|
}
|
|
8112
8451
|
}
|
|
8113
|
-
const pdas = getShieldPoolPDAs(programId, mint);
|
|
8452
|
+
const pdas = await getShieldPoolPDAs(programId, mint);
|
|
8114
8453
|
const needsTreeForProof = paddedInputs.some(
|
|
8115
8454
|
(utxo) => utxo.amount > BigInt(0) && utxo.index !== void 0
|
|
8116
8455
|
);
|
|
@@ -8120,7 +8459,7 @@ async function transact(params, options) {
|
|
|
8120
8459
|
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");
|
|
8121
8460
|
const nearTipMaxDistance = nearTipFallbackMaxDistance(connection);
|
|
8122
8461
|
const useRelayMerkleByDefault = shouldUseRelayMerkleByDefault(connection);
|
|
8123
|
-
const relayMintKey = mint
|
|
8462
|
+
const relayMintKey = mint;
|
|
8124
8463
|
let relayTreeDisabledForMint = _relayMerkleDisabledMints.has(relayMintKey) || !useRelayMerkleByDefault;
|
|
8125
8464
|
const requiredRelayIndex = paddedInputs.reduce((maxIndex, utxo) => {
|
|
8126
8465
|
if (utxo.amount === BigInt(0) || utxo.index === void 0 || utxo.index < 0) {
|
|
@@ -8246,7 +8585,7 @@ async function transact(params, options) {
|
|
|
8246
8585
|
if (treeState) {
|
|
8247
8586
|
const chainRoot = merkleTree.root().toString(16).padStart(64, "0");
|
|
8248
8587
|
if (chainRoot !== treeState.root) {
|
|
8249
|
-
const acct = await connection
|
|
8588
|
+
const acct = await fetchAccountBytes(connection, pdas.merkleTree, "confirmed");
|
|
8250
8589
|
const stillAccepted = acct ? isRootAccepted(acct.data, chainRoot) : false;
|
|
8251
8590
|
if (stillAccepted) {
|
|
8252
8591
|
onProgress?.(`Chain-built tree is behind the tip but its root is still in the on-chain root history; proving against it.`);
|
|
@@ -8490,7 +8829,7 @@ async function transact(params, options) {
|
|
|
8490
8829
|
const missingRelayIndex = parseMissingRelayIndexError(errorMsg);
|
|
8491
8830
|
if (retryableProofError && relayUrl && missingRelayIndex && missingRelayIndex.treeLength === 0 && missingRelayIndex.leafIndex > 0 && submissionAttempts >= RELAY_EMPTY_TREE_FAILFAST_RETRIES) {
|
|
8492
8831
|
throw new Error(
|
|
8493
|
-
`Relay commitment cache stayed empty for mint ${mint
|
|
8832
|
+
`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.`
|
|
8494
8833
|
);
|
|
8495
8834
|
}
|
|
8496
8835
|
if (retryableProofError && submissionAttempts < maxRootRetries) {
|
|
@@ -8686,18 +9025,17 @@ async function transact(params, options) {
|
|
|
8686
9025
|
}
|
|
8687
9026
|
const isDeposit = externalAmount > BigInt(0);
|
|
8688
9027
|
if (isDeposit) {
|
|
8689
|
-
const
|
|
8690
|
-
|
|
8691
|
-
if (!hasKeypairSigning2 && !hasWalletSigning2) {
|
|
9028
|
+
const depositSigner = depositorKeypair ?? signer;
|
|
9029
|
+
if (!depositSigner) {
|
|
8692
9030
|
throw new Error(
|
|
8693
|
-
"Deposits require depositorKeypair or
|
|
9031
|
+
"Deposits require depositorKeypair or signer. The depositor must sign to transfer SOL into the shielded pool."
|
|
8694
9032
|
);
|
|
8695
9033
|
}
|
|
8696
9034
|
onProgress?.("Submitting deposit transaction (user signs)...");
|
|
8697
9035
|
try {
|
|
8698
9036
|
const nullifier0Bytes = bigintToBytes323(inputNullifiers[0]);
|
|
8699
9037
|
const nullifier1Bytes = bigintToBytes323(inputNullifiers[1]);
|
|
8700
|
-
const depositor =
|
|
9038
|
+
const depositor = depositSigner;
|
|
8701
9039
|
const directResult = await submitTransactionDirect(
|
|
8702
9040
|
connection,
|
|
8703
9041
|
programId,
|
|
@@ -8720,7 +9058,8 @@ async function transact(params, options) {
|
|
|
8720
9058
|
relayerFee,
|
|
8721
9059
|
options.onTransactProofBuilt,
|
|
8722
9060
|
externalFeePayer,
|
|
8723
|
-
options.relaySupplementalAlt
|
|
9061
|
+
options.relaySupplementalAlt,
|
|
9062
|
+
options.transactionVersion
|
|
8724
9063
|
);
|
|
8725
9064
|
signature = directResult.signature;
|
|
8726
9065
|
commitmentIndices = directResult.commitmentIndices;
|
|
@@ -8742,14 +9081,14 @@ async function transact(params, options) {
|
|
|
8742
9081
|
break;
|
|
8743
9082
|
}
|
|
8744
9083
|
}
|
|
8745
|
-
const
|
|
8746
|
-
|
|
8747
|
-
if (!relayUrl &&
|
|
9084
|
+
const directSigner = depositorKeypair ?? signer;
|
|
9085
|
+
void depositorPublicKey;
|
|
9086
|
+
if (!relayUrl && directSigner) {
|
|
8748
9087
|
onProgress?.("Submitting transaction directly (no relay)...");
|
|
8749
9088
|
try {
|
|
8750
9089
|
const nullifier0Bytes = bigintToBytes323(inputNullifiers[0]);
|
|
8751
9090
|
const nullifier1Bytes = bigintToBytes323(inputNullifiers[1]);
|
|
8752
|
-
const depositor =
|
|
9091
|
+
const depositor = directSigner;
|
|
8753
9092
|
const directResult = await submitTransactionDirect(
|
|
8754
9093
|
connection,
|
|
8755
9094
|
programId,
|
|
@@ -8772,7 +9111,10 @@ async function transact(params, options) {
|
|
|
8772
9111
|
altAddresses,
|
|
8773
9112
|
relayer ?? null,
|
|
8774
9113
|
relayerFee,
|
|
8775
|
-
options.onTransactProofBuilt
|
|
9114
|
+
options.onTransactProofBuilt,
|
|
9115
|
+
void 0,
|
|
9116
|
+
void 0,
|
|
9117
|
+
options.transactionVersion
|
|
8776
9118
|
);
|
|
8777
9119
|
signature = directResult.signature;
|
|
8778
9120
|
commitmentIndices = directResult.commitmentIndices;
|
|
@@ -8818,10 +9160,10 @@ async function transact(params, options) {
|
|
|
8818
9160
|
} catch {
|
|
8819
9161
|
url = new URL(baseUrl, typeof window !== "undefined" ? window.location.origin : "http://localhost");
|
|
8820
9162
|
}
|
|
8821
|
-
url.searchParams.set("wallet", depositorPubkey
|
|
8822
|
-
url.searchParams.set("recipient", recipient
|
|
9163
|
+
url.searchParams.set("wallet", depositorPubkey);
|
|
9164
|
+
url.searchParams.set("recipient", recipient);
|
|
8823
9165
|
url.searchParams.set("context", "withdraw");
|
|
8824
|
-
url.searchParams.set("pool_mint", mint
|
|
9166
|
+
url.searchParams.set("pool_mint", mint);
|
|
8825
9167
|
url.searchParams.set("nullifier0", toHex(bigintToBytes323(inputNullifiers[0])));
|
|
8826
9168
|
url.searchParams.set("nullifier1", toHex(bigintToBytes323(inputNullifiers[1])));
|
|
8827
9169
|
const quoteRes = await relayFetch(url.toString());
|
|
@@ -8847,9 +9189,9 @@ async function transact(params, options) {
|
|
|
8847
9189
|
} catch {
|
|
8848
9190
|
url = new URL(baseUrl, typeof window !== "undefined" ? window.location.origin : "http://localhost");
|
|
8849
9191
|
}
|
|
8850
|
-
url.searchParams.set("wallet", depositorPubkey
|
|
9192
|
+
url.searchParams.set("wallet", depositorPubkey);
|
|
8851
9193
|
url.searchParams.set("context", "send");
|
|
8852
|
-
url.searchParams.set("pool_mint", mint
|
|
9194
|
+
url.searchParams.set("pool_mint", mint);
|
|
8853
9195
|
url.searchParams.set(
|
|
8854
9196
|
"nullifier0",
|
|
8855
9197
|
inputNullifiers[0].toString(16).padStart(64, "0")
|
|
@@ -8916,7 +9258,7 @@ async function transact(params, options) {
|
|
|
8916
9258
|
relayAuthSigner: relayAuthPlan.kind === "wallet" ? relayAuthPlan.signer : void 0,
|
|
8917
9259
|
relayAuthBatch: options.relayAuthBatch,
|
|
8918
9260
|
settlement: {
|
|
8919
|
-
connection,
|
|
9261
|
+
connection: settlementConnectionFromRpc(connection),
|
|
8920
9262
|
programId,
|
|
8921
9263
|
mint,
|
|
8922
9264
|
inputNullifiers
|
|
@@ -8960,10 +9302,7 @@ async function transact(params, options) {
|
|
|
8960
9302
|
"All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
|
|
8961
9303
|
);
|
|
8962
9304
|
try {
|
|
8963
|
-
const [merkleTreePda] =
|
|
8964
|
-
[Buffer.from("merkle_tree"), mint.toBuffer()],
|
|
8965
|
-
programId
|
|
8966
|
-
);
|
|
9305
|
+
const [merkleTreePda] = await findProgramAddress(["merkle_tree", addressBytes(mint)], programId);
|
|
8967
9306
|
const chainTree = await buildMerkleTreeFromChain(
|
|
8968
9307
|
connection,
|
|
8969
9308
|
programId,
|
|
@@ -9336,18 +9675,16 @@ async function swapUtxo(params, options) {
|
|
|
9336
9675
|
throw new Error("Maximum 2 input UTXOs allowed");
|
|
9337
9676
|
}
|
|
9338
9677
|
assertInputMints(inputUtxos, NATIVE_SOL_MINT);
|
|
9339
|
-
if (options.expectedMint &&
|
|
9678
|
+
if (options.expectedMint && options.expectedMint !== NATIVE_SOL_MINT) {
|
|
9340
9679
|
throw new Error(
|
|
9341
|
-
`swapUtxo expects ${NATIVE_SOL_MINT
|
|
9680
|
+
`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.`
|
|
9342
9681
|
);
|
|
9343
9682
|
}
|
|
9344
9683
|
await preflightNullifiers(inputUtxos, connection, programId);
|
|
9345
|
-
const outputMintAccount = await connection
|
|
9346
|
-
commitment: "confirmed"
|
|
9347
|
-
});
|
|
9684
|
+
const outputMintAccount = await fetchAccountBytes(connection, outputMint, "confirmed");
|
|
9348
9685
|
if (!outputMintAccount) {
|
|
9349
9686
|
throw new Error(
|
|
9350
|
-
`Swap output mint ${outputMint
|
|
9687
|
+
`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.`
|
|
9351
9688
|
);
|
|
9352
9689
|
}
|
|
9353
9690
|
const totalInputAmount = sumUtxoAmounts(inputUtxos);
|
|
@@ -9369,7 +9706,7 @@ async function swapUtxo(params, options) {
|
|
|
9369
9706
|
}
|
|
9370
9707
|
}
|
|
9371
9708
|
const swapPoolMint = NATIVE_SOL_MINT;
|
|
9372
|
-
const pdas = getShieldPoolPDAs(programId, swapPoolMint);
|
|
9709
|
+
const pdas = await getShieldPoolPDAs(programId, swapPoolMint);
|
|
9373
9710
|
let merkleState = null;
|
|
9374
9711
|
const paddedInputs = [...inputUtxos];
|
|
9375
9712
|
while (paddedInputs.length < 2) {
|
|
@@ -9434,7 +9771,7 @@ async function swapUtxo(params, options) {
|
|
|
9434
9771
|
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");
|
|
9435
9772
|
const nearTipMaxDistance = nearTipFallbackMaxDistance(connection);
|
|
9436
9773
|
const useRelayMerkleByDefault = shouldUseRelayMerkleByDefault(connection);
|
|
9437
|
-
const relayMintKey = swapPoolMint
|
|
9774
|
+
const relayMintKey = swapPoolMint;
|
|
9438
9775
|
let relayTreeDisabledForMint = _relayMerkleDisabledMints.has(relayMintKey) || !useRelayMerkleByDefault;
|
|
9439
9776
|
const hasCachedTree = !!cachedMerkleTree && cachedMerkleTree.length > 0;
|
|
9440
9777
|
const requiredRelayIndex = paddedInputs.reduce((maxIndex, utxo) => {
|
|
@@ -9553,7 +9890,7 @@ async function swapUtxo(params, options) {
|
|
|
9553
9890
|
if (merkleState) {
|
|
9554
9891
|
const chainRoot = merkleTree.root().toString(16).padStart(64, "0");
|
|
9555
9892
|
if (chainRoot !== merkleState.root) {
|
|
9556
|
-
const acct = await connection
|
|
9893
|
+
const acct = await fetchAccountBytes(connection, pdas.merkleTree, "confirmed");
|
|
9557
9894
|
if (acct && isRootAccepted(acct.data, chainRoot)) {
|
|
9558
9895
|
onProgress?.("Chain-built tree is behind the tip but its root is still accepted on chain; proving against it.");
|
|
9559
9896
|
merkleState = { ...merkleState, root: chainRoot, nextIndex: merkleTree.length };
|
|
@@ -9785,7 +10122,7 @@ async function swapUtxo(params, options) {
|
|
|
9785
10122
|
const missingRelayIndex = parseMissingRelayIndexError(errorMsg);
|
|
9786
10123
|
if (retryableProofError && relayUrl && missingRelayIndex && missingRelayIndex.treeLength === 0 && missingRelayIndex.leafIndex > 0 && attempt >= RELAY_EMPTY_TREE_FAILFAST_RETRIES) {
|
|
9787
10124
|
throw new Error(
|
|
9788
|
-
`Relay commitment cache stayed empty for mint ${swapPoolMint
|
|
10125
|
+
`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.`
|
|
9789
10126
|
);
|
|
9790
10127
|
}
|
|
9791
10128
|
if (retryableProofError && attempt < maxRootRetries) {
|
|
@@ -9946,10 +10283,10 @@ async function swapUtxo(params, options) {
|
|
|
9946
10283
|
} catch {
|
|
9947
10284
|
url = new URL(baseUrl, typeof window !== "undefined" ? window.location.origin : "http://localhost");
|
|
9948
10285
|
}
|
|
9949
|
-
url.searchParams.set("wallet", poolPda
|
|
9950
|
-
url.searchParams.set("recipient", recipientWallet
|
|
9951
|
-
url.searchParams.set("sender", recipientWallet
|
|
9952
|
-
url.searchParams.set("pool_mint", mint
|
|
10286
|
+
url.searchParams.set("wallet", poolPda);
|
|
10287
|
+
url.searchParams.set("recipient", recipientWallet);
|
|
10288
|
+
url.searchParams.set("sender", recipientWallet);
|
|
10289
|
+
url.searchParams.set("pool_mint", mint);
|
|
9953
10290
|
url.searchParams.set("nullifier0", toHex(bigintToBytes323(inputNullifiers[0])));
|
|
9954
10291
|
url.searchParams.set("nullifier1", toHex(bigintToBytes323(inputNullifiers[1])));
|
|
9955
10292
|
const quoteRes = await relayFetch(url.toString());
|
|
@@ -9971,18 +10308,15 @@ async function swapUtxo(params, options) {
|
|
|
9971
10308
|
}
|
|
9972
10309
|
if (options.onSwapStatePredicted && inputNullifiers.length > 0) {
|
|
9973
10310
|
const nBytes = bigintToBytes323(inputNullifiers[0]);
|
|
9974
|
-
const [ssp] =
|
|
9975
|
-
|
|
9976
|
-
programId
|
|
9977
|
-
);
|
|
9978
|
-
await options.onSwapStatePredicted(ssp.toBase58());
|
|
10311
|
+
const [ssp] = await findProgramAddress(["swap_state", addressBytes(pdas.pool), new Uint8Array(nBytes)], programId);
|
|
10312
|
+
await options.onSwapStatePredicted(ssp);
|
|
9979
10313
|
}
|
|
9980
10314
|
const requestBody = {
|
|
9981
10315
|
proof_bytes: proofB64,
|
|
9982
10316
|
public_inputs: publicInputsB64,
|
|
9983
|
-
output_mint: outputMint
|
|
9984
|
-
recipient_ata: recipientAta
|
|
9985
|
-
recipient: recipientWallet
|
|
10317
|
+
output_mint: outputMint,
|
|
10318
|
+
recipient_ata: recipientAta,
|
|
10319
|
+
recipient: recipientWallet,
|
|
9986
10320
|
// The relay parses this as a u64 and rejects a JSON number ("invalid type: integer,
|
|
9987
10321
|
// expected a string"). A string also removes the old 2^53 ceiling instead of guarding it.
|
|
9988
10322
|
min_output_amount: minOutputAmount.toString(),
|
|
@@ -10394,7 +10728,7 @@ function cleanupStalePendingOperations(maxAgeMs = 24 * 60 * 60 * 1e3) {
|
|
|
10394
10728
|
init_utxo();
|
|
10395
10729
|
|
|
10396
10730
|
// src/relay/batch-auth.ts
|
|
10397
|
-
var
|
|
10731
|
+
var import_kit9 = require("@solana/kit");
|
|
10398
10732
|
var RelayBatchAuthCoordinator = class {
|
|
10399
10733
|
constructor(options) {
|
|
10400
10734
|
this.proofSlotsInUse = 0;
|
|
@@ -10417,7 +10751,7 @@ var RelayBatchAuthCoordinator = class {
|
|
|
10417
10751
|
throw new Error(`submitConcurrency must be a positive integer (got ${concurrency}).`);
|
|
10418
10752
|
}
|
|
10419
10753
|
this.signer = options.signer;
|
|
10420
|
-
this.sender = options.signer
|
|
10754
|
+
this.sender = options.signer.address;
|
|
10421
10755
|
this.expectedItems = options.items;
|
|
10422
10756
|
this.submitConcurrency = concurrency;
|
|
10423
10757
|
const proofConcurrency = options.proofConcurrency ?? 2;
|
|
@@ -10529,7 +10863,7 @@ var RelayBatchAuthCoordinator = class {
|
|
|
10529
10863
|
try {
|
|
10530
10864
|
const programId = waiting[0].programId;
|
|
10531
10865
|
for (const w of waiting) {
|
|
10532
|
-
if (
|
|
10866
|
+
if (w.programId !== programId) {
|
|
10533
10867
|
throw new Error("Every item of a batch must target the same program id.");
|
|
10534
10868
|
}
|
|
10535
10869
|
}
|
|
@@ -10541,15 +10875,15 @@ var RelayBatchAuthCoordinator = class {
|
|
|
10541
10875
|
const issuedAt = preimages[0].auth_issued_at;
|
|
10542
10876
|
const message = buildRelayBatchAuthMessage(programId, issuedAt, digests);
|
|
10543
10877
|
this.waves += 1;
|
|
10544
|
-
if (!(this.signer
|
|
10545
|
-
const asTransaction = !this.signer.
|
|
10878
|
+
if (!(0, import_kit9.isKeyPairSigner)(this.signer)) {
|
|
10879
|
+
const asTransaction = !("signMessages" in this.signer || "modifyAndSignMessages" in this.signer);
|
|
10546
10880
|
this.onProgress?.(
|
|
10547
10881
|
`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.`)
|
|
10548
10882
|
);
|
|
10549
10883
|
}
|
|
10550
10884
|
const approvalStartedMs = Date.now();
|
|
10551
10885
|
const { signature, mode } = await signRelayAuthPayload(this.signer, message);
|
|
10552
|
-
if (!(this.signer
|
|
10886
|
+
if (!(0, import_kit9.isKeyPairSigner)(this.signer)) {
|
|
10553
10887
|
assertApprovalWithinFreshnessWindow(
|
|
10554
10888
|
Date.now() - approvalStartedMs,
|
|
10555
10889
|
REQUEST_AUTH_BATCH_MAX_AGE_SECONDS
|
|
@@ -10616,16 +10950,13 @@ async function transactBatch(items, options) {
|
|
|
10616
10950
|
const { proofConcurrency, submitConcurrency, ...shared } = options;
|
|
10617
10951
|
const signer = shared.depositorKeypair ? shared.depositorKeypair : (() => {
|
|
10618
10952
|
const wallet = shared.walletPublicKey ?? shared.depositorPublicKey;
|
|
10619
|
-
if (
|
|
10620
|
-
if (shared.
|
|
10621
|
-
if (shared.signAuthTransaction) {
|
|
10622
|
-
return { walletPublicKey: wallet, signAuthTransaction: shared.signAuthTransaction };
|
|
10623
|
-
}
|
|
10953
|
+
if (wallet && shared.signMessage) return messageSignerFromCallback(wallet, shared.signMessage);
|
|
10954
|
+
if (shared.signer) return shared.signer;
|
|
10624
10955
|
return null;
|
|
10625
10956
|
})();
|
|
10626
10957
|
if (!signer) {
|
|
10627
10958
|
throw new Error(
|
|
10628
|
-
"transactBatch requires an authenticated sender: pass `depositorKeypair` (a local
|
|
10959
|
+
"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."
|
|
10629
10960
|
);
|
|
10630
10961
|
}
|
|
10631
10962
|
const coordinator = createRelayBatchAuthCoordinator({
|
|
@@ -10661,8 +10992,8 @@ async function transactBatch(items, options) {
|
|
|
10661
10992
|
|
|
10662
10993
|
// src/scanning/scan.ts
|
|
10663
10994
|
var import_bs583 = __toESM(require("bs58"), 1);
|
|
10664
|
-
|
|
10665
|
-
var
|
|
10995
|
+
init_address();
|
|
10996
|
+
var import_token2 = require("@solana-program/token");
|
|
10666
10997
|
init_inputs();
|
|
10667
10998
|
init_utxo();
|
|
10668
10999
|
var bs583 = import_bs583.default.default || import_bs583.default;
|
|
@@ -10675,7 +11006,7 @@ var CHAIN_NOTES_OFFSET_TRANSACT = 1 + PROOF_LEN3 + PUBLIC_INPUTS_LEN3;
|
|
|
10675
11006
|
var CHAIN_NOTES_OFFSET_TRANSACT_SWAP = 1 + PROOF_LEN3 + PUBLIC_INPUTS_LEN3 + SWAP_PARAMS_LEN;
|
|
10676
11007
|
var PUBLIC_INPUTS_OFFSET = 1 + PROOF_LEN3;
|
|
10677
11008
|
var SWAP_OUTPUT_MINT_OFFSET = CHAIN_NOTES_OFFSET_TRANSACT;
|
|
10678
|
-
var
|
|
11009
|
+
var TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
|
|
10679
11010
|
var SOL_MINT = "So11111111111111111111111111111111111111112";
|
|
10680
11011
|
var USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
|
|
10681
11012
|
var USDT_MINT = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
|
|
@@ -10750,7 +11081,7 @@ function parseSwapOutputMint(data) {
|
|
|
10750
11081
|
const mintBytes = data.slice(SWAP_OUTPUT_MINT_OFFSET, end);
|
|
10751
11082
|
if (mintBytes.every((byte) => byte === 0)) return void 0;
|
|
10752
11083
|
try {
|
|
10753
|
-
return
|
|
11084
|
+
return addressFromBytes(mintBytes);
|
|
10754
11085
|
} catch {
|
|
10755
11086
|
return void 0;
|
|
10756
11087
|
}
|
|
@@ -10799,7 +11130,7 @@ function inferAssetMeta(meta, accountKeys, ixAccountKeyIndexes) {
|
|
|
10799
11130
|
return { mint: SOL_MINT, decimals: 9 };
|
|
10800
11131
|
}
|
|
10801
11132
|
const tokenProgramAtLayoutPos = ixAccountKeyIndexes.length > 9 ? accountKeyToBase58(accountKeys[ixAccountKeyIndexes[9]]) : void 0;
|
|
10802
|
-
const isSplTransact = tokenProgramAtLayoutPos ===
|
|
11133
|
+
const isSplTransact = tokenProgramAtLayoutPos === TOKEN_PROGRAM_ID;
|
|
10803
11134
|
if (!isSplTransact) {
|
|
10804
11135
|
return { mint: SOL_MINT, decimals: 9 };
|
|
10805
11136
|
}
|
|
@@ -10816,7 +11147,7 @@ function inferSplFeeFromTreasury(meta, accountKeys, ixAccountKeyIndexes) {
|
|
|
10816
11147
|
if (!Array.isArray(accountKeys) || !Array.isArray(ixAccountKeyIndexes)) return null;
|
|
10817
11148
|
if (ixAccountKeyIndexes.length <= 11) return null;
|
|
10818
11149
|
const tokenProgramAtLayoutPos = ixAccountKeyIndexes.length > 9 ? accountKeyToBase58(accountKeys[ixAccountKeyIndexes[9]]) : void 0;
|
|
10819
|
-
if (tokenProgramAtLayoutPos !==
|
|
11150
|
+
if (tokenProgramAtLayoutPos !== TOKEN_PROGRAM_ID) return null;
|
|
10820
11151
|
const treasuryAccountIndex = ixAccountKeyIndexes[11];
|
|
10821
11152
|
if (!Number.isInteger(treasuryAccountIndex) || treasuryAccountIndex < 0) return null;
|
|
10822
11153
|
const tokenEntries = collectTokenBalanceEntries(meta);
|
|
@@ -10840,7 +11171,7 @@ function parseSwapRecipientAta(data) {
|
|
|
10840
11171
|
const recipientAtaBytes = data.slice(recipientAtaStart, recipientAtaEnd);
|
|
10841
11172
|
if (recipientAtaBytes.every((byte) => byte === 0)) return void 0;
|
|
10842
11173
|
try {
|
|
10843
|
-
return
|
|
11174
|
+
return addressFromBytes(recipientAtaBytes);
|
|
10844
11175
|
} catch {
|
|
10845
11176
|
return void 0;
|
|
10846
11177
|
}
|
|
@@ -10907,7 +11238,7 @@ function parseTransactIxContext(data, accountKeys, ixAccountKeyIndexes, meta) {
|
|
|
10907
11238
|
}
|
|
10908
11239
|
} else if (tag === TRANSACT_TAG2 && publicAmount < 0n && Array.isArray(ixAccountKeyIndexes) && Array.isArray(accountKeys) && ixAccountKeyIndexes.length >= 8) {
|
|
10909
11240
|
const tokenProgramAtLayoutPos = ixAccountKeyIndexes.length > 9 ? accountKeyToBase58(accountKeys[ixAccountKeyIndexes[9]]) : void 0;
|
|
10910
|
-
if (tokenProgramAtLayoutPos ===
|
|
11241
|
+
if (tokenProgramAtLayoutPos === TOKEN_PROGRAM_ID && ixAccountKeyIndexes.length > 10) {
|
|
10911
11242
|
const recipientAtaIdx = ixAccountKeyIndexes[10];
|
|
10912
11243
|
if (Number.isInteger(recipientAtaIdx) && recipientAtaIdx >= 0 && recipientAtaIdx < accountKeys.length) {
|
|
10913
11244
|
recipient = accountKeyToBase58(accountKeys[recipientAtaIdx]) ?? "unknown";
|
|
@@ -11002,10 +11333,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
|
|
|
11002
11333
|
let rpcCalls = 0;
|
|
11003
11334
|
const candidates = Array.from(swapCtxByCommitment.keys());
|
|
11004
11335
|
if (candidates.length === 0) return { records, rpcCalls };
|
|
11005
|
-
const [registry] =
|
|
11006
|
-
[Buffer.from("cloak_chain_note_registry")],
|
|
11007
|
-
programId
|
|
11008
|
-
);
|
|
11336
|
+
const [registry] = await findProgramAddress(["cloak_chain_note_registry"], programId);
|
|
11009
11337
|
onStatus?.("Scanning swap note-carrier registry...");
|
|
11010
11338
|
const carrierSigs = [];
|
|
11011
11339
|
let before;
|
|
@@ -11013,7 +11341,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
|
|
|
11013
11341
|
let batch = [];
|
|
11014
11342
|
try {
|
|
11015
11343
|
batch = await withRpcRetry(
|
|
11016
|
-
() => connection
|
|
11344
|
+
() => fetchSignaturesForAddress(connection, registry, { before, limit: SIGNATURE_PAGE_SIZE })
|
|
11017
11345
|
);
|
|
11018
11346
|
} catch {
|
|
11019
11347
|
break;
|
|
@@ -11031,7 +11359,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
|
|
|
11031
11359
|
let tx = null;
|
|
11032
11360
|
try {
|
|
11033
11361
|
tx = await withRpcRetry(
|
|
11034
|
-
() => connection
|
|
11362
|
+
() => fetchTransactionJson(connection, si.signature, {
|
|
11035
11363
|
commitment: "confirmed",
|
|
11036
11364
|
maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
|
|
11037
11365
|
})
|
|
@@ -11106,7 +11434,7 @@ async function scanRecipientDeliveryNotes(opts) {
|
|
|
11106
11434
|
const viewingSecret = deriveViewingKeyFromNk(viewingKeyNk).privateKey;
|
|
11107
11435
|
const notes = [];
|
|
11108
11436
|
let rpcCalls = 0;
|
|
11109
|
-
const registry = getDeliveryRegistryPDA(programId);
|
|
11437
|
+
const registry = await getDeliveryRegistryPDA(programId);
|
|
11110
11438
|
onStatus?.("Scanning recipient-delivery registry...");
|
|
11111
11439
|
const carrierSigs = [];
|
|
11112
11440
|
let before;
|
|
@@ -11114,7 +11442,7 @@ async function scanRecipientDeliveryNotes(opts) {
|
|
|
11114
11442
|
let batch = [];
|
|
11115
11443
|
try {
|
|
11116
11444
|
batch = await withRpcRetry(
|
|
11117
|
-
() => connection
|
|
11445
|
+
() => fetchSignaturesForAddress(connection, registry, { before, limit: SIGNATURE_PAGE_SIZE })
|
|
11118
11446
|
);
|
|
11119
11447
|
} catch {
|
|
11120
11448
|
break;
|
|
@@ -11132,7 +11460,7 @@ async function scanRecipientDeliveryNotes(opts) {
|
|
|
11132
11460
|
let tx = null;
|
|
11133
11461
|
try {
|
|
11134
11462
|
tx = await withRpcRetry(
|
|
11135
|
-
() => connection
|
|
11463
|
+
() => fetchTransactionJson(connection, si.signature, {
|
|
11136
11464
|
commitment: "confirmed",
|
|
11137
11465
|
maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
|
|
11138
11466
|
})
|
|
@@ -11173,7 +11501,7 @@ async function scanRecipientDeliveryNotes(opts) {
|
|
|
11173
11501
|
});
|
|
11174
11502
|
if (recomputed.toString(16).padStart(64, "0") === parsed.commitment) {
|
|
11175
11503
|
commitmentVerified = true;
|
|
11176
|
-
matchedMint = mint
|
|
11504
|
+
matchedMint = mint;
|
|
11177
11505
|
break;
|
|
11178
11506
|
}
|
|
11179
11507
|
}
|
|
@@ -11238,7 +11566,7 @@ async function scanTransactions(opts) {
|
|
|
11238
11566
|
while (true) {
|
|
11239
11567
|
try {
|
|
11240
11568
|
rawBatch = await withRpcRetry(
|
|
11241
|
-
() => connection
|
|
11569
|
+
() => fetchSignaturesForAddress(connection, programId, {
|
|
11242
11570
|
before: beforeSig,
|
|
11243
11571
|
limit: signaturePageSize
|
|
11244
11572
|
})
|
|
@@ -11303,7 +11631,7 @@ async function scanTransactions(opts) {
|
|
|
11303
11631
|
batchSigs.map(async (sigInfo) => {
|
|
11304
11632
|
try {
|
|
11305
11633
|
return await withRpcRetry(
|
|
11306
|
-
() => connection
|
|
11634
|
+
() => fetchTransactionJson(connection, sigInfo.signature, {
|
|
11307
11635
|
commitment: "confirmed",
|
|
11308
11636
|
maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
|
|
11309
11637
|
})
|
|
@@ -11326,13 +11654,13 @@ async function scanTransactions(opts) {
|
|
|
11326
11654
|
const loadedAddresses = tx.meta?.loadedAddresses;
|
|
11327
11655
|
let accountKeys;
|
|
11328
11656
|
if (loadedAddresses) {
|
|
11329
|
-
const
|
|
11657
|
+
const writable2 = Array.isArray(loadedAddresses.writable) ? loadedAddresses.writable : [];
|
|
11330
11658
|
const readonly_ = Array.isArray(loadedAddresses.readonly) ? loadedAddresses.readonly : [];
|
|
11331
|
-
accountKeys = [...staticKeys, ...
|
|
11659
|
+
accountKeys = [...staticKeys, ...writable2, ...readonly_];
|
|
11332
11660
|
} else {
|
|
11333
11661
|
accountKeys = staticKeys;
|
|
11334
11662
|
}
|
|
11335
|
-
const programIdStr = programId
|
|
11663
|
+
const programIdStr = programId;
|
|
11336
11664
|
const allIxs = [];
|
|
11337
11665
|
const normalizeAccountIndexes = (value) => {
|
|
11338
11666
|
if (!Array.isArray(value)) return void 0;
|
|
@@ -11404,10 +11732,11 @@ async function scanTransactions(opts) {
|
|
|
11404
11732
|
const onChainAta = recipientAtaIdx >= 0 && recipientAtaIdx < accountKeys.length ? accountKeyToBase58(accountKeys[recipientAtaIdx]) : void 0;
|
|
11405
11733
|
if (onChainAta) {
|
|
11406
11734
|
try {
|
|
11407
|
-
const expectedAta = (0,
|
|
11408
|
-
|
|
11409
|
-
|
|
11410
|
-
|
|
11735
|
+
const [expectedAta] = await (0, import_token2.findAssociatedTokenPda)({
|
|
11736
|
+
mint: (0, import_kit.address)(asset.mint),
|
|
11737
|
+
owner: (0, import_kit.address)(walletPublicKey),
|
|
11738
|
+
tokenProgram: import_token2.TOKEN_PROGRAM_ADDRESS
|
|
11739
|
+
});
|
|
11411
11740
|
if (onChainAta === expectedAta) {
|
|
11412
11741
|
isOurs = true;
|
|
11413
11742
|
resolvedRecipient = walletPublicKey;
|
|
@@ -11620,7 +11949,7 @@ async function scanTransactions(opts) {
|
|
|
11620
11949
|
// deposit — that is the public deposit amount. A deposit that also merged inputs
|
|
11621
11950
|
// carries a larger output 0 and is not recoverable from public data alone.
|
|
11622
11951
|
amount: grossAmount,
|
|
11623
|
-
mintAddress:
|
|
11952
|
+
mintAddress: (0, import_kit.address)(asset.mint),
|
|
11624
11953
|
outputCommitments: ixCtx.outputCommitments ?? []
|
|
11625
11954
|
});
|
|
11626
11955
|
if (recoveredDeposit) {
|
|
@@ -11646,7 +11975,7 @@ async function scanTransactions(opts) {
|
|
|
11646
11975
|
noteSalt: compactNote.noteSalt,
|
|
11647
11976
|
amount: compactNote.outAmount0,
|
|
11648
11977
|
keypair: { privateKey: 0n, publicKey: compactNote.outPubkey0 },
|
|
11649
|
-
mintAddress:
|
|
11978
|
+
mintAddress: (0, import_kit.address)(asset.mint),
|
|
11650
11979
|
outputIndex: 0,
|
|
11651
11980
|
// v4 describes output 0, which is where change lands
|
|
11652
11981
|
outputCommitments: ixCtx.outputCommitments ?? []
|
|
@@ -11839,7 +12168,7 @@ function formatComplianceCsv(report) {
|
|
|
11839
12168
|
}
|
|
11840
12169
|
|
|
11841
12170
|
// src/wallet/utxo-wallet.ts
|
|
11842
|
-
|
|
12171
|
+
init_address();
|
|
11843
12172
|
init_utxo();
|
|
11844
12173
|
var UtxoWallet = class _UtxoWallet {
|
|
11845
12174
|
constructor(viewingKey) {
|
|
@@ -11850,7 +12179,7 @@ var UtxoWallet = class _UtxoWallet {
|
|
|
11850
12179
|
* Add a UTXO to the wallet (discovered from chain or created)
|
|
11851
12180
|
*/
|
|
11852
12181
|
addUtxo(utxo, mint = NATIVE_SOL_MINT) {
|
|
11853
|
-
const mintKey = mint
|
|
12182
|
+
const mintKey = mint;
|
|
11854
12183
|
if (!this.wallets.has(mintKey)) {
|
|
11855
12184
|
this.wallets.set(mintKey, {
|
|
11856
12185
|
mint,
|
|
@@ -11874,7 +12203,7 @@ var UtxoWallet = class _UtxoWallet {
|
|
|
11874
12203
|
* Mark a UTXO as spent
|
|
11875
12204
|
*/
|
|
11876
12205
|
markSpent(utxo, mint = NATIVE_SOL_MINT) {
|
|
11877
|
-
const wallet = this.wallets.get(mint
|
|
12206
|
+
const wallet = this.wallets.get(mint);
|
|
11878
12207
|
if (!wallet) return;
|
|
11879
12208
|
const walletUtxo = wallet.utxos.find(
|
|
11880
12209
|
(u) => u.amount === utxo.amount && u.keypair.publicKey === utxo.keypair.publicKey && u.blinding === utxo.blinding && !u.isSpent
|
|
@@ -11888,7 +12217,7 @@ var UtxoWallet = class _UtxoWallet {
|
|
|
11888
12217
|
* Get total balance (unspent only)
|
|
11889
12218
|
*/
|
|
11890
12219
|
getBalance(mint = NATIVE_SOL_MINT) {
|
|
11891
|
-
const wallet = this.wallets.get(mint
|
|
12220
|
+
const wallet = this.wallets.get(mint);
|
|
11892
12221
|
if (!wallet) return BigInt(0);
|
|
11893
12222
|
return wallet.utxos.filter((u) => !u.isSpent).reduce((sum, u) => sum + u.amount, BigInt(0));
|
|
11894
12223
|
}
|
|
@@ -11896,7 +12225,7 @@ var UtxoWallet = class _UtxoWallet {
|
|
|
11896
12225
|
* Get all unspent UTXOs
|
|
11897
12226
|
*/
|
|
11898
12227
|
getUnspentUtxos(mint = NATIVE_SOL_MINT) {
|
|
11899
|
-
const wallet = this.wallets.get(mint
|
|
12228
|
+
const wallet = this.wallets.get(mint);
|
|
11900
12229
|
if (!wallet) return [];
|
|
11901
12230
|
return wallet.utxos.filter((u) => !u.isSpent);
|
|
11902
12231
|
}
|
|
@@ -12052,7 +12381,7 @@ var UtxoWallet = class _UtxoWallet {
|
|
|
12052
12381
|
data.viewingKey ? new Uint8Array(data.viewingKey) : void 0
|
|
12053
12382
|
);
|
|
12054
12383
|
for (const w of data.wallets) {
|
|
12055
|
-
const mint =
|
|
12384
|
+
const mint = (0, import_kit.address)(w.mint);
|
|
12056
12385
|
for (const u of w.utxos) {
|
|
12057
12386
|
wallet.addUtxo({
|
|
12058
12387
|
amount: BigInt(u.amount),
|
|
@@ -12084,7 +12413,7 @@ var UtxoWallet = class _UtxoWallet {
|
|
|
12084
12413
|
* Get wallet statistics
|
|
12085
12414
|
*/
|
|
12086
12415
|
getStats(mint = NATIVE_SOL_MINT) {
|
|
12087
|
-
const wallet = this.wallets.get(mint
|
|
12416
|
+
const wallet = this.wallets.get(mint);
|
|
12088
12417
|
if (!wallet) {
|
|
12089
12418
|
return {
|
|
12090
12419
|
totalUtxos: 0,
|
|
@@ -12134,8 +12463,67 @@ var SimpleWallet = class {
|
|
|
12134
12463
|
}
|
|
12135
12464
|
};
|
|
12136
12465
|
|
|
12466
|
+
// src/index.ts
|
|
12467
|
+
init_address();
|
|
12468
|
+
|
|
12469
|
+
// src/solana/compat.ts
|
|
12470
|
+
var import_kit10 = require("@solana/kit");
|
|
12471
|
+
init_address();
|
|
12472
|
+
function addressFromPublicKey(publicKey) {
|
|
12473
|
+
return (0, import_kit.address)(publicKey.toBase58());
|
|
12474
|
+
}
|
|
12475
|
+
function signerFromKeypair(keypair) {
|
|
12476
|
+
return (0, import_kit10.createKeyPairSignerFromBytes)(keypair.secretKey);
|
|
12477
|
+
}
|
|
12478
|
+
function signerFromWalletAdapter(adapter, options = {}) {
|
|
12479
|
+
if (!adapter.publicKey) throw new Error("Wallet adapter has no public key (not connected)");
|
|
12480
|
+
const walletAddress = addressFromPublicKey(adapter.publicKey);
|
|
12481
|
+
const signer = {
|
|
12482
|
+
address: walletAddress,
|
|
12483
|
+
async modifyAndSignTransactions(transactions) {
|
|
12484
|
+
if (!adapter.signTransaction) throw new Error("Wallet adapter cannot sign transactions");
|
|
12485
|
+
const web3 = options.web3 ?? await loadWeb3();
|
|
12486
|
+
const out = [];
|
|
12487
|
+
for (const transaction of transactions) {
|
|
12488
|
+
const legacy = web3.VersionedTransaction.deserialize(transactionBytes(transaction));
|
|
12489
|
+
const signed = await adapter.signTransaction(legacy);
|
|
12490
|
+
const decoded = transactionFromBytes(signed.serialize());
|
|
12491
|
+
out.push({ ...transaction, ...decoded });
|
|
12492
|
+
}
|
|
12493
|
+
return out;
|
|
12494
|
+
}
|
|
12495
|
+
};
|
|
12496
|
+
if (adapter.signMessage) {
|
|
12497
|
+
const signMessage = adapter.signMessage.bind(adapter);
|
|
12498
|
+
Object.assign(signer, {
|
|
12499
|
+
async signMessages(messages) {
|
|
12500
|
+
const dictionaries = [];
|
|
12501
|
+
for (const message of messages) {
|
|
12502
|
+
const signature = await signMessage(message.content);
|
|
12503
|
+
dictionaries.push({ [walletAddress]: signature });
|
|
12504
|
+
}
|
|
12505
|
+
return dictionaries;
|
|
12506
|
+
}
|
|
12507
|
+
});
|
|
12508
|
+
}
|
|
12509
|
+
return signer;
|
|
12510
|
+
}
|
|
12511
|
+
async function loadWeb3() {
|
|
12512
|
+
const name = "@solana/web3.js";
|
|
12513
|
+
try {
|
|
12514
|
+
return await import(
|
|
12515
|
+
/* webpackIgnore: true */
|
|
12516
|
+
name
|
|
12517
|
+
);
|
|
12518
|
+
} catch {
|
|
12519
|
+
throw new Error(
|
|
12520
|
+
"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"
|
|
12521
|
+
);
|
|
12522
|
+
}
|
|
12523
|
+
}
|
|
12524
|
+
|
|
12137
12525
|
// src/bridge/rail-verify.ts
|
|
12138
|
-
var
|
|
12526
|
+
var import_tweetnacl6 = __toESM(require("tweetnacl"), 1);
|
|
12139
12527
|
var import_sha256 = require("@noble/hashes/sha256");
|
|
12140
12528
|
var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
|
|
12141
12529
|
var b58 = /* @__PURE__ */ (() => {
|
|
@@ -12246,7 +12634,7 @@ function verifyQuoteSignature(resp) {
|
|
|
12246
12634
|
const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
|
|
12247
12635
|
const sig = resp.signature.replace(/^ed25519:/, "");
|
|
12248
12636
|
try {
|
|
12249
|
-
return { valid:
|
|
12637
|
+
return { valid: import_tweetnacl6.default.sign.detached.verify(message, b58.decode(sig), b58.decode(ONECLICK_PUBKEY_B58)) };
|
|
12250
12638
|
} catch (e) {
|
|
12251
12639
|
return { valid: false, reason: e instanceof Error ? e.message : String(e) };
|
|
12252
12640
|
}
|
|
@@ -12344,58 +12732,63 @@ function cloakBridgeRail(relayUrl) {
|
|
|
12344
12732
|
}
|
|
12345
12733
|
|
|
12346
12734
|
// src/bridge/paymaster-client.ts
|
|
12347
|
-
var
|
|
12348
|
-
var
|
|
12349
|
-
|
|
12350
|
-
|
|
12735
|
+
var import_kit11 = require("@solana/kit");
|
|
12736
|
+
var import_system3 = require("@solana-program/system");
|
|
12737
|
+
var import_token3 = require("@solana-program/token");
|
|
12738
|
+
init_address();
|
|
12739
|
+
async function validatePaymasterTopUpTransaction(tx, expect) {
|
|
12740
|
+
const compiledMessage = (0, import_kit11.getCompiledTransactionMessageDecoder)().decode(tx.messageBytes);
|
|
12741
|
+
const ixs = (0, import_kit11.getInstructionsFromCompiledTransactionMessage)(compiledMessage);
|
|
12351
12742
|
if (ixs.length !== 1 && ixs.length !== 2) {
|
|
12352
12743
|
throw new Error(
|
|
12353
12744
|
`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`
|
|
12354
12745
|
);
|
|
12355
12746
|
}
|
|
12356
12747
|
const ix0 = ixs[0];
|
|
12357
|
-
if (
|
|
12748
|
+
if (ix0.programAddress !== import_system.SYSTEM_PROGRAM_ADDRESS) {
|
|
12358
12749
|
throw new Error(
|
|
12359
|
-
`paymaster top-up instruction 0 is owned by ${ix0.
|
|
12750
|
+
`paymaster top-up instruction 0 is owned by ${ix0.programAddress}, not the System Program \u2014 refusing to sign an unrecognised first instruction`
|
|
12360
12751
|
);
|
|
12361
12752
|
}
|
|
12362
|
-
const transfer2 =
|
|
12363
|
-
|
|
12753
|
+
const transfer2 = (0, import_system3.parseTransferSolInstruction)(
|
|
12754
|
+
ix0
|
|
12755
|
+
);
|
|
12756
|
+
if (transfer2.accounts.destination.address !== expect.recipient) {
|
|
12364
12757
|
throw new Error(
|
|
12365
|
-
`paymaster top-up sends SOL to ${transfer2.
|
|
12758
|
+
`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`
|
|
12366
12759
|
);
|
|
12367
12760
|
}
|
|
12368
|
-
if (
|
|
12761
|
+
if (transfer2.data.amount > expect.maxGrantLamports) {
|
|
12369
12762
|
throw new Error(
|
|
12370
|
-
`paymaster top-up grants ${transfer2.
|
|
12763
|
+
`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`
|
|
12371
12764
|
);
|
|
12372
12765
|
}
|
|
12373
12766
|
if (ixs.length === 1) return;
|
|
12374
12767
|
const ix1 = ixs[1];
|
|
12375
|
-
if (
|
|
12768
|
+
if (ix1.programAddress !== import_token3.TOKEN_PROGRAM_ADDRESS) {
|
|
12376
12769
|
throw new Error(
|
|
12377
|
-
`paymaster top-up instruction 1 is owned by ${ix1.
|
|
12770
|
+
`paymaster top-up instruction 1 is owned by ${ix1.programAddress}, not the SPL Token program \u2014 refusing to sign an unrecognised second instruction`
|
|
12378
12771
|
);
|
|
12379
12772
|
}
|
|
12380
|
-
const spl = (0,
|
|
12381
|
-
const authority = spl.
|
|
12382
|
-
if (
|
|
12773
|
+
const spl = (0, import_token3.parseTransferInstruction)(ix1);
|
|
12774
|
+
const authority = spl.accounts.authority.address;
|
|
12775
|
+
if (authority !== expect.recipient) {
|
|
12383
12776
|
throw new Error(
|
|
12384
|
-
`paymaster top-up's fee transfer is authorised by ${authority
|
|
12777
|
+
`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`
|
|
12385
12778
|
);
|
|
12386
12779
|
}
|
|
12387
|
-
const expectedDestination = (0,
|
|
12388
|
-
expect.feeMint,
|
|
12389
|
-
expect.paymentAddress,
|
|
12390
|
-
|
|
12391
|
-
);
|
|
12392
|
-
const destination = spl.
|
|
12393
|
-
if (
|
|
12780
|
+
const [expectedDestination] = await (0, import_token3.findAssociatedTokenPda)({
|
|
12781
|
+
mint: expect.feeMint,
|
|
12782
|
+
owner: expect.paymentAddress,
|
|
12783
|
+
tokenProgram: import_token3.TOKEN_PROGRAM_ADDRESS
|
|
12784
|
+
});
|
|
12785
|
+
const destination = spl.accounts.destination.address;
|
|
12786
|
+
if (destination !== expectedDestination) {
|
|
12394
12787
|
throw new Error(
|
|
12395
|
-
`paymaster top-up's fee transfer is addressed to ${destination
|
|
12788
|
+
`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`
|
|
12396
12789
|
);
|
|
12397
12790
|
}
|
|
12398
|
-
const paidAmount =
|
|
12791
|
+
const paidAmount = spl.data.amount;
|
|
12399
12792
|
if (paidAmount !== expect.feeTokenAmount) {
|
|
12400
12793
|
throw new Error(
|
|
12401
12794
|
`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`
|
|
@@ -12428,7 +12821,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
12428
12821
|
method: "POST",
|
|
12429
12822
|
headers: { "Content-Type": "application/json" },
|
|
12430
12823
|
body: JSON.stringify({
|
|
12431
|
-
recipient: receiver.
|
|
12824
|
+
recipient: receiver.address,
|
|
12432
12825
|
grant_lamports: Number(grantLamports)
|
|
12433
12826
|
})
|
|
12434
12827
|
});
|
|
@@ -12438,29 +12831,29 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
12438
12831
|
"paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
|
|
12439
12832
|
);
|
|
12440
12833
|
}
|
|
12441
|
-
const feeMint =
|
|
12442
|
-
const paymentAddress =
|
|
12834
|
+
const feeMint = (0, import_kit.address)(prepared.fee_mint);
|
|
12835
|
+
const paymentAddress = (0, import_kit.address)(prepared.payment_address);
|
|
12443
12836
|
const feeTokenAmount = BigInt(prepared.fee_token_amount);
|
|
12444
|
-
const tx =
|
|
12445
|
-
validatePaymasterTopUpTransaction(tx, {
|
|
12446
|
-
recipient: receiver.
|
|
12837
|
+
const tx = transactionFromBytes(base64ToBytes(prepared.transaction));
|
|
12838
|
+
await validatePaymasterTopUpTransaction(tx, {
|
|
12839
|
+
recipient: receiver.address,
|
|
12447
12840
|
maxGrantLamports: grantLamports,
|
|
12448
12841
|
feeMint,
|
|
12449
12842
|
feeTokenAmount,
|
|
12450
12843
|
paymentAddress
|
|
12451
12844
|
});
|
|
12452
|
-
|
|
12845
|
+
const partiallySigned = await signCompiledTransaction(receiver, tx);
|
|
12453
12846
|
const cosignRes = await relayFetch(`${relayUrl}/bridge/paymaster/cosign`, {
|
|
12454
12847
|
method: "POST",
|
|
12455
12848
|
headers: { "Content-Type": "application/json" },
|
|
12456
12849
|
body: JSON.stringify({
|
|
12457
|
-
transaction:
|
|
12850
|
+
transaction: bytesToBase64(transactionBytes(partiallySigned)),
|
|
12458
12851
|
voucher: prepared.voucher
|
|
12459
12852
|
})
|
|
12460
12853
|
});
|
|
12461
12854
|
const cosigned = await parseBridgeResponse2(cosignRes, "paymaster cosign");
|
|
12462
12855
|
return {
|
|
12463
|
-
transaction:
|
|
12856
|
+
transaction: transactionFromBytes(base64ToBytes(cosigned.transaction)),
|
|
12464
12857
|
feeTokenAmount,
|
|
12465
12858
|
feeMint: prepared.fee_mint,
|
|
12466
12859
|
paymentAddress: prepared.payment_address
|
|
@@ -12468,12 +12861,11 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
12468
12861
|
}
|
|
12469
12862
|
|
|
12470
12863
|
// src/bridge/derive.ts
|
|
12471
|
-
var import_web316 = require("@solana/web3.js");
|
|
12472
12864
|
var import_hmac = require("@noble/hashes/hmac");
|
|
12473
12865
|
var import_sha512 = require("@noble/hashes/sha512");
|
|
12474
12866
|
var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
|
|
12475
12867
|
var MAX_RECEIVER_INDEX = 1e4;
|
|
12476
|
-
function deriveBridgeReceiver(nk, index) {
|
|
12868
|
+
async function deriveBridgeReceiver(nk, index) {
|
|
12477
12869
|
if (!Number.isInteger(index) || index < 0) {
|
|
12478
12870
|
throw new Error(`index must be a non-negative integer, got ${index}`);
|
|
12479
12871
|
}
|
|
@@ -12483,54 +12875,56 @@ function deriveBridgeReceiver(nk, index) {
|
|
|
12483
12875
|
);
|
|
12484
12876
|
}
|
|
12485
12877
|
const h = (0, import_hmac.hmac)(import_sha512.sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
|
|
12486
|
-
return
|
|
12878
|
+
return signerFromSecretKey(h.slice(0, 32));
|
|
12487
12879
|
}
|
|
12488
12880
|
|
|
12489
12881
|
// src/bridge/discover.ts
|
|
12490
|
-
var
|
|
12491
|
-
var
|
|
12882
|
+
var import_kit12 = require("@solana/kit");
|
|
12883
|
+
var import_token4 = require("@solana-program/token");
|
|
12492
12884
|
function describeError(err) {
|
|
12493
12885
|
return err instanceof Error ? err.message : String(err);
|
|
12494
12886
|
}
|
|
12495
|
-
async function listBridgeDeposits(
|
|
12887
|
+
async function listBridgeDeposits(rpc, nk, opts) {
|
|
12496
12888
|
const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
|
|
12497
12889
|
const stopAfterUnused = opts.stopAfterUnused ?? 5;
|
|
12498
12890
|
const out = [];
|
|
12499
12891
|
let consecutiveUnused = 0;
|
|
12500
12892
|
for (let index = 0; index < scanDepth; index++) {
|
|
12501
|
-
const kp = deriveBridgeReceiver(nk, index);
|
|
12502
|
-
const receiver = kp.
|
|
12503
|
-
const tokenAccount = (0,
|
|
12893
|
+
const kp = await deriveBridgeReceiver(nk, index);
|
|
12894
|
+
const receiver = kp.address;
|
|
12895
|
+
const [tokenAccount] = await (0, import_token4.findAssociatedTokenPda)({
|
|
12896
|
+
mint: opts.mint,
|
|
12897
|
+
owner: receiver,
|
|
12898
|
+
tokenProgram: import_token4.TOKEN_PROGRAM_ADDRESS
|
|
12899
|
+
});
|
|
12504
12900
|
try {
|
|
12505
|
-
const [recvInfo, ataInfo] = await
|
|
12506
|
-
const lamports = recvInfo?.lamports ??
|
|
12901
|
+
const [recvInfo, ataInfo] = await fetchMultipleAccountBytes(rpc, [receiver, tokenAccount]);
|
|
12902
|
+
const lamports = recvInfo?.lamports ?? 0n;
|
|
12507
12903
|
let tokenBalance = 0n;
|
|
12508
12904
|
if (ataInfo) {
|
|
12509
12905
|
try {
|
|
12510
|
-
tokenBalance = BigInt((await
|
|
12906
|
+
tokenBalance = BigInt((await rpc.getTokenAccountBalance(tokenAccount).send()).value.amount);
|
|
12511
12907
|
} catch (err) {
|
|
12512
|
-
if (!(
|
|
12908
|
+
if (!((0, import_kit12.isSolanaError)(err) && /could not find account/i.test(err.message))) {
|
|
12513
12909
|
throw err;
|
|
12514
12910
|
}
|
|
12515
12911
|
}
|
|
12516
12912
|
}
|
|
12517
|
-
if (lamports ===
|
|
12913
|
+
if (lamports === 0n && !ataInfo) {
|
|
12518
12914
|
consecutiveUnused++;
|
|
12519
12915
|
if (consecutiveUnused >= stopAfterUnused) break;
|
|
12520
12916
|
continue;
|
|
12521
12917
|
}
|
|
12522
12918
|
consecutiveUnused = 0;
|
|
12523
12919
|
const shieldSignatures = [];
|
|
12524
|
-
const sigs = await
|
|
12920
|
+
const sigs = await fetchSignaturesForAddress(rpc, receiver, { limit: 20 });
|
|
12525
12921
|
for (const s of sigs) {
|
|
12526
12922
|
if (s.err) continue;
|
|
12527
|
-
const tx = await
|
|
12923
|
+
const tx = await fetchParsedTransaction(rpc, s.signature, {
|
|
12528
12924
|
maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
|
|
12529
12925
|
});
|
|
12530
|
-
const keys = tx?.transaction.message.
|
|
12531
|
-
|
|
12532
|
-
});
|
|
12533
|
-
if (keys && [...Array(keys.length).keys()].some((i) => keys.get(i)?.equals(opts.programId))) {
|
|
12926
|
+
const keys = tx?.transaction.message.accountKeys;
|
|
12927
|
+
if (keys && keys.some((k) => k.pubkey === opts.programId)) {
|
|
12534
12928
|
shieldSignatures.push(s.signature);
|
|
12535
12929
|
}
|
|
12536
12930
|
}
|
|
@@ -12557,7 +12951,7 @@ async function listBridgeDeposits(conn, nk, opts) {
|
|
|
12557
12951
|
tokenAccount,
|
|
12558
12952
|
state: "unknown",
|
|
12559
12953
|
tokenBalance: 0n,
|
|
12560
|
-
lamports:
|
|
12954
|
+
lamports: 0n,
|
|
12561
12955
|
error: describeError(err)
|
|
12562
12956
|
});
|
|
12563
12957
|
}
|
|
@@ -12566,34 +12960,38 @@ async function listBridgeDeposits(conn, nk, opts) {
|
|
|
12566
12960
|
}
|
|
12567
12961
|
|
|
12568
12962
|
// src/bridge/deposit-core.ts
|
|
12569
|
-
var
|
|
12570
|
-
var
|
|
12963
|
+
var import_kit13 = require("@solana/kit");
|
|
12964
|
+
var import_system4 = require("@solana-program/system");
|
|
12571
12965
|
init_utxo();
|
|
12572
12966
|
|
|
12573
12967
|
// src/bridge/funder.ts
|
|
12574
|
-
var
|
|
12575
|
-
|
|
12968
|
+
var import_token5 = require("@solana-program/token");
|
|
12969
|
+
init_address();
|
|
12576
12970
|
var MAINNET_RENT_0 = 890880;
|
|
12577
12971
|
var MAINNET_RENT_1 = 897840;
|
|
12578
12972
|
var FEE_BUDGET = 13e4;
|
|
12579
12973
|
var CLEANUP_FEE_BUDGET = 5e3;
|
|
12580
|
-
|
|
12581
|
-
|
|
12582
|
-
|
|
12583
|
-
|
|
12584
|
-
|
|
12974
|
+
async function pda(seeds, programId) {
|
|
12975
|
+
const [address2] = await findProgramAddress(seeds, programId);
|
|
12976
|
+
return address2;
|
|
12977
|
+
}
|
|
12978
|
+
async function deriveFundingTargets(d) {
|
|
12979
|
+
const pool = await pda(["pool", addressBytes(d.mint)], d.programId);
|
|
12980
|
+
const poolBytes = addressBytes(pool);
|
|
12981
|
+
const [nullifier0, nullifier1, riskNonce, [depositorAta]] = await Promise.all([
|
|
12585
12982
|
// program: NullifierAccount::derive_pda_with_pool -> [b"nullifier", pool, nullifier]
|
|
12586
|
-
|
|
12587
|
-
|
|
12983
|
+
pda(["nullifier", poolBytes, d.nullifiers[0]], d.programId),
|
|
12984
|
+
pda(["nullifier", poolBytes, d.nullifiers[1]], d.programId),
|
|
12588
12985
|
// relay: derive_risk_nonce_pda -> [b"risk_nonce", bind0]
|
|
12589
|
-
|
|
12590
|
-
|
|
12591
|
-
|
|
12986
|
+
pda(["risk_nonce", d.bind0], d.programId),
|
|
12987
|
+
(0, import_token5.findAssociatedTokenPda)({ mint: d.mint, owner: d.depositor, tokenProgram: import_token5.TOKEN_PROGRAM_ADDRESS })
|
|
12988
|
+
]);
|
|
12989
|
+
return { pool, nullifier0, nullifier1, riskNonce, depositorAta };
|
|
12592
12990
|
}
|
|
12593
|
-
async function readRent(
|
|
12991
|
+
async function readRent(rpc) {
|
|
12594
12992
|
const [zero, one] = await Promise.all([
|
|
12595
|
-
|
|
12596
|
-
|
|
12993
|
+
rpc.getMinimumBalanceForRentExemption(0n).send(),
|
|
12994
|
+
rpc.getMinimumBalanceForRentExemption(1n).send()
|
|
12597
12995
|
]);
|
|
12598
12996
|
return { zero, one };
|
|
12599
12997
|
}
|
|
@@ -12607,7 +13005,66 @@ var DepositError = class extends Error {
|
|
|
12607
13005
|
this.name = "DepositError";
|
|
12608
13006
|
}
|
|
12609
13007
|
};
|
|
12610
|
-
async function
|
|
13008
|
+
async function resolveLoadedAddresses(rpc, compiled) {
|
|
13009
|
+
const lookups = compiled.addressTableLookups ?? [];
|
|
13010
|
+
if (lookups.length === 0) return { writable: [], readonly: [] };
|
|
13011
|
+
const tables = await fetchLookupTables(rpc, lookups.map((l) => l.lookupTableAddress));
|
|
13012
|
+
const writable2 = [];
|
|
13013
|
+
const readonly2 = [];
|
|
13014
|
+
lookups.forEach((lookup, i) => {
|
|
13015
|
+
const addresses = tables[i].addresses;
|
|
13016
|
+
for (const idx of lookup.writableIndexes) writable2.push(addresses[idx]);
|
|
13017
|
+
for (const idx of lookup.readonlyIndexes) readonly2.push(addresses[idx]);
|
|
13018
|
+
});
|
|
13019
|
+
return { writable: writable2, readonly: readonly2 };
|
|
13020
|
+
}
|
|
13021
|
+
function makeDepositSigner(params) {
|
|
13022
|
+
const { rpc, R, funder, programId, log, state } = params;
|
|
13023
|
+
return {
|
|
13024
|
+
address: R.address,
|
|
13025
|
+
signMessages: (messages) => R.signMessages(messages),
|
|
13026
|
+
async signTransactions(transactions) {
|
|
13027
|
+
const out = [];
|
|
13028
|
+
for (const tx of transactions) {
|
|
13029
|
+
state.measuredSize = transactionBytes(tx).length;
|
|
13030
|
+
const compiled = (0, import_kit13.getCompiledTransactionMessageDecoder)().decode(tx.messageBytes);
|
|
13031
|
+
const loadedAddresses = await resolveLoadedAddresses(rpc, compiled);
|
|
13032
|
+
const instructions = (0, import_kit13.getInstructionsFromCompiledTransactionMessage)(compiled, loadedAddresses);
|
|
13033
|
+
const transactIx = instructions.find((i) => i.programAddress === programId);
|
|
13034
|
+
if (!transactIx || !transactIx.accounts) {
|
|
13035
|
+
throw new Error(
|
|
13036
|
+
"deposit transaction has no instruction for the Cloak program \u2014 cannot locate the accounts the funding seam needs to fund"
|
|
13037
|
+
);
|
|
13038
|
+
}
|
|
13039
|
+
const at = (n) => transactIx.accounts[n].address;
|
|
13040
|
+
const targets = [
|
|
13041
|
+
{ a: at(12), need: MAINNET_RENT_0, name: "risk_nonce" },
|
|
13042
|
+
{ a: at(4), need: MAINNET_RENT_1, name: "nullifier_0" },
|
|
13043
|
+
{ a: at(5), need: MAINNET_RENT_1, name: "nullifier_1" }
|
|
13044
|
+
];
|
|
13045
|
+
const infos = await fetchMultipleAccountBytes(rpc, targets.map((t) => t.a));
|
|
13046
|
+
state.fundedAccounts = targets.map((t, i) => ({
|
|
13047
|
+
name: t.name,
|
|
13048
|
+
address: t.a,
|
|
13049
|
+
lamportsSent: Math.max(0, t.need - Number(infos[i]?.lamports ?? 0n))
|
|
13050
|
+
}));
|
|
13051
|
+
const fundingInstructions = targets.flatMap((t, i) => {
|
|
13052
|
+
const held = infos[i]?.lamports ?? 0n;
|
|
13053
|
+
const need = BigInt(t.need);
|
|
13054
|
+
return held >= need ? [] : [(0, import_system4.getTransferSolInstruction)({ source: funder, destination: t.a, amount: need - held })];
|
|
13055
|
+
});
|
|
13056
|
+
if (fundingInstructions.length > 0) {
|
|
13057
|
+
const sig = await sendInstructions(rpc, funder, fundingInstructions);
|
|
13058
|
+
log(` seam: funded ${fundingInstructions.length} program accounts read off the built tx \u2014 ${sig.slice(0, 16)}\u2026`);
|
|
13059
|
+
}
|
|
13060
|
+
const [signatures] = await R.signTransactions([tx]);
|
|
13061
|
+
out.push(signatures);
|
|
13062
|
+
}
|
|
13063
|
+
return out;
|
|
13064
|
+
}
|
|
13065
|
+
};
|
|
13066
|
+
}
|
|
13067
|
+
async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log, grantOverride, opts) {
|
|
12611
13068
|
if (!opts.noteSpendKey || opts.noteSpendKey.length !== 32) {
|
|
12612
13069
|
throw new Error(
|
|
12613
13070
|
"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."
|
|
@@ -12628,77 +13085,43 @@ async function depositFromDerivedKey(conn, R, funder, amount, log = console.log,
|
|
|
12628
13085
|
"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."
|
|
12629
13086
|
);
|
|
12630
13087
|
}
|
|
12631
|
-
assertAllowedRpcConnection(
|
|
13088
|
+
assertAllowedRpcConnection(rpc);
|
|
12632
13089
|
const relayUrl = opts.relayUrl;
|
|
12633
13090
|
const programId = opts.programId;
|
|
12634
13091
|
const mint = opts.mint;
|
|
12635
13092
|
setCircuitsPath(resolveCircuitsBase());
|
|
12636
|
-
const grantR = grantOverride ?? MAINNET_RENT_0 + FEE_BUDGET + CLEANUP_FEE_BUDGET;
|
|
12637
|
-
const heldByR = await
|
|
13093
|
+
const grantR = BigInt(grantOverride ?? MAINNET_RENT_0 + FEE_BUDGET + CLEANUP_FEE_BUDGET);
|
|
13094
|
+
const heldByR = (await rpc.getBalance(R.address).send()).value;
|
|
12638
13095
|
if (heldByR >= grantR) {
|
|
12639
13096
|
log(` R already holds ${heldByR} (>= ${grantR}) \u2014 no top-up needed`);
|
|
12640
13097
|
} else {
|
|
12641
|
-
|
|
12642
|
-
|
|
12643
|
-
|
|
12644
|
-
|
|
12645
|
-
|
|
12646
|
-
|
|
12647
|
-
|
|
12648
|
-
const
|
|
12649
|
-
|
|
12650
|
-
measuredSize = tx.serialize().length;
|
|
12651
|
-
const alts = await Promise.all(
|
|
12652
|
-
tx.message.addressTableLookups.map(async (l) => (await conn.getAddressLookupTable(l.accountKey)).value)
|
|
12653
|
-
);
|
|
12654
|
-
const keys = tx.message.getAccountKeys({ addressLookupTableAccounts: alts });
|
|
12655
|
-
const ix = tx.message.compiledInstructions.find((i) => keys.get(i.programIdIndex).equals(programId));
|
|
12656
|
-
const at = (n) => keys.get(ix.accountKeyIndexes[n]);
|
|
12657
|
-
const targets = [
|
|
12658
|
-
{ a: at(12), need: MAINNET_RENT_0, name: "risk_nonce" },
|
|
12659
|
-
{ a: at(4), need: MAINNET_RENT_1, name: "nullifier_0" },
|
|
12660
|
-
{ a: at(5), need: MAINNET_RENT_1, name: "nullifier_1" }
|
|
12661
|
-
];
|
|
12662
|
-
const infos = await conn.getMultipleAccountsInfo(targets.map((t) => t.a));
|
|
12663
|
-
fundedAccounts = targets.map((t, i) => ({
|
|
12664
|
-
name: t.name,
|
|
12665
|
-
address: t.a.toBase58(),
|
|
12666
|
-
lamportsSent: Math.max(0, t.need - (infos[i]?.lamports ?? 0))
|
|
12667
|
-
}));
|
|
12668
|
-
const ixs = targets.flatMap((t, i) => (infos[i]?.lamports ?? 0) >= t.need ? [] : [import_web319.SystemProgram.transfer({
|
|
12669
|
-
fromPubkey: funder.publicKey,
|
|
12670
|
-
toPubkey: t.a,
|
|
12671
|
-
lamports: t.need - (infos[i]?.lamports ?? 0)
|
|
12672
|
-
})]);
|
|
12673
|
-
if (ixs.length) {
|
|
12674
|
-
const sig = await (0, import_web319.sendAndConfirmTransaction)(conn, new import_web319.Transaction().add(...ixs), [funder]);
|
|
12675
|
-
log(` seam: funded ${ixs.length} program accounts read off the built tx \u2014 ${sig.slice(0, 16)}\u2026`);
|
|
12676
|
-
}
|
|
12677
|
-
tx.sign([R]);
|
|
12678
|
-
return tx;
|
|
12679
|
-
}
|
|
12680
|
-
tx.partialSign(R);
|
|
12681
|
-
return tx;
|
|
12682
|
-
};
|
|
12683
|
-
const signMessage = async (m) => import_tweetnacl8.default.sign.detached(m, R.secretKey);
|
|
13098
|
+
const topUp = grantR - heldByR;
|
|
13099
|
+
await sendInstructions(rpc, funder, [
|
|
13100
|
+
(0, import_system4.getTransferSolInstruction)({ source: funder, destination: R.address, amount: topUp })
|
|
13101
|
+
]);
|
|
13102
|
+
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"}`);
|
|
13103
|
+
}
|
|
13104
|
+
const state = { measuredSize: -1, fundedAccounts: [] };
|
|
13105
|
+
const depositSigner = makeDepositSigner({ rpc, R, funder, programId, log, state });
|
|
13106
|
+
const signMessage = (m) => signMessageBytes(R, m);
|
|
12684
13107
|
const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
|
|
12685
13108
|
const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
|
|
12686
13109
|
const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
|
|
12687
13110
|
const zeroInput = await createZeroUtxo(mint);
|
|
12688
|
-
const rBefore = await
|
|
13111
|
+
const rBefore = (await rpc.getBalance(R.address).send()).value;
|
|
12689
13112
|
let result;
|
|
12690
13113
|
try {
|
|
12691
13114
|
result = await transact(
|
|
12692
|
-
{ inputUtxos: [zeroInput], outputUtxos: [utxo], externalAmount: amount, depositor: R.
|
|
13115
|
+
{ inputUtxos: [zeroInput], outputUtxos: [utxo], externalAmount: amount, depositor: R.address },
|
|
12693
13116
|
{
|
|
12694
|
-
connection:
|
|
13117
|
+
connection: rpc,
|
|
12695
13118
|
programId,
|
|
12696
13119
|
relayUrl,
|
|
12697
|
-
// NO depositorKeypair: the SDK branches `if (
|
|
12698
|
-
// (transact.ts
|
|
12699
|
-
depositorPublicKey: R.
|
|
12700
|
-
walletPublicKey: R.
|
|
12701
|
-
|
|
13120
|
+
// NO depositorKeypair: the SDK branches `if (depositorKeypair) … else if (signer)`
|
|
13121
|
+
// (transact.ts), so passing one silently skips the funding seam.
|
|
13122
|
+
depositorPublicKey: R.address,
|
|
13123
|
+
walletPublicKey: R.address,
|
|
13124
|
+
signer: depositSigner,
|
|
12702
13125
|
signMessage,
|
|
12703
13126
|
chainNoteViewingKeyNk: nk,
|
|
12704
13127
|
chainNoteSalt: noteSalt,
|
|
@@ -12708,78 +13131,84 @@ async function depositFromDerivedKey(conn, R, funder, amount, log = console.log,
|
|
|
12708
13131
|
);
|
|
12709
13132
|
} catch (e) {
|
|
12710
13133
|
const msg = e instanceof Error ? e.message : String(e);
|
|
12711
|
-
throw new DepositError(msg, fundedAccounts, measuredSize);
|
|
13134
|
+
throw new DepositError(msg, state.fundedAccounts, state.measuredSize);
|
|
12712
13135
|
}
|
|
12713
|
-
const rAfter = await
|
|
13136
|
+
const rAfter = (await rpc.getBalance(R.address).send()).value;
|
|
12714
13137
|
const noteIndex = result.outputUtxos[0].index;
|
|
12715
13138
|
if (noteIndex === void 0) throw new Error("deposit landed but the note has no index \u2014 it cannot be discovered later");
|
|
12716
13139
|
return {
|
|
12717
13140
|
signature: result.signature,
|
|
12718
13141
|
noteIndex,
|
|
12719
13142
|
amount: result.outputUtxos[0].amount,
|
|
12720
|
-
txSize: measuredSize,
|
|
12721
|
-
rBefore,
|
|
12722
|
-
rAfter,
|
|
12723
|
-
rentExempt: rAfter >= MAINNET_RENT_0,
|
|
13143
|
+
txSize: state.measuredSize,
|
|
13144
|
+
rBefore: Number(rBefore),
|
|
13145
|
+
rAfter: Number(rAfter),
|
|
13146
|
+
rentExempt: rAfter >= BigInt(MAINNET_RENT_0),
|
|
12724
13147
|
inputNullifiers: result.inputNullifiers,
|
|
12725
|
-
fundedAccounts
|
|
13148
|
+
fundedAccounts: state.fundedAccounts
|
|
12726
13149
|
};
|
|
12727
13150
|
}
|
|
12728
13151
|
|
|
12729
13152
|
// src/bridge/cleanup.ts
|
|
12730
|
-
var
|
|
12731
|
-
|
|
12732
|
-
var DEFAULT_MINT =
|
|
12733
|
-
async function cleanupReceivingAddress(
|
|
12734
|
-
assertAllowedRpcConnection(
|
|
12735
|
-
const rAta = (0,
|
|
12736
|
-
const info = await
|
|
13153
|
+
var import_token6 = require("@solana-program/token");
|
|
13154
|
+
init_address();
|
|
13155
|
+
var DEFAULT_MINT = (0, import_kit.address)("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
|
|
13156
|
+
async function cleanupReceivingAddress(rpc, R, dustDestination, mint = DEFAULT_MINT) {
|
|
13157
|
+
assertAllowedRpcConnection(rpc);
|
|
13158
|
+
const [rAta] = await (0, import_token6.findAssociatedTokenPda)({ mint, owner: R.address, tokenProgram: import_token6.TOKEN_PROGRAM_ADDRESS });
|
|
13159
|
+
const info = await fetchAccountBytes(rpc, rAta);
|
|
12737
13160
|
if (!info) {
|
|
12738
13161
|
return {
|
|
12739
13162
|
closed: false,
|
|
12740
13163
|
dustSwept: 0n,
|
|
12741
|
-
rentReturned:
|
|
13164
|
+
rentReturned: 0n,
|
|
12742
13165
|
destination: null,
|
|
12743
13166
|
signature: null,
|
|
12744
13167
|
note: "no token account \u2014 nothing to recover"
|
|
12745
13168
|
};
|
|
12746
13169
|
}
|
|
12747
|
-
const bal = BigInt((await
|
|
13170
|
+
const bal = BigInt((await rpc.getTokenAccountBalance(rAta).send()).value.amount);
|
|
12748
13171
|
const rentHeld = info.lamports;
|
|
12749
|
-
const before = await
|
|
13172
|
+
const before = (await rpc.getBalance(R.address).send()).value;
|
|
12750
13173
|
const ixs = [];
|
|
12751
13174
|
let destination = null;
|
|
12752
13175
|
if (bal > 0n && !dustDestination) {
|
|
12753
13176
|
return {
|
|
12754
13177
|
closed: false,
|
|
12755
13178
|
dustSwept: 0n,
|
|
12756
|
-
rentReturned:
|
|
13179
|
+
rentReturned: 0n,
|
|
12757
13180
|
destination: null,
|
|
12758
13181
|
signature: null,
|
|
12759
13182
|
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`
|
|
12760
13183
|
};
|
|
12761
13184
|
}
|
|
12762
13185
|
if (bal > 0n && dustDestination) {
|
|
12763
|
-
const destAta = (0,
|
|
12764
|
-
const destInfo = await
|
|
13186
|
+
const [destAta] = await (0, import_token6.findAssociatedTokenPda)({ mint, owner: dustDestination, tokenProgram: import_token6.TOKEN_PROGRAM_ADDRESS });
|
|
13187
|
+
const destInfo = await fetchAccountBytes(rpc, destAta);
|
|
12765
13188
|
if (!destInfo) {
|
|
12766
|
-
const ataRent = await (0,
|
|
12767
|
-
if (before < ataRent + CLEANUP_FEE_BUDGET) {
|
|
13189
|
+
const ataRent = await rpc.getMinimumBalanceForRentExemption(BigInt((0, import_token6.getTokenSize)())).send();
|
|
13190
|
+
if (before < ataRent + BigInt(CLEANUP_FEE_BUDGET)) {
|
|
12768
13191
|
throw new Error(
|
|
12769
|
-
`dustDestination ${dustDestination
|
|
13192
|
+
`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.`
|
|
12770
13193
|
);
|
|
12771
13194
|
}
|
|
12772
|
-
ixs.push(
|
|
13195
|
+
ixs.push(
|
|
13196
|
+
(0, import_token6.getCreateAssociatedTokenIdempotentInstruction)({
|
|
13197
|
+
payer: R,
|
|
13198
|
+
ata: destAta,
|
|
13199
|
+
owner: dustDestination,
|
|
13200
|
+
mint,
|
|
13201
|
+
tokenProgram: import_token6.TOKEN_PROGRAM_ADDRESS
|
|
13202
|
+
})
|
|
13203
|
+
);
|
|
12773
13204
|
}
|
|
12774
|
-
ixs.push((0,
|
|
12775
|
-
destination = destAta
|
|
13205
|
+
ixs.push((0, import_token6.getTransferInstruction)({ source: rAta, destination: destAta, authority: R, amount: bal }));
|
|
13206
|
+
destination = destAta;
|
|
12776
13207
|
}
|
|
12777
|
-
ixs.push((0,
|
|
12778
|
-
const signature = await (
|
|
12779
|
-
|
|
12780
|
-
|
|
12781
|
-
const after = await conn.getBalance(R.publicKey);
|
|
12782
|
-
const gone = await conn.getAccountInfo(rAta) === null;
|
|
13208
|
+
ixs.push((0, import_token6.getCloseAccountInstruction)({ account: rAta, destination: R.address, owner: R }));
|
|
13209
|
+
const signature = await sendInstructions(rpc, R, ixs, { version: "legacy", commitment: "confirmed" });
|
|
13210
|
+
const after = (await rpc.getBalance(R.address).send()).value;
|
|
13211
|
+
const gone = await fetchAccountBytes(rpc, rAta) === null;
|
|
12783
13212
|
return {
|
|
12784
13213
|
closed: gone,
|
|
12785
13214
|
dustSwept: bal,
|
|
@@ -12903,10 +13332,11 @@ async function withShieldRetries(attempt, hooks = {}) {
|
|
|
12903
13332
|
}
|
|
12904
13333
|
|
|
12905
13334
|
// src/index.ts
|
|
12906
|
-
var VERSION = "0.2.
|
|
13335
|
+
var VERSION = "0.2.5";
|
|
12907
13336
|
var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
12908
13337
|
// Annotate the CommonJS export names for ESM import in node:
|
|
12909
13338
|
0 && (module.exports = {
|
|
13339
|
+
AccountRole,
|
|
12910
13340
|
BRIDGE_ESCROW_LABEL,
|
|
12911
13341
|
BUILD_ALLOWS_LOCAL_ENDPOINTS,
|
|
12912
13342
|
CHAIN_NOTE_SALT_BITS,
|
|
@@ -12955,6 +13385,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
12955
13385
|
RootNotFoundError,
|
|
12956
13386
|
SCANNER_SUPPORTS_TRANSACT_SWAP,
|
|
12957
13387
|
SIGN_IN_MESSAGE,
|
|
13388
|
+
SYSTEM_PROGRAM_ADDRESS,
|
|
12958
13389
|
SanctionsQuoteError,
|
|
12959
13390
|
SettlementVerificationError,
|
|
12960
13391
|
ShieldPoolErrors,
|
|
@@ -12963,6 +13394,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
12963
13394
|
TRANSACTION_CIRCUITS_VERSION,
|
|
12964
13395
|
TRANSACT_AUTH_FIELDS,
|
|
12965
13396
|
TRANSACT_SWAP_AUTH_FIELDS,
|
|
13397
|
+
TransactionConfirmationError,
|
|
12966
13398
|
UtxoAlreadySpentError,
|
|
12967
13399
|
UtxoWallet,
|
|
12968
13400
|
VARIABLE_FEE_DENOMINATOR,
|
|
@@ -12971,6 +13403,11 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
12971
13403
|
VERSION,
|
|
12972
13404
|
WITHDRAW_FEE_BPS,
|
|
12973
13405
|
WITHDRAW_FIXED_FEE,
|
|
13406
|
+
accountMeta,
|
|
13407
|
+
address,
|
|
13408
|
+
addressBytes,
|
|
13409
|
+
addressFromBytes,
|
|
13410
|
+
addressFromPublicKey,
|
|
12974
13411
|
assertDirectSubmissionLanded,
|
|
12975
13412
|
assertInputMints,
|
|
12976
13413
|
assertTransactionCircuitIntegrity,
|
|
@@ -12985,6 +13422,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
12985
13422
|
buildRelayAuthPreimage,
|
|
12986
13423
|
buildRelayBatchAuthMessage,
|
|
12987
13424
|
buildTransactRequestBody,
|
|
13425
|
+
buildTransactionMessage,
|
|
12988
13426
|
bytesToHex,
|
|
12989
13427
|
calculateFee,
|
|
12990
13428
|
calculateFeeBigint,
|
|
@@ -13010,9 +13448,11 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13010
13448
|
computeSwapRefundCommitment,
|
|
13011
13449
|
computeUtxoCommitment,
|
|
13012
13450
|
computeUtxoNullifier,
|
|
13451
|
+
confirmSignature,
|
|
13013
13452
|
confirmTransactSettlement,
|
|
13014
13453
|
copyNoteToClipboard,
|
|
13015
13454
|
createCloakError,
|
|
13455
|
+
createCloakRpc,
|
|
13016
13456
|
createDepositInstruction,
|
|
13017
13457
|
createLogger,
|
|
13018
13458
|
createRecoverableChangeUtxo,
|
|
@@ -13057,12 +13497,17 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13057
13497
|
exportKeys,
|
|
13058
13498
|
exportNote,
|
|
13059
13499
|
exportWalletKeys,
|
|
13500
|
+
fetchAccountBytes,
|
|
13060
13501
|
fetchCommitments,
|
|
13502
|
+
fetchLatestBlockhash,
|
|
13503
|
+
fetchLookupTables,
|
|
13061
13504
|
fetchRiskQuoteInstruction,
|
|
13062
13505
|
fetchRiskQuoteIx,
|
|
13506
|
+
fetchSignaturesForAddress,
|
|
13063
13507
|
filterNotesByNetwork,
|
|
13064
13508
|
filterWithdrawableNotes,
|
|
13065
13509
|
findNoteByCommitment,
|
|
13510
|
+
findProgramAddress,
|
|
13066
13511
|
formatAmount,
|
|
13067
13512
|
formatComplianceCsv,
|
|
13068
13513
|
formatErrorForLogging,
|
|
@@ -13071,6 +13516,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13071
13516
|
fundReceiverViaPaymaster,
|
|
13072
13517
|
generateCloakKeys,
|
|
13073
13518
|
generateCommitmentAsync,
|
|
13519
|
+
generateKeyPairSigner,
|
|
13074
13520
|
generateMasterSeed,
|
|
13075
13521
|
generateNoteFromWallet,
|
|
13076
13522
|
generateUtxoKeypair,
|
|
@@ -13097,20 +13543,22 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13097
13543
|
hexToBytes,
|
|
13098
13544
|
importKeys,
|
|
13099
13545
|
importWalletKeys,
|
|
13546
|
+
isAddress,
|
|
13100
13547
|
isBrowser,
|
|
13101
13548
|
isBrowserLike,
|
|
13102
13549
|
isDebugEnabled,
|
|
13550
|
+
isMessageSigner,
|
|
13103
13551
|
isPlausibleSignature,
|
|
13104
13552
|
isReactNative,
|
|
13105
13553
|
isRootNotFoundError,
|
|
13106
13554
|
isSubmissionOutcomeUnknownResponse,
|
|
13107
13555
|
isTerminalFailure,
|
|
13556
|
+
isTransactionSigner,
|
|
13108
13557
|
isValidHex,
|
|
13109
13558
|
isValidRpcUrl,
|
|
13110
13559
|
isValidSolanaAddress,
|
|
13111
13560
|
isWithdrawAmountSufficient,
|
|
13112
13561
|
isWithdrawable,
|
|
13113
|
-
keypairToAdapter,
|
|
13114
13562
|
listBridgeDeposits,
|
|
13115
13563
|
loadPendingDeposits,
|
|
13116
13564
|
loadPendingWithdrawals,
|
|
@@ -13119,6 +13567,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13119
13567
|
matchDepositNote,
|
|
13120
13568
|
matchSwapRefundLeaf,
|
|
13121
13569
|
mayRetry,
|
|
13570
|
+
messageSignerFromCallback,
|
|
13122
13571
|
openRecipientDeliveryNote,
|
|
13123
13572
|
parseAmount,
|
|
13124
13573
|
parseDeliveryCarrierMemo,
|
|
@@ -13128,11 +13577,13 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13128
13577
|
parseRelayErrorSignature,
|
|
13129
13578
|
parseTransactionError,
|
|
13130
13579
|
partialWithdraw,
|
|
13580
|
+
partiallySignTransaction,
|
|
13131
13581
|
poseidonHash,
|
|
13132
13582
|
preflightCheck,
|
|
13133
13583
|
preflightNullifiers,
|
|
13134
13584
|
prepareEncryptedOutput,
|
|
13135
13585
|
prepareEncryptedOutputForRecipient,
|
|
13586
|
+
programInstruction,
|
|
13136
13587
|
proofToBytes,
|
|
13137
13588
|
pubkeyToFieldElement,
|
|
13138
13589
|
pubkeyToLimbs,
|
|
@@ -13157,22 +13608,34 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13157
13608
|
scanTransactions,
|
|
13158
13609
|
sdkLogger,
|
|
13159
13610
|
selectUtxos,
|
|
13611
|
+
sendInstructions,
|
|
13612
|
+
sendRawTransaction,
|
|
13160
13613
|
sendTransaction,
|
|
13161
13614
|
serializeAuthTransactionMessage,
|
|
13162
13615
|
serializeNote,
|
|
13163
13616
|
serializeUtxo,
|
|
13164
13617
|
setCircuitsPath,
|
|
13165
13618
|
setDebugMode,
|
|
13619
|
+
signCompiledTransaction,
|
|
13620
|
+
signMessageBytes,
|
|
13166
13621
|
signRelayAuthPayload,
|
|
13167
13622
|
signTransaction,
|
|
13623
|
+
signerFromKeypair,
|
|
13624
|
+
signerFromSecretKey,
|
|
13625
|
+
signerFromWalletAdapter,
|
|
13168
13626
|
splitTo2Limbs,
|
|
13169
13627
|
submitTransactToRelay,
|
|
13170
13628
|
sumUtxoAmounts,
|
|
13171
13629
|
swapUtxo,
|
|
13172
13630
|
swapWithChange,
|
|
13631
|
+
toAddress,
|
|
13173
13632
|
toComplianceReport,
|
|
13174
13633
|
transact,
|
|
13175
13634
|
transactBatch,
|
|
13635
|
+
transactionBase64,
|
|
13636
|
+
transactionBytes,
|
|
13637
|
+
transactionFromBytes,
|
|
13638
|
+
transactionWireSize,
|
|
13176
13639
|
transfer,
|
|
13177
13640
|
truncate,
|
|
13178
13641
|
tryDecryptNote,
|