-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy path_utils.ts
2702 lines (2473 loc) · 79.2 KB
/
_utils.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 { AcceleratingDistributor__factory } from "@across-protocol/across-token/dist/typechain";
import {
ERC20__factory,
HubPool__factory,
SpokePool,
SpokePool__factory,
} from "@across-protocol/contracts/dist/typechain";
import acrossDeployments from "@across-protocol/contracts/dist/deployments/deployments.json";
import * as sdk from "@across-protocol/sdk";
import {
BALANCER_NETWORK_CONFIG,
BalancerSDK,
BalancerNetworkConfig,
Multicall3,
} from "@balancer-labs/sdk";
import axios, { AxiosError, AxiosRequestHeaders } from "axios";
import {
BigNumber,
BigNumberish,
ethers,
providers,
utils,
Signer,
} from "ethers";
import {
assert,
coerce,
create,
define,
Infer,
integer,
min,
size,
string,
Struct,
} from "superstruct";
import enabledMainnetRoutesAsJson from "../src/data/routes_1_0xc186fA914353c44b2E33eBE05f21846F1048bEda.json";
import enabledSepoliaRoutesAsJson from "../src/data/routes_11155111_0x14224e63716afAcE30C9a417E0542281869f7d9e.json";
import rpcProvidersJson from "../src/data/rpc-providers.json";
import {
MINIMAL_BALANCER_V2_POOL_ABI,
MINIMAL_BALANCER_V2_VAULT_ABI,
MINIMAL_MULTICALL3_ABI,
} from "./_abis";
import { BatchAccountBalanceResponse } from "./batch-account-balance";
import { StaticJsonRpcProvider } from "@ethersproject/providers";
import { VercelRequestQuery, VercelResponse } from "@vercel/node";
import {
BLOCK_TAG_LAG,
CHAIN_IDs,
CHAINS,
CUSTOM_GAS_TOKENS,
DEFAULT_LITE_CHAIN_USD_MAX_BALANCE,
DEFAULT_LITE_CHAIN_USD_MAX_DEPOSIT,
DEFI_LLAMA_POOL_LOOKUP,
DOMAIN_CALLDATA_DELIMITER,
EXTERNAL_POOL_TOKEN_EXCHANGE_RATE,
MULTICALL3_ADDRESS,
MULTICALL3_ADDRESS_OVERRIDES,
SECONDS_PER_YEAR,
TOKEN_SYMBOLS_MAP,
disabledL1Tokens,
graphAPIKey,
maxRelayFeePct,
relayerFeeCapitalCostConfig,
} from "./_constants";
import { PoolStateOfUser, PoolStateResult, TokenInfo } from "./_types";
import {
buildInternalCacheKey,
getCachedValue,
makeCacheGetterAndSetter,
} from "./_cache";
import {
MissingParamError,
InvalidParamError,
RouteNotEnabledError,
AcrossApiError,
HttpErrorToStatusCode,
AcrossErrorCode,
TokenNotFoundError,
} from "./_errors";
import { Token } from "./_dexes/types";
export { InputError, handleErrorCondition } from "./_errors";
export const { Profiler } = sdk.utils;
type LoggingUtility = sdk.relayFeeCalculator.Logger;
type RpcProviderName = keyof typeof rpcProvidersJson.providers.urls;
import { getEnvs } from "./_env";
const {
REACT_APP_HUBPOOL_CHAINID,
REACT_APP_COINGECKO_PRO_API_KEY,
BASE_FEE_MARKUP,
PRIORITY_FEE_MARKUP,
OP_STACK_L1_DATA_FEE_MARKUP,
VERCEL_ENV,
LOG_LEVEL,
REACT_APP_DISABLED_CHAINS,
REACT_APP_DISABLED_CHAINS_FOR_AVAILABLE_ROUTES,
REACT_APP_DISABLED_TOKENS_FOR_AVAILABLE_ROUTES,
LIMITS_BUFFER_MULTIPLIERS,
CHAIN_USD_MAX_BALANCES,
CHAIN_USD_MAX_DEPOSITS,
VERCEL_AUTOMATION_BYPASS_SECRET,
RPC_HEADERS,
} = getEnvs();
// Don't permit HUB_POOL_CHAIN_ID=0
export const HUB_POOL_CHAIN_ID = Number(REACT_APP_HUBPOOL_CHAINID || 1) as
| 1
| 11155111;
// Tokens that should be disabled in the routes
export const DISABLED_ROUTE_TOKENS = (
getEnvs().DISABLED_ROUTE_TOKENS || ""
).split(",");
// This is an array of chainIds that should be disabled. This array overrides
// the ENABLED_ROUTES object below. This is useful for disabling a chainId
// temporarily without having to redeploy the app or change core config
// data (e.g. the ENABLED_ROUTES object and the data/routes.json files).
export const DISABLED_CHAINS = (REACT_APP_DISABLED_CHAINS || "").split(",");
// This is an array of chainIds that should be disabled. In contrast to the
// above constant `DISABLED_CHAINS`, this constant is used to disable chains
// only for the `/available-routes` endpoint and DOES NOT affect the
// `ENABLED_ROUTES` object.
export const DISABLED_CHAINS_FOR_AVAILABLE_ROUTES = (
REACT_APP_DISABLED_CHAINS_FOR_AVAILABLE_ROUTES || ""
).split(",");
export const DISABLED_TOKENS_FOR_AVAILABLE_ROUTES = (
REACT_APP_DISABLED_TOKENS_FOR_AVAILABLE_ROUTES || ""
).split(",");
// Chains that require special role to be accessed.
export const OPT_IN_CHAINS = (getEnvs().OPT_IN_CHAINS || "").split(",");
const _ENABLED_ROUTES =
HUB_POOL_CHAIN_ID === 1
? enabledMainnetRoutesAsJson
: enabledSepoliaRoutesAsJson;
_ENABLED_ROUTES.routes = _ENABLED_ROUTES.routes.filter(
({ fromChain, toChain, fromTokenSymbol }) =>
![fromChain, toChain].some((chainId) =>
DISABLED_CHAINS.includes(chainId.toString())
) && !DISABLED_ROUTE_TOKENS.includes(fromTokenSymbol)
);
export const ENABLED_ROUTES = _ENABLED_ROUTES;
export const LogLevels = {
ERROR: 3,
WARN: 2,
INFO: 1,
DEBUG: 0,
} as const;
// Singleton logger so we don't create multiple.
let logger: LoggingUtility;
/**
* Resolves a logging utility to be used. This instance caches its responses
* @returns A valid Logging utility that can be used throughout the runtime
*/
export const getLogger = (): LoggingUtility => {
if (!logger) {
const defaultLogLevel = VERCEL_ENV === "production" ? "ERROR" : "DEBUG";
let logLevel =
LOG_LEVEL && Object.keys(LogLevels).includes(LOG_LEVEL)
? (LOG_LEVEL as keyof typeof LogLevels)
: defaultLogLevel;
logger = {
debug: (...args) => {
if (LogLevels[logLevel] <= LogLevels.DEBUG) {
console.debug(args);
}
},
info: (...args) => {
if (LogLevels[logLevel] <= LogLevels.INFO) {
console.info(args);
}
},
warn: (...args) => {
if (LogLevels[logLevel] <= LogLevels.WARN) {
console.warn(args);
}
},
error: (...args) => {
if (LogLevels[logLevel] <= LogLevels.ERROR) {
console.error(args);
}
},
};
}
return logger;
};
/**
* Resolves the current vercel endpoint dynamically
* @returns A valid URL of the current endpoint in vercel
*/
export const resolveVercelEndpoint = (omitOverride = false) => {
if (!omitOverride && process.env.REACT_APP_VERCEL_API_BASE_URL_OVERRIDE) {
return process.env.REACT_APP_VERCEL_API_BASE_URL_OVERRIDE;
}
const url = process.env.VERCEL_URL ?? "across.to";
const env = process.env.VERCEL_ENV ?? "development";
switch (env) {
case "preview":
case "production":
return `https://${url}`;
case "development":
default:
return `http://127.0.0.1:3000`;
}
};
export const getVercelHeaders = (): AxiosRequestHeaders | undefined => {
if (VERCEL_AUTOMATION_BYPASS_SECRET) {
return {
"x-vercel-protection-bypass": VERCEL_AUTOMATION_BYPASS_SECRET,
};
}
};
export const validateChainAndTokenParams = (
queryParams: Partial<{
token: string;
inputToken: string;
outputToken: string;
originChainId: string;
destinationChainId: string;
}>
) => {
let {
token,
inputToken: inputTokenAddress,
outputToken: outputTokenAddress,
originChainId,
destinationChainId: _destinationChainId,
} = queryParams;
if (!_destinationChainId) {
throw new MissingParamError({
message: "Query param 'destinationChainId' must be provided",
});
}
if (originChainId === _destinationChainId) {
throw new InvalidParamError({
message: "Origin and destination chains cannot be the same",
});
}
if (!token && (!inputTokenAddress || !outputTokenAddress)) {
throw new MissingParamError({
message:
"Query param 'token' or 'inputToken' and 'outputToken' must be provided",
});
}
const destinationChainId = Number(_destinationChainId);
inputTokenAddress = _getAddressOrThrowInputError(
(token || inputTokenAddress) as string,
token ? "token" : "inputToken"
);
outputTokenAddress = outputTokenAddress
? _getAddressOrThrowInputError(outputTokenAddress, "outputToken")
: undefined;
const { l1Token, outputToken, inputToken, resolvedOriginChainId } =
getRouteDetails(
inputTokenAddress,
destinationChainId,
originChainId ? Number(originChainId) : undefined,
outputTokenAddress
);
if (
disabledL1Tokens.includes(l1Token.address.toLowerCase()) ||
!isRouteEnabled(
resolvedOriginChainId,
destinationChainId,
inputToken.address,
outputToken.address
)
) {
throw new RouteNotEnabledError({
message: "Route is not enabled.",
});
}
return {
l1Token,
inputToken,
outputToken,
destinationChainId,
resolvedOriginChainId,
};
};
export const validateDepositMessage = async (
recipient: string,
destinationChainId: number,
relayer: string,
outputTokenAddress: string,
amountInput: string,
message: string
) => {
if (!sdk.utils.isMessageEmpty(message)) {
if (!ethers.utils.isHexString(message)) {
throw new InvalidParamError({
message: "Message must be a hex string",
param: "message",
});
}
if (message.length % 2 !== 0) {
// Our message encoding is a hex string, so we need to check that the length is even.
throw new InvalidParamError({
message: "Message must be an even hex string",
param: "message",
});
}
const isRecipientAContract =
getStaticIsContract(destinationChainId, recipient) ||
(await isContractCache(destinationChainId, recipient).get());
if (!isRecipientAContract) {
throw new InvalidParamError({
message: "Recipient must be a contract when a message is provided",
param: "recipient",
});
} else {
// If we're in this case, it's likely that we're going to have to simulate the execution of
// a complex message handling from the specified relayer to the specified recipient by calling
// the arbitrary function call `handleAcrossMessage` at the recipient. So that we can discern
// the difference between an OUT_OF_FUNDS error in either the transfer or through the execution
// of the `handleAcrossMessage` we will check that the balance of the relayer is sufficient to
// support this deposit.
const balanceOfToken = await getCachedTokenBalance(
destinationChainId,
relayer,
outputTokenAddress
);
if (balanceOfToken.lt(amountInput)) {
throw new InvalidParamError({
message:
`Relayer Address (${relayer}) doesn't have enough funds to support this deposit;` +
` for help, please reach out to https://discord.across.to`,
param: "relayer",
});
}
}
}
};
function getStaticIsContract(chainId: number, address: string) {
const deployedAcrossContract = Object.values(
(
acrossDeployments as {
[chainId: number]: {
[contractName: string]: {
address: string;
};
};
}
)[chainId]
).find(
(contract) => contract.address.toLowerCase() === address.toLowerCase()
);
return !!deployedAcrossContract;
}
export function getChainInfo(chainId: number) {
const chainInfo = CHAINS[chainId];
if (!chainInfo) {
throw new Error(`Cannot get chain info for chain ${chainId}`);
}
return chainInfo;
}
export function getWrappedNativeTokenAddress(chainId: number) {
const chainInfo = getChainInfo(chainId);
const wrappedNativeTokenSymbol =
chainId === CHAIN_IDs.LENS ? "WGHO" : `W${chainInfo.nativeToken}`;
const wrappedNativeToken =
TOKEN_SYMBOLS_MAP[
wrappedNativeTokenSymbol as keyof typeof TOKEN_SYMBOLS_MAP
];
const wrappedNativeTokenAddress = wrappedNativeToken?.addresses[chainId];
if (!wrappedNativeTokenAddress) {
throw new Error(
`Cannot get wrapped native token for chain ${chainId} and symbol ${wrappedNativeTokenSymbol}`
);
}
return wrappedNativeTokenAddress;
}
/**
* Utility function to resolve route details based on given `inputTokenAddress` and `destinationChainId`.
* The optional parameter `originChainId` can be omitted if the `inputTokenAddress` is unique across all
* chains. If the `inputTokenAddress` is not unique across all chains, the `originChainId` must be
* provided to resolve the correct token details.
* @param inputTokenAddress The token address to resolve details for.
* @param destinationChainId The destination chain id of the route.
* @param originChainId Optional if the `inputTokenAddress` is unique across all chains. Required if not.
* @param outputTokenAddress Optional output token address.
* @returns Token details of route and additional information, such as the inferred origin chain id, L1
* token address and the input/output token addresses.
*/
export const getRouteDetails = (
inputTokenAddress: string,
destinationChainId: number,
originChainId?: number,
outputTokenAddress?: string
) => {
const inputToken = getTokenByAddress(inputTokenAddress, originChainId);
if (!inputToken) {
throw new InvalidParamError({
message: originChainId
? "Unsupported token on given origin chain"
: "Unsupported token address",
param: "inputTokenAddress",
});
}
const l1TokenAddress =
TOKEN_SYMBOLS_MAP[inputToken.symbol as keyof typeof TOKEN_SYMBOLS_MAP]
.addresses[HUB_POOL_CHAIN_ID];
const l1Token = getTokenByAddress(l1TokenAddress, HUB_POOL_CHAIN_ID);
if (!l1Token) {
throw new InvalidParamError({
message: "No L1 token found for given input token address",
param: "inputTokenAddress",
});
}
outputTokenAddress ??=
inputToken.addresses[destinationChainId] ||
l1Token.addresses[destinationChainId];
const outputToken = outputTokenAddress
? getTokenByAddress(outputTokenAddress, destinationChainId)
: undefined;
if (!outputToken) {
throw new InvalidParamError({
message: "Unsupported token address on given destination chain",
param: "outputTokenAddress",
});
}
const possibleOriginChainIds = originChainId
? [originChainId]
: _getChainIdsOfToken(inputTokenAddress, inputToken);
if (possibleOriginChainIds.length === 0) {
throw new InvalidParamError({
message: "Unsupported token address",
param: "inputTokenAddress",
});
}
if (possibleOriginChainIds.length > 1) {
throw new InvalidParamError({
message:
"More than one route is enabled for the provided inputs causing ambiguity. Please specify the originChainId.",
param: "inputTokenAddress",
});
}
const resolvedOriginChainId = possibleOriginChainIds[0];
return {
inputToken: {
...inputToken,
symbol: sdk.utils.isBridgedUsdc(inputToken.symbol)
? _getBridgedUsdcTokenSymbol(inputToken.symbol, resolvedOriginChainId)
: inputToken.symbol,
address: utils.getAddress(inputToken.addresses[resolvedOriginChainId]),
},
outputToken: {
...outputToken,
symbol: sdk.utils.isBridgedUsdc(outputToken.symbol)
? _getBridgedUsdcTokenSymbol(outputToken.symbol, destinationChainId)
: outputToken.symbol,
address: utils.getAddress(outputToken.addresses[destinationChainId]),
},
l1Token: {
...l1Token,
address: l1TokenAddress,
},
resolvedOriginChainId,
};
};
export const getTokenByAddress = (
tokenAddress: string,
chainId?: number
):
| {
decimals: number;
symbol: string;
name: string;
addresses: Record<number, string>;
coingeckoId: string;
}
| undefined => {
const matches =
Object.entries(TOKEN_SYMBOLS_MAP).filter(([_symbol, { addresses }]) =>
chainId
? addresses[chainId]?.toLowerCase() === tokenAddress.toLowerCase()
: Object.values(addresses).some(
(address) => address.toLowerCase() === tokenAddress.toLowerCase()
)
) || [];
if (matches.length === 0) {
return undefined;
}
if (matches.length > 1) {
const nativeUsdc = matches.find(([symbol]) => symbol === "USDC");
if (chainId === HUB_POOL_CHAIN_ID && nativeUsdc) {
return nativeUsdc[1];
}
}
return matches[0][1];
};
const _getChainIdsOfToken = (
tokenAddress: string,
token: Omit<
(typeof TOKEN_SYMBOLS_MAP)[keyof typeof TOKEN_SYMBOLS_MAP],
"coingeckoId"
>
) => {
const chainIds = Object.entries(token.addresses).filter(
([_, address]) => address.toLowerCase() === tokenAddress.toLowerCase()
);
return chainIds.map(([chainId]) => Number(chainId));
};
const _getBridgedUsdcTokenSymbol = (tokenSymbol: string, chainId: number) => {
if (!sdk.utils.isBridgedUsdc(tokenSymbol)) {
throw new Error(`Token ${tokenSymbol} is not a bridged USDC token`);
}
switch (chainId) {
case CHAIN_IDs.BASE:
return TOKEN_SYMBOLS_MAP.USDbC.symbol;
case CHAIN_IDs.ZORA:
return TOKEN_SYMBOLS_MAP.USDzC.symbol;
default:
return TOKEN_SYMBOLS_MAP["USDC.e"].symbol;
}
};
const _getAddressOrThrowInputError = (address: string, paramName: string) => {
try {
return ethers.utils.getAddress(address);
} catch (err) {
throw new InvalidParamError({
message: `Invalid address provided for '${paramName}'`,
param: paramName,
});
}
};
export const getHubPool = (provider: providers.Provider) => {
return HubPool__factory.connect(ENABLED_ROUTES.hubPoolAddress, provider);
};
/**
* Resolves a fixed Static RPC provider if an override url has been specified.
* @returns A provider or undefined if an override was not specified.
*/
export const getPublicProvider = (
chainId: string
): providers.StaticJsonRpcProvider | undefined => {
const chain = sdk.constants.PUBLIC_NETWORKS[Number(chainId)];
if (chain) {
const headers = getProviderHeaders(chainId);
return new ethers.providers.StaticJsonRpcProvider({
url: chain.publicRPC,
headers,
});
} else {
return undefined;
}
};
/**
* Generates a fixed HubPoolClientConfig object
* @returns A fixed constant
*/
export const makeHubPoolClientConfig = (chainId = 1) => {
return {
chainId: chainId,
hubPoolAddress: ENABLED_ROUTES.hubPoolAddress,
wethAddress: TOKEN_SYMBOLS_MAP.WETH.addresses[CHAIN_IDs.MAINNET],
configStoreAddress: ENABLED_ROUTES.acrossConfigStoreAddress,
acceleratingDistributorAddress:
ENABLED_ROUTES.acceleratingDistributorAddress,
merkleDistributorAddress: ENABLED_ROUTES.merkleDistributorAddress,
};
};
/**
* Resolves the current HubPoolClient
* @returns A HubPool client that can query the blockchain
*/
export const getHubPoolClient = () => {
const hubPoolConfig = makeHubPoolClientConfig(HUB_POOL_CHAIN_ID);
return new sdk.pool.Client(
hubPoolConfig,
{
provider: getProvider(HUB_POOL_CHAIN_ID),
},
(_, __) => {} // Dummy function that does nothing and is needed to construct this client.
);
};
export const baseFeeMarkup: {
[chainId: string]: number;
} = JSON.parse(BASE_FEE_MARKUP || "{}");
export const priorityFeeMarkup: {
[chainId: string]: number;
} = JSON.parse(PRIORITY_FEE_MARKUP || "{}");
export const opStackL1DataFeeMarkup: {
[chainId: string]: number;
} = JSON.parse(OP_STACK_L1_DATA_FEE_MARKUP || "{}");
// Conservative values bsaed on existing configurations:
// - base fee gets marked up 1.5x because most chains have a theoretically volatile base fee but practically little
// volume so the base fee doesn't move much.
// - priority fee gets marked up 1.0x because new chains don't have enough volume to move priority
// fees much.
// - op stack l1 data fee gets marked up 1.0x because the op stack l1 data fee is based on ethereum
// base fee.
export const DEFAULT_BASE_FEE_MARKUP = 0.5;
export const DEFAULT_PRIORITY_FEE_MARKUP = 0;
export const DEFAULT_OP_L1_DATA_FEE_MARKUP = 1;
export const getGasMarkup = (
chainId: string | number
): {
baseFeeMarkup: BigNumber;
priorityFeeMarkup: BigNumber;
opStackL1DataFeeMarkup: BigNumber;
} => {
let _baseFeeMarkup: BigNumber | undefined;
let _priorityFeeMarkup: BigNumber | undefined;
let _opStackL1DataFeeMarkup: BigNumber | undefined;
if (typeof baseFeeMarkup[chainId] === "number") {
_baseFeeMarkup = utils.parseEther((1 + baseFeeMarkup[chainId]).toString());
}
if (typeof priorityFeeMarkup[chainId] === "number") {
_priorityFeeMarkup = utils.parseEther(
(1 + priorityFeeMarkup[chainId]).toString()
);
}
if (typeof opStackL1DataFeeMarkup[chainId] === "number") {
_opStackL1DataFeeMarkup = utils.parseEther(
(1 + opStackL1DataFeeMarkup[chainId]).toString()
);
}
// Otherwise, use default gas markup.
if (_baseFeeMarkup === undefined) {
_baseFeeMarkup = utils.parseEther((1 + DEFAULT_BASE_FEE_MARKUP).toString());
}
if (_priorityFeeMarkup === undefined) {
_priorityFeeMarkup = utils.parseEther(
(1 + DEFAULT_PRIORITY_FEE_MARKUP).toString()
);
}
if (_opStackL1DataFeeMarkup === undefined) {
_opStackL1DataFeeMarkup = utils.parseEther(
(1 + DEFAULT_OP_L1_DATA_FEE_MARKUP).toString()
);
}
return {
baseFeeMarkup: _baseFeeMarkup,
priorityFeeMarkup: _priorityFeeMarkup,
opStackL1DataFeeMarkup: _opStackL1DataFeeMarkup,
};
};
/**
* Retrieves an isntance of the Across SDK RelayFeeCalculator
* @param destinationChainId The destination chain that a bridge operation will transfer to
* @returns An instance of the `RelayFeeCalculator` for the specific chain specified by `destinationChainId`
*/
export const getRelayerFeeCalculator = (
destinationChainId: number,
overrides: Partial<{
spokePoolAddress: string;
relayerAddress: string;
}> = {}
) => {
const queries = getRelayerFeeCalculatorQueries(destinationChainId, overrides);
const relayerFeeCalculatorConfig = {
feeLimitPercent: maxRelayFeePct * 100,
queries,
capitalCostsConfig: relayerFeeCapitalCostConfig,
};
if (relayerFeeCalculatorConfig.feeLimitPercent < 1)
throw new Error(
"Setting fee limit % < 1% will produce nonsensical relay fee details"
);
return new sdk.relayFeeCalculator.RelayFeeCalculator(
relayerFeeCalculatorConfig,
logger
);
};
export const getRelayerFeeCalculatorQueries = (
destinationChainId: number,
overrides: Partial<{
spokePoolAddress: string;
relayerAddress: string;
}> = {}
) => {
const baseArgs = {
chainId: destinationChainId,
provider: getProvider(destinationChainId, { useSpeedProvider: true }),
symbolMapping: TOKEN_SYMBOLS_MAP,
spokePoolAddress:
overrides.spokePoolAddress || getSpokePoolAddress(destinationChainId),
simulatedRelayerAddress:
overrides.relayerAddress ||
sdk.constants.DEFAULT_SIMULATED_RELAYER_ADDRESS,
coingeckoProApiKey: REACT_APP_COINGECKO_PRO_API_KEY,
logger: getLogger(),
};
const customGasTokenSymbol = CUSTOM_GAS_TOKENS[destinationChainId];
if (customGasTokenSymbol) {
return new sdk.relayFeeCalculator.CustomGasTokenQueries({
queryBaseArgs: [
baseArgs.provider,
baseArgs.symbolMapping,
baseArgs.spokePoolAddress,
baseArgs.simulatedRelayerAddress,
baseArgs.logger,
baseArgs.coingeckoProApiKey,
undefined,
"usd",
],
customGasTokenSymbol,
});
}
return sdk.relayFeeCalculator.QueryBase__factory.create(
baseArgs.chainId,
baseArgs.provider,
baseArgs.symbolMapping,
baseArgs.spokePoolAddress,
baseArgs.simulatedRelayerAddress,
baseArgs.coingeckoProApiKey,
baseArgs.logger
);
};
/**
* Retrieves the results of the `relayFeeCalculator` SDK function: `relayerFeeDetails`
* @param inputToken A valid input token address
* @param outputToken A valid output token address
* @param amount The amount of funds that are requesting to be transferred
* @param originChainId The origin chain that this token will be transferred from
* @param destinationChainId The destination chain that this token will be transferred to
* @param recipientAddress The address that will receive the transferred funds
* @param message An optional message to include in the transfer
* @param tokenPrice Price of input token in gas token units, used by SDK to compute gas fee percentages.
* @param relayerAddress Relayer address that SDK will use to simulate the fill transaction for gas cost estimation if
* the gasUnits is not defined.
* @param gasPrice Gas price that SDK will use to compute gas fee percentages.
* @param [gasUnits] An optional gas cost to use for the transfer. If not provided, the SDK will recompute this.
* @returns Relayer fee components for a fill of the given `amount` of transferring `l1Token` to `destinationChainId`
*/
export const getRelayerFeeDetails = async (
deposit: {
inputToken: string;
outputToken: string;
amount: sdk.utils.BigNumberish;
originChainId: number;
destinationChainId: number;
recipientAddress: string;
message?: string;
},
tokenPrice: number,
relayerAddress: string,
gasPrice?: sdk.utils.BigNumberish,
gasUnits?: sdk.utils.BigNumberish,
tokenGasCost?: sdk.utils.BigNumberish
): Promise<sdk.relayFeeCalculator.RelayerFeeDetails> => {
const {
inputToken,
outputToken,
amount,
originChainId,
destinationChainId,
recipientAddress,
message,
} = deposit;
const relayFeeCalculator = getRelayerFeeCalculator(destinationChainId, {
relayerAddress,
});
return await relayFeeCalculator.relayerFeeDetails(
buildDepositForSimulation({
amount: amount.toString(),
inputToken,
outputToken,
recipientAddress,
originChainId,
destinationChainId,
message,
}),
amount,
sdk.utils.isMessageEmpty(message),
relayerAddress,
tokenPrice,
gasPrice,
gasUnits,
tokenGasCost
);
};
export const buildDepositForSimulation = (depositArgs: {
amount: BigNumberish;
inputToken: string;
outputToken: string;
recipientAddress: string;
originChainId: number;
destinationChainId: number;
message?: string;
}) => {
const {
amount,
inputToken,
outputToken,
recipientAddress,
originChainId,
destinationChainId,
message,
} = depositArgs;
// Small amount to simulate filling with. Should be low enough to guarantee a successful fill.
const safeOutputAmount = sdk.utils.toBN(100);
return {
inputAmount: sdk.utils.toBN(amount),
outputAmount: sdk.utils.isMessageEmpty(message)
? safeOutputAmount
: sdk.utils.toBN(amount),
depositId: sdk.utils.bnUint32Max,
depositor: recipientAddress,
recipient: recipientAddress,
destinationChainId,
originChainId,
quoteTimestamp: sdk.utils.getCurrentTime() - 60, // Set the quote timestamp to 60 seconds ago ~ 1 ETH block
inputToken,
outputToken,
fillDeadline: sdk.utils.bnUint32Max.toNumber(), // Defined as `INFINITE_FILL_DEADLINE` in SpokePool.sol
exclusiveRelayer: sdk.constants.ZERO_ADDRESS,
exclusivityDeadline: 0, // Defined as ZERO in SpokePool.sol
message: message ?? sdk.constants.EMPTY_MESSAGE,
messageHash: sdk.utils.getMessageHash(
message ?? sdk.constants.EMPTY_MESSAGE
),
fromLiteChain: false, // FIXME
toLiteChain: false, // FIXME
};
};
/**
* Creates an HTTP call to the `/api/coingecko` endpoint to resolve a CoinGecko price
* @param l1Token The ERC20 token address of the coin to find the cached price of
* @param baseCurrency The base currency to convert the token price to
* @param date An optional date string in the format of `DD-MM-YYYY` to resolve a historical price
* @returns The price of the `l1Token` token.
*/
export const getCachedTokenPrice = async (
l1Token: string,
baseCurrency: string = "eth",
historicalDateISO?: string,
chainId?: number
): Promise<number> => {
return Number(
(
await axios(`${resolveVercelEndpoint()}/api/coingecko`, {
params: {
l1Token,
chainId,
baseCurrency,
date: historicalDateISO,
},
headers: getVercelHeaders(),
})
).data.price
);
};
/**
* Creates an HTTP call to the `/api/limits` endpoint to resolve limits for a given token/route.
* @param inputToken The input token address
* @param outputToken The output token address
* @param originChainId The origin chain id
* @param destinationChainId The destination chain id
*/
export const getCachedLimits = async (
inputToken: string,
outputToken: string,
originChainId: number,
destinationChainId: number,
amount?: string,
recipient?: string,
relayer?: string,
message?: string
): Promise<{
minDeposit: string;
maxDeposit: string;
maxDepositInstant: string;
maxDepositShortDelay: string;
recommendedDepositInstant: string;
relayerFeeDetails: {
relayFeeTotal: string;
relayFeePercent: string;
capitalFeePercent: string;
capitalFeeTotal: string;
gasFeePercent: string;
gasFeeTotal: string;
};
}> => {
return (
await axios(`${resolveVercelEndpoint()}/api/limits`, {
headers: getVercelHeaders(),
params: {
inputToken,
outputToken,
originChainId,
destinationChainId,
amount,
message,
recipient,
relayer,
},
})
).data;
};
export async function getSuggestedFees(params: {
inputToken: string;
outputToken: string;
originChainId: number;
destinationChainId: number;
amount: string;
skipAmountLimit?: boolean;
message?: string;
depositMethod?: string;
recipient?: string;
}): Promise<{
estimatedFillTimeSec: number;
timestamp: number;
isAmountTooLow: boolean;
quoteBlock: string;
exclusiveRelayer: string;
exclusivityDeadline: number;
spokePoolAddress: string;
destinationSpokePoolAddress: string;
totalRelayFee: {
pct: string;
total: string;
};
relayerCapitalFee: {
pct: string;
total: string;
};
relayerGasFee: {
pct: string;
total: string;
};
lpFee: {
pct: string;
total: string;
};
limits: {
minDeposit: string;
maxDeposit: string;
maxDepositInstant: string;