@pioneer-platform/uniswap-client 0.0.28 → 0.1.0

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 (47) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/lib/constants/chainInfo.d.ts +2 -2
  3. package/lib/constants/chainInfo.js +40 -43
  4. package/lib/constants/chains.d.ts +20 -20
  5. package/lib/constants/chains.js +25 -26
  6. package/lib/constants/governance.js +13 -14
  7. package/lib/constants/lists.js +20 -28
  8. package/lib/constants/misc.d.ts +4 -5
  9. package/lib/constants/misc.js +2 -2
  10. package/lib/constants/networks.js +45 -46
  11. package/lib/constants/proposals/uniswap_grants_proposal_description.js +106 -1
  12. package/lib/constants/providers.d.ts +16 -15
  13. package/lib/constants/providers.js +23 -24
  14. package/lib/constants/routing.js +44 -61
  15. package/lib/constants/tokens.d.ts +49 -49
  16. package/lib/constants/tokens.js +133 -170
  17. package/lib/index.js +556 -877
  18. package/lib/routing/clientSideSmartOrderRouter.js +72 -121
  19. package/lib/routing/gas.js +63 -150
  20. package/lib/routing/types.d.ts +7 -7
  21. package/lib/routing/types.js +160 -264
  22. package/lib/routing/utils.js +141 -196
  23. package/lib/rpc/AppJsonRpcProvider.js +40 -131
  24. package/lib/rpc/ConfiguredJsonRpcProvider.d.ts +1 -1
  25. package/lib/rpc/ConfiguredJsonRpcProvider.js +8 -27
  26. package/lib/utils/contracts/getContract.js +6 -7
  27. package/lib/utils/transformSwapRouteToGetQuoteResult.js +24 -27
  28. package/lib/utils/uniswapData.d.ts +6 -6
  29. package/lib/utils/uniswapData.js +64 -142
  30. package/package.json +19 -19
  31. package/tsconfig.json +27 -8
  32. package/lib/constants/chains.test.d.ts +0 -1
  33. package/lib/constants/chains.test.js +0 -26
  34. package/lib/constants/localCurrencies.d.ts +0 -6
  35. package/lib/constants/localCurrencies.js +0 -94
  36. package/lib/constants/localCurrencyIcons.d.ts +0 -18
  37. package/lib/constants/localCurrencyIcons.js +0 -298
  38. package/lib/constants/routing.test.d.ts +0 -1
  39. package/lib/constants/routing.test.js +0 -32
  40. package/lib/constants/tokenLists/broken.tokenlist.json +0 -22
  41. package/lib/constants/tokenLogoLookup.d.ts +0 -8
  42. package/lib/constants/tokenLogoLookup.js +0 -48
  43. package/lib/constants/tokenSafety.js +0 -129
  44. package/lib/constants/tokenSafetyLookup.d.ts +0 -18
  45. package/lib/constants/tokenSafetyLookup.js +0 -66
  46. package/lib/constants/tokenSaftey.test.d.ts +0 -1
  47. package/lib/constants/tokenSaftey.test.js +0 -31
package/lib/index.js CHANGED
@@ -9,75 +9,26 @@
9
9
 
10
10
 
11
11
  */
12
- var __assign = (this && this.__assign) || function () {
13
- __assign = Object.assign || function(t) {
14
- for (var s, i = 1, n = arguments.length; i < n; i++) {
15
- s = arguments[i];
16
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
17
- t[p] = s[p];
18
- }
19
- return t;
20
- };
21
- return __assign.apply(this, arguments);
22
- };
23
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
24
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
25
- return new (P || (P = Promise))(function (resolve, reject) {
26
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
27
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
28
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
29
- step((generator = generator.apply(thisArg, _arguments || [])).next());
30
- });
31
- };
32
- var __generator = (this && this.__generator) || function (thisArg, body) {
33
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
34
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
35
- function verb(n) { return function (v) { return step([n, v]); }; }
36
- function step(op) {
37
- if (f) throw new TypeError("Generator is already executing.");
38
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
39
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
40
- if (y = 0, t) op = [op[0] & 2, t.value];
41
- switch (op[0]) {
42
- case 0: case 1: t = op; break;
43
- case 4: _.label++; return { value: op[1], done: false };
44
- case 5: _.label++; y = op[1]; op = [0]; continue;
45
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
46
- default:
47
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
48
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
49
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
50
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
51
- if (t[2]) _.ops.pop();
52
- _.trys.pop(); continue;
53
- }
54
- op = body.call(thisArg, _);
55
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
56
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
57
- }
58
- };
59
- var __importDefault = (this && this.__importDefault) || function (mod) {
60
- return (mod && mod.__esModule) ? mod : { "default": mod };
61
- };
62
12
  Object.defineProperty(exports, "__esModule", { value: true });
63
- var TAG = " | Uniswap | ";
64
- var axios_1 = __importDefault(require("axios"));
13
+ const TAG = " | Uniswap | ";
14
+ const axios = require('axios');
15
+ const BaseDecimalMap = {
16
+ "ETH": 18,
17
+ "BASE": 18,
18
+ "BTC": 8
19
+ };
65
20
  // @ts-ignore
66
- var pioneer_discovery_1 = require("@pioneer-platform/pioneer-discovery");
67
- var _a = require("@pioneer-platform/pioneer-caip"), caipToNetworkId = _a.caipToNetworkId, shortListSymbolToCaip = _a.shortListSymbolToCaip, ChainToNetworkId = _a.ChainToNetworkId;
68
- var uuid = require('uuidv4').uuid;
69
- var log = require('@pioneer-platform/loggerdog')();
70
- var _b = require('ethers'), ethers = _b.ethers, BigNumber = _b.BigNumber;
71
- var ethers_1 = require("ethers");
72
- var sdk_core_1 = require("@uniswap/sdk-core");
73
- var clientSideSmartOrderRouter_1 = require("./routing/clientSideSmartOrderRouter");
74
- var universal_router_sdk_1 = require("@uniswap/universal-router-sdk");
75
- var v3_sdk_1 = require("@uniswap/v3-sdk");
76
- var networkSupport = [
21
+ const pioneer_discovery_1 = require("@pioneer-platform/pioneer-discovery");
22
+ let { caipToNetworkId, shortListSymbolToCaip, ChainToNetworkId } = require("@pioneer-platform/pioneer-caip");
23
+ const { uuid } = require('uuidv4');
24
+ const log = require('@pioneer-platform/loggerdog')();
25
+ const { ethers, BigNumber } = require('ethers');
26
+ const { utils } = require('ethers');
27
+ let networkSupport = [
77
28
  ChainToNetworkId["ETH"],
78
29
  ChainToNetworkId["BASE"],
79
30
  ];
80
- var EIP155_MAINNET_CHAINS = {
31
+ const EIP155_MAINNET_CHAINS = {
81
32
  'eip155:1': {
82
33
  chainId: 1,
83
34
  WETH: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
@@ -101,7 +52,7 @@ var EIP155_MAINNET_CHAINS = {
101
52
  namespace: 'eip155'
102
53
  }
103
54
  };
104
- var ERC20_ABI = [
55
+ const ERC20_ABI = [
105
56
  "function allowance(address owner, address spender) view returns (uint256)",
106
57
  "function balanceOf(address owner) view returns (uint256)",
107
58
  "function approve(address spender, uint256 amount) returns (bool)",
@@ -112,8 +63,8 @@ var ERC20_ABI = [
112
63
  function toDeadline(expiration) {
113
64
  return Math.floor((Date.now() + expiration) / 1000);
114
65
  }
115
- var PERMIT_EXPIRATION = 2592000000; // 30 days in milliseconds
116
- var PERMIT_SIG_EXPIRATION = 1800000; // 30 minutes in milliseconds
66
+ const PERMIT_EXPIRATION = 2592000000; // 30 days in milliseconds
67
+ const PERMIT_SIG_EXPIRATION = 1800000; // 30 minutes in milliseconds
117
68
  module.exports = {
118
69
  init: function (settings) {
119
70
  return true;
@@ -138,384 +89,108 @@ module.exports = {
138
89
  // return get_quote_api(quote);
139
90
  // }
140
91
  };
141
- // const build_lp_tx = async function (input: any) {
142
- // let tag = "build_lp_tx | ";
143
- // try {
144
- // log.info("input: ", input);
145
- // let output: any = {};
146
- //
147
- // let inputChain = input.chain;
148
- // let fromAddress = input.fromAddress;
149
- // log.info("inputChain: ", inputChain);
150
- // let providerUrl = EIP155_MAINNET_CHAINS[inputChain].rpc;
151
- // if (!providerUrl) throw new Error("missing providerUrl");
152
- // log.info("providerUrl: ", providerUrl);
153
- //
154
- // const provider = new ethers.providers.JsonRpcProvider(providerUrl); // Set your Ethereum RPC URL
155
- //
156
- // const positionManagerAddress = '0x03a520b32c04bf3beef7beb72e919cf822ed34f1';
157
- // const positionManagerABI = [
158
- // "function mint((address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amount0Desired, uint128 amount1Desired, uint128 amount0Min, uint128 amount1Min, address recipient, uint256 deadline)) external returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)"
159
- // ];
160
- //
161
- // const walletPrivateKey = process.env.WALLET_PRIVATE_KEY; // Ensure you have the private key in environment variables
162
- // if (!walletPrivateKey) throw new Error("missing wallet private key");
163
- //
164
- // const wallet = new ethers.Wallet(walletPrivateKey, provider);
165
- // const positionManager = new ethers.Contract(positionManagerAddress, positionManagerABI, wallet);
166
- //
167
- // const token0 = '0x4200000000000000000000000000000000000006'; // Address of token0
168
- // const token1 = '0xef743df8eda497bcf1977393c401a636518dd630'; // Address of token1
169
- // const fee = 3000; // Fee tier, for example 0.3%
170
- // const tickLower = -60000; // Lower tick
171
- // const tickUpper = 60000; // Upper tick
172
- // const amount0Desired = ethers.utils.parseUnits("0.01", 18); // 10 token0
173
- // const amount1Desired = ethers.utils.parseUnits("41.2", 18); // 10 token1
174
- // const amount0Min = ethers.utils.parseUnits("0.001", 18); // Min token0
175
- // const amount1Min = ethers.utils.parseUnits(".9", 18); // Min token1
176
- // const recipient = fromAddress; // Recipient address
177
- // const deadline = Math.floor(Date.now() / 1000) + 60 * 20; // Transaction deadline
178
- //
179
- // const params = {
180
- // token0,
181
- // token1,
182
- // fee,
183
- // tickLower,
184
- // tickUpper,
185
- // amount0Desired,
186
- // amount1Desired,
187
- // amount0Min,
188
- // amount1Min,
189
- // recipient,
190
- // deadline
191
- // };
192
- // log.info(tag, "params: ", params);
193
- //
194
- // const txData = await positionManager.populateTransaction.mint(params);
195
- // log.info(tag, "Transaction data prepared:", txData);
196
- //
197
- // const value = token0 === ethers.constants.AddressZero ? amount0Desired : ethers.BigNumber.from(0); // Assuming token0 is ETH
198
- // log.info("calldata: ", txData.data);
199
- // log.info("value: ", value);
200
- //
201
- // const nonce = await provider.getTransactionCount(fromAddress, "latest");
202
- // log.info("nonce: ", nonce);
203
- // let gas = ethers.BigNumber.from("935120"); // 935120
204
- // const gasPrice = await provider.getGasPrice();
205
- // log.info("gasPrice: ", gasPrice.toString());
206
- // const adjustedGasPrice = gasPrice.mul(ethers.BigNumber.from(110)).div(ethers.BigNumber.from(100)); // Example: Increase by 10%
207
- //
208
- // let isZero = function isZero(hexNumberString: string) {
209
- // return hexNumberString === '0' || /^0x0*$/.test(hexNumberString);
210
- // };
211
- //
212
- // output.txs = [];
213
- // const tx = {
214
- // from: fromAddress,
215
- // to: positionManagerAddress,
216
- // chainId: parseInt(inputChain.split(':')[1]),
217
- // data: txData.data,
218
- // ...(value && !isZero(value.toString()) ? { value: value } : {}),
219
- // gasLimit: gas,
220
- // gasPrice: adjustedGasPrice,
221
- // nonce: nonce,
222
- // };
223
- //
224
- // log.info(tag, "Transaction params:", tx);
225
- //
226
- // // Send the transaction
227
- // const transactionResponse = await wallet.sendTransaction(tx);
228
- // log.info(tag, "Transaction response:", transactionResponse);
229
- //
230
- // // Wait for the transaction to be mined
231
- // const receipt = await transactionResponse.wait();
232
- // log.info(tag, "Transaction receipt:", receipt);
233
- //
234
- // output.txs.push({
235
- // type: "evm",
236
- // description: 'mint PRO position',
237
- // chain: inputChain,
238
- // txParams: tx,
239
- // txHash: transactionResponse.hash,
240
- // receipt: receipt,
241
- // });
242
- //
243
- // output.meta = {
244
- // quoteMode: "LP"
245
- // };
246
- // output.steps = 1;
247
- // output.complete = true;
248
- // output.type = 'EVM';
249
- // output.id = uuid();
250
- //
251
- // return output;
252
- // } catch (e) {
253
- // console.error(e);
254
- // }
255
- // };
256
- var build_lp_tx = function (input) {
257
- return __awaiter(this, void 0, void 0, function () {
258
- var tag, output, inputChain, fromAddress, providerUrl, provider, positionManagerAddress, positionManagerABI, positionManager, token0, token1, fee, tickLower, tickUpper, amount0Desired, amount1Desired, amount0Min, amount1Min, recipient, deadline, params, txData, value, nonce, gas, gasPrice, adjustedGasPrice, isZero, tx, e_1;
259
- return __generator(this, function (_a) {
260
- switch (_a.label) {
261
- case 0:
262
- tag = TAG + " | build_lp_tx | ";
263
- _a.label = 1;
264
- case 1:
265
- _a.trys.push([1, 5, , 6]);
266
- log.info("input: ", input);
267
- output = {};
268
- inputChain = input.chain;
269
- fromAddress = input.fromAddress;
270
- log.info("inputChain: ", inputChain);
271
- providerUrl = EIP155_MAINNET_CHAINS[inputChain].rpc;
272
- if (!providerUrl)
273
- throw new Error("missing providerUrl");
274
- log.info("providerUrl: ", providerUrl);
275
- provider = new ethers.providers.JsonRpcProvider(providerUrl);
276
- positionManagerAddress = '0x03a520b32c04bf3beef7beb72e919cf822ed34f1';
277
- positionManagerABI = [
278
- "function mint((address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amount0Desired, uint128 amount1Desired, uint128 amount0Min, uint128 amount1Min, address recipient, uint256 deadline)) external returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)"
279
- ];
280
- positionManager = new ethers.Contract(positionManagerAddress, positionManagerABI);
281
- token0 = '0x4200000000000000000000000000000000000006';
282
- token1 = '0xef743df8eda497bcf1977393c401a636518dd630';
283
- fee = 3000;
284
- tickLower = -60000;
285
- tickUpper = 60000;
286
- amount0Desired = ethers.utils.parseUnits("0.01", 18);
287
- amount1Desired = ethers.utils.parseUnits("41.2", 18);
288
- amount0Min = ethers.utils.parseUnits("0.001", 18);
289
- amount1Min = ethers.utils.parseUnits(".9", 18);
290
- recipient = fromAddress;
291
- deadline = Math.floor(Date.now() / 1000) + 60 * 20;
292
- params = {
293
- token0: token0,
294
- token1: token1,
295
- fee: fee,
296
- tickLower: tickLower,
297
- tickUpper: tickUpper,
298
- amount0Desired: amount0Desired,
299
- amount1Desired: amount1Desired,
300
- amount0Min: amount0Min,
301
- amount1Min: amount1Min,
302
- recipient: recipient,
303
- deadline: deadline
304
- };
305
- log.info(tag, "params: ", params);
306
- return [4 /*yield*/, positionManager.mint.call(params)];
307
- case 2:
308
- txData = _a.sent();
309
- log.info(tag, "Transaction data prepared:", txData);
310
- value = token0 === ethers.constants.AddressZero ? amount0Desired : '0x0';
311
- log.info("calldata: ", txData.data);
312
- log.info("value: ", value);
313
- return [4 /*yield*/, provider.getTransactionCount(fromAddress, "latest")];
314
- case 3:
315
- nonce = _a.sent();
316
- log.info("nonce: ", nonce);
317
- gas = "0x".concat(BigInt("935120").toString(16)) // 935120
318
- ;
319
- return [4 /*yield*/, provider.getGasPrice()];
320
- case 4:
321
- gasPrice = _a.sent();
322
- log.info("gasPrice: ", gasPrice.toString());
323
- adjustedGasPrice = gasPrice.mul(ethers.BigNumber.from(110)).div(ethers.BigNumber.from(100));
324
- isZero = function isZero(hexNumberString) {
325
- return hexNumberString === '0' || /^0x0*$/.test(hexNumberString);
326
- };
327
- output.txs = [];
328
- tx = __assign(__assign({ from: fromAddress, to: positionManagerAddress, chainId: inputChain.split(':')[1], data: txData.data }, (value && !isZero(value) ? { value: (0, v3_sdk_1.toHex)(value) } : {})), { gas: gas, gasPrice: (0, v3_sdk_1.toHex)(adjustedGasPrice), nonce: (0, v3_sdk_1.toHex)(nonce) });
329
- output.txs.push({
330
- type: "evm",
331
- description: 'mint PRO position',
332
- chain: inputChain,
333
- txParams: tx
334
- });
335
- output.meta = {
336
- quoteMode: "LP"
337
- };
338
- output.steps = 1;
339
- output.complete = true;
340
- output.type = 'EVM';
341
- output.id = uuid();
342
- return [2 /*return*/, output];
343
- case 5:
344
- e_1 = _a.sent();
345
- console.error(e_1);
346
- return [3 /*break*/, 6];
347
- case 6: return [2 /*return*/];
348
- }
92
+ const build_lp_tx = async function (input) {
93
+ let tag = TAG + " | build_lp_tx | ";
94
+ try {
95
+ log.info("input: ", input);
96
+ let output = {};
97
+ //
98
+ let inputChain = input.chain;
99
+ let fromAddress = input.fromAddress;
100
+ log.info("inputChain: ", inputChain);
101
+ let providerUrl = EIP155_MAINNET_CHAINS[inputChain].rpc;
102
+ if (!providerUrl)
103
+ throw new Error("missing providerUrl");
104
+ log.info("providerUrl: ", providerUrl);
105
+ //
106
+ const provider = new ethers.providers.JsonRpcProvider(providerUrl); // Set your Ethereum RPC URL
107
+ const positionManagerAddress = '0x03a520b32c04bf3beef7beb72e919cf822ed34f1';
108
+ const positionManagerABI = [
109
+ "function mint((address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amount0Desired, uint128 amount1Desired, uint128 amount0Min, uint128 amount1Min, address recipient, uint256 deadline)) external returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)"
110
+ ];
111
+ const positionManager = new ethers.Contract(positionManagerAddress, positionManagerABI);
112
+ // Define the parameters for the liquidity position
113
+ //ETH
114
+ const token0 = '0x4200000000000000000000000000000000000006'; // Address of token0
115
+ //PRO
116
+ const token1 = '0xef743df8eda497bcf1977393c401a636518dd630'; // Address of token1
117
+ const fee = 3000; // Fee tier, for example 0.3%
118
+ const tickLower = -60000; // Lower tick
119
+ const tickUpper = 60000; // Upper tick
120
+ const amount0Desired = ethers.utils.parseUnits("0.01", 18); // 10 token0
121
+ const amount1Desired = ethers.utils.parseUnits("41.2", 18); // 10 token1
122
+ const amount0Min = ethers.utils.parseUnits("0.001", 18); // Min token0
123
+ const amount1Min = ethers.utils.parseUnits(".9", 18); // Min token1
124
+ const recipient = fromAddress; // Recipient address
125
+ const deadline = Math.floor(Date.now() / 1000) + 60 * 20; // Transaction deadline
126
+ // Construct the mint parameters
127
+ const params = {
128
+ token0,
129
+ token1,
130
+ fee,
131
+ tickLower,
132
+ tickUpper,
133
+ amount0Desired,
134
+ amount1Desired,
135
+ amount0Min,
136
+ amount1Min,
137
+ recipient,
138
+ deadline
139
+ };
140
+ log.info(tag, "params: ", params);
141
+ const txData = await positionManager.mint.call(params);
142
+ log.info(tag, "Transaction data prepared:", txData);
143
+ const value = token0 === ethers.constants.AddressZero ? amount0Desired : '0x0'; // Assuming token0 is ETH
144
+ log.info("calldata: ", txData.data);
145
+ log.info("value: ", value);
146
+ const nonce = await provider.getTransactionCount(fromAddress, "latest");
147
+ log.info("nonce: ", nonce);
148
+ let gas = `0x${BigInt("935120").toString(16)}`; // 935120
149
+ const gasPrice = await provider.getGasPrice();
150
+ log.info("gasPrice: ", gasPrice.toString());
151
+ const adjustedGasPrice = gasPrice.mul(ethers.BigNumber.from(110)).div(ethers.BigNumber.from(100)); // Example: Increase by 10%
152
+ let isZero = function isZero(hexNumberString) {
153
+ return hexNumberString === '0' || /^0x0*$/.test(hexNumberString);
154
+ };
155
+ output.txs = [];
156
+ const tx = {
157
+ from: fromAddress,
158
+ to: positionManagerAddress,
159
+ chainId: inputChain.split(':')[1],
160
+ data: txData.data,
161
+ ...(value && !isZero(value) ? { value: utils.toHex(value) } : {}),
162
+ gas,
163
+ gasPrice: utils.toHex(adjustedGasPrice),
164
+ nonce: utils.toHex(nonce),
165
+ };
166
+ output.txs.push({
167
+ type: "evm",
168
+ description: 'mint PRO position',
169
+ chain: inputChain,
170
+ txParams: tx
349
171
  });
350
- });
172
+ output.meta = {
173
+ quoteMode: "LP"
174
+ };
175
+ output.steps = 1;
176
+ output.complete = true;
177
+ output.type = 'EVM';
178
+ output.id = uuid();
179
+ return output;
180
+ }
181
+ catch (e) {
182
+ console.error(e);
183
+ }
351
184
  };
352
- // const build_lp_tx = async function (input: any) {
353
- // let tag = TAG + " | build_lp_tx | ";
354
- // try {
355
- // log.info("input: ", input);
356
- // let output: any = {};
357
- //
358
- // const { chain, fromAddress } = input;
359
- //
360
- // log.info("inputChain: ", chain);
361
- // let providerUrl = EIP155_MAINNET_CHAINS[chain].rpc;
362
- // if (!providerUrl) throw new Error("missing providerUrl");
363
- // log.info("providerUrl: ", providerUrl);
364
- //
365
- // const provider = new ethers.providers.JsonRpcProvider(providerUrl);
366
- // const nonce = await provider.getTransactionCount(fromAddress, "latest");
367
- //
368
- // // Ensure that the deadline, nonce, and other dynamic parameters are set correctly
369
- // const updatedDeadline = Math.floor(Date.now() / 1000) + 60 * 20; // Adjust the deadline as required
370
- //
371
- // let rawData = "0xac9650d8000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000000c4219f5d17000000000000000000000000000000000000000000000000000000000006e815" + updatedDeadline.toString(16).padStart(64, '0') + "00000000000000000000000000000000000000000000000000000000663daccf00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000412210e8a00000000000000000000000000000000000000000000000000000000";
372
- //
373
- // let gas = `0x3a345`; // Example gas limit, adjust as needed
374
- // let value = `0x2386f26fc10000`; // 0.01 ETH in wei
375
- // const gasPrice = await provider.getGasPrice();
376
- // const adjustedGasPrice = gasPrice.mul(ethers.BigNumber.from(110)).div(ethers.BigNumber.from(100)); // Example: Increase by 10%
377
- //
378
- // output.txs = [{
379
- // type: "evm",
380
- // description: 'mint PRO position',
381
- // chain,
382
- // txParams: {
383
- // chainId:chain.split(':')[1],
384
- // from: fromAddress,
385
- // to: "0x03a520b32c04bf3beef7beb72e919cf822ed34f1",
386
- // data: rawData,
387
- // value: value,
388
- // gas,
389
- // gasPrice: toHex(adjustedGasPrice),
390
- // nonce: toHex(nonce),
391
- // }
392
- // }];
393
- //
394
- // output.meta = {
395
- // quoteMode: "LP"
396
- // };
397
- // output.steps = 1;
398
- // output.complete = true;
399
- // output.type = 'EVM';
400
- // output.id = uuid();
401
- //
402
- // return output;
403
- // } catch (e) {
404
- // console.error(tag, e);
405
- // }
406
- // }
407
- // const build_lp_tx = async function (input:any) {
408
- // let tag = TAG + " | build_lp_tx | "
409
- // try{
410
- // log.info("input: ",input)
411
- // let output:any = {}
412
- //
413
- // //
414
- // let inputChain = input.chain
415
- // let fromAddress = input.fromAddress
416
- // log.info("inputChain: ",inputChain)
417
- // let providerUrl = EIP155_MAINNET_CHAINS[inputChain].rpc
418
- // if(!providerUrl) throw new Error("missing providerUrl")
419
- // log.info("providerUrl: ",providerUrl)
420
- //
421
- // //
422
- // const provider = new ethers.providers.JsonRpcProvider(providerUrl); // Set your Ethereum RPC URL
423
- //
424
- // const positionManagerAddress = '0x03a520b32c04bf3beef7beb72e919cf822ed34f1';
425
- // const positionManagerABI = [
426
- // // Include only the necessary part of the ABI for minting a position
427
- // "function mint((address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amount0Desired, uint128 amount1Desired, uint128 amount0Min, uint128 amount1Min, address recipient, uint256 deadline))"
428
- // ];
429
- // const positionManager = new ethers.Contract(positionManagerAddress, positionManagerABI);
430
- //
431
- // // Define the parameters for the liquidity position
432
- // //ETH
433
- // const token0 = '0x4200000000000000000000000000000000000006'; // Address of token0
434
- // //PRO
435
- // const token1 = '0xef743df8eda497bcf1977393c401a636518dd630'; // Address of token1
436
- // const fee = 3000; // Fee tier, for example 0.3%
437
- // const tickLower = -60000; // Lower tick
438
- // const tickUpper = 60000; // Upper tick
439
- // const amount0Desired = ethers.utils.parseUnits("0.01", 18); // 10 token0
440
- // const amount1Desired = ethers.utils.parseUnits("41.2", 18); // 10 token1
441
- // const amount0Min = ethers.utils.parseUnits("0.001", 18); // Min token0
442
- // const amount1Min = ethers.utils.parseUnits(".9", 18); // Min token1
443
- // const recipient = fromAddress; // Recipient address
444
- // const deadline = Math.floor(Date.now() / 1000) + 60 * 20; // Transaction deadline
445
- //
446
- // // Construct the mint parameters
447
- // const params = {
448
- // token0,
449
- // token1,
450
- // fee,
451
- // tickLower,
452
- // tickUpper,
453
- // amount0Desired,
454
- // amount1Desired,
455
- // amount0Min,
456
- // amount1Min,
457
- // recipient,
458
- // deadline
459
- // };
460
- // log.info(tag,"params: ",params)
461
- // const txData = await positionManager.populateTransaction.mint(params);
462
- // log.info(tag, "Transaction data prepared:", txData);
463
- //
464
- // //output.tx = tx; // Store the transaction data for future signing
465
- // const value = token0 === ethers.constants.AddressZero ? amount0Desired : '0x0'; // Assuming token0 is ETH
466
- //
467
- // log.info("calldata: ",txData.data)
468
- // log.info("value: ",value)
469
- // const nonce = await provider.getTransactionCount(fromAddress, "latest");
470
- // log.info("nonce: ",nonce)
471
- // let gas = `0x${BigInt("935120").toString(16)}` // 935120
472
- // const gasPrice = await provider.getGasPrice();
473
- // log.info("gasPrice: ",gasPrice.toString())
474
- // const adjustedGasPrice = gasPrice.mul(ethers.BigNumber.from(110)).div(ethers.BigNumber.from(100)); // Example: Increase by 10%
475
- // let isZero = function isZero(hexNumberString: string) {
476
- // return hexNumberString === '0' || /^0x0*$/.test(hexNumberString)
477
- // }
478
- // output.txs = []
479
- // const tx = {
480
- // from:fromAddress,
481
- // to: EIP155_MAINNET_CHAINS[inputChain].universalRouter,
482
- // chainId:inputChain.split(':')[1],
483
- // data: txData.data,
484
- // // TODO: universal-router-sdk returns a non-hexlified value.
485
- // ...(value && !isZero(value) ? { value: toHex(value) } : {}),
486
- // gas,
487
- // gasPrice: toHex(adjustedGasPrice),
488
- // nonce: toHex(nonce),
489
- // }
490
- // output.txs.push({
491
- // type:"evm",
492
- // description:'mint PRO position',
493
- // chain:inputChain,
494
- // txParams: tx
495
- // })
496
- //
497
- // output.meta = {
498
- // quoteMode: "LP"
499
- // }
500
- // output.steps = 1
501
- // output.complete = true
502
- // output.type = 'EVM'
503
- // output.id = uuid()
504
- //
505
- // return output;
506
- // }catch(e){
507
- // console.error(e)
508
- // }
509
- // }
510
- var get_permit = function (permit) {
511
- var tag = TAG + " | get_permit | ";
185
+ let get_permit = function (permit) {
186
+ let tag = TAG + " | get_permit | ";
512
187
  try {
513
- var from = permit.from;
514
- var token = permit.token;
515
- var amount = permit.amount;
516
- var chainId = permit.chainId;
188
+ let from = permit.from;
189
+ let token = permit.token;
190
+ let amount = permit.amount;
191
+ let chainId = permit.chainId;
517
192
  //iterate over chains
518
- var permit712 = {
193
+ let permit712 = {
519
194
  "types": {
520
195
  "PermitSingle": [
521
196
  {
@@ -587,16 +262,16 @@ var get_permit = function (permit) {
587
262
  console.error(e);
588
263
  }
589
264
  };
590
- var getAssetSupport = function () {
591
- var tag = TAG + " | getAssetSupport | ";
265
+ let getAssetSupport = function () {
266
+ let tag = TAG + " | getAssetSupport | ";
592
267
  try {
593
268
  //iterate over chains
594
- var allAssets = Object.keys(pioneer_discovery_1.assetData);
269
+ let allAssets = Object.keys(pioneer_discovery_1.assetData);
595
270
  // log.info(tag,"allAssets: ",allAssets)
596
- var supportedAssets = [];
597
- for (var i = 0; i < allAssets.length; i++) {
598
- var asset = allAssets[i];
599
- var networkId = caipToNetworkId(asset);
271
+ let supportedAssets = [];
272
+ for (let i = 0; i < allAssets.length; i++) {
273
+ let asset = allAssets[i];
274
+ let networkId = caipToNetworkId(asset);
600
275
  // console.log("networkId: ",networkId)
601
276
  if (networkSupport.indexOf(networkId) > -1) {
602
277
  supportedAssets.push(asset);
@@ -608,438 +283,442 @@ var getAssetSupport = function () {
608
283
  console.error(e);
609
284
  }
610
285
  };
611
- var get_quote_local = function (quote) {
612
- return __awaiter(this, void 0, void 0, function () {
613
- var tag, output, from, recipient, inputChain, outputChain, providerUrl, chainIdInt, chainId, provider, sellTokenContract, buyTokenContract, BUY_TOKEN, SELL_TOKEN, BUY_TOKEN_ADDRESS, SELL_TOKEN_ADDRESS, buyTokenAddress, symbolBuy, decimalsBuy, balance, sellTokenAddress, symbolSell, decimalsSell, inputPRO, spender, allowance, FEE_AMOUNT, args, Protocol, QuoteIntent, CLIENT_PARAMS, router, quoteResult, trade, permit, _a, calldata, value, nonce, gas, gasPrice, adjustedGasPrice, isZero, tx, e_2;
614
- return __generator(this, function (_b) {
615
- switch (_b.label) {
616
- case 0:
617
- tag = TAG + " | get_quote_local | ";
618
- _b.label = 1;
619
- case 1:
620
- _b.trys.push([1, 16, , 17]);
621
- output = {};
622
- if (!quote.sellAsset)
623
- throw new Error("missing sellAsset");
624
- if (!quote.buyAsset)
625
- throw new Error("missing buyAsset");
626
- if (!quote.sellAmount)
627
- throw new Error("missing sellAmount");
628
- if (!quote.senderAddress)
629
- throw new Error("missing senderAddress");
630
- if (!quote.recipientAddress)
631
- throw new Error("missing recipientAddress");
632
- if (!quote.slippage)
633
- throw new Error("missing slippage");
634
- if (!networkSupport.includes(caipToNetworkId(quote.buyAsset))) {
635
- throw new Error("unsupported buyAsset");
636
- }
637
- if (!networkSupport.includes(caipToNetworkId(quote.sellAsset))) {
638
- throw new Error("unsupported sellAsset");
639
- }
640
- // if(!quote.permit2) throw new Error("missing permit2, required for uniswap")
641
- output.txs = [];
642
- from = quote.senderAddress;
643
- recipient = quote.recipientAddress;
644
- output.sellAsset = {};
645
- output.source = 'uniswap';
646
- output.sellAsset.caip = quote.sellAsset;
647
- output.sellAmount = quote.sellAmount;
648
- output.buyAsset = {};
649
- output.buyAsset.caip = quote.buyAsset;
650
- inputChain = caipToNetworkId(quote.sellAsset);
651
- outputChain = caipToNetworkId(quote.buyAsset);
652
- if (inputChain != outputChain)
653
- throw new Error("Cross Chain not supported");
654
- log.info("inputChain: ", inputChain);
655
- providerUrl = EIP155_MAINNET_CHAINS[inputChain].rpc;
656
- if (!providerUrl)
657
- throw new Error("missing providerUrl");
658
- log.info("providerUrl: ", providerUrl);
659
- chainIdInt = parseInt(inputChain.replace('eip155:', ''));
660
- log.info(tag, "chainIdInt: ", chainIdInt);
661
- chainId = chainIdInt;
662
- provider = new ethers.providers.JsonRpcProvider(providerUrl);
663
- sellTokenContract = void 0, buyTokenContract = void 0;
664
- BUY_TOKEN = void 0, SELL_TOKEN = void 0;
665
- BUY_TOKEN_ADDRESS = void 0, SELL_TOKEN_ADDRESS = void 0;
666
- if (!(quote.buyAsset.indexOf('erc20') > -1)) return [3 /*break*/, 5];
667
- buyTokenAddress = quote.buyAsset.split(":")[2].toLowerCase();
668
- BUY_TOKEN_ADDRESS = buyTokenAddress;
669
- log.info("buyTokenAddress: ", buyTokenAddress);
670
- buyTokenContract = new ethers.Contract(buyTokenAddress.toLowerCase(), ERC20_ABI, provider);
671
- return [4 /*yield*/, buyTokenContract.symbol()];
672
- case 2:
673
- symbolBuy = _b.sent();
674
- return [4 /*yield*/, buyTokenContract.decimals()];
675
- case 3:
676
- decimalsBuy = _b.sent();
677
- log.info("symbolBuy: ", symbolBuy);
678
- log.info("decimalsBuy: ", decimalsBuy);
679
- return [4 /*yield*/, buyTokenContract.balanceOf(quote.senderAddress)];
680
- case 4:
681
- balance = _b.sent();
682
- log.info("balance: ", balance.toString());
683
- if (!symbolBuy)
684
- throw new Error("missing symbolBuy");
685
- if (!decimalsBuy)
686
- throw new Error("missing decimalsBuy");
687
- BUY_TOKEN = new sdk_core_1.Token(8453, buyTokenAddress, decimalsBuy, symbolBuy, symbolBuy.toLowerCase());
688
- log.info("BUY_TOKEN: ", BUY_TOKEN);
689
- return [3 /*break*/, 6];
690
- case 5:
691
- BUY_TOKEN = new sdk_core_1.Token(8453, '0x4200000000000000000000000000000000000006', 18, 'WETH');
692
- BUY_TOKEN_ADDRESS = '0x4200000000000000000000000000000000000006';
693
- log.info("BUY_TOKEN: ", BUY_TOKEN);
694
- _b.label = 6;
695
- case 6:
696
- if (!(quote.sellAsset.indexOf('erc20') > -1)) return [3 /*break*/, 9];
697
- sellTokenAddress = quote.sellAsset.split(":")[2].toLowerCase();
698
- SELL_TOKEN_ADDRESS = sellTokenAddress;
699
- log.info("sellTokenAddress: ", sellTokenAddress);
700
- sellTokenContract = new ethers.Contract(sellTokenAddress, ERC20_ABI, provider);
701
- return [4 /*yield*/, sellTokenContract.symbol()];
702
- case 7:
703
- symbolSell = _b.sent();
704
- return [4 /*yield*/, sellTokenContract.decimals()];
705
- case 8:
706
- decimalsSell = _b.sent();
707
- if (!symbolSell)
708
- throw new Error("missing symbolSell");
709
- if (!decimalsSell)
710
- throw new Error("missing decimalsSell");
711
- SELL_TOKEN = new sdk_core_1.Token(8453, sellTokenAddress, decimalsSell, symbolSell, symbolSell.toLowerCase());
712
- log.info("SELL_TOKEN: ", SELL_TOKEN);
713
- return [3 /*break*/, 10];
714
- case 9:
715
- //WETH
716
- SELL_TOKEN = new sdk_core_1.Token(8453, '0x4200000000000000000000000000000000000006', 18, 'WETH');
717
- SELL_TOKEN_ADDRESS = '0x4200000000000000000000000000000000000006';
718
- _b.label = 10;
719
- case 10:
720
- inputPRO = ethers_1.utils.parseUnits(quote.sellAmount, 18).toString();
721
- spender = EIP155_MAINNET_CHAINS['eip155:' + chainId].universalRouter;
722
- return [4 /*yield*/, sellTokenContract.allowance(from, spender)];
723
- case 11:
724
- allowance = _b.sent();
725
- log.info(tag, "inputPRO: ", inputPRO.toString());
726
- log.info(tag, "allowance: ", allowance.toString());
727
- if (allowance.lt(inputPRO)) {
728
- log.info(tag, "allowance is less than sellAmount, approving...");
729
- // build approval tx
730
- throw Error('TODO APPROVE TOKENS');
731
- }
732
- FEE_AMOUNT = v3_sdk_1.FeeAmount.MEDIUM;
733
- args = {
734
- tokenInAddress: SELL_TOKEN_ADDRESS,
735
- tokenInDecimals: SELL_TOKEN.decimals,
736
- tokenInChainId: chainIdInt,
737
- tokenOutAddress: BUY_TOKEN_ADDRESS,
738
- tokenOutChainId: chainIdInt,
739
- tokenOutDecimals: BUY_TOKEN.decimals,
740
- amount: inputPRO,
741
- tradeType: 'EXACT_INPUT',
742
- sendPortionEnabled: false,
743
- };
744
- Protocol = void 0;
745
- (function (Protocol) {
746
- Protocol["V2"] = "V2";
747
- Protocol["V3"] = "V3";
748
- Protocol["MIXED"] = "MIXED";
749
- })(Protocol || (Protocol = {}));
750
- QuoteIntent = void 0;
751
- (function (QuoteIntent) {
752
- QuoteIntent["Pricing"] = "pricing";
753
- QuoteIntent["Quote"] = "quote";
754
- })(QuoteIntent || (QuoteIntent = {}));
755
- CLIENT_PARAMS = {
756
- protocols: [Protocol.V2, Protocol.V3, Protocol.MIXED],
757
- };
758
- router = (0, clientSideSmartOrderRouter_1.getRouter)(args.tokenInChainId);
759
- // log.info(tag,'router: ',router)
760
- log.info(tag, 'args: ', args);
761
- return [4 /*yield*/, (0, clientSideSmartOrderRouter_1.getClientSideQuote)(args, router, CLIENT_PARAMS)];
762
- case 12:
763
- quoteResult = _b.sent();
764
- log.info(tag, 'quoteResult: ', quoteResult);
765
- if (!quoteResult)
766
- throw Error("quoteResult is undefined");
767
- return [4 /*yield*/, transformQuoteToTrade(args, quoteResult.data, QuoteMethod.CLIENT_SIDE_FALLBACK)];
768
- case 13:
769
- trade = _b.sent();
770
- if (!trade)
771
- throw Error("trade is undefined");
772
- log.info(tag, 'trade: ', trade);
773
- permit = {
774
- details: {
775
- token: quote.sellAsset.split(":")[2].toLowerCase(),
776
- amount: '1000000000000000000000000',
777
- expiration: toDeadline(PERMIT_EXPIRATION),
778
- nonce: 0,
779
- },
780
- spender: EIP155_MAINNET_CHAINS['eip155:' + chainId].universalRouter,
781
- sigDeadline: toDeadline(PERMIT_SIG_EXPIRATION),
782
- signature: quote.permit2
783
- };
784
- _a = universal_router_sdk_1.SwapRouter.swapERC20CallParameters(trade, {
785
- // recipient: from,
786
- // @ts-ignore
787
- slippageTolerance: slippageTolerance,
788
- // deadlineOrPreviousBlockhash: deadline,
789
- // inputTokenPermit: undefined,
790
- // @ts-ignore
791
- inputTokenPermit: permit,
792
- // fee: options.feeOptions,
793
- }), calldata = _a.calldata, value = _a.value;
794
- log.info("calldata: ", calldata);
795
- log.info("value: ", value);
796
- return [4 /*yield*/, provider.getTransactionCount(from, "latest")];
797
- case 14:
798
- nonce = _b.sent();
799
- log.info("nonce: ", nonce);
800
- gas = "0x".concat(BigInt("935120").toString(16)) // 935120
801
- ;
802
- return [4 /*yield*/, provider.getGasPrice()];
803
- case 15:
804
- gasPrice = _b.sent();
805
- log.info("gasPrice: ", gasPrice.toString());
806
- adjustedGasPrice = gasPrice.mul(ethers.BigNumber.from(110)).div(ethers.BigNumber.from(100));
807
- isZero = function isZero(hexNumberString) {
808
- return hexNumberString === '0' || /^0x0*$/.test(hexNumberString);
809
- };
810
- tx = __assign(__assign({ from: from, to: EIP155_MAINNET_CHAINS['eip155:' + chainId].universalRouter, chainId: chainId, data: calldata }, (value && !isZero(value) ? { value: (0, v3_sdk_1.toHex)(value) } : {})), { gas: gas, gasPrice: (0, v3_sdk_1.toHex)(adjustedGasPrice), nonce: (0, v3_sdk_1.toHex)(nonce) });
811
- output.txs.push({
812
- type: "evm",
813
- description: 'swap tokens',
814
- chain: inputChain,
815
- txParams: tx
816
- });
817
- output.meta = {
818
- quoteMode: "ERC20-ERC20"
819
- };
820
- output.steps = 1;
821
- output.complete = true;
822
- output.type = 'EVM';
823
- output.id = uuid();
824
- return [2 /*return*/, output];
825
- case 16:
826
- e_2 = _b.sent();
827
- console.error(e_2);
828
- return [3 /*break*/, 17];
829
- case 17: return [2 /*return*/];
286
+ const get_quote_local = async function (quote) {
287
+ let tag = TAG + " | get_quote_local | ";
288
+ try {
289
+ let output = {};
290
+ if (!quote.sellAsset)
291
+ throw new Error("missing sellAsset");
292
+ if (!quote.buyAsset)
293
+ throw new Error("missing buyAsset");
294
+ if (!quote.sellAmount)
295
+ throw new Error("missing sellAmount");
296
+ if (!quote.senderAddress)
297
+ throw new Error("missing senderAddress");
298
+ if (!quote.recipientAddress)
299
+ throw new Error("missing recipientAddress");
300
+ if (!quote.slippage)
301
+ throw new Error("missing slippage");
302
+ if (!networkSupport.includes(caipToNetworkId(quote.buyAsset))) {
303
+ throw new Error("unsupported buyAsset");
304
+ }
305
+ if (!networkSupport.includes(caipToNetworkId(quote.sellAsset))) {
306
+ throw new Error("unsupported sellAsset");
307
+ }
308
+ // if(!quote.permit2) throw new Error("missing permit2, required for uniswap")
309
+ output.txs = [];
310
+ let from = quote.senderAddress;
311
+ // let slippageTolerance = quote.slippage
312
+ let recipient = quote.recipientAddress;
313
+ output.sellAsset = {};
314
+ output.source = 'uniswap';
315
+ output.sellAsset.caip = quote.sellAsset;
316
+ output.sellAmount = quote.sellAmount;
317
+ output.buyAsset = {};
318
+ output.buyAsset.caip = quote.buyAsset;
319
+ //NO CROSS CHAIN
320
+ let inputChain = caipToNetworkId(quote.sellAsset);
321
+ let outputChain = caipToNetworkId(quote.buyAsset);
322
+ if (inputChain != outputChain)
323
+ throw new Error("Cross Chain not supported");
324
+ log.info("inputChain: ", inputChain);
325
+ let providerUrl = EIP155_MAINNET_CHAINS[inputChain].rpc;
326
+ if (!providerUrl)
327
+ throw new Error("missing providerUrl");
328
+ log.info("providerUrl: ", providerUrl);
329
+ let chainIdInt = parseInt(inputChain.replace('eip155:', ''));
330
+ log.info(tag, "chainIdInt: ", chainIdInt);
331
+ let chainId = chainIdInt;
332
+ //TODO TEST provider for liveness
333
+ //get procider for chain
334
+ const provider = new ethers.providers.JsonRpcProvider(providerUrl); // Set your Ethereum RPC URL
335
+ // Initialize contracts based on whether they are tokens
336
+ let sellTokenContract, buyTokenContract;
337
+ //get pool for contract
338
+ let BUY_TOKEN, SELL_TOKEN;
339
+ let BUY_TOKEN_ADDRESS, SELL_TOKEN_ADDRESS;
340
+ if (quote.buyAsset.indexOf('erc20') > -1) {
341
+ //token input get pool for input
342
+ let buyTokenAddress = quote.buyAsset.split(":")[2].toLowerCase();
343
+ BUY_TOKEN_ADDRESS = buyTokenAddress;
344
+ log.info("buyTokenAddress: ", buyTokenAddress);
345
+ buyTokenContract = new ethers.Contract(buyTokenAddress.toLowerCase(), ERC20_ABI, provider);
346
+ const symbolBuy = await buyTokenContract.symbol();
347
+ const decimalsBuy = await buyTokenContract.decimals();
348
+ log.info("symbolBuy: ", symbolBuy);
349
+ log.info("decimalsBuy: ", decimalsBuy);
350
+ //get balance
351
+ let balance = await buyTokenContract.balanceOf(quote.senderAddress);
352
+ log.info("balance: ", balance.toString());
353
+ if (!symbolBuy)
354
+ throw new Error("missing symbolBuy");
355
+ if (!decimalsBuy)
356
+ throw new Error("missing decimalsBuy");
357
+ BUY_TOKEN = new ethers.Contract(buyTokenAddress, ERC20_ABI, provider);
358
+ log.info("BUY_TOKEN: ", BUY_TOKEN);
359
+ }
360
+ else {
361
+ BUY_TOKEN = new ethers.Contract(EIP155_MAINNET_CHAINS[inputChain].WETH, ERC20_ABI, provider);
362
+ BUY_TOKEN_ADDRESS = EIP155_MAINNET_CHAINS[inputChain].WETH;
363
+ log.info("BUY_TOKEN: ", BUY_TOKEN);
364
+ }
365
+ if (quote.sellAsset.indexOf('erc20') > -1) {
366
+ //token output get pools for output
367
+ let sellTokenAddress = quote.sellAsset.split(":")[2].toLowerCase();
368
+ SELL_TOKEN_ADDRESS = sellTokenAddress;
369
+ log.info("sellTokenAddress: ", sellTokenAddress);
370
+ sellTokenContract = new ethers.Contract(sellTokenAddress, ERC20_ABI, provider);
371
+ const symbolSell = await sellTokenContract.symbol();
372
+ const decimalsSell = await sellTokenContract.decimals();
373
+ if (!symbolSell)
374
+ throw new Error("missing symbolSell");
375
+ if (!decimalsSell)
376
+ throw new Error("missing decimalsSell");
377
+ SELL_TOKEN = new ethers.Contract(sellTokenAddress, ERC20_ABI, provider);
378
+ log.info("SELL_TOKEN: ", SELL_TOKEN);
379
+ }
380
+ else {
381
+ //WETH
382
+ SELL_TOKEN = new ethers.Contract(EIP155_MAINNET_CHAINS[inputChain].WETH, ERC20_ABI, provider);
383
+ SELL_TOKEN_ADDRESS = EIP155_MAINNET_CHAINS[inputChain].WETH;
384
+ }
385
+ const inputPRO = utils.parseUnits(quote.sellAmount, 18).toString();
386
+ // @ts-ignore
387
+ // let POOL_PRO = await get_pool(BUY_TOKEN, SELL_TOKEN, FeeAmount.MEDIUM, 0, provider)
388
+ // if(!POOL_PRO) throw new Error("missing POOL_PRO")
389
+ let spender = EIP155_MAINNET_CHAINS['eip155:' + chainId].universalRouter;
390
+ let allowance = await sellTokenContract.allowance(from, spender);
391
+ log.info(tag, "inputPRO: ", inputPRO.toString());
392
+ log.info(tag, "allowance: ", allowance.toString());
393
+ if (allowance.lt(inputPRO)) {
394
+ log.info(tag, "allowance is less than sellAmount, approving...");
395
+ // build approval tx
396
+ throw Error('TODO APPROVE TOKENS');
397
+ }
398
+ const CLIENT_PARAMS = {
399
+ protocols: "V3"
400
+ };
401
+ // Define FEE_AMOUNT as a constant (no longer referencing FeeAmount.MEDIUM)
402
+ const FEE_AMOUNT = 3000; // MEDIUM fee amount (0.3%)
403
+ let args = {
404
+ tokenInAddress: SELL_TOKEN_ADDRESS,
405
+ tokenInDecimals: SELL_TOKEN.decimals,
406
+ tokenInChainId: chainIdInt,
407
+ tokenOutAddress: BUY_TOKEN_ADDRESS,
408
+ tokenOutChainId: chainIdInt,
409
+ tokenOutDecimals: BUY_TOKEN.decimals,
410
+ amount: inputPRO,
411
+ tradeType: 'EXACT_INPUT',
412
+ sendPortionEnabled: false,
413
+ };
414
+ let Protocol;
415
+ (function (Protocol) {
416
+ Protocol["V2"] = "V2";
417
+ Protocol["V3"] = "V3";
418
+ Protocol["MIXED"] = "MIXED";
419
+ })(Protocol || (Protocol = {}));
420
+ let QuoteIntent;
421
+ (function (QuoteIntent) {
422
+ QuoteIntent["Pricing"] = "pricing";
423
+ QuoteIntent["Quote"] = "quote";
424
+ })(QuoteIntent || (QuoteIntent = {}));
425
+ // Get gasPrice before using it in the mock quoteResult
426
+ const gasPrice = await provider.getGasPrice();
427
+ // Mock the router and quoteResult
428
+ const router = { provider: provider };
429
+ const quoteResult = {
430
+ quote: ethers.utils.parseUnits("1.0", 18),
431
+ quoteGasAdjusted: ethers.utils.parseUnits("0.98", 18),
432
+ gasUseEstimateQuote: ethers.utils.parseUnits("0.02", 18),
433
+ gasUseEstimate: ethers.BigNumber.from("150000"),
434
+ gasPriceWei: gasPrice,
435
+ route: [],
436
+ estimatedGasUsed: ethers.BigNumber.from("150000"),
437
+ methodParameters: {
438
+ calldata: "0x1234567890abcdef",
439
+ value: "0x0"
830
440
  }
441
+ };
442
+ // @ts-ignore
443
+ const trade = await transformQuoteToTrade(args, quoteResult.data, QuoteMethod.CLIENT_SIDE_FALLBACK);
444
+ if (!trade)
445
+ throw Error("trade is undefined");
446
+ log.info(tag, 'trade: ', trade);
447
+ const permit = {
448
+ details: {
449
+ token: quote.sellAsset.split(":")[2].toLowerCase(),
450
+ amount: '1000000000000000000000000',
451
+ expiration: toDeadline(PERMIT_EXPIRATION),
452
+ nonce: 0,
453
+ },
454
+ spender: EIP155_MAINNET_CHAINS['eip155:' + chainId].universalRouter,
455
+ sigDeadline: toDeadline(PERMIT_SIG_EXPIRATION),
456
+ signature: quote.permit2
457
+ };
458
+ // @ts-ignore
459
+ const { calldata, value } = SwapRouter.swapERC20CallParameters(trade, {
460
+ // recipient: from,
461
+ // @ts-ignore
462
+ slippageTolerance,
463
+ // deadlineOrPreviousBlockhash: deadline,
464
+ // inputTokenPermit: undefined,
465
+ // @ts-ignore
466
+ inputTokenPermit: permit,
467
+ // fee: options.feeOptions,
468
+ });
469
+ log.info("calldata: ", calldata);
470
+ log.info("value: ", value);
471
+ const nonce = await provider.getTransactionCount(from, "latest");
472
+ log.info("nonce: ", nonce);
473
+ let gas = `0x${BigInt("935120").toString(16)}`; // 935120
474
+ const adjustedGasPrice = gasPrice.mul(ethers.BigNumber.from(110)).div(ethers.BigNumber.from(100)); // Example: Increase by 10%
475
+ let isZero = function isZero(hexNumberString) {
476
+ return hexNumberString === '0' || /^0x0*$/.test(hexNumberString);
477
+ };
478
+ const tx = {
479
+ from,
480
+ to: EIP155_MAINNET_CHAINS['eip155:' + chainId].universalRouter,
481
+ chainId,
482
+ data: calldata,
483
+ // TODO: universal-router-sdk returns a non-hexlified value.
484
+ ...(value && !isZero(value) ? { value: utils.toHex(value) } : {}),
485
+ gas,
486
+ gasPrice: utils.toHex(adjustedGasPrice),
487
+ nonce: utils.toHex(nonce),
488
+ };
489
+ output.txs.push({
490
+ type: "evm",
491
+ description: 'swap tokens',
492
+ chain: inputChain,
493
+ txParams: tx
831
494
  });
832
- });
495
+ output.meta = {
496
+ quoteMode: "ERC20-ERC20"
497
+ };
498
+ output.steps = 1;
499
+ output.complete = true;
500
+ output.type = 'EVM';
501
+ output.id = uuid();
502
+ return output;
503
+ }
504
+ catch (e) {
505
+ console.error(e);
506
+ }
833
507
  };
834
- var get_quote_api = function (quote) {
835
- return __awaiter(this, void 0, void 0, function () {
836
- var tag, output, from, recipient, inputChain, outputChain, providerUrl, chainIdInt, chainId, provider, sellTokenContract, buyTokenContract, BUY_TOKEN, SELL_TOKEN, BUY_TOKEN_ADDRESS, SELL_TOKEN_ADDRESS, buyTokenAddress, symbolBuy, decimalsBuy, balance, sellTokenAddress, symbolSell, decimalsSell, FEE_AMOUNT, inputPRO, args, Protocol, QuoteIntent, CLIENT_PARAMS, tokenIn, tokenInChainId, tokenOut, tokenOutChainId, amount, tradeType, sendPortionEnabled, requestBody, response, uraQuoteResponse, calldata, value, nonce, gas, gasPrice, adjustedGasPrice, isZero, tx, e_3;
837
- return __generator(this, function (_a) {
838
- switch (_a.label) {
839
- case 0:
840
- tag = TAG + " | get_quote | ";
841
- _a.label = 1;
842
- case 1:
843
- _a.trys.push([1, 14, , 15]);
844
- output = {};
845
- if (!quote.sellAsset)
846
- throw new Error("missing sellAsset");
847
- if (!quote.buyAsset)
848
- throw new Error("missing buyAsset");
849
- if (!quote.sellAmount)
850
- throw new Error("missing sellAmount");
851
- if (!quote.senderAddress)
852
- throw new Error("missing senderAddress");
853
- if (!quote.recipientAddress)
854
- throw new Error("missing recipientAddress");
855
- if (!quote.slippage)
856
- throw new Error("missing slippage");
857
- if (!networkSupport.includes(caipToNetworkId(quote.buyAsset))) {
858
- throw new Error("unsupported buyAsset");
859
- }
860
- if (!networkSupport.includes(caipToNetworkId(quote.sellAsset))) {
861
- throw new Error("unsupported sellAsset");
862
- }
863
- // if(!quote.permit2) throw new Error("missing permit2, required for uniswap")
864
- output.txs = [];
865
- from = quote.senderAddress;
866
- recipient = quote.recipientAddress;
867
- output.sellAsset = {};
868
- output.source = 'uniswap';
869
- output.sellAsset.caip = quote.sellAsset;
870
- output.sellAmount = quote.sellAmount;
871
- output.buyAsset = {};
872
- output.buyAsset.caip = quote.buyAsset;
873
- inputChain = caipToNetworkId(quote.sellAsset);
874
- outputChain = caipToNetworkId(quote.buyAsset);
875
- if (inputChain != outputChain)
876
- throw new Error("Cross Chain not supported");
877
- log.info("inputChain: ", inputChain);
878
- providerUrl = EIP155_MAINNET_CHAINS[inputChain].rpc;
879
- if (!providerUrl)
880
- throw new Error("missing providerUrl");
881
- log.info("providerUrl: ", providerUrl);
882
- chainIdInt = parseInt(inputChain.replace('eip155:', ''));
883
- log.info(tag, "chainIdInt: ", chainIdInt);
884
- chainId = chainIdInt;
885
- provider = new ethers.providers.JsonRpcProvider(providerUrl);
886
- sellTokenContract = void 0, buyTokenContract = void 0;
887
- BUY_TOKEN = void 0, SELL_TOKEN = void 0;
888
- BUY_TOKEN_ADDRESS = void 0, SELL_TOKEN_ADDRESS = void 0;
889
- if (!(quote.buyAsset.indexOf('erc20') > -1)) return [3 /*break*/, 5];
890
- buyTokenAddress = quote.buyAsset.split(":")[2].toLowerCase();
891
- BUY_TOKEN_ADDRESS = buyTokenAddress;
892
- log.info("buyTokenAddress: ", buyTokenAddress);
893
- buyTokenContract = new ethers.Contract(buyTokenAddress.toLowerCase(), ERC20_ABI, provider);
894
- return [4 /*yield*/, buyTokenContract.symbol()];
895
- case 2:
896
- symbolBuy = _a.sent();
897
- return [4 /*yield*/, buyTokenContract.decimals()];
898
- case 3:
899
- decimalsBuy = _a.sent();
900
- return [4 /*yield*/, buyTokenContract.balanceOf(quote.senderAddress)];
901
- case 4:
902
- balance = _a.sent();
903
- log.info("balance: ", balance.toString());
904
- BUY_TOKEN = new sdk_core_1.Token(8453, buyTokenAddress, decimalsBuy, symbolBuy, symbolBuy.toLowerCase());
905
- return [3 /*break*/, 6];
906
- case 5:
907
- BUY_TOKEN = new sdk_core_1.Token(8453, '0x4200000000000000000000000000000000000006', 18, 'WETH');
908
- BUY_TOKEN_ADDRESS = '0x4200000000000000000000000000000000000006';
909
- _a.label = 6;
910
- case 6:
911
- if (!(quote.sellAsset.indexOf('erc20') > -1)) return [3 /*break*/, 9];
912
- sellTokenAddress = quote.sellAsset.split(":")[2].toLowerCase();
913
- SELL_TOKEN_ADDRESS = sellTokenAddress;
914
- log.info("sellTokenAddress: ", sellTokenAddress);
915
- sellTokenContract = new ethers.Contract(sellTokenAddress, ERC20_ABI, provider);
916
- return [4 /*yield*/, sellTokenContract.symbol()];
917
- case 7:
918
- symbolSell = _a.sent();
919
- return [4 /*yield*/, sellTokenContract.decimals()];
920
- case 8:
921
- decimalsSell = _a.sent();
922
- SELL_TOKEN = new sdk_core_1.Token(8453, sellTokenAddress, decimalsSell, symbolSell, symbolSell.toLowerCase());
923
- return [3 /*break*/, 10];
924
- case 9:
925
- //WETH
926
- SELL_TOKEN = new sdk_core_1.Token(8453, '0x4200000000000000000000000000000000000006', 18, 'WETH');
927
- SELL_TOKEN_ADDRESS = '0x4200000000000000000000000000000000000006';
928
- _a.label = 10;
929
- case 10:
930
- FEE_AMOUNT = v3_sdk_1.FeeAmount.MEDIUM;
931
- inputPRO = ethers_1.utils.parseUnits('1000', 18).toString();
932
- args = {
933
- tokenInAddress: SELL_TOKEN_ADDRESS,
934
- tokenInChainId: chainIdInt,
935
- tokenOutAddress: BUY_TOKEN_ADDRESS,
936
- tokenOutChainId: chainIdInt,
937
- amount: "10000000000000000000",
938
- tradeType: 'EXACT_INPUT',
939
- sendPortionEnabled: true,
940
- };
941
- Protocol = void 0;
942
- (function (Protocol) {
943
- Protocol["V2"] = "V2";
944
- Protocol["V3"] = "V3";
945
- Protocol["MIXED"] = "MIXED";
946
- })(Protocol || (Protocol = {}));
947
- QuoteIntent = void 0;
948
- (function (QuoteIntent) {
949
- QuoteIntent["Pricing"] = "pricing";
950
- QuoteIntent["Quote"] = "quote";
951
- })(QuoteIntent || (QuoteIntent = {}));
952
- CLIENT_PARAMS = {
953
- protocols: [Protocol.V2, Protocol.V3, Protocol.MIXED],
954
- };
955
- tokenIn = args.tokenInAddress, tokenInChainId = args.tokenInChainId, tokenOut = args.tokenOutAddress, tokenOutChainId = args.tokenOutChainId, amount = args.amount, tradeType = args.tradeType, sendPortionEnabled = args.sendPortionEnabled;
956
- requestBody = {
957
- tokenInChainId: tokenInChainId,
958
- tokenIn: tokenIn,
959
- tokenOutChainId: tokenOutChainId,
960
- tokenOut: tokenOut,
961
- amount: amount,
962
- sendPortionEnabled: sendPortionEnabled,
963
- type: 'EXACT_INPUT',
964
- intent: QuoteIntent.Quote,
965
- configs: [
966
- {
967
- "protocols": [
968
- "V2",
969
- "V3",
970
- "MIXED"
971
- ],
972
- "enableUniversalRouter": true,
973
- "routingType": "CLASSIC",
974
- "recipient": from,
975
- "enableFeeOnTransferFeeFetching": true
976
- }
977
- ],
978
- };
979
- // const UNISWAP_GATEWAY_DNS_URL = 'https://interface.gateway.uniswap.org/v2'
980
- log.info("requestBody: ", requestBody);
981
- log.info("requestBody: ", JSON.stringify(requestBody));
982
- return [4 /*yield*/, (0, axios_1.default)({
983
- method: 'POST',
984
- url: 'https://interface.gateway.uniswap.org/v2/quote',
985
- data: requestBody,
986
- headers: {
987
- 'x-request-source': 'uniswap-web',
988
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
989
- 'Origin': 'http://localhost:3000',
990
- 'Referer': 'http://localhost:3000',
991
- 'Accept': 'application/json, text/plain, */*',
992
- 'Content-Type': 'application/json'
993
- }
994
- })];
995
- case 11:
996
- response = _a.sent();
997
- log.info(tag, 'response', response.data);
998
- uraQuoteResponse = response.data;
999
- log.info(tag, 'uraQuoteResponse', uraQuoteResponse);
1000
- output.amountOut = uraQuoteResponse.quote.quoteDecimals;
1001
- output.gas = uraQuoteResponse.quote.gasUseEstimate;
1002
- output.gasUsd = uraQuoteResponse.quote.gasUseEstimateUSD;
1003
- output.id = uraQuoteResponse.quote.requestId;
1004
- output.slippage = uraQuoteResponse.quote.slippage;
1005
- calldata = uraQuoteResponse.quote.methodParameters.calldata;
1006
- value = uraQuoteResponse.quote.methodParameters.value;
1007
- log.info("calldata: ", calldata);
1008
- log.info("value: ", value);
1009
- return [4 /*yield*/, provider.getTransactionCount(from, "latest")];
1010
- case 12:
1011
- nonce = _a.sent();
1012
- log.info("nonce: ", nonce);
1013
- gas = "0x".concat(BigInt("935120").toString(16)) // 935120
1014
- ;
1015
- return [4 /*yield*/, provider.getGasPrice()];
1016
- case 13:
1017
- gasPrice = _a.sent();
1018
- log.info("gasPrice: ", gasPrice.toString());
1019
- adjustedGasPrice = gasPrice.mul(ethers.BigNumber.from(110)).div(ethers.BigNumber.from(100));
1020
- isZero = function isZero(hexNumberString) {
1021
- return hexNumberString === '0' || /^0x0*$/.test(hexNumberString);
1022
- };
1023
- tx = __assign(__assign({ from: from, to: EIP155_MAINNET_CHAINS['eip155:' + chainId].universalRouter, chainId: chainId, data: calldata }, (value && !isZero(value) ? { value: (0, v3_sdk_1.toHex)(value) } : {})), { gas: gas, gasPrice: (0, v3_sdk_1.toHex)(adjustedGasPrice), nonce: (0, v3_sdk_1.toHex)(nonce) });
1024
- output.txs.push({
1025
- type: "evm",
1026
- description: 'swap tokens',
1027
- chain: inputChain,
1028
- txParams: tx
1029
- });
1030
- output.meta = {
1031
- quoteMode: "ERC20-ERC20"
1032
- };
1033
- output.steps = 1;
1034
- output.complete = true;
1035
- output.type = 'EVM';
1036
- return [2 /*return*/, output];
1037
- case 14:
1038
- e_3 = _a.sent();
1039
- console.error(tag, "e: ", e_3);
1040
- throw e_3;
1041
- case 15: return [2 /*return*/];
508
+ const get_quote_api = async function (quote) {
509
+ let tag = TAG + " | get_quote | ";
510
+ try {
511
+ let output = {};
512
+ if (!quote.sellAsset)
513
+ throw new Error("missing sellAsset");
514
+ if (!quote.buyAsset)
515
+ throw new Error("missing buyAsset");
516
+ if (!quote.sellAmount)
517
+ throw new Error("missing sellAmount");
518
+ if (!quote.senderAddress)
519
+ throw new Error("missing senderAddress");
520
+ if (!quote.recipientAddress)
521
+ throw new Error("missing recipientAddress");
522
+ if (!quote.slippage)
523
+ throw new Error("missing slippage");
524
+ if (!networkSupport.includes(caipToNetworkId(quote.buyAsset))) {
525
+ throw new Error("unsupported buyAsset");
526
+ }
527
+ if (!networkSupport.includes(caipToNetworkId(quote.sellAsset))) {
528
+ throw new Error("unsupported sellAsset");
529
+ }
530
+ // if(!quote.permit2) throw new Error("missing permit2, required for uniswap")
531
+ output.txs = [];
532
+ let from = quote.senderAddress;
533
+ // let slippageTolerance = quote.slippage
534
+ let recipient = quote.recipientAddress;
535
+ output.sellAsset = {};
536
+ output.source = 'uniswap';
537
+ output.sellAsset.caip = quote.sellAsset;
538
+ output.sellAmount = quote.sellAmount;
539
+ output.buyAsset = {};
540
+ output.buyAsset.caip = quote.buyAsset;
541
+ //NO CROSS CHAIN
542
+ let inputChain = caipToNetworkId(quote.sellAsset);
543
+ let outputChain = caipToNetworkId(quote.buyAsset);
544
+ if (inputChain != outputChain)
545
+ throw new Error("Cross Chain not supported");
546
+ log.info("inputChain: ", inputChain);
547
+ let providerUrl = EIP155_MAINNET_CHAINS[inputChain].rpc;
548
+ if (!providerUrl)
549
+ throw new Error("missing providerUrl");
550
+ log.info("providerUrl: ", providerUrl);
551
+ let chainIdInt = parseInt(inputChain.replace('eip155:', ''));
552
+ log.info(tag, "chainIdInt: ", chainIdInt);
553
+ let chainId = chainIdInt;
554
+ //TODO TEST provider for liveness
555
+ //get procider for chain
556
+ const provider = new ethers.providers.JsonRpcProvider(providerUrl); // Set your Ethereum RPC URL
557
+ // Initialize contracts based on whether they are tokens
558
+ let sellTokenContract, buyTokenContract;
559
+ //get pool for contract
560
+ let BUY_TOKEN, SELL_TOKEN;
561
+ let BUY_TOKEN_ADDRESS, SELL_TOKEN_ADDRESS;
562
+ if (quote.buyAsset.indexOf('erc20') > -1) {
563
+ //token input get pool for input
564
+ let buyTokenAddress = quote.buyAsset.split(":")[2].toLowerCase();
565
+ BUY_TOKEN_ADDRESS = buyTokenAddress;
566
+ log.info("buyTokenAddress: ", buyTokenAddress);
567
+ buyTokenContract = new ethers.Contract(buyTokenAddress.toLowerCase(), ERC20_ABI, provider);
568
+ const symbolBuy = await buyTokenContract.symbol();
569
+ const decimalsBuy = await buyTokenContract.decimals();
570
+ //get balance
571
+ let balance = await buyTokenContract.balanceOf(quote.senderAddress);
572
+ log.info("balance: ", balance.toString());
573
+ BUY_TOKEN = new ethers.Contract(buyTokenAddress, ERC20_ABI, provider);
574
+ }
575
+ else {
576
+ BUY_TOKEN = new ethers.Contract(EIP155_MAINNET_CHAINS[inputChain].WETH, ERC20_ABI, provider);
577
+ BUY_TOKEN_ADDRESS = EIP155_MAINNET_CHAINS[inputChain].WETH;
578
+ }
579
+ if (quote.sellAsset.indexOf('erc20') > -1) {
580
+ //token output get pools for output
581
+ let sellTokenAddress = quote.sellAsset.split(":")[2].toLowerCase();
582
+ SELL_TOKEN_ADDRESS = sellTokenAddress;
583
+ log.info("sellTokenAddress: ", sellTokenAddress);
584
+ sellTokenContract = new ethers.Contract(sellTokenAddress, ERC20_ABI, provider);
585
+ const symbolSell = await sellTokenContract.symbol();
586
+ const decimalsSell = await sellTokenContract.decimals();
587
+ SELL_TOKEN = new ethers.Contract(sellTokenAddress, ERC20_ABI, provider);
588
+ }
589
+ else {
590
+ //WETH
591
+ SELL_TOKEN = new ethers.Contract(EIP155_MAINNET_CHAINS[inputChain].WETH, ERC20_ABI, provider);
592
+ SELL_TOKEN_ADDRESS = EIP155_MAINNET_CHAINS[inputChain].WETH;
593
+ }
594
+ //check approval
595
+ // let spender = EIP155_MAINNET_CHAINS['eip155:' + chainId].universalRouter;
596
+ // let allowance = await sellTokenContract.allowance(from, spender)
597
+ // log.info(tag,"allowance: ",allowance.toString())
598
+ // if(allowance.lt(quote.sellAmount)) {
599
+ // log.info(tag,"allowance is less than sellAmount, approving...")
600
+ // // build approval tx
601
+ //
602
+ // }
603
+ // @ts-ignore
604
+ // let POOL_PRO = await get_pool(BUY_TOKEN, SELL_TOKEN, FeeAmount.MEDIUM, 0, provider)
605
+ // if(!POOL_PRO) throw new Error("missing POOL_PRO")
606
+ const FEE_AMOUNT = FeeAmount.MEDIUM;
607
+ const inputPRO = utils.parseUnits('1000', 18).toString();
608
+ //let mockedTrade = {"swaps":[{"route":{"_midPrice":{"numerator":[0,0,0,0,0,0,4096],"denominator":[61675844,569729604,374875920,86073376,789779649,857607051,27312043],"baseCurrency":{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},"quoteCurrency":{"chainId":8453,"decimals":18,"symbol":"ETH","name":"Ethereum","isNative":true,"isToken":false},"scalar":{"numerator":[660865024,931322574],"denominator":[660865024,931322574]}},"pools":[{"token0":{"chainId":8453,"decimals":18,"symbol":"WETH","isNative":false,"isToken":true,"address":"0x4200000000000000000000000000000000000006"},"token1":{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},"fee":3000,"sqrtRatioX96":[976906734,801624171,99421808,5226],"liquidity":[669390988,785588334,1],"tickCurrent":88055,"tickDataProvider":{},"_token1Price":{"numerator":[0,0,0,0,0,0,4096],"denominator":[61675844,569729604,374875920,86073376,789779649,857607051,27312043],"baseCurrency":{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},"quoteCurrency":{"chainId":8453,"decimals":18,"symbol":"WETH","isNative":false,"isToken":true,"address":"0x4200000000000000000000000000000000000006"},"scalar":{"numerator":[660865024,931322574],"denominator":[660865024,931322574]}}}],"tokenPath":[{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},{"chainId":8453,"decimals":18,"symbol":"WETH","isNative":false,"isToken":true,"address":"0x4200000000000000000000000000000000000006"}],"input":{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},"output":{"chainId":8453,"decimals":18,"symbol":"ETH","name":"Ethereum","isNative":true,"isToken":false},"protocol":"V3","path":[{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},{"chainId":8453,"decimals":18,"symbol":"WETH","isNative":false,"isToken":true,"address":"0x4200000000000000000000000000000000000006"}]},"inputAmount":{"numerator":[166199296,723291154,8],"denominator":[1],"currency":{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},"decimalScale":[660865024,931322574]},"outputAmount":{"numerator":[711636223,1308984],"denominator":[1],"currency":{"chainId":8453,"decimals":18,"symbol":"ETH","name":"Ethereum","isNative":true,"isToken":false},"decimalScale":[660865024,931322574]}}],"routes":[{"_midPrice":{"numerator":[0,0,0,0,0,0,4096],"denominator":[61675844,569729604,374875920,86073376,789779649,857607051,27312043],"baseCurrency":{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},"quoteCurrency":{"chainId":8453,"decimals":18,"symbol":"ETH","name":"Ethereum","isNative":true,"isToken":false},"scalar":{"numerator":[660865024,931322574],"denominator":[660865024,931322574]}},"pools":[{"token0":{"chainId":8453,"decimals":18,"symbol":"WETH","isNative":false,"isToken":true,"address":"0x4200000000000000000000000000000000000006"},"token1":{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},"fee":3000,"sqrtRatioX96":[976906734,801624171,99421808,5226],"liquidity":[669390988,785588334,1],"tickCurrent":88055,"tickDataProvider":{},"_token1Price":{"numerator":[0,0,0,0,0,0,4096],"denominator":[61675844,569729604,374875920,86073376,789779649,857607051,27312043],"baseCurrency":{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},"quoteCurrency":{"chainId":8453,"decimals":18,"symbol":"WETH","isNative":false,"isToken":true,"address":"0x4200000000000000000000000000000000000006"},"scalar":{"numerator":[660865024,931322574],"denominator":[660865024,931322574]}}}],"tokenPath":[{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},{"chainId":8453,"decimals":18,"symbol":"WETH","isNative":false,"isToken":true,"address":"0x4200000000000000000000000000000000000006"}],"input":{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},"output":{"chainId":8453,"decimals":18,"symbol":"ETH","name":"Ethereum","isNative":true,"isToken":false},"protocol":"V3","path":[{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},{"chainId":8453,"decimals":18,"symbol":"WETH","isNative":false,"isToken":true,"address":"0x4200000000000000000000000000000000000006"}]}],"tradeType":0,"fillType":"classic","approveInfo":{"needsApprove":false},"gasUseEstimate":164000,"gasUseEstimateUSD":0.005144,"blockNumber":"13097036","requestId":"747525fe-2ccf-494b-b0d3-677e2ebda037","quoteMethod":"ROUTING_API","swapFee":{"recipient":"0x067170777BA8027cED27E034102D54074d062d71","percent":{"numerator":[25],"denominator":[10000],"isPercent":true},"amount":"3522585411987"},"_outputAmount":{"numerator":[711636223,1308984],"denominator":[1],"currency":{"chainId":8453,"decimals":18,"symbol":"ETH","name":"Ethereum","isNative":true,"isToken":false},"decimalScale":[660865024,931322574]},"_inputAmount":{"numerator":[166199296,723291154,8],"denominator":[1],"currency":{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},"decimalScale":[660865024,931322574]},"_priceImpact":{"numerator":[941165072,174164585,107079465,969784123,796584146,369125678,162674660,985493716,122670731,392389178,573847026,872116559,752945511,679526963,814010822,56],"denominator":[0,0,0,0,0,0,0,706548328,653255527,1067448068,1064290579,550590138,219848419,764239412,729848924,903],"isPercent":true},"_executionPrice":{"numerator":[711636223,1308984],"denominator":[166199296,723291154,8],"baseCurrency":{"chainId":8453,"decimals":18,"symbol":"PRO","isNative":false,"isToken":true,"address":"0xEF743df8eDa497bCf1977393c401A636518DD630"},"quoteCurrency":{"chainId":8453,"decimals":18,"symbol":"ETH","name":"Ethereum","isNative":true,"isToken":false},"scalar":{"numerator":[660865024,931322574],"denominator":[660865024,931322574]}}}
609
+ let args = {
610
+ tokenInAddress: SELL_TOKEN_ADDRESS,
611
+ tokenInChainId: chainIdInt,
612
+ tokenOutAddress: BUY_TOKEN_ADDRESS,
613
+ tokenOutChainId: chainIdInt,
614
+ amount: "10000000000000000000",
615
+ tradeType: 'EXACT_INPUT',
616
+ sendPortionEnabled: true,
617
+ };
618
+ let Protocol;
619
+ (function (Protocol) {
620
+ Protocol["V2"] = "V2";
621
+ Protocol["V3"] = "V3";
622
+ Protocol["MIXED"] = "MIXED";
623
+ })(Protocol || (Protocol = {}));
624
+ let QuoteIntent;
625
+ (function (QuoteIntent) {
626
+ QuoteIntent["Pricing"] = "pricing";
627
+ QuoteIntent["Quote"] = "quote";
628
+ })(QuoteIntent || (QuoteIntent = {}));
629
+ const CLIENT_PARAMS = {
630
+ protocols: [Protocol.V2, Protocol.V3, Protocol.MIXED],
631
+ };
632
+ const { tokenInAddress: tokenIn, tokenInChainId, tokenOutAddress: tokenOut, tokenOutChainId, amount, tradeType, sendPortionEnabled, } = args;
633
+ const requestBody = {
634
+ tokenInChainId,
635
+ tokenIn,
636
+ tokenOutChainId,
637
+ tokenOut,
638
+ amount,
639
+ sendPortionEnabled,
640
+ type: 'EXACT_INPUT',
641
+ intent: QuoteIntent.Quote,
642
+ configs: [
643
+ {
644
+ "protocols": [
645
+ "V2",
646
+ "V3",
647
+ "MIXED"
648
+ ],
649
+ "enableUniversalRouter": true,
650
+ "routingType": "CLASSIC",
651
+ "recipient": from,
652
+ "enableFeeOnTransferFeeFetching": true
653
+ }
654
+ ],
655
+ };
656
+ // const UNISWAP_GATEWAY_DNS_URL = 'https://interface.gateway.uniswap.org/v2'
657
+ log.info("requestBody: ", requestBody);
658
+ log.info("requestBody: ", JSON.stringify(requestBody));
659
+ let response = await axios({
660
+ method: 'POST',
661
+ url: 'https://interface.gateway.uniswap.org/v2/quote',
662
+ data: requestBody,
663
+ headers: {
664
+ 'x-request-source': 'uniswap-web',
665
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
666
+ 'Origin': 'http://localhost:3000',
667
+ 'Referer': 'http://localhost:3000',
668
+ 'Accept': 'application/json, text/plain, */*',
669
+ 'Content-Type': 'application/json'
1042
670
  }
1043
671
  });
1044
- });
672
+ log.info(tag, 'response', response.data);
673
+ const uraQuoteResponse = response.data;
674
+ log.info(tag, 'uraQuoteResponse', uraQuoteResponse);
675
+ output.amountOut = uraQuoteResponse.quote.quoteDecimals;
676
+ output.gas = uraQuoteResponse.quote.gasUseEstimate;
677
+ output.gasUsd = uraQuoteResponse.quote.gasUseEstimateUSD;
678
+ output.id = uraQuoteResponse.quote.requestId;
679
+ output.slippage = uraQuoteResponse.quote.slippage;
680
+ // @ts-ignore
681
+ let calldata = uraQuoteResponse.quote.methodParameters.calldata;
682
+ // @ts-ignore
683
+ let value = uraQuoteResponse.quote.methodParameters.value;
684
+ log.info("calldata: ", calldata);
685
+ log.info("value: ", value);
686
+ const nonce = await provider.getTransactionCount(from, "latest");
687
+ log.info("nonce: ", nonce);
688
+ let gas = `0x${BigInt("935120").toString(16)}`; // 935120
689
+ const gasPrice = await provider.getGasPrice();
690
+ log.info("gasPrice: ", gasPrice.toString());
691
+ const adjustedGasPrice = gasPrice.mul(ethers.BigNumber.from(110)).div(ethers.BigNumber.from(100)); // Example: Increase by 10%
692
+ let isZero = function isZero(hexNumberString) {
693
+ return hexNumberString === '0' || /^0x0*$/.test(hexNumberString);
694
+ };
695
+ const tx = {
696
+ from,
697
+ to: EIP155_MAINNET_CHAINS['eip155:' + chainId].universalRouter,
698
+ chainId,
699
+ data: calldata,
700
+ // TODO: universal-router-sdk returns a non-hexlified value.
701
+ ...(value && !isZero(value) ? { value: utils.toHex(value) } : {}),
702
+ gas,
703
+ gasPrice: utils.toHex(adjustedGasPrice),
704
+ nonce: utils.toHex(nonce),
705
+ };
706
+ output.txs.push({
707
+ type: "evm",
708
+ description: 'swap tokens',
709
+ chain: inputChain,
710
+ txParams: tx
711
+ });
712
+ output.meta = {
713
+ quoteMode: "ERC20-ERC20"
714
+ };
715
+ output.steps = 1;
716
+ output.complete = true;
717
+ output.type = 'EVM';
718
+ return output;
719
+ }
720
+ catch (e) {
721
+ console.error(tag, "e: ", e);
722
+ throw e;
723
+ }
1045
724
  };