@pioneer-platform/uniswap-client 0.0.26 → 0.0.28

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.
@@ -1,7 +1,7 @@
1
1
  import { ChainId } from '@uniswap/sdk-core';
2
2
  import { SupportedL1ChainId, SupportedL2ChainId } from './chains';
3
- export declare const AVERAGE_L1_BLOCK_TIME: any;
4
- export declare const DEFAULT_MS_BEFORE_WARNING: any;
3
+ export declare const AVERAGE_L1_BLOCK_TIME: number;
4
+ export declare const DEFAULT_MS_BEFORE_WARNING: number;
5
5
  /**
6
6
  *
7
7
  * @param chainId
package/lib/index.js CHANGED
@@ -62,12 +62,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
62
62
  Object.defineProperty(exports, "__esModule", { value: true });
63
63
  var TAG = " | Uniswap | ";
64
64
  var axios_1 = __importDefault(require("axios"));
65
+ // @ts-ignore
66
+ var pioneer_discovery_1 = require("@pioneer-platform/pioneer-discovery");
65
67
  var _a = require("@pioneer-platform/pioneer-caip"), caipToNetworkId = _a.caipToNetworkId, shortListSymbolToCaip = _a.shortListSymbolToCaip, ChainToNetworkId = _a.ChainToNetworkId;
66
68
  var uuid = require('uuidv4').uuid;
67
69
  var log = require('@pioneer-platform/loggerdog')();
68
70
  var _b = require('ethers'), ethers = _b.ethers, BigNumber = _b.BigNumber;
69
71
  var ethers_1 = require("ethers");
70
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");
71
75
  var v3_sdk_1 = require("@uniswap/v3-sdk");
72
76
  var networkSupport = [
73
77
  ChainToNetworkId["ETH"],
@@ -105,6 +109,11 @@ var ERC20_ABI = [
105
109
  "function symbol() view returns (string)",
106
110
  "function decimals() view returns (uint8)"
107
111
  ];
112
+ function toDeadline(expiration) {
113
+ return Math.floor((Date.now() + expiration) / 1000);
114
+ }
115
+ var PERMIT_EXPIRATION = 2592000000; // 30 days in milliseconds
116
+ var PERMIT_SIG_EXPIRATION = 1800000; // 30 minutes in milliseconds
108
117
  module.exports = {
109
118
  init: function (settings) {
110
119
  return true;
@@ -112,13 +121,719 @@ module.exports = {
112
121
  networkSupport: function () {
113
122
  return networkSupport;
114
123
  },
124
+ assetSupport: function () {
125
+ return getAssetSupport();
126
+ },
127
+ buildPermitTx: function (permit) {
128
+ return get_permit(permit);
129
+ },
130
+ buildLpTx: function (quote) {
131
+ return build_lp_tx(quote);
132
+ },
115
133
  getQuote: function (quote) {
116
- return get_quote(quote);
134
+ return get_quote_local(quote);
117
135
  }
136
+ //ProvideLP
137
+ // getQuote: function (quote:any) {
138
+ // return get_quote_api(quote);
139
+ // }
118
140
  };
119
- var get_quote = function (quote) {
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) {
120
257
  return __awaiter(this, void 0, void 0, function () {
121
- 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_1;
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
+ }
349
+ });
350
+ });
351
+ };
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 | ";
512
+ try {
513
+ var from = permit.from;
514
+ var token = permit.token;
515
+ var amount = permit.amount;
516
+ var chainId = permit.chainId;
517
+ //iterate over chains
518
+ var permit712 = {
519
+ "types": {
520
+ "PermitSingle": [
521
+ {
522
+ "name": "details",
523
+ "type": "PermitDetails"
524
+ },
525
+ {
526
+ "name": "spender",
527
+ "type": "address"
528
+ },
529
+ {
530
+ "name": "sigDeadline",
531
+ "type": "uint256"
532
+ }
533
+ ],
534
+ "PermitDetails": [
535
+ {
536
+ "name": "token",
537
+ "type": "address"
538
+ },
539
+ {
540
+ "name": "amount",
541
+ "type": "uint160"
542
+ },
543
+ {
544
+ "name": "expiration",
545
+ "type": "uint48"
546
+ },
547
+ {
548
+ "name": "nonce",
549
+ "type": "uint48"
550
+ }
551
+ ],
552
+ "EIP712Domain": [
553
+ {
554
+ "name": "name",
555
+ "type": "string"
556
+ },
557
+ {
558
+ "name": "chainId",
559
+ "type": "uint256"
560
+ },
561
+ {
562
+ "name": "verifyingContract",
563
+ "type": "address"
564
+ }
565
+ ]
566
+ },
567
+ "domain": {
568
+ "name": "Permit2",
569
+ "chainId": permit.chainId,
570
+ "verifyingContract": "0x000000000022d473030f116ddee9f6b43ac78ba3"
571
+ },
572
+ "primaryType": "PermitSingle",
573
+ "message": {
574
+ "details": {
575
+ "token": permit.token,
576
+ "amount": permit.amount,
577
+ "expiration": permit.expiry,
578
+ "nonce": "1"
579
+ },
580
+ "spender": EIP155_MAINNET_CHAINS['eip155:' + chainId].universalRouter,
581
+ "sigDeadline": permit.sigDeadline
582
+ }
583
+ };
584
+ return permit712;
585
+ }
586
+ catch (e) {
587
+ console.error(e);
588
+ }
589
+ };
590
+ var getAssetSupport = function () {
591
+ var tag = TAG + " | getAssetSupport | ";
592
+ try {
593
+ //iterate over chains
594
+ var allAssets = Object.keys(pioneer_discovery_1.assetData);
595
+ // 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);
600
+ // console.log("networkId: ",networkId)
601
+ if (networkSupport.indexOf(networkId) > -1) {
602
+ supportedAssets.push(asset);
603
+ }
604
+ }
605
+ return supportedAssets;
606
+ }
607
+ catch (e) {
608
+ console.error(e);
609
+ }
610
+ };
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*/];
830
+ }
831
+ });
832
+ });
833
+ };
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;
122
837
  return __generator(this, function (_a) {
123
838
  switch (_a.label) {
124
839
  case 0:
@@ -139,11 +854,18 @@ var get_quote = function (quote) {
139
854
  throw new Error("missing recipientAddress");
140
855
  if (!quote.slippage)
141
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
+ }
142
863
  // if(!quote.permit2) throw new Error("missing permit2, required for uniswap")
143
864
  output.txs = [];
144
865
  from = quote.senderAddress;
145
866
  recipient = quote.recipientAddress;
146
867
  output.sellAsset = {};
868
+ output.source = 'uniswap';
147
869
  output.sellAsset.caip = quote.sellAsset;
148
870
  output.sellAmount = quote.sellAmount;
149
871
  output.buyAsset = {};
@@ -214,7 +936,7 @@ var get_quote = function (quote) {
214
936
  tokenOutChainId: chainIdInt,
215
937
  amount: "10000000000000000000",
216
938
  tradeType: 'EXACT_INPUT',
217
- sendPortionEnabled: false,
939
+ sendPortionEnabled: true,
218
940
  };
219
941
  Protocol = void 0;
220
942
  (function (Protocol) {
@@ -254,6 +976,9 @@ var get_quote = function (quote) {
254
976
  }
255
977
  ],
256
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));
257
982
  return [4 /*yield*/, (0, axios_1.default)({
258
983
  method: 'POST',
259
984
  url: 'https://interface.gateway.uniswap.org/v2/quote',
@@ -310,9 +1035,9 @@ var get_quote = function (quote) {
310
1035
  output.type = 'EVM';
311
1036
  return [2 /*return*/, output];
312
1037
  case 14:
313
- e_1 = _a.sent();
314
- console.error(tag, "e: ", e_1);
315
- throw e_1;
1038
+ e_3 = _a.sent();
1039
+ console.error(tag, "e: ", e_3);
1040
+ throw e_3;
316
1041
  case 15: return [2 /*return*/];
317
1042
  }
318
1043
  });
@@ -88,20 +88,35 @@ function getQuote(_a, router, routerConfig) {
88
88
  return __generator(this, function (_b) {
89
89
  switch (_b.label) {
90
90
  case 0:
91
+ console.log("Checkpoint: getQuote");
91
92
  tokenInIsNative = Object.values(types_1.SwapRouterNativeAssets).includes(tokenIn.address);
92
93
  tokenOutIsNative = Object.values(types_1.SwapRouterNativeAssets).includes(tokenOut.address);
93
- currencyIn = tokenInIsNative
94
- ? (0, tokens_1.nativeOnChain)(tokenIn.chainId)
95
- : new sdk_core_1.Token(tokenIn.chainId, tokenIn.address, tokenIn.decimals, tokenIn.symbol);
96
- currencyOut = tokenOutIsNative
97
- ? (0, tokens_1.nativeOnChain)(tokenOut.chainId)
98
- : new sdk_core_1.Token(tokenOut.chainId, tokenOut.address, tokenOut.decimals, tokenOut.symbol);
94
+ console.log("Checkpoint: getQuote2");
95
+ if (tokenInIsNative) {
96
+ console.log("Checkpoint: tokenInIsNative");
97
+ currencyIn = (0, tokens_1.nativeOnChain)(tokenIn.chainId); // Use the native token for the chain if tokenIn is native
98
+ }
99
+ else {
100
+ console.log("Checkpoint: !tokenInIsNative tokenIn: ", tokenIn);
101
+ currencyIn = new sdk_core_1.Token(tokenIn.chainId, tokenIn.address, tokenIn.decimals, tokenIn.symbol); // Otherwise, create a new token
102
+ }
103
+ if (tokenOutIsNative) {
104
+ console.log("Checkpoint: tokenOutIsNative");
105
+ currencyOut = (0, tokens_1.nativeOnChain)(tokenOut.chainId); // Use the native token for the chain if tokenOut is native
106
+ }
107
+ else {
108
+ console.log("Checkpoint: !tokenOutIsNative");
109
+ currencyOut = new sdk_core_1.Token(tokenOut.chainId, tokenOut.address, tokenOut.decimals, tokenOut.symbol); // Otherwise, create a new token
110
+ }
99
111
  baseCurrency = tradeType === sdk_core_1.TradeType.EXACT_INPUT ? currencyIn : currencyOut;
100
112
  quoteCurrency = tradeType === sdk_core_1.TradeType.EXACT_INPUT ? currencyOut : currencyIn;
113
+ console.log("baseCurrency", baseCurrency);
114
+ console.log("quoteCurrency", quoteCurrency);
101
115
  amount = sdk_core_1.CurrencyAmount.fromRawAmount(baseCurrency, jsbi_1.default.BigInt(amountRaw));
102
116
  return [4 /*yield*/, router.route(amount, quoteCurrency, tradeType, /*swapConfig=*/ undefined, routerConfig)];
103
117
  case 1:
104
118
  swapRoute = _b.sent();
119
+ console.log("swapRoute", swapRoute);
105
120
  if (!swapRoute) {
106
121
  return [2 /*return*/, { state: types_1.QuoteState.NOT_FOUND }];
107
122
  }
@@ -4,5 +4,5 @@ import { SupportedInterfaceChain } from '../constants/chains';
4
4
  export default class ConfiguredJsonRpcProvider extends StaticJsonRpcProvider {
5
5
  constructor(url: string | undefined, networkish: Networkish & {
6
6
  chainId: SupportedInterfaceChain;
7
- }, pollingInterval?: any);
7
+ }, pollingInterval?: number);
8
8
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pioneer-platform/uniswap-client",
3
- "version": "0.0.26",
3
+ "version": "0.0.28",
4
4
  "main": "./lib/index.js",
5
5
  "types": "./lib/index.d.ts",
6
6
  "dependencies": {
@@ -9,6 +9,7 @@
9
9
  "@pioneer-platform/maya-network": "^8.3.7",
10
10
  "@pioneer-platform/pioneer-caip": "^9.2.23",
11
11
  "@pioneer-platform/pioneer-coins": "^9.2.13",
12
+ "@pioneer-platform/pioneer-discovery": "^0.0.7",
12
13
  "@types/ms": "^0.7.34",
13
14
  "@types/ms.macro": "^2.0.2",
14
15
  "@uniswap/router-sdk": "1.9.0",
@@ -30,6 +31,7 @@
30
31
  "scripts": {
31
32
  "npm": "npm i",
32
33
  "test": "npm run build && node __tests__/test-module.js",
34
+ "test-sdk": "npm run build && node __tests__/test-module-sdk.js",
33
35
  "build": "tsc -p .",
34
36
  "prepublish": "npm run build",
35
37
  "refresh": "rm -rf ./node_modules ./package-lock.json && npm install"