-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathMonitor.ts
More file actions
1654 lines (1532 loc) · 68.5 KB
/
Monitor.ts
File metadata and controls
1654 lines (1532 loc) · 68.5 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 { BundleDataApproxClient } from "../clients";
import { EXPECTED_L1_TO_L2_MESSAGE_TIME } from "../common";
import {
BalanceType,
BundleAction,
DepositWithBlock,
FillStatus,
FillWithBlock,
L1Token,
RelayerBalanceReport,
RelayerBalanceTable,
TokenTransfer,
TokenInfo,
SwapFlowInitialized,
} from "../interfaces";
import {
BigNumber,
bnZero,
bnUint32Max,
Contract,
convertFromWei,
createFormatFunction,
ERC20,
blockExplorerLink,
blockExplorerLinks,
formatUnits,
getNativeTokenAddressForChain,
getNativeTokenSymbol,
getNetworkName,
getUnfilledDeposits,
mapAsync,
getEndBlockBuffers,
parseUnits,
providers,
toBN,
toBNWei,
winston,
TOKEN_SYMBOLS_MAP,
CHAIN_IDs,
isDefined,
resolveTokenDecimals,
sortEventsDescending,
getWidestPossibleExpectedBlockRange,
utils,
_buildPoolRebalanceRoot,
getRemoteTokenForL1Token,
getTokenInfo,
ConvertDecimals,
getL1TokenAddress,
isEVMSpokePoolClient,
isSVMSpokePoolClient,
toAddressType,
Address,
EvmAddress,
assert,
getBinanceApiClient,
getBinanceWithdrawalLimits,
chainIsEvm,
getSolanaTokenBalance,
getFillStatusPda,
getKitKeypairFromEvmSigner,
getRelayDataFromFill,
sortEventsAscending,
chainHasNativeToken,
} from "../utils";
import { MonitorClients, updateMonitorClients } from "./MonitorClientHelper";
import { MonitorConfig, L2Token } from "./MonitorConfig";
import { getImpliedBundleBlockRanges } from "../dataworker/DataworkerUtils";
import { PUBLIC_NETWORKS, TOKEN_EQUIVALENCE_REMAPPING } from "@across-protocol/constants";
import { utils as sdkUtils, arch } from "@across-protocol/sdk";
import {
address,
fetchEncodedAccount,
getBase64EncodedWireTransaction,
signTransactionMessageWithSigners,
} from "@solana/kit";
import { HyperliquidExecutor } from "../hyperliquid/HyperliquidExecutor";
import { HyperliquidExecutorConfig } from "../hyperliquid/HyperliquidExecutorConfig";
// 60 minutes, which is the length of the challenge window, so if a rebalance takes longer than this to finalize,
// then its finalizing after the subsequent challenge period has started, which is sub-optimal.
export const REBALANCE_FINALIZE_GRACE_PERIOD = Number(process.env.REBALANCE_FINALIZE_GRACE_PERIOD ?? 60 * 60);
// bundle frequency.
export const ALL_CHAINS_NAME = "All chains";
const ALL_BALANCE_TYPES = [BalanceType.CURRENT, BalanceType.PENDING, BalanceType.PENDING_TRANSFERS, BalanceType.TOTAL];
type BalanceRequest = { chainId: number; token: Address; account: Address };
export class Monitor {
// Block range to search is only defined on calling update().
private hubPoolStartingBlock: number | undefined = undefined;
private hubPoolEndingBlock: number | undefined = undefined;
private spokePoolsBlocks: Record<number, { startingBlock: number | undefined; endingBlock: number | undefined }> = {};
private balanceCache: { [chainId: number]: { [token: string]: { [account: string]: BigNumber } } } = {};
private decimals: { [chainId: number]: { [token: string]: number } } = {};
private additionalL1Tokens: L1Token[] = [];
private l2OnlyTokens: L2Token[] = [];
// Chains for each spoke pool client.
public monitorChains: number[];
// Chains that we care about inventory manager activity on, so doesn't include Ethereum which doesn't
// have an inventory manager adapter.
public crossChainAdapterSupportedChains: number[];
private bundleDataApproxClient: BundleDataApproxClient;
private l1Tokens: L1Token[];
public constructor(
readonly logger: winston.Logger,
readonly monitorConfig: MonitorConfig,
readonly clients: MonitorClients
) {
this.crossChainAdapterSupportedChains = clients.crossChainTransferClient.adapterManager.supportedChains();
this.monitorChains = Object.values(clients.spokePoolClients).map(({ chainId }) => chainId);
for (const chainId of this.monitorChains) {
this.spokePoolsBlocks[chainId] = { startingBlock: undefined, endingBlock: undefined };
}
logger.debug({
at: "Monitor#constructor",
message: "Initialized monitor",
monitorChains: this.monitorChains,
crossChainAdapterSupportedChains: this.crossChainAdapterSupportedChains,
});
this.additionalL1Tokens = monitorConfig.additionalL1NonLpTokens.map((l1Token) => {
const l1TokenInfo = getTokenInfo(EvmAddress.from(l1Token), this.clients.hubPoolClient.chainId);
assert(l1TokenInfo.address.isEVM());
return {
...l1TokenInfo,
address: l1TokenInfo.address,
};
});
this.l2OnlyTokens = monitorConfig.l2OnlyTokens;
this.l1Tokens = this.clients.hubPoolClient.getL1Tokens();
this.bundleDataApproxClient = new BundleDataApproxClient(
this.clients.spokePoolClients,
this.clients.hubPoolClient,
this.monitorChains,
[...this.l1Tokens, ...this.additionalL1Tokens].map(({ address }) => address),
this.logger
);
}
/**
* Returns L2-only tokens for a specific chain.
*/
private getL2OnlyTokensForChain(chainId: number): L2Token[] {
return this.l2OnlyTokens.filter((token) => token.chainId === chainId);
}
/**
* Generates markdown report for a token's balances across the specified chains.
* Returns the token markdown section and summary entry.
*/
private generateTokenBalanceMarkdown(
report: RelayerBalanceTable,
token: { symbol: string; decimals: number },
chainNames: string[],
labelSuffix = ""
): { mrkdwn: string; summaryEntry: string } {
let tokenMrkdwn = "";
for (const chainName of chainNames) {
const balancesBN = Object.values(report[token.symbol]?.[chainName] ?? {});
if (balancesBN.find((b) => b.gt(bnZero))) {
const balances = balancesBN.map((balance) =>
balance.gt(bnZero) ? convertFromWei(balance.toString(), token.decimals) : "0"
);
tokenMrkdwn += `${chainName}: ${balances.join(", ")}\n`;
} else {
tokenMrkdwn += `${chainName}: 0\n`;
}
}
const totalBalance = report[token.symbol]?.[ALL_CHAINS_NAME]?.[BalanceType.TOTAL] ?? bnZero;
if (totalBalance.gt(bnZero)) {
return {
mrkdwn: `*[${token.symbol}${labelSuffix}]*\n` + tokenMrkdwn,
summaryEntry: `${token.symbol}: ${convertFromWei(totalBalance.toString(), token.decimals)}\n`,
};
}
return { mrkdwn: "", summaryEntry: `${token.symbol}: 0\n` };
}
public async update(): Promise<void> {
// Clear balance cache at the start of each update.
// Note: decimals don't need to be cleared because they shouldn't ever change.
this.balanceCache = {};
await updateMonitorClients(this.clients);
await this.computeHubPoolBlocks();
await this.computeSpokePoolsBlocks();
// We should initialize the bundle data approx client here because it depends on the spoke pool clients, and we
// should do it every time the spoke pool clients are updated.
this.bundleDataApproxClient.initialize();
const searchConfigs = Object.fromEntries(
Object.entries(this.spokePoolsBlocks).map(([chainId, config]) => [
chainId,
{
from: config.startingBlock,
to: config.endingBlock,
maxLookBack: 0,
},
])
);
const tokensPerChain = Object.fromEntries(
this.monitorChains.filter(chainIsEvm).map((chainId) => {
const l2Tokens = this.l1Tokens
.map((l1Token) => this.getRemoteTokenForL1Token(l1Token.address, chainId))
.filter(isDefined);
return [chainId, l2Tokens];
})
);
await this.clients.tokenTransferClient.update(searchConfigs, tokensPerChain);
}
async checkUtilization(): Promise<void> {
this.logger.debug({ at: "Monitor#checkUtilization", message: "Checking for pool utilization ratio" });
const l1TokenUtilizations = await Promise.all(
this.l1Tokens.map(async (l1Token) => {
const utilization = await this.clients.hubPoolClient.getCurrentPoolUtilization(l1Token.address);
return {
l1Token: l1Token.address,
chainId: this.monitorConfig.hubPoolChainId,
poolCollateralSymbol: l1Token.symbol,
utilization: toBN(utilization.toString()),
};
})
);
// Send notification if pool utilization is above configured threshold.
for (const l1TokenUtilization of l1TokenUtilizations) {
if (l1TokenUtilization.utilization.gt(toBN(this.monitorConfig.utilizationThreshold).mul(toBNWei("0.01")))) {
const utilizationString = l1TokenUtilization.utilization.mul(100).toString();
const mrkdwn = `${l1TokenUtilization.poolCollateralSymbol} pool token at \
${blockExplorerLink(l1TokenUtilization.l1Token.toEvmAddress(), l1TokenUtilization.chainId)} on \
${getNetworkName(l1TokenUtilization.chainId)} is at \
${createFormatFunction(0, 2)(utilizationString)}% utilization!`;
this.logger.debug({ at: "Monitor#checkUtilization", message: "High pool utilization warning 🏊", mrkdwn });
}
}
}
async checkUnknownRootBundleCallers(): Promise<void> {
this.logger.debug({ at: "Monitor#RootBundleCallers", message: "Checking for unknown root bundle callers" });
const proposedBundles = this.clients.hubPoolClient.getProposedRootBundlesInBlockRange(
this.hubPoolStartingBlock,
this.hubPoolEndingBlock
);
const disputedBundles = this.clients.hubPoolClient.getDisputedRootBundlesInBlockRange(
this.hubPoolStartingBlock,
this.hubPoolEndingBlock
);
for (const event of proposedBundles) {
this.notifyIfUnknownCaller(event.proposer.toEvmAddress(), BundleAction.PROPOSED, event.txnRef);
}
for (const event of disputedBundles) {
this.notifyIfUnknownCaller(event.disputer, BundleAction.DISPUTED, event.txnRef);
}
}
async reportInvalidFills(): Promise<void> {
const invalidFills = await sdkUtils.findInvalidFills(this.clients.spokePoolClients);
const invalidFillsByChainId: Record<string, number> = {};
invalidFills.forEach((invalidFill) => {
const destinationChainName = getNetworkName(invalidFill.fill.destinationChainId);
invalidFillsByChainId[destinationChainName] = (invalidFillsByChainId[destinationChainName] ?? 0) + 1;
const destinationChainId = invalidFill.fill.destinationChainId;
const outputToken = invalidFill.fill.outputToken;
let tokenInfo: TokenInfo;
try {
tokenInfo = this.clients.hubPoolClient.getTokenInfoForAddress(outputToken, destinationChainId);
} catch {
tokenInfo = { symbol: "UNKNOWN TOKEN", decimals: 18, address: outputToken };
}
const formatterFunction = createFormatFunction(2, 4, false, tokenInfo.decimals);
const formattedOutputAmount = formatterFunction(invalidFill.fill.outputAmount.toString());
const message =
`Invalid fill detected for ${getNetworkName(invalidFill.fill.originChainId)} deposit. ` +
`Output amount: ${formattedOutputAmount} ${tokenInfo.symbol}`;
const deposit = invalidFill.deposit
? {
txnRef: invalidFill.deposit.txnRef,
inputToken: invalidFill.deposit.inputToken.toNative(),
depositor: invalidFill.deposit.depositor.toNative(),
}
: undefined;
this.logger.warn({
at: "Monitor::reportInvalidFills",
message,
destinationChainId,
outputToken: invalidFill.fill.outputToken.toNative(),
relayer: invalidFill.fill.relayer.toNative(),
blockExplorerLink: blockExplorerLink(invalidFill.fill.txnRef, destinationChainId),
reason: invalidFill.reason,
deposit,
notificationPath: "across-invalid-fills",
});
});
if (Object.keys(invalidFillsByChainId).length > 0) {
this.logger.info({
at: "Monitor::invalidFillsByChain",
message: "Invalid fills by chain",
invalidFillsByChainId,
notificationPath: "across-invalid-fills",
});
}
}
async reportUnfilledDeposits(): Promise<void> {
const { hubPoolClient, spokePoolClients } = this.clients;
const unfilledDeposits: Record<number, DepositWithBlock[]> = Object.fromEntries(
await mapAsync(Object.values(spokePoolClients), async ({ chainId: destinationChainId }) => {
const deposits = getUnfilledDeposits(spokePoolClients[destinationChainId], spokePoolClients, hubPoolClient).map(
({ deposit, invalidFills: invalid }) => {
// Ignore depositId >= bnUInt32Max; these tend to be pre-fills that are eventually valid and
// tend to confuse this reporting because there are multiple deposits with the same depositId.
if (deposit.depositId < bnUint32Max && invalid.length > 0) {
const invalidFills = Object.fromEntries(
invalid.map(({ relayer, destinationChainId, depositId, txnRef, outputAmount }) => {
return [relayer, { destinationChainId, depositId, txnRef, outputAmount }];
})
);
this.logger.warn({
at: "SpokePoolClient",
chainId: destinationChainId,
message: `Unfilled deposit found matching ${getNetworkName(deposit.originChainId)} deposit.`,
depositOutputAmount: deposit.outputAmount.toString(),
depositTxnRef: deposit.txnRef,
invalidFills,
notificationPath: "across-unfilled-deposits",
});
}
return deposit;
}
);
const fillStatus = await spokePoolClients[destinationChainId].fillStatusArray(deposits);
return [destinationChainId, deposits.filter((_, idx) => fillStatus[idx] !== FillStatus.Filled)];
})
);
// Group unfilled amounts by chain id and token id.
const unfilledAmountByChainAndToken: { [chainId: number]: { [tokenAddress: string]: BigNumber } } = {};
Object.entries(unfilledDeposits).forEach(([_destinationChainId, deposits]) => {
const chainId = Number(_destinationChainId);
unfilledAmountByChainAndToken[chainId] ??= {};
deposits.forEach(({ outputToken, outputAmount }) => {
const unfilledAmount = unfilledAmountByChainAndToken[chainId][outputToken.toBytes32()] ?? bnZero;
unfilledAmountByChainAndToken[chainId][outputToken.toBytes32()] = unfilledAmount.add(outputAmount);
});
});
let mrkdwn = "";
for (const [chainIdStr, amountByToken] of Object.entries(unfilledAmountByChainAndToken)) {
// Skipping chains with no unfilled deposits.
if (!amountByToken) {
continue;
}
const chainId = parseInt(chainIdStr);
mrkdwn += `*Destination: ${getNetworkName(chainId)}*\n`;
for (const tokenAddress of Object.keys(amountByToken)) {
let symbol: string;
let unfilledAmount: string;
try {
let decimals: number;
({ symbol, decimals } = this.clients.hubPoolClient.getTokenInfoForAddress(
toAddressType(tokenAddress, chainId),
chainId
));
unfilledAmount = convertFromWei(amountByToken[tokenAddress].toString(), decimals);
} catch {
symbol = tokenAddress; // Using the address helps investigation.
unfilledAmount = amountByToken[tokenAddress].toString();
}
// Convert to number of tokens for readability.
mrkdwn += `${symbol}: ${unfilledAmount}\n`;
}
}
if (mrkdwn) {
this.logger.info({ at: "Monitor#reportUnfilledDeposits", message: "Unfilled deposits ⏱", mrkdwn });
}
}
async reportOpenHyperliquidOrders(): Promise<void> {
// Piggyback off of the hyperliquid executor logic so that we can call `getOutstandingOrdersOnPair` for each configured pair.
const hyperEvmSpoke = this.clients.spokePoolClients[CHAIN_IDs.HYPEREVM];
assert(isEVMSpokePoolClient(hyperEvmSpoke));
const dstProvider = hyperEvmSpoke.spokePool.provider;
const hyperliquidExecutorConfig = new HyperliquidExecutorConfig(process.env);
const hyperliquidExecutor = new HyperliquidExecutor(
this.logger,
{
...hyperliquidExecutorConfig,
supportedTokens: this.monitorConfig.hyperliquidTokens,
lookback: this.monitorConfig.hyperliquidOrderMaximumLifetime * 12, // Lookback is a function of lifetime.
} as HyperliquidExecutorConfig,
{ ...this.clients, dstProvider }
);
await hyperliquidExecutor.initialize();
const outstandingOrders = Object.fromEntries(
await mapAsync(Object.entries(hyperliquidExecutor.pairs), async ([pairId, pair]) => [
pairId,
await hyperliquidExecutor.getOutstandingOrdersOnPair(pair),
])
);
const oldHyperliquidOrders: { [pairId: string]: SwapFlowInitialized & { age: number } } = Object.fromEntries(
(
await mapAsync(Object.entries(outstandingOrders), async ([pairId, orderSet]) => {
// If no outstanding orders. Nothing to do, so return.
if (orderSet.length === 0) {
return undefined;
}
const sortedOrders = sortEventsAscending(orderSet);
const earliestOrder = sortedOrders[0];
const orderBlock = await dstProvider.getBlock(earliestOrder.blockNumber);
const orderAge = Date.now() / 1000 - orderBlock.timestamp;
if (orderAge > this.monitorConfig.hyperliquidOrderMaximumLifetime) {
return [pairId, { ...earliestOrder, age: orderAge }];
}
return undefined;
})
).filter(isDefined)
);
const nOutstandingOrders = Object.values(oldHyperliquidOrders).flat().length;
if (Object.values(oldHyperliquidOrders).length !== 0) {
const finalTokenBalances = await mapAsync(Object.keys(oldHyperliquidOrders), async (pairId) => {
const [, finalTokenSymbol] = pairId.split("-");
const pair = hyperliquidExecutor.pairs[pairId];
return hyperliquidExecutor.querySpotBalance(finalTokenSymbol, pair.swapHandler, pair.finalTokenDecimals);
});
const formatter = createFormatFunction(2, 4, false, 8);
this.logger.error({
at: "Monitor#reportOpenHyperliquidOrders",
message: "Old outstanding Hyperliquid orders",
oldHyperliquidOrders,
outstandingOrders: nOutstandingOrders,
affectedPairs: Object.keys(oldHyperliquidOrders),
affectedSwapHandlers: Object.keys(oldHyperliquidOrders).map((pairId) =>
hyperliquidExecutor.pairs[pairId].swapHandler.toNative()
),
approximateAmountShort: Object.values(oldHyperliquidOrders).map((order, idx) =>
formatter(order.maxAmountToSend.sub(finalTokenBalances[idx]))
),
});
} else {
this.logger.debug({
at: "Monitor#reportOpenHyperliquidOrders",
message: "No old outstanding Hyperliquid orders",
outstandingOrders: outstandingOrders.length,
});
}
}
l2TokenAmountToL1TokenAmountConverter(l2Token: Address, chainId: number): (BigNumber) => BigNumber {
// Step 1: Get l1 token address equivalent of L2 token
const l1Token = getL1TokenAddress(l2Token, chainId);
const l1TokenDecimals = getTokenInfo(l1Token, this.clients.hubPoolClient.chainId).decimals;
const l2TokenDecimals = getTokenInfo(l2Token, chainId).decimals;
return ConvertDecimals(l2TokenDecimals, l1TokenDecimals);
}
getL1TokensForRelayerBalancesReport(): L1Token[] {
const allL1Tokens = [...this.l1Tokens, ...this.additionalL1Tokens].map(({ symbol, ...tokenInfo }) => {
return {
...tokenInfo,
// Remap symbols so that we're using a symbol available to us in TOKEN_SYMBOLS_MAP.
symbol: TOKEN_EQUIVALENCE_REMAPPING[symbol] ?? symbol,
};
});
// @dev Handle special case for L1 USDC which is mapped to two L2 tokens on some chains, so we can more easily
// see L2 Bridged USDC balance versus Native USDC. Add USDC.e right after the USDC element.
const indexOfUsdc = allL1Tokens.findIndex(({ symbol }) => symbol === "USDC");
if (indexOfUsdc > -1 && TOKEN_SYMBOLS_MAP["USDC.e"].addresses[this.clients.hubPoolClient.chainId]) {
allL1Tokens.splice(indexOfUsdc, 0, {
symbol: "USDC.e",
address: EvmAddress.from(TOKEN_SYMBOLS_MAP["USDC.e"].addresses[this.clients.hubPoolClient.chainId]),
decimals: 6,
});
}
return allL1Tokens;
}
async reportRelayerBalances(): Promise<void> {
const relayers = this.monitorConfig.monitoredRelayers;
const allL1Tokens = this.getL1TokensForRelayerBalancesReport();
const l2OnlyTokens = this.l2OnlyTokens;
const chainIds = this.monitorChains;
const allChainNames = chainIds.map(getNetworkName).concat([ALL_CHAINS_NAME]);
const reports = this.initializeBalanceReports(relayers, allL1Tokens, l2OnlyTokens, allChainNames);
await this.updateCurrentRelayerBalances(reports);
await this.updateLatestAndFutureRelayerRefunds(reports);
for (const relayer of relayers) {
const report = reports[relayer.toNative()];
let summaryMrkdwn = "*[Summary]*\n";
let mrkdwn = "Token amounts: current, pending execution, cross-chain transfers, total\n";
// Report L1 tokens (all chains)
for (const token of allL1Tokens) {
const { mrkdwn: tokenMrkdwn, summaryEntry } = this.generateTokenBalanceMarkdown(report, token, allChainNames);
mrkdwn += tokenMrkdwn;
summaryMrkdwn += summaryEntry;
}
// Report L2-only tokens (only their specific chain)
for (const token of l2OnlyTokens) {
const { mrkdwn: tokenMrkdwn, summaryEntry } = this.generateTokenBalanceMarkdown(
report,
token,
[getNetworkName(token.chainId)],
" (L2-only)"
);
mrkdwn += tokenMrkdwn;
summaryMrkdwn += summaryEntry;
}
mrkdwn += summaryMrkdwn;
this.logger.info({
at: "Monitor#reportRelayerBalances",
message: `Balance report for ${relayer} 📖`,
mrkdwn,
});
}
// Build a combined token list for decimal lookups in the debug logging
const allTokensWithDecimals = new Map<string, number>();
allL1Tokens.forEach((token) => allTokensWithDecimals.set(token.symbol, token.decimals));
l2OnlyTokens.forEach((token) => allTokensWithDecimals.set(token.symbol, token.decimals));
Object.entries(reports).forEach(([relayer, balanceTable]) => {
Object.entries(balanceTable).forEach(([tokenSymbol, columns]) => {
const decimals = allTokensWithDecimals.get(tokenSymbol);
if (!decimals) {
throw new Error(`No decimals found for ${tokenSymbol}`);
}
Object.entries(columns).forEach(([chainName, cell]) => {
if (this._tokenEnabledForNetwork(tokenSymbol, chainName) || chainName === ALL_CHAINS_NAME) {
Object.entries(cell).forEach(([balanceType, balance]) => {
// Don't log zero balances.
if (balance.isZero()) {
return;
}
this.logger.debug({
at: "Monitor#reportRelayerBalances",
message: "Machine-readable single balance report",
relayer,
tokenSymbol,
decimals,
chainName,
balanceType,
balanceInWei: balance.toString(),
balance: Number(utils.formatUnits(balance, decimals)),
datadog: true,
});
});
}
});
});
});
}
// Update current balances of all tokens on each supported chain for each relayer.
async updateCurrentRelayerBalances(relayerBalanceReport: RelayerBalanceReport): Promise<void> {
const l1Tokens = this.getL1TokensForRelayerBalancesReport();
for (const relayer of this.monitorConfig.monitoredRelayers) {
for (const chainId of this.monitorChains) {
// If the monitored relayer address is invalid on the monitored chain (e.g. the monitored relayer is a base58 address while the chain ID is mainnet),
// then there is no balance to update in this loop.
if (!relayer.isValidOn(chainId)) {
continue;
}
const l2ToL1Tokens = this.getL2ToL1TokenMap(l1Tokens, chainId);
const l2TokenAddresses = Object.keys(l2ToL1Tokens);
const tokenBalances = await this._getBalances(
l2TokenAddresses.map((address) => ({
token: toAddressType(address, chainId),
chainId: chainId,
account: relayer,
}))
);
for (let i = 0; i < l2TokenAddresses.length; i++) {
const decimalConverter = this.l2TokenAmountToL1TokenAmountConverter(
toAddressType(l2TokenAddresses[i], chainId),
chainId
);
const { symbol } = l2ToL1Tokens[l2TokenAddresses[i]];
this.updateRelayerBalanceTable(
relayerBalanceReport[relayer.toNative()],
symbol,
getNetworkName(chainId),
BalanceType.CURRENT,
decimalConverter(tokenBalances[i])
);
}
// Handle L2-only tokens for this chain
const l2OnlyTokensForChain = this.getL2OnlyTokensForChain(chainId);
if (l2OnlyTokensForChain.length > 0) {
const l2OnlyBalances = await this._getBalances(
l2OnlyTokensForChain.map((token) => ({
token: token.address,
chainId: chainId,
account: relayer,
}))
);
for (let i = 0; i < l2OnlyTokensForChain.length; i++) {
const token = l2OnlyTokensForChain[i];
// L2-only tokens don't need decimal conversion since they don't map to L1
this.updateRelayerBalanceTable(
relayerBalanceReport[relayer.toNative()],
token.symbol,
getNetworkName(chainId),
BalanceType.CURRENT,
l2OnlyBalances[i]
);
}
}
}
}
}
// Returns a dictionary of L2 token addresses on this chain to their mapped L1 token info. For example, this
// will return a dictionary for Optimism including WETH, WBTC, USDC, USDC.e, USDT entries where the key is
// the token's Optimism address and the value is the equivalent L1 token info.
protected getL2ToL1TokenMap(l1Tokens: L1Token[], chainId: number): { [l2TokenAddress: string]: L1Token } {
return Object.fromEntries(
l1Tokens
.map((l1Token) => {
// @dev l2TokenSymbols is a list of all keys in TOKEN_SYMBOLS_MAP where the hub chain address is equal to the
// l1 token address.
const l2TokenSymbols = Object.entries(TOKEN_SYMBOLS_MAP)
.filter(
([, { addresses }]) =>
addresses[this.clients.hubPoolClient.chainId]?.toLowerCase() ===
l1Token.address.toEvmAddress().toLowerCase()
)
.map(([symbol]) => symbol);
// Create an entry for all L2 tokens that share a symbol with the L1 token. This includes tokens
// like USDC which has multiple L2 tokens mapped to the same L1 token for a given chain ID.
return l2TokenSymbols
.filter((symbol) => TOKEN_SYMBOLS_MAP[symbol].addresses[chainId] !== undefined)
.map((symbol) => {
if (chainId !== this.clients.hubPoolClient.chainId && sdkUtils.isBridgedUsdc(symbol)) {
return [TOKEN_SYMBOLS_MAP[symbol].addresses[chainId], { ...l1Token, symbol: "USDC.e" }];
} else {
const remappedSymbol = TOKEN_EQUIVALENCE_REMAPPING[symbol] ?? symbol;
return [TOKEN_SYMBOLS_MAP[symbol].addresses[chainId], { ...l1Token, symbol: remappedSymbol }];
}
});
})
.flat()
);
}
async checkBalances(): Promise<void> {
const { monitoredBalances } = this.monitorConfig;
const balances = await this._getBalances(monitoredBalances);
const decimalValues = await this._getDecimals(monitoredBalances);
this.logger.debug({
at: "Monitor#checkBalances",
message: "Checking balances",
currentBalances: monitoredBalances.map(({ chainId, token, account, warnThreshold, errorThreshold }, i) => {
return {
chainId,
token,
account,
currentBalance: balances[i].toString(),
warnThreshold: parseUnits(warnThreshold.toString(), decimalValues[i]),
errorThreshold: parseUnits(errorThreshold.toString(), decimalValues[i]),
};
}),
});
const alerts = (
await Promise.all(
monitoredBalances.map(
async (
{ chainId, token, account, warnThreshold, errorThreshold },
i
): Promise<undefined | { level: "warn" | "error"; text: string }> => {
const balance = balances[i];
const decimals = decimalValues[i];
let trippedThreshold: { level: "warn" | "error"; threshold: number } | null = null;
if (warnThreshold !== null && balance.lt(parseUnits(warnThreshold.toString(), decimals))) {
trippedThreshold = { level: "warn", threshold: warnThreshold };
}
if (errorThreshold !== null && balance.lt(parseUnits(errorThreshold.toString(), decimals))) {
trippedThreshold = { level: "error", threshold: errorThreshold };
}
if (trippedThreshold !== null) {
let symbol;
const nativeTokenForChain = getNativeTokenAddressForChain(chainId);
if (token.eq(nativeTokenForChain)) {
symbol = getNativeTokenSymbol(chainId);
} else {
const spokePoolClient = this.clients.spokePoolClients[chainId];
if (isEVMSpokePoolClient(spokePoolClient)) {
symbol = await new Contract(
token.toEvmAddress(),
ERC20.abi,
spokePoolClient.spokePool.provider
).symbol();
} else {
symbol = getTokenInfo(token, chainId).symbol;
}
}
return {
level: trippedThreshold.level,
text: ` ${getNetworkName(chainId)} ${symbol} balance for ${blockExplorerLink(
account.toNative(),
chainId
)} is ${formatUnits(balance, decimals)}. Threshold: ${trippedThreshold.threshold}`,
};
}
}
)
)
).filter((text) => text !== undefined);
if (alerts.length > 0) {
// Just send out the maximum alert level rather than splitting into warnings and errors.
const maxAlertlevel = alerts.some((alert) => alert.level === "error") ? "error" : "warn";
const mrkdwn =
"Some balance(s) are below the configured threshold!\n" + alerts.map(({ text }) => text).join("\n");
this.logger[maxAlertlevel]({ at: "Monitor", message: "Balance(s) below threshold", mrkdwn: mrkdwn });
}
}
async checkBinanceWithdrawalLimits() {
const binanceApi = await getBinanceApiClient(process.env["BINANCE_API_BASE"]);
const wdQuota = await getBinanceWithdrawalLimits(binanceApi);
const aboveWarnThreshold =
isDefined(this.monitorConfig.binanceWithdrawWarnThreshold) &&
wdQuota.usedWdQuota / wdQuota.wdQuota > this.monitorConfig.binanceWithdrawWarnThreshold;
const aboveAlertThreshold =
isDefined(this.monitorConfig.binanceWithdrawAlertThreshold) &&
wdQuota.usedWdQuota / wdQuota.wdQuota > this.monitorConfig.binanceWithdrawAlertThreshold;
const level = aboveAlertThreshold ? "error" : aboveWarnThreshold ? "warn" : "debug";
this.logger[level]({
at: "Monitor#checkBinanceWithdrawalLimits",
message: "Binance withdrawal quota",
datadog: true,
wdQuota,
});
}
async checkSpokePoolRunningBalances(): Promise<void> {
// We define a custom format function since we do not want the same precision that `convertFromWei` gives us.
const formatWei = (weiVal: string, decimals: number) =>
weiVal === "0" ? "0" : createFormatFunction(1, 4, false, decimals)(weiVal);
const hubPoolClient = this.clients.hubPoolClient;
const monitoredTokenSymbols = this.monitorConfig.monitoredTokenSymbols;
// Define the chain IDs in the same order as `enabledChainIds` so that block range ordering is preserved.
const chainIds =
this.monitorConfig.monitoredSpokePoolChains.length !== 0
? this.monitorChains.filter((chain) => this.monitorConfig.monitoredSpokePoolChains.includes(chain))
: this.monitorChains;
const l2TokenForChain = (chainId: number, symbol: string) => {
const _l2Token = TOKEN_SYMBOLS_MAP[symbol]?.addresses[chainId];
return isDefined(_l2Token) ? toAddressType(_l2Token, chainId) : undefined;
};
const pendingRelayerRefunds = {};
const pendingRebalanceRoots = {};
// Take the validated bundles from the hub pool client.
const validatedBundles = sortEventsDescending(hubPoolClient.getValidatedRootBundles()).slice(
0,
this.monitorConfig.bundlesCount
);
// Fetch the data from the latest root bundle.
const bundle = hubPoolClient.getLatestProposedRootBundle();
const nextBundleMainnetStartBlock = hubPoolClient.getNextBundleStartBlockNumber(
this.clients.bundleDataClient.chainIdListForBundleEvaluationBlockNumbers,
hubPoolClient.latestHeightSearched,
hubPoolClient.chainId
);
const enabledChainIds = this.clients.configStoreClient.getChainIdIndicesForBlock(nextBundleMainnetStartBlock);
this.logger.debug({
at: "Monitor#checkSpokePoolRunningBalances",
message: "Mainnet root bundles in scope",
validatedBundles,
outstandingBundle: bundle,
});
const slowFillBlockRange = await getWidestPossibleExpectedBlockRange(
enabledChainIds,
this.clients.spokePoolClients,
getEndBlockBuffers(enabledChainIds, this.clients.bundleDataClient.blockRangeEndBlockBuffer),
this.clients,
hubPoolClient.latestHeightSearched,
this.clients.configStoreClient.getEnabledChains(hubPoolClient.latestHeightSearched)
);
const blockRangeTail = bundle.bundleEvaluationBlockNumbers.map((endBlockForChain, idx) => {
const endBlockNumber = Number(endBlockForChain);
const spokeLatestBlockSearched = this.clients.spokePoolClients[enabledChainIds[idx]]?.latestHeightSearched ?? 0;
return spokeLatestBlockSearched === 0
? [endBlockNumber, endBlockNumber]
: [endBlockNumber + 1, spokeLatestBlockSearched > endBlockNumber ? spokeLatestBlockSearched : endBlockNumber];
});
this.logger.debug({
at: "Monitor#checkSpokePoolRunningBalances",
message: "Block ranges to search",
slowFillBlockRange,
blockRangeTail,
});
const lastProposedBundleBlockRanges = getImpliedBundleBlockRanges(
hubPoolClient,
this.clients.configStoreClient,
hubPoolClient.hasPendingProposal()
? hubPoolClient.getLatestProposedRootBundle()
: hubPoolClient.getNthFullyExecutedRootBundle(-1)
);
// Do all async tasks in parallel. We want to know about the pool rebalances, slow fills in the most recent proposed bundle, refunds
// from the last `n` bundles, pending refunds which have not been made official via a root bundle proposal, and the current balances of
// all the spoke pools.
const [poolRebalanceRoot, currentBundleData, currentSpokeBalances] = await Promise.all([
this.clients.bundleDataClient.loadData(lastProposedBundleBlockRanges, this.clients.spokePoolClients, true),
this.clients.bundleDataClient.loadData(slowFillBlockRange, this.clients.spokePoolClients, true),
Object.fromEntries(
await mapAsync(chainIds, async (chainId) => {
const spokePool = this.clients.spokePoolClients[chainId].spokePoolAddress;
const l2TokenAddresses = monitoredTokenSymbols
.map((symbol) => l2TokenForChain(chainId, symbol))
.filter(isDefined);
const balances = Object.fromEntries(
await mapAsync(l2TokenAddresses, async (l2Token) => [
l2Token,
(
await this._getBalances([
{
token: l2Token,
chainId: chainId,
account: spokePool,
},
])
)[0],
])
);
return [chainId, balances];
})
),
]);
const poolRebalanceLeaves = (
await _buildPoolRebalanceRoot(
lastProposedBundleBlockRanges[0][1],
lastProposedBundleBlockRanges[0][1],
poolRebalanceRoot.bundleDepositsV3,
poolRebalanceRoot.bundleFillsV3,
poolRebalanceRoot.bundleSlowFillsV3,
poolRebalanceRoot.unexecutableSlowFills,
poolRebalanceRoot.expiredDepositsToRefundV3,
this.clients
)
).leaves;
// Get the pool rebalance leaf amounts.
const enabledTokens = [...this.l1Tokens];
for (const leaf of poolRebalanceLeaves) {
if (!chainIds.includes(leaf.chainId)) {
continue;
}
const l2TokenMap = this.getL2ToL1TokenMap(enabledTokens, leaf.chainId);
pendingRebalanceRoots[leaf.chainId] = {};
Object.entries(l2TokenMap).forEach(([l2Token, l1Token]) => {
const rebalanceAmount =
leaf.netSendAmounts[
leaf.l1Tokens
.map((l1Token) => l1Token.toEvmAddress())
.findIndex((token) => token === l1Token.address.toEvmAddress())
];
pendingRebalanceRoots[leaf.chainId][l2Token] = rebalanceAmount ?? bnZero;
});
}
this.logger.debug({
at: "Monitor#checkSpokePoolRunningBalances",
message: "Print pool rebalance leaves",
poolRebalanceRootLeaves: poolRebalanceLeaves,
});
// Calculate the pending refunds.
for (const chainId of chainIds) {
const l2TokenMap = this.getL2ToL1TokenMap(enabledTokens, chainId);
const l2TokenAddresses = monitoredTokenSymbols
.map((symbol) => l2TokenForChain(chainId, symbol))
.filter(isDefined);
pendingRelayerRefunds[chainId] = {};
l2TokenAddresses.forEach((l2Token) => {
const l1Token = l2TokenMap[l2Token.toNative()];
const upcomingBundleRefunds = this.getUpcomingRefunds(chainId, l1Token.address);
pendingRelayerRefunds[chainId][l2Token.toNative()] = upcomingBundleRefunds;
});
this.logger.debug({
at: "Monitor#checkSpokePoolRunningBalances",
message: "Print refund amounts for chainId",
chainId,
pendingDeductions: pendingRelayerRefunds[chainId],
});
}
// Get the slow fill amounts. Only do this step if there were slow fills in the most recent root bundle.
Object.entries(currentBundleData.bundleSlowFillsV3)
.filter(([chainId]) => chainIds.includes(+chainId))
.map(([chainId, bundleSlowFills]) => {
const l2TokenAddresses = monitoredTokenSymbols
.map((symbol) => l2TokenForChain(+chainId, symbol))
.filter(isDefined);
Object.entries(bundleSlowFills)
.filter(([l2Token]) => l2TokenAddresses.map((_l2Token) => _l2Token.toBytes32()).includes(l2Token))
.map(([l2Token, fills]) => {
const _l2Token = toAddressType(l2Token, +chainId);
const pendingSlowFillAmounts = fills
.map((fill) => fill.outputAmount)
.filter(isDefined)
.reduce((totalAmounts, outputAmount) => totalAmounts.add(outputAmount), bnZero);
pendingRelayerRefunds[chainId][_l2Token.toNative()] =
pendingRelayerRefunds[chainId][_l2Token.toNative()].add(pendingSlowFillAmounts);
});
});
// Print the output: The current spoke pool balance, the amount of refunds to payout, the pending pool rebalances, and then the sum of the three.
let tokenMarkdown =
"Token amounts: current, pending relayer refunds, pool rebalances, adjusted spoke pool balance\n";
for (const tokenSymbol of monitoredTokenSymbols) {
tokenMarkdown += `*[${tokenSymbol}]*\n`;
for (const chainId of chainIds) {
const tokenAddress = l2TokenForChain(chainId, tokenSymbol);
// If the token does not exist on the chain, then ignore this report.
if (!isDefined(tokenAddress)) {
continue;
}
const tokenDecimals = resolveTokenDecimals(tokenSymbol);
const currentSpokeBalance = formatWei(
currentSpokeBalances[chainId][tokenAddress.toNative()].toString(),
tokenDecimals
);
// Relayer refunds may be undefined when there were no refunds included in the last bundle.
const currentRelayerRefunds = formatWei(
(pendingRelayerRefunds[chainId]?.[tokenAddress.toNative()] ?? bnZero).toString(),
tokenDecimals
);
// Rebalance roots will be undefined when there was no root in the last bundle for the chain.
const currentRebalanceRoots = formatWei(
(pendingRebalanceRoots[chainId]?.[tokenAddress.toNative()] ?? bnZero).toString(),
tokenDecimals
);
const virtualSpokeBalance = formatWei(
currentSpokeBalances[chainId][tokenAddress.toNative()]
.add(pendingRebalanceRoots[chainId]?.[tokenAddress.toNative()] ?? bnZero)
.sub(pendingRelayerRefunds[chainId]?.[tokenAddress.toNative()] ?? bnZero)
.toString(),
tokenDecimals
);
tokenMarkdown += `${getNetworkName(chainId)}: `;
tokenMarkdown +=
currentSpokeBalance +
`, ${currentRelayerRefunds !== "0" ? "-" : ""}` +
currentRelayerRefunds +
", " +
currentRebalanceRoots +
", " +
virtualSpokeBalance +
"\n";
}
}
this.logger.info({
at: "Monitor#checkSpokePoolRunningBalances",