privacycash 1.0.6
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/.github/workflows/npm-publish.yml +67 -0
- package/README.md +22 -0
- package/__tests__/e2e.test.ts +52 -0
- package/__tests__/encryption.test.ts +1635 -0
- package/circuit2/transaction2.wasm +0 -0
- package/circuit2/transaction2.zkey +0 -0
- package/dist/config.d.ts +7 -0
- package/dist/config.js +16 -0
- package/dist/deposit.d.ts +18 -0
- package/dist/deposit.js +402 -0
- package/dist/exportUtils.d.ts +6 -0
- package/dist/exportUtils.js +6 -0
- package/dist/getUtxos.d.ts +27 -0
- package/dist/getUtxos.js +352 -0
- package/dist/index.d.ts +61 -0
- package/dist/index.js +169 -0
- package/dist/models/keypair.d.ts +26 -0
- package/dist/models/keypair.js +43 -0
- package/dist/models/utxo.d.ts +49 -0
- package/dist/models/utxo.js +76 -0
- package/dist/utils/address_lookup_table.d.ts +8 -0
- package/dist/utils/address_lookup_table.js +21 -0
- package/dist/utils/constants.d.ts +14 -0
- package/dist/utils/constants.js +15 -0
- package/dist/utils/encryption.d.ts +107 -0
- package/dist/utils/encryption.js +374 -0
- package/dist/utils/logger.d.ts +9 -0
- package/dist/utils/logger.js +35 -0
- package/dist/utils/merkle_tree.d.ts +92 -0
- package/dist/utils/merkle_tree.js +186 -0
- package/dist/utils/node-shim.d.ts +5 -0
- package/dist/utils/node-shim.js +5 -0
- package/dist/utils/prover.d.ts +33 -0
- package/dist/utils/prover.js +123 -0
- package/dist/utils/utils.d.ts +67 -0
- package/dist/utils/utils.js +151 -0
- package/dist/withdraw.d.ts +21 -0
- package/dist/withdraw.js +270 -0
- package/package.json +48 -0
- package/src/config.ts +28 -0
- package/src/deposit.ts +496 -0
- package/src/exportUtils.ts +6 -0
- package/src/getUtxos.ts +466 -0
- package/src/index.ts +191 -0
- package/src/models/keypair.ts +52 -0
- package/src/models/utxo.ts +97 -0
- package/src/utils/address_lookup_table.ts +29 -0
- package/src/utils/constants.ts +26 -0
- package/src/utils/encryption.ts +461 -0
- package/src/utils/logger.ts +42 -0
- package/src/utils/merkle_tree.ts +207 -0
- package/src/utils/node-shim.ts +6 -0
- package/src/utils/prover.ts +189 -0
- package/src/utils/utils.ts +213 -0
- package/src/withdraw.ts +334 -0
- package/tsconfig.json +28 -0
package/src/deposit.ts
ADDED
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
import { Connection, Keypair, PublicKey, TransactionInstruction, SystemProgram, ComputeBudgetProgram, VersionedTransaction, TransactionMessage, LAMPORTS_PER_SOL } from '@solana/web3.js';
|
|
2
|
+
import BN from 'bn.js';
|
|
3
|
+
import { Utxo } from './models/utxo.js';
|
|
4
|
+
import { fetchMerkleProof, findCommitmentPDAs, findNullifierPDAs, getExtDataHash, getProgramAccounts, queryRemoteTreeState, findCrossCheckNullifierPDAs } from './utils/utils.js';
|
|
5
|
+
import { prove, parseProofToBytesArray, parseToBytesArray } from './utils/prover.js';
|
|
6
|
+
import * as hasher from '@lightprotocol/hasher.rs';
|
|
7
|
+
import { MerkleTree } from './utils/merkle_tree.js';
|
|
8
|
+
import { EncryptionService, serializeProofAndExtData } from './utils/encryption.js';
|
|
9
|
+
import { Keypair as UtxoKeypair } from './models/keypair.js';
|
|
10
|
+
import { getUtxos, isUtxoSpent } from './getUtxos.js';
|
|
11
|
+
import { FIELD_SIZE, FEE_RECIPIENT, MERKLE_TREE_DEPTH, INDEXER_API_URL, PROGRAM_ID } from './utils/constants.js';
|
|
12
|
+
import { useExistingALT } from './utils/address_lookup_table.js';
|
|
13
|
+
import { logger } from './utils/logger.js';
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
// Function to relay pre-signed deposit transaction to indexer backend
|
|
17
|
+
async function relayDepositToIndexer(signedTransaction: string, publicKey: PublicKey, referrer?: string): Promise<string> {
|
|
18
|
+
try {
|
|
19
|
+
logger.debug('Relaying pre-signed deposit transaction to indexer backend...');
|
|
20
|
+
|
|
21
|
+
const params: any = {
|
|
22
|
+
signedTransaction,
|
|
23
|
+
senderAddress: publicKey.toString()
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
if (referrer) {
|
|
27
|
+
params.referralWalletAddress = referrer
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const response = await fetch(`${INDEXER_API_URL}/deposit`, {
|
|
31
|
+
method: 'POST',
|
|
32
|
+
headers: {
|
|
33
|
+
'Content-Type': 'application/json',
|
|
34
|
+
},
|
|
35
|
+
body: JSON.stringify(params)
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
if (!response.ok) {
|
|
39
|
+
logger.error('res text:', await response.text())
|
|
40
|
+
throw new Error('response not ok')
|
|
41
|
+
// const errorData = await response.json() as { error?: string };
|
|
42
|
+
// throw new Error(`Deposit relay failed: ${response.status} ${response.statusText} - ${errorData.error || 'Unknown error'}`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const result = await response.json() as { signature: string, success: boolean };
|
|
46
|
+
logger.debug('Pre-signed deposit transaction relayed successfully!');
|
|
47
|
+
logger.debug('Response:', result);
|
|
48
|
+
|
|
49
|
+
return result.signature;
|
|
50
|
+
} catch (error) {
|
|
51
|
+
console.error('Failed to relay deposit transaction to indexer:', error);
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
type DepositParams = {
|
|
57
|
+
publicKey: PublicKey,
|
|
58
|
+
connection: Connection,
|
|
59
|
+
amount_in_lamports: number,
|
|
60
|
+
storage: Storage,
|
|
61
|
+
encryptionService: EncryptionService,
|
|
62
|
+
keyBasePath: string,
|
|
63
|
+
lightWasm: hasher.LightWasm,
|
|
64
|
+
referrer?: string,
|
|
65
|
+
transactionSigner: (tx: VersionedTransaction) => Promise<VersionedTransaction>
|
|
66
|
+
}
|
|
67
|
+
export async function deposit({ lightWasm, storage, keyBasePath, publicKey, connection, amount_in_lamports, encryptionService, transactionSigner, referrer }: DepositParams) {
|
|
68
|
+
// check limit
|
|
69
|
+
let limitAmount = await checkDepositLimit(connection)
|
|
70
|
+
if (limitAmount && amount_in_lamports > limitAmount * LAMPORTS_PER_SOL) {
|
|
71
|
+
throw new Error(`Don't deposit more than ${limitAmount} SOL`)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// const amount_in_lamports = amount_in_sol * LAMPORTS_PER_SOL
|
|
75
|
+
const fee_amount_in_lamports = 0
|
|
76
|
+
logger.debug('Encryption key generated from user keypair');
|
|
77
|
+
logger.debug(`User wallet: ${publicKey.toString()}`);
|
|
78
|
+
logger.debug(`Deposit amount: ${amount_in_lamports} lamports (${amount_in_lamports / LAMPORTS_PER_SOL} SOL)`);
|
|
79
|
+
logger.debug(`Calculated fee: ${fee_amount_in_lamports} lamports (${fee_amount_in_lamports / LAMPORTS_PER_SOL} SOL)`);
|
|
80
|
+
|
|
81
|
+
// Check wallet balance
|
|
82
|
+
const balance = await connection.getBalance(publicKey);
|
|
83
|
+
logger.debug(`Wallet balance: ${balance / 1e9} SOL`);
|
|
84
|
+
|
|
85
|
+
if (balance < amount_in_lamports + fee_amount_in_lamports) {
|
|
86
|
+
new Error(`Insufficient balance: ${balance / 1e9} SOL. Need at least ${(amount_in_lamports + fee_amount_in_lamports) / LAMPORTS_PER_SOL} SOL.`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const { treeAccount, treeTokenAccount, globalConfigAccount } = getProgramAccounts()
|
|
90
|
+
|
|
91
|
+
// Create the merkle tree with the pre-initialized poseidon hash
|
|
92
|
+
const tree = new MerkleTree(MERKLE_TREE_DEPTH, lightWasm);
|
|
93
|
+
|
|
94
|
+
// Initialize root and nextIndex variables
|
|
95
|
+
const { root, nextIndex: currentNextIndex } = await queryRemoteTreeState();
|
|
96
|
+
|
|
97
|
+
logger.debug(`Using tree root: ${root}`);
|
|
98
|
+
logger.debug(`New UTXOs will be inserted at indices: ${currentNextIndex} and ${currentNextIndex + 1}`);
|
|
99
|
+
|
|
100
|
+
// Generate a deterministic private key derived from the wallet keypair
|
|
101
|
+
// const utxoPrivateKey = encryptionService.deriveUtxoPrivateKey();
|
|
102
|
+
const utxoPrivateKey = encryptionService.getUtxoPrivateKeyV2();
|
|
103
|
+
|
|
104
|
+
// Create a UTXO keypair that will be used for all inputs and outputs
|
|
105
|
+
const utxoKeypair = new UtxoKeypair(utxoPrivateKey, lightWasm);
|
|
106
|
+
logger.debug('Using wallet-derived UTXO keypair for deposit');
|
|
107
|
+
|
|
108
|
+
// Fetch existing UTXOs for this user
|
|
109
|
+
logger.debug('\nFetching existing UTXOs...');
|
|
110
|
+
const existingUnspentUtxos = await getUtxos({ connection, publicKey, encryptionService, storage });
|
|
111
|
+
|
|
112
|
+
// Calculate output amounts and external amount based on scenario
|
|
113
|
+
let extAmount: number;
|
|
114
|
+
let outputAmount: string;
|
|
115
|
+
|
|
116
|
+
// Create inputs based on whether we have existing UTXOs
|
|
117
|
+
let inputs: Utxo[];
|
|
118
|
+
let inputMerklePathIndices: number[];
|
|
119
|
+
let inputMerklePathElements: string[][];
|
|
120
|
+
|
|
121
|
+
if (existingUnspentUtxos.length === 0) {
|
|
122
|
+
// Scenario 1: Fresh deposit with dummy inputs - add new funds to the system
|
|
123
|
+
extAmount = amount_in_lamports;
|
|
124
|
+
outputAmount = new BN(amount_in_lamports).sub(new BN(fee_amount_in_lamports)).toString();
|
|
125
|
+
|
|
126
|
+
logger.debug(`Fresh deposit scenario (no existing UTXOs):`);
|
|
127
|
+
logger.debug(`External amount (deposit): ${extAmount}`);
|
|
128
|
+
logger.debug(`Fee amount: ${fee_amount_in_lamports}`);
|
|
129
|
+
logger.debug(`Output amount: ${outputAmount}`);
|
|
130
|
+
|
|
131
|
+
// Use two dummy UTXOs as inputs
|
|
132
|
+
inputs = [
|
|
133
|
+
new Utxo({
|
|
134
|
+
lightWasm,
|
|
135
|
+
keypair: utxoKeypair
|
|
136
|
+
}),
|
|
137
|
+
new Utxo({
|
|
138
|
+
lightWasm,
|
|
139
|
+
keypair: utxoKeypair
|
|
140
|
+
})
|
|
141
|
+
];
|
|
142
|
+
|
|
143
|
+
// Both inputs are dummy, so use mock indices and zero-filled Merkle paths
|
|
144
|
+
inputMerklePathIndices = inputs.map((input) => input.index || 0);
|
|
145
|
+
inputMerklePathElements = inputs.map(() => {
|
|
146
|
+
return [...new Array(tree.levels).fill("0")];
|
|
147
|
+
});
|
|
148
|
+
} else {
|
|
149
|
+
// Scenario 2: Deposit that consolidates with existing UTXO(s)
|
|
150
|
+
const firstUtxo = existingUnspentUtxos[0];
|
|
151
|
+
const firstUtxoAmount = firstUtxo.amount;
|
|
152
|
+
const secondUtxoAmount = existingUnspentUtxos.length > 1 ? existingUnspentUtxos[1].amount : new BN(0);
|
|
153
|
+
extAmount = amount_in_lamports; // Still depositing new funds
|
|
154
|
+
|
|
155
|
+
// Output combines existing UTXO amounts + new deposit amount - fee
|
|
156
|
+
outputAmount = firstUtxoAmount.add(secondUtxoAmount).add(new BN(amount_in_lamports)).sub(new BN(fee_amount_in_lamports)).toString();
|
|
157
|
+
|
|
158
|
+
logger.debug(`Deposit with consolidation scenario:`);
|
|
159
|
+
logger.debug(`First existing UTXO amount: ${firstUtxoAmount.toString()}`);
|
|
160
|
+
if (secondUtxoAmount.gt(new BN(0))) {
|
|
161
|
+
logger.debug(`Second existing UTXO amount: ${secondUtxoAmount.toString()}`);
|
|
162
|
+
}
|
|
163
|
+
logger.debug(`New deposit amount: ${amount_in_lamports}`);
|
|
164
|
+
logger.debug(`Fee amount: ${fee_amount_in_lamports}`);
|
|
165
|
+
logger.debug(`Output amount (existing UTXOs + deposit - fee): ${outputAmount}`);
|
|
166
|
+
logger.debug(`External amount (deposit): ${extAmount}`);
|
|
167
|
+
|
|
168
|
+
logger.debug('\nFirst UTXO to be consolidated:');
|
|
169
|
+
await firstUtxo.log();
|
|
170
|
+
|
|
171
|
+
// Use first existing UTXO as first input, and either second UTXO or dummy UTXO as second input
|
|
172
|
+
const secondUtxo = existingUnspentUtxos.length > 1 ? existingUnspentUtxos[1] : new Utxo({
|
|
173
|
+
lightWasm,
|
|
174
|
+
keypair: utxoKeypair,
|
|
175
|
+
amount: '0'
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
inputs = [
|
|
179
|
+
firstUtxo, // Use the first existing UTXO
|
|
180
|
+
secondUtxo // Use second UTXO if available, otherwise dummy
|
|
181
|
+
];
|
|
182
|
+
|
|
183
|
+
// Fetch Merkle proofs for real UTXOs
|
|
184
|
+
const firstUtxoCommitment = await firstUtxo.getCommitment();
|
|
185
|
+
const firstUtxoMerkleProof = await fetchMerkleProof(firstUtxoCommitment);
|
|
186
|
+
|
|
187
|
+
let secondUtxoMerkleProof;
|
|
188
|
+
if (secondUtxo.amount.gt(new BN(0))) {
|
|
189
|
+
// Second UTXO is real, fetch its proof
|
|
190
|
+
const secondUtxoCommitment = await secondUtxo.getCommitment();
|
|
191
|
+
secondUtxoMerkleProof = await fetchMerkleProof(secondUtxoCommitment);
|
|
192
|
+
logger.debug('\nSecond UTXO to be consolidated:');
|
|
193
|
+
await secondUtxo.log();
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Use the real pathIndices from API for real inputs, mock index for dummy input
|
|
197
|
+
inputMerklePathIndices = [
|
|
198
|
+
firstUtxo.index || 0, // Use the real UTXO's index
|
|
199
|
+
secondUtxo.amount.gt(new BN(0)) ? (secondUtxo.index || 0) : 0 // Real UTXO index or dummy
|
|
200
|
+
];
|
|
201
|
+
|
|
202
|
+
// Create Merkle path elements: real proof for real inputs, zeros for dummy input
|
|
203
|
+
inputMerklePathElements = [
|
|
204
|
+
firstUtxoMerkleProof.pathElements, // Real Merkle proof for first existing UTXO
|
|
205
|
+
secondUtxo.amount.gt(new BN(0)) ? secondUtxoMerkleProof!.pathElements : [...new Array(tree.levels).fill("0")] // Real proof or zero-filled for dummy
|
|
206
|
+
];
|
|
207
|
+
|
|
208
|
+
logger.debug(`Using first UTXO with amount: ${firstUtxo.amount.toString()} and index: ${firstUtxo.index}`);
|
|
209
|
+
logger.debug(`Using second ${secondUtxo.amount.gt(new BN(0)) ? 'UTXO' : 'dummy UTXO'} with amount: ${secondUtxo.amount.toString()}${secondUtxo.amount.gt(new BN(0)) ? ` and index: ${secondUtxo.index}` : ''}`);
|
|
210
|
+
logger.debug(`First UTXO Merkle proof path indices from API: [${firstUtxoMerkleProof.pathIndices.join(', ')}]`);
|
|
211
|
+
if (secondUtxo.amount.gt(new BN(0))) {
|
|
212
|
+
logger.debug(`Second UTXO Merkle proof path indices from API: [${secondUtxoMerkleProof!.pathIndices.join(', ')}]`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const publicAmountForCircuit = new BN(extAmount).sub(new BN(fee_amount_in_lamports)).add(FIELD_SIZE).mod(FIELD_SIZE);
|
|
217
|
+
logger.debug(`Public amount calculation: (${extAmount} - ${fee_amount_in_lamports} + FIELD_SIZE) % FIELD_SIZE = ${publicAmountForCircuit.toString()}`);
|
|
218
|
+
|
|
219
|
+
// Create outputs for the transaction with the same shared keypair
|
|
220
|
+
const outputs = [
|
|
221
|
+
new Utxo({
|
|
222
|
+
lightWasm,
|
|
223
|
+
amount: outputAmount,
|
|
224
|
+
keypair: utxoKeypair,
|
|
225
|
+
index: currentNextIndex // This UTXO will be inserted at currentNextIndex
|
|
226
|
+
}), // Output with value (either deposit amount minus fee, or input amount minus fee)
|
|
227
|
+
new Utxo({
|
|
228
|
+
lightWasm,
|
|
229
|
+
amount: '0',
|
|
230
|
+
keypair: utxoKeypair,
|
|
231
|
+
index: currentNextIndex + 1 // This UTXO will be inserted at currentNextIndex + 1
|
|
232
|
+
}) // Empty UTXO
|
|
233
|
+
];
|
|
234
|
+
|
|
235
|
+
// Verify this matches the circuit balance equation: sumIns + publicAmount = sumOuts
|
|
236
|
+
const sumIns = inputs.reduce((sum, input) => sum.add(input.amount), new BN(0));
|
|
237
|
+
const sumOuts = outputs.reduce((sum, output) => sum.add(output.amount), new BN(0));
|
|
238
|
+
logger.debug(`Circuit balance check: sumIns(${sumIns.toString()}) + publicAmount(${publicAmountForCircuit.toString()}) should equal sumOuts(${sumOuts.toString()})`);
|
|
239
|
+
|
|
240
|
+
// Convert to circuit-compatible format
|
|
241
|
+
const publicAmountCircuitResult = sumIns.add(publicAmountForCircuit).mod(FIELD_SIZE);
|
|
242
|
+
logger.debug(`Balance verification: ${sumIns.toString()} + ${publicAmountForCircuit.toString()} (mod FIELD_SIZE) = ${publicAmountCircuitResult.toString()}`);
|
|
243
|
+
logger.debug(`Expected sum of outputs: ${sumOuts.toString()}`);
|
|
244
|
+
logger.debug(`Balance equation satisfied: ${publicAmountCircuitResult.eq(sumOuts)}`);
|
|
245
|
+
|
|
246
|
+
// Generate nullifiers and commitments
|
|
247
|
+
const inputNullifiers = await Promise.all(inputs.map(x => x.getNullifier()));
|
|
248
|
+
const outputCommitments = await Promise.all(outputs.map(x => x.getCommitment()));
|
|
249
|
+
|
|
250
|
+
// Save original commitment and nullifier values for verification
|
|
251
|
+
logger.debug('\n=== UTXO VALIDATION ===');
|
|
252
|
+
logger.debug('Output 0 Commitment:', outputCommitments[0]);
|
|
253
|
+
logger.debug('Output 1 Commitment:', outputCommitments[1]);
|
|
254
|
+
|
|
255
|
+
// Encrypt the UTXO data using a compact format that includes the keypair
|
|
256
|
+
logger.debug('\nEncrypting UTXOs with keypair data...');
|
|
257
|
+
const encryptedOutput1 = encryptionService.encryptUtxo(outputs[0]);
|
|
258
|
+
const encryptedOutput2 = encryptionService.encryptUtxo(outputs[1]);
|
|
259
|
+
|
|
260
|
+
logger.debug(`\nOutput[0] (with value):`);
|
|
261
|
+
await outputs[0].log();
|
|
262
|
+
logger.debug(`\nOutput[1] (empty):`);
|
|
263
|
+
await outputs[1].log();
|
|
264
|
+
|
|
265
|
+
logger.debug(`\nEncrypted output 1 size: ${encryptedOutput1.length} bytes`);
|
|
266
|
+
logger.debug(`Encrypted output 2 size: ${encryptedOutput2.length} bytes`);
|
|
267
|
+
logger.debug(`Total encrypted outputs size: ${encryptedOutput1.length + encryptedOutput2.length} bytes`);
|
|
268
|
+
|
|
269
|
+
// Test decryption to verify commitment values match
|
|
270
|
+
logger.debug('\n=== TESTING DECRYPTION ===');
|
|
271
|
+
logger.debug('Decrypting output 1 to verify commitment matches...');
|
|
272
|
+
const decryptedUtxo1 = await encryptionService.decryptUtxo(encryptedOutput1, lightWasm);
|
|
273
|
+
const decryptedCommitment1 = await decryptedUtxo1.getCommitment();
|
|
274
|
+
logger.debug('Original commitment:', outputCommitments[0]);
|
|
275
|
+
logger.debug('Decrypted commitment:', decryptedCommitment1);
|
|
276
|
+
logger.debug('Commitment matches:', outputCommitments[0] === decryptedCommitment1);
|
|
277
|
+
|
|
278
|
+
// Create the deposit ExtData with real encrypted outputs
|
|
279
|
+
const extData = {
|
|
280
|
+
// recipient - just a placeholder, not actually used for deposits.
|
|
281
|
+
recipient: new PublicKey('AWexibGxNFKTa1b5R5MN4PJr9HWnWRwf8EW9g8cLx3dM'),
|
|
282
|
+
extAmount: new BN(extAmount),
|
|
283
|
+
encryptedOutput1: encryptedOutput1,
|
|
284
|
+
encryptedOutput2: encryptedOutput2,
|
|
285
|
+
fee: new BN(fee_amount_in_lamports),
|
|
286
|
+
feeRecipient: FEE_RECIPIENT,
|
|
287
|
+
mintAddress: inputs[0].mintAddress
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
// Calculate the extDataHash with the encrypted outputs (now includes mintAddress for security)
|
|
291
|
+
const calculatedExtDataHash = getExtDataHash(extData);
|
|
292
|
+
|
|
293
|
+
// Create the input for the proof generation (must match circuit input order exactly)
|
|
294
|
+
const input = {
|
|
295
|
+
// Common transaction data
|
|
296
|
+
root: root,
|
|
297
|
+
inputNullifier: inputNullifiers, // Use resolved values instead of Promise objects
|
|
298
|
+
outputCommitment: outputCommitments, // Use resolved values instead of Promise objects
|
|
299
|
+
publicAmount: publicAmountForCircuit.toString(), // Use proper field arithmetic result
|
|
300
|
+
extDataHash: calculatedExtDataHash,
|
|
301
|
+
|
|
302
|
+
// Input UTXO data (UTXOs being spent) - ensure all values are in decimal format
|
|
303
|
+
inAmount: inputs.map(x => x.amount.toString(10)),
|
|
304
|
+
inPrivateKey: inputs.map(x => x.keypair.privkey),
|
|
305
|
+
inBlinding: inputs.map(x => x.blinding.toString(10)),
|
|
306
|
+
inPathIndices: inputMerklePathIndices,
|
|
307
|
+
inPathElements: inputMerklePathElements,
|
|
308
|
+
|
|
309
|
+
// Output UTXO data (UTXOs being created) - ensure all values are in decimal format
|
|
310
|
+
outAmount: outputs.map(x => x.amount.toString(10)),
|
|
311
|
+
outBlinding: outputs.map(x => x.blinding.toString(10)),
|
|
312
|
+
outPubkey: outputs.map(x => x.keypair.pubkey),
|
|
313
|
+
|
|
314
|
+
// new mint address
|
|
315
|
+
mintAddress: inputs[0].mintAddress
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
logger.info('generating ZK proof...');
|
|
319
|
+
|
|
320
|
+
// Generate the zero-knowledge proof
|
|
321
|
+
const { proof, publicSignals } = await prove(input, keyBasePath);
|
|
322
|
+
// Parse the proof and public signals into byte arrays
|
|
323
|
+
const proofInBytes = parseProofToBytesArray(proof);
|
|
324
|
+
const inputsInBytes = parseToBytesArray(publicSignals);
|
|
325
|
+
|
|
326
|
+
// Create the proof object to submit to the program
|
|
327
|
+
const proofToSubmit = {
|
|
328
|
+
proofA: proofInBytes.proofA,
|
|
329
|
+
proofB: proofInBytes.proofB.flat(),
|
|
330
|
+
proofC: proofInBytes.proofC,
|
|
331
|
+
root: inputsInBytes[0],
|
|
332
|
+
publicAmount: inputsInBytes[1],
|
|
333
|
+
extDataHash: inputsInBytes[2],
|
|
334
|
+
inputNullifiers: [
|
|
335
|
+
inputsInBytes[3],
|
|
336
|
+
inputsInBytes[4]
|
|
337
|
+
],
|
|
338
|
+
outputCommitments: [
|
|
339
|
+
inputsInBytes[5],
|
|
340
|
+
inputsInBytes[6]
|
|
341
|
+
],
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
// Find PDAs for nullifiers and commitments
|
|
345
|
+
const { nullifier0PDA, nullifier1PDA } = findNullifierPDAs(proofToSubmit);
|
|
346
|
+
const { nullifier2PDA, nullifier3PDA } = findCrossCheckNullifierPDAs(proofToSubmit);
|
|
347
|
+
const { commitment0PDA, commitment1PDA } = findCommitmentPDAs(proofToSubmit);
|
|
348
|
+
|
|
349
|
+
// Address Lookup Table for transaction size optimization
|
|
350
|
+
logger.debug('Setting up Address Lookup Table...');
|
|
351
|
+
|
|
352
|
+
const ALT_ADDRESS = new PublicKey('72bpRay17JKp4k8H87p7ieU9C6aRDy5yCqwvtpTN2wuU');
|
|
353
|
+
const lookupTableAccount = await useExistingALT(connection, ALT_ADDRESS);
|
|
354
|
+
|
|
355
|
+
if (!lookupTableAccount?.value) {
|
|
356
|
+
throw new Error(`ALT not found at address ${ALT_ADDRESS.toString()} `);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// Serialize the proof and extData
|
|
360
|
+
const serializedProof = serializeProofAndExtData(proofToSubmit, extData);
|
|
361
|
+
logger.debug(`Total instruction data size: ${serializedProof.length} bytes`);
|
|
362
|
+
|
|
363
|
+
// Create the deposit instruction (user signs, not relayer)
|
|
364
|
+
const depositInstruction = new TransactionInstruction({
|
|
365
|
+
keys: [
|
|
366
|
+
{ pubkey: treeAccount, isSigner: false, isWritable: true },
|
|
367
|
+
{ pubkey: nullifier0PDA, isSigner: false, isWritable: true },
|
|
368
|
+
{ pubkey: nullifier1PDA, isSigner: false, isWritable: true },
|
|
369
|
+
{ pubkey: nullifier2PDA, isSigner: false, isWritable: false },
|
|
370
|
+
{ pubkey: nullifier3PDA, isSigner: false, isWritable: false },
|
|
371
|
+
{ pubkey: commitment0PDA, isSigner: false, isWritable: true },
|
|
372
|
+
{ pubkey: commitment1PDA, isSigner: false, isWritable: true },
|
|
373
|
+
{ pubkey: treeTokenAccount, isSigner: false, isWritable: true },
|
|
374
|
+
{ pubkey: globalConfigAccount, isSigner: false, isWritable: false },
|
|
375
|
+
// recipient - just a placeholder, not actually used for deposits. using an ALT address to save bytes
|
|
376
|
+
{ pubkey: new PublicKey('AWexibGxNFKTa1b5R5MN4PJr9HWnWRwf8EW9g8cLx3dM'), isSigner: false, isWritable: true },
|
|
377
|
+
// fee recipient
|
|
378
|
+
{ pubkey: FEE_RECIPIENT, isSigner: false, isWritable: true },
|
|
379
|
+
// signer
|
|
380
|
+
{ pubkey: publicKey, isSigner: true, isWritable: true },
|
|
381
|
+
{ pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
|
|
382
|
+
],
|
|
383
|
+
programId: PROGRAM_ID,
|
|
384
|
+
data: serializedProof,
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
// Set compute budget for the transaction
|
|
388
|
+
const modifyComputeUnits = ComputeBudgetProgram.setComputeUnitLimit({
|
|
389
|
+
units: 1_000_000
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
// Create versioned transaction with Address Lookup Table
|
|
393
|
+
const recentBlockhash = await connection.getLatestBlockhash();
|
|
394
|
+
|
|
395
|
+
const messageV0 = new TransactionMessage({
|
|
396
|
+
payerKey: publicKey, // User pays for their own deposit
|
|
397
|
+
recentBlockhash: recentBlockhash.blockhash,
|
|
398
|
+
instructions: [modifyComputeUnits, depositInstruction],
|
|
399
|
+
}).compileToV0Message([lookupTableAccount.value]);
|
|
400
|
+
|
|
401
|
+
let versionedTransaction = new VersionedTransaction(messageV0);
|
|
402
|
+
|
|
403
|
+
// sign tx
|
|
404
|
+
versionedTransaction = await transactionSigner(versionedTransaction)
|
|
405
|
+
|
|
406
|
+
logger.debug('Transaction signed by user');
|
|
407
|
+
|
|
408
|
+
// Serialize the signed transaction for relay
|
|
409
|
+
const serializedTransaction = Buffer.from(versionedTransaction.serialize()).toString('base64');
|
|
410
|
+
|
|
411
|
+
logger.debug('Prepared signed transaction for relay to indexer backend');
|
|
412
|
+
|
|
413
|
+
// Relay the pre-signed transaction to indexer backend
|
|
414
|
+
logger.info('submitting transaction to relayer...')
|
|
415
|
+
const signature = await relayDepositToIndexer(serializedTransaction, publicKey, referrer);
|
|
416
|
+
logger.debug('Transaction signature:', signature);
|
|
417
|
+
logger.debug(`Transaction link: https://explorer.solana.com/tx/${signature}`);
|
|
418
|
+
|
|
419
|
+
logger.info('Waiting for transaction confirmation...')
|
|
420
|
+
|
|
421
|
+
let retryTimes = 0
|
|
422
|
+
let itv = 2
|
|
423
|
+
const encryptedOutputStr = Buffer.from(encryptedOutput1).toString('hex')
|
|
424
|
+
let start = Date.now()
|
|
425
|
+
while (true) {
|
|
426
|
+
logger.debug(`retryTimes: ${retryTimes}`)
|
|
427
|
+
await new Promise(resolve => setTimeout(resolve, itv * 1000));
|
|
428
|
+
logger.debug('Fetching updated tree state...');
|
|
429
|
+
let res = await fetch(INDEXER_API_URL + '/utxos/check/' + encryptedOutputStr)
|
|
430
|
+
let resJson = await res.json()
|
|
431
|
+
if (resJson.exists) {
|
|
432
|
+
logger.debug(`Top up successfully in ${((Date.now() - start) / 1000).toFixed(2)} seconds!`);
|
|
433
|
+
return { tx: signature }
|
|
434
|
+
}
|
|
435
|
+
if (retryTimes >= 10) {
|
|
436
|
+
throw new Error('Refresh the page to see latest balance.')
|
|
437
|
+
}
|
|
438
|
+
retryTimes++
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
async function checkDepositLimit(connection: Connection) {
|
|
445
|
+
try {
|
|
446
|
+
|
|
447
|
+
// Derive the tree account PDA
|
|
448
|
+
const [treeAccount] = PublicKey.findProgramAddressSync(
|
|
449
|
+
[Buffer.from('merkle_tree')],
|
|
450
|
+
PROGRAM_ID
|
|
451
|
+
);
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
// Fetch the account data
|
|
455
|
+
const accountInfo = await connection.getAccountInfo(treeAccount);
|
|
456
|
+
|
|
457
|
+
if (!accountInfo) {
|
|
458
|
+
console.error('ā Tree account not found. Make sure the program is initialized.');
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
console.log(`Account data size: ${accountInfo.data.length} bytes`);
|
|
463
|
+
const authority = new PublicKey(accountInfo.data.slice(8, 40));
|
|
464
|
+
const nextIndex = new BN(accountInfo.data.slice(40, 48), 'le');
|
|
465
|
+
const rootIndex = new BN(accountInfo.data.slice(4112, 4120), 'le');
|
|
466
|
+
const maxDepositAmount = new BN(accountInfo.data.slice(4120, 4128), 'le');
|
|
467
|
+
const bump = accountInfo.data[4128];
|
|
468
|
+
|
|
469
|
+
console.log('\nš MerkleTreeAccount Details:');
|
|
470
|
+
console.log(`āā Authority: ${authority.toString()}`);
|
|
471
|
+
console.log(`āā Next Index: ${nextIndex.toString()}`);
|
|
472
|
+
console.log(`āā Root Index: ${rootIndex.toString()}`);
|
|
473
|
+
console.log(`āā Max Deposit Amount: ${maxDepositAmount.toString()} lamports`);
|
|
474
|
+
|
|
475
|
+
// Convert to SOL using BN division to handle large numbers
|
|
476
|
+
const lamportsPerSol = new BN(1_000_000_000);
|
|
477
|
+
const maxDepositSol = maxDepositAmount.div(lamportsPerSol);
|
|
478
|
+
const remainder = maxDepositAmount.mod(lamportsPerSol);
|
|
479
|
+
|
|
480
|
+
// Format the SOL amount with decimals
|
|
481
|
+
let solFormatted = '1';
|
|
482
|
+
if (remainder.eq(new BN(0))) {
|
|
483
|
+
solFormatted = maxDepositSol.toString();
|
|
484
|
+
} else {
|
|
485
|
+
// Handle fractional SOL by converting remainder to decimal
|
|
486
|
+
const fractional = remainder.toNumber() / 1e9;
|
|
487
|
+
solFormatted = `${maxDepositSol.toString()}${fractional.toFixed(9).substring(1)}`;
|
|
488
|
+
}
|
|
489
|
+
console.log('solFormatted', solFormatted)
|
|
490
|
+
return Number(solFormatted)
|
|
491
|
+
|
|
492
|
+
} catch (error) {
|
|
493
|
+
console.log('ā Error reading deposit limit:', error);
|
|
494
|
+
throw error
|
|
495
|
+
}
|
|
496
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { getConfig } from './config.js'
|
|
2
|
+
export { deposit } from './deposit.js'
|
|
3
|
+
export { withdraw } from './withdraw.js'
|
|
4
|
+
export { EncryptionService } from './utils/encryption.js'
|
|
5
|
+
export { setLogger } from './utils/logger.js'
|
|
6
|
+
export { getBalanceFromUtxos, getUtxos, localstorageKey } from './getUtxos.js'
|