@lifi/sdk 2.2.2 → 3.0.0-alpha.1

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 (183) hide show
  1. package/dist/LiFi.d.ts +69 -62
  2. package/dist/LiFi.js +71 -60
  3. package/dist/allowance/getAllowance.d.ts +6 -0
  4. package/dist/allowance/getAllowance.js +78 -0
  5. package/dist/allowance/index.d.ts +3 -2
  6. package/dist/allowance/index.js +3 -2
  7. package/dist/allowance/setAllowance.d.ts +5 -0
  8. package/dist/allowance/setAllowance.js +50 -0
  9. package/dist/allowance/types.d.ts +27 -0
  10. package/dist/allowance/types.js +1 -0
  11. package/dist/balance/getBalance.d.ts +2 -0
  12. package/dist/balance/getBalance.js +93 -0
  13. package/dist/balance/getTokenBalance.d.ts +2 -2
  14. package/dist/balance/getTokenBalance.js +4 -4
  15. package/dist/balance/index.d.ts +1 -12
  16. package/dist/balance/index.js +1 -9
  17. package/dist/cjs/LiFi.d.ts +69 -62
  18. package/dist/cjs/LiFi.js +69 -58
  19. package/dist/cjs/allowance/getAllowance.d.ts +6 -0
  20. package/dist/cjs/allowance/getAllowance.js +85 -0
  21. package/dist/cjs/allowance/index.d.ts +3 -2
  22. package/dist/cjs/allowance/index.js +3 -2
  23. package/dist/cjs/allowance/setAllowance.d.ts +5 -0
  24. package/dist/cjs/allowance/setAllowance.js +56 -0
  25. package/dist/cjs/allowance/types.d.ts +27 -0
  26. package/dist/cjs/allowance/types.js +2 -0
  27. package/dist/cjs/balance/getBalance.d.ts +2 -0
  28. package/dist/cjs/balance/getBalance.js +97 -0
  29. package/dist/cjs/balance/getTokenBalance.d.ts +2 -2
  30. package/dist/cjs/balance/getTokenBalance.js +6 -9
  31. package/dist/cjs/balance/index.d.ts +1 -12
  32. package/dist/cjs/balance/index.js +1 -9
  33. package/dist/cjs/connectors.d.ts +7 -5
  34. package/dist/cjs/connectors.js +45 -37
  35. package/dist/cjs/constants.d.ts +6 -0
  36. package/dist/cjs/constants.js +9 -0
  37. package/dist/cjs/execution/RouteExecutionManager.d.ts +24 -30
  38. package/dist/cjs/execution/RouteExecutionManager.js +27 -45
  39. package/dist/cjs/execution/StatusManager.d.ts +22 -23
  40. package/dist/cjs/execution/StatusManager.js +21 -22
  41. package/dist/cjs/execution/StepExecutionManager.d.ts +3 -3
  42. package/dist/cjs/execution/StepExecutionManager.js +118 -125
  43. package/dist/cjs/execution/StepExecutor.d.ts +4 -4
  44. package/dist/cjs/execution/StepExecutor.js +6 -6
  45. package/dist/cjs/execution/checkAllowance.d.ts +4 -0
  46. package/dist/cjs/execution/checkAllowance.js +77 -0
  47. package/dist/cjs/execution/checkBalance.d.ts +2 -0
  48. package/dist/cjs/execution/checkBalance.js +42 -0
  49. package/dist/cjs/execution/multisig.d.ts +4 -3
  50. package/dist/cjs/execution/multisig.js +9 -11
  51. package/dist/cjs/execution/prepareRestart.d.ts +3 -0
  52. package/dist/cjs/execution/prepareRestart.js +65 -0
  53. package/dist/cjs/execution/stepComparison.d.ts +3 -3
  54. package/dist/cjs/execution/stepComparison.js +2 -2
  55. package/dist/cjs/execution/switchChain.d.ts +13 -8
  56. package/dist/cjs/execution/switchChain.js +16 -11
  57. package/dist/cjs/execution/utils.d.ts +9 -3
  58. package/dist/cjs/execution/utils.js +19 -66
  59. package/dist/cjs/execution/waitForReceivingTransaction.d.ts +3 -0
  60. package/dist/cjs/execution/waitForReceivingTransaction.js +58 -0
  61. package/dist/cjs/helpers.d.ts +7 -17
  62. package/dist/cjs/helpers.js +6 -38
  63. package/dist/cjs/request.js +1 -1
  64. package/dist/cjs/services/ApiService.d.ts +2 -2
  65. package/dist/cjs/services/ApiService.js +2 -0
  66. package/dist/cjs/services/ChainsService.d.ts +1 -1
  67. package/dist/cjs/services/ConfigService.d.ts +1 -1
  68. package/dist/cjs/services/ConfigService.js +1 -2
  69. package/dist/cjs/typeguards.d.ts +1 -1
  70. package/dist/cjs/types/abi.d.ts +5 -0
  71. package/dist/cjs/types/abi.js +45 -0
  72. package/dist/cjs/types/index.d.ts +2 -2
  73. package/dist/cjs/types/index.js +3 -3
  74. package/dist/cjs/types/internal.types.d.ts +24 -30
  75. package/dist/cjs/utils/errors.d.ts +15 -14
  76. package/dist/cjs/utils/errors.js +38 -37
  77. package/dist/cjs/utils/getMaxPriorityFeePerGas.d.ts +2 -0
  78. package/dist/cjs/utils/getMaxPriorityFeePerGas.js +22 -0
  79. package/dist/cjs/utils/index.d.ts +5 -0
  80. package/dist/cjs/utils/index.js +21 -0
  81. package/dist/cjs/utils/median.d.ts +1 -0
  82. package/dist/cjs/utils/median.js +15 -0
  83. package/dist/cjs/utils/parseError.d.ts +4 -4
  84. package/dist/cjs/utils/parseError.js +41 -38
  85. package/dist/cjs/utils/utils.d.ts +1 -16
  86. package/dist/cjs/utils/utils.js +9 -78
  87. package/dist/cjs/version.d.ts +1 -1
  88. package/dist/cjs/version.js +1 -1
  89. package/dist/connectors.d.ts +7 -5
  90. package/dist/connectors.js +19 -35
  91. package/dist/constants.d.ts +6 -0
  92. package/dist/constants.js +6 -0
  93. package/dist/execution/RouteExecutionManager.d.ts +24 -30
  94. package/dist/execution/RouteExecutionManager.js +27 -45
  95. package/dist/execution/StatusManager.d.ts +22 -23
  96. package/dist/execution/StatusManager.js +22 -23
  97. package/dist/execution/StepExecutionManager.d.ts +3 -3
  98. package/dist/execution/StepExecutionManager.js +116 -123
  99. package/dist/execution/StepExecutor.d.ts +4 -4
  100. package/dist/execution/StepExecutor.js +6 -6
  101. package/dist/execution/checkAllowance.d.ts +4 -0
  102. package/dist/execution/checkAllowance.js +73 -0
  103. package/dist/execution/checkBalance.d.ts +2 -0
  104. package/dist/execution/checkBalance.js +38 -0
  105. package/dist/execution/multisig.d.ts +4 -3
  106. package/dist/execution/multisig.js +10 -12
  107. package/dist/execution/prepareRestart.d.ts +3 -0
  108. package/dist/execution/prepareRestart.js +61 -0
  109. package/dist/execution/stepComparison.d.ts +3 -3
  110. package/dist/execution/stepComparison.js +3 -3
  111. package/dist/execution/switchChain.d.ts +13 -8
  112. package/dist/execution/switchChain.js +17 -12
  113. package/dist/execution/utils.d.ts +9 -3
  114. package/dist/execution/utils.js +18 -61
  115. package/dist/execution/waitForReceivingTransaction.d.ts +3 -0
  116. package/dist/execution/waitForReceivingTransaction.js +51 -0
  117. package/dist/helpers.d.ts +7 -17
  118. package/dist/helpers.js +5 -34
  119. package/dist/request.js +2 -2
  120. package/dist/services/ApiService.d.ts +2 -2
  121. package/dist/services/ApiService.js +2 -0
  122. package/dist/services/ChainsService.d.ts +1 -1
  123. package/dist/services/ConfigService.d.ts +1 -1
  124. package/dist/services/ConfigService.js +2 -3
  125. package/dist/typeguards.d.ts +1 -1
  126. package/dist/types/abi.d.ts +5 -0
  127. package/dist/types/abi.js +42 -0
  128. package/dist/types/index.d.ts +2 -2
  129. package/dist/types/index.js +2 -2
  130. package/dist/types/internal.types.d.ts +24 -30
  131. package/dist/utils/errors.d.ts +15 -14
  132. package/dist/utils/errors.js +36 -35
  133. package/dist/utils/getMaxPriorityFeePerGas.d.ts +2 -0
  134. package/dist/utils/getMaxPriorityFeePerGas.js +18 -0
  135. package/dist/utils/index.d.ts +5 -0
  136. package/dist/utils/index.js +5 -0
  137. package/dist/utils/median.d.ts +1 -0
  138. package/dist/utils/median.js +11 -0
  139. package/dist/utils/parseError.d.ts +4 -4
  140. package/dist/utils/parseError.js +42 -39
  141. package/dist/utils/utils.d.ts +1 -16
  142. package/dist/utils/utils.js +7 -69
  143. package/dist/version.d.ts +1 -1
  144. package/dist/version.js +1 -1
  145. package/package.json +28 -27
  146. package/dist/allowance/checkAllowance.d.ts +0 -4
  147. package/dist/allowance/checkAllowance.js +0 -96
  148. package/dist/allowance/tokenApproval.d.ts +0 -22
  149. package/dist/allowance/tokenApproval.js +0 -59
  150. package/dist/allowance/utils.d.ts +0 -15
  151. package/dist/allowance/utils.js +0 -77
  152. package/dist/balance/checkBalance.d.ts +0 -3
  153. package/dist/balance/checkBalance.js +0 -38
  154. package/dist/balance/utils.d.ts +0 -6
  155. package/dist/balance/utils.js +0 -143
  156. package/dist/cjs/allowance/checkAllowance.d.ts +0 -4
  157. package/dist/cjs/allowance/checkAllowance.js +0 -103
  158. package/dist/cjs/allowance/tokenApproval.d.ts +0 -22
  159. package/dist/cjs/allowance/tokenApproval.js +0 -69
  160. package/dist/cjs/allowance/utils.d.ts +0 -15
  161. package/dist/cjs/allowance/utils.js +0 -87
  162. package/dist/cjs/balance/checkBalance.d.ts +0 -3
  163. package/dist/cjs/balance/checkBalance.js +0 -45
  164. package/dist/cjs/balance/utils.d.ts +0 -6
  165. package/dist/cjs/balance/utils.js +0 -150
  166. package/dist/cjs/types/ERC20.d.ts +0 -22
  167. package/dist/cjs/types/ERC20.js +0 -53
  168. package/dist/cjs/utils/getProvider.d.ts +0 -3
  169. package/dist/cjs/utils/getProvider.js +0 -11
  170. package/dist/cjs/utils/multicall.d.ts +0 -10
  171. package/dist/cjs/utils/multicall.js +0 -68
  172. package/dist/cjs/utils/multicallAbi.json +0 -313
  173. package/dist/cjs/utils/preRestart.d.ts +0 -3
  174. package/dist/cjs/utils/preRestart.js +0 -56
  175. package/dist/types/ERC20.d.ts +0 -22
  176. package/dist/types/ERC20.js +0 -50
  177. package/dist/utils/getProvider.d.ts +0 -3
  178. package/dist/utils/getProvider.js +0 -7
  179. package/dist/utils/multicall.d.ts +0 -10
  180. package/dist/utils/multicall.js +0 -61
  181. package/dist/utils/multicallAbi.json +0 -313
  182. package/dist/utils/preRestart.d.ts +0 -3
  183. package/dist/utils/preRestart.js +0 -52
@@ -1,103 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.checkAllowance = void 0;
7
- const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
- const ethers_1 = require("ethers");
9
- const utils_1 = require("../allowance/utils");
10
- const getProvider_1 = require("../utils/getProvider");
11
- const parseError_1 = require("../utils/parseError");
12
- const checkAllowance = async (signer, step, statusManager, settings, chain, allowUserInteraction = false, shouldBatchTransactions = false) => {
13
- // Ask the user to set an allowance
14
- let allowanceProcess = statusManager.findOrCreateProcess(step, 'TOKEN_ALLOWANCE');
15
- // Check allowance
16
- try {
17
- if (allowanceProcess.txHash && allowanceProcess.status !== 'DONE') {
18
- if (allowanceProcess.status !== 'PENDING') {
19
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'PENDING');
20
- }
21
- await (0, getProvider_1.getProvider)(signer).waitForTransaction(allowanceProcess.txHash);
22
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
23
- }
24
- else {
25
- const approvalRequest = {
26
- from: step.action.fromToken.address,
27
- to: step.estimate.approvalAddress,
28
- };
29
- if (settings.updateTransactionRequestHook) {
30
- const config = await settings.updateTransactionRequestHook(approvalRequest);
31
- approvalRequest.gasLimit = config.gasLimit;
32
- approvalRequest.gasPrice = config.gasPrice;
33
- approvalRequest.maxFeePerGas = config.maxFeePerGas;
34
- approvalRequest.maxPriorityFeePerGas = config.maxPriorityFeePerGas;
35
- }
36
- if (!approvalRequest.from) {
37
- throw new Error('Missing Signer address');
38
- }
39
- if (!approvalRequest.to) {
40
- throw new Error('Missing ERC20 contract address');
41
- }
42
- const approved = await (0, utils_1.getApproved)(signer, approvalRequest.from, approvalRequest.to, approvalRequest);
43
- if (new bignumber_js_1.default(step.action.fromAmount).gt(approved)) {
44
- if (!allowUserInteraction) {
45
- return;
46
- }
47
- const approvalAmount = settings.infiniteApproval
48
- ? ethers_1.constants.MaxUint256.toString()
49
- : step.action.fromAmount;
50
- if (shouldBatchTransactions) {
51
- const populatedTransaction = await (0, utils_1.setApproval)(signer, step.action.fromToken.address, step.estimate.approvalAddress, approvalAmount, true);
52
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
53
- return populatedTransaction;
54
- }
55
- const approveTx = (await (0, utils_1.setApproval)(signer, step.action.fromToken.address, step.estimate.approvalAddress, approvalAmount));
56
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'PENDING', {
57
- txHash: approveTx.hash,
58
- txLink: chain.metamask.blockExplorerUrls[0] + 'tx/' + approveTx.hash,
59
- });
60
- // Wait for the transcation
61
- await approveTx.wait();
62
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
63
- }
64
- else {
65
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
66
- }
67
- }
68
- }
69
- catch (e) {
70
- if (e.code === 'TRANSACTION_REPLACED' && e.replacement) {
71
- await transactionReplaced(e.replacement, allowanceProcess, step, chain, statusManager);
72
- }
73
- else {
74
- const error = await (0, parseError_1.parseError)(e, step, allowanceProcess);
75
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'FAILED', {
76
- error: {
77
- message: error.message,
78
- htmlMessage: error.htmlMessage,
79
- code: error.code,
80
- },
81
- });
82
- statusManager.updateExecution(step, 'FAILED');
83
- throw error;
84
- }
85
- }
86
- };
87
- exports.checkAllowance = checkAllowance;
88
- const transactionReplaced = async (replacementTx, allowanceProcess, step, chain, statusManager) => {
89
- try {
90
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'PENDING', {
91
- txHash: replacementTx.hash,
92
- txLink: chain.metamask.blockExplorerUrls[0] + 'tx/' + replacementTx.hash,
93
- });
94
- await replacementTx.wait();
95
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
96
- }
97
- catch (e) {
98
- if (e.code === 'TRANSACTION_REPLACED' && e.replacement) {
99
- await transactionReplaced(e.replacement, allowanceProcess, step, chain, statusManager);
100
- }
101
- throw e;
102
- }
103
- };
@@ -1,22 +0,0 @@
1
- import { Token } from '@lifi/types';
2
- import { Signer } from 'ethers';
3
- import { RevokeTokenData } from '../types';
4
- export interface ApproveTokenRequest {
5
- signer: Signer;
6
- token: Token;
7
- approvalAddress: string;
8
- amount: string;
9
- infiniteApproval?: boolean;
10
- }
11
- export interface RevokeApprovalRequest {
12
- signer: Signer;
13
- token: Token;
14
- approvalAddress: string;
15
- }
16
- export declare const getTokenApproval: (signer: Signer, token: Token, approvalAddress: string) => Promise<string | undefined>;
17
- export declare const bulkGetTokenApproval: (signer: Signer, tokenData: RevokeTokenData[]) => Promise<{
18
- token: Token;
19
- approval: string | undefined;
20
- }[]>;
21
- export declare const approveToken: ({ signer, token, approvalAddress, amount, infiniteApproval, }: ApproveTokenRequest) => Promise<void>;
22
- export declare const revokeTokenApproval: ({ signer, token, approvalAddress, }: RevokeApprovalRequest) => Promise<void>;
@@ -1,69 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.revokeTokenApproval = exports.approveToken = exports.bulkGetTokenApproval = exports.getTokenApproval = void 0;
7
- const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
- const ethers_1 = require("ethers");
9
- const helpers_1 = require("../helpers");
10
- const utils_1 = require("../utils/utils");
11
- const utils_2 = require("./utils");
12
- const getTokenApproval = async (signer, token, approvalAddress) => {
13
- // native token don't need approval
14
- if ((0, utils_1.isNativeTokenAddress)(token.address)) {
15
- return;
16
- }
17
- const approved = await (0, utils_2.getApproved)(signer, token.address, approvalAddress);
18
- return approved.toFixed(0);
19
- };
20
- exports.getTokenApproval = getTokenApproval;
21
- const bulkGetTokenApproval = async (signer, tokenData) => {
22
- // filter out native tokens
23
- const filteredTokenData = tokenData.filter(({ token }) => !(0, utils_1.isNativeTokenAddress)(token.address));
24
- // group by chain
25
- const tokenDataByChain = (0, utils_2.groupByChain)(filteredTokenData);
26
- const approvalPromises = Object.keys(tokenDataByChain).map(async (chainId) => {
27
- const parsedChainId = Number.parseInt(chainId);
28
- // get allowances for current chain and token list
29
- return (0, utils_2.getAllowanceViaMulticall)(signer, parsedChainId, tokenDataByChain[parsedChainId]);
30
- });
31
- const approvalsByChain = await Promise.all(approvalPromises);
32
- const approvals = approvalsByChain.flat();
33
- return tokenData.map(({ token }) => {
34
- // native token don't need approval
35
- if ((0, utils_1.isNativeTokenAddress)(token.address)) {
36
- return { token, approval: undefined };
37
- }
38
- const approved = approvals.find((approval) => (0, helpers_1.isSameToken)(approval.token, token));
39
- return { token, approval: approved?.approvedAmount.toString() };
40
- });
41
- };
42
- exports.bulkGetTokenApproval = bulkGetTokenApproval;
43
- const approveToken = async ({ signer, token, approvalAddress, amount, infiniteApproval = false, }) => {
44
- // native token don't need approval
45
- if ((0, utils_1.isNativeTokenAddress)(token.address)) {
46
- return;
47
- }
48
- const approvedAmount = await (0, utils_2.getApproved)(signer, token.address, approvalAddress);
49
- if (new bignumber_js_1.default(amount).gt(approvedAmount)) {
50
- const approvalAmount = infiniteApproval
51
- ? ethers_1.constants.MaxUint256.toString()
52
- : amount;
53
- const approveTx = await (0, utils_2.setApproval)(signer, token.address, approvalAddress, approvalAmount);
54
- await approveTx.wait();
55
- }
56
- };
57
- exports.approveToken = approveToken;
58
- const revokeTokenApproval = async ({ signer, token, approvalAddress, }) => {
59
- // native token don't need approval
60
- if ((0, utils_1.isNativeTokenAddress)(token.address)) {
61
- return;
62
- }
63
- const approvedAmount = await (0, utils_2.getApproved)(signer, token.address, approvalAddress);
64
- if (!approvedAmount.isZero()) {
65
- const approveTx = await (0, utils_2.setApproval)(signer, token.address, approvalAddress, '0');
66
- await approveTx.wait();
67
- }
68
- };
69
- exports.revokeTokenApproval = revokeTokenApproval;
@@ -1,15 +0,0 @@
1
- import { TransactionRequest } from '@ethersproject/abstract-provider';
2
- import { ChainId, Token } from '@lifi/types';
3
- import BigNumber from 'bignumber.js';
4
- import { ContractTransaction, PopulatedTransaction, Signer } from 'ethers';
5
- import { RevokeTokenData } from '../types';
6
- export declare const getApproved: (signer: Signer, tokenAddress: string, contractAddress: string, transactionRequest?: TransactionRequest) => Promise<BigNumber>;
7
- export declare const setApproval: (signer: Signer, tokenAddress: string, contractAddress: string, amount: string, returnPopulatedTransaction?: boolean) => Promise<ContractTransaction | PopulatedTransaction>;
8
- export declare const getAllowanceViaMulticall: (signer: Signer, chainId: ChainId, tokenData: RevokeTokenData[]) => Promise<{
9
- token: Token;
10
- approvalAddress: string;
11
- approvedAmount: BigNumber;
12
- }[]>;
13
- export declare const groupByChain: (tokenDataList: RevokeTokenData[]) => {
14
- [chainId: number]: RevokeTokenData[];
15
- };
@@ -1,87 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.groupByChain = exports.getAllowanceViaMulticall = exports.setApproval = exports.getApproved = void 0;
7
- const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
- const ethers_1 = require("ethers");
9
- const ChainsService_1 = __importDefault(require("../services/ChainsService"));
10
- const types_1 = require("../types");
11
- const errors_1 = require("../utils/errors");
12
- const multicall_1 = require("../utils/multicall");
13
- const getApproved = async (signer, tokenAddress, contractAddress, transactionRequest) => {
14
- const signerAddress = await signer.getAddress();
15
- const erc20 = new ethers_1.Contract(tokenAddress, types_1.ERC20_ABI, signer);
16
- try {
17
- const approved = await erc20.allowance(signerAddress, contractAddress, {
18
- gasLimit: transactionRequest?.gasLimit,
19
- gasPrice: transactionRequest?.gasPrice,
20
- maxFeePerGas: transactionRequest?.maxFeePerGas,
21
- maxPriorityFeePerGas: transactionRequest?.maxPriorityFeePerGas,
22
- });
23
- return new bignumber_js_1.default(approved.toString());
24
- }
25
- catch (e) {
26
- return new bignumber_js_1.default(0);
27
- }
28
- };
29
- exports.getApproved = getApproved;
30
- const setApproval = async (signer, tokenAddress, contractAddress, amount, returnPopulatedTransaction) => {
31
- const erc20 = new ethers_1.Contract(tokenAddress, types_1.ERC20_ABI, signer);
32
- if (returnPopulatedTransaction) {
33
- return erc20.populateTransaction.approve(contractAddress, amount);
34
- }
35
- const transactionRequest = await erc20.populateTransaction.approve(contractAddress, amount);
36
- try {
37
- const estimatedGasLimit = await signer.estimateGas(transactionRequest);
38
- if (estimatedGasLimit) {
39
- const formattedGasLimit = ethers_1.ethers.BigNumber.from(`${(BigInt(estimatedGasLimit.toString()) * 125n) / 100n}`);
40
- transactionRequest.gasLimit = formattedGasLimit;
41
- }
42
- }
43
- catch (error) { }
44
- return signer.sendTransaction(transactionRequest);
45
- };
46
- exports.setApproval = setApproval;
47
- const getAllowanceViaMulticall = async (signer, chainId, tokenData) => {
48
- const chainsService = ChainsService_1.default.getInstance();
49
- const chain = await chainsService.getChainById(chainId);
50
- if (!chain.multicallAddress) {
51
- throw new errors_1.ServerError(`No multicall address configured for chainId ${chainId}.`);
52
- }
53
- const ownerAddress = await signer.getAddress();
54
- const calls = [];
55
- tokenData.map(({ token, approvalAddress }) => {
56
- calls.push({
57
- address: token.address,
58
- name: 'allowance',
59
- params: [ownerAddress, approvalAddress],
60
- });
61
- });
62
- const result = await (0, multicall_1.fetchDataUsingMulticall)(calls, types_1.ERC20_ABI, chainId, chain.multicallAddress);
63
- if (!result.length) {
64
- throw new errors_1.ServerError(`Couldn't load allowance from chainId ${chainId} using multicall.`);
65
- }
66
- const parsedResult = result.map(({ data }) => ({
67
- approvalAmount: data ?? new bignumber_js_1.default(0),
68
- }));
69
- return tokenData.map(({ token, approvalAddress }, i) => ({
70
- token,
71
- approvalAddress,
72
- approvedAmount: parsedResult[i].approvalAmount,
73
- }));
74
- };
75
- exports.getAllowanceViaMulticall = getAllowanceViaMulticall;
76
- const groupByChain = (tokenDataList) => {
77
- // group by chain
78
- const tokenDataByChain = {};
79
- tokenDataList.forEach((tokenData) => {
80
- if (!tokenDataByChain[tokenData.token.chainId]) {
81
- tokenDataByChain[tokenData.token.chainId] = [];
82
- }
83
- tokenDataByChain[tokenData.token.chainId].push(tokenData);
84
- });
85
- return tokenDataByChain;
86
- };
87
- exports.groupByChain = groupByChain;
@@ -1,3 +0,0 @@
1
- import { ethers } from 'ethers';
2
- import { LifiStep } from '..';
3
- export declare const checkBalance: (signer: ethers.Signer, step: LifiStep, depth?: number) => Promise<void>;
@@ -1,45 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.checkBalance = void 0;
7
- const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
- const errors_1 = require("../utils/errors");
9
- const getTokenBalance_1 = require("./getTokenBalance");
10
- const checkBalance = async (signer, step, depth = 0) => {
11
- const tokenAmount = await (0, getTokenBalance_1.getTokenBalance)(await signer.getAddress(), step.action.fromToken);
12
- if (tokenAmount) {
13
- const currentBalance = new bignumber_js_1.default(tokenAmount.amount).shiftedBy(tokenAmount.decimals);
14
- const neededBalance = new bignumber_js_1.default(step.action.fromAmount);
15
- if (currentBalance.lt(neededBalance)) {
16
- if (depth <= 3) {
17
- await new Promise((resolve) => {
18
- setTimeout(resolve, 200);
19
- });
20
- await (0, exports.checkBalance)(signer, step, depth + 1);
21
- }
22
- else if (neededBalance.multipliedBy(1 - step.action.slippage).lte(currentBalance)) {
23
- // adjust amount in slippage limits
24
- step.action.fromAmount = currentBalance.toFixed(0);
25
- }
26
- else {
27
- const neeeded = neededBalance.shiftedBy(-tokenAmount.decimals).toFixed();
28
- const current = currentBalance
29
- .shiftedBy(-tokenAmount.decimals)
30
- .toFixed();
31
- let errorMessage = `Your ${tokenAmount.symbol} balance is too low, ` +
32
- `you try to transfer ${neeeded} ${tokenAmount.symbol}, ` +
33
- `but your wallet only holds ${current} ${tokenAmount.symbol}. ` +
34
- `No funds have been sent. `;
35
- if (!currentBalance.isZero()) {
36
- errorMessage +=
37
- `If the problem consists, please delete this transfer and ` +
38
- `start a new one with a maximum of ${current} ${tokenAmount.symbol}.`;
39
- }
40
- throw new errors_1.BalanceError('The balance is too low.', errorMessage);
41
- }
42
- }
43
- }
44
- };
45
- exports.checkBalance = checkBalance;
@@ -1,6 +0,0 @@
1
- import { Token, TokenAmount } from '@lifi/types';
2
- export declare const getBalances: (walletAddress: string, tokens: Token[]) => Promise<TokenAmount[]>;
3
- declare const _default: {
4
- getBalances: (walletAddress: string, tokens: Token[]) => Promise<TokenAmount[]>;
5
- };
6
- export default _default;
@@ -1,150 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getBalances = void 0;
7
- const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
- const ethers_1 = require("ethers");
9
- const connectors_1 = require("../connectors");
10
- const multicall_1 = require("../utils/multicall");
11
- const utils_1 = require("../utils/utils");
12
- const balanceAbi = [
13
- {
14
- constant: true,
15
- inputs: [{ name: 'who', type: 'address' }],
16
- name: 'balanceOf',
17
- outputs: [{ name: '', type: 'uint256' }],
18
- payable: false,
19
- stateMutability: 'view',
20
- type: 'function',
21
- },
22
- {
23
- constant: true,
24
- inputs: [{ name: 'addr', type: 'address' }],
25
- name: 'getEthBalance',
26
- outputs: [{ name: 'balance', type: 'uint256' }],
27
- payable: false,
28
- stateMutability: 'view',
29
- type: 'function',
30
- },
31
- ];
32
- const getBalances = async (walletAddress, tokens) => {
33
- if (tokens.length === 0) {
34
- return [];
35
- }
36
- const { chainId } = tokens[0];
37
- tokens.forEach((token) => {
38
- if (token.chainId !== chainId) {
39
- // eslint-disable-next-line no-console
40
- console.warn(`Requested tokens have to be on the same chain.`);
41
- return [];
42
- }
43
- });
44
- if ((await (0, connectors_1.getMulticallAddress)(chainId)) && tokens.length > 1) {
45
- return getBalancesFromProviderUsingMulticall(walletAddress, tokens);
46
- }
47
- else {
48
- return getBalancesFromProvider(walletAddress, tokens);
49
- }
50
- };
51
- exports.getBalances = getBalances;
52
- const getBalancesFromProviderUsingMulticall = async (walletAddress, tokens) => {
53
- // Configuration
54
- const { chainId } = tokens[0];
55
- const multicallAddress = await (0, connectors_1.getMulticallAddress)(chainId);
56
- if (!multicallAddress) {
57
- throw new Error('No multicallAddress found for the given chain.');
58
- }
59
- return executeMulticall(walletAddress, tokens, multicallAddress, chainId);
60
- };
61
- const executeMulticall = async (walletAddress, tokens, multicallAddress, chainId) => {
62
- // Collect calls we want to make
63
- const calls = [];
64
- tokens.map((token) => {
65
- if ((0, utils_1.isZeroAddress)(token.address)) {
66
- calls.push({
67
- address: multicallAddress,
68
- name: 'getEthBalance',
69
- params: [walletAddress],
70
- });
71
- }
72
- else {
73
- calls.push({
74
- address: token.address,
75
- name: 'balanceOf',
76
- params: [walletAddress],
77
- });
78
- }
79
- });
80
- const res = await fetchViaMulticall(calls, balanceAbi, chainId, multicallAddress);
81
- if (!res.length) {
82
- return [];
83
- }
84
- return tokens.map((token, i) => {
85
- const amount = new bignumber_js_1.default(res[i].amount.toString() || '0')
86
- .shiftedBy(-token.decimals)
87
- .toFixed();
88
- return {
89
- ...token,
90
- amount: amount || '0',
91
- blockNumber: res[i].blockNumber,
92
- };
93
- });
94
- };
95
- const fetchViaMulticall = async (calls, abi, chainId, multicallAddress) => {
96
- const result = await (0, multicall_1.fetchDataUsingMulticall)(calls, abi, chainId, multicallAddress);
97
- return result.map(({ data, blockNumber }) => ({
98
- amount: data ? data : new bignumber_js_1.default(0),
99
- blockNumber,
100
- }));
101
- };
102
- const getBalancesFromProvider = async (walletAddress, tokens) => {
103
- const chainId = tokens[0].chainId;
104
- const rpc = await (0, connectors_1.getRpcProvider)(chainId);
105
- const tokenAmountPromises = tokens.map(async (token) => {
106
- let amount = '0';
107
- let blockNumber;
108
- try {
109
- const balance = await getBalanceFromProvider(walletAddress, token.address, chainId, rpc);
110
- amount = new bignumber_js_1.default(balance.amount.toString())
111
- .shiftedBy(-token.decimals)
112
- .toString();
113
- blockNumber = balance.blockNumber;
114
- }
115
- catch (e) {
116
- // eslint-disable-next-line no-console
117
- console.warn(e);
118
- }
119
- return {
120
- ...token,
121
- amount,
122
- blockNumber,
123
- };
124
- });
125
- return Promise.all(tokenAmountPromises);
126
- };
127
- const getBalanceFromProvider = async (walletAddress, assetId, chainId, provider) => {
128
- const blockNumber = await getCurrentBlockNumber(chainId);
129
- let balance;
130
- if ((0, utils_1.isZeroAddress)(assetId)) {
131
- balance = await provider.getBalance(walletAddress, blockNumber);
132
- }
133
- else {
134
- const contract = new ethers_1.ethers.Contract(assetId, ['function balanceOf(address owner) view returns (uint256)'], provider);
135
- balance = await contract.balanceOf(walletAddress, {
136
- blockTag: blockNumber,
137
- });
138
- }
139
- return {
140
- amount: balance,
141
- blockNumber,
142
- };
143
- };
144
- const getCurrentBlockNumber = async (chainId) => {
145
- const rpc = await (0, connectors_1.getRpcProvider)(chainId);
146
- return rpc.getBlockNumber();
147
- };
148
- exports.default = {
149
- getBalances: exports.getBalances,
150
- };
@@ -1,22 +0,0 @@
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
- }
@@ -1,53 +0,0 @@
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
- ];
@@ -1,3 +0,0 @@
1
- import { Provider } from '@ethersproject/abstract-provider';
2
- import { Signer } from 'ethers';
3
- export declare const getProvider: (signer: Signer) => Provider;
@@ -1,11 +0,0 @@
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;
@@ -1,10 +0,0 @@
1
- import { Fragment, JsonFragment } from '@ethersproject/abi';
2
- export 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
- }[]>;