@instadapp/interop-x 0.0.0-dev.e916c22 → 0.0.0-dev.ea4acf6

Sign up to get free protection for your applications and to get access to all the features.
Files changed (100) hide show
  1. package/dist/package.json +9 -2
  2. package/dist/src/abi/aaveV2Resolver.json +832 -0
  3. package/dist/src/abi/aaveV3Resolver.json +628 -0
  4. package/dist/src/abi/balanceResolver.json +211 -0
  5. package/dist/src/abi/index.js +6 -0
  6. package/dist/src/api/index.js +7 -0
  7. package/dist/src/constants/addresses.js +6 -0
  8. package/dist/src/constants/capPerChain.js +8 -0
  9. package/dist/src/constants/index.js +2 -0
  10. package/dist/src/constants/tokens.js +44 -44
  11. package/dist/src/constants/wrappedNativeToken.js +8 -0
  12. package/dist/src/crons/index.js +3 -0
  13. package/dist/src/crons/prices.js +16 -0
  14. package/dist/src/db/models/transaction.js +1 -1
  15. package/dist/src/errors/index.js +30 -0
  16. package/dist/src/gnosis/actions/aaveV2/source.js +26 -1
  17. package/dist/src/gnosis/actions/aaveV2/target.js +18 -4
  18. package/dist/src/gnosis/actions/aaveV3/index.js +11 -0
  19. package/dist/src/gnosis/actions/aaveV3/source.js +74 -0
  20. package/dist/src/gnosis/actions/aaveV3/target.js +87 -0
  21. package/dist/src/gnosis/actions/index.js +2 -0
  22. package/dist/src/index.js +2 -1
  23. package/dist/src/providers/index.js +17 -0
  24. package/dist/src/providers/retry-provider.js +45 -0
  25. package/dist/src/services/Prices.js +74 -0
  26. package/dist/src/services/index.js +8 -0
  27. package/dist/src/tasks/InteropX/{ProcessSubmitSubmitEvents.js → ProcessSubmitEvents.js} +108 -14
  28. package/dist/src/tasks/InteropX/ProcessValidateEvents.js +30 -10
  29. package/dist/src/tasks/InteropX/SyncLogExecuteEvents.js +3 -2
  30. package/dist/src/tasks/InteropX/SyncLogSubmitEvents.js +3 -2
  31. package/dist/src/tasks/InteropX/SyncLogValidateEvents.js +3 -2
  32. package/dist/src/tasks/index.js +3 -4
  33. package/dist/src/typechain/AaveV2Resolver.js +2 -0
  34. package/dist/src/typechain/AaveV3Resolver.js +2 -0
  35. package/dist/src/typechain/BalanceResolver.js +2 -0
  36. package/dist/src/typechain/factories/AaveV2Resolver__factory.js +1191 -0
  37. package/dist/src/typechain/factories/AaveV3Resolver__factory.js +887 -0
  38. package/dist/src/typechain/factories/BalanceResolver__factory.js +228 -0
  39. package/dist/src/typechain/factories/index.js +7 -1
  40. package/dist/src/typechain/index.js +7 -1
  41. package/dist/src/utils/async.js +18 -0
  42. package/dist/src/utils/dsa.js +36 -0
  43. package/dist/src/utils/formatting.js +67 -0
  44. package/dist/src/utils/gnosis.js +87 -0
  45. package/dist/src/utils/http.js +10 -0
  46. package/dist/src/utils/index.js +22 -220
  47. package/dist/src/utils/interop.js +16 -0
  48. package/dist/src/utils/tokens.js +22 -0
  49. package/dist/src/utils/validate.js +111 -0
  50. package/dist/src/utils/web3.js +93 -0
  51. package/package.json +9 -2
  52. package/src/abi/aaveV2Resolver.json +832 -0
  53. package/src/abi/aaveV3Resolver.json +628 -0
  54. package/src/abi/balanceResolver.json +211 -0
  55. package/src/abi/index.ts +6 -0
  56. package/src/api/index.ts +8 -0
  57. package/src/constants/addresses.ts +18 -1
  58. package/src/constants/capPerChain.ts +5 -0
  59. package/src/constants/index.ts +2 -0
  60. package/src/constants/tokens.ts +44 -44
  61. package/src/constants/wrappedNativeToken.ts +5 -0
  62. package/src/crons/index.ts +1 -0
  63. package/src/crons/prices.ts +12 -0
  64. package/src/db/models/transaction.ts +1 -1
  65. package/src/errors/index.ts +26 -0
  66. package/src/gnosis/actions/aaveV2/source.ts +56 -3
  67. package/src/gnosis/actions/aaveV2/target.ts +30 -11
  68. package/src/gnosis/actions/aaveV3/index.ts +9 -0
  69. package/src/gnosis/actions/aaveV3/source.ts +119 -0
  70. package/src/gnosis/actions/aaveV3/target.ts +142 -0
  71. package/src/gnosis/actions/index.ts +2 -0
  72. package/src/index.ts +1 -0
  73. package/src/providers/index.ts +1 -0
  74. package/src/providers/retry-provider.ts +51 -0
  75. package/src/services/Prices.ts +89 -0
  76. package/src/services/index.ts +1 -0
  77. package/src/tasks/InteropX/{ProcessSubmitSubmitEvents.ts → ProcessSubmitEvents.ts} +135 -20
  78. package/src/tasks/InteropX/ProcessValidateEvents.ts +42 -19
  79. package/src/tasks/InteropX/SyncLogExecuteEvents.ts +5 -6
  80. package/src/tasks/InteropX/SyncLogSubmitEvents.ts +6 -7
  81. package/src/tasks/InteropX/SyncLogValidateEvents.ts +6 -7
  82. package/src/tasks/index.ts +3 -4
  83. package/src/typechain/AaveV2Resolver.ts +1017 -0
  84. package/src/typechain/AaveV3Resolver.ts +935 -0
  85. package/src/typechain/BalanceResolver.ts +266 -0
  86. package/src/typechain/factories/AaveV2Resolver__factory.ts +1198 -0
  87. package/src/typechain/factories/AaveV3Resolver__factory.ts +894 -0
  88. package/src/typechain/factories/BalanceResolver__factory.ts +235 -0
  89. package/src/typechain/factories/index.ts +3 -0
  90. package/src/typechain/index.ts +6 -0
  91. package/src/utils/async.ts +22 -0
  92. package/src/utils/dsa.ts +56 -0
  93. package/src/utils/formatting.ts +68 -0
  94. package/src/utils/gnosis.ts +166 -0
  95. package/src/utils/http.ts +6 -0
  96. package/src/utils/index.ts +9 -365
  97. package/src/utils/interop.ts +28 -0
  98. package/src/utils/tokens.ts +21 -0
  99. package/src/utils/validate.ts +179 -0
  100. package/src/utils/web3.ts +132 -0
@@ -1,223 +1,25 @@
1
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.encodeConnectorMethod = exports.LiquidityError = exports.generateGnosisTransaction = exports.getContract = exports.ContractError = exports.generateInteropTransactionHash = exports.asyncCallWithTimeout = exports.buildSignatureBytes = exports.getRpcProviderUrl = exports.signGnosisSafeTx = exports.short = exports.shortenHash = exports.http = void 0;
7
- /**
8
- * @module util
9
- */
10
- const axios_1 = __importDefault(require("axios"));
11
- const axios_retry_1 = __importDefault(require("axios-retry"));
12
- const constants_1 = require("@/constants");
13
- const ethers_1 = require("ethers");
14
- const async_retry_1 = __importDefault(require("async-retry"));
15
- const connectors_1 = require("@/abi/connectors");
16
- const web3_eth_abi_1 = __importDefault(require("web3-eth-abi"));
17
- exports.http = axios_1.default.create();
18
- (0, axios_retry_1.default)(exports.http, { retries: 3, retryDelay: axios_retry_1.default.exponentialDelay });
19
- function shortenHash(hash, length = 4) {
20
- if (!hash)
21
- return;
22
- if (hash.length < 12)
23
- return hash;
24
- const beginningChars = hash.startsWith("0x") ? length + 2 : length;
25
- const shortened = hash.substr(0, beginningChars) + "…" + hash.substr(-length);
26
- return shortened;
27
- }
28
- exports.shortenHash = shortenHash;
29
- function short(buffer) {
30
- return buffer.toString("hex").slice(0, 8) + "...";
31
- }
32
- exports.short = short;
33
- const signGnosisSafeTx = async ({ to, data = null, value = "0", operation = "1", baseGas = "0", gasPrice = "0", gasToken = "0x0000000000000000000000000000000000000000", refundReceiver = "0x0000000000000000000000000000000000000000", safeTxGas = "79668", nonce = "0", chainId = 137, }, { signer }) => {
34
- const gnosisSafe = constants_1.addresses[chainId].gnosisSafe;
35
- const domain = {
36
- verifyingContract: gnosisSafe,
37
- chainId,
38
- };
39
- const types = {
40
- SafeTx: [
41
- { type: "address", name: "to" },
42
- { type: "uint256", name: "value" },
43
- { type: "bytes", name: "data" },
44
- { type: "uint8", name: "operation" },
45
- { type: "uint256", name: "safeTxGas" },
46
- { type: "uint256", name: "baseGas" },
47
- { type: "uint256", name: "gasPrice" },
48
- { type: "address", name: "gasToken" },
49
- { type: "address", name: "refundReceiver" },
50
- { type: "uint256", name: "nonce" },
51
- ],
52
- };
53
- const message = {
54
- baseGas,
55
- data,
56
- gasPrice,
57
- gasToken,
58
- nonce: Number(nonce),
59
- operation,
60
- refundReceiver,
61
- safeAddress: gnosisSafe,
62
- safeTxGas: String(safeTxGas),
63
- to,
64
- value,
65
- };
66
- return await signer._signTypedData(domain, types, message);
67
- };
68
- exports.signGnosisSafeTx = signGnosisSafeTx;
69
- const getRpcProviderUrl = (chainId) => {
70
- switch (chainId) {
71
- case 1:
72
- return "https://rpc.ankr.com/eth";
73
- case 137:
74
- return "https://rpc.ankr.com/polygon";
75
- case 43114:
76
- return "https://rpc.ankr.com/avalanche";
77
- default:
78
- throw new Error(`Unknown chainId: ${chainId}`);
79
- }
80
- };
81
- exports.getRpcProviderUrl = getRpcProviderUrl;
82
- const buildSignatureBytes = (signatures) => {
83
- signatures.sort((left, right) => left.signer.toLowerCase().localeCompare(right.signer.toLowerCase()));
84
- let signatureBytes = "0x";
85
- for (const sig of signatures) {
86
- signatureBytes += sig.data.slice(2);
87
- }
88
- return signatureBytes;
89
- };
90
- exports.buildSignatureBytes = buildSignatureBytes;
91
- /**
92
- * Call an async function with a maximum time limit (in milliseconds) for the timeout
93
- * Resolved promise for async function call, or an error if time limit reached
94
- */
95
- const asyncCallWithTimeout = async (asyncPromise, timeout) => {
96
- let timeoutHandle;
97
- const timeoutPromise = new Promise((_resolve, reject) => {
98
- timeoutHandle = setTimeout(() => reject(new Error("Async call timeout limit reached")), timeout);
99
- });
100
- return Promise.race([asyncPromise, timeoutPromise]).then((result) => {
101
- clearTimeout(timeoutHandle);
102
- return result;
103
- });
104
- };
105
- exports.asyncCallWithTimeout = asyncCallWithTimeout;
106
- const generateInteropTransactionHash = (data) => {
107
- return ethers_1.ethers.utils.solidityKeccak256(Array.from({ length: 7 }, () => "string"), [
108
- String(data.actionId),
109
- String(data.vnonce),
110
- String(data.sourceSender),
111
- String(data.sourceChainId),
112
- String(data.sourceDsaId),
113
- String(data.targetChainId),
114
- String(data.targetDsaId),
115
- ]);
116
- };
117
- exports.generateInteropTransactionHash = generateInteropTransactionHash;
118
- class ContractError extends Error {
119
- }
120
- exports.ContractError = ContractError;
121
- function getContract(address, contractInterface, signerOrProvider) {
122
- if (!ethers_1.ethers.utils.getAddress(address) ||
123
- address === ethers_1.ethers.constants.AddressZero) {
124
- throw Error(`Invalid 'address' parameter '${address}'.`);
125
- }
126
- const contract = new ethers_1.ethers.Contract(address, contractInterface, signerOrProvider);
127
- // Make sure the contract properties is writable
128
- const desc = Object.getOwnPropertyDescriptor(contract, "functions");
129
- if (!desc || desc.writable !== true) {
130
- return contract;
131
- }
132
- return new Proxy(contract, {
133
- get(target, prop, receiver) {
134
- const value = Reflect.get(target, prop, receiver);
135
- if (typeof value === "function" &&
136
- (contract.functions.hasOwnProperty(prop) ||
137
- ["queryFilter"].includes(String(prop)))) {
138
- let isConstant = false;
139
- try {
140
- isConstant = contract.interface.getFunction(String(prop)).constant;
141
- }
142
- catch (error) { }
143
- return async (...args) => {
144
- try {
145
- return await (0, async_retry_1.default)(async () => await value.bind(contract)(...args), { retries: isConstant ? 1 : 3 });
146
- }
147
- catch (error) {
148
- const err = new ContractError(`Error calling "${String(prop)}" on "${address}": ${error.reason || error.message}`);
149
- err.method = String(prop);
150
- err.address = address;
151
- err.args = [...args];
152
- throw err;
153
- }
154
- };
155
- }
156
- if (typeof value === "object" &&
157
- [
158
- "populateTransaction",
159
- "estimateGas",
160
- "functions",
161
- "callStatic",
162
- ].includes(String(prop))) {
163
- const parentProp = String(prop);
164
- return new Proxy(value, {
165
- get(target, prop, receiver) {
166
- const value = Reflect.get(target, prop, receiver);
167
- if (typeof value === "function") {
168
- return async (...args) => {
169
- try {
170
- return await (0, async_retry_1.default)(async () => await value.bind(contract)(...args), { retries: parentProp === "callStatic" ? 3 : 1 });
171
- }
172
- catch (error) {
173
- const err = new ContractError(`Error calling "${String(prop)}" using "${parentProp}" on "${address}": ${error.reason || error.message}`);
174
- err.method = String(prop);
175
- err.address = address;
176
- err.args = [...args];
177
- throw err;
178
- }
179
- };
180
- }
181
- },
182
- });
183
- }
184
- return value;
185
- },
186
- });
187
- }
188
- exports.getContract = getContract;
189
- const generateGnosisTransaction = async (transactionData, safeContract) => {
190
- console.log(transactionData);
191
- let isExecuted = await safeContract.dataHashes(await safeContract.getTransactionHash(transactionData.to, transactionData.value, transactionData.data, transactionData.operation, transactionData.safeTxGas, transactionData.baseGas, transactionData.gasPrice, transactionData.gasToken, transactionData.refundReceiver, transactionData.nonce));
192
- while (isExecuted == 1) {
193
- transactionData.safeTxGas = ethers_1.ethers.BigNumber.from(String(transactionData.safeTxGas))
194
- .add(1)
195
- .toString();
196
- isExecuted = await safeContract.dataHashes(await safeContract.getTransactionHash(transactionData.to, transactionData.value, transactionData.data, transactionData.operation, transactionData.safeTxGas, transactionData.baseGas, transactionData.gasPrice, transactionData.gasToken, transactionData.refundReceiver, transactionData.nonce));
197
- }
198
- return transactionData;
199
- };
200
- exports.generateGnosisTransaction = generateGnosisTransaction;
201
- class LiquidityError extends Error {
202
- constructor(message) {
203
- super(message || "Not enough liquidity");
204
- Object.setPrototypeOf(this, new.target.prototype);
205
- }
206
- }
207
- exports.LiquidityError = LiquidityError;
208
- const encodeConnectorMethod = (params) => {
209
- const connectorInterface = getInterface(connectors_1.connectors.versions[2][params.connector], params.method);
210
- if (!connectorInterface)
211
- throw new Error(`ConnectorInterface '${params.method}' not found`);
212
- //@ts-ignore
213
- return web3_eth_abi_1.default.encodeFunctionCall(connectorInterface, params.args);
214
- };
215
- exports.encodeConnectorMethod = encodeConnectorMethod;
216
- const getInterface = (abiItems, method) => {
217
- const abiItem = abiItems.find((abiItem) => abiItem.name === method);
218
- if (!abiItem) {
219
- console.error(`${method} is an invalid method.`);
220
- return;
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]; } };
221
7
  }
222
- return abiItem;
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);
223
15
  };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./async"), exports);
18
+ __exportStar(require("./dsa"), exports);
19
+ __exportStar(require("./formatting"), exports);
20
+ __exportStar(require("./gnosis"), exports);
21
+ __exportStar(require("./http"), exports);
22
+ __exportStar(require("./interop"), exports);
23
+ __exportStar(require("./web3"), exports);
24
+ __exportStar(require("./validate"), exports);
25
+ __exportStar(require("./tokens"), exports);
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateInteropTransactionHash = void 0;
4
+ const ethers_1 = require("ethers");
5
+ const generateInteropTransactionHash = (data) => {
6
+ return ethers_1.ethers.utils.solidityKeccak256(Array.from({ length: 7 }, () => "string"), [
7
+ String(data.actionId),
8
+ String(data.vnonce),
9
+ String(data.sourceSender),
10
+ String(data.sourceChainId),
11
+ String(data.sourceDsaId),
12
+ String(data.targetChainId),
13
+ String(data.targetDsaId),
14
+ ]);
15
+ };
16
+ exports.generateInteropTransactionHash = generateInteropTransactionHash;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isNativeOrWrappedToken = exports.isNativeWrappedToken = exports.isNativeToken = void 0;
4
+ const constants_1 = require("@/constants");
5
+ const isNativeToken = (tokenAddress) => {
6
+ return tokenAddress.toLowerCase() === "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE".toLowerCase();
7
+ };
8
+ exports.isNativeToken = isNativeToken;
9
+ const isNativeWrappedToken = (tokenAddress, chainId) => {
10
+ return constants_1.wrappedNativeToken[chainId].toLowerCase() == tokenAddress.toLowerCase();
11
+ };
12
+ exports.isNativeWrappedToken = isNativeWrappedToken;
13
+ const isNativeOrWrappedToken = (tokenAddress, chainId) => {
14
+ if ((0, exports.isNativeToken)(tokenAddress)) {
15
+ return true;
16
+ }
17
+ if ((0, exports.isNativeWrappedToken)(tokenAddress, chainId)) {
18
+ return true;
19
+ }
20
+ return false;
21
+ };
22
+ exports.isNativeOrWrappedToken = isNativeOrWrappedToken;
@@ -0,0 +1,111 @@
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.validateLiquidityCap = exports.validateTargetLiquidity = exports.validateSourceLiquidity = exports.validateChains = void 0;
7
+ const abi_1 = __importDefault(require("@/abi"));
8
+ const constants_1 = require("@/constants");
9
+ const errors_1 = require("@/errors");
10
+ const web3_1 = require("./web3");
11
+ const bignumber_js_1 = __importDefault(require("bignumber.js"));
12
+ const formatting_1 = require("./formatting");
13
+ const tokens_1 = require("./tokens");
14
+ const services_1 = require("@/services");
15
+ const providers_1 = require("@/providers");
16
+ const dsa_1 = require("./dsa");
17
+ const validateChains = ({ sourceChainId, targetChainId }) => {
18
+ if (!sourceChainId) {
19
+ throw new errors_1.InvalidChaindIdError("Source chain id is required");
20
+ }
21
+ if (!targetChainId) {
22
+ throw new errors_1.InvalidChaindIdError("Target chain id is required");
23
+ }
24
+ if (sourceChainId == targetChainId) {
25
+ throw new errors_1.InvalidChaindIdError("Source and target chain cannot be the same");
26
+ }
27
+ if (!constants_1.addresses[sourceChainId]) {
28
+ throw new errors_1.InvalidChaindIdError("Invalid source chain id");
29
+ }
30
+ if (!constants_1.addresses[targetChainId]) {
31
+ throw new errors_1.InvalidChaindIdError("Invalid target chain id");
32
+ }
33
+ };
34
+ exports.validateChains = validateChains;
35
+ const validateSourceLiquidity = async ({ position = null, sourceChainId, sourceDsaId, isSupply = false, sourceProvider = null, }) => {
36
+ sourceProvider = sourceProvider || new providers_1.JsonRpcRetryProvider((0, web3_1.getRpcProviderUrl)(sourceChainId));
37
+ const sourceBalanceResolverContract = (0, web3_1.getContract)(constants_1.addresses[sourceChainId].balanceResolver, abi_1.default.balanceResolver, sourceProvider);
38
+ const srcDsaAddress = await (0, dsa_1.getDsaAccountAddress)({ dsaId: sourceDsaId, chainId: sourceChainId, provider: sourceProvider });
39
+ const srcBalance = await sourceBalanceResolverContract.checkLiquidity(position, srcDsaAddress, isSupply, false);
40
+ if (!srcBalance.isOk) {
41
+ let liquidityRequired = "";
42
+ srcBalance.withdraw.forEach(a => {
43
+ const token = constants_1.tokens[sourceChainId].find(t => t.address.toLowerCase() === a.token.toLowerCase());
44
+ if (token && (new bignumber_js_1.default(a.liquidityShort.toString()).isZero()) == false) {
45
+ liquidityRequired += `- Need ${new bignumber_js_1.default(a.liquidityShort.toString()).dividedBy(10 ** token.decimals).toFormat()} ${token.symbol}\n`;
46
+ }
47
+ });
48
+ throw new errors_1.LowLiquidityError(`Liquidity low on ${(0, formatting_1.chainIdToName)(sourceChainId)}: \n` + liquidityRequired);
49
+ }
50
+ };
51
+ exports.validateSourceLiquidity = validateSourceLiquidity;
52
+ const validateTargetLiquidity = async ({ position = null, targetChainId, targetDsaId, targetProvider = null, }) => {
53
+ targetProvider = targetProvider || new providers_1.JsonRpcRetryProvider((0, web3_1.getRpcProviderUrl)(targetChainId));
54
+ const sourceBalanceResolverContract = (0, web3_1.getContract)(constants_1.addresses[targetChainId].balanceResolver, abi_1.default.balanceResolver, targetProvider);
55
+ // TODO:
56
+ const targetDsaAddress = await (0, dsa_1.getDsaAccountAddress)({ dsaId: targetDsaId, chainId: targetChainId, provider: targetProvider });
57
+ const targetBalance = await sourceBalanceResolverContract.checkLiquidity(position, targetDsaAddress, true, true);
58
+ if (!targetBalance.isOk) {
59
+ let liquidityRequired = "";
60
+ targetBalance.supply.forEach(a => {
61
+ const token = constants_1.tokens[targetChainId].find(t => t.address.toLowerCase() === a.token.toLowerCase());
62
+ if (token) {
63
+ liquidityRequired += `- Need ${new bignumber_js_1.default(a.liquidityShort.toString()).dividedBy(10 ** token.decimals).toFormat()} ${token.symbol}\n`;
64
+ }
65
+ });
66
+ throw new errors_1.LowLiquidityError(`Liquidity low on ${(0, formatting_1.chainIdToName)(targetChainId)}: \n` + liquidityRequired);
67
+ }
68
+ };
69
+ exports.validateTargetLiquidity = validateTargetLiquidity;
70
+ const mapTokenAddressToMainnetToken = (address, targetChainId) => {
71
+ targetChainId = String(targetChainId);
72
+ const token = constants_1.tokens[targetChainId].find((t) => t.address.toLowerCase() === address.toLowerCase());
73
+ if (targetChainId === "1") {
74
+ return token;
75
+ }
76
+ if (!token) {
77
+ return null;
78
+ }
79
+ return constants_1.tokens["1"].find((t) => t.symbol === token.symbol);
80
+ };
81
+ const validateLiquidityCap = async (position, sourceChainId, targetChainId) => {
82
+ const cap = constants_1.capPerChain[targetChainId] || 1000000;
83
+ const mainnetPrices = services_1.Prices.getMainnetPrices();
84
+ const nativeTokenPrice = services_1.Prices.getNetworkTokenPrices()[targetChainId];
85
+ let total = new bignumber_js_1.default(0);
86
+ const supplyPosition = position.supply;
87
+ for (const { sourceToken: srcTokenAddress, targetToken: tokenAddress, amount } of supplyPosition) {
88
+ let tokenPrice;
89
+ let token;
90
+ if ((0, tokens_1.isNativeWrappedToken)(srcTokenAddress, sourceChainId)) {
91
+ tokenPrice = nativeTokenPrice;
92
+ token = constants_1.tokens[targetChainId].find(t => t.address === '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE');
93
+ }
94
+ else {
95
+ const mainnetToken = mapTokenAddressToMainnetToken(tokenAddress, targetChainId);
96
+ if (!mainnetToken) {
97
+ throw new Error(`Token ${tokenAddress} is not valid.`);
98
+ }
99
+ tokenPrice = mainnetPrices[mainnetToken.address];
100
+ if (!tokenPrice) {
101
+ throw new Error(`Token ${tokenAddress} is not valid!`);
102
+ }
103
+ token = mainnetToken;
104
+ }
105
+ total = total.plus((tokenPrice * Number(amount)) / 10 ** token.decimals);
106
+ }
107
+ if (total.isGreaterThan(cap)) {
108
+ throw new Error(`Total amount of tokens in the transaction is greater than the maximum limit of estimated ${(0, formatting_1.formatUsd)(cap)}`);
109
+ }
110
+ };
111
+ exports.validateLiquidityCap = validateLiquidityCap;
@@ -0,0 +1,93 @@
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.getContract = exports.ContractError = exports.getRpcProviderUrl = void 0;
7
+ const errors_1 = require("@/errors");
8
+ const async_retry_1 = __importDefault(require("async-retry"));
9
+ const ethers_1 = require("ethers");
10
+ const getRpcProviderUrl = (chainId) => {
11
+ switch (chainId) {
12
+ case 1:
13
+ return "https://rpc.ankr.com/eth";
14
+ case 137:
15
+ return "https://rpc.ankr.com/polygon";
16
+ case 43114:
17
+ return "https://rpc.ankr.com/avalanche";
18
+ default:
19
+ throw new errors_1.UnsupportedChaindIdError(chainId);
20
+ }
21
+ };
22
+ exports.getRpcProviderUrl = getRpcProviderUrl;
23
+ class ContractError extends Error {
24
+ }
25
+ exports.ContractError = ContractError;
26
+ function getContract(address, contractInterface, signerOrProvider) {
27
+ if (!ethers_1.ethers.utils.getAddress(address) ||
28
+ address === ethers_1.ethers.constants.AddressZero) {
29
+ throw Error(`Invalid 'address' parameter '${address}'.`);
30
+ }
31
+ const contract = new ethers_1.ethers.Contract(address, contractInterface, signerOrProvider);
32
+ // Make sure the contract properties is writable
33
+ const desc = Object.getOwnPropertyDescriptor(contract, "functions");
34
+ if (!desc || desc.writable !== true) {
35
+ return contract;
36
+ }
37
+ return new Proxy(contract, {
38
+ get(target, prop, receiver) {
39
+ const value = Reflect.get(target, prop, receiver);
40
+ if (typeof value === "function" &&
41
+ (contract.functions.hasOwnProperty(prop) ||
42
+ ["queryFilter"].includes(String(prop)))) {
43
+ let isConstant = false;
44
+ try {
45
+ isConstant = contract.interface.getFunction(String(prop)).constant;
46
+ }
47
+ catch (error) { }
48
+ return async (...args) => {
49
+ try {
50
+ return await (0, async_retry_1.default)(async () => await value.bind(contract)(...args), { retries: isConstant ? 1 : 3 });
51
+ }
52
+ catch (error) {
53
+ const err = new ContractError(`Error calling "${String(prop)}" on "${address}": ${error.reason || error.message}`);
54
+ err.method = String(prop);
55
+ err.address = address;
56
+ err.args = [...args];
57
+ throw err;
58
+ }
59
+ };
60
+ }
61
+ if (typeof value === "object" &&
62
+ [
63
+ "populateTransaction",
64
+ "estimateGas",
65
+ "functions",
66
+ "callStatic",
67
+ ].includes(String(prop))) {
68
+ const parentProp = String(prop);
69
+ return new Proxy(value, {
70
+ get(target, prop, receiver) {
71
+ const value = Reflect.get(target, prop, receiver);
72
+ if (typeof value === "function") {
73
+ return async (...args) => {
74
+ try {
75
+ return await (0, async_retry_1.default)(async () => await value.bind(contract)(...args), { retries: parentProp === "callStatic" ? 3 : 1 });
76
+ }
77
+ catch (error) {
78
+ const err = new ContractError(`Error calling "${String(prop)}" using "${parentProp}" on "${address}": ${error.reason || error.message}`);
79
+ err.method = String(prop);
80
+ err.address = address;
81
+ err.args = [...args];
82
+ throw err;
83
+ }
84
+ };
85
+ }
86
+ },
87
+ });
88
+ }
89
+ return value;
90
+ },
91
+ });
92
+ }
93
+ exports.getContract = getContract;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@instadapp/interop-x",
3
- "version": "0.0.0-dev.e916c22",
3
+ "version": "0.0.0-dev.ea4acf6",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "engines": {
@@ -29,10 +29,13 @@
29
29
  "await-spawn": "^4.0.2",
30
30
  "axios": "^0.27.2",
31
31
  "axios-retry": "^3.2.5",
32
+ "bignumber.js": "^9.0.2",
33
+ "bluebird": "^3.7.2",
32
34
  "chalk": "4.1.2",
35
+ "dedent": "^0.7.0",
33
36
  "dotenv": "^16.0.1",
34
37
  "ethereumjs-util": "^7.1.4",
35
- "ethers": "^5.6.5",
38
+ "ethers": "^5.6.8",
36
39
  "ethers-multisend": "^2.1.1",
37
40
  "expand-home-dir": "^0.0.3",
38
41
  "fastify": "^3.29.0",
@@ -48,6 +51,7 @@
48
51
  "libp2p-websockets": "^0.16.2",
49
52
  "luxon": "^2.4.0",
50
53
  "module-alias": "^2.2.2",
54
+ "node-cron": "^3.0.1",
51
55
  "patch-package": "^6.4.7",
52
56
  "postinstall-postinstall": "^2.1.0",
53
57
  "sequelize": "6.18.0",
@@ -62,7 +66,10 @@
62
66
  },
63
67
  "devDependencies": {
64
68
  "@typechain/ethers-v5": "^10.0.0",
69
+ "@types/async-retry": "^1.4.4",
70
+ "@types/bluebird": "^3.5.36",
65
71
  "@types/bn.js": "^5.1.0",
72
+ "@types/dedent": "^0.7.0",
66
73
  "@types/fs-extra": "^9.0.13",
67
74
  "@types/node": "^17.0.33",
68
75
  "nodemon": "^2.0.16",