@lifi/sdk 1.1.2 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/Lifi.js +179 -285
  3. package/dist/allowance/index.js +56 -148
  4. package/dist/allowance/utils.js +51 -116
  5. package/dist/balances/index.js +29 -92
  6. package/dist/balances/utils.js +108 -218
  7. package/dist/cjs/Lifi.d.ts +200 -0
  8. package/dist/cjs/Lifi.js +376 -0
  9. package/dist/cjs/allowance/index.d.ts +22 -0
  10. package/dist/cjs/allowance/index.js +78 -0
  11. package/dist/cjs/allowance/utils.d.ts +14 -0
  12. package/dist/cjs/allowance/utils.js +82 -0
  13. package/dist/cjs/balances/index.d.ts +11 -0
  14. package/dist/cjs/balances/index.js +46 -0
  15. package/dist/cjs/balances/utils.d.ts +5 -0
  16. package/dist/cjs/balances/utils.js +150 -0
  17. package/dist/cjs/connectors.d.ts +6 -0
  18. package/dist/cjs/connectors.js +77 -0
  19. package/dist/cjs/execution/StatusManager.d.ts +65 -0
  20. package/dist/cjs/execution/StatusManager.js +167 -0
  21. package/dist/cjs/execution/StepExecutor.d.ts +15 -0
  22. package/dist/cjs/execution/StepExecutor.js +74 -0
  23. package/dist/cjs/execution/allowance.execute.d.ts +4 -0
  24. package/dist/cjs/execution/allowance.execute.js +97 -0
  25. package/dist/cjs/execution/balanceCheck.execute.d.ts +3 -0
  26. package/dist/cjs/execution/balanceCheck.execute.js +48 -0
  27. package/dist/cjs/execution/bridges/bridge.execute.d.ts +7 -0
  28. package/dist/cjs/execution/bridges/bridge.execute.js +154 -0
  29. package/dist/cjs/execution/exchanges/swap.execute.d.ts +7 -0
  30. package/dist/cjs/execution/exchanges/swap.execute.js +164 -0
  31. package/dist/cjs/execution/index.d.ts +1 -0
  32. package/dist/cjs/execution/index.js +17 -0
  33. package/dist/cjs/execution/stepComparison.d.ts +14 -0
  34. package/dist/cjs/execution/stepComparison.js +46 -0
  35. package/dist/cjs/execution/switchChain.d.ts +16 -0
  36. package/dist/cjs/execution/switchChain.js +58 -0
  37. package/dist/cjs/execution/utils.d.ts +6 -0
  38. package/dist/cjs/execution/utils.js +137 -0
  39. package/dist/cjs/helpers.d.ts +18 -0
  40. package/dist/cjs/helpers.js +54 -0
  41. package/dist/cjs/index.d.ts +6 -0
  42. package/dist/cjs/index.js +27 -0
  43. package/dist/cjs/services/ApiService.d.ts +15 -0
  44. package/dist/cjs/services/ApiService.js +272 -0
  45. package/dist/cjs/services/ChainsService.d.ts +11 -0
  46. package/dist/cjs/services/ChainsService.js +54 -0
  47. package/dist/cjs/services/ConfigService.d.ts +23 -0
  48. package/dist/cjs/services/ConfigService.js +98 -0
  49. package/dist/cjs/typeguards.d.ts +4 -0
  50. package/dist/cjs/typeguards.js +53 -0
  51. package/dist/cjs/types/ERC20.d.ts +22 -0
  52. package/dist/cjs/types/ERC20.js +53 -0
  53. package/dist/cjs/types/index.d.ts +4 -0
  54. package/dist/cjs/types/index.js +22 -0
  55. package/dist/cjs/types/internal.types.d.ts +85 -0
  56. package/dist/cjs/types/internal.types.js +2 -0
  57. package/dist/cjs/utils/errors.d.ts +75 -0
  58. package/dist/cjs/utils/errors.js +115 -0
  59. package/dist/cjs/utils/getProvider.d.ts +3 -0
  60. package/dist/cjs/utils/getProvider.js +11 -0
  61. package/dist/cjs/utils/multicall.d.ts +10 -0
  62. package/dist/cjs/utils/multicall.js +77 -0
  63. package/dist/cjs/utils/multicallAbi.json +313 -0
  64. package/dist/cjs/utils/parseError.d.ts +38 -0
  65. package/dist/cjs/utils/parseError.js +141 -0
  66. package/dist/cjs/utils/preRestart.d.ts +2 -0
  67. package/dist/cjs/utils/preRestart.js +31 -0
  68. package/dist/cjs/utils/utils.d.ts +26 -0
  69. package/dist/cjs/utils/utils.js +120 -0
  70. package/dist/connectors.js +50 -133
  71. package/dist/execution/StatusManager.js +34 -41
  72. package/dist/execution/StepExecutor.js +54 -123
  73. package/dist/execution/allowance.execute.js +76 -142
  74. package/dist/execution/balanceCheck.execute.js +29 -74
  75. package/dist/execution/bridges/bridge.execute.js +132 -221
  76. package/dist/execution/exchanges/swap.execute.js +142 -225
  77. package/dist/execution/index.js +1 -17
  78. package/dist/execution/stepComparison.js +22 -61
  79. package/dist/execution/switchChain.js +33 -81
  80. package/dist/execution/utils.js +60 -119
  81. package/dist/helpers.js +15 -53
  82. package/dist/index.js +6 -25
  83. package/dist/services/ApiService.js +248 -385
  84. package/dist/services/ChainsService.js +29 -89
  85. package/dist/services/ConfigService.js +47 -86
  86. package/dist/typeguards.js +13 -21
  87. package/dist/types/ERC20.js +1 -4
  88. package/dist/types/index.js +4 -22
  89. package/dist/types/internal.types.js +1 -2
  90. package/dist/utils/errors.js +47 -93
  91. package/dist/utils/getProvider.js +3 -7
  92. package/dist/utils/multicall.js +61 -117
  93. package/dist/utils/parseError.js +73 -141
  94. package/dist/utils/preRestart.js +14 -21
  95. package/dist/utils/utils.js +47 -130
  96. package/package.json +34 -11
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const types_1 = require("../types");
13
+ const DefaultExecutionSettings = {
14
+ /* eslint-disable-next-line @typescript-eslint/no-empty-function */
15
+ updateCallback: () => { },
16
+ switchChainHook: () => Promise.resolve(undefined),
17
+ acceptSlippageUpdateHook: () => Promise.resolve(undefined),
18
+ infiniteApproval: false,
19
+ };
20
+ class ConfigService {
21
+ constructor() {
22
+ this.resolveSetupPromise = undefined;
23
+ /**
24
+ * This call immediately returns the current config. It does not make sure that all chain data is already loaded
25
+ * Use this if you need access to basic information like API urls or settings
26
+ */
27
+ this.getConfig = () => {
28
+ return this.config;
29
+ };
30
+ /**
31
+ * This call waits for all setup promises to be done.
32
+ * Use this if you need access to chain data (RPCs or multicalls)
33
+ */
34
+ this.getConfigAsync = () => __awaiter(this, void 0, void 0, function* () {
35
+ yield this.setupPromise;
36
+ return this.config;
37
+ });
38
+ this.updateConfig = (configUpdate) => {
39
+ // API
40
+ this.config.apiUrl = configUpdate.apiUrl || this.config.apiUrl;
41
+ // RPCS
42
+ this.config.rpcs = Object.assign(this.config.rpcs, configUpdate.rpcs);
43
+ // MULTICALL
44
+ this.config.multicallAddresses = Object.assign(this.config.multicallAddresses, configUpdate.multicallAddresses);
45
+ // SETTINGS
46
+ this.config.defaultExecutionSettings = Object.assign(this.config.defaultExecutionSettings, configUpdate.defaultExecutionSettings);
47
+ // OPTIONS
48
+ this.config.defaultRouteOptions = Object.assign(this.config.defaultRouteOptions, configUpdate.defaultRouteOptions);
49
+ return this.config;
50
+ };
51
+ this.updateChains = (chains) => {
52
+ var _a;
53
+ for (const chain of chains) {
54
+ const chainId = chain.id;
55
+ // set RPCs if they were not configured by the user before
56
+ if (!this.config.rpcs[chainId].length) {
57
+ this.config.rpcs[chainId] = chain.metamask.rpcUrls;
58
+ }
59
+ // set multicall addresses if they exist and were not configured by the user before
60
+ if (chain.multicallAddress && !this.config.multicallAddresses[chainId]) {
61
+ this.config.multicallAddresses[chainId] = chain.multicallAddress;
62
+ }
63
+ }
64
+ (_a = this.resolveSetupPromise) === null || _a === void 0 ? void 0 : _a.call(this);
65
+ return this.config;
66
+ };
67
+ this.config = ConfigService.getDefaultConfig();
68
+ this.setupPromise = new Promise((resolve) => {
69
+ this.resolveSetupPromise = resolve;
70
+ });
71
+ }
72
+ static chainIdToObject(val) {
73
+ const result = {};
74
+ const values = Object.values(types_1.ChainId);
75
+ values.forEach((chainId) => {
76
+ if (typeof chainId !== 'string') {
77
+ result[chainId] = val ? JSON.parse(JSON.stringify(val)) : val;
78
+ }
79
+ });
80
+ return result;
81
+ }
82
+ static getInstance() {
83
+ if (!this.instance) {
84
+ this.instance = new ConfigService();
85
+ }
86
+ return this.instance;
87
+ }
88
+ }
89
+ exports.default = ConfigService;
90
+ ConfigService.getDefaultConfig = () => {
91
+ return {
92
+ apiUrl: 'https://li.quest/v1/',
93
+ rpcs: ConfigService.chainIdToObject([]),
94
+ multicallAddresses: ConfigService.chainIdToObject(undefined),
95
+ defaultExecutionSettings: DefaultExecutionSettings,
96
+ defaultRouteOptions: {},
97
+ };
98
+ };
@@ -0,0 +1,4 @@
1
+ import { RoutesRequest, Step, Token } from './types';
2
+ export declare const isRoutesRequest: (routesRequest: RoutesRequest) => routesRequest is RoutesRequest;
3
+ export declare const isStep: (step: Step) => step is Step;
4
+ export declare const isToken: (token: Token) => token is Token;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isToken = exports.isStep = exports.isRoutesRequest = void 0;
4
+ const isRoutesRequest = (routesRequest) => {
5
+ const { fromChainId, fromAmount, fromTokenAddress, toChainId, toTokenAddress, options, } = routesRequest;
6
+ return (typeof fromChainId === 'number' &&
7
+ typeof fromAmount === 'string' &&
8
+ fromAmount !== '' &&
9
+ typeof fromTokenAddress === 'string' &&
10
+ fromTokenAddress !== '' &&
11
+ typeof toChainId === 'number' &&
12
+ typeof toTokenAddress === 'string' &&
13
+ toTokenAddress !== '' &&
14
+ (!options || isRoutesOptions(options)));
15
+ };
16
+ exports.isRoutesRequest = isRoutesRequest;
17
+ const isRoutesOptions = (routeOptions) => !(routeOptions === null || routeOptions === void 0 ? void 0 : routeOptions.slippage) || typeof routeOptions.slippage === 'number';
18
+ const isStep = (step) => {
19
+ const { id, type, tool, action, estimate } = step;
20
+ return (typeof id === 'string' &&
21
+ ['swap', 'cross', 'lifi'].includes(type) &&
22
+ typeof tool === 'string' &&
23
+ isAction(action) &&
24
+ isEstimate(estimate));
25
+ };
26
+ exports.isStep = isStep;
27
+ const isAction = (action) => {
28
+ const { fromChainId, fromAmount, fromToken, toChainId, toToken, slippage } = action;
29
+ return (typeof fromChainId === 'number' &&
30
+ typeof fromAmount === 'string' &&
31
+ fromAmount !== '' &&
32
+ (0, exports.isToken)(fromToken) &&
33
+ typeof toChainId === 'number' &&
34
+ (0, exports.isToken)(toToken) &&
35
+ typeof slippage === 'number');
36
+ };
37
+ const isEstimate = (estimate) => {
38
+ const { fromAmount, toAmount, toAmountMin, approvalAddress } = estimate;
39
+ return (typeof fromAmount === 'string' &&
40
+ fromAmount !== '' &&
41
+ typeof toAmount === 'string' &&
42
+ toAmount !== '' &&
43
+ typeof toAmountMin === 'string' &&
44
+ toAmountMin !== '' &&
45
+ typeof approvalAddress === 'string');
46
+ };
47
+ const isToken = (token) => {
48
+ const { address, decimals, chainId } = token;
49
+ return (typeof address === 'string' &&
50
+ typeof decimals === 'number' &&
51
+ typeof chainId === 'number');
52
+ };
53
+ exports.isToken = isToken;
@@ -0,0 +1,22 @@
1
+ import { BaseContract, BigNumber, BigNumberish, CallOverrides, ContractTransaction, Overrides } from 'ethers';
2
+ export declare const ERC20_ABI: {
3
+ name: string;
4
+ inputs: {
5
+ internalType: string;
6
+ name: string;
7
+ type: string;
8
+ }[];
9
+ outputs: {
10
+ internalType: string;
11
+ name: string;
12
+ type: string;
13
+ }[];
14
+ stateMutability: string;
15
+ type: string;
16
+ }[];
17
+ export interface ERC20Contract extends BaseContract {
18
+ allowance(owner: string, spender: string, overrides?: CallOverrides): Promise<BigNumber>;
19
+ approve(spender: string, amount: BigNumberish, overrides?: Overrides & {
20
+ from?: string | Promise<string>;
21
+ }): Promise<ContractTransaction>;
22
+ }
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ERC20_ABI = void 0;
4
+ exports.ERC20_ABI = [
5
+ {
6
+ name: 'approve',
7
+ inputs: [
8
+ {
9
+ internalType: 'address',
10
+ name: 'spender',
11
+ type: 'address',
12
+ },
13
+ {
14
+ internalType: 'uint256',
15
+ name: 'amount',
16
+ type: 'uint256',
17
+ },
18
+ ],
19
+ outputs: [
20
+ {
21
+ internalType: 'bool',
22
+ name: '',
23
+ type: 'bool',
24
+ },
25
+ ],
26
+ stateMutability: 'nonpayable',
27
+ type: 'function',
28
+ },
29
+ {
30
+ name: 'allowance',
31
+ inputs: [
32
+ {
33
+ internalType: 'address',
34
+ name: 'owner',
35
+ type: 'address',
36
+ },
37
+ {
38
+ internalType: 'address',
39
+ name: 'spender',
40
+ type: 'address',
41
+ },
42
+ ],
43
+ outputs: [
44
+ {
45
+ internalType: 'uint256',
46
+ name: '',
47
+ type: 'uint256',
48
+ },
49
+ ],
50
+ stateMutability: 'view',
51
+ type: 'function',
52
+ },
53
+ ];
@@ -0,0 +1,4 @@
1
+ export * from '@lifi/types';
2
+ export { ErrorCode, LifiError } from '../utils/errors';
3
+ export * from './ERC20';
4
+ export * from './internal.types';
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.LifiError = void 0;
18
+ __exportStar(require("@lifi/types"), exports);
19
+ var errors_1 = require("../utils/errors");
20
+ Object.defineProperty(exports, "LifiError", { enumerable: true, get: function () { return errors_1.LifiError; } });
21
+ __exportStar(require("./ERC20"), exports);
22
+ __exportStar(require("./internal.types"), exports);
@@ -0,0 +1,85 @@
1
+ import { Route, RouteOptions, Step, Token } from '@lifi/types';
2
+ import BigNumber from 'bignumber.js';
3
+ import { Signer } from 'ethers';
4
+ import { ChainId } from '.';
5
+ import { StatusManager } from '../execution/StatusManager';
6
+ import { StepExecutor } from '../execution/StepExecutor';
7
+ export interface TokenWithAmounts extends Token {
8
+ amount?: BigNumber;
9
+ amountRendered?: string;
10
+ }
11
+ export declare type ParsedReceipt = {
12
+ fromAmount?: string;
13
+ toAmount: string;
14
+ gasUsed: string;
15
+ gasPrice: string;
16
+ gasFee: string;
17
+ toTokenAddress?: string;
18
+ };
19
+ interface ExecutionParams {
20
+ signer: Signer;
21
+ step: Step;
22
+ statusManager: StatusManager;
23
+ settings: InternalExecutionSettings;
24
+ }
25
+ export interface ExecuteSwapParams extends ExecutionParams {
26
+ step: Step;
27
+ }
28
+ export interface ExecuteCrossParams extends ExecutionParams {
29
+ step: Step;
30
+ }
31
+ export declare type CallbackFunction = (updatedRoute: Route) => void;
32
+ export declare type Config = {
33
+ apiUrl: string;
34
+ rpcs: Record<ChainId, string[]>;
35
+ multicallAddresses: Record<ChainId, string | undefined>;
36
+ defaultExecutionSettings: InternalExecutionSettings;
37
+ defaultRouteOptions: RouteOptions;
38
+ };
39
+ export declare type ConfigUpdate = {
40
+ apiUrl?: string;
41
+ rpcs?: Record<number, string[]>;
42
+ multicallAddresses?: Record<number, string | undefined>;
43
+ defaultExecutionSettings?: ExecutionSettings;
44
+ defaultRouteOptions?: RouteOptions;
45
+ };
46
+ export declare type SwitchChainHook = (requiredChainId: number) => Promise<Signer | undefined>;
47
+ export interface AcceptSlippageUpdateHookParams {
48
+ toToken: Token;
49
+ oldToAmount: string;
50
+ newToAmount: string;
51
+ oldSlippage: number;
52
+ newSlippage: number;
53
+ }
54
+ export declare type AcceptSlippageUpdateHook = (params: AcceptSlippageUpdateHookParams) => Promise<boolean | undefined>;
55
+ export interface ExecutionData {
56
+ route: Route;
57
+ executors: StepExecutor[];
58
+ settings: InternalExecutionSettings;
59
+ }
60
+ export interface ExecutionSettings {
61
+ updateCallback?: CallbackFunction;
62
+ switchChainHook?: SwitchChainHook;
63
+ acceptSlippageUpdateHook?: AcceptSlippageUpdateHook;
64
+ infiniteApproval?: boolean;
65
+ }
66
+ export interface InternalExecutionSettings extends ExecutionSettings {
67
+ updateCallback: CallbackFunction;
68
+ switchChainHook: SwitchChainHook;
69
+ acceptSlippageUpdateHook: AcceptSlippageUpdateHook;
70
+ infiniteApproval: boolean;
71
+ }
72
+ export declare type EnforcedObjectProperties<T> = T & {
73
+ [P in keyof T]-?: T[P];
74
+ };
75
+ export interface ActiveRouteDictionary {
76
+ [k: string]: ExecutionData;
77
+ }
78
+ export declare type RevokeTokenData = {
79
+ token: Token;
80
+ approvalAddress: string;
81
+ };
82
+ export interface HaltingSettings {
83
+ allowUpdates?: boolean;
84
+ }
85
+ export {};
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,75 @@
1
+ declare enum ErrorType {
2
+ RPCError = "RPCError",
3
+ ProviderError = "ProviderError",
4
+ ServerError = "ServerError",
5
+ TransactionError = "TransactionError",
6
+ ValidationError = "ValidationError",
7
+ NotFoundError = "NotFoundError",
8
+ UnknownError = "UnknownError",
9
+ SlippageError = "SlippageError"
10
+ }
11
+ export declare enum LifiErrorCode {
12
+ InternalError = 1000,
13
+ ValidationError = 1001,
14
+ TransactionUnderpriced = 1002,
15
+ TransactionFailed = 1003,
16
+ TransactionUnprepared = 1008,
17
+ Timeout = 1004,
18
+ ProviderUnavailable = 1005,
19
+ NotFound = 1006,
20
+ ChainSwitchError = 1007,
21
+ SlippageNotMet = 1008,
22
+ SlippageError = 1008,
23
+ GasLimitError = 1009
24
+ }
25
+ export declare enum MetaMaskRPCErrorCode {
26
+ invalidInput = -32000,
27
+ resourceNotFound = -32001,
28
+ resourceUnavailable = -32002,
29
+ transactionRejected = -32003,
30
+ methodNotSupported = -32004,
31
+ limitExceeded = -32005,
32
+ parse = -32700,
33
+ invalidRequest = -32600,
34
+ methodNotFound = -32601,
35
+ invalidParams = -32602,
36
+ internal = -32603
37
+ }
38
+ export declare enum MetaMaskProviderErrorCode {
39
+ userRejectedRequest = 4001,
40
+ unauthorized = 4100,
41
+ unsupportedMethod = 4200,
42
+ disconnected = 4900,
43
+ chainDisconnected = 4901
44
+ }
45
+ export declare type ErrorCode = LifiErrorCode | MetaMaskRPCErrorCode | MetaMaskProviderErrorCode;
46
+ export declare class LifiError extends Error {
47
+ code: ErrorCode;
48
+ htmlMessage?: string;
49
+ constructor(type: ErrorType, code: number, message: string, htmlMessage?: string, stack?: string);
50
+ }
51
+ export declare class RPCError extends LifiError {
52
+ constructor(code: ErrorCode, message: string, htmlMessage?: string, stack?: string);
53
+ }
54
+ export declare class ProviderError extends LifiError {
55
+ constructor(code: ErrorCode, message: string, htmlMessage?: string, stack?: string);
56
+ }
57
+ export declare class ServerError extends LifiError {
58
+ constructor(message: string, htmlMessage?: string, stack?: string);
59
+ }
60
+ export declare class ValidationError extends LifiError {
61
+ constructor(message: string, htmlMessage?: string, stack?: string);
62
+ }
63
+ export declare class TransactionError extends LifiError {
64
+ constructor(code: ErrorCode, message: string, htmlMessage?: string, stack?: string);
65
+ }
66
+ export declare class SlippageError extends LifiError {
67
+ constructor(message: string, htmlMessage?: string, stack?: string);
68
+ }
69
+ export declare class NotFoundError extends LifiError {
70
+ constructor(message: string, htmlMessage?: string, stack?: string);
71
+ }
72
+ export declare class UnknownError extends LifiError {
73
+ constructor(code: ErrorCode, message: string, htmlMessage?: string, stack?: string);
74
+ }
75
+ export {};
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UnknownError = exports.NotFoundError = exports.SlippageError = exports.TransactionError = exports.ValidationError = exports.ServerError = exports.ProviderError = exports.RPCError = exports.LifiError = exports.MetaMaskProviderErrorCode = exports.MetaMaskRPCErrorCode = exports.LifiErrorCode = void 0;
4
+ var ErrorType;
5
+ (function (ErrorType) {
6
+ ErrorType["RPCError"] = "RPCError";
7
+ ErrorType["ProviderError"] = "ProviderError";
8
+ ErrorType["ServerError"] = "ServerError";
9
+ ErrorType["TransactionError"] = "TransactionError";
10
+ ErrorType["ValidationError"] = "ValidationError";
11
+ ErrorType["NotFoundError"] = "NotFoundError";
12
+ ErrorType["UnknownError"] = "UnknownError";
13
+ ErrorType["SlippageError"] = "SlippageError";
14
+ })(ErrorType || (ErrorType = {}));
15
+ var LifiErrorCode;
16
+ (function (LifiErrorCode) {
17
+ LifiErrorCode[LifiErrorCode["InternalError"] = 1000] = "InternalError";
18
+ LifiErrorCode[LifiErrorCode["ValidationError"] = 1001] = "ValidationError";
19
+ LifiErrorCode[LifiErrorCode["TransactionUnderpriced"] = 1002] = "TransactionUnderpriced";
20
+ LifiErrorCode[LifiErrorCode["TransactionFailed"] = 1003] = "TransactionFailed";
21
+ LifiErrorCode[LifiErrorCode["TransactionUnprepared"] = 1008] = "TransactionUnprepared";
22
+ LifiErrorCode[LifiErrorCode["Timeout"] = 1004] = "Timeout";
23
+ LifiErrorCode[LifiErrorCode["ProviderUnavailable"] = 1005] = "ProviderUnavailable";
24
+ LifiErrorCode[LifiErrorCode["NotFound"] = 1006] = "NotFound";
25
+ LifiErrorCode[LifiErrorCode["ChainSwitchError"] = 1007] = "ChainSwitchError";
26
+ LifiErrorCode[LifiErrorCode["SlippageNotMet"] = 1008] = "SlippageNotMet";
27
+ LifiErrorCode[LifiErrorCode["SlippageError"] = 1008] = "SlippageError";
28
+ LifiErrorCode[LifiErrorCode["GasLimitError"] = 1009] = "GasLimitError";
29
+ })(LifiErrorCode = exports.LifiErrorCode || (exports.LifiErrorCode = {}));
30
+ var MetaMaskRPCErrorCode;
31
+ (function (MetaMaskRPCErrorCode) {
32
+ MetaMaskRPCErrorCode[MetaMaskRPCErrorCode["invalidInput"] = -32000] = "invalidInput";
33
+ MetaMaskRPCErrorCode[MetaMaskRPCErrorCode["resourceNotFound"] = -32001] = "resourceNotFound";
34
+ MetaMaskRPCErrorCode[MetaMaskRPCErrorCode["resourceUnavailable"] = -32002] = "resourceUnavailable";
35
+ MetaMaskRPCErrorCode[MetaMaskRPCErrorCode["transactionRejected"] = -32003] = "transactionRejected";
36
+ MetaMaskRPCErrorCode[MetaMaskRPCErrorCode["methodNotSupported"] = -32004] = "methodNotSupported";
37
+ MetaMaskRPCErrorCode[MetaMaskRPCErrorCode["limitExceeded"] = -32005] = "limitExceeded";
38
+ MetaMaskRPCErrorCode[MetaMaskRPCErrorCode["parse"] = -32700] = "parse";
39
+ MetaMaskRPCErrorCode[MetaMaskRPCErrorCode["invalidRequest"] = -32600] = "invalidRequest";
40
+ MetaMaskRPCErrorCode[MetaMaskRPCErrorCode["methodNotFound"] = -32601] = "methodNotFound";
41
+ MetaMaskRPCErrorCode[MetaMaskRPCErrorCode["invalidParams"] = -32602] = "invalidParams";
42
+ MetaMaskRPCErrorCode[MetaMaskRPCErrorCode["internal"] = -32603] = "internal";
43
+ })(MetaMaskRPCErrorCode = exports.MetaMaskRPCErrorCode || (exports.MetaMaskRPCErrorCode = {}));
44
+ var MetaMaskProviderErrorCode;
45
+ (function (MetaMaskProviderErrorCode) {
46
+ MetaMaskProviderErrorCode[MetaMaskProviderErrorCode["userRejectedRequest"] = 4001] = "userRejectedRequest";
47
+ MetaMaskProviderErrorCode[MetaMaskProviderErrorCode["unauthorized"] = 4100] = "unauthorized";
48
+ MetaMaskProviderErrorCode[MetaMaskProviderErrorCode["unsupportedMethod"] = 4200] = "unsupportedMethod";
49
+ MetaMaskProviderErrorCode[MetaMaskProviderErrorCode["disconnected"] = 4900] = "disconnected";
50
+ MetaMaskProviderErrorCode[MetaMaskProviderErrorCode["chainDisconnected"] = 4901] = "chainDisconnected";
51
+ })(MetaMaskProviderErrorCode = exports.MetaMaskProviderErrorCode || (exports.MetaMaskProviderErrorCode = {}));
52
+ class LifiError extends Error {
53
+ constructor(type, code, message, htmlMessage, stack) {
54
+ super(message);
55
+ // Set the prototype explicitly: https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
56
+ Object.setPrototypeOf(this, LifiError.prototype);
57
+ this.code = code;
58
+ // the name property is used by toString(). It is a string and we can't use our custom ErrorTypes, that's why we have to cast
59
+ this.name = type.toString();
60
+ this.htmlMessage = htmlMessage;
61
+ // passing a stack allows us to preserve the stack from errors that we caught and just want to transform in one of our custom errors
62
+ if (stack) {
63
+ this.stack = stack;
64
+ }
65
+ }
66
+ }
67
+ exports.LifiError = LifiError;
68
+ class RPCError extends LifiError {
69
+ constructor(code, message, htmlMessage, stack) {
70
+ super(ErrorType.RPCError, code, message, htmlMessage, stack);
71
+ }
72
+ }
73
+ exports.RPCError = RPCError;
74
+ class ProviderError extends LifiError {
75
+ constructor(code, message, htmlMessage, stack) {
76
+ super(ErrorType.ProviderError, code, message, htmlMessage, stack);
77
+ }
78
+ }
79
+ exports.ProviderError = ProviderError;
80
+ class ServerError extends LifiError {
81
+ constructor(message, htmlMessage, stack) {
82
+ super(ErrorType.ServerError, LifiErrorCode.InternalError, message, htmlMessage, stack);
83
+ }
84
+ }
85
+ exports.ServerError = ServerError;
86
+ class ValidationError extends LifiError {
87
+ constructor(message, htmlMessage, stack) {
88
+ super(ErrorType.ValidationError, LifiErrorCode.ValidationError, message, htmlMessage, stack);
89
+ }
90
+ }
91
+ exports.ValidationError = ValidationError;
92
+ class TransactionError extends LifiError {
93
+ constructor(code, message, htmlMessage, stack) {
94
+ super(ErrorType.TransactionError, code, message, htmlMessage, stack);
95
+ }
96
+ }
97
+ exports.TransactionError = TransactionError;
98
+ class SlippageError extends LifiError {
99
+ constructor(message, htmlMessage, stack) {
100
+ super(ErrorType.SlippageError, LifiErrorCode.SlippageError, message, htmlMessage, stack);
101
+ }
102
+ }
103
+ exports.SlippageError = SlippageError;
104
+ class NotFoundError extends LifiError {
105
+ constructor(message, htmlMessage, stack) {
106
+ super(ErrorType.NotFoundError, LifiErrorCode.NotFound, message, htmlMessage, stack);
107
+ }
108
+ }
109
+ exports.NotFoundError = NotFoundError;
110
+ class UnknownError extends LifiError {
111
+ constructor(code, message, htmlMessage, stack) {
112
+ super(ErrorType.UnknownError, code, message, htmlMessage, stack);
113
+ }
114
+ }
115
+ exports.UnknownError = UnknownError;
@@ -0,0 +1,3 @@
1
+ import { Provider } from '@ethersproject/abstract-provider';
2
+ import { Signer } from 'ethers';
3
+ export declare const getProvider: (signer: Signer) => Provider;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getProvider = void 0;
4
+ const errors_1 = require("./errors");
5
+ const getProvider = (signer) => {
6
+ if (!signer.provider) {
7
+ throw new errors_1.ProviderError(errors_1.LifiErrorCode.ProviderUnavailable, 'No provider available in signer.');
8
+ }
9
+ return signer.provider;
10
+ };
11
+ exports.getProvider = getProvider;
@@ -0,0 +1,10 @@
1
+ import { Fragment, JsonFragment } from '@ethersproject/abi';
2
+ export declare type MultiCallData = {
3
+ address: string;
4
+ name: string;
5
+ params?: any[];
6
+ };
7
+ export declare const fetchDataUsingMulticall: (calls: Array<MultiCallData>, abi: ReadonlyArray<Fragment | JsonFragment | string>, chainId: number, multicallAddress: string, requireSuccess?: boolean) => Promise<{
8
+ data: unknown;
9
+ blockNumber: number;
10
+ }[]>;
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.fetchDataUsingMulticall = void 0;
16
+ const abi_1 = require("@ethersproject/abi");
17
+ const contracts_1 = require("@ethersproject/contracts");
18
+ const connectors_1 = require("../connectors");
19
+ const utils_1 = require("./utils");
20
+ const multicallAbi_json_1 = __importDefault(require("./multicallAbi.json"));
21
+ const MAX_MULTICALL_SIZE = 100;
22
+ const fetchDataUsingMulticall = (calls, abi, chainId, multicallAddress, requireSuccess = false) => __awaiter(void 0, void 0, void 0, function* () {
23
+ // 1. create contract using multicall contract address and abi...
24
+ const provider = yield (0, connectors_1.getRpcProvider)(chainId);
25
+ const multicallContract = new contracts_1.Contract(multicallAddress, multicallAbi_json_1.default, provider);
26
+ const abiInterface = new abi_1.Interface(abi);
27
+ // split up lists into chunks to stay below multicall limit
28
+ const chunkedList = (0, utils_1.splitListIntoChunks)(calls, MAX_MULTICALL_SIZE);
29
+ const chunkedResults = yield Promise.all(chunkedList.map((chunkedCalls) => __awaiter(void 0, void 0, void 0, function* () {
30
+ const callData = chunkedCalls.map((call) => [
31
+ call.address.toLowerCase(),
32
+ abiInterface.encodeFunctionData(call.name, call.params),
33
+ ]);
34
+ try {
35
+ // 3. get bytes array from multicall contract by process aggregate method...
36
+ const { blockNumber, returnData } = yield multicallContract.tryBlockAndAggregate(requireSuccess, callData);
37
+ // 4. decode bytes array to useful data array...
38
+ return returnData
39
+ .map(({ success, returnData }, i) => {
40
+ if (!success) {
41
+ // requested function failed
42
+ console.error(`Multicall unsuccessful for address "${chunkedCalls[i].address}", ` +
43
+ `function "${chunkedCalls[i].name}", chainId "${chainId}"`);
44
+ return [];
45
+ }
46
+ if (returnData.toString() === '0x') {
47
+ // requested function does probably not exist
48
+ console.error(`Multicall no response for address "${chunkedCalls[i].address}", ` +
49
+ `function "${chunkedCalls[i].name}", chainId "${chainId}"`);
50
+ return [];
51
+ }
52
+ try {
53
+ return abiInterface.decodeFunctionResult(chunkedCalls[i].name, returnData);
54
+ }
55
+ catch (e) {
56
+ // requested function returns other data than expected
57
+ console.error(`Multicall parsing unsuccessful for address "${chunkedCalls[i].address}", ` +
58
+ `function "${chunkedCalls[i].name}", chainId "${chainId}"`);
59
+ return [];
60
+ }
61
+ })
62
+ .map((data) => {
63
+ return {
64
+ data: data[0],
65
+ blockNumber: blockNumber.toNumber(),
66
+ };
67
+ });
68
+ }
69
+ catch (e) {
70
+ // whole rpc call failed, probably an rpc issue
71
+ console.error(`Multicall failed on chainId "${chainId}"`, chunkedList, e);
72
+ return [];
73
+ }
74
+ })));
75
+ return chunkedResults.flat();
76
+ });
77
+ exports.fetchDataUsingMulticall = fetchDataUsingMulticall;