-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathBundleDataClient.ts
1587 lines (1471 loc) · 75.5 KB
/
BundleDataClient.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
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 assert from "assert";
import _ from "lodash";
import {
ProposedRootBundle,
SlowFillRequestWithBlock,
SpokePoolClientsByChain,
FillType,
FillStatus,
LoadDataReturnValue,
BundleDepositsV3,
BundleExcessSlowFills,
BundleFillsV3,
BundleFillV3,
BundleSlowFills,
ExpiredDepositsToRefundV3,
Clients,
CombinedRefunds,
FillWithBlock,
Deposit,
DepositWithBlock,
} from "../../interfaces";
import { SpokePoolClient } from "..";
import {
BigNumber,
bnZero,
queryHistoricalDepositForFill,
assign,
fixedPointAdjustment,
isDefined,
toBN,
forEachAsync,
getBlockRangeForChain,
getImpliedBundleBlockRanges,
getMessageHash,
getRelayEventKey,
isSlowFill,
mapAsync,
bnUint32Max,
isZeroValueDeposit,
findFillEvent,
isZeroValueFillOrSlowFillRequest,
chainIsEvm,
Address,
duplicateEvent,
} from "../../utils";
import winston from "winston";
import {
BundleData,
BundleDataSS,
getEndBlockBuffers,
getRefundInformationFromFill,
getRefundsFromBundle,
getWidestPossibleExpectedBlockRange,
isChainDisabled,
prettyPrintV3SpokePoolEvents,
V3DepositWithBlock,
V3FillWithBlock,
verifyFillRepayment,
} from "./utils";
import { UNDEFINED_MESSAGE_HASH } from "../../constants";
// max(uint256) - 1
export const INFINITE_FILL_DEADLINE = bnUint32Max;
type DataCache = Record<string, Promise<LoadDataReturnValue>>;
// V3 dictionary helper functions
function updateExpiredDepositsV3(dict: ExpiredDepositsToRefundV3, deposit: V3DepositWithBlock): void {
// A deposit refund for a deposit is invalid if the depositor has a bytes32 address input for an EVM chain. It is valid otherwise.
if (chainIsEvm(deposit.originChainId) && !deposit.depositor.isValidEvmAddress()) {
return;
}
const { originChainId, inputToken: _inputToken } = deposit;
const inputToken = _inputToken.toString();
if (!dict?.[originChainId]?.[inputToken]) {
assign(dict, [originChainId, inputToken], []);
}
dict[originChainId][inputToken].push(deposit);
}
function updateBundleDepositsV3(dict: BundleDepositsV3, deposit: V3DepositWithBlock): void {
const { originChainId, inputToken: _inputToken } = deposit;
const inputToken = _inputToken.toString();
if (!dict?.[originChainId]?.[inputToken]) {
assign(dict, [originChainId, inputToken], []);
}
dict[originChainId][inputToken].push(deposit);
}
function updateBundleFillsV3(
dict: BundleFillsV3,
fill: V3FillWithBlock,
lpFeePct: BigNumber,
repaymentChainId: number,
repaymentToken: Address,
repaymentAddress: Address
): void {
// We shouldn't pass any unrepayable fills into this function, so we perform an extra safety check.
assert(
chainIsEvm(repaymentChainId) && fill.relayer.isValidEvmAddress(),
"validatedBundleV3Fills dictionary should only contain fills with valid repayment information"
);
if (!dict?.[repaymentChainId]?.[repaymentToken.toString()]) {
assign(dict, [repaymentChainId, repaymentToken.toString()], {
fills: [],
totalRefundAmount: bnZero,
realizedLpFees: bnZero,
refunds: {},
});
}
const bundleFill: BundleFillV3 = { ...fill, lpFeePct, relayer: repaymentAddress };
// Add all fills, slow and fast, to dictionary.
assign(dict, [repaymentChainId, repaymentToken, "fills"], [bundleFill]);
// All fills update the bundle LP fees.
const refundObj = dict[repaymentChainId][repaymentToken.toString()];
const realizedLpFee = bundleFill.inputAmount.mul(bundleFill.lpFeePct).div(fixedPointAdjustment);
refundObj.realizedLpFees = refundObj.realizedLpFees ? refundObj.realizedLpFees.add(realizedLpFee) : realizedLpFee;
// Only fast fills get refunded.
if (!isSlowFill(bundleFill)) {
const refundAmount = bundleFill.inputAmount.mul(fixedPointAdjustment.sub(lpFeePct)).div(fixedPointAdjustment);
refundObj.totalRefundAmount = refundObj.totalRefundAmount
? refundObj.totalRefundAmount.add(refundAmount)
: refundAmount;
// Instantiate dictionary if it doesn't exist.
refundObj.refunds ??= {};
if (refundObj.refunds[bundleFill.relayer.toString()]) {
refundObj.refunds[bundleFill.relayer.toString()] =
refundObj.refunds[bundleFill.relayer.toString()].add(refundAmount);
} else {
refundObj.refunds[bundleFill.relayer.toString()] = refundAmount;
}
}
}
function updateBundleExcessSlowFills(
dict: BundleExcessSlowFills,
deposit: V3DepositWithBlock & { lpFeePct: BigNumber }
): void {
const { destinationChainId, outputToken: _outputToken } = deposit;
const outputToken = _outputToken.toString();
if (!dict?.[destinationChainId]?.[outputToken]) {
assign(dict, [destinationChainId, outputToken], []);
}
dict[destinationChainId][outputToken].push(deposit);
}
function updateBundleSlowFills(dict: BundleSlowFills, deposit: V3DepositWithBlock & { lpFeePct: BigNumber }): void {
if (chainIsEvm(deposit.destinationChainId) && !deposit.recipient.isValidEvmAddress()) {
return;
}
const { destinationChainId, outputToken: _outputToken } = deposit;
const outputToken = _outputToken.toString();
if (!dict?.[destinationChainId]?.[outputToken]) {
assign(dict, [destinationChainId, outputToken], []);
}
dict[destinationChainId][outputToken].push(deposit);
}
// @notice Shared client for computing data needed to construct or validate a bundle.
export class BundleDataClient {
private loadDataCache: DataCache = {};
private arweaveDataCache: Record<string, Promise<LoadDataReturnValue | undefined>> = {};
private bundleTimestampCache: Record<string, { [chainId: number]: number[] }> = {};
// eslint-disable-next-line no-useless-constructor
constructor(
readonly logger: winston.Logger,
readonly clients: Clients,
readonly spokePoolClients: { [chainId: number]: SpokePoolClient },
readonly chainIdListForBundleEvaluationBlockNumbers: number[],
readonly blockRangeEndBlockBuffer: { [chainId: number]: number } = {}
) {}
// This should be called whenever it's possible that the loadData information for a block range could have changed.
// For instance, if the spoke or hub clients have been updated, it probably makes sense to clear this to be safe.
clearCache(): void {
this.loadDataCache = {};
}
private async loadDataFromCache(key: string): Promise<LoadDataReturnValue> {
// Always return a deep cloned copy of object stored in cache. Since JS passes by reference instead of value, we
// want to minimize the risk that the programmer accidentally mutates data in the cache.
return _.cloneDeep(await this.loadDataCache[key]);
}
getBundleTimestampsFromCache(key: string): undefined | { [chainId: number]: number[] } {
if (this.bundleTimestampCache[key]) {
return _.cloneDeep(this.bundleTimestampCache[key]);
}
return undefined;
}
setBundleTimestampsInCache(key: string, timestamps: { [chainId: number]: number[] }): void {
this.bundleTimestampCache[key] = timestamps;
}
static getArweaveClientKey(blockRangesForChains: number[][]): string {
// As a unique key for this bundle, use the bundle mainnet end block, which should
// never be duplicated between bundles as long as thebundle block range
// always progresses forwards, which I think is a safe assumption. Other chains might pause
// but mainnet should never pause.
return blockRangesForChains[0][1].toString();
}
private getArweaveBundleDataClientKey(blockRangesForChains: number[][]): string {
return `bundles-${BundleDataClient.getArweaveClientKey(blockRangesForChains)}`;
}
// Post-populate any missing message hashes.
// @todo This can be removed once the legacy types hurdle is cleared (earliest 7 days post migration).
backfillMessageHashes(data: Pick<BundleData, "bundleDepositsV3" | "bundleFillsV3">): void {
Object.values(data.bundleDepositsV3).forEach((x) =>
Object.values(x).forEach((deposits) =>
deposits.forEach((deposit) => {
if (deposit.messageHash === UNDEFINED_MESSAGE_HASH) {
deposit.messageHash = getMessageHash(deposit.message);
}
})
)
);
Object.values(data.bundleFillsV3).forEach((x) =>
Object.values(x).forEach(({ fills }) =>
fills.forEach((fill) => {
if (fill.messageHash === UNDEFINED_MESSAGE_HASH && isDefined(fill.message)) {
// If messageHash is undefined, fill should be of type FilledV3Relay and should have a message.
fill.messageHash = getMessageHash(fill.message);
}
if (
fill.relayExecutionInfo.updatedMessageHash === UNDEFINED_MESSAGE_HASH &&
isDefined(fill.relayExecutionInfo.updatedMessage)
) {
fill.relayExecutionInfo.updatedMessageHash = getMessageHash(fill.relayExecutionInfo.updatedMessage);
}
})
)
);
}
private async loadPersistedDataFromArweave(
blockRangesForChains: number[][]
): Promise<LoadDataReturnValue | undefined> {
if (!isDefined(this.clients?.arweaveClient)) {
return undefined;
}
const start = performance.now();
const persistedData = await this.clients.arweaveClient.getByTopic(
this.getArweaveBundleDataClientKey(blockRangesForChains),
BundleDataSS
);
// If there is no data or the data is empty, return undefined because we couldn't
// pull info from the Arweave persistence layer.
if (!isDefined(persistedData) || persistedData.length < 1) {
return undefined;
}
// A converter function to account for the fact that our SuperStruct schema does not support numeric
// keys in records. Fundamentally, this is a limitation of superstruct itself.
const convertTypedStringRecordIntoNumericRecord = <UnderlyingType>(
data: Record<string, Record<string, UnderlyingType>>
): Record<number, Record<string, UnderlyingType>> =>
Object.keys(data).reduce(
(acc, chainId) => {
acc[Number(chainId)] = data[chainId];
return acc;
},
{} as Record<number, Record<string, UnderlyingType>>
);
const data = persistedData[0].data;
this.backfillMessageHashes(data);
const bundleData = {
bundleFillsV3: convertTypedStringRecordIntoNumericRecord(data.bundleFillsV3),
expiredDepositsToRefundV3: convertTypedStringRecordIntoNumericRecord(data.expiredDepositsToRefundV3),
bundleDepositsV3: convertTypedStringRecordIntoNumericRecord(data.bundleDepositsV3),
unexecutableSlowFills: convertTypedStringRecordIntoNumericRecord(data.unexecutableSlowFills),
bundleSlowFillsV3: convertTypedStringRecordIntoNumericRecord(data.bundleSlowFillsV3),
};
this.logger.debug({
at: "BundleDataClient#loadPersistedDataFromArweave",
message: `Loaded persisted data from Arweave in ${Math.round(performance.now() - start) / 1000}s.`,
blockRanges: JSON.stringify(blockRangesForChains),
bundleData: prettyPrintV3SpokePoolEvents(
bundleData.bundleDepositsV3,
bundleData.bundleFillsV3,
bundleData.bundleSlowFillsV3,
bundleData.expiredDepositsToRefundV3,
bundleData.unexecutableSlowFills
),
});
return bundleData;
}
// @dev This function should probably be moved to the InventoryClient since it bypasses loadData completely now.
async getPendingRefundsFromValidBundles(): Promise<CombinedRefunds[]> {
const refunds = [];
if (!this.clients.hubPoolClient.isUpdated) {
throw new Error("BundleDataClient::getPendingRefundsFromValidBundles HubPoolClient not updated.");
}
const bundle = this.clients.hubPoolClient.getLatestFullyExecutedRootBundle(
this.clients.hubPoolClient.latestBlockSearched
);
if (bundle !== undefined) {
refunds.push(await this.getPendingRefundsFromBundle(bundle));
} // No more valid bundles in history!
return refunds;
}
// @dev This function should probably be moved to the InventoryClient since it bypasses loadData completely now.
// Return refunds from input bundle.
async getPendingRefundsFromBundle(bundle: ProposedRootBundle): Promise<CombinedRefunds> {
const nextBundleMainnetStartBlock = this.clients.hubPoolClient.getNextBundleStartBlockNumber(
this.chainIdListForBundleEvaluationBlockNumbers,
this.clients.hubPoolClient.latestBlockSearched,
this.clients.hubPoolClient.chainId
);
const chainIds = this.clients.configStoreClient.getChainIdIndicesForBlock(nextBundleMainnetStartBlock);
// Reconstruct latest bundle block range.
const bundleEvaluationBlockRanges = getImpliedBundleBlockRanges(
this.clients.hubPoolClient,
this.clients.configStoreClient,
bundle
);
let combinedRefunds: CombinedRefunds;
// Here we don't call loadData because our fallback is to approximate refunds if we don't have arweave data, rather
// than use the much slower loadData to compute all refunds. We don't need to consider slow fills or deposit
// expiries here so we can skip some steps. We also don't need to compute LP fees as they should be small enough
// so as not to affect this approximate refund count.
const arweaveData = await this.loadArweaveData(bundleEvaluationBlockRanges);
if (arweaveData === undefined) {
combinedRefunds = await this.getApproximateRefundsForBlockRange(chainIds, bundleEvaluationBlockRanges);
} else {
const { bundleFillsV3, expiredDepositsToRefundV3 } = arweaveData;
combinedRefunds = getRefundsFromBundle(bundleFillsV3, expiredDepositsToRefundV3);
// If we don't have a spoke pool client for a chain, then we won't be able to deduct refunds correctly for this
// chain. For most of the pending bundle's liveness period, these past refunds are already executed so this is
// a reasonable assumption. This empty refund chain also matches what the alternative
// `getApproximateRefundsForBlockRange` would return.
Object.keys(combinedRefunds).forEach((chainId) => {
if (this.spokePoolClients[Number(chainId)] === undefined) {
delete combinedRefunds[Number(chainId)];
}
});
}
// The latest proposed bundle's refund leaves might have already been partially or entirely executed.
// We have to deduct the executed amounts from the total refund amounts.
return this.deductExecutedRefunds(combinedRefunds, bundle);
}
// @dev This helper function should probably be moved to the InventoryClient
async getApproximateRefundsForBlockRange(chainIds: number[], blockRanges: number[][]): Promise<CombinedRefunds> {
const refundsForChain: CombinedRefunds = {};
for (const chainId of chainIds) {
if (this.spokePoolClients[chainId] === undefined) {
continue;
}
const chainIndex = chainIds.indexOf(chainId);
// @dev This function does not account for pre-fill refunds as it is optimized for speed. The way to detect
// pre-fill refunds is to load all deposits that are unmatched by fills in the spoke pool client's memory
// and then query the FillStatus on-chain, but that might slow this function down too much. For now, we
// will live with this expected inaccuracy as it should be small. The pre-fill would have to precede the deposit
// by more than the caller's event lookback window which is expected to be unlikely.
const fillsToCount = this.spokePoolClients[chainId].getFills().filter((fill) => {
if (
fill.blockNumber < blockRanges[chainIndex][0] ||
fill.blockNumber > blockRanges[chainIndex][1] ||
isZeroValueFillOrSlowFillRequest(fill)
) {
return false;
}
// If origin spoke pool client isn't defined, we can't validate it.
if (this.spokePoolClients[fill.originChainId] === undefined) {
return false;
}
const matchingDeposit = this.spokePoolClients[fill.originChainId].getDeposit(fill.depositId);
const hasMatchingDeposit =
matchingDeposit !== undefined && getRelayEventKey(fill) === getRelayEventKey(matchingDeposit);
return hasMatchingDeposit;
});
await forEachAsync(fillsToCount, async (_fill) => {
const matchingDeposit = this.spokePoolClients[_fill.originChainId].getDeposit(_fill.depositId);
assert(isDefined(matchingDeposit), "Deposit not found for fill.");
const fill = await verifyFillRepayment(
_fill,
this.spokePoolClients[_fill.destinationChainId].spokePool.provider,
matchingDeposit,
this.clients.hubPoolClient
);
if (!isDefined(fill)) {
return;
}
const { chainToSendRefundTo, repaymentToken } = getRefundInformationFromFill(
fill,
this.clients.hubPoolClient,
blockRanges,
this.chainIdListForBundleEvaluationBlockNumbers,
matchingDeposit.fromLiteChain
);
// Assume that lp fees are 0 for the sake of speed. In the future we could batch compute
// these or make hardcoded assumptions based on the origin-repayment chain direction. This might result
// in slight over estimations of refunds, but its not clear whether underestimating or overestimating is
// worst from the relayer's perspective.
const { relayer, inputAmount: refundAmount } = fill;
refundsForChain[chainToSendRefundTo] ??= {};
refundsForChain[chainToSendRefundTo][repaymentToken.toString()] ??= {};
const existingRefundAmount =
refundsForChain[chainToSendRefundTo][repaymentToken.toString()][relayer.toString()] ?? bnZero;
refundsForChain[chainToSendRefundTo][repaymentToken.toString()][relayer.toString()] =
existingRefundAmount.add(refundAmount);
});
}
return refundsForChain;
}
getUpcomingDepositAmount(chainId: number, l2Token: Address, latestBlockToSearch: number): BigNumber {
if (this.spokePoolClients[chainId] === undefined) {
return toBN(0);
}
return this.spokePoolClients[chainId]
.getDeposits()
.filter((deposit) => deposit.blockNumber > latestBlockToSearch && deposit.inputToken.eq(l2Token))
.reduce((acc, deposit) => {
return acc.add(deposit.inputAmount);
}, toBN(0));
}
// @dev This function should probably be moved to the InventoryClient since it bypasses loadData completely now.
// Return refunds from the next valid bundle. This will contain any refunds that have been sent but are not included
// in a valid bundle with all of its leaves executed. This contains refunds from:
// - Bundles that passed liveness but have not had all of their pool rebalance leaves executed.
// - Bundles that are pending liveness
// - Fills sent after the pending, but not validated, bundle
async getNextBundleRefunds(): Promise<CombinedRefunds[]> {
const hubPoolClient = this.clients.hubPoolClient;
const nextBundleMainnetStartBlock = hubPoolClient.getNextBundleStartBlockNumber(
this.chainIdListForBundleEvaluationBlockNumbers,
hubPoolClient.latestBlockSearched,
hubPoolClient.chainId
);
const chainIds = this.clients.configStoreClient.getChainIdIndicesForBlock(nextBundleMainnetStartBlock);
const combinedRefunds: CombinedRefunds[] = [];
// @dev: If spoke pool client is undefined for a chain, then the end block will be null or undefined, which
// should be handled gracefully and effectively cause this function to ignore refunds for the chain.
let widestBundleBlockRanges = getWidestPossibleExpectedBlockRange(
chainIds,
this.spokePoolClients,
getEndBlockBuffers(chainIds, this.blockRangeEndBlockBuffer),
this.clients,
this.clients.hubPoolClient.latestBlockSearched,
this.clients.configStoreClient.getEnabledChains(this.clients.hubPoolClient.latestBlockSearched)
);
// Return block ranges for blocks after _pendingBlockRanges and up to widestBlockRanges.
// If a chain is disabled or doesn't have a spoke pool client, return a range of 0
function getBlockRangeDelta(_pendingBlockRanges: number[][]): number[][] {
return widestBundleBlockRanges.map((blockRange, index) => {
// If pending block range doesn't have an entry for the widest range, which is possible when a new chain
// is added to the CHAIN_ID_INDICES list, then simply set the initial block range to the widest block range.
// This will produce a block range delta of 0 where the returned range for this chain is [widest[1], widest[1]].
const initialBlockRange = _pendingBlockRanges[index] ?? blockRange;
// If chain is disabled, return disabled range
if (initialBlockRange[0] === initialBlockRange[1]) {
return initialBlockRange;
}
// If pending bundle end block exceeds widest end block or if widest end block is undefined
// (which is possible if the spoke pool client for the chain is not defined), return an empty range since there are no
// "new" events to consider for this chain.
if (!isDefined(blockRange[1]) || initialBlockRange[1] >= blockRange[1]) {
return [initialBlockRange[1], initialBlockRange[1]];
}
// If initialBlockRange][0] > widestBlockRange[0], then we'll ignore any blocks
// between initialBlockRange[0] and widestBlockRange[0] (inclusive) for simplicity reasons. In practice
// this should not happen.
return [initialBlockRange[1] + 1, blockRange[1]];
});
}
// If there is a pending bundle that has not been fully executed, then it should have arweave
// data so we can load it from there.
if (hubPoolClient.hasPendingProposal()) {
const pendingBundleBlockRanges = getImpliedBundleBlockRanges(
hubPoolClient,
this.clients.configStoreClient,
hubPoolClient.getLatestProposedRootBundle()
);
// Similar to getAppoximateRefundsForBlockRange, we'll skip the full bundle reconstruction if the arweave
// data is undefined and use the much faster approximation method which doesn't consider LP fees which is
// ok for this use case.
const arweaveData = await this.loadArweaveData(pendingBundleBlockRanges);
if (arweaveData === undefined) {
combinedRefunds.push(await this.getApproximateRefundsForBlockRange(chainIds, pendingBundleBlockRanges));
} else {
const { bundleFillsV3, expiredDepositsToRefundV3 } = arweaveData;
combinedRefunds.push(getRefundsFromBundle(bundleFillsV3, expiredDepositsToRefundV3));
}
// Shorten the widestBundleBlockRanges now to not double count the pending bundle blocks.
widestBundleBlockRanges = getBlockRangeDelta(pendingBundleBlockRanges);
}
// Next, load all refunds sent after the last bundle proposal. This can be expensive so we'll skip the full
// bundle reconstruction and make some simplifying assumptions:
// - Only look up fills sent after the pending bundle's end blocks
// - Skip LP fee computations and just assume the relayer is being refunded the full deposit.inputAmount
const start = performance.now();
combinedRefunds.push(await this.getApproximateRefundsForBlockRange(chainIds, widestBundleBlockRanges));
this.logger.debug({
at: "BundleDataClient#getNextBundleRefunds",
message: `Loading approximate refunds for next bundle in ${Math.round(performance.now() - start) / 1000}s.`,
blockRanges: JSON.stringify(widestBundleBlockRanges),
});
return combinedRefunds;
}
// @dev This helper function should probably be moved to the InventoryClient
getExecutedRefunds(
spokePoolClient: SpokePoolClient,
relayerRefundRoot: string
): {
[tokenAddress: string]: {
[relayer: string]: BigNumber;
};
} {
if (!isDefined(spokePoolClient)) {
return {};
}
// @dev Search from right to left since there can be multiple root bundles with the same relayer refund root.
// The caller should take caution if they're trying to use this function to find matching refunds for older
// root bundles as opposed to more recent ones.
const bundle = _.findLast(
spokePoolClient.getRootBundleRelays(),
(bundle) => bundle.relayerRefundRoot === relayerRefundRoot
);
if (bundle === undefined) {
return {};
}
const executedRefundLeaves = spokePoolClient
.getRelayerRefundExecutions()
.filter((leaf) => leaf.rootBundleId === bundle.rootBundleId);
const executedRefunds: { [tokenAddress: string]: { [relayer: string]: BigNumber } } = {};
for (const refundLeaf of executedRefundLeaves) {
const tokenAddress = refundLeaf.l2TokenAddress.toString();
if (executedRefunds[tokenAddress] === undefined) {
executedRefunds[tokenAddress] = {};
}
const executedTokenRefunds = executedRefunds[tokenAddress];
for (let i = 0; i < refundLeaf.refundAddresses.length; i++) {
const relayer = refundLeaf.refundAddresses[i].toString();
const refundAmount = refundLeaf.refundAmounts[i];
if (executedTokenRefunds[relayer] === undefined) {
executedTokenRefunds[relayer] = bnZero;
}
executedTokenRefunds[relayer] = executedTokenRefunds[relayer].add(refundAmount);
}
}
return executedRefunds;
}
// @dev This helper function should probably be moved to the InventoryClient
private deductExecutedRefunds(
allRefunds: CombinedRefunds,
bundleContainingRefunds: ProposedRootBundle
): CombinedRefunds {
for (const chainIdStr of Object.keys(allRefunds)) {
const chainId = Number(chainIdStr);
if (!isDefined(this.spokePoolClients[chainId])) {
continue;
}
const executedRefunds = this.getExecutedRefunds(
this.spokePoolClients[chainId],
bundleContainingRefunds.relayerRefundRoot
);
for (const tokenAddress of Object.keys(allRefunds[chainId])) {
const refunds = allRefunds[chainId][tokenAddress];
if (executedRefunds[tokenAddress] === undefined || refunds === undefined) {
continue;
}
for (const relayer of Object.keys(refunds)) {
const executedAmount = executedRefunds[tokenAddress][relayer];
if (executedAmount === undefined) {
continue;
}
// Since there should only be a single executed relayer refund leaf for each relayer-token-chain combination,
// we can deduct this refund and mark it as executed if the executed amount is > 0.
refunds[relayer] = bnZero;
}
}
}
return allRefunds;
}
getRefundsFor(bundleRefunds: CombinedRefunds, relayer: Address, chainId: number, token: Address): BigNumber {
if (!bundleRefunds[chainId] || !bundleRefunds[chainId][token.toString()]) {
return BigNumber.from(0);
}
const allRefunds = bundleRefunds[chainId][token.toString()];
return allRefunds && allRefunds[relayer.toString()] ? allRefunds[relayer.toString()] : BigNumber.from(0);
}
getTotalRefund(refunds: CombinedRefunds[], relayer: Address, chainId: number, refundToken: Address): BigNumber {
return refunds.reduce((totalRefund, refunds) => {
return totalRefund.add(this.getRefundsFor(refunds, relayer, chainId, refundToken));
}, bnZero);
}
private async loadArweaveData(blockRangesForChains: number[][]): Promise<LoadDataReturnValue> {
const arweaveKey = this.getArweaveBundleDataClientKey(blockRangesForChains);
// eslint-disable-next-line @typescript-eslint/no-misused-promises
if (!this.arweaveDataCache[arweaveKey]) {
this.arweaveDataCache[arweaveKey] = this.loadPersistedDataFromArweave(blockRangesForChains);
}
const arweaveData = _.cloneDeep(await this.arweaveDataCache[arweaveKey]);
return arweaveData!;
}
// Common data re-formatting logic shared across all data worker public functions.
// User must pass in spoke pool to search event data against. This allows the user to refund relays and fill deposits
// on deprecated spoke pools.
async loadData(
blockRangesForChains: number[][],
spokePoolClients: SpokePoolClientsByChain,
attemptArweaveLoad = false
): Promise<LoadDataReturnValue> {
const key = JSON.stringify(blockRangesForChains);
// eslint-disable-next-line @typescript-eslint/no-misused-promises
if (!this.loadDataCache[key]) {
let arweaveData;
if (attemptArweaveLoad) {
arweaveData = await this.loadArweaveData(blockRangesForChains);
} else {
arweaveData = undefined;
}
const data = isDefined(arweaveData)
? // We can return the data to a Promise to keep the return type consistent.
// Note: this is now a fast operation since we've already loaded the data from Arweave.
Promise.resolve(arweaveData)
: this.loadDataFromScratch(blockRangesForChains, spokePoolClients);
this.loadDataCache[key] = data;
}
return this.loadDataFromCache(key);
}
private async loadDataFromScratch(
blockRangesForChains: number[][],
spokePoolClients: SpokePoolClientsByChain
): Promise<LoadDataReturnValue> {
let start = performance.now();
const key = JSON.stringify(blockRangesForChains);
if (!this.clients.configStoreClient.isUpdated) {
throw new Error("ConfigStoreClient not updated");
} else if (!this.clients.hubPoolClient.isUpdated) {
throw new Error("HubPoolClient not updated");
}
const chainIds = this.clients.configStoreClient.getChainIdIndicesForBlock(blockRangesForChains[0][0]);
if (blockRangesForChains.length > chainIds.length) {
throw new Error(
`Unexpected block range list length of ${blockRangesForChains.length}, should be <= ${chainIds.length}`
);
}
// V3 specific objects:
const bundleDepositsV3: BundleDepositsV3 = {}; // Deposits in bundle block range.
const bundleFillsV3: BundleFillsV3 = {}; // Fills to refund in bundle block range.
const bundleInvalidFillsV3: V3FillWithBlock[] = []; // Fills that are not valid in this bundle.
const bundleUnrepayableFillsV3: V3FillWithBlock[] = []; // Fills that are not repayable in this bundle.
const bundleInvalidSlowFillRequests: SlowFillRequestWithBlock[] = []; // Slow fill requests that are not valid in this bundle.
const bundleSlowFillsV3: BundleSlowFills = {}; // Deposits that we need to send slow fills
// for in this bundle.
const expiredDepositsToRefundV3: ExpiredDepositsToRefundV3 = {};
// Newly expired deposits in this bundle that need to be refunded.
const unexecutableSlowFills: BundleExcessSlowFills = {};
// Deposit data for all Slowfills that was included in a previous
// bundle and can no longer be executed because (1) they were replaced with a FastFill in this bundle or
// (2) the fill deadline has passed. We'll need to decrement running balances for these deposits on the
// destination chain where the slow fill would have been executed.
const _isChainDisabled = (chainId: number): boolean => {
const blockRangeForChain = getBlockRangeForChain(blockRangesForChains, chainId, chainIds);
return isChainDisabled(blockRangeForChain);
};
const _canCreateSlowFillLeaf = (deposit: DepositWithBlock): boolean => {
return (
// Cannot slow fill when input and output tokens are not equivalent.
this.clients.hubPoolClient.areTokensEquivalent(
deposit.inputToken,
deposit.originChainId,
deposit.outputToken,
deposit.destinationChainId,
deposit.quoteBlockNumber
) &&
// Cannot slow fill from or to a lite chain.
!deposit.fromLiteChain &&
!deposit.toLiteChain
);
};
const _depositIsExpired = (deposit: DepositWithBlock): boolean => {
return deposit.fillDeadline < bundleBlockTimestamps[deposit.destinationChainId][1];
};
const _getFillStatusForDeposit = (deposit: Deposit, queryBlock: number): Promise<FillStatus> => {
return spokePoolClients[deposit.destinationChainId].relayFillStatus(
deposit,
// We can assume that in production
// the block to query is not one that the spoke pool client
// hasn't queried. This is because this function will usually be called
// in production with block ranges that were validated by
// DataworkerUtils.blockRangesAreInvalidForSpokeClients.
Math.min(queryBlock, spokePoolClients[deposit.destinationChainId].latestBlockSearched),
deposit.destinationChainId
);
};
// Infer chain ID's to load from number of block ranges passed in.
const allChainIds = blockRangesForChains
.map((_blockRange, index) => chainIds[index])
.filter((chainId) => !_isChainDisabled(chainId) && spokePoolClients[chainId] !== undefined);
allChainIds.forEach((chainId) => {
const spokePoolClient = spokePoolClients[chainId];
if (!spokePoolClient.isUpdated) {
throw new Error(`SpokePoolClient for chain ${chainId} not updated.`);
}
});
// If spoke pools are V3 contracts, then we need to compute start and end timestamps for block ranges to
// determine whether fillDeadlines have expired.
// @dev Going to leave this in so we can see impact on run-time in prod. This makes (allChainIds.length * 2) RPC
// calls in parallel.
const _cachedBundleTimestamps = this.getBundleTimestampsFromCache(key);
let bundleBlockTimestamps: { [chainId: string]: number[] } = {};
if (!_cachedBundleTimestamps) {
bundleBlockTimestamps = await this.getBundleBlockTimestamps(chainIds, blockRangesForChains, spokePoolClients);
this.setBundleTimestampsInCache(key, bundleBlockTimestamps);
this.logger.debug({
at: "BundleDataClient#loadData",
message: "Bundle block timestamps",
bundleBlockTimestamps,
blockRangesForChains: JSON.stringify(blockRangesForChains),
});
} else {
bundleBlockTimestamps = _cachedBundleTimestamps;
}
// Use this dictionary to conveniently unite all events with the same relay data hash which will make
// secondary lookups faster. The goal is to lazily fill up this dictionary with all events in the SpokePool
// client's in-memory event cache.
const v3RelayHashes: {
[relayHash: string]: {
// Note: Since there are no partial fills in v3, there should only be one fill per relay hash.
// Moreover, the SpokePool blocks multiple slow fill requests, so
// there should also only be one slow fill request per relay hash.
deposits?: V3DepositWithBlock[];
fill?: V3FillWithBlock;
slowFillRequest?: SlowFillRequestWithBlock;
};
} = {};
// Process all deposits first and populate the v3RelayHashes dictionary. Sort deposits into whether they are
// in this bundle block range or in a previous bundle block range.
const bundleDepositHashes: string[] = [];
const olderDepositHashes: string[] = [];
const decodeBundleDepositHash = (depositHash: string): { relayDataHash: string; index: number } => {
const [relayDataHash, i] = depositHash.split("@");
return { relayDataHash, index: Number(i) };
};
// Prerequisite step: Load all deposit events from the current or older bundles into the v3RelayHashes dictionary
// for convenient matching with fills.
for (const originChainId of allChainIds) {
const originClient = spokePoolClients[originChainId];
const originChainBlockRange = getBlockRangeForChain(blockRangesForChains, originChainId, chainIds);
for (const destinationChainId of allChainIds) {
if (originChainId === destinationChainId) {
continue;
}
originClient.getDepositsForDestinationChainWithDuplicates(destinationChainId).forEach((deposit) => {
if (deposit.blockNumber > originChainBlockRange[1] || isZeroValueDeposit(deposit)) {
return;
}
const relayDataHash = getRelayEventKey(deposit);
if (!v3RelayHashes[relayDataHash]) {
v3RelayHashes[relayDataHash] = {
deposits: [deposit],
fill: undefined,
slowFillRequest: undefined,
};
} else {
const { deposits } = v3RelayHashes[relayDataHash];
assert(isDefined(deposits) && deposits.length > 0, "Deposit should exist in relay hash dictionary.");
deposits.push(deposit);
}
// Account for duplicate deposits by concatenating the relayDataHash with the count of the number of times
// we have seen it so far.
const { deposits } = v3RelayHashes[relayDataHash];
assert(isDefined(deposits) && deposits.length > 0, "Deposit should exist in relay hash dictionary.");
const newBundleDepositHash = `${relayDataHash}@${deposits.length - 1}`;
const decodedBundleDepositHash = decodeBundleDepositHash(newBundleDepositHash);
assert(
decodedBundleDepositHash.relayDataHash === relayDataHash &&
decodedBundleDepositHash.index === deposits.length - 1,
"Not using correct bundle deposit hash key"
);
if (deposit.blockNumber >= originChainBlockRange[0]) {
if (
bundleDepositsV3?.[originChainId]?.[deposit.inputToken.toString()]?.find((d) =>
duplicateEvent(deposit, d)
)
) {
this.logger.debug({
at: "BundleDataClient#loadData",
message: "Duplicate deposit detected",
deposit,
});
throw new Error("Duplicate deposit detected");
}
bundleDepositHashes.push(newBundleDepositHash);
updateBundleDepositsV3(bundleDepositsV3, deposit);
} else if (deposit.blockNumber < originChainBlockRange[0]) {
olderDepositHashes.push(newBundleDepositHash);
}
});
}
}
this.logger.debug({
at: "BundleDataClient#loadData",
message: `Processed ${bundleDepositHashes.length + olderDepositHashes.length} deposits in ${
performance.now() - start
}ms.`,
});
start = performance.now();
// Process fills and maintain the following the invariants:
// - Every single fill whose type is not SlowFill in the bundle block range whose relay data matches
// with a deposit in the same or an older range produces a refund to the filler,
// unless the specified filler address cannot be repaid on the repayment chain.
// - Fills can match with duplicate deposits, so for every matched fill whose type is not SlowFill
// in the bundle block range, produce a refund to the filler for each matched deposit.
// - For every SlowFill in the block range that matches with multiple deposits, produce a refund to the depositor
// for every deposit except except the first.
// Assumptions about fills:
// - Duplicate fills for the same relay data hash are impossible to send.
// - Fills can only be sent before the deposit's fillDeadline.
const validatedBundleV3Fills: (V3FillWithBlock & { quoteTimestamp: number })[] = [];
const validatedBundleSlowFills: V3DepositWithBlock[] = [];
const validatedBundleUnexecutableSlowFills: V3DepositWithBlock[] = [];
let fillCounter = 0;
for (const originChainId of allChainIds) {
const originClient = spokePoolClients[originChainId];
for (const destinationChainId of allChainIds) {
if (originChainId === destinationChainId) {
continue;
}
const destinationClient = spokePoolClients[destinationChainId];
const destinationChainBlockRange = getBlockRangeForChain(blockRangesForChains, destinationChainId, chainIds);
const originChainBlockRange = getBlockRangeForChain(blockRangesForChains, originChainId, chainIds);
const fastFillsReplacingSlowFills: string[] = [];
await forEachAsync(
destinationClient
.getFillsForOriginChain(originChainId)
// We can remove fills for deposits with input amount equal to zero because these will result in 0 refunded
// tokens to the filler. We can't remove non-empty message deposit here in case there is a slow fill
// request for the deposit, we'd want to see the fill took place.
.filter(
(fill) => fill.blockNumber <= destinationChainBlockRange[1] && !isZeroValueFillOrSlowFillRequest(fill)
),
async (fill) => {
fillCounter++;
const relayDataHash = getRelayEventKey(fill);
if (v3RelayHashes[relayDataHash]) {
if (!v3RelayHashes[relayDataHash].fill) {
const { deposits } = v3RelayHashes[relayDataHash];
assert(isDefined(deposits) && deposits.length > 0, "Deposit should exist in relay hash dictionary.");
v3RelayHashes[relayDataHash].fill = fill;
if (fill.blockNumber >= destinationChainBlockRange[0]) {
const fillToRefund = await verifyFillRepayment(
fill,
destinationClient.spokePool.provider,
deposits[0],
this.clients.hubPoolClient
);
if (!isDefined(fillToRefund)) {
bundleUnrepayableFillsV3.push(fill);
// We don't return here yet because we still need to mark unexecutable slow fill leaves
// or duplicate deposits. However, we won't issue a fast fill refund.
} else {
v3RelayHashes[relayDataHash].fill = fillToRefund;
validatedBundleV3Fills.push({
...fillToRefund,
quoteTimestamp: deposits[0].quoteTimestamp,
});
// Now that we know this deposit has been filled on-chain, identify any duplicate deposits
// sent for this fill and refund them to the filler, because this value would not be paid out
// otherwise. These deposits can no longer expire and get refunded as an expired deposit,
// and they won't trigger a pre-fill refund because the fill is in this bundle.
// Pre-fill refunds only happen when deposits are sent in this bundle and the
// fill is from a prior bundle. Paying out the filler keeps the behavior consistent for how
// we deal with duplicate deposits regardless if the deposit is matched with a pre-fill or
// a current bundle fill.
const duplicateDeposits = deposits.slice(1);
duplicateDeposits.forEach((duplicateDeposit) => {
if (isSlowFill(fill)) {
updateExpiredDepositsV3(expiredDepositsToRefundV3, duplicateDeposit);
} else {
validatedBundleV3Fills.push({
...fillToRefund,
quoteTimestamp: duplicateDeposit.quoteTimestamp,
});
}
});
}
// If fill replaced a slow fill request, then mark it as one that might have created an
// unexecutable slow fill. We can't know for sure until we check the slow fill request
// events.
if (
fill.relayExecutionInfo.fillType === FillType.ReplacedSlowFill &&
_canCreateSlowFillLeaf(deposits[0])
) {
fastFillsReplacingSlowFills.push(relayDataHash);
}
}
} else {
this.logger.debug({
at: "BundleDataClient#loadData",
message: "Duplicate fill detected",
fill,
});
throw new Error("Duplicate fill detected");
}
return;
}
// At this point, there is no relay hash dictionary entry for this fill, so we need to
// instantiate the entry. We won't modify the fill.relayer until we match it with a deposit.
v3RelayHashes[relayDataHash] = {
deposits: undefined,
fill,
slowFillRequest: undefined,
};
// TODO: We can remove the following historical query once we deprecate the deposit()
// function since there won't be any old, unexpired deposits anymore assuming the spoke pool client
// lookbacks have been validated, which they should be before we run this function.
// Since there was no deposit matching the relay hash, we need to do a historical query for an
// older deposit in case the spoke pool client's lookback isn't old enough to find the matching deposit.
// We can skip this step if the fill's fill deadline is not infinite, because we can assume that the
// spoke pool clients have loaded deposits old enough to cover all fills with a non-infinite fill deadline.
if (fill.blockNumber >= destinationChainBlockRange[0]) {
// Fill has a non-infinite expiry, and we can assume our spoke pool clients have old enough deposits
// to conclude that this fill is invalid if we haven't found a matching deposit in memory, so
// skip the historical query.
if (!INFINITE_FILL_DEADLINE.eq(fill.fillDeadline)) {
bundleInvalidFillsV3.push(fill);
return;
}
// If deposit is using the deterministic relay hash feature, then the following binary search-based
// algorithm will not work. However, it is impossible to emit an infinite fill deadline using
// the unsafeDepositV3 function so there is no need to catch the special case.
const historicalDeposit = await queryHistoricalDepositForFill(originClient, fill);
if (!historicalDeposit.found) {
bundleInvalidFillsV3.push(fill);
} else {
const matchedDeposit = historicalDeposit.deposit;
// If deposit is in a following bundle, then this fill will have to be refunded once that deposit
// is in the current bundle.
if (matchedDeposit.blockNumber > originChainBlockRange[1]) {
bundleInvalidFillsV3.push(fill);
return;
}