-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathSvmSpoke.Fill.AcrossPlus.ts
385 lines (322 loc) · 14.8 KB
/
SvmSpoke.Fill.AcrossPlus.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import * as anchor from "@coral-xyz/anchor";
import { BN, Program } from "@coral-xyz/anchor";
import {
ASSOCIATED_TOKEN_PROGRAM_ID,
TOKEN_PROGRAM_ID,
createMint,
getOrCreateAssociatedTokenAccount,
mintTo,
getAccount,
createTransferCheckedInstruction,
getAssociatedTokenAddressSync,
createAssociatedTokenAccountInstruction,
getMinimumBalanceForRentExemptAccount,
createApproveCheckedInstruction,
} from "@solana/spl-token";
import {
PublicKey,
Keypair,
AccountMeta,
TransactionInstruction,
sendAndConfirmTransaction,
Transaction,
ComputeBudgetProgram,
} from "@solana/web3.js";
import {
calculateRelayHashUint8Array,
MulticallHandlerCoder,
AcrossPlusMessageCoder,
sendTransactionWithLookupTable,
loadFillRelayParams,
intToU8Array32,
} from "../../src/svm/web3-v1";
import { MulticallHandler } from "../../target/types/multicall_handler";
import { common } from "./SvmSpoke.common";
import { FillDataParams, FillDataValues } from "../../src/types/svm";
const { provider, connection, program, owner, chainId, seedBalance } = common;
const { initializeState, assertSE } = common;
describe("svm_spoke.fill.across_plus", () => {
anchor.setProvider(provider);
const payer = (anchor.AnchorProvider.env().wallet as anchor.Wallet).payer;
const relayer = Keypair.generate();
const handlerProgram = anchor.workspace.MulticallHandler as Program<MulticallHandler>;
let handlerSigner: PublicKey,
handlerATA: PublicKey,
finalRecipient: PublicKey,
finalRecipientATA: PublicKey,
state: PublicKey,
mint: PublicKey,
relayerATA: PublicKey;
const relayAmount = 500000;
const mintDecimals = 6;
let relayData: any; // reused relay data for all tests.
let accounts: any; // Store accounts to simplify contract interactions.
function updateRelayData(newRelayData: any) {
relayData = newRelayData;
const relayHashUint8Array = calculateRelayHashUint8Array(relayData, chainId);
const [fillStatusPDA] = PublicKey.findProgramAddressSync(
[Buffer.from("fills"), relayHashUint8Array],
program.programId
);
accounts = {
state,
signer: relayer.publicKey,
instructionParams: program.programId,
mint: mint,
relayerTokenAccount: relayerATA,
recipientTokenAccount: handlerATA,
fillStatus: fillStatusPDA,
tokenProgram: TOKEN_PROGRAM_ID,
associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
systemProgram: anchor.web3.SystemProgram.programId,
};
}
async function createApproveAndFillIx(multicallHandlerCoder: MulticallHandlerCoder, bufferParams = false) {
// Delegate state PDA to pull relayer tokens.
const approveIx = await createApproveCheckedInstruction(
accounts.relayerTokenAccount,
accounts.mint,
accounts.state,
accounts.signer,
BigInt(relayAmount),
mintDecimals
);
const remainingAccounts: AccountMeta[] = [
{ pubkey: handlerProgram.programId, isSigner: false, isWritable: false },
...multicallHandlerCoder.compiledKeyMetas,
];
const relayHash = Array.from(calculateRelayHashUint8Array(relayData, chainId));
// Prepare fill instruction.
const fillRelayValues: FillDataValues = [relayHash, relayData, new BN(1), relayer.publicKey];
if (bufferParams) {
await loadFillRelayParams(program, relayer, fillRelayValues[1], fillRelayValues[2], fillRelayValues[3]);
[accounts.instructionParams] = PublicKey.findProgramAddressSync(
[Buffer.from("instruction_params"), relayer.publicKey.toBuffer()],
program.programId
);
}
const fillRelayParams: FillDataParams = bufferParams ? [fillRelayValues[0], null, null, null] : fillRelayValues;
const fillIx = await program.methods
.fillRelay(...fillRelayParams)
.accounts(accounts)
.remainingAccounts(remainingAccounts)
.instruction();
return { approveIx, fillIx };
}
before("Creates token mint and associated token accounts", async () => {
mint = await createMint(connection, payer, owner, owner, mintDecimals);
relayerATA = (await getOrCreateAssociatedTokenAccount(connection, payer, mint, relayer.publicKey)).address;
await mintTo(connection, payer, mint, relayerATA, owner, seedBalance);
await connection.requestAirdrop(relayer.publicKey, 10_000_000_000); // 10 SOL
[handlerSigner] = PublicKey.findProgramAddressSync([Buffer.from("handler_signer")], handlerProgram.programId);
handlerATA = (await getOrCreateAssociatedTokenAccount(connection, payer, mint, handlerSigner, true)).address;
});
beforeEach(async () => {
finalRecipient = Keypair.generate().publicKey;
finalRecipientATA = (await getOrCreateAssociatedTokenAccount(connection, payer, mint, finalRecipient)).address;
({ state } = await initializeState());
const initialRelayData = {
depositor: finalRecipient,
recipient: handlerSigner, // Handler PDA that can forward tokens as needed within the message call.
exclusiveRelayer: relayer.publicKey,
inputToken: mint, // This is lazy. it should be an encoded token from a separate domain most likely.
outputToken: mint,
inputAmount: new BN(relayAmount),
outputAmount: new BN(relayAmount),
originChainId: new BN(1),
depositId: intToU8Array32(Math.floor(Math.random() * 1000000)), // force that we always have a new deposit id.
fillDeadline: new BN(Math.floor(Date.now() / 1000) + 60), // 1 minute from now
exclusivityDeadline: new BN(Math.floor(Date.now() / 1000) + 30), // 30 seconds from now
message: Buffer.from(""), // Will be populated in the tests below.
};
updateRelayData(initialRelayData);
});
it("Forwards tokens to the final recipient within invoked message call", async () => {
const iRelayerBal = (await getAccount(connection, relayerATA)).amount;
// Construct ix to transfer all tokens from handler to the final recipient.
const transferIx = createTransferCheckedInstruction(
handlerATA,
mint,
finalRecipientATA,
handlerSigner,
relayData.outputAmount,
mintDecimals
);
const multicallHandlerCoder = new MulticallHandlerCoder([transferIx]);
const handlerMessage = multicallHandlerCoder.encode();
const message = new AcrossPlusMessageCoder({
handler: handlerProgram.programId,
readOnlyLen: multicallHandlerCoder.readOnlyLen,
valueAmount: new BN(0),
accounts: multicallHandlerCoder.compiledMessage.accountKeys,
handlerMessage,
});
const encodedMessage = message.encode();
// Update relay data with the encoded message.
const newRelayData = { ...relayData, message: encodedMessage };
updateRelayData(newRelayData);
// Send approval and fill in one transaction.
const { approveIx, fillIx } = await createApproveAndFillIx(multicallHandlerCoder);
await sendAndConfirmTransaction(connection, new Transaction().add(approveIx, fillIx), [relayer]);
// Verify relayer's balance after the fill
const fRelayerBal = (await getAccount(connection, relayerATA)).amount;
assertSE(fRelayerBal, iRelayerBal - BigInt(relayAmount), "Relayer's balance should be reduced by the relay amount");
// Verify final recipient's balance after the fill
const finalRecipientAccount = await getAccount(connection, finalRecipientATA);
assertSE(
finalRecipientAccount.amount,
relayAmount,
"Final recipient's balance should be increased by the relay amount"
);
});
describe("Max token distributions within invoked message call", async () => {
const fillTokenDistributions = async (numberOfDistributions: number, bufferParams = false) => {
const iRelayerBal = (await getAccount(connection, relayerATA)).amount;
const distributionAmount = Math.floor(relayAmount / numberOfDistributions);
const recipientAccounts: PublicKey[] = [];
const transferInstructions: TransactionInstruction[] = [];
for (let i = 0; i < numberOfDistributions; i++) {
const recipient = Keypair.generate().publicKey;
const recipientATA = (await getOrCreateAssociatedTokenAccount(connection, payer, mint, recipient)).address;
recipientAccounts.push(recipientATA);
// Construct ix to transfer tokens from handler to the recipient.
const transferInstruction = createTransferCheckedInstruction(
handlerATA,
mint,
recipientATA,
handlerSigner,
distributionAmount,
mintDecimals
);
transferInstructions.push(transferInstruction);
}
const multicallHandlerCoder = new MulticallHandlerCoder(transferInstructions);
const handlerMessage = multicallHandlerCoder.encode();
const message = new AcrossPlusMessageCoder({
handler: handlerProgram.programId,
readOnlyLen: multicallHandlerCoder.readOnlyLen,
valueAmount: new BN(0),
accounts: multicallHandlerCoder.compiledMessage.accountKeys,
handlerMessage,
});
const encodedMessage = message.encode();
// Update relay data with the encoded message and total relay amount.
const newRelayData = {
...relayData,
message: encodedMessage,
outputAmount: new BN(distributionAmount * numberOfDistributions),
};
updateRelayData(newRelayData);
// Prepare approval and fill instructions as we will need to use Address Lookup Table (ALT).
const { approveIx, fillIx } = await createApproveAndFillIx(multicallHandlerCoder, bufferParams);
// Fill using the ALT.
const computeBudgetIx = ComputeBudgetProgram.setComputeUnitLimit({ units: 1_400_000 });
await sendTransactionWithLookupTable(connection, [computeBudgetIx, approveIx, fillIx], relayer);
// Verify relayer's balance after the fill
await new Promise((resolve) => setTimeout(resolve, 500)); // Make sure token transfers get processed.
const fRelayerBal = (await getAccount(connection, relayerATA)).amount;
assertSE(
fRelayerBal,
iRelayerBal - BigInt(distributionAmount * numberOfDistributions),
"Relayer's balance should be reduced by the relay amount"
);
// Verify all recipient account balances after the fill.
const recipientBalances = await Promise.all(
recipientAccounts.map(async (account) => (await connection.getTokenAccountBalance(account)).value.amount)
);
recipientBalances.forEach((balance, i) => {
assertSE(balance, distributionAmount, `Recipient account ${i} balance should match distribution amount`);
});
};
it("Max token distributions within invoked message call, regular params", async () => {
// Larger distribution would exceed message size limits.
const numberOfDistributions = 7;
await fillTokenDistributions(numberOfDistributions);
});
it("Max token distributions within invoked message call, buffer account params", async () => {
// Larger distribution count hits inner instruction size limit when invoking CPI to message handler on public
// devnet. On localnet this is not an issue, but we hit out of memory panic above 34 distributions.
const numberOfDistributions = 19;
await fillTokenDistributions(numberOfDistributions, true);
});
});
it("Sends lamports from the relayer to value recipient", async () => {
const valueAmount = new BN(1_000_000_000);
const valueRecipient = Keypair.generate().publicKey;
const multicallHandlerCoder = new MulticallHandlerCoder([], valueRecipient);
const handlerMessage = multicallHandlerCoder.encode();
const message = new AcrossPlusMessageCoder({
handler: handlerProgram.programId,
readOnlyLen: multicallHandlerCoder.readOnlyLen,
valueAmount,
accounts: multicallHandlerCoder.compiledMessage.accountKeys,
handlerMessage,
});
const encodedMessage = message.encode();
// Update relay data with the encoded message.
const newRelayData = { ...relayData, message: encodedMessage };
updateRelayData(newRelayData);
// Send approval and fill in one transaction.
const { approveIx, fillIx } = await createApproveAndFillIx(multicallHandlerCoder);
await sendAndConfirmTransaction(connection, new Transaction().add(approveIx, fillIx), [relayer]);
// Verify value recipient balance.
const valueRecipientAccount = await connection.getAccountInfo(valueRecipient);
if (valueRecipientAccount === null) throw new Error("Account not found");
assertSE(
valueRecipientAccount.lamports,
valueAmount.toNumber(),
"Value recipient's balance should be increased by the value amount"
);
});
it("Creates new ATA when forwarding tokens within invoked message call", async () => {
// We need precise estimate of required funding for ATA creation.
const valueAmount = await getMinimumBalanceForRentExemptAccount(connection);
const anotherRecipient = Keypair.generate().publicKey;
const anotherRecipientATA = getAssociatedTokenAddressSync(mint, anotherRecipient);
// Construct ix to create recipient ATA funded via handler PDA.
const createTokenAccountInstruction = createAssociatedTokenAccountInstruction(
handlerSigner,
anotherRecipientATA,
anotherRecipient,
mint
);
// Construct ix to transfer all tokens from handler to the recipient ATA.
const transferInstruction = createTransferCheckedInstruction(
handlerATA,
mint,
anotherRecipientATA,
handlerSigner,
relayData.outputAmount,
mintDecimals
);
// Encode both instructions with handler PDA as the payer for ATA initialization.
const multicallHandlerCoder = new MulticallHandlerCoder(
[createTokenAccountInstruction, transferInstruction],
handlerSigner
);
const handlerMessage = multicallHandlerCoder.encode();
const message = new AcrossPlusMessageCoder({
handler: handlerProgram.programId,
readOnlyLen: multicallHandlerCoder.readOnlyLen,
valueAmount: new BN(valueAmount), // Must exactly cover ATA creation.
accounts: multicallHandlerCoder.compiledMessage.accountKeys,
handlerMessage,
});
const encodedMessage = message.encode();
// Update relay data with the encoded message.
const newRelayData = { ...relayData, message: encodedMessage };
updateRelayData(newRelayData);
// Prepare approval and fill instructions as we will need to use Address Lookup Table (ALT).
const { approveIx, fillIx } = await createApproveAndFillIx(multicallHandlerCoder);
// Fill using the ALT.
await sendTransactionWithLookupTable(connection, [approveIx, fillIx], relayer);
// Verify recipient's balance after the fill
await new Promise((resolve) => setTimeout(resolve, 500)); // Make sure token transfer gets processed.
const anotherRecipientAccount = await getAccount(connection, anotherRecipientATA);
assertSE(
anotherRecipientAccount.amount,
relayAmount,
"Recipient's balance should be increased by the relay amount"
);
});
});