UNPKG

ttxd-alpha

Version:

An SDK for building applications on top of V2,V3 and Solana exchanges

2,351 lines (2,343 loc) 89.8 kB
import { CurrencyAmount, TradeType, Percent } from '@uniswap/sdk-core'; import { Pair, RouteV2, TradeV2, RouterV2, Trade, Pool, Route, SwapQuoter, computePoolAddress, computePoolAddressOnchain } from 'ttxd'; import { ethers, BigNumber } from 'ethers'; import { Keypair, Connection, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js'; import BN from 'bn.js'; import Decimal from 'decimal.js'; import { NATIVE_MINT } from '@solana/spl-token'; import { TxVersion, Raydium, CLMM_PROGRAM_ID, AMM_V4, AMM_STABLE, PoolUtils } from '@raydium-io/raydium-sdk-v2'; import bs58 from 'bs58'; import { readFile } from 'fs/promises'; import path from 'path'; import JSBI from 'jsbi'; function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } function _regeneratorRuntime() { _regeneratorRuntime = function () { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function (t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function (t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(typeof e + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function (e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function () { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function (e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function (t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function (t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function (e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } var uniswapV2poolABI = [ { inputs: [ ], payable: false, stateMutability: "nonpayable", type: "constructor" }, { anonymous: false, inputs: [ { indexed: true, internalType: "address", name: "owner", type: "address" }, { indexed: true, internalType: "address", name: "spender", type: "address" }, { indexed: false, internalType: "uint256", name: "value", type: "uint256" } ], name: "Approval", type: "event" }, { anonymous: false, inputs: [ { indexed: true, internalType: "address", name: "sender", type: "address" }, { indexed: false, internalType: "uint256", name: "amount0", type: "uint256" }, { indexed: false, internalType: "uint256", name: "amount1", type: "uint256" }, { indexed: true, internalType: "address", name: "to", type: "address" } ], name: "Burn", type: "event" }, { anonymous: false, inputs: [ { indexed: true, internalType: "address", name: "sender", type: "address" }, { indexed: false, internalType: "uint256", name: "amount0", type: "uint256" }, { indexed: false, internalType: "uint256", name: "amount1", type: "uint256" } ], name: "Mint", type: "event" }, { anonymous: false, inputs: [ { indexed: true, internalType: "address", name: "sender", type: "address" }, { indexed: false, internalType: "uint256", name: "amount0In", type: "uint256" }, { indexed: false, internalType: "uint256", name: "amount1In", type: "uint256" }, { indexed: false, internalType: "uint256", name: "amount0Out", type: "uint256" }, { indexed: false, internalType: "uint256", name: "amount1Out", type: "uint256" }, { indexed: true, internalType: "address", name: "to", type: "address" } ], name: "Swap", type: "event" }, { anonymous: false, inputs: [ { indexed: false, internalType: "uint112", name: "reserve0", type: "uint112" }, { indexed: false, internalType: "uint112", name: "reserve1", type: "uint112" } ], name: "Sync", type: "event" }, { anonymous: false, inputs: [ { indexed: true, internalType: "address", name: "from", type: "address" }, { indexed: true, internalType: "address", name: "to", type: "address" }, { indexed: false, internalType: "uint256", name: "value", type: "uint256" } ], name: "Transfer", type: "event" }, { constant: true, inputs: [ ], name: "DOMAIN_SEPARATOR", outputs: [ { internalType: "bytes32", name: "", type: "bytes32" } ], payable: false, stateMutability: "view", type: "function" }, { constant: true, inputs: [ ], name: "MINIMUM_LIQUIDITY", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], payable: false, stateMutability: "view", type: "function" }, { constant: true, inputs: [ ], name: "PERMIT_TYPEHASH", outputs: [ { internalType: "bytes32", name: "", type: "bytes32" } ], payable: false, stateMutability: "view", type: "function" }, { constant: true, inputs: [ { internalType: "address", name: "", type: "address" }, { internalType: "address", name: "", type: "address" } ], name: "allowance", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], payable: false, stateMutability: "view", type: "function" }, { constant: false, inputs: [ { internalType: "address", name: "spender", type: "address" }, { internalType: "uint256", name: "value", type: "uint256" } ], name: "approve", outputs: [ { internalType: "bool", name: "", type: "bool" } ], payable: false, stateMutability: "nonpayable", type: "function" }, { constant: true, inputs: [ { internalType: "address", name: "", type: "address" } ], name: "balanceOf", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], payable: false, stateMutability: "view", type: "function" }, { constant: false, inputs: [ { internalType: "address", name: "to", type: "address" } ], name: "burn", outputs: [ { internalType: "uint256", name: "amount0", type: "uint256" }, { internalType: "uint256", name: "amount1", type: "uint256" } ], payable: false, stateMutability: "nonpayable", type: "function" }, { constant: true, inputs: [ ], name: "decimals", outputs: [ { internalType: "uint8", name: "", type: "uint8" } ], payable: false, stateMutability: "view", type: "function" }, { constant: true, inputs: [ ], name: "factory", outputs: [ { internalType: "address", name: "", type: "address" } ], payable: false, stateMutability: "view", type: "function" }, { constant: true, inputs: [ ], name: "getReserves", outputs: [ { internalType: "uint112", name: "_reserve0", type: "uint112" }, { internalType: "uint112", name: "_reserve1", type: "uint112" }, { internalType: "uint32", name: "_blockTimestampLast", type: "uint32" } ], payable: false, stateMutability: "view", type: "function" }, { constant: false, inputs: [ { internalType: "address", name: "_token0", type: "address" }, { internalType: "address", name: "_token1", type: "address" } ], name: "initialize", outputs: [ ], payable: false, stateMutability: "nonpayable", type: "function" }, { constant: true, inputs: [ ], name: "kLast", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], payable: false, stateMutability: "view", type: "function" }, { constant: false, inputs: [ { internalType: "address", name: "to", type: "address" } ], name: "mint", outputs: [ { internalType: "uint256", name: "liquidity", type: "uint256" } ], payable: false, stateMutability: "nonpayable", type: "function" }, { constant: true, inputs: [ ], name: "name", outputs: [ { internalType: "string", name: "", type: "string" } ], payable: false, stateMutability: "view", type: "function" }, { constant: true, inputs: [ { internalType: "address", name: "", type: "address" } ], name: "nonces", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], payable: false, stateMutability: "view", type: "function" }, { constant: false, inputs: [ { internalType: "address", name: "owner", type: "address" }, { internalType: "address", name: "spender", type: "address" }, { internalType: "uint256", name: "value", type: "uint256" }, { internalType: "uint256", name: "deadline", type: "uint256" }, { internalType: "uint8", name: "v", type: "uint8" }, { internalType: "bytes32", name: "r", type: "bytes32" }, { internalType: "bytes32", name: "s", type: "bytes32" } ], name: "permit", outputs: [ ], payable: false, stateMutability: "nonpayable", type: "function" }, { constant: true, inputs: [ ], name: "price0CumulativeLast", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], payable: false, stateMutability: "view", type: "function" }, { constant: true, inputs: [ ], name: "price1CumulativeLast", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], payable: false, stateMutability: "view", type: "function" }, { constant: false, inputs: [ { internalType: "address", name: "to", type: "address" } ], name: "skim", outputs: [ ], payable: false, stateMutability: "nonpayable", type: "function" }, { constant: false, inputs: [ { internalType: "uint256", name: "amount0Out", type: "uint256" }, { internalType: "uint256", name: "amount1Out", type: "uint256" }, { internalType: "address", name: "to", type: "address" }, { internalType: "bytes", name: "data", type: "bytes" } ], name: "swap", outputs: [ ], payable: false, stateMutability: "nonpayable", type: "function" }, { constant: true, inputs: [ ], name: "symbol", outputs: [ { internalType: "string", name: "", type: "string" } ], payable: false, stateMutability: "view", type: "function" }, { constant: false, inputs: [ ], name: "sync", outputs: [ ], payable: false, stateMutability: "nonpayable", type: "function" }, { constant: true, inputs: [ ], name: "token0", outputs: [ { internalType: "address", name: "", type: "address" } ], payable: false, stateMutability: "view", type: "function" }, { constant: true, inputs: [ ], name: "token1", outputs: [ { internalType: "address", name: "", type: "address" } ], payable: false, stateMutability: "view", type: "function" }, { constant: true, inputs: [ ], name: "totalSupply", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], payable: false, stateMutability: "view", type: "function" }, { constant: false, inputs: [ { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "value", type: "uint256" } ], name: "transfer", outputs: [ { internalType: "bool", name: "", type: "bool" } ], payable: false, stateMutability: "nonpayable", type: "function" }, { constant: false, inputs: [ { internalType: "address", name: "from", type: "address" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "value", type: "uint256" } ], name: "transferFrom", outputs: [ { internalType: "bool", name: "", type: "bool" } ], payable: false, stateMutability: "nonpayable", type: "function" } ]; var uniswapV2RouterABI = [ { inputs: [ { internalType: "address", name: "_factory", type: "address" }, { internalType: "address", name: "_WETH", type: "address" } ], stateMutability: "nonpayable", type: "constructor" }, { inputs: [ ], name: "WETH", outputs: [ { internalType: "address", name: "", type: "address" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "address", name: "tokenA", type: "address" }, { internalType: "address", name: "tokenB", type: "address" }, { internalType: "uint256", name: "amountADesired", type: "uint256" }, { internalType: "uint256", name: "amountBDesired", type: "uint256" }, { internalType: "uint256", name: "amountAMin", type: "uint256" }, { internalType: "uint256", name: "amountBMin", type: "uint256" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "addLiquidity", outputs: [ { internalType: "uint256", name: "amountA", type: "uint256" }, { internalType: "uint256", name: "amountB", type: "uint256" }, { internalType: "uint256", name: "liquidity", type: "uint256" } ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "address", name: "token", type: "address" }, { internalType: "uint256", name: "amountTokenDesired", type: "uint256" }, { internalType: "uint256", name: "amountTokenMin", type: "uint256" }, { internalType: "uint256", name: "amountETHMin", type: "uint256" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "addLiquidityETH", outputs: [ { internalType: "uint256", name: "amountToken", type: "uint256" }, { internalType: "uint256", name: "amountETH", type: "uint256" }, { internalType: "uint256", name: "liquidity", type: "uint256" } ], stateMutability: "payable", type: "function" }, { inputs: [ ], name: "factory", outputs: [ { internalType: "address", name: "", type: "address" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountOut", type: "uint256" }, { internalType: "uint256", name: "reserveIn", type: "uint256" }, { internalType: "uint256", name: "reserveOut", type: "uint256" } ], name: "getAmountIn", outputs: [ { internalType: "uint256", name: "amountIn", type: "uint256" } ], stateMutability: "pure", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountIn", type: "uint256" }, { internalType: "uint256", name: "reserveIn", type: "uint256" }, { internalType: "uint256", name: "reserveOut", type: "uint256" } ], name: "getAmountOut", outputs: [ { internalType: "uint256", name: "amountOut", type: "uint256" } ], stateMutability: "pure", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountOut", type: "uint256" }, { internalType: "address[]", name: "path", type: "address[]" } ], name: "getAmountsIn", outputs: [ { internalType: "uint256[]", name: "amounts", type: "uint256[]" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountIn", type: "uint256" }, { internalType: "address[]", name: "path", type: "address[]" } ], name: "getAmountsOut", outputs: [ { internalType: "uint256[]", name: "amounts", type: "uint256[]" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountA", type: "uint256" }, { internalType: "uint256", name: "reserveA", type: "uint256" }, { internalType: "uint256", name: "reserveB", type: "uint256" } ], name: "quote", outputs: [ { internalType: "uint256", name: "amountB", type: "uint256" } ], stateMutability: "pure", type: "function" }, { inputs: [ { internalType: "address", name: "tokenA", type: "address" }, { internalType: "address", name: "tokenB", type: "address" }, { internalType: "uint256", name: "liquidity", type: "uint256" }, { internalType: "uint256", name: "amountAMin", type: "uint256" }, { internalType: "uint256", name: "amountBMin", type: "uint256" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "removeLiquidity", outputs: [ { internalType: "uint256", name: "amountA", type: "uint256" }, { internalType: "uint256", name: "amountB", type: "uint256" } ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "address", name: "token", type: "address" }, { internalType: "uint256", name: "liquidity", type: "uint256" }, { internalType: "uint256", name: "amountTokenMin", type: "uint256" }, { internalType: "uint256", name: "amountETHMin", type: "uint256" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "removeLiquidityETH", outputs: [ { internalType: "uint256", name: "amountToken", type: "uint256" }, { internalType: "uint256", name: "amountETH", type: "uint256" } ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "address", name: "token", type: "address" }, { internalType: "uint256", name: "liquidity", type: "uint256" }, { internalType: "uint256", name: "amountTokenMin", type: "uint256" }, { internalType: "uint256", name: "amountETHMin", type: "uint256" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "removeLiquidityETHSupportingFeeOnTransferTokens", outputs: [ { internalType: "uint256", name: "amountETH", type: "uint256" } ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "address", name: "token", type: "address" }, { internalType: "uint256", name: "liquidity", type: "uint256" }, { internalType: "uint256", name: "amountTokenMin", type: "uint256" }, { internalType: "uint256", name: "amountETHMin", type: "uint256" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" }, { internalType: "bool", name: "approveMax", type: "bool" }, { internalType: "uint8", name: "v", type: "uint8" }, { internalType: "bytes32", name: "r", type: "bytes32" }, { internalType: "bytes32", name: "s", type: "bytes32" } ], name: "removeLiquidityETHWithPermit", outputs: [ { internalType: "uint256", name: "amountToken", type: "uint256" }, { internalType: "uint256", name: "amountETH", type: "uint256" } ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "address", name: "token", type: "address" }, { internalType: "uint256", name: "liquidity", type: "uint256" }, { internalType: "uint256", name: "amountTokenMin", type: "uint256" }, { internalType: "uint256", name: "amountETHMin", type: "uint256" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" }, { internalType: "bool", name: "approveMax", type: "bool" }, { internalType: "uint8", name: "v", type: "uint8" }, { internalType: "bytes32", name: "r", type: "bytes32" }, { internalType: "bytes32", name: "s", type: "bytes32" } ], name: "removeLiquidityETHWithPermitSupportingFeeOnTransferTokens", outputs: [ { internalType: "uint256", name: "amountETH", type: "uint256" } ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "address", name: "tokenA", type: "address" }, { internalType: "address", name: "tokenB", type: "address" }, { internalType: "uint256", name: "liquidity", type: "uint256" }, { internalType: "uint256", name: "amountAMin", type: "uint256" }, { internalType: "uint256", name: "amountBMin", type: "uint256" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" }, { internalType: "bool", name: "approveMax", type: "bool" }, { internalType: "uint8", name: "v", type: "uint8" }, { internalType: "bytes32", name: "r", type: "bytes32" }, { internalType: "bytes32", name: "s", type: "bytes32" } ], name: "removeLiquidityWithPermit", outputs: [ { internalType: "uint256", name: "amountA", type: "uint256" }, { internalType: "uint256", name: "amountB", type: "uint256" } ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountOut", type: "uint256" }, { internalType: "address[]", name: "path", type: "address[]" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "swapETHForExactTokens", outputs: [ { internalType: "uint256[]", name: "amounts", type: "uint256[]" } ], stateMutability: "payable", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountOutMin", type: "uint256" }, { internalType: "address[]", name: "path", type: "address[]" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "swapExactETHForTokens", outputs: [ { internalType: "uint256[]", name: "amounts", type: "uint256[]" } ], stateMutability: "payable", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountOutMin", type: "uint256" }, { internalType: "address[]", name: "path", type: "address[]" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "swapExactETHForTokensSupportingFeeOnTransferTokens", outputs: [ ], stateMutability: "payable", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountIn", type: "uint256" }, { internalType: "uint256", name: "amountOutMin", type: "uint256" }, { internalType: "address[]", name: "path", type: "address[]" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "swapExactTokensForETH", outputs: [ { internalType: "uint256[]", name: "amounts", type: "uint256[]" } ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountIn", type: "uint256" }, { internalType: "uint256", name: "amountOutMin", type: "uint256" }, { internalType: "address[]", name: "path", type: "address[]" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "swapExactTokensForETHSupportingFeeOnTransferTokens", outputs: [ ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountIn", type: "uint256" }, { internalType: "uint256", name: "amountOutMin", type: "uint256" }, { internalType: "address[]", name: "path", type: "address[]" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "swapExactTokensForTokens", outputs: [ { internalType: "uint256[]", name: "amounts", type: "uint256[]" } ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountIn", type: "uint256" }, { internalType: "uint256", name: "amountOutMin", type: "uint256" }, { internalType: "address[]", name: "path", type: "address[]" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "swapExactTokensForTokensSupportingFeeOnTransferTokens", outputs: [ ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountOut", type: "uint256" }, { internalType: "uint256", name: "amountInMax", type: "uint256" }, { internalType: "address[]", name: "path", type: "address[]" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "swapTokensForExactETH", outputs: [ { internalType: "uint256[]", name: "amounts", type: "uint256[]" } ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "uint256", name: "amountOut", type: "uint256" }, { internalType: "uint256", name: "amountInMax", type: "uint256" }, { internalType: "address[]", name: "path", type: "address[]" }, { internalType: "address", name: "to", type: "address" }, { internalType: "uint256", name: "deadline", type: "uint256" } ], name: "swapTokensForExactTokens", outputs: [ { internalType: "uint256[]", name: "amounts", type: "uint256[]" } ], stateMutability: "nonpayable", type: "function" }, { stateMutability: "payable", type: "receive" } ]; var NETWORK_ADDRESSES = { 1: { uniswapv2: { factory: '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f', router: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D' }, pancakeswapv2: { factory: '0x1097053Fd2ea711dad45caCcc45EfF7548fCB362', router: '0xEfF92A263d31888d860bD50809A8D171709b7b1c' }, sushiswapv2: { factory: '0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac', router: '0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F' } }, 42161: { uniswapv2: { factory: '0xf1D7CC64Fb4452F05c498126312eBE29f30Fbcf9', router: '0x4752ba5dbc23f44d87826276bf6fd6b1c372ad24' }, pancakeswapv2: { factory: '0x02a84c1b3BBD7401a5f7fa98a384EBC70bB5749E', router: '0x8cFe327CEc66d1C090Dd72bd0FF11d690C33a2Eb' } }, 56: { uniswapv2: { factory: '0x8909Dc15e40173Ff4699343b6eB8132c65e18eC6', router: '0x4752ba5dbc23f44d87826276bf6fd6b1c372ad24' }, pancakeswapv2: { factory: '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73', router: '0x10ED43C718714eb63d5aA57B78B54704E256024E' }, sushiswapv2: { factory: '0xc35DADB65012eC5796536bD9864eD8773aBc74C4', router: '0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506' } }, 8453: { uniswapv2: { factory: '0x8909Dc15e40173Ff4699343b6eB8132c65e18eC6', router: '0x4752ba5dbc23f44d87826276bf6fd6b1c372ad24' }, pancakeswapv2: { factory: '0x02a84c1b3BBD7401a5f7fa98a384EBC70bB5749E', router: '0x8cFe327CEc66d1C090Dd72bd0FF11d690C33a2Eb' } }, 137: { quickswapv2: { factory: '0x5757371414417b8C6CAad45bAeF941aBc7d3Ab32', router: '0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff' }, uniswapv2: { factory: '0x9e5A52f57b3038F1B8EeE45F28b3C1967e22799C', router: '0xedf6066a2b290C185783862C7F4776A2C8077AD1' }, sushiswapv2: { factory: '0xc35DADB65012eC5796536bD9864eD8773aBc74C4', router: '0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506' } } }; var DEFAULT_V2_GAS_LIMIT = 300000; var CHAIN_GAS_CONFIGS = { 1: { maxFeePerGas: "10", maxPriorityFeePerGas: "4" }, 56: { maxFeePerGas: "6", maxPriorityFeePerGas: "3" }, 8453: { maxFeePerGas: "6", maxPriorityFeePerGas: "3" }, 42161: { maxFeePerGas: "6", maxPriorityFeePerGas: "3" }, 137: { maxFeePerGas: "50", maxPriorityFeePerGas: "30" } }; /** * Swap tokens using Uniswap V2 * @param chainId - ChainId (e.g., ChainId.BASE, ChainId.ETHEREUM) * @param exchange - Exchange name (e.g., 'uniswap', 'sushiswapv2') * @param token1 - Input token (Token instance) * @param token2 - Output token (Token instance) * @param amount - Amount of input token to swap (as string) * @param provider - Ethers.js provider instance * @param signer - Ethers.js signer instance */ function swapV2(_x) { return _swapV.apply(this, arguments); } function _swapV() { _swapV = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) { var chainId, exchange, token1, token2, amount, provider, signer, _ref$gasLimit, gasLimit, maxFeePerGas, maxPriorityFeePerGas, defaultChainGasConfig, finalMaxFeePerGas, finalMaxPriorityFeePerGas, networkConfig, v2Router, v2RouterContract, pairAddress, pairContract, reserves, reserve0, reserve1, _ref2, token0, token1Sorted, pair, route, trade, routerParams, tokenToApprove, _yield$Promise$all, userBalance, currentAllowance, approveTx, approvalReceipt, swapTx, txResponse, receipt; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: chainId = _ref.chainId, exchange = _ref.exchange, token1 = _ref.token1, token2 = _ref.token2, amount = _ref.amount, provider = _ref.provider, signer = _ref.signer, _ref$gasLimit = _ref.gasLimit, gasLimit = _ref$gasLimit === void 0 ? DEFAULT_V2_GAS_LIMIT : _ref$gasLimit, maxFeePerGas = _ref.maxFeePerGas, maxPriorityFeePerGas = _ref.maxPriorityFeePerGas; defaultChainGasConfig = CHAIN_GAS_CONFIGS[chainId]; finalMaxFeePerGas = maxFeePerGas || defaultChainGasConfig.maxFeePerGas; finalMaxPriorityFeePerGas = maxPriorityFeePerGas || defaultChainGasConfig.maxPriorityFeePerGas; console.log("Default Gas Config", defaultChainGasConfig); console.log("Final Max Gas Fee", finalMaxFeePerGas); console.log("Final Max Priority Gas Fee", finalMaxPriorityFeePerGas); networkConfig = NETWORK_ADDRESSES[chainId][exchange]; if (networkConfig) { _context.next = 10; break; } throw new Error("Unsupported chainId: " + chainId + " or exchange: " + exchange); case 10: v2Router = networkConfig.router; v2RouterContract = new ethers.Contract(v2Router, uniswapV2RouterABI, signer); _context.prev = 12; // Get pair address and reserves pairAddress = Pair.getAddress(token1, token2); pairContract = new ethers.Contract(pairAddress, uniswapV2poolABI, provider); _context.next = 17; return pairContract['getReserves'](); case 17: reserves = _context.sent; reserve0 = reserves[0], reserve1 = reserves[1]; // Determine token order _ref2 = token1.sortsBefore(token2) ? [token1, token2] : [token2, token1], token0 = _ref2[0], token1Sorted = _ref2[1]; pair = new Pair(CurrencyAmount.fromRawAmount(token0, reserve0), CurrencyAmount.fromRawAmount(token1Sorted, reserve1)); // Create Route and Trade route = new RouteV2([pair], token1, token2); trade = new TradeV2(route, CurrencyAmount.fromRawAmount(token1, amount), TradeType.EXACT_INPUT); // Get router call parameters routerParams = RouterV2.swapCallParameters(trade, { ttl: 50, recipient: signer.address, allowedSlippage: new Percent('1', '100') }); tokenToApprove = new ethers.Contract(routerParams.args[2][0], uniswapV2poolABI, signer); _context.next = 27; return Promise.all([tokenToApprove.balanceOf(signer.address), tokenToApprove.allowance(signer.address, v2Router)]); case 27: _yield$Promise$all = _context.sent; userBalance = _yield$Promise$all[0]; currentAllowance = _yield$Promise$all[1]; console.log('User Balance:', userBalance.toString()); // Approve only if current allowance is insufficient if (!currentAllowance.lt(amount)) { _context.next = 46; break; } console.log("Not enough Allowance, Token Approving..."); _context.prev = 33; _context.next = 36; return tokenToApprove.approve(v2Router, amount, { gasLimit: ethers.utils.hexlify(gasLimit), maxFeePerGas: ethers.utils.parseUnits(finalMaxFeePerGas, 'gwei'), maxPriorityFeePerGas: ethers.utils.parseUnits(finalMaxPriorityFeePerGas, 'gwei') }); case 36: approveTx = _context.sent; _context.next = 39; return approveTx.wait(); case 39: approvalReceipt = _context.sent; console.log('Tokens Approved:', approvalReceipt.transactionHash); _context.next = 46; break; case 43: _context.prev = 43; _context.t0 = _context["catch"](33); if (_context.t0 instanceof Error) { console.error('Error during token approval:', _context.t0.message); } else { console.error('An unknown error occurred:', _context.t0); } case 46: swapTx = { to: v2Router, data: routerParams.methodName === 'swapExactTokensForTokens' ? v2RouterContract["interface"].encodeFunctionData(routerParams.methodName, routerParams.args) : v2RouterContract["interface"].encodeFunctionData(routerParams.methodName, routerParams.args), value: routerParams.value, gasLimit: ethers.utils.hexlify(gasLimit), maxFeePerGas: ethers.utils.parseUnits(finalMaxFeePerGas, 'gwei'), maxPriorityFeePerGas: ethers.utils.parseUnits(finalMaxPriorityFeePerGas, 'gwei') }; _context.next = 49; return signer.sendTransaction(swapTx); case 49: txResponse = _context.sent; _context.next = 52; return txResponse.wait(); case 52: receipt = _context.sent; console.log('Swap Transaction Mined:', receipt.transactionHash); _context.next = 59; break; case 56: _context.prev = 56; _context.t1 = _context["catch"](12); console.error('Swap Failed:', _context.t1); case 59: case "end": return _context.stop(); } }, _callee, null, [[12, 56], [33, 43]]); })); return _swapV.apply(this, arguments); } var txVersion = TxVersion.V0; // Establish connection and initialize Raydium SDK function initSdk(_x) { return _initSdk.apply(this, arguments); } function _initSdk() { _initSdk = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(params) { var privateKey, rpcUrl, owner, connectionConfig, connection, raydium; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: privateKey = params.privateKey, rpcUrl = params.rpcUrl; owner = Keypair.fromSecretKey(bs58.decode(privateKey)); // Configure connection without WebSocket connectionConfig = { commitment: 'confirmed', httpHeaders: { 'x-session-hash': "QNDEMO" + Math.ceil(Math.random() * 1e9) } }; connection = new Connection(rpcUrl || 'https://api.mainnet-beta.solana.com', connectionConfig); _context.next = 6; return Raydium.load({ owner: owner, connection: connection, cluster: 'mainnet', disableFeatureCheck: true, disableLoadToken: !(params != null && params.loadToken), blockhashCommitment: 'finalized' }); case 6: raydium = _context.sent; return _context.abrupt("return", raydium); case 8: case "end": return _context.stop(); } }, _callee); })); return _initSdk.apply(this, arguments); } var JITO_TIP_PAYMENT_ACCOUNT = "96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5"; var MAX_RETRIES = 3; var INITIAL_BACKOFF = 1000; var MAX_BACKOFF = 30000; var JITTER_MAX = 100; var RPC_URL = ""; var COMPUTE_UNITS = 1000000; var DEFAULT_SLIPPAGE = 0.05; var DEFAULT_PRIORITY_FEE = 0.0005; var SOL_TO_MICROLAMPORTS = 1e9; var RETRYABLE_ERRORS = /*#__PURE__*/new Set(['network error', 'connection error', 'transaction simulation failed', 'blockhash not found', 'timed out awaiting confirmation', 'node is behind', 'failed to get recent blockhash', 'too many requests']); var VALID_CLMM_PROGRAM_ID = /*#__PURE__*/new Set([/*#__PURE__*/CLMM_PROGRAM_ID.toBase58()]); var VALID_AMM_PROGRAM_ID = /*#__PURE__*/new Set([/*#__PURE__*/AMM_V4.toBase58(), /*#__PURE__*/AMM_STABLE.toBase58()]); // validating clmm program ID var isValidClmm = function isValidClmm(id) { return VALID_CLMM_PROGRAM_ID.has(id); }; var isValidAmm = function isValidAmm(id) { return VALID_AMM_PROGRAM_ID.has(id); }; // Helper function to add jitter to backoff function addJitter(backoff) { var jitter = Math.random() * JITTER_MAX; return Math.min(backoff + jitter, MAX_BACKOFF); } // Helper function to check if error is retryable function isRetryableError(error) { var errorMessage = error.message.toLowerCase(); return [].concat(RETRYABLE_ERRORS).some(function (e) { return errorMessage.includes(e); }); } function retryWithBackoff(_x, _x2, _x3) { return