-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathSpokeUtils.ts
More file actions
1034 lines (945 loc) · 38.9 KB
/
SpokeUtils.ts
File metadata and controls
1034 lines (945 loc) · 38.9 KB
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { SvmSpokeClient } from "@across-protocol/contracts";
import { decodeFillStatusAccount, fetchState } from "@across-protocol/contracts/dist/src/svm/clients/SvmSpoke";
import { intToU8Array32 } from "@across-protocol/contracts/dist/src/svm/web3-v1/conversionUtils";
import { hashNonEmptyMessage } from "@across-protocol/contracts/dist/src/svm/web3-v1";
import {
ASSOCIATED_TOKEN_PROGRAM_ADDRESS,
TOKEN_PROGRAM_ADDRESS,
fetchMint,
getApproveCheckedInstruction,
getCreateAssociatedTokenIdempotentInstruction,
} from "@solana-program/token";
import {
Address,
appendTransactionMessageInstruction,
fetchEncodedAccount,
fetchEncodedAccounts,
getAddressEncoder,
getProgramDerivedAddress,
getU32Encoder,
getU64Encoder,
pipe,
ReadonlyUint8Array,
some,
type TransactionSigner,
} from "@solana/kit";
import assert from "assert";
import { arrayify, hexZeroPad, hexlify } from "ethers/lib/utils";
import { Logger } from "winston";
import { SYSTEM_PROGRAM_ADDRESS } from "@solana-program/system";
import { DepositWithBlock, FillStatus, FillWithBlock, RelayData, RelayExecutionEventInfo } from "../../interfaces";
import {
BigNumber,
EvmAddress,
SvmAddress,
Address as SdkAddress,
chainIsSvm,
chunk,
isUnsafeDepositId,
keccak256,
toAddressType,
} from "../../utils";
import {
SvmCpiEventsClient,
bigToU8a32,
createDefaultTransaction,
getEventAuthority,
getFillStatusPda,
getStatePda,
toAddress,
unwrapEventData,
} from "./";
import { EventWithData, SVMEventNames, SVMProvider } from "./types";
import { CHAIN_IDs } from "../../constants";
/**
* @note: Average Solana slot duration is about 400-500ms. We can be conservative
* and choose 400 to ensure that the most slots get included in our ranges
*/
export const SLOT_DURATION_MS = 400;
type ProtoFill = Omit<RelayData, "recipient" | "outputToken"> & {
destinationChainId: number;
recipient: SvmAddress;
outputToken: SvmAddress;
};
/**
* Retrieves the chain time at a particular slot.
*/
export async function getTimestampForSlot(provider: SVMProvider, slotNumber: number): Promise<number> {
// @note: getBlockTime receives a slot number, not a block number.
const slotTime = await provider.getBlockTime(BigInt(slotNumber)).send();
return Number(slotTime);
}
/**
* Returns the current fill deadline buffer.
* @param provider SVM Provider instance
* @param statePda Spoke Pool's State PDA
* @returns fill deadline buffer
*/
export async function getFillDeadline(provider: SVMProvider, statePda: Address): Promise<number> {
const state = await fetchState(provider, statePda);
return state.data.fillDeadlineBuffer;
}
/**
* Finds the deposit id at a specific block number.
* @param blockTag The block number to search for the deposit ID at.
* @returns The deposit ID.
*/
export function getDepositIdAtBlock(_contract: unknown, _blockTag: number): Promise<BigNumber> {
throw new Error("getDepositIdAtBlock: not implemented");
}
/**
* Helper function to query deposit events within a time window.
* @param eventClient - SvmCpiEventsClient instance
* @param depositId - The deposit ID to search for
* @param slot - The slot to search up to (defaults to current slot)
* @param secondsLookback - The number of seconds to look back for deposits (defaults to 2 days)
* @returns Array of deposit events within the slot window
*/
async function queryDepositEventsInWindow(
eventClient: SvmCpiEventsClient,
depositId: BigNumber,
slot?: bigint,
secondsLookback = 2 * 24 * 60 * 60 // 2 days
): Promise<EventWithData[]> {
// We can only perform this search when we have a safe deposit ID.
if (isUnsafeDepositId(depositId)) {
throw new Error(`Cannot find historical deposit for unsafe deposit ID ${depositId}.`);
}
const provider = eventClient.getRpc();
const currentSlot = await provider.getSlot({ commitment: "confirmed" }).send();
// If no slot is provided, use the current slot
// If a slot is provided, ensure it's not in the future
const endSlot = slot !== undefined ? BigInt(Math.min(Number(slot), Number(currentSlot))) : currentSlot;
// Calculate start slot (approximately secondsLookback seconds earlier)
const slotsInElapsed = BigInt(Math.round((secondsLookback * 1000) / SLOT_DURATION_MS));
const startSlot = endSlot - slotsInElapsed;
// Query for the deposit events with this limited slot range
return eventClient.queryEvents("FundsDeposited", startSlot, endSlot);
}
/**
* Finds deposit events within a time window (default 2 days) ending at the specified slot.
*
* @remarks
* This implementation uses a slot-limited search approach because Solana PDA state has
* limitations that prevent directly referencing old deposit IDs. Unlike EVM chains where
* we might use binary search across the entire chain history, in Solana we must query within
* a constrained slot range.
*
* The search window is calculated by:
* 1. Using the provided slot (or current confirmed slot if none is provided)
* 2. Looking back 2 days worth of slots from that point
*
* We use a 2-day window because:
* 1. Most valid deposits that need to be processed will be recent
* 2. This covers multiple bundle submission periods
* 3. It balances performance with practical deposit age
*
* @important
* This function may return `undefined` for valid deposit IDs that are older than the search
* window (approximately 2 days before the specified slot). This is an acceptable limitation
* as deposits this old are typically not relevant to current operations. This can be an issue
* if no proposal was made for a chain over a period of > 1.5 days.
*
* @param eventClient - SvmCpiEventsClient instance
* @param depositId - The deposit ID to search for
* @param slot - The slot to search up to (defaults to current slot). The search will look
* for deposits between (slot - secondsLookback) and slot.
* @param secondsLookback - The number of seconds to look back for deposits (defaults to 2 days).
* @returns The deposit if found within the slot window, undefined otherwise
*/
export async function findDeposit(
eventClient: SvmCpiEventsClient,
depositId: BigNumber,
slot?: bigint,
secondsLookback = 2 * 24 * 60 * 60 // 2 days
): Promise<DepositWithBlock | undefined> {
const depositEvents = await queryDepositEventsInWindow(eventClient, depositId, slot, secondsLookback);
// Find the first matching deposit event
const depositEvent = depositEvents.find((event) =>
depositId.eq((event.data as unknown as { depositId: BigNumber }).depositId)
);
// If no deposit event is found, return undefined
if (!depositEvent) {
return undefined;
}
const unwrappedDepositEvent = unwrapEventData(depositEvent.data) as Record<string, unknown>;
const destinationChainId = unwrappedDepositEvent.destinationChainId as number;
// Return the deposit event with block info
return {
txnRef: depositEvent.signature.toString(),
blockNumber: Number(depositEvent.slot),
txnIndex: 0,
logIndex: 0,
...unwrappedDepositEvent,
depositor: toAddressType(unwrappedDepositEvent.depositor as string, CHAIN_IDs.SOLANA),
recipient: toAddressType(unwrappedDepositEvent.recipient as string, destinationChainId),
inputToken: toAddressType(unwrappedDepositEvent.inputToken as string, CHAIN_IDs.SOLANA),
outputToken: toAddressType(unwrappedDepositEvent.outputToken as string, destinationChainId),
exclusiveRelayer: toAddressType(unwrappedDepositEvent.exclusiveRelayer as string, destinationChainId),
} as DepositWithBlock;
}
/**
* Finds all deposit events within a time window (default 2 days) ending at the specified slot.
*
* @remarks
* This implementation uses a slot-limited search approach because Solana PDA state has
* limitations that prevent directly referencing old deposit IDs. Unlike EVM chains where
* we might use binary search across the entire chain history, in Solana we must query within
* a constrained slot range.
*
* The search window is calculated by:
* 1. Using the provided slot (or current confirmed slot if none is provided)
* 2. Looking back 2 days worth of slots from that point
*
* We use a 2-day window because:
* 1. Most valid deposits that need to be processed will be recent
* 2. This covers multiple bundle submission periods
* 3. It balances performance with practical deposit age
*
* @important
* This function may return an empty array for valid deposit IDs that are older than the search
* window (approximately 2 days before the specified slot). This is an acceptable limitation
* as deposits this old are typically not relevant to current operations. This can be an issue
* if no proposal was made for a chain over a period of > 1.5 days.
*
* @param eventClient - SvmCpiEventsClient instance
* @param depositId - The deposit ID to search for
* @param slot - The slot to search up to (defaults to current slot). The search will look
* for deposits between (slot - secondsLookback) and slot.
* @param secondsLookback - The number of seconds to look back for deposits (defaults to 2 days).
* @returns Array of deposits if found within the slot window, empty array otherwise
*/
export async function findAllDeposits(
eventClient: SvmCpiEventsClient,
depositId: BigNumber,
slot?: bigint,
secondsLookback = 2 * 24 * 60 * 60 // 2 days
): Promise<DepositWithBlock[]> {
const depositEvents = await queryDepositEventsInWindow(eventClient, depositId, slot, secondsLookback);
// Filter for all matching deposit events
const matchingEvents = depositEvents.filter((event) =>
depositId.eq((event.data as unknown as { depositId: BigNumber }).depositId)
);
// Return all deposit events with block info
return matchingEvents.map((event) => ({
txnRef: event.signature.toString(),
blockNumber: Number(event.slot),
txnIndex: 0,
logIndex: 0,
...(unwrapEventData(event.data) as Record<string, unknown>),
})) as DepositWithBlock[];
}
/**
* Resolves the fill status of a deposit at a specific slot or at the current confirmed one.
*
* If no slot is provided, attempts to solve the fill status using the PDA. Otherwise, it is reconstructed from PDA events.
*
* @param programId - The spoke pool program ID.
* @param relayData - Deposit information used to locate the fill status.
* @param destinationChainId - Destination chain ID (must be an SVM chain).
* @param provider - SVM provider instance.
* @param svmEventsClient - SVM events client for querying events.
* @param atHeight - (Optional) Specific slot number to query. Defaults to the latest confirmed slot.
* @returns The fill status for the deposit at the specified or current slot.
*/
export async function relayFillStatus(
programId: Address,
relayData: RelayData,
destinationChainId: number,
svmEventsClient: SvmCpiEventsClient,
atHeight?: number
): Promise<FillStatus> {
assert(chainIsSvm(destinationChainId), "Destination chain must be an SVM chain");
const provider = svmEventsClient.getRpc();
// Get fill status PDA using relayData
const fillStatusPda = await getFillStatusPda(programId, relayData, destinationChainId);
const currentSlot = await provider.getSlot({ commitment: "confirmed" }).send();
// If no specific slot is requested, try fetching the current status from the PDA
if (atHeight === undefined) {
const [fillStatusAccount, currentSlotTimestamp] = await Promise.all([
fetchEncodedAccount(provider, fillStatusPda, { commitment: "confirmed" }),
provider.getBlockTime(currentSlot).send(),
]);
// If the PDA exists, return the stored fill status
if (fillStatusAccount.exists) {
const decodedAccountData = decodeFillStatusAccount(fillStatusAccount);
return decodedAccountData.data.status;
}
// If the PDA doesn't exist and the deadline hasn't passed yet, the deposit must be unfilled,
// since PDAs can't be closed before the fill deadline.
else if (Number(currentSlotTimestamp) < relayData.fillDeadline) {
return FillStatus.Unfilled;
}
}
// If status couldn't be determined from the PDA, or if a specific slot was requested, reconstruct the status from events
const toSlot = atHeight ? BigInt(atHeight) : currentSlot;
return resolveFillStatusFromPdaEvents(fillStatusPda, toSlot, svmEventsClient);
}
/**
* Resolves fill statuses for multiple deposits at a specific or latest confirmed slot,
* using PDAs when possible and falling back to events if needed.
*
* @param programId The spoke pool program ID.
* @param relayData An array of relay data to resolve fill statuses for.
* @param destinationChainId The destination chain ID (must be an SVM chain).
* @param provider SVM Provider instance.
* @param svmEventsClient SVM events client instance for querying events.
* @param atHeight (Optional) The slot number to query at. If omitted, queries the latest confirmed slot.
* @returns An array of fill statuses for the specified deposits at the requested slot (or at the current confirmed slot).
*/
export async function fillStatusArray(
programId: Address,
relayData: RelayData[],
destinationChainId: number,
svmEventsClient: SvmCpiEventsClient,
atHeight?: number,
logger?: Logger
): Promise<(FillStatus | undefined)[]> {
assert(chainIsSvm(destinationChainId), "Destination chain must be an SVM chain");
const provider = svmEventsClient.getRpc();
const chunkSize = 100;
const chunkedRelayData = chunk(relayData, chunkSize);
// Get all PDAs
const fillStatusPdas = (
await Promise.all(
chunkedRelayData.map((relayDataChunk) =>
Promise.all(relayDataChunk.map((relayData) => getFillStatusPda(programId, relayData, destinationChainId)))
)
)
).flat();
if (atHeight !== undefined && logger) {
logger.warn({
at: "SvmSpokeUtils#fillStatusArray",
message:
"Querying specific slots for large arrays is slow. For current status, omit 'atHeight' param to use latest confirmed slot instead.",
});
}
// If no specific slot is requested, try fetching current statuses from PDAs
// Otherwise, initialize all statuses as undefined
const fillStatuses: (FillStatus | undefined)[] =
atHeight === undefined
? await fetchBatchFillStatusFromPdaAccounts(provider, fillStatusPdas, relayData)
: new Array(relayData.length).fill(undefined);
// Collect indices of deposits that still need their status resolved
const missingStatuses = fillStatuses.reduce<number[]>((acc, status, index) => {
if (status === undefined) {
acc.push(index);
}
return acc;
}, []);
// Chunk the missing deposits for batch processing
const missingChunked = chunk(missingStatuses, chunkSize);
const missingResults: { index: number; fillStatus: FillStatus }[] = [];
// Determine the toSlot to use for event reconstruction
const toSlot = atHeight ? BigInt(atHeight) : await provider.getSlot({ commitment: "confirmed" }).send();
// @note: This path is mostly used for deposits past their fill deadline.
// If it becomes a bottleneck, consider returning an "Unknown" status that can be handled downstream.
for (const chunk of missingChunked) {
const chunkResults = await Promise.all(
chunk.map(async (missingIndex) => {
return {
index: missingIndex,
fillStatus: await resolveFillStatusFromPdaEvents(fillStatusPdas[missingIndex], toSlot, svmEventsClient),
};
})
);
missingResults.push(...chunkResults);
}
// Fill in missing statuses back to the result array
missingResults.forEach(({ index, fillStatus }) => {
fillStatuses[index] = fillStatus;
});
return fillStatuses;
}
/**
* Finds the `FilledRelay` event for a given deposit within the provided slot range.
*
* @param relayData - Deposit information that is used to complete a fill.
* @param destinationChainId - Destination chain ID (must be an SVM chain).
* @param svmEventsClient - SVM events client instance for querying events.
* @param fromSlot - Starting slot to search.
* @param toSlot (Optional) Ending slot to search. If not provided, the current confirmed slot will be used.
* @returns The fill event with block info, or `undefined` if not found.
*/
export async function findFillEvent(
relayData: RelayData,
destinationChainId: number,
svmEventsClient: SvmCpiEventsClient,
fromSlot: number,
toSlot?: number
): Promise<FillWithBlock | undefined> {
assert(chainIsSvm(destinationChainId), "Destination chain must be an SVM chain");
toSlot ??= Number(await svmEventsClient.getRpc().getSlot({ commitment: "confirmed" }).send());
// Get fillStatus PDA using relayData
const programId = svmEventsClient.getProgramAddress();
const fillStatusPda = await getFillStatusPda(programId, relayData, destinationChainId);
// Get fill events from fillStatus PDA
const fillEvents = await svmEventsClient.queryDerivedAddressEvents(
SVMEventNames.FilledRelay,
fillStatusPda,
BigInt(fromSlot),
BigInt(toSlot),
{ limit: 10 }
);
assert(fillEvents.length <= 1, `Expected at most one fill event for ${fillStatusPda}, got ${fillEvents.length}`);
if (fillEvents.length > 0) {
const rawFillEvent = fillEvents[0];
const eventData = unwrapEventData(rawFillEvent.data) as FillWithBlock & {
depositor: string;
recipient: string;
inputToken: string;
outputToken: string;
exclusiveRelayer: string;
relayer: string;
relayExecutionInfo: RelayExecutionEventInfo & { updatedRecipient: string };
};
const originChainId = eventData.originChainId;
const parsedFillEvent = {
...eventData,
transactionHash: rawFillEvent.signature,
blockNumber: Number(rawFillEvent.slot),
transactionIndex: 0,
logIndex: 0,
destinationChainId,
inputToken: toAddressType(eventData.inputToken, originChainId),
outputToken: toAddressType(eventData.outputToken, destinationChainId),
relayer: toAddressType(eventData.relayer, destinationChainId),
exclusiveRelayer: toAddressType(eventData.exclusiveRelayer, destinationChainId),
depositor: toAddressType(eventData.depositor, originChainId),
recipient: toAddressType(eventData.recipient, destinationChainId),
relayExecutionInfo: {
...eventData.relayExecutionInfo,
updatedRecipient: eventData.relayExecutionInfo.updatedRecipient,
},
} as FillWithBlock;
return parsedFillEvent;
}
return undefined;
}
/**
* @param spokePool Address (program ID) of the SvmSpoke.
* @param relayData RelayData instance, supplemented with destinationChainId
* @param relayer Address of the relayer filling the deposit.
* @param repaymentChainId Optional repaymentChainId (defaults to destinationChainId).
* @returns An Ethers UnsignedTransaction instance.
*/
export async function fillRelayInstruction(
spokePool: SvmAddress,
relayData: ProtoFill,
signer: TransactionSigner<string>,
recipientTokenAccount: Address<string>,
repaymentAddress: EvmAddress | SvmAddress = SvmAddress.from(signer.address),
repaymentChainId = relayData.destinationChainId
) {
const program = toAddress(spokePool);
assert(
repaymentAddress.isValidOn(repaymentChainId),
`Invalid repayment address for chain ${repaymentChainId}: ${repaymentAddress.toNative()}.`
);
const _relayDataHash = getRelayDataHash(relayData, relayData.destinationChainId);
const relayDataHash = new Uint8Array(Buffer.from(_relayDataHash.slice(2), "hex"));
const relayer = SvmAddress.from(signer.address);
// Create ATA for the relayer and recipient token accounts
const relayerTokenAccount = await getAssociatedTokenAddress(relayer, relayData.outputToken);
const [statePda, fillStatusPda, eventAuthority] = await Promise.all([
getStatePda(program),
getFillStatusPda(program, relayData, relayData.destinationChainId),
getEventAuthority(program),
]);
const depositIdBuffer = new Uint8Array(32);
const shortenedBuffer = new Uint8Array(Buffer.from(relayData.depositId.toHexString().slice(2), "hex"));
depositIdBuffer.set(shortenedBuffer, 32 - shortenedBuffer.length);
const delegatePda = await getFillRelayDelegatePda(
relayDataHash,
BigInt(repaymentChainId),
toAddress(relayer),
program
);
const [recipient, outputToken, exclusiveRelayer, depositor, inputToken] = [
relayData.recipient,
relayData.outputToken,
relayData.exclusiveRelayer,
relayData.depositor,
relayData.inputToken,
].map(toAddress);
return SvmSpokeClient.getFillRelayInstruction({
signer,
state: statePda,
delegate: toAddress(SvmAddress.from(delegatePda.toString())),
mint: outputToken,
relayerTokenAccount: relayerTokenAccount,
recipientTokenAccount: recipientTokenAccount,
fillStatus: fillStatusPda,
eventAuthority,
program,
relayHash: relayDataHash,
relayData: some({
depositor,
recipient,
exclusiveRelayer,
inputToken,
outputToken,
inputAmount: bigToU8a32(relayData.inputAmount.toBigInt()),
outputAmount: relayData.outputAmount.toBigInt(),
originChainId: BigInt(relayData.originChainId),
fillDeadline: relayData.fillDeadline,
exclusivityDeadline: relayData.exclusivityDeadline,
depositId: depositIdBuffer,
message: new Uint8Array(Buffer.from(relayData.message.slice(2), "hex")),
}),
repaymentChainId: some(BigInt(repaymentChainId)),
repaymentAddress: toAddress(repaymentAddress),
});
}
/**
* @param mint Address of the token corresponding to the account being made.
* @param relayer Address of the relayer filling the deposit.
* @returns An instruction for creating a new token account.
*/
export function createTokenAccountsInstruction(
mint: SvmAddress,
relayer: TransactionSigner<string>
): SvmSpokeClient.CreateTokenAccountsInstruction {
return SvmSpokeClient.getCreateTokenAccountsInstruction({
signer: relayer,
mint: toAddress(mint),
});
}
/**
* @notice Return the fillRelay transaction for a given deposit
* @param spokePoolAddr Address of the spoke pool we're trying to fill through
* @param solanaClient RPC client to interact with Solana chain
* @param relayData RelayData instance, supplemented with destinationChainId
* @param signer signer associated with the relayer creating a Fill. Can be VoidSigner for gas estimation
* @param repaymentChainId Chain id where relayer repayment is desired
* @param repaymentAddress Address to which repayment will go to on repaymentChainId
* @returns FillRelay transaction
*/
export async function getFillRelayTx(
spokePoolAddr: SvmAddress,
solanaClient: SVMProvider,
relayData: Omit<RelayData, "recipent" | "outputToken"> & {
destinationChainId: number;
recipient: SvmAddress;
outputToken: SvmAddress;
},
signer: TransactionSigner,
repaymentChainId: number,
repaymentAddress: SdkAddress
) {
const { depositor, recipient, inputToken, outputToken, exclusiveRelayer, destinationChainId } = relayData;
// tsc appeasement...should be unnecessary, but isn't. @todo Identify why.
assert(recipient.isSVM(), `getFillRelayTx: recipient not an SVM address (${recipient})`);
assert(
repaymentAddress.isValidOn(repaymentChainId),
`getFillRelayTx: repayment address ${repaymentAddress} not valid on chain ${repaymentChainId})`
);
const program = toAddress(spokePoolAddr);
const _relayDataHash = getRelayDataHash(relayData, destinationChainId);
const relayDataHash = new Uint8Array(Buffer.from(_relayDataHash.slice(2), "hex"));
const [state, delegate] = await Promise.all([
getStatePda(program),
getFillRelayDelegatePda(relayDataHash, BigInt(repaymentChainId), toAddress(repaymentAddress), program),
]);
const mint = toAddress(outputToken);
const mintInfo = await fetchMint(solanaClient, mint);
const [recipientAta, relayerAta, fillStatus, eventAuthority] = await Promise.all([
getAssociatedTokenAddress(recipient, outputToken, mintInfo.programAddress),
getAssociatedTokenAddress(SvmAddress.from(signer.address), outputToken, mintInfo.programAddress),
getFillStatusPda(program, relayData, destinationChainId),
getEventAuthority(program),
]);
const svmRelayData: SvmSpokeClient.FillRelayInput["relayData"] = {
depositor: toAddress(depositor),
recipient: toAddress(recipient),
exclusiveRelayer: toAddress(exclusiveRelayer),
inputToken: toAddress(inputToken),
outputToken: mint,
inputAmount: bigToU8a32(relayData.inputAmount.toBigInt()),
outputAmount: relayData.outputAmount.toBigInt(),
originChainId: relayData.originChainId,
depositId: new Uint8Array(intToU8Array32(relayData.depositId.toNumber())),
fillDeadline: relayData.fillDeadline,
exclusivityDeadline: relayData.exclusivityDeadline,
message: new Uint8Array(Buffer.from(relayData.message, "hex")),
};
const fillInput: SvmSpokeClient.FillRelayInput = {
signer: signer,
state,
delegate,
mint,
relayerTokenAccount: relayerAta,
recipientTokenAccount: recipientAta,
fillStatus,
tokenProgram: mintInfo.programAddress,
associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ADDRESS,
systemProgram: SYSTEM_PROGRAM_ADDRESS,
eventAuthority,
program,
relayHash: relayDataHash,
relayData: svmRelayData,
repaymentChainId: BigInt(repaymentChainId),
repaymentAddress: toAddress(repaymentAddress),
};
// Pass createRecipientAtaIfNeeded =true to the createFillInstruction function to create the recipient token account
// if it doesn't exist.
return createFillInstruction(signer, solanaClient, fillInput, mintInfo.data.decimals, true);
}
/**
* Creates a fill instruction.
* @param signer - The signer of the transaction.
* @param solanaClient - The Solana client.
* @param fillInput - The fill input.
* @param tokenDecimals - The token decimals.
* @param createRecipientAtaIfNeeded - Whether to create a recipient token account.
* @returns The fill instruction.
*/
export const createFillInstruction = async (
signer: TransactionSigner,
solanaClient: SVMProvider,
fillInput: SvmSpokeClient.FillRelayInput,
tokenDecimals: number,
createRecipientAtaIfNeeded: boolean = true
) => {
const mintInfo = await fetchMint(solanaClient, fillInput.mint);
const approveIx = getApproveCheckedInstruction(
{
source: fillInput.relayerTokenAccount,
mint: fillInput.mint,
delegate: fillInput.delegate,
owner: fillInput.signer,
amount: (fillInput.relayData as SvmSpokeClient.RelayDataArgs).outputAmount,
decimals: tokenDecimals,
},
{
programAddress: mintInfo.programAddress,
}
);
const getCreateAssociatedTokenIdempotentIx = () =>
getCreateAssociatedTokenIdempotentInstruction({
payer: signer,
owner: (fillInput.relayData as SvmSpokeClient.RelayDataArgs).recipient,
mint: fillInput.mint,
ata: fillInput.recipientTokenAccount,
systemProgram: SYSTEM_PROGRAM_ADDRESS,
tokenProgram: fillInput.tokenProgram,
});
const createFillIx = SvmSpokeClient.getFillRelayInstruction(fillInput);
return pipe(
await createDefaultTransaction(solanaClient, signer),
(tx) =>
createRecipientAtaIfNeeded ? appendTransactionMessageInstruction(getCreateAssociatedTokenIdempotentIx(), tx) : tx,
(tx) => appendTransactionMessageInstruction(approveIx, tx),
(tx) => appendTransactionMessageInstruction(createFillIx, tx)
);
};
/**
* Creates a deposit instruction.
* @param signer - The signer of the transaction.
* @param solanaClient - The Solana client.
* @param depositInput - The deposit input.
* @param tokenDecimals - The token decimals.
* @param createVaultAtaIfNeeded - Whether to create a vault token account.
* @returns The deposit instruction.
*/
export const createDepositInstruction = async (
signer: TransactionSigner,
solanaClient: SVMProvider,
depositInput: SvmSpokeClient.DepositInput,
tokenDecimals: number,
createVaultAtaIfNeeded: boolean = true
) => {
const getCreateAssociatedTokenIdempotentIx = () =>
getCreateAssociatedTokenIdempotentInstruction({
payer: signer,
owner: depositInput.state,
mint: depositInput.mint,
ata: depositInput.vault,
systemProgram: depositInput.systemProgram,
tokenProgram: depositInput.tokenProgram,
});
const mintInfo = await fetchMint(solanaClient, depositInput.mint);
const approveIx = getApproveCheckedInstruction(
{
source: depositInput.depositorTokenAccount,
mint: depositInput.mint,
delegate: depositInput.delegate,
owner: depositInput.depositor,
amount: depositInput.inputAmount,
decimals: tokenDecimals,
},
{
programAddress: mintInfo.programAddress,
}
);
const depositIx = SvmSpokeClient.getDepositInstruction(depositInput);
return pipe(
await createDefaultTransaction(solanaClient, signer),
(tx) =>
createVaultAtaIfNeeded ? appendTransactionMessageInstruction(getCreateAssociatedTokenIdempotentIx(), tx) : tx,
(tx) => appendTransactionMessageInstruction(approveIx, tx),
(tx) => appendTransactionMessageInstruction(depositIx, tx)
);
};
/**
* Creates a request slow fill instruction.
* @param signer - The signer of the transaction.
* @param solanaClient - The Solana client.
* @param depositInput - The deposit input.
* @returns The request slow fill instruction.
*/
export const createRequestSlowFillInstruction = async (
signer: TransactionSigner,
solanaClient: SVMProvider,
depositInput: SvmSpokeClient.RequestSlowFillInput
) => {
const requestSlowFillIx = SvmSpokeClient.getRequestSlowFillInstruction(depositInput);
return pipe(await createDefaultTransaction(solanaClient, signer), (tx) =>
appendTransactionMessageInstruction(requestSlowFillIx, tx)
);
};
/**
* Creates a close fill PDA instruction.
* @param signer - The signer of the transaction.
* @param solanaClient - The Solana client.
* @param fillStatusPda - The fill status PDA.
* @returns The close fill PDA instruction.
*/
export const createCloseFillPdaInstruction = async (
signer: TransactionSigner,
solanaClient: SVMProvider,
fillStatusPda: Address
) => {
const closeFillPdaIx = SvmSpokeClient.getCloseFillPdaInstruction({
signer,
state: await getStatePda(SvmSpokeClient.SVM_SPOKE_PROGRAM_ADDRESS),
fillStatus: fillStatusPda,
});
return pipe(await createDefaultTransaction(solanaClient, signer), (tx) =>
appendTransactionMessageInstruction(closeFillPdaIx, tx)
);
};
export async function getAssociatedTokenAddress(
owner: SvmAddress,
mint: SvmAddress,
tokenProgramId: Address<string> = TOKEN_PROGRAM_ADDRESS
): Promise<Address<string>> {
const encoder = getAddressEncoder();
const [associatedToken] = await getProgramDerivedAddress({
programAddress: ASSOCIATED_TOKEN_PROGRAM_ADDRESS,
seeds: [encoder.encode(toAddress(owner)), encoder.encode(tokenProgramId), encoder.encode(toAddress(mint))],
});
return associatedToken;
}
export function getRelayDataHash(relayData: RelayData, destinationChainId: number): string {
const addressEncoder = getAddressEncoder();
const uint64Encoder = getU64Encoder();
const uint32Encoder = getU32Encoder();
assert(relayData.message.startsWith("0x"), "Message must be a hex string");
const encodeAddress = (data: SdkAddress) => Uint8Array.from(addressEncoder.encode(toAddress(data)));
const contentToHash = Buffer.concat([
encodeAddress(relayData.depositor),
encodeAddress(relayData.recipient),
encodeAddress(relayData.exclusiveRelayer),
encodeAddress(relayData.inputToken),
encodeAddress(relayData.outputToken),
arrayify(hexZeroPad(hexlify(relayData.inputAmount), 32)),
Uint8Array.from(uint64Encoder.encode(BigInt(relayData.outputAmount.toString()))),
Uint8Array.from(uint64Encoder.encode(BigInt(relayData.originChainId.toString()))),
arrayify(hexZeroPad(hexlify(relayData.depositId), 32)),
Uint8Array.from(uint32Encoder.encode(relayData.fillDeadline)),
Uint8Array.from(uint32Encoder.encode(relayData.exclusivityDeadline)),
hashNonEmptyMessage(Buffer.from(arrayify(relayData.message))),
Uint8Array.from(uint64Encoder.encode(BigInt(destinationChainId))),
]);
return keccak256(contentToHash);
}
async function resolveFillStatusFromPdaEvents(
fillStatusPda: Address,
toSlot: bigint,
svmEventsClient: SvmCpiEventsClient
): Promise<FillStatus> {
// Get fill and requested slow fill events from fillStatus PDA
const eventsToQuery = [SVMEventNames.FilledRelay, SVMEventNames.RequestedSlowFill];
const relevantEvents = (
await Promise.all(
eventsToQuery.map((eventName) =>
// PDAs should have only a few events, requesting up to 10 should be enough.
svmEventsClient.queryDerivedAddressEvents(eventName, fillStatusPda, undefined, toSlot, { limit: 10 })
)
)
).flat();
if (relevantEvents.length === 0) {
// No fill or requested slow fill events found for this PDA
return FillStatus.Unfilled;
}
// Sort events in ascending order of slot number
relevantEvents.sort((a, b) => Number(a.slot - b.slot));
// At this point we have an ordered array of only fill and requested slow fill events and
// since it's not possible to submit a slow fill request once a fill has been submitted,
// we can use the last event in the list to determine the fill status at the requested slot.
const fillStatusEvent = relevantEvents.pop();
switch (fillStatusEvent!.name) {
case SVMEventNames.FilledRelay:
return FillStatus.Filled;
case SVMEventNames.RequestedSlowFill:
return FillStatus.RequestedSlowFill;
default:
throw new Error(`Unexpected event name: ${fillStatusEvent!.name}`);
}
}
/**
* Attempts to resolve the fill status for an array of deposits by reading their fillStatus PDAs.
*
* - If a PDA exists, the status is read directly from it.
* - If the PDA does not exist but the deposit's fill deadline has not passed, the deposit is considered unfilled.
* - If the PDA does not exist and the fill deadline has passed, the status cannot be determined and is set to undefined.
*
* Assumes PDAs can only be closed after the fill deadline expires.
*
* @param provider SVM provider instance
* @param fillStatusPdas An array of fill status PDAs to retrieve the fill status for.
* @param relayData An array of relay data from which the fill status PDAs were derived.
*/
async function fetchBatchFillStatusFromPdaAccounts(
provider: SVMProvider,
fillStatusPdas: Address[],
relayDataArray: RelayData[]
): Promise<(FillStatus | undefined)[]> {
const chunkSize = 100; // SVM method getMultipleAccounts allows a max of 100 addresses per request
const currentSlot = await provider.getSlot({ commitment: "confirmed" }).send();
const [pdaAccounts, currentSlotTimestamp] = await Promise.all([
Promise.all(
chunk(fillStatusPdas, chunkSize).map((chunk) =>
fetchEncodedAccounts(provider, chunk, { commitment: "confirmed" })
)
),
provider.getBlockTime(currentSlot).send(),
]);
const fillStatuses = pdaAccounts.flat().map((account, index) => {
// If the PDA exists, we can fetch the status directly.
if (account.exists) {
const decodedAccount = decodeFillStatusAccount(account);
return decodedAccount.data.status;
}
// If the PDA doesn't exist and the deadline hasn't passed yet, the deposit must be unfilled,
// since PDAs can't be closed before the fill deadline.
else if (Number(currentSlotTimestamp) < relayDataArray[index].fillDeadline) {
return FillStatus.Unfilled;
}
// If the PDA doesn't exist and the fill deadline has passed, then the status can't be determined and is set to undefined.
return undefined;
});
return fillStatuses;
}
/**
* Returns the delegate PDA for deposit.
*/
export async function getDepositDelegatePda(
depositData: {
depositor: Address<string>;
recipient: Address<string>;
inputToken: Address<string>;
outputToken: Address<string>;
inputAmount: bigint;
outputAmount: ReadonlyUint8Array;
destinationChainId: bigint;
exclusiveRelayer: Address<string>;
quoteTimestamp: bigint;
fillDeadline: bigint;
exclusivityParameter: bigint;
message: Uint8Array;
},
programId: Address<string>
): Promise<Address<string>> {
const addrEnc = getAddressEncoder();
const u64 = getU64Encoder();
const u32 = getU32Encoder();
const parts: Uint8Array[] = [
Uint8Array.from(addrEnc.encode(depositData.depositor)),
Uint8Array.from(addrEnc.encode(depositData.recipient)),
Uint8Array.from(addrEnc.encode(depositData.inputToken)),
Uint8Array.from(addrEnc.encode(depositData.outputToken)),
Uint8Array.from(u64.encode(depositData.inputAmount)),
Uint8Array.from(depositData.outputAmount),
Uint8Array.from(u64.encode(depositData.destinationChainId)),
Uint8Array.from(addrEnc.encode(depositData.exclusiveRelayer)),
Uint8Array.from(u32.encode(depositData.quoteTimestamp)),
Uint8Array.from(u32.encode(depositData.fillDeadline)),
Uint8Array.from(u32.encode(depositData.exclusivityParameter)),
Uint8Array.from(u32.encode(BigInt(depositData.message.length))),
depositData.message,
];
const seedHash = Buffer.from(keccak256(Buffer.concat(parts)).slice(2), "hex");
const [pda] = await getProgramDerivedAddress({
programAddress: programId,
seeds: [Buffer.from("delegate"), seedHash],
});
return pda;
}
/**
* Returns the delegate PDA for depositNow.
*/
export async function getDepositNowDelegatePda(
depositData: {
depositor: Address<string>;
recipient: Address<string>;
inputToken: Address<string>;
outputToken: Address<string>;
inputAmount: bigint;
outputAmount: ReadonlyUint8Array;
destinationChainId: bigint;
exclusiveRelayer: Address<string>;
fillDeadlineOffset: bigint;
exclusivityPeriod: bigint;
message: Uint8Array;
},
programId: Address<string>
): Promise<Address<string>> {
const addrEnc = getAddressEncoder();
const u64 = getU64Encoder();
const u32 = getU32Encoder();
const parts: Uint8Array[] = [
Uint8Array.from(addrEnc.encode(depositData.depositor)),
Uint8Array.from(addrEnc.encode(depositData.recipient)),
Uint8Array.from(addrEnc.encode(depositData.inputToken)),
Uint8Array.from(addrEnc.encode(depositData.outputToken)),
Uint8Array.from(u64.encode(depositData.inputAmount)),
Uint8Array.from(depositData.outputAmount),
Uint8Array.from(u64.encode(depositData.destinationChainId)),
Uint8Array.from(addrEnc.encode(depositData.exclusiveRelayer)),
Uint8Array.from(u32.encode(depositData.fillDeadlineOffset)),
Uint8Array.from(u32.encode(depositData.exclusivityPeriod)),
Uint8Array.from(u32.encode(BigInt(depositData.message.length))),
depositData.message,
];
const seedHash = Buffer.from(keccak256(Buffer.concat(parts)).slice(2), "hex");
const [pda] = await getProgramDerivedAddress({