@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
package/package.json CHANGED
@@ -1,33 +1,35 @@
1
1
  {
2
2
  "name": "@lifi/sdk",
3
- "version": "2.2.2",
3
+ "version": "3.0.0-alpha.1",
4
4
  "description": "LI.FI Any-to-Any Cross-Chain-Swap SDK",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "module": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
8
8
  "scripts": {
9
- "watch": "tsc -w -p ./tsconfig.json",
9
+ "addscope": "node tools/packagejson name @lifi/sdk",
10
10
  "build": "yarn clean && tsc --project ./tsconfig.json && tsc --project ./tsconfig.cjs.json",
11
11
  "clean": "node tools/cleanup",
12
+ "coverage": "vitest run --coverage",
13
+ "lint": "eslint --ext .tsx --ext .ts ./src",
14
+ "lint:fix": "eslint --ext .tsx --ext .ts ./src --fix",
12
15
  "package": "npm run build && npm pack",
16
+ "postpublish": "npm run use:gitReadme && pinst --enable",
17
+ "pre-commit": "lint-staged",
18
+ "pre-push": "yarn types:check && yarn build && yarn test:unit",
19
+ "prepare": "husky install",
20
+ "prepublishOnly": "run-s build use:npmReadme && pinst --enable",
21
+ "prettier:fix": "prettier --write ./src/.",
22
+ "release": "standard-version -a",
23
+ "release:alpha": "standard-version -a --prerelease alpha --skip.changelog",
24
+ "release:beta": "standard-version -a --prerelease beta --skip.changelog",
13
25
  "test": "vitest --run --dangerouslyIgnoreUnhandledErrors",
14
- "test:unit": "yarn test .unit.spec.ts",
15
26
  "test:cov": "yarn test --coverage",
16
27
  "test:e2e": "yarn test -c vitest.e2e.config.ts",
17
- "addscope": "node tools/packagejson name @lifi/sdk",
18
- "pre-commit": "lint-staged",
19
- "pre-push": "yarn types:check && yarn build && yarn test:unit",
20
- "lint": "eslint --ext .tsx --ext .ts ./src",
21
- "lint:fix": "eslint --ext .tsx --ext .ts ./src --fix",
28
+ "test:unit": "yarn test .unit.spec.ts",
22
29
  "types:check": "tsc --noEmit",
23
- "prettier:fix": "prettier --write ./src/.",
24
- "use:npmReadme": "mv 'README.md' 'git.README.md' && mv 'npm.README.md' 'README.md'",
25
30
  "use:gitReadme": "mv 'README.md' 'npm.README.md' && mv 'git.README.md' 'README.md'",
26
- "prepublishOnly": "run-s build use:npmReadme && pinst --enable",
27
- "postpublish": "npm run use:gitReadme && pinst --enable",
28
- "prepare": "husky install",
29
- "release": "standard-version -a",
30
- "release:beta": "standard-version -a --prerelease beta --skip.changelog"
31
+ "use:npmReadme": "mv 'README.md' 'git.README.md' && mv 'npm.README.md' 'README.md'",
32
+ "watch": "tsc -w -p ./tsconfig.json"
31
33
  },
32
34
  "standard-version": {
33
35
  "scripts": {
@@ -75,33 +77,32 @@
75
77
  "url": "https://github.com/lifinance/sdk/issues"
76
78
  },
77
79
  "dependencies": {
78
- "@ethersproject/abi": "^5.7.0",
79
- "@ethersproject/contracts": "^5.7.0",
80
- "@lifi/types": "^8.0.4",
81
- "bignumber.js": "^9.1.1",
80
+ "@lifi/types": "^9.0.0-alpha.0",
82
81
  "eth-rpc-errors": "^4.0.3",
83
- "ethers": "^5.7.2"
82
+ "viem": "^1.5.2"
84
83
  },
85
84
  "devDependencies": {
86
85
  "@commitlint/cli": "^17.6.7",
87
86
  "@commitlint/config-conventional": "^17.6.7",
88
87
  "@mswjs/interceptors": "^0.22.16",
89
- "@typescript-eslint/eslint-plugin": "^6.1.0",
90
- "@typescript-eslint/parser": "^6.1.0",
91
- "@vitest/coverage-c8": "^0.33.0",
88
+ "@types/ws": "^8.5.5",
89
+ "@typescript-eslint/eslint-plugin": "^6.2.1",
90
+ "@typescript-eslint/parser": "^6.2.1",
91
+ "@vitest/coverage-v8": "^0.34.1",
92
92
  "cross-fetch": "^4.0.0",
93
- "eslint": "^8.45.0",
94
- "eslint-config-prettier": "^8.8.0",
93
+ "eslint": "^8.46.0",
94
+ "eslint-config-prettier": "^8.10.0",
95
+ "eslint-plugin-jsdoc": "^46.4.5",
95
96
  "eslint-plugin-prettier": "^5.0.0",
96
97
  "husky": "^8.0.3",
97
98
  "lint-staged": "^13.2.3",
98
99
  "msw": "1.0.1",
99
100
  "npm-run-all": "^4.1.5",
100
101
  "pinst": "^3.0.0",
101
- "prettier": "^3.0.0",
102
+ "prettier": "^3.0.1",
102
103
  "standard-version": "^9.5.0",
103
104
  "typescript": "^5.1.6",
104
- "vitest": "^0.33.0"
105
+ "vitest": "^0.34.1"
105
106
  },
106
107
  "directories": {
107
108
  "test": "test"
@@ -1,4 +0,0 @@
1
- import { PopulatedTransaction, Signer } from 'ethers';
2
- import { StatusManager } from '../execution/StatusManager';
3
- import { Chain, InternalExecutionSettings, LifiStep } from '../types';
4
- export declare const checkAllowance: (signer: Signer, step: LifiStep, statusManager: StatusManager, settings: InternalExecutionSettings, chain: Chain, allowUserInteraction?: boolean, shouldBatchTransactions?: boolean) => Promise<void | PopulatedTransaction>;
@@ -1,96 +0,0 @@
1
- import BigNumber from 'bignumber.js';
2
- import { constants, } from 'ethers';
3
- import { getApproved, setApproval } from '../allowance/utils';
4
- import { getProvider } from '../utils/getProvider';
5
- import { parseError } from '../utils/parseError';
6
- export const checkAllowance = async (signer, step, statusManager, settings, chain, allowUserInteraction = false, shouldBatchTransactions = false) => {
7
- // Ask the user to set an allowance
8
- let allowanceProcess = statusManager.findOrCreateProcess(step, 'TOKEN_ALLOWANCE');
9
- // Check allowance
10
- try {
11
- if (allowanceProcess.txHash && allowanceProcess.status !== 'DONE') {
12
- if (allowanceProcess.status !== 'PENDING') {
13
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'PENDING');
14
- }
15
- await getProvider(signer).waitForTransaction(allowanceProcess.txHash);
16
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
17
- }
18
- else {
19
- const approvalRequest = {
20
- from: step.action.fromToken.address,
21
- to: step.estimate.approvalAddress,
22
- };
23
- if (settings.updateTransactionRequestHook) {
24
- const config = await settings.updateTransactionRequestHook(approvalRequest);
25
- approvalRequest.gasLimit = config.gasLimit;
26
- approvalRequest.gasPrice = config.gasPrice;
27
- approvalRequest.maxFeePerGas = config.maxFeePerGas;
28
- approvalRequest.maxPriorityFeePerGas = config.maxPriorityFeePerGas;
29
- }
30
- if (!approvalRequest.from) {
31
- throw new Error('Missing Signer address');
32
- }
33
- if (!approvalRequest.to) {
34
- throw new Error('Missing ERC20 contract address');
35
- }
36
- const approved = await getApproved(signer, approvalRequest.from, approvalRequest.to, approvalRequest);
37
- if (new BigNumber(step.action.fromAmount).gt(approved)) {
38
- if (!allowUserInteraction) {
39
- return;
40
- }
41
- const approvalAmount = settings.infiniteApproval
42
- ? constants.MaxUint256.toString()
43
- : step.action.fromAmount;
44
- if (shouldBatchTransactions) {
45
- const populatedTransaction = await setApproval(signer, step.action.fromToken.address, step.estimate.approvalAddress, approvalAmount, true);
46
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
47
- return populatedTransaction;
48
- }
49
- const approveTx = (await setApproval(signer, step.action.fromToken.address, step.estimate.approvalAddress, approvalAmount));
50
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'PENDING', {
51
- txHash: approveTx.hash,
52
- txLink: chain.metamask.blockExplorerUrls[0] + 'tx/' + approveTx.hash,
53
- });
54
- // Wait for the transcation
55
- await approveTx.wait();
56
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
57
- }
58
- else {
59
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
60
- }
61
- }
62
- }
63
- catch (e) {
64
- if (e.code === 'TRANSACTION_REPLACED' && e.replacement) {
65
- await transactionReplaced(e.replacement, allowanceProcess, step, chain, statusManager);
66
- }
67
- else {
68
- const error = await parseError(e, step, allowanceProcess);
69
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'FAILED', {
70
- error: {
71
- message: error.message,
72
- htmlMessage: error.htmlMessage,
73
- code: error.code,
74
- },
75
- });
76
- statusManager.updateExecution(step, 'FAILED');
77
- throw error;
78
- }
79
- }
80
- };
81
- const transactionReplaced = async (replacementTx, allowanceProcess, step, chain, statusManager) => {
82
- try {
83
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'PENDING', {
84
- txHash: replacementTx.hash,
85
- txLink: chain.metamask.blockExplorerUrls[0] + 'tx/' + replacementTx.hash,
86
- });
87
- await replacementTx.wait();
88
- allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
89
- }
90
- catch (e) {
91
- if (e.code === 'TRANSACTION_REPLACED' && e.replacement) {
92
- await transactionReplaced(e.replacement, allowanceProcess, step, chain, statusManager);
93
- }
94
- throw e;
95
- }
96
- };
@@ -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,59 +0,0 @@
1
- import BigNumber from 'bignumber.js';
2
- import { constants } from 'ethers';
3
- import { isSameToken } from '../helpers';
4
- import { isNativeTokenAddress } from '../utils/utils';
5
- import { getAllowanceViaMulticall, getApproved, groupByChain, setApproval, } from './utils';
6
- export const getTokenApproval = async (signer, token, approvalAddress) => {
7
- // native token don't need approval
8
- if (isNativeTokenAddress(token.address)) {
9
- return;
10
- }
11
- const approved = await getApproved(signer, token.address, approvalAddress);
12
- return approved.toFixed(0);
13
- };
14
- export const bulkGetTokenApproval = async (signer, tokenData) => {
15
- // filter out native tokens
16
- const filteredTokenData = tokenData.filter(({ token }) => !isNativeTokenAddress(token.address));
17
- // group by chain
18
- const tokenDataByChain = groupByChain(filteredTokenData);
19
- const approvalPromises = Object.keys(tokenDataByChain).map(async (chainId) => {
20
- const parsedChainId = Number.parseInt(chainId);
21
- // get allowances for current chain and token list
22
- return getAllowanceViaMulticall(signer, parsedChainId, tokenDataByChain[parsedChainId]);
23
- });
24
- const approvalsByChain = await Promise.all(approvalPromises);
25
- const approvals = approvalsByChain.flat();
26
- return tokenData.map(({ token }) => {
27
- // native token don't need approval
28
- if (isNativeTokenAddress(token.address)) {
29
- return { token, approval: undefined };
30
- }
31
- const approved = approvals.find((approval) => isSameToken(approval.token, token));
32
- return { token, approval: approved?.approvedAmount.toString() };
33
- });
34
- };
35
- export const approveToken = async ({ signer, token, approvalAddress, amount, infiniteApproval = false, }) => {
36
- // native token don't need approval
37
- if (isNativeTokenAddress(token.address)) {
38
- return;
39
- }
40
- const approvedAmount = await getApproved(signer, token.address, approvalAddress);
41
- if (new BigNumber(amount).gt(approvedAmount)) {
42
- const approvalAmount = infiniteApproval
43
- ? constants.MaxUint256.toString()
44
- : amount;
45
- const approveTx = await setApproval(signer, token.address, approvalAddress, approvalAmount);
46
- await approveTx.wait();
47
- }
48
- };
49
- export const revokeTokenApproval = async ({ signer, token, approvalAddress, }) => {
50
- // native token don't need approval
51
- if (isNativeTokenAddress(token.address)) {
52
- return;
53
- }
54
- const approvedAmount = await getApproved(signer, token.address, approvalAddress);
55
- if (!approvedAmount.isZero()) {
56
- const approveTx = await setApproval(signer, token.address, approvalAddress, '0');
57
- await approveTx.wait();
58
- }
59
- };
@@ -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,77 +0,0 @@
1
- import BigNumber from 'bignumber.js';
2
- import { Contract, ethers, } from 'ethers';
3
- import ChainsService from '../services/ChainsService';
4
- import { ERC20_ABI } from '../types';
5
- import { ServerError } from '../utils/errors';
6
- import { fetchDataUsingMulticall } from '../utils/multicall';
7
- export const getApproved = async (signer, tokenAddress, contractAddress, transactionRequest) => {
8
- const signerAddress = await signer.getAddress();
9
- const erc20 = new Contract(tokenAddress, ERC20_ABI, signer);
10
- try {
11
- const approved = await erc20.allowance(signerAddress, contractAddress, {
12
- gasLimit: transactionRequest?.gasLimit,
13
- gasPrice: transactionRequest?.gasPrice,
14
- maxFeePerGas: transactionRequest?.maxFeePerGas,
15
- maxPriorityFeePerGas: transactionRequest?.maxPriorityFeePerGas,
16
- });
17
- return new BigNumber(approved.toString());
18
- }
19
- catch (e) {
20
- return new BigNumber(0);
21
- }
22
- };
23
- export const setApproval = async (signer, tokenAddress, contractAddress, amount, returnPopulatedTransaction) => {
24
- const erc20 = new Contract(tokenAddress, ERC20_ABI, signer);
25
- if (returnPopulatedTransaction) {
26
- return erc20.populateTransaction.approve(contractAddress, amount);
27
- }
28
- const transactionRequest = await erc20.populateTransaction.approve(contractAddress, amount);
29
- try {
30
- const estimatedGasLimit = await signer.estimateGas(transactionRequest);
31
- if (estimatedGasLimit) {
32
- const formattedGasLimit = ethers.BigNumber.from(`${(BigInt(estimatedGasLimit.toString()) * 125n) / 100n}`);
33
- transactionRequest.gasLimit = formattedGasLimit;
34
- }
35
- }
36
- catch (error) { }
37
- return signer.sendTransaction(transactionRequest);
38
- };
39
- export const getAllowanceViaMulticall = async (signer, chainId, tokenData) => {
40
- const chainsService = ChainsService.getInstance();
41
- const chain = await chainsService.getChainById(chainId);
42
- if (!chain.multicallAddress) {
43
- throw new ServerError(`No multicall address configured for chainId ${chainId}.`);
44
- }
45
- const ownerAddress = await signer.getAddress();
46
- const calls = [];
47
- tokenData.map(({ token, approvalAddress }) => {
48
- calls.push({
49
- address: token.address,
50
- name: 'allowance',
51
- params: [ownerAddress, approvalAddress],
52
- });
53
- });
54
- const result = await fetchDataUsingMulticall(calls, ERC20_ABI, chainId, chain.multicallAddress);
55
- if (!result.length) {
56
- throw new ServerError(`Couldn't load allowance from chainId ${chainId} using multicall.`);
57
- }
58
- const parsedResult = result.map(({ data }) => ({
59
- approvalAmount: data ?? new BigNumber(0),
60
- }));
61
- return tokenData.map(({ token, approvalAddress }, i) => ({
62
- token,
63
- approvalAddress,
64
- approvedAmount: parsedResult[i].approvalAmount,
65
- }));
66
- };
67
- export const groupByChain = (tokenDataList) => {
68
- // group by chain
69
- const tokenDataByChain = {};
70
- tokenDataList.forEach((tokenData) => {
71
- if (!tokenDataByChain[tokenData.token.chainId]) {
72
- tokenDataByChain[tokenData.token.chainId] = [];
73
- }
74
- tokenDataByChain[tokenData.token.chainId].push(tokenData);
75
- });
76
- return tokenDataByChain;
77
- };
@@ -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,38 +0,0 @@
1
- import BigNumber from 'bignumber.js';
2
- import { BalanceError } from '../utils/errors';
3
- import { getTokenBalance } from './getTokenBalance';
4
- export const checkBalance = async (signer, step, depth = 0) => {
5
- const tokenAmount = await getTokenBalance(await signer.getAddress(), step.action.fromToken);
6
- if (tokenAmount) {
7
- const currentBalance = new BigNumber(tokenAmount.amount).shiftedBy(tokenAmount.decimals);
8
- const neededBalance = new BigNumber(step.action.fromAmount);
9
- if (currentBalance.lt(neededBalance)) {
10
- if (depth <= 3) {
11
- await new Promise((resolve) => {
12
- setTimeout(resolve, 200);
13
- });
14
- await checkBalance(signer, step, depth + 1);
15
- }
16
- else if (neededBalance.multipliedBy(1 - step.action.slippage).lte(currentBalance)) {
17
- // adjust amount in slippage limits
18
- step.action.fromAmount = currentBalance.toFixed(0);
19
- }
20
- else {
21
- const neeeded = neededBalance.shiftedBy(-tokenAmount.decimals).toFixed();
22
- const current = currentBalance
23
- .shiftedBy(-tokenAmount.decimals)
24
- .toFixed();
25
- let errorMessage = `Your ${tokenAmount.symbol} balance is too low, ` +
26
- `you try to transfer ${neeeded} ${tokenAmount.symbol}, ` +
27
- `but your wallet only holds ${current} ${tokenAmount.symbol}. ` +
28
- `No funds have been sent. `;
29
- if (!currentBalance.isZero()) {
30
- errorMessage +=
31
- `If the problem consists, please delete this transfer and ` +
32
- `start a new one with a maximum of ${current} ${tokenAmount.symbol}.`;
33
- }
34
- throw new BalanceError('The balance is too low.', errorMessage);
35
- }
36
- }
37
- }
38
- };
@@ -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,143 +0,0 @@
1
- import BigNumber from 'bignumber.js';
2
- import { ethers } from 'ethers';
3
- import { getMulticallAddress, getRpcProvider } from '../connectors';
4
- import { fetchDataUsingMulticall } from '../utils/multicall';
5
- import { isZeroAddress } from '../utils/utils';
6
- const balanceAbi = [
7
- {
8
- constant: true,
9
- inputs: [{ name: 'who', type: 'address' }],
10
- name: 'balanceOf',
11
- outputs: [{ name: '', type: 'uint256' }],
12
- payable: false,
13
- stateMutability: 'view',
14
- type: 'function',
15
- },
16
- {
17
- constant: true,
18
- inputs: [{ name: 'addr', type: 'address' }],
19
- name: 'getEthBalance',
20
- outputs: [{ name: 'balance', type: 'uint256' }],
21
- payable: false,
22
- stateMutability: 'view',
23
- type: 'function',
24
- },
25
- ];
26
- export const getBalances = async (walletAddress, tokens) => {
27
- if (tokens.length === 0) {
28
- return [];
29
- }
30
- const { chainId } = tokens[0];
31
- tokens.forEach((token) => {
32
- if (token.chainId !== chainId) {
33
- // eslint-disable-next-line no-console
34
- console.warn(`Requested tokens have to be on the same chain.`);
35
- return [];
36
- }
37
- });
38
- if ((await getMulticallAddress(chainId)) && tokens.length > 1) {
39
- return getBalancesFromProviderUsingMulticall(walletAddress, tokens);
40
- }
41
- else {
42
- return getBalancesFromProvider(walletAddress, tokens);
43
- }
44
- };
45
- const getBalancesFromProviderUsingMulticall = async (walletAddress, tokens) => {
46
- // Configuration
47
- const { chainId } = tokens[0];
48
- const multicallAddress = await getMulticallAddress(chainId);
49
- if (!multicallAddress) {
50
- throw new Error('No multicallAddress found for the given chain.');
51
- }
52
- return executeMulticall(walletAddress, tokens, multicallAddress, chainId);
53
- };
54
- const executeMulticall = async (walletAddress, tokens, multicallAddress, chainId) => {
55
- // Collect calls we want to make
56
- const calls = [];
57
- tokens.map((token) => {
58
- if (isZeroAddress(token.address)) {
59
- calls.push({
60
- address: multicallAddress,
61
- name: 'getEthBalance',
62
- params: [walletAddress],
63
- });
64
- }
65
- else {
66
- calls.push({
67
- address: token.address,
68
- name: 'balanceOf',
69
- params: [walletAddress],
70
- });
71
- }
72
- });
73
- const res = await fetchViaMulticall(calls, balanceAbi, chainId, multicallAddress);
74
- if (!res.length) {
75
- return [];
76
- }
77
- return tokens.map((token, i) => {
78
- const amount = new BigNumber(res[i].amount.toString() || '0')
79
- .shiftedBy(-token.decimals)
80
- .toFixed();
81
- return {
82
- ...token,
83
- amount: amount || '0',
84
- blockNumber: res[i].blockNumber,
85
- };
86
- });
87
- };
88
- const fetchViaMulticall = async (calls, abi, chainId, multicallAddress) => {
89
- const result = await fetchDataUsingMulticall(calls, abi, chainId, multicallAddress);
90
- return result.map(({ data, blockNumber }) => ({
91
- amount: data ? data : new BigNumber(0),
92
- blockNumber,
93
- }));
94
- };
95
- const getBalancesFromProvider = async (walletAddress, tokens) => {
96
- const chainId = tokens[0].chainId;
97
- const rpc = await getRpcProvider(chainId);
98
- const tokenAmountPromises = tokens.map(async (token) => {
99
- let amount = '0';
100
- let blockNumber;
101
- try {
102
- const balance = await getBalanceFromProvider(walletAddress, token.address, chainId, rpc);
103
- amount = new BigNumber(balance.amount.toString())
104
- .shiftedBy(-token.decimals)
105
- .toString();
106
- blockNumber = balance.blockNumber;
107
- }
108
- catch (e) {
109
- // eslint-disable-next-line no-console
110
- console.warn(e);
111
- }
112
- return {
113
- ...token,
114
- amount,
115
- blockNumber,
116
- };
117
- });
118
- return Promise.all(tokenAmountPromises);
119
- };
120
- const getBalanceFromProvider = async (walletAddress, assetId, chainId, provider) => {
121
- const blockNumber = await getCurrentBlockNumber(chainId);
122
- let balance;
123
- if (isZeroAddress(assetId)) {
124
- balance = await provider.getBalance(walletAddress, blockNumber);
125
- }
126
- else {
127
- const contract = new ethers.Contract(assetId, ['function balanceOf(address owner) view returns (uint256)'], provider);
128
- balance = await contract.balanceOf(walletAddress, {
129
- blockTag: blockNumber,
130
- });
131
- }
132
- return {
133
- amount: balance,
134
- blockNumber,
135
- };
136
- };
137
- const getCurrentBlockNumber = async (chainId) => {
138
- const rpc = await getRpcProvider(chainId);
139
- return rpc.getBlockNumber();
140
- };
141
- export default {
142
- getBalances,
143
- };
@@ -1,4 +0,0 @@
1
- import { PopulatedTransaction, Signer } from 'ethers';
2
- import { StatusManager } from '../execution/StatusManager';
3
- import { Chain, InternalExecutionSettings, LifiStep } from '../types';
4
- export declare const checkAllowance: (signer: Signer, step: LifiStep, statusManager: StatusManager, settings: InternalExecutionSettings, chain: Chain, allowUserInteraction?: boolean, shouldBatchTransactions?: boolean) => Promise<void | PopulatedTransaction>;