@uniswap/router-sdk 1.6.0 → 1.7.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.
- package/dist/constants.d.ts +2 -0
- package/dist/entities/trade.d.ts +11 -1
- package/dist/router-sdk.cjs.development.js +32 -4
- package/dist/router-sdk.cjs.development.js.map +1 -1
- package/dist/router-sdk.cjs.production.min.js +1 -1
- package/dist/router-sdk.cjs.production.min.js.map +1 -1
- package/dist/router-sdk.esm.js +32 -5
- package/dist/router-sdk.esm.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router-sdk.cjs.production.min.js","sources":["../src/approveAndCall.ts","../src/constants.ts","../src/multicallExtended.ts","../src/paymentsExtended.ts","../node_modules/regenerator-runtime/runtime.js","../src/entities/mixedRoute/route.ts","../src/entities/mixedRoute/trade.ts","../src/entities/protocol.ts","../src/entities/route.ts","../src/entities/trade.ts","../src/utils/encodeMixedRouteToPath.ts","../src/utils/index.ts","../src/swapRouter.ts"],"sourcesContent":["import { Interface } from '@ethersproject/abi'\nimport invariant from 'tiny-invariant'\nimport { abi } from '@uniswap/swap-router-contracts/artifacts/contracts/interfaces/IApproveAndCall.sol/IApproveAndCall.json'\nimport { Currency, Percent, Token } from '@uniswap/sdk-core'\nimport {\n MintSpecificOptions,\n IncreaseSpecificOptions,\n NonfungiblePositionManager,\n Position,\n toHex,\n} from '@uniswap/v3-sdk'\nimport JSBI from 'jsbi'\n\n// condensed version of v3-sdk AddLiquidityOptions containing only necessary swap + add attributes\nexport type CondensedAddLiquidityOptions = Omit<MintSpecificOptions, 'createPool'> | IncreaseSpecificOptions\n\nexport enum ApprovalTypes {\n NOT_REQUIRED = 0,\n MAX = 1,\n MAX_MINUS_ONE = 2,\n ZERO_THEN_MAX = 3,\n ZERO_THEN_MAX_MINUS_ONE = 4,\n}\n\n// type guard\nexport function isMint(options: CondensedAddLiquidityOptions): options is Omit<MintSpecificOptions, 'createPool'> {\n return Object.keys(options).some((k) => k === 'recipient')\n}\n\nexport abstract class ApproveAndCall {\n public static INTERFACE: Interface = new Interface(abi)\n\n /**\n * Cannot be constructed.\n */\n private constructor() {}\n\n public static encodeApproveMax(token: Token): string {\n return ApproveAndCall.INTERFACE.encodeFunctionData('approveMax', [token.address])\n }\n\n public static encodeApproveMaxMinusOne(token: Token): string {\n return ApproveAndCall.INTERFACE.encodeFunctionData('approveMaxMinusOne', [token.address])\n }\n\n public static encodeApproveZeroThenMax(token: Token): string {\n return ApproveAndCall.INTERFACE.encodeFunctionData('approveZeroThenMax', [token.address])\n }\n\n public static encodeApproveZeroThenMaxMinusOne(token: Token): string {\n return ApproveAndCall.INTERFACE.encodeFunctionData('approveZeroThenMaxMinusOne', [token.address])\n }\n\n public static encodeCallPositionManager(calldatas: string[]): string {\n invariant(calldatas.length > 0, 'NULL_CALLDATA')\n\n if (calldatas.length == 1) {\n return ApproveAndCall.INTERFACE.encodeFunctionData('callPositionManager', calldatas)\n } else {\n const encodedMulticall = NonfungiblePositionManager.INTERFACE.encodeFunctionData('multicall', [calldatas])\n return ApproveAndCall.INTERFACE.encodeFunctionData('callPositionManager', [encodedMulticall])\n }\n }\n /**\n * Encode adding liquidity to a position in the nft manager contract\n * @param position Forcasted position with expected amount out from swap\n * @param minimalPosition Forcasted position with custom minimal token amounts\n * @param addLiquidityOptions Options for adding liquidity\n * @param slippageTolerance Defines maximum slippage\n */\n public static encodeAddLiquidity(\n position: Position,\n minimalPosition: Position,\n addLiquidityOptions: CondensedAddLiquidityOptions,\n slippageTolerance: Percent\n ): string {\n let { amount0: amount0Min, amount1: amount1Min } = position.mintAmountsWithSlippage(slippageTolerance)\n\n // position.mintAmountsWithSlippage() can create amounts not dependenable in scenarios\n // such as range orders. Allow the option to provide a position with custom minimum amounts\n // for these scenarios\n if (JSBI.lessThan(minimalPosition.amount0.quotient, amount0Min)) {\n amount0Min = minimalPosition.amount0.quotient\n }\n if (JSBI.lessThan(minimalPosition.amount1.quotient, amount1Min)) {\n amount1Min = minimalPosition.amount1.quotient\n }\n\n if (isMint(addLiquidityOptions)) {\n return ApproveAndCall.INTERFACE.encodeFunctionData('mint', [\n {\n token0: position.pool.token0.address,\n token1: position.pool.token1.address,\n fee: position.pool.fee,\n tickLower: position.tickLower,\n tickUpper: position.tickUpper,\n amount0Min: toHex(amount0Min),\n amount1Min: toHex(amount1Min),\n recipient: addLiquidityOptions.recipient,\n },\n ])\n } else {\n return ApproveAndCall.INTERFACE.encodeFunctionData('increaseLiquidity', [\n {\n token0: position.pool.token0.address,\n token1: position.pool.token1.address,\n amount0Min: toHex(amount0Min),\n amount1Min: toHex(amount1Min),\n tokenId: toHex(addLiquidityOptions.tokenId),\n },\n ])\n }\n }\n\n public static encodeApprove(token: Currency, approvalType: ApprovalTypes): string {\n switch (approvalType) {\n case ApprovalTypes.MAX:\n return ApproveAndCall.encodeApproveMax(token.wrapped)\n case ApprovalTypes.MAX_MINUS_ONE:\n return ApproveAndCall.encodeApproveMaxMinusOne(token.wrapped)\n case ApprovalTypes.ZERO_THEN_MAX:\n return ApproveAndCall.encodeApproveZeroThenMax(token.wrapped)\n case ApprovalTypes.ZERO_THEN_MAX_MINUS_ONE:\n return ApproveAndCall.encodeApproveZeroThenMaxMinusOne(token.wrapped)\n default:\n throw 'Error: invalid ApprovalType'\n }\n }\n}\n","import JSBI from 'jsbi'\n\nexport const MSG_SENDER = '0x0000000000000000000000000000000000000001'\nexport const ADDRESS_THIS = '0x0000000000000000000000000000000000000002'\n\nexport const ZERO = JSBI.BigInt(0)\nexport const ONE = JSBI.BigInt(1)\n\n// = 1 << 23 or 100000000000000000000000\nexport const V2_FEE_PATH_PLACEHOLDER = 8388608\n","import { Interface } from '@ethersproject/abi'\nimport { BigintIsh } from '@uniswap/sdk-core'\nimport { abi } from '@uniswap/swap-router-contracts/artifacts/contracts/interfaces/IMulticallExtended.sol/IMulticallExtended.json'\nimport { Multicall, toHex } from '@uniswap/v3-sdk'\n\n// deadline or previousBlockhash\nexport type Validation = BigintIsh | string\n\nfunction validateAndParseBytes32(bytes32: string): string {\n if (!bytes32.match(/^0x[0-9a-fA-F]{64}$/)) {\n throw new Error(`${bytes32} is not valid bytes32.`)\n }\n\n return bytes32.toLowerCase()\n}\n\nexport abstract class MulticallExtended {\n public static INTERFACE: Interface = new Interface(abi)\n\n /**\n * Cannot be constructed.\n */\n private constructor() {}\n\n public static encodeMulticall(calldatas: string | string[], validation?: Validation): string {\n // if there's no validation, we can just fall back to regular multicall\n if (typeof validation === 'undefined') {\n return Multicall.encodeMulticall(calldatas)\n }\n\n // if there is validation, we have to normalize calldatas\n if (!Array.isArray(calldatas)) {\n calldatas = [calldatas]\n }\n\n // this means the validation value should be a previousBlockhash\n if (typeof validation === 'string' && validation.startsWith('0x')) {\n const previousBlockhash = validateAndParseBytes32(validation)\n return MulticallExtended.INTERFACE.encodeFunctionData('multicall(bytes32,bytes[])', [\n previousBlockhash,\n calldatas,\n ])\n } else {\n const deadline = toHex(validation)\n return MulticallExtended.INTERFACE.encodeFunctionData('multicall(uint256,bytes[])', [deadline, calldatas])\n }\n }\n}\n","import { Interface } from '@ethersproject/abi'\nimport { Percent, Token, validateAndParseAddress } from '@uniswap/sdk-core'\nimport { abi } from '@uniswap/swap-router-contracts/artifacts/contracts/interfaces/IPeripheryPaymentsWithFeeExtended.sol/IPeripheryPaymentsWithFeeExtended.json'\nimport { FeeOptions, Payments, toHex } from '@uniswap/v3-sdk'\nimport JSBI from 'jsbi'\n\nfunction encodeFeeBips(fee: Percent): string {\n return toHex(fee.multiply(10_000).quotient)\n}\n\nexport abstract class PaymentsExtended {\n public static INTERFACE: Interface = new Interface(abi)\n\n /**\n * Cannot be constructed.\n */\n private constructor() {}\n\n public static encodeUnwrapWETH9(amountMinimum: JSBI, recipient?: string, feeOptions?: FeeOptions): string {\n // if there's a recipient, just pass it along\n if (typeof recipient === 'string') {\n return Payments.encodeUnwrapWETH9(amountMinimum, recipient, feeOptions)\n }\n\n if (!!feeOptions) {\n const feeBips = encodeFeeBips(feeOptions.fee)\n const feeRecipient = validateAndParseAddress(feeOptions.recipient)\n\n return PaymentsExtended.INTERFACE.encodeFunctionData('unwrapWETH9WithFee(uint256,uint256,address)', [\n toHex(amountMinimum),\n feeBips,\n feeRecipient,\n ])\n } else {\n return PaymentsExtended.INTERFACE.encodeFunctionData('unwrapWETH9(uint256)', [toHex(amountMinimum)])\n }\n }\n\n public static encodeSweepToken(\n token: Token,\n amountMinimum: JSBI,\n recipient?: string,\n feeOptions?: FeeOptions\n ): string {\n // if there's a recipient, just pass it along\n if (typeof recipient === 'string') {\n return Payments.encodeSweepToken(token, amountMinimum, recipient, feeOptions)\n }\n\n if (!!feeOptions) {\n const feeBips = encodeFeeBips(feeOptions.fee)\n const feeRecipient = validateAndParseAddress(feeOptions.recipient)\n\n return PaymentsExtended.INTERFACE.encodeFunctionData('sweepTokenWithFee(address,uint256,uint256,address)', [\n token.address,\n toHex(amountMinimum),\n feeBips,\n feeRecipient,\n ])\n } else {\n return PaymentsExtended.INTERFACE.encodeFunctionData('sweepToken(address,uint256)', [\n token.address,\n toHex(amountMinimum),\n ])\n }\n }\n\n public static encodePull(token: Token, amount: JSBI): string {\n return PaymentsExtended.INTERFACE.encodeFunctionData('pull', [token.address, toHex(amount)])\n }\n\n public static encodeWrapETH(amount: JSBI): string {\n return PaymentsExtended.INTERFACE.encodeFunctionData('wrapETH', [toHex(amount)])\n }\n}\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = GeneratorFunctionPrototype;\n define(Gp, \"constructor\", GeneratorFunctionPrototype);\n define(GeneratorFunctionPrototype, \"constructor\", GeneratorFunction);\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n });\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n define(Gp, iteratorSymbol, function() {\n return this;\n });\n\n define(Gp, \"toString\", function() {\n return \"[object Generator]\";\n });\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, in modern engines\n // we can explicitly access globalThis. In older engines we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n","import invariant from 'tiny-invariant'\n\nimport { Currency, Price, Token } from '@uniswap/sdk-core'\nimport { Pool } from '@uniswap/v3-sdk'\nimport { Pair } from '@uniswap/v2-sdk'\n\ntype TPool = Pair | Pool\n\n/**\n * Represents a list of pools or pairs through which a swap can occur\n * @template TInput The input token\n * @template TOutput The output token\n */\nexport class MixedRouteSDK<TInput extends Currency, TOutput extends Currency> {\n public readonly pools: TPool[]\n public readonly path: Token[]\n public readonly input: TInput\n public readonly output: TOutput\n\n private _midPrice: Price<TInput, TOutput> | null = null\n\n /**\n * Creates an instance of route.\n * @param pools An array of `TPool` objects (pools or pairs), ordered by the route the swap will take\n * @param input The input token\n * @param output The output token\n */\n public constructor(pools: TPool[], input: TInput, output: TOutput) {\n invariant(pools.length > 0, 'POOLS')\n\n const chainId = pools[0].chainId\n const allOnSameChain = pools.every((pool) => pool.chainId === chainId)\n invariant(allOnSameChain, 'CHAIN_IDS')\n\n const wrappedInput = input.wrapped\n invariant(pools[0].involvesToken(wrappedInput), 'INPUT')\n\n invariant(pools[pools.length - 1].involvesToken(output.wrapped), 'OUTPUT')\n\n /**\n * Normalizes token0-token1 order and selects the next token/fee step to add to the path\n * */\n const tokenPath: Token[] = [wrappedInput]\n for (const [i, pool] of pools.entries()) {\n const currentInputToken = tokenPath[i]\n invariant(currentInputToken.equals(pool.token0) || currentInputToken.equals(pool.token1), 'PATH')\n const nextToken = currentInputToken.equals(pool.token0) ? pool.token1 : pool.token0\n tokenPath.push(nextToken)\n }\n\n this.pools = pools\n this.path = tokenPath\n this.input = input\n this.output = output ?? tokenPath[tokenPath.length - 1]\n }\n\n public get chainId(): number {\n return this.pools[0].chainId\n }\n\n /**\n * Returns the mid price of the route\n */\n public get midPrice(): Price<TInput, TOutput> {\n if (this._midPrice !== null) return this._midPrice\n\n const price = this.pools.slice(1).reduce(\n ({ nextInput, price }, pool) => {\n return nextInput.equals(pool.token0)\n ? {\n nextInput: pool.token1,\n price: price.multiply(pool.token0Price),\n }\n : {\n nextInput: pool.token0,\n price: price.multiply(pool.token1Price),\n }\n },\n this.pools[0].token0.equals(this.input.wrapped)\n ? {\n nextInput: this.pools[0].token1,\n price: this.pools[0].token0Price,\n }\n : {\n nextInput: this.pools[0].token0,\n price: this.pools[0].token1Price,\n }\n ).price\n\n return (this._midPrice = new Price(this.input, this.output, price.denominator, price.numerator))\n }\n}\n","import { Currency, Fraction, Percent, Price, sortedInsert, CurrencyAmount, TradeType, Token } from '@uniswap/sdk-core'\nimport { Pair } from '@uniswap/v2-sdk'\nimport { BestTradeOptions, Pool } from '@uniswap/v3-sdk'\nimport invariant from 'tiny-invariant'\nimport { ONE, ZERO } from '../../constants'\nimport { MixedRouteSDK } from './route'\n\n/**\n * Trades comparator, an extension of the input output comparator that also considers other dimensions of the trade in ranking them\n * @template TInput The input token, either Ether or an ERC-20\n * @template TOutput The output token, either Ether or an ERC-20\n * @template TTradeType The trade type, either exact input or exact output\n * @param a The first trade to compare\n * @param b The second trade to compare\n * @returns A sorted ordering for two neighboring elements in a trade array\n */\nexport function tradeComparator<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(\n a: MixedRouteTrade<TInput, TOutput, TTradeType>,\n b: MixedRouteTrade<TInput, TOutput, TTradeType>\n) {\n // must have same input and output token for comparison\n invariant(a.inputAmount.currency.equals(b.inputAmount.currency), 'INPUT_CURRENCY')\n invariant(a.outputAmount.currency.equals(b.outputAmount.currency), 'OUTPUT_CURRENCY')\n if (a.outputAmount.equalTo(b.outputAmount)) {\n if (a.inputAmount.equalTo(b.inputAmount)) {\n // consider the number of hops since each hop costs gas\n const aHops = a.swaps.reduce((total, cur) => total + cur.route.path.length, 0)\n const bHops = b.swaps.reduce((total, cur) => total + cur.route.path.length, 0)\n return aHops - bHops\n }\n // trade A requires less input than trade B, so A should come first\n if (a.inputAmount.lessThan(b.inputAmount)) {\n return -1\n } else {\n return 1\n }\n } else {\n // tradeA has less output than trade B, so should come second\n if (a.outputAmount.lessThan(b.outputAmount)) {\n return 1\n } else {\n return -1\n }\n }\n}\n\n/**\n * Represents a trade executed against a set of routes where some percentage of the input is\n * split across each route.\n *\n * Each route has its own set of pools. Pools can not be re-used across routes.\n *\n * Does not account for slippage, i.e., changes in price environment that can occur between\n * the time the trade is submitted and when it is executed.\n * @notice This class is functionally the same as the `Trade` class in the `@uniswap/v3-sdk` package, aside from typing and some input validation.\n * @template TInput The input token, either Ether or an ERC-20\n * @template TOutput The output token, either Ether or an ERC-20\n * @template TTradeType The trade type, either exact input or exact output\n */\nexport class MixedRouteTrade<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType> {\n /**\n * @deprecated Deprecated in favor of 'swaps' property. If the trade consists of multiple routes\n * this will return an error.\n *\n * When the trade consists of just a single route, this returns the route of the trade,\n * i.e. which pools the trade goes through.\n */\n public get route(): MixedRouteSDK<TInput, TOutput> {\n invariant(this.swaps.length == 1, 'MULTIPLE_ROUTES')\n return this.swaps[0].route\n }\n\n /**\n * The swaps of the trade, i.e. which routes and how much is swapped in each that\n * make up the trade.\n */\n public readonly swaps: {\n route: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n\n /**\n * The type of the trade, either exact in or exact out.\n */\n public readonly tradeType: TTradeType\n\n /**\n * The cached result of the input amount computation\n * @private\n */\n private _inputAmount: CurrencyAmount<TInput> | undefined\n\n /**\n * The input amount for the trade assuming no slippage.\n */\n public get inputAmount(): CurrencyAmount<TInput> {\n if (this._inputAmount) {\n return this._inputAmount\n }\n\n const inputCurrency = this.swaps[0].inputAmount.currency\n const totalInputFromRoutes = this.swaps\n .map(({ inputAmount }) => inputAmount)\n .reduce((total, cur) => total.add(cur), CurrencyAmount.fromRawAmount(inputCurrency, 0))\n\n this._inputAmount = totalInputFromRoutes\n return this._inputAmount\n }\n\n /**\n * The cached result of the output amount computation\n * @private\n */\n private _outputAmount: CurrencyAmount<TOutput> | undefined\n\n /**\n * The output amount for the trade assuming no slippage.\n */\n public get outputAmount(): CurrencyAmount<TOutput> {\n if (this._outputAmount) {\n return this._outputAmount\n }\n\n const outputCurrency = this.swaps[0].outputAmount.currency\n const totalOutputFromRoutes = this.swaps\n .map(({ outputAmount }) => outputAmount)\n .reduce((total, cur) => total.add(cur), CurrencyAmount.fromRawAmount(outputCurrency, 0))\n\n this._outputAmount = totalOutputFromRoutes\n return this._outputAmount\n }\n\n /**\n * The cached result of the computed execution price\n * @private\n */\n private _executionPrice: Price<TInput, TOutput> | undefined\n\n /**\n * The price expressed in terms of output amount/input amount.\n */\n public get executionPrice(): Price<TInput, TOutput> {\n return (\n this._executionPrice ??\n (this._executionPrice = new Price(\n this.inputAmount.currency,\n this.outputAmount.currency,\n this.inputAmount.quotient,\n this.outputAmount.quotient\n ))\n )\n }\n\n /**\n * The cached result of the price impact computation\n * @private\n */\n private _priceImpact: Percent | undefined\n\n /**\n * Returns the percent difference between the route's mid price and the price impact\n */\n public get priceImpact(): Percent {\n if (this._priceImpact) {\n return this._priceImpact\n }\n\n let spotOutputAmount = CurrencyAmount.fromRawAmount(this.outputAmount.currency, 0)\n for (const { route, inputAmount } of this.swaps) {\n const midPrice = route.midPrice\n spotOutputAmount = spotOutputAmount.add(midPrice.quote(inputAmount))\n }\n\n const priceImpact = spotOutputAmount.subtract(this.outputAmount).divide(spotOutputAmount)\n this._priceImpact = new Percent(priceImpact.numerator, priceImpact.denominator)\n\n return this._priceImpact\n }\n\n /**\n * Constructs a trade by simulating swaps through the given route\n * @template TInput The input token, either Ether or an ERC-20.\n * @template TOutput The output token, either Ether or an ERC-20.\n * @template TTradeType The type of the trade, either exact in or exact out.\n * @param route route to swap through\n * @param amount the amount specified, either input or output, depending on tradeType\n * @param tradeType whether the trade is an exact input or exact output swap\n * @returns The route\n */\n public static async fromRoute<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(\n route: MixedRouteSDK<TInput, TOutput>,\n amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>,\n tradeType: TTradeType\n ): Promise<MixedRouteTrade<TInput, TOutput, TTradeType>> {\n const amounts: CurrencyAmount<Token>[] = new Array(route.path.length)\n let inputAmount: CurrencyAmount<TInput>\n let outputAmount: CurrencyAmount<TOutput>\n\n invariant(tradeType === TradeType.EXACT_INPUT, 'TRADE_TYPE')\n\n invariant(amount.currency.equals(route.input), 'INPUT')\n amounts[0] = amount.wrapped\n for (let i = 0; i < route.path.length - 1; i++) {\n const pool = route.pools[i]\n const [outputAmount] = await pool.getOutputAmount(amounts[i])\n amounts[i + 1] = outputAmount\n }\n inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator)\n outputAmount = CurrencyAmount.fromFractionalAmount(\n route.output,\n amounts[amounts.length - 1].numerator,\n amounts[amounts.length - 1].denominator\n )\n\n return new MixedRouteTrade({\n routes: [{ inputAmount, outputAmount, route }],\n tradeType,\n })\n }\n\n /**\n * Constructs a trade from routes by simulating swaps\n *\n * @template TInput The input token, either Ether or an ERC-20.\n * @template TOutput The output token, either Ether or an ERC-20.\n * @template TTradeType The type of the trade, either exact in or exact out.\n * @param routes the routes to swap through and how much of the amount should be routed through each\n * @param tradeType whether the trade is an exact input or exact output swap\n * @returns The trade\n */\n public static async fromRoutes<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(\n routes: {\n amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>\n route: MixedRouteSDK<TInput, TOutput>\n }[],\n tradeType: TTradeType\n ): Promise<MixedRouteTrade<TInput, TOutput, TTradeType>> {\n const populatedRoutes: {\n route: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n invariant(tradeType === TradeType.EXACT_INPUT, 'TRADE_TYPE')\n\n for (const { route, amount } of routes) {\n const amounts: CurrencyAmount<Token>[] = new Array(route.path.length)\n let inputAmount: CurrencyAmount<TInput>\n let outputAmount: CurrencyAmount<TOutput>\n\n invariant(amount.currency.equals(route.input), 'INPUT')\n inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator)\n amounts[0] = CurrencyAmount.fromFractionalAmount(route.input.wrapped, amount.numerator, amount.denominator)\n\n for (let i = 0; i < route.path.length - 1; i++) {\n const pool = route.pools[i]\n const [outputAmount] = await pool.getOutputAmount(amounts[i])\n amounts[i + 1] = outputAmount\n }\n\n outputAmount = CurrencyAmount.fromFractionalAmount(\n route.output,\n amounts[amounts.length - 1].numerator,\n amounts[amounts.length - 1].denominator\n )\n\n populatedRoutes.push({ route, inputAmount, outputAmount })\n }\n\n return new MixedRouteTrade({\n routes: populatedRoutes,\n tradeType,\n })\n }\n\n /**\n * Creates a trade without computing the result of swapping through the route. Useful when you have simulated the trade\n * elsewhere and do not have any tick data\n * @template TInput The input token, either Ether or an ERC-20\n * @template TOutput The output token, either Ether or an ERC-20\n * @template TTradeType The type of the trade, either exact in or exact out\n * @param constructorArguments The arguments passed to the trade constructor\n * @returns The unchecked trade\n */\n public static createUncheckedTrade<\n TInput extends Currency,\n TOutput extends Currency,\n TTradeType extends TradeType\n >(constructorArguments: {\n route: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n tradeType: TTradeType\n }): MixedRouteTrade<TInput, TOutput, TTradeType> {\n return new MixedRouteTrade({\n ...constructorArguments,\n routes: [\n {\n inputAmount: constructorArguments.inputAmount,\n outputAmount: constructorArguments.outputAmount,\n route: constructorArguments.route,\n },\n ],\n })\n }\n\n /**\n * Creates a trade without computing the result of swapping through the routes. Useful when you have simulated the trade\n * elsewhere and do not have any tick data\n * @template TInput The input token, either Ether or an ERC-20\n * @template TOutput The output token, either Ether or an ERC-20\n * @template TTradeType The type of the trade, either exact in or exact out\n * @param constructorArguments The arguments passed to the trade constructor\n * @returns The unchecked trade\n */\n public static createUncheckedTradeWithMultipleRoutes<\n TInput extends Currency,\n TOutput extends Currency,\n TTradeType extends TradeType\n >(constructorArguments: {\n routes: {\n route: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n tradeType: TTradeType\n }): MixedRouteTrade<TInput, TOutput, TTradeType> {\n return new MixedRouteTrade(constructorArguments)\n }\n\n /**\n * Construct a trade by passing in the pre-computed property values\n * @param routes The routes through which the trade occurs\n * @param tradeType The type of trade, exact input or exact output\n */\n private constructor({\n routes,\n tradeType,\n }: {\n routes: {\n route: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n tradeType: TTradeType\n }) {\n const inputCurrency = routes[0].inputAmount.currency\n const outputCurrency = routes[0].outputAmount.currency\n invariant(\n routes.every(({ route }) => inputCurrency.wrapped.equals(route.input.wrapped)),\n 'INPUT_CURRENCY_MATCH'\n )\n invariant(\n routes.every(({ route }) => outputCurrency.wrapped.equals(route.output.wrapped)),\n 'OUTPUT_CURRENCY_MATCH'\n )\n\n const numPools = routes.map(({ route }) => route.pools.length).reduce((total, cur) => total + cur, 0)\n const poolAddressSet = new Set<string>()\n for (const { route } of routes) {\n for (const pool of route.pools) {\n pool instanceof Pool\n ? poolAddressSet.add(Pool.getAddress(pool.token0, pool.token1, pool.fee))\n : poolAddressSet.add(Pair.getAddress(pool.token0, pool.token1))\n }\n }\n\n invariant(numPools == poolAddressSet.size, 'POOLS_DUPLICATED')\n\n invariant(tradeType === TradeType.EXACT_INPUT, 'TRADE_TYPE')\n\n this.swaps = routes\n this.tradeType = tradeType\n }\n\n /**\n * Get the minimum amount that must be received from this trade for the given slippage tolerance\n * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade\n * @returns The amount out\n */\n public minimumAmountOut(slippageTolerance: Percent, amountOut = this.outputAmount): CurrencyAmount<TOutput> {\n invariant(!slippageTolerance.lessThan(ZERO), 'SLIPPAGE_TOLERANCE')\n /// does not support exactOutput, as enforced in the constructor\n const slippageAdjustedAmountOut = new Fraction(ONE)\n .add(slippageTolerance)\n .invert()\n .multiply(amountOut.quotient).quotient\n return CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut)\n }\n\n /**\n * Get the maximum amount in that can be spent via this trade for the given slippage tolerance\n * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade\n * @returns The amount in\n */\n public maximumAmountIn(slippageTolerance: Percent, amountIn = this.inputAmount): CurrencyAmount<TInput> {\n invariant(!slippageTolerance.lessThan(ZERO), 'SLIPPAGE_TOLERANCE')\n return amountIn\n /// does not support exactOutput\n }\n\n /**\n * Return the execution price after accounting for slippage tolerance\n * @param slippageTolerance the allowed tolerated slippage\n * @returns The execution price\n */\n public worstExecutionPrice(slippageTolerance: Percent): Price<TInput, TOutput> {\n return new Price(\n this.inputAmount.currency,\n this.outputAmount.currency,\n this.maximumAmountIn(slippageTolerance).quotient,\n this.minimumAmountOut(slippageTolerance).quotient\n )\n }\n\n /**\n * Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token\n * amount to an output token, making at most `maxHops` hops.\n * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting\n * the amount in among multiple routes.\n * @param pools the pools to consider in finding the best trade\n * @param nextAmountIn exact amount of input currency to spend\n * @param currencyOut the desired currency out\n * @param maxNumResults maximum number of results to return\n * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool\n * @param currentPools used in recursion; the current list of pools\n * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter\n * @param bestTrades used in recursion; the current list of best trades\n * @returns The exact in trade\n */\n public static async bestTradeExactIn<TInput extends Currency, TOutput extends Currency>(\n pools: (Pool | Pair)[],\n currencyAmountIn: CurrencyAmount<TInput>,\n currencyOut: TOutput,\n { maxNumResults = 3, maxHops = 3 }: BestTradeOptions = {},\n // used in recursion.\n currentPools: (Pool | Pair)[] = [],\n nextAmountIn: CurrencyAmount<Currency> = currencyAmountIn,\n bestTrades: MixedRouteTrade<TInput, TOutput, TradeType.EXACT_INPUT>[] = []\n ): Promise<MixedRouteTrade<TInput, TOutput, TradeType.EXACT_INPUT>[]> {\n invariant(pools.length > 0, 'POOLS')\n invariant(maxHops > 0, 'MAX_HOPS')\n invariant(currencyAmountIn === nextAmountIn || currentPools.length > 0, 'INVALID_RECURSION')\n\n const amountIn = nextAmountIn.wrapped\n const tokenOut = currencyOut.wrapped\n for (let i = 0; i < pools.length; i++) {\n const pool = pools[i]\n // pool irrelevant\n if (!pool.token0.equals(amountIn.currency) && !pool.token1.equals(amountIn.currency)) continue\n if (pool instanceof Pair) {\n if ((pool as Pair).reserve0.equalTo(ZERO) || (pool as Pair).reserve1.equalTo(ZERO)) continue\n }\n\n let amountOut: CurrencyAmount<Token>\n try {\n ;[amountOut] = await pool.getOutputAmount(amountIn)\n } catch (error) {\n // input too low\n // @ts-ignore[2571] error is unknown\n if (error.isInsufficientInputAmountError) {\n continue\n }\n throw error\n }\n // we have arrived at the output token, so this is the final trade of one of the paths\n if (amountOut.currency.isToken && amountOut.currency.equals(tokenOut)) {\n sortedInsert(\n bestTrades,\n await MixedRouteTrade.fromRoute(\n new MixedRouteSDK([...currentPools, pool], currencyAmountIn.currency, currencyOut),\n currencyAmountIn,\n TradeType.EXACT_INPUT\n ),\n maxNumResults,\n tradeComparator\n )\n } else if (maxHops > 1 && pools.length > 1) {\n const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length))\n\n // otherwise, consider all the other paths that lead from this token as long as we have not exceeded maxHops\n await MixedRouteTrade.bestTradeExactIn(\n poolsExcludingThisPool,\n currencyAmountIn,\n currencyOut,\n {\n maxNumResults,\n maxHops: maxHops - 1,\n },\n [...currentPools, pool],\n amountOut,\n bestTrades\n )\n }\n }\n\n return bestTrades\n }\n}\n","export enum Protocol {\n V2 = 'V2',\n V3 = 'V3',\n MIXED = 'MIXED',\n}\n","// entities/route.ts\n\nimport { Route as V2RouteSDK, Pair } from '@uniswap/v2-sdk'\nimport { Route as V3RouteSDK, Pool } from '@uniswap/v3-sdk'\nimport { Protocol } from './protocol'\nimport { Currency, Price, Token } from '@uniswap/sdk-core'\nimport { MixedRouteSDK } from './mixedRoute/route'\n\nexport interface IRoute<TInput extends Currency, TOutput extends Currency, TPool extends Pool | Pair> {\n protocol: Protocol\n // array of pools if v3 or pairs if v2\n pools: TPool[]\n path: Token[]\n midPrice: Price<TInput, TOutput>\n input: TInput\n output: TOutput\n}\n\n// V2 route wrapper\nexport class RouteV2<TInput extends Currency, TOutput extends Currency>\n extends V2RouteSDK<TInput, TOutput>\n implements IRoute<TInput, TOutput, Pair>\n{\n public readonly protocol: Protocol = Protocol.V2\n public readonly pools: Pair[]\n\n constructor(v2Route: V2RouteSDK<TInput, TOutput>) {\n super(v2Route.pairs, v2Route.input, v2Route.output)\n this.pools = this.pairs\n }\n}\n\n// V3 route wrapper\nexport class RouteV3<TInput extends Currency, TOutput extends Currency>\n extends V3RouteSDK<TInput, TOutput>\n implements IRoute<TInput, TOutput, Pool>\n{\n public readonly protocol: Protocol = Protocol.V3\n public readonly path: Token[]\n\n constructor(v3Route: V3RouteSDK<TInput, TOutput>) {\n super(v3Route.pools, v3Route.input, v3Route.output)\n this.path = v3Route.tokenPath\n }\n}\n\n// Mixed route wrapper\nexport class MixedRoute<TInput extends Currency, TOutput extends Currency>\n extends MixedRouteSDK<TInput, TOutput>\n implements IRoute<TInput, TOutput, Pool | Pair>\n{\n public readonly protocol: Protocol = Protocol.MIXED\n\n constructor(mixedRoute: MixedRouteSDK<TInput, TOutput>) {\n super(mixedRoute.pools, mixedRoute.input, mixedRoute.output)\n }\n}\n","import { Currency, CurrencyAmount, Fraction, Percent, Price, TradeType } from '@uniswap/sdk-core'\nimport { Pair, Route as V2RouteSDK, Trade as V2TradeSDK } from '@uniswap/v2-sdk'\nimport { Pool, Route as V3RouteSDK, Trade as V3TradeSDK } from '@uniswap/v3-sdk'\nimport invariant from 'tiny-invariant'\nimport { ONE, ZERO } from '../constants'\nimport { MixedRouteSDK } from './mixedRoute/route'\nimport { MixedRouteTrade as MixedRouteTradeSDK } from './mixedRoute/trade'\nimport { IRoute, MixedRoute, RouteV2, RouteV3 } from './route'\n\nexport class Trade<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType> {\n public readonly routes: IRoute<TInput, TOutput, Pair | Pool>[]\n public readonly tradeType: TTradeType\n private _outputAmount: CurrencyAmount<TOutput> | undefined\n private _inputAmount: CurrencyAmount<TInput> | undefined\n\n /**\n * The swaps of the trade, i.e. which routes and how much is swapped in each that\n * make up the trade. May consist of swaps in v2 or v3.\n */\n public readonly swaps: {\n route: IRoute<TInput, TOutput, Pair | Pool>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n\n // construct a trade across v2 and v3 routes from pre-computed amounts\n public constructor({\n v2Routes,\n v3Routes,\n tradeType,\n mixedRoutes,\n }: {\n v2Routes: {\n routev2: V2RouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n v3Routes: {\n routev3: V3RouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n tradeType: TTradeType\n mixedRoutes?: {\n mixedRoute: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n }) {\n this.swaps = []\n this.routes = []\n // wrap v2 routes\n for (const { routev2, inputAmount, outputAmount } of v2Routes) {\n const route = new RouteV2(routev2)\n this.routes.push(route)\n this.swaps.push({\n route,\n inputAmount,\n outputAmount,\n })\n }\n // wrap v3 routes\n for (const { routev3, inputAmount, outputAmount } of v3Routes) {\n const route = new RouteV3(routev3)\n this.routes.push(route)\n this.swaps.push({\n route,\n inputAmount,\n outputAmount,\n })\n }\n // wrap mixedRoutes\n if (mixedRoutes) {\n for (const { mixedRoute, inputAmount, outputAmount } of mixedRoutes) {\n const route = new MixedRoute(mixedRoute)\n this.routes.push(route)\n this.swaps.push({\n route,\n inputAmount,\n outputAmount,\n })\n }\n }\n this.tradeType = tradeType\n\n // each route must have the same input and output currency\n const inputCurrency = this.swaps[0].inputAmount.currency\n const outputCurrency = this.swaps[0].outputAmount.currency\n invariant(\n this.swaps.every(({ route }) => inputCurrency.wrapped.equals(route.input.wrapped)),\n 'INPUT_CURRENCY_MATCH'\n )\n invariant(\n this.swaps.every(({ route }) => outputCurrency.wrapped.equals(route.output.wrapped)),\n 'OUTPUT_CURRENCY_MATCH'\n )\n\n // pools must be unique inter protocols\n const numPools = this.swaps.map(({ route }) => route.pools.length).reduce((total, cur) => total + cur, 0)\n const poolAddressSet = new Set<string>()\n for (const { route } of this.swaps) {\n for (const pool of route.pools) {\n if (pool instanceof Pool) {\n poolAddressSet.add(Pool.getAddress(pool.token0, pool.token1, (pool as Pool).fee))\n } else if (pool instanceof Pair) {\n const pair = pool\n poolAddressSet.add(Pair.getAddress(pair.token0, pair.token1))\n } else {\n throw new Error('Unexpected pool type in route when constructing trade object')\n }\n }\n }\n invariant(numPools == poolAddressSet.size, 'POOLS_DUPLICATED')\n }\n\n public get inputAmount(): CurrencyAmount<TInput> {\n if (this._inputAmount) {\n return this._inputAmount\n }\n\n const inputCurrency = this.swaps[0].inputAmount.currency\n const totalInputFromRoutes = this.swaps\n .map(({ inputAmount }) => inputAmount)\n .reduce((total, cur) => total.add(cur), CurrencyAmount.fromRawAmount(inputCurrency, 0))\n\n this._inputAmount = totalInputFromRoutes\n return this._inputAmount\n }\n\n public get outputAmount(): CurrencyAmount<TOutput> {\n if (this._outputAmount) {\n return this._outputAmount\n }\n\n const outputCurrency = this.swaps[0].outputAmount.currency\n const totalOutputFromRoutes = this.swaps\n .map(({ outputAmount }) => outputAmount)\n .reduce((total, cur) => total.add(cur), CurrencyAmount.fromRawAmount(outputCurrency, 0))\n\n this._outputAmount = totalOutputFromRoutes\n return this._outputAmount\n }\n\n private _executionPrice: Price<TInput, TOutput> | undefined\n\n /**\n * The price expressed in terms of output amount/input amount.\n */\n public get executionPrice(): Price<TInput, TOutput> {\n return (\n this._executionPrice ??\n (this._executionPrice = new Price(\n this.inputAmount.currency,\n this.outputAmount.currency,\n this.inputAmount.quotient,\n this.outputAmount.quotient\n ))\n )\n }\n\n /**\n * The cached result of the price impact computation\n * @private\n */\n private _priceImpact: Percent | undefined\n /**\n * Returns the percent difference between the route's mid price and the price impact\n */\n public get priceImpact(): Percent {\n if (this._priceImpact) {\n return this._priceImpact\n }\n\n let spotOutputAmount = CurrencyAmount.fromRawAmount(this.outputAmount.currency, 0)\n for (const { route, inputAmount } of this.swaps) {\n const midPrice = route.midPrice\n spotOutputAmount = spotOutputAmount.add(midPrice.quote(inputAmount))\n }\n\n const priceImpact = spotOutputAmount.subtract(this.outputAmount).divide(spotOutputAmount)\n this._priceImpact = new Percent(priceImpact.numerator, priceImpact.denominator)\n\n return this._priceImpact\n }\n\n /**\n * Get the minimum amount that must be received from this trade for the given slippage tolerance\n * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade\n * @returns The amount out\n */\n public minimumAmountOut(slippageTolerance: Percent, amountOut = this.outputAmount): CurrencyAmount<TOutput> {\n invariant(!slippageTolerance.lessThan(ZERO), 'SLIPPAGE_TOLERANCE')\n if (this.tradeType === TradeType.EXACT_OUTPUT) {\n return amountOut\n } else {\n const slippageAdjustedAmountOut = new Fraction(ONE)\n .add(slippageTolerance)\n .invert()\n .multiply(amountOut.quotient).quotient\n return CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut)\n }\n }\n\n /**\n * Get the maximum amount in that can be spent via this trade for the given slippage tolerance\n * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade\n * @returns The amount in\n */\n public maximumAmountIn(slippageTolerance: Percent, amountIn = this.inputAmount): CurrencyAmount<TInput> {\n invariant(!slippageTolerance.lessThan(ZERO), 'SLIPPAGE_TOLERANCE')\n if (this.tradeType === TradeType.EXACT_INPUT) {\n return amountIn\n } else {\n const slippageAdjustedAmountIn = new Fraction(ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient\n return CurrencyAmount.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn)\n }\n }\n\n /**\n * Return the execution price after accounting for slippage tolerance\n * @param slippageTolerance the allowed tolerated slippage\n * @returns The execution price\n */\n public worstExecutionPrice(slippageTolerance: Percent): Price<TInput, TOutput> {\n return new Price(\n this.inputAmount.currency,\n this.outputAmount.currency,\n this.maximumAmountIn(slippageTolerance).quotient,\n this.minimumAmountOut(slippageTolerance).quotient\n )\n }\n\n public static async fromRoutes<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(\n v2Routes: {\n routev2: V2RouteSDK<TInput, TOutput>\n amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>\n }[],\n v3Routes: {\n routev3: V3RouteSDK<TInput, TOutput>\n amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>\n }[],\n tradeType: TTradeType,\n mixedRoutes?: {\n mixedRoute: MixedRouteSDK<TInput, TOutput>\n amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>\n }[]\n ): Promise<Trade<TInput, TOutput, TTradeType>> {\n const populatedV2Routes: {\n routev2: V2RouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n const populatedV3Routes: {\n routev3: V3RouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n const populatedMixedRoutes: {\n mixedRoute: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n for (const { routev2, amount } of v2Routes) {\n const v2Trade = new V2TradeSDK(routev2, amount, tradeType)\n const { inputAmount, outputAmount } = v2Trade\n\n populatedV2Routes.push({\n routev2,\n inputAmount,\n outputAmount,\n })\n }\n\n for (const { routev3, amount } of v3Routes) {\n const v3Trade = await V3TradeSDK.fromRoute(routev3, amount, tradeType)\n const { inputAmount, outputAmount } = v3Trade\n\n populatedV3Routes.push({\n routev3,\n inputAmount,\n outputAmount,\n })\n }\n\n if (mixedRoutes) {\n for (const { mixedRoute, amount } of mixedRoutes) {\n const mixedRouteTrade = await MixedRouteTradeSDK.fromRoute(mixedRoute, amount, tradeType)\n const { inputAmount, outputAmount } = mixedRouteTrade\n\n populatedMixedRoutes.push({\n mixedRoute,\n inputAmount,\n outputAmount,\n })\n }\n }\n\n return new Trade({\n v2Routes: populatedV2Routes,\n v3Routes: populatedV3Routes,\n mixedRoutes: populatedMixedRoutes,\n tradeType,\n })\n }\n\n public static async fromRoute<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(\n route: V2RouteSDK<TInput, TOutput> | V3RouteSDK<TInput, TOutput> | MixedRouteSDK<TInput, TOutput>,\n amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>,\n tradeType: TTradeType\n ): Promise<Trade<TInput, TOutput, TTradeType>> {\n let v2Routes: {\n routev2: V2RouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n let v3Routes: {\n routev3: V3RouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n let mixedRoutes: {\n mixedRoute: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n if (route instanceof V2RouteSDK) {\n const v2Trade = new V2TradeSDK(route, amount, tradeType)\n const { inputAmount, outputAmount } = v2Trade\n v2Routes = [{ routev2: route, inputAmount, outputAmount }]\n } else if (route instanceof V3RouteSDK) {\n const v3Trade = await V3TradeSDK.fromRoute(route, amount, tradeType)\n const { inputAmount, outputAmount } = v3Trade\n v3Routes = [{ routev3: route, inputAmount, outputAmount }]\n } else if (route instanceof MixedRouteSDK) {\n const mixedRouteTrade = await MixedRouteTradeSDK.fromRoute(route, amount, tradeType)\n const { inputAmount, outputAmount } = mixedRouteTrade\n mixedRoutes = [{ mixedRoute: route, inputAmount, outputAmount }]\n } else {\n throw new Error('Invalid route type')\n }\n\n return new Trade({\n v2Routes,\n v3Routes,\n mixedRoutes,\n tradeType,\n })\n }\n}\n","import { pack } from '@ethersproject/solidity'\nimport { Currency, Token } from '@uniswap/sdk-core'\nimport { Pool } from '@uniswap/v3-sdk'\nimport { Pair } from '@uniswap/v2-sdk'\nimport { MixedRouteSDK } from '../entities/mixedRoute/route'\nimport { V2_FEE_PATH_PLACEHOLDER } from '../constants'\n\n/**\n * Converts a route to a hex encoded path\n * @notice only supports exactIn route encodings\n * @param route the mixed path to convert to an encoded path\n * @returns the exactIn encoded path\n */\nexport function encodeMixedRouteToPath(route: MixedRouteSDK<Currency, Currency>): string {\n const firstInputToken: Token = route.input.wrapped\n\n const { path, types } = route.pools.reduce(\n (\n { inputToken, path, types }: { inputToken: Token; path: (string | number)[]; types: string[] },\n pool: Pool | Pair,\n index\n ): { inputToken: Token; path: (string | number)[]; types: string[] } => {\n const outputToken: Token = pool.token0.equals(inputToken) ? pool.token1 : pool.token0\n if (index === 0) {\n return {\n inputToken: outputToken,\n types: ['address', 'uint24', 'address'],\n path: [inputToken.address, pool instanceof Pool ? pool.fee : V2_FEE_PATH_PLACEHOLDER, outputToken.address],\n }\n } else {\n return {\n inputToken: outputToken,\n types: [...types, 'uint24', 'address'],\n path: [...path, pool instanceof Pool ? pool.fee : V2_FEE_PATH_PLACEHOLDER, outputToken.address],\n }\n }\n },\n { inputToken: firstInputToken, path: [], types: [] }\n )\n\n return pack(types, path)\n}\n","import { Currency, Token } from '@uniswap/sdk-core'\nimport { Pair } from '@uniswap/v2-sdk'\nimport { Pool } from '@uniswap/v3-sdk'\nimport { MixedRouteSDK } from '../entities/mixedRoute/route'\n\n/**\n * Utility function to return each consecutive section of Pools or Pairs in a MixedRoute\n * @param route\n * @returns a nested array of Pools or Pairs in the order of the route\n */\nexport const partitionMixedRouteByProtocol = (route: MixedRouteSDK<Currency, Currency>): (Pool | Pair)[][] => {\n let acc = []\n\n let left = 0\n let right = 0\n while (right < route.pools.length) {\n if (\n (route.pools[left] instanceof Pool && route.pools[right] instanceof Pair) ||\n (route.pools[left] instanceof Pair && route.pools[right] instanceof Pool)\n ) {\n acc.push(route.pools.slice(left, right))\n left = right\n }\n // seek forward with right pointer\n right++\n if (right === route.pools.length) {\n /// we reached the end, take the rest\n acc.push(route.pools.slice(left, right))\n }\n }\n return acc\n}\n\n/**\n * Simple utility function to get the output of an array of Pools or Pairs\n * @param pools\n * @param firstInputToken\n * @returns the output token of the last pool in the array\n */\nexport const getOutputOfPools = (pools: (Pool | Pair)[], firstInputToken: Token): Token => {\n const { inputToken: outputToken } = pools.reduce(\n ({ inputToken }, pool: Pool | Pair): { inputToken: Token } => {\n if (!pool.involvesToken(inputToken)) throw new Error('PATH')\n const outputToken: Token = pool.token0.equals(inputToken) ? pool.token1 : pool.token0\n return {\n inputToken: outputToken,\n }\n },\n { inputToken: firstInputToken }\n )\n return outputToken\n}\n","import { Interface } from '@ethersproject/abi'\nimport { Currency, CurrencyAmount, Percent, TradeType, validateAndParseAddress, WETH9 } from '@uniswap/sdk-core'\nimport { abi } from '@uniswap/swap-router-contracts/artifacts/contracts/interfaces/ISwapRouter02.sol/ISwapRouter02.json'\nimport { Trade as V2Trade } from '@uniswap/v2-sdk'\nimport {\n encodeRouteToPath,\n FeeOptions,\n MethodParameters,\n Payments,\n PermitOptions,\n Pool,\n Position,\n SelfPermit,\n toHex,\n Trade as V3Trade,\n} from '@uniswap/v3-sdk'\nimport invariant from 'tiny-invariant'\nimport JSBI from 'jsbi'\nimport { ADDRESS_THIS, MSG_SENDER } from './constants'\nimport { ApproveAndCall, ApprovalTypes, CondensedAddLiquidityOptions } from './approveAndCall'\nimport { Trade } from './entities/trade'\nimport { Protocol } from './entities/protocol'\nimport { MixedRoute, RouteV2, RouteV3 } from './entities/route'\nimport { MulticallExtended, Validation } from './multicallExtended'\nimport { PaymentsExtended } from './paymentsExtended'\nimport { MixedRouteTrade } from './entities/mixedRoute/trade'\nimport { encodeMixedRouteToPath } from './utils/encodeMixedRouteToPath'\nimport { MixedRouteSDK } from './entities/mixedRoute/route'\nimport { partitionMixedRouteByProtocol, getOutputOfPools } from './utils'\n\nconst ZERO = JSBI.BigInt(0)\nconst REFUND_ETH_PRICE_IMPACT_THRESHOLD = new Percent(JSBI.BigInt(50), JSBI.BigInt(100))\n\n/**\n * Options for producing the arguments to send calls to the router.\n */\nexport interface SwapOptions {\n /**\n * How much the execution price is allowed to move unfavorably from the trade execution price.\n */\n slippageTolerance: Percent\n\n /**\n * The account that should receive the output. If omitted, output is sent to msg.sender.\n */\n recipient?: string\n\n /**\n * Either deadline (when the transaction expires, in epoch seconds), or previousBlockhash.\n */\n deadlineOrPreviousBlockhash?: Validation\n\n /**\n * The optional permit parameters for spending the input.\n */\n inputTokenPermit?: PermitOptions\n\n /**\n * Optional information for taking a fee on output.\n */\n fee?: FeeOptions\n}\n\nexport interface SwapAndAddOptions extends SwapOptions {\n /**\n * The optional permit parameters for pulling in remaining output token.\n */\n outputTokenPermit?: PermitOptions\n}\n\ntype AnyTradeType =\n | Trade<Currency, Currency, TradeType>\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n | (\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n )[]\n\n/**\n * Represents the Uniswap V2 + V3 SwapRouter02, and has static methods for helping execute trades.\n */\nexport abstract class SwapRouter {\n public static INTERFACE: Interface = new Interface(abi)\n\n /**\n * Cannot be constructed.\n */\n private constructor() {}\n\n /**\n * @notice Generates the calldata for a Swap with a V2 Route.\n * @param trade The V2Trade to encode.\n * @param options SwapOptions to use for the trade.\n * @param routerMustCustody Flag for whether funds should be sent to the router\n * @param performAggregatedSlippageCheck Flag for whether we want to perform an aggregated slippage check\n * @returns A string array of calldatas for the trade.\n */\n private static encodeV2Swap(\n trade: V2Trade<Currency, Currency, TradeType>,\n options: SwapOptions,\n routerMustCustody: boolean,\n performAggregatedSlippageCheck: boolean\n ): string {\n const amountIn: string = toHex(trade.maximumAmountIn(options.slippageTolerance).quotient)\n const amountOut: string = toHex(trade.minimumAmountOut(options.slippageTolerance).quotient)\n\n const path = trade.route.path.map((token) => token.address)\n const recipient = routerMustCustody\n ? ADDRESS_THIS\n : typeof options.recipient === 'undefined'\n ? MSG_SENDER\n : validateAndParseAddress(options.recipient)\n\n if (trade.tradeType === TradeType.EXACT_INPUT) {\n const exactInputParams = [amountIn, performAggregatedSlippageCheck ? 0 : amountOut, path, recipient]\n\n return SwapRouter.INTERFACE.encodeFunctionData('swapExactTokensForTokens', exactInputParams)\n } else {\n const exactOutputParams = [amountOut, amountIn, path, recipient]\n\n return SwapRouter.INTERFACE.encodeFunctionData('swapTokensForExactTokens', exactOutputParams)\n }\n }\n\n /**\n * @notice Generates the calldata for a Swap with a V3 Route.\n * @param trade The V3Trade to encode.\n * @param options SwapOptions to use for the trade.\n * @param routerMustCustody Flag for whether funds should be sent to the router\n * @param performAggregatedSlippageCheck Flag for whether we want to perform an aggregated slippage check\n * @returns A string array of calldatas for the trade.\n */\n private static encodeV3Swap(\n trade: V3Trade<Currency, Currency, TradeType>,\n options: SwapOptions,\n routerMustCustody: boolean,\n performAggregatedSlippageCheck: boolean\n ): string[] {\n const calldatas: string[] = []\n\n for (const { route, inputAmount, outputAmount } of trade.swaps) {\n const amountIn: string = toHex(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient)\n const amountOut: string = toHex(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient)\n\n // flag for whether the trade is single hop or not\n const singleHop = route.pools.length === 1\n\n const recipient = routerMustCustody\n ? ADDRESS_THIS\n : typeof options.recipient === 'undefined'\n ? MSG_SENDER\n : validateAndParseAddress(options.recipient)\n\n if (singleHop) {\n if (trade.tradeType === TradeType.EXACT_INPUT) {\n const exactInputSingleParams = {\n tokenIn: route.tokenPath[0].address,\n tokenOut: route.tokenPath[1].address,\n fee: route.pools[0].fee,\n recipient,\n amountIn,\n amountOutMinimum: performAggregatedSlippageCheck ? 0 : amountOut,\n sqrtPriceLimitX96: 0,\n }\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInputSingle', [exactInputSingleParams]))\n } else {\n const exactOutputSingleParams = {\n tokenIn: route.tokenPath[0].address,\n tokenOut: route.tokenPath[1].address,\n fee: route.pools[0].fee,\n recipient,\n amountOut,\n amountInMaximum: amountIn,\n sqrtPriceLimitX96: 0,\n }\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutputSingle', [exactOutputSingleParams]))\n }\n } else {\n const path: string = encodeRouteToPath(route, trade.tradeType === TradeType.EXACT_OUTPUT)\n\n if (trade.tradeType === TradeType.EXACT_INPUT) {\n const exactInputParams = {\n path,\n recipient,\n amountIn,\n amountOutMinimum: performAggregatedSlippageCheck ? 0 : amountOut,\n }\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInput', [exactInputParams]))\n } else {\n const exactOutputParams = {\n path,\n recipient,\n amountOut,\n amountInMaximum: amountIn,\n }\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutput', [exactOutputParams]))\n }\n }\n }\n\n return calldatas\n }\n\n /**\n * @notice Generates the calldata for a MixedRouteSwap. Since single hop routes are not MixedRoutes, we will instead generate\n * them via the existing encodeV3Swap and encodeV2Swap methods.\n * @param trade The MixedRouteTrade to encode.\n * @param options SwapOptions to use for the trade.\n * @param routerMustCustody Flag for whether funds should be sent to the router\n * @param performAggregatedSlippageCheck Flag for whether we want to perform an aggregated slippage check\n * @returns A string array of calldatas for the trade.\n */\n private static encodeMixedRouteSwap(\n trade: MixedRouteTrade<Currency, Currency, TradeType>,\n options: SwapOptions,\n routerMustCustody: boolean,\n performAggregatedSlippageCheck: boolean\n ): string[] {\n const calldatas: string[] = []\n\n invariant(trade.tradeType === TradeType.EXACT_INPUT, 'TRADE_TYPE')\n\n for (const { route, inputAmount, outputAmount } of trade.swaps) {\n const amountIn: string = toHex(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient)\n const amountOut: string = toHex(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient)\n\n // flag for whether the trade is single hop or not\n const singleHop = route.pools.length === 1\n\n const recipient = routerMustCustody\n ? ADDRESS_THIS\n : typeof options.recipient === 'undefined'\n ? MSG_SENDER\n : validateAndParseAddress(options.recipient)\n\n const mixedRouteIsAllV3 = (route: MixedRouteSDK<Currency, Currency>) => {\n return route.pools.every((pool) => pool instanceof Pool)\n }\n\n if (singleHop) {\n /// For single hop, since it isn't really a mixedRoute, we'll just mimic behavior of V3 or V2\n /// We don't use encodeV3Swap() or encodeV2Swap() because casting the trade to a V3Trade or V2Trade is overcomplex\n if (mixedRouteIsAllV3(route)) {\n const exactInputSingleParams = {\n tokenIn: route.path[0].address,\n tokenOut: route.path[1].address,\n fee: (route.pools as Pool[])[0].fee,\n recipient,\n amountIn,\n amountOutMinimum: performAggregatedSlippageCheck ? 0 : amountOut,\n sqrtPriceLimitX96: 0,\n }\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInputSingle', [exactInputSingleParams]))\n } else {\n const path = route.path.map((token) => token.address)\n\n const exactInputParams = [amountIn, performAggregatedSlippageCheck ? 0 : amountOut, path, recipient]\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('swapExactTokensForTokens', exactInputParams))\n }\n } else {\n const sections = partitionMixedRouteByProtocol(route)\n\n const isLastSectionInRoute = (i: number) => {\n return i === sections.length - 1\n }\n\n let outputToken\n let inputToken = route.input.wrapped\n\n for (let i = 0; i < sections.length; i++) {\n const section = sections[i]\n /// Now, we get output of this section\n outputToken = getOutputOfPools(section, inputToken)\n\n const newRouteOriginal = new MixedRouteSDK(\n [...section],\n section[0].token0.equals(inputToken) ? section[0].token0 : section[0].token1,\n outputToken\n )\n const newRoute = new MixedRoute(newRouteOriginal)\n\n /// Previous output is now input\n inputToken = outputToken\n\n if (mixedRouteIsAllV3(newRoute)) {\n const path: string = encodeMixedRouteToPath(newRoute)\n const exactInputParams = {\n path,\n // By default router holds funds until the last swap, then it is sent to the recipient\n // special case exists where we are unwrapping WETH output, in which case `routerMustCustody` is set to true\n // and router still holds the funds. That logic bundled into how the value of `recipient` is calculated\n recipient: isLastSectionInRoute(i) ? recipient : ADDRESS_THIS,\n amountIn: i == 0 ? amountIn : 0,\n amountOutMinimum: !isLastSectionInRoute(i) ? 0 : amountOut,\n }\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInput', [exactInputParams]))\n } else {\n const exactInputParams = [\n i == 0 ? amountIn : 0, // amountIn\n !isLastSectionInRoute(i) ? 0 : amountOut, // amountOutMin\n newRoute.path.map((token) => token.address), // path\n isLastSectionInRoute(i) ? recipient : ADDRESS_THIS, // to\n ]\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('swapExactTokensForTokens', exactInputParams))\n }\n }\n }\n }\n\n return calldatas\n }\n\n private static encodeSwaps(\n trades: AnyTradeType,\n options: SwapOptions,\n isSwapAndAdd?: boolean\n ): {\n calldatas: string[]\n sampleTrade:\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n routerMustCustody: boolean\n inputIsNative: boolean\n outputIsNative: boolean\n totalAmountIn: CurrencyAmount<Currency>\n minimumAmountOut: CurrencyAmount<Currency>\n quoteAmountOut: CurrencyAmount<Currency>\n } {\n // If dealing with an instance of the aggregated Trade object, unbundle it to individual trade objects.\n if (trades instanceof Trade) {\n invariant(\n trades.swaps.every(\n (swap) =>\n swap.route.protocol == Protocol.V3 ||\n swap.route.protocol == Protocol.V2 ||\n swap.route.protocol == Protocol.MIXED\n ),\n 'UNSUPPORTED_PROTOCOL'\n )\n\n let individualTrades: (\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n )[] = []\n\n for (const { route, inputAmount, outputAmount } of trades.swaps) {\n if (route.protocol == Protocol.V2) {\n individualTrades.push(\n new V2Trade(\n route as RouteV2<Currency, Currency>,\n trades.tradeType == TradeType.EXACT_INPUT ? inputAmount : outputAmount,\n trades.tradeType\n )\n )\n } else if (route.protocol == Protocol.V3) {\n individualTrades.push(\n V3Trade.createUncheckedTrade({\n route: route as RouteV3<Currency, Currency>,\n inputAmount,\n outputAmount,\n tradeType: trades.tradeType,\n })\n )\n } else if (route.protocol == Protocol.MIXED) {\n individualTrades.push(\n /// we can change the naming of this function on MixedRouteTrade if needed\n MixedRouteTrade.createUncheckedTrade({\n route: route as MixedRoute<Currency, Currency>,\n inputAmount,\n outputAmount,\n tradeType: trades.tradeType,\n })\n )\n } else {\n throw new Error('UNSUPPORTED_TRADE_PROTOCOL')\n }\n }\n trades = individualTrades\n }\n\n if (!Array.isArray(trades)) {\n trades = [trades]\n }\n\n const numberOfTrades = trades.reduce(\n (numberOfTrades, trade) =>\n numberOfTrades + (trade instanceof V3Trade || trade instanceof MixedRouteTrade ? trade.swaps.length : 1),\n 0\n )\n\n const sampleTrade = trades[0]\n\n // All trades should have the same starting/ending currency and trade type\n invariant(\n trades.every((trade) => trade.inputAmount.currency.equals(sampleTrade.inputAmount.currency)),\n 'TOKEN_IN_DIFF'\n )\n invariant(\n trades.every((trade) => trade.outputAmount.currency.equals(sampleTrade.outputAmount.currency)),\n 'TOKEN_OUT_DIFF'\n )\n invariant(\n trades.every((trade) => trade.tradeType === sampleTrade.tradeType),\n 'TRADE_TYPE_DIFF'\n )\n\n const calldatas: string[] = []\n\n const inputIsNative = sampleTrade.inputAmount.currency.isNative\n const outputIsNative = sampleTrade.outputAmount.currency.isNative\n\n // flag for whether we want to perform an aggregated slippage check\n // 1. when there are >2 exact input trades. this is only a heuristic,\n // as it's still more gas-expensive even in this case, but has benefits\n // in that the reversion probability is lower\n const performAggregatedSlippageCheck = sampleTrade.tradeType === TradeType.EXACT_INPUT && numberOfTrades > 2\n // flag for whether funds should be send first to the router\n // 1. when receiving ETH (which much be unwrapped from WETH)\n // 2. when a fee on the output is being taken\n // 3. when performing swap and add\n // 4. when performing an aggregated slippage check\n const routerMustCustody = outputIsNative || !!options.fee || !!isSwapAndAdd || performAggregatedSlippageCheck\n\n // encode permit if necessary\n if (options.inputTokenPermit) {\n invariant(sampleTrade.inputAmount.currency.isToken, 'NON_TOKEN_PERMIT')\n calldatas.push(SelfPermit.encodePermit(sampleTrade.inputAmount.currency, options.inputTokenPermit))\n }\n\n for (const trade of trades) {\n if (trade instanceof V2Trade) {\n calldatas.push(SwapRouter.encodeV2Swap(trade, options, routerMustCustody, performAggregatedSlippageCheck))\n } else if (trade instanceof V3Trade) {\n for (const calldata of SwapRouter.encodeV3Swap(\n trade,\n options,\n routerMustCustody,\n performAggregatedSlippageCheck\n )) {\n calldatas.push(calldata)\n }\n } else if (trade instanceof MixedRouteTrade) {\n for (const calldata of SwapRouter.encodeMixedRouteSwap(\n trade,\n options,\n routerMustCustody,\n performAggregatedSlippageCheck\n )) {\n calldatas.push(calldata)\n }\n } else {\n throw new Error('Unsupported trade object')\n }\n }\n\n const ZERO_IN: CurrencyAmount<Currency> = CurrencyAmount.fromRawAmount(sampleTrade.inputAmount.currency, 0)\n const ZERO_OUT: CurrencyAmount<Currency> = CurrencyAmount.fromRawAmount(sampleTrade.outputAmount.currency, 0)\n\n const minimumAmountOut: CurrencyAmount<Currency> = trades.reduce(\n (sum, trade) => sum.add(trade.minimumAmountOut(options.slippageTolerance)),\n ZERO_OUT\n )\n\n const quoteAmountOut: CurrencyAmount<Currency> = trades.reduce(\n (sum, trade) => sum.add(trade.outputAmount),\n ZERO_OUT\n )\n\n const totalAmountIn: CurrencyAmount<Currency> = trades.reduce(\n (sum, trade) => sum.add(trade.maximumAmountIn(options.slippageTolerance)),\n ZERO_IN\n )\n\n return {\n calldatas,\n sampleTrade,\n routerMustCustody,\n inputIsNative,\n outputIsNative,\n totalAmountIn,\n minimumAmountOut,\n quoteAmountOut,\n }\n }\n\n /**\n * Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.\n * @param trades to produce call parameters for\n * @param options options for the call parameters\n */\n public static swapCallParameters(\n trades:\n | Trade<Currency, Currency, TradeType>\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n | (\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n )[],\n options: SwapOptions\n ): MethodParameters {\n const {\n calldatas,\n sampleTrade,\n routerMustCustody,\n inputIsNative,\n outputIsNative,\n totalAmountIn,\n minimumAmountOut,\n } = SwapRouter.encodeSwaps(trades, options)\n\n // unwrap or sweep\n if (routerMustCustody) {\n if (outputIsNative) {\n calldatas.push(PaymentsExtended.encodeUnwrapWETH9(minimumAmountOut.quotient, options.recipient, options.fee))\n } else {\n calldatas.push(\n PaymentsExtended.encodeSweepToken(\n sampleTrade.outputAmount.currency.wrapped,\n minimumAmountOut.quotient,\n options.recipient,\n options.fee\n )\n )\n }\n }\n\n // must refund when paying in ETH: either with an uncertain input amount OR if there's a chance of a partial fill.\n // unlike ERC20's, the full ETH value must be sent in the transaction, so the rest must be refunded.\n if (inputIsNative && (sampleTrade.tradeType === TradeType.EXACT_OUTPUT || SwapRouter.riskOfPartialFill(trades))) {\n calldatas.push(Payments.encodeRefundETH())\n }\n\n return {\n calldata: MulticallExtended.encodeMulticall(calldatas, options.deadlineOrPreviousBlockhash),\n value: toHex(inputIsNative ? totalAmountIn.quotient : ZERO),\n }\n }\n\n /**\n * Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.\n * @param trades to produce call parameters for\n * @param options options for the call parameters\n */\n public static swapAndAddCallParameters(\n trades: AnyTradeType,\n options: SwapAndAddOptions,\n position: Position,\n addLiquidityOptions: CondensedAddLiquidityOptions,\n tokenInApprovalType: ApprovalTypes,\n tokenOutApprovalType: ApprovalTypes\n ): MethodParameters {\n const {\n calldatas,\n inputIsNative,\n outputIsNative,\n sampleTrade,\n totalAmountIn: totalAmountSwapped,\n quoteAmountOut,\n minimumAmountOut,\n } = SwapRouter.encodeSwaps(trades, options, true)\n\n // encode output token permit if necessary\n if (options.outputTokenPermit) {\n invariant(quoteAmountOut.currency.isToken, 'NON_TOKEN_PERMIT_OUTPUT')\n calldatas.push(SelfPermit.encodePermit(quoteAmountOut.currency, options.outputTokenPermit))\n }\n\n const chainId = sampleTrade.route.chainId\n const zeroForOne = position.pool.token0.wrapped.address === totalAmountSwapped.currency.wrapped.address\n const { positionAmountIn, positionAmountOut } = SwapRouter.getPositionAmounts(position, zeroForOne)\n\n // if tokens are native they will be converted to WETH9\n const tokenIn = inputIsNative ? WETH9[chainId] : positionAmountIn.currency.wrapped\n const tokenOut = outputIsNative ? WETH9[chainId] : positionAmountOut.currency.wrapped\n\n // if swap output does not make up whole outputTokenBalanceDesired, pull in remaining tokens for adding liquidity\n const amountOutRemaining = positionAmountOut.subtract(quoteAmountOut.wrapped)\n if (amountOutRemaining.greaterThan(CurrencyAmount.fromRawAmount(positionAmountOut.currency, 0))) {\n // if output is native, this means the remaining portion is included as native value in the transaction\n // and must be wrapped. Otherwise, pull in remaining ERC20 token.\n outputIsNative\n ? calldatas.push(PaymentsExtended.encodeWrapETH(amountOutRemaining.quotient))\n : calldatas.push(PaymentsExtended.encodePull(tokenOut, amountOutRemaining.quotient))\n }\n\n // if input is native, convert to WETH9, else pull ERC20 token\n inputIsNative\n ? calldatas.push(PaymentsExtended.encodeWrapETH(positionAmountIn.quotient))\n : calldatas.push(PaymentsExtended.encodePull(tokenIn, positionAmountIn.quotient))\n\n // approve token balances to NFTManager\n if (tokenInApprovalType !== ApprovalTypes.NOT_REQUIRED)\n calldatas.push(ApproveAndCall.encodeApprove(tokenIn, tokenInApprovalType))\n if (tokenOutApprovalType !== ApprovalTypes.NOT_REQUIRED)\n calldatas.push(ApproveAndCall.encodeApprove(tokenOut, tokenOutApprovalType))\n\n // represents a position with token amounts resulting from a swap with maximum slippage\n // hence the minimal amount out possible.\n const minimalPosition = Position.fromAmounts({\n pool: position.pool,\n tickLower: position.tickLower,\n tickUpper: position.tickUpper,\n amount0: zeroForOne ? position.amount0.quotient.toString() : minimumAmountOut.quotient.toString(),\n amount1: zeroForOne ? minimumAmountOut.quotient.toString() : position.amount1.quotient.toString(),\n useFullPrecision: false,\n })\n\n // encode NFTManager add liquidity\n calldatas.push(\n ApproveAndCall.encodeAddLiquidity(position, minimalPosition, addLiquidityOptions, options.slippageTolerance)\n )\n\n // sweep remaining tokens\n inputIsNative\n ? calldatas.push(PaymentsExtended.encodeUnwrapWETH9(ZERO))\n : calldatas.push(PaymentsExtended.encodeSweepToken(tokenIn, ZERO))\n outputIsNative\n ? calldatas.push(PaymentsExtended.encodeUnwrapWETH9(ZERO))\n : calldatas.push(PaymentsExtended.encodeSweepToken(tokenOut, ZERO))\n\n let value: JSBI\n if (inputIsNative) {\n value = totalAmountSwapped.wrapped.add(positionAmountIn.wrapped).quotient\n } else if (outputIsNative) {\n value = amountOutRemaining.quotient\n } else {\n value = ZERO\n }\n\n return {\n calldata: MulticallExtended.encodeMulticall(calldatas, options.deadlineOrPreviousBlockhash),\n value: value.toString(),\n }\n }\n\n // if price impact is very high, there's a chance of hitting max/min prices resulting in a partial fill of the swap\n private static riskOfPartialFill(trades: AnyTradeType): boolean {\n if (Array.isArray(trades)) {\n return trades.some((trade) => {\n return SwapRouter.v3TradeWithHighPriceImpact(trade)\n })\n } else {\n return SwapRouter.v3TradeWithHighPriceImpact(trades)\n }\n }\n\n private static v3TradeWithHighPriceImpact(\n trade:\n | Trade<Currency, Currency, TradeType>\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n ): boolean {\n return !(trade instanceof V2Trade) && trade.priceImpact.greaterThan(REFUND_ETH_PRICE_IMPACT_THRESHOLD)\n }\n\n private static getPositionAmounts(\n position: Position,\n zeroForOne: boolean\n ): {\n positionAmountIn: CurrencyAmount<Currency>\n positionAmountOut: CurrencyAmount<Currency>\n } {\n const { amount0, amount1 } = position.mintAmounts\n const currencyAmount0 = CurrencyAmount.fromRawAmount(position.pool.token0, amount0)\n const currencyAmount1 = CurrencyAmount.fromRawAmount(position.pool.token1, amount1)\n\n const [positionAmountIn, positionAmountOut] = zeroForOne\n ? [currencyAmount0, currencyAmount1]\n : [currencyAmount1, currencyAmount0]\n return { positionAmountIn, positionAmountOut }\n }\n}\n"],"names":["ApprovalTypes","MSG_SENDER","ADDRESS_THIS","ZERO","JSBI","BigInt","ONE","isMint","options","Object","keys","some","k","ApproveAndCall","encodeApproveMax","token","INTERFACE","encodeFunctionData","address","encodeApproveMaxMinusOne","encodeApproveZeroThenMax","encodeApproveZeroThenMaxMinusOne","encodeCallPositionManager","calldatas","length","invariant","encodedMulticall","NonfungiblePositionManager","encodeAddLiquidity","position","minimalPosition","addLiquidityOptions","slippageTolerance","mintAmountsWithSlippage","amount0Min","amount0","amount1Min","amount1","lessThan","quotient","token0","pool","token1","fee","tickLower","tickUpper","toHex","recipient","tokenId","encodeApprove","approvalType","MAX","wrapped","MAX_MINUS_ONE","ZERO_THEN_MAX","ZERO_THEN_MAX_MINUS_ONE","Interface","abi","MulticallExtended","encodeMulticall","validation","Multicall","Array","isArray","startsWith","previousBlockhash","bytes32","match","Error","toLowerCase","validateAndParseBytes32","deadline","encodeFeeBips","multiply","PaymentsExtended","encodeUnwrapWETH9","amountMinimum","feeOptions","Payments","feeBips","feeRecipient","validateAndParseAddress","encodeSweepToken","encodePull","amount","encodeWrapETH","runtime","exports","Op","prototype","hasOwn","hasOwnProperty","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","define","obj","key","value","defineProperty","enumerable","configurable","writable","err","wrap","innerFn","outerFn","self","tryLocsList","generator","create","Generator","context","Context","_invoke","state","method","arg","undefined","done","delegate","delegateResult","maybeInvokeDelegate","ContinueSentinel","sent","_sent","dispatchException","abrupt","record","tryCatch","type","makeInvokeMethod","fn","call","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","this","getProto","getPrototypeOf","NativeIteratorPrototype","values","Gp","defineIteratorMethods","forEach","AsyncIterator","PromiseImpl","previousPromise","callInvokeWithMethodAndArg","resolve","reject","invoke","result","__await","then","unwrapped","error","TypeError","info","resultName","next","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","iterable","iteratorMethod","isNaN","i","doneResult","displayName","isGeneratorFunction","genFun","ctor","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","iter","object","reverse","pop","skipTempReset","prev","charAt","slice","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","catch","thrown","delegateYield","module","regeneratorRuntime","accidentalStrictMode","globalThis","Function","MixedRouteSDK","pools","input","output","chainId","every","wrappedInput","involvesToken","tokenPath","entries","currentInputToken","equals","nextToken","path","_midPrice","price","reduce","nextInput","token0Price","token1Price","Price","denominator","numerator","tradeComparator","a","b","inputAmount","currency","outputAmount","equalTo","swaps","total","cur","route","Protocol","MixedRouteTrade","routes","tradeType","inputCurrency","outputCurrency","numPools","map","poolAddressSet","Set","add","Pool","getAddress","Pair","size","TradeType","EXACT_INPUT","fromRoute","amounts","getOutputAmount","CurrencyAmount","fromFractionalAmount","fromRoutes","populatedRoutes","createUncheckedTrade","constructorArguments","createUncheckedTradeWithMultipleRoutes","minimumAmountOut","amountOut","slippageAdjustedAmountOut","Fraction","invert","fromRawAmount","maximumAmountIn","amountIn","worstExecutionPrice","bestTradeExactIn","currencyAmountIn","currencyOut","currentPools","nextAmountIn","bestTrades","maxNumResults","maxHops","tokenOut","reserve0","reserve1","_context3","isInsufficientInputAmountError","isToken","sortedInsert","poolsExcludingThisPool","concat","_inputAmount","totalInputFromRoutes","_outputAmount","totalOutputFromRoutes","_executionPrice","_priceImpact","spotOutputAmount","midPrice","quote","priceImpact","subtract","divide","Percent","RouteV2","v2Route","pairs","V2","_this","V2RouteSDK","RouteV3","v3Route","V3","V3RouteSDK","MixedRoute","mixedRoute","MIXED","Trade","v2Routes","v3Routes","mixedRoutes","routev2","routev3","EXACT_OUTPUT","slippageAdjustedAmountIn","populatedV2Routes","populatedV3Routes","populatedMixedRoutes","v2Trade","V2TradeSDK","V3TradeSDK","v3Trade","MixedRouteTradeSDK","mixedRouteTrade","encodeMixedRouteToPath","index","inputToken","types","outputToken","pack","partitionMixedRouteByProtocol","acc","left","right","getOutputOfPools","firstInputToken","REFUND_ETH_PRICE_IMPACT_THRESHOLD","SwapRouter","encodeV2Swap","trade","routerMustCustody","performAggregatedSlippageCheck","encodeV3Swap","singleHop","tokenIn","amountOutMinimum","sqrtPriceLimitX96","amountInMaximum","encodeRouteToPath","encodeMixedRouteSwap","mixedRouteIsAllV3","sections","isLastSectionInRoute","section","newRouteOriginal","newRoute","exactInputParams","encodeSwaps","trades","isSwapAndAdd","swap","protocol","individualTrades","V2Trade","V3Trade","numberOfTrades","sampleTrade","inputIsNative","isNative","outputIsNative","inputTokenPermit","SelfPermit","encodePermit","ZERO_IN","ZERO_OUT","sum","quoteAmountOut","totalAmountIn","swapCallParameters","riskOfPartialFill","encodeRefundETH","calldata","deadlineOrPreviousBlockhash","swapAndAddCallParameters","tokenInApprovalType","tokenOutApprovalType","totalAmountSwapped","outputTokenPermit","zeroForOne","getPositionAmounts","positionAmountIn","positionAmountOut","WETH9","amountOutRemaining","greaterThan","NOT_REQUIRED","Position","fromAmounts","toString","useFullPrecision","v3TradeWithHighPriceImpact","mintAmounts","currencyAmount0","currencyAmount1"],"mappings":"8IAgBYA,0sBCdCC,EAAa,6CACbC,EAAe,6CAEfC,EAAOC,EAAKC,OAAO,GACnBC,EAAMF,EAAKC,OAAO,YDmBfE,EAAOC,UACdC,OAAOC,KAAKF,GAASG,MAAK,SAACC,SAA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GAClB,CAACA,EAAiBD,SACf,CAAEZ,sBAAkBC,8BAzlBftD,YAAuB,IAAIvT,YAAUC,iUX5Ed"}
|
|
1
|
+
{"version":3,"file":"router-sdk.cjs.production.min.js","sources":["../src/approveAndCall.ts","../src/constants.ts","../src/multicallExtended.ts","../src/paymentsExtended.ts","../node_modules/regenerator-runtime/runtime.js","../src/entities/mixedRoute/route.ts","../src/entities/mixedRoute/trade.ts","../src/entities/protocol.ts","../src/entities/route.ts","../src/entities/trade.ts","../src/utils/encodeMixedRouteToPath.ts","../src/utils/index.ts","../src/swapRouter.ts"],"sourcesContent":["import { Interface } from '@ethersproject/abi'\nimport invariant from 'tiny-invariant'\nimport { abi } from '@uniswap/swap-router-contracts/artifacts/contracts/interfaces/IApproveAndCall.sol/IApproveAndCall.json'\nimport { Currency, Percent, Token } from '@uniswap/sdk-core'\nimport {\n MintSpecificOptions,\n IncreaseSpecificOptions,\n NonfungiblePositionManager,\n Position,\n toHex,\n} from '@uniswap/v3-sdk'\nimport JSBI from 'jsbi'\n\n// condensed version of v3-sdk AddLiquidityOptions containing only necessary swap + add attributes\nexport type CondensedAddLiquidityOptions = Omit<MintSpecificOptions, 'createPool'> | IncreaseSpecificOptions\n\nexport enum ApprovalTypes {\n NOT_REQUIRED = 0,\n MAX = 1,\n MAX_MINUS_ONE = 2,\n ZERO_THEN_MAX = 3,\n ZERO_THEN_MAX_MINUS_ONE = 4,\n}\n\n// type guard\nexport function isMint(options: CondensedAddLiquidityOptions): options is Omit<MintSpecificOptions, 'createPool'> {\n return Object.keys(options).some((k) => k === 'recipient')\n}\n\nexport abstract class ApproveAndCall {\n public static INTERFACE: Interface = new Interface(abi)\n\n /**\n * Cannot be constructed.\n */\n private constructor() {}\n\n public static encodeApproveMax(token: Token): string {\n return ApproveAndCall.INTERFACE.encodeFunctionData('approveMax', [token.address])\n }\n\n public static encodeApproveMaxMinusOne(token: Token): string {\n return ApproveAndCall.INTERFACE.encodeFunctionData('approveMaxMinusOne', [token.address])\n }\n\n public static encodeApproveZeroThenMax(token: Token): string {\n return ApproveAndCall.INTERFACE.encodeFunctionData('approveZeroThenMax', [token.address])\n }\n\n public static encodeApproveZeroThenMaxMinusOne(token: Token): string {\n return ApproveAndCall.INTERFACE.encodeFunctionData('approveZeroThenMaxMinusOne', [token.address])\n }\n\n public static encodeCallPositionManager(calldatas: string[]): string {\n invariant(calldatas.length > 0, 'NULL_CALLDATA')\n\n if (calldatas.length == 1) {\n return ApproveAndCall.INTERFACE.encodeFunctionData('callPositionManager', calldatas)\n } else {\n const encodedMulticall = NonfungiblePositionManager.INTERFACE.encodeFunctionData('multicall', [calldatas])\n return ApproveAndCall.INTERFACE.encodeFunctionData('callPositionManager', [encodedMulticall])\n }\n }\n /**\n * Encode adding liquidity to a position in the nft manager contract\n * @param position Forcasted position with expected amount out from swap\n * @param minimalPosition Forcasted position with custom minimal token amounts\n * @param addLiquidityOptions Options for adding liquidity\n * @param slippageTolerance Defines maximum slippage\n */\n public static encodeAddLiquidity(\n position: Position,\n minimalPosition: Position,\n addLiquidityOptions: CondensedAddLiquidityOptions,\n slippageTolerance: Percent\n ): string {\n let { amount0: amount0Min, amount1: amount1Min } = position.mintAmountsWithSlippage(slippageTolerance)\n\n // position.mintAmountsWithSlippage() can create amounts not dependenable in scenarios\n // such as range orders. Allow the option to provide a position with custom minimum amounts\n // for these scenarios\n if (JSBI.lessThan(minimalPosition.amount0.quotient, amount0Min)) {\n amount0Min = minimalPosition.amount0.quotient\n }\n if (JSBI.lessThan(minimalPosition.amount1.quotient, amount1Min)) {\n amount1Min = minimalPosition.amount1.quotient\n }\n\n if (isMint(addLiquidityOptions)) {\n return ApproveAndCall.INTERFACE.encodeFunctionData('mint', [\n {\n token0: position.pool.token0.address,\n token1: position.pool.token1.address,\n fee: position.pool.fee,\n tickLower: position.tickLower,\n tickUpper: position.tickUpper,\n amount0Min: toHex(amount0Min),\n amount1Min: toHex(amount1Min),\n recipient: addLiquidityOptions.recipient,\n },\n ])\n } else {\n return ApproveAndCall.INTERFACE.encodeFunctionData('increaseLiquidity', [\n {\n token0: position.pool.token0.address,\n token1: position.pool.token1.address,\n amount0Min: toHex(amount0Min),\n amount1Min: toHex(amount1Min),\n tokenId: toHex(addLiquidityOptions.tokenId),\n },\n ])\n }\n }\n\n public static encodeApprove(token: Currency, approvalType: ApprovalTypes): string {\n switch (approvalType) {\n case ApprovalTypes.MAX:\n return ApproveAndCall.encodeApproveMax(token.wrapped)\n case ApprovalTypes.MAX_MINUS_ONE:\n return ApproveAndCall.encodeApproveMaxMinusOne(token.wrapped)\n case ApprovalTypes.ZERO_THEN_MAX:\n return ApproveAndCall.encodeApproveZeroThenMax(token.wrapped)\n case ApprovalTypes.ZERO_THEN_MAX_MINUS_ONE:\n return ApproveAndCall.encodeApproveZeroThenMaxMinusOne(token.wrapped)\n default:\n throw 'Error: invalid ApprovalType'\n }\n }\n}\n","import { Percent } from '@uniswap/sdk-core'\nimport JSBI from 'jsbi'\n\nexport const MSG_SENDER = '0x0000000000000000000000000000000000000001'\nexport const ADDRESS_THIS = '0x0000000000000000000000000000000000000002'\n\nexport const ZERO = JSBI.BigInt(0)\nexport const ONE = JSBI.BigInt(1)\n\n// = 1 << 23 or 100000000000000000000000\nexport const V2_FEE_PATH_PLACEHOLDER = 8388608\n\nexport const ZERO_PERCENT = new Percent(ZERO)\n","import { Interface } from '@ethersproject/abi'\nimport { BigintIsh } from '@uniswap/sdk-core'\nimport { abi } from '@uniswap/swap-router-contracts/artifacts/contracts/interfaces/IMulticallExtended.sol/IMulticallExtended.json'\nimport { Multicall, toHex } from '@uniswap/v3-sdk'\n\n// deadline or previousBlockhash\nexport type Validation = BigintIsh | string\n\nfunction validateAndParseBytes32(bytes32: string): string {\n if (!bytes32.match(/^0x[0-9a-fA-F]{64}$/)) {\n throw new Error(`${bytes32} is not valid bytes32.`)\n }\n\n return bytes32.toLowerCase()\n}\n\nexport abstract class MulticallExtended {\n public static INTERFACE: Interface = new Interface(abi)\n\n /**\n * Cannot be constructed.\n */\n private constructor() {}\n\n public static encodeMulticall(calldatas: string | string[], validation?: Validation): string {\n // if there's no validation, we can just fall back to regular multicall\n if (typeof validation === 'undefined') {\n return Multicall.encodeMulticall(calldatas)\n }\n\n // if there is validation, we have to normalize calldatas\n if (!Array.isArray(calldatas)) {\n calldatas = [calldatas]\n }\n\n // this means the validation value should be a previousBlockhash\n if (typeof validation === 'string' && validation.startsWith('0x')) {\n const previousBlockhash = validateAndParseBytes32(validation)\n return MulticallExtended.INTERFACE.encodeFunctionData('multicall(bytes32,bytes[])', [\n previousBlockhash,\n calldatas,\n ])\n } else {\n const deadline = toHex(validation)\n return MulticallExtended.INTERFACE.encodeFunctionData('multicall(uint256,bytes[])', [deadline, calldatas])\n }\n }\n}\n","import { Interface } from '@ethersproject/abi'\nimport { Percent, Token, validateAndParseAddress } from '@uniswap/sdk-core'\nimport { abi } from '@uniswap/swap-router-contracts/artifacts/contracts/interfaces/IPeripheryPaymentsWithFeeExtended.sol/IPeripheryPaymentsWithFeeExtended.json'\nimport { FeeOptions, Payments, toHex } from '@uniswap/v3-sdk'\nimport JSBI from 'jsbi'\n\nfunction encodeFeeBips(fee: Percent): string {\n return toHex(fee.multiply(10_000).quotient)\n}\n\nexport abstract class PaymentsExtended {\n public static INTERFACE: Interface = new Interface(abi)\n\n /**\n * Cannot be constructed.\n */\n private constructor() {}\n\n public static encodeUnwrapWETH9(amountMinimum: JSBI, recipient?: string, feeOptions?: FeeOptions): string {\n // if there's a recipient, just pass it along\n if (typeof recipient === 'string') {\n return Payments.encodeUnwrapWETH9(amountMinimum, recipient, feeOptions)\n }\n\n if (!!feeOptions) {\n const feeBips = encodeFeeBips(feeOptions.fee)\n const feeRecipient = validateAndParseAddress(feeOptions.recipient)\n\n return PaymentsExtended.INTERFACE.encodeFunctionData('unwrapWETH9WithFee(uint256,uint256,address)', [\n toHex(amountMinimum),\n feeBips,\n feeRecipient,\n ])\n } else {\n return PaymentsExtended.INTERFACE.encodeFunctionData('unwrapWETH9(uint256)', [toHex(amountMinimum)])\n }\n }\n\n public static encodeSweepToken(\n token: Token,\n amountMinimum: JSBI,\n recipient?: string,\n feeOptions?: FeeOptions\n ): string {\n // if there's a recipient, just pass it along\n if (typeof recipient === 'string') {\n return Payments.encodeSweepToken(token, amountMinimum, recipient, feeOptions)\n }\n\n if (!!feeOptions) {\n const feeBips = encodeFeeBips(feeOptions.fee)\n const feeRecipient = validateAndParseAddress(feeOptions.recipient)\n\n return PaymentsExtended.INTERFACE.encodeFunctionData('sweepTokenWithFee(address,uint256,uint256,address)', [\n token.address,\n toHex(amountMinimum),\n feeBips,\n feeRecipient,\n ])\n } else {\n return PaymentsExtended.INTERFACE.encodeFunctionData('sweepToken(address,uint256)', [\n token.address,\n toHex(amountMinimum),\n ])\n }\n }\n\n public static encodePull(token: Token, amount: JSBI): string {\n return PaymentsExtended.INTERFACE.encodeFunctionData('pull', [token.address, toHex(amount)])\n }\n\n public static encodeWrapETH(amount: JSBI): string {\n return PaymentsExtended.INTERFACE.encodeFunctionData('wrapETH', [toHex(amount)])\n }\n}\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = GeneratorFunctionPrototype;\n define(Gp, \"constructor\", GeneratorFunctionPrototype);\n define(GeneratorFunctionPrototype, \"constructor\", GeneratorFunction);\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n });\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n define(Gp, iteratorSymbol, function() {\n return this;\n });\n\n define(Gp, \"toString\", function() {\n return \"[object Generator]\";\n });\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, in modern engines\n // we can explicitly access globalThis. In older engines we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n","import invariant from 'tiny-invariant'\n\nimport { Currency, Price, Token } from '@uniswap/sdk-core'\nimport { Pool } from '@uniswap/v3-sdk'\nimport { Pair } from '@uniswap/v2-sdk'\n\ntype TPool = Pair | Pool\n\n/**\n * Represents a list of pools or pairs through which a swap can occur\n * @template TInput The input token\n * @template TOutput The output token\n */\nexport class MixedRouteSDK<TInput extends Currency, TOutput extends Currency> {\n public readonly pools: TPool[]\n public readonly path: Token[]\n public readonly input: TInput\n public readonly output: TOutput\n\n private _midPrice: Price<TInput, TOutput> | null = null\n\n /**\n * Creates an instance of route.\n * @param pools An array of `TPool` objects (pools or pairs), ordered by the route the swap will take\n * @param input The input token\n * @param output The output token\n */\n public constructor(pools: TPool[], input: TInput, output: TOutput) {\n invariant(pools.length > 0, 'POOLS')\n\n const chainId = pools[0].chainId\n const allOnSameChain = pools.every((pool) => pool.chainId === chainId)\n invariant(allOnSameChain, 'CHAIN_IDS')\n\n const wrappedInput = input.wrapped\n invariant(pools[0].involvesToken(wrappedInput), 'INPUT')\n\n invariant(pools[pools.length - 1].involvesToken(output.wrapped), 'OUTPUT')\n\n /**\n * Normalizes token0-token1 order and selects the next token/fee step to add to the path\n * */\n const tokenPath: Token[] = [wrappedInput]\n for (const [i, pool] of pools.entries()) {\n const currentInputToken = tokenPath[i]\n invariant(currentInputToken.equals(pool.token0) || currentInputToken.equals(pool.token1), 'PATH')\n const nextToken = currentInputToken.equals(pool.token0) ? pool.token1 : pool.token0\n tokenPath.push(nextToken)\n }\n\n this.pools = pools\n this.path = tokenPath\n this.input = input\n this.output = output ?? tokenPath[tokenPath.length - 1]\n }\n\n public get chainId(): number {\n return this.pools[0].chainId\n }\n\n /**\n * Returns the mid price of the route\n */\n public get midPrice(): Price<TInput, TOutput> {\n if (this._midPrice !== null) return this._midPrice\n\n const price = this.pools.slice(1).reduce(\n ({ nextInput, price }, pool) => {\n return nextInput.equals(pool.token0)\n ? {\n nextInput: pool.token1,\n price: price.multiply(pool.token0Price),\n }\n : {\n nextInput: pool.token0,\n price: price.multiply(pool.token1Price),\n }\n },\n this.pools[0].token0.equals(this.input.wrapped)\n ? {\n nextInput: this.pools[0].token1,\n price: this.pools[0].token0Price,\n }\n : {\n nextInput: this.pools[0].token0,\n price: this.pools[0].token1Price,\n }\n ).price\n\n return (this._midPrice = new Price(this.input, this.output, price.denominator, price.numerator))\n }\n}\n","import { Currency, Fraction, Percent, Price, sortedInsert, CurrencyAmount, TradeType, Token } from '@uniswap/sdk-core'\nimport { Pair } from '@uniswap/v2-sdk'\nimport { BestTradeOptions, Pool } from '@uniswap/v3-sdk'\nimport invariant from 'tiny-invariant'\nimport { ONE, ZERO } from '../../constants'\nimport { MixedRouteSDK } from './route'\n\n/**\n * Trades comparator, an extension of the input output comparator that also considers other dimensions of the trade in ranking them\n * @template TInput The input token, either Ether or an ERC-20\n * @template TOutput The output token, either Ether or an ERC-20\n * @template TTradeType The trade type, either exact input or exact output\n * @param a The first trade to compare\n * @param b The second trade to compare\n * @returns A sorted ordering for two neighboring elements in a trade array\n */\nexport function tradeComparator<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(\n a: MixedRouteTrade<TInput, TOutput, TTradeType>,\n b: MixedRouteTrade<TInput, TOutput, TTradeType>\n) {\n // must have same input and output token for comparison\n invariant(a.inputAmount.currency.equals(b.inputAmount.currency), 'INPUT_CURRENCY')\n invariant(a.outputAmount.currency.equals(b.outputAmount.currency), 'OUTPUT_CURRENCY')\n if (a.outputAmount.equalTo(b.outputAmount)) {\n if (a.inputAmount.equalTo(b.inputAmount)) {\n // consider the number of hops since each hop costs gas\n const aHops = a.swaps.reduce((total, cur) => total + cur.route.path.length, 0)\n const bHops = b.swaps.reduce((total, cur) => total + cur.route.path.length, 0)\n return aHops - bHops\n }\n // trade A requires less input than trade B, so A should come first\n if (a.inputAmount.lessThan(b.inputAmount)) {\n return -1\n } else {\n return 1\n }\n } else {\n // tradeA has less output than trade B, so should come second\n if (a.outputAmount.lessThan(b.outputAmount)) {\n return 1\n } else {\n return -1\n }\n }\n}\n\n/**\n * Represents a trade executed against a set of routes where some percentage of the input is\n * split across each route.\n *\n * Each route has its own set of pools. Pools can not be re-used across routes.\n *\n * Does not account for slippage, i.e., changes in price environment that can occur between\n * the time the trade is submitted and when it is executed.\n * @notice This class is functionally the same as the `Trade` class in the `@uniswap/v3-sdk` package, aside from typing and some input validation.\n * @template TInput The input token, either Ether or an ERC-20\n * @template TOutput The output token, either Ether or an ERC-20\n * @template TTradeType The trade type, either exact input or exact output\n */\nexport class MixedRouteTrade<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType> {\n /**\n * @deprecated Deprecated in favor of 'swaps' property. If the trade consists of multiple routes\n * this will return an error.\n *\n * When the trade consists of just a single route, this returns the route of the trade,\n * i.e. which pools the trade goes through.\n */\n public get route(): MixedRouteSDK<TInput, TOutput> {\n invariant(this.swaps.length == 1, 'MULTIPLE_ROUTES')\n return this.swaps[0].route\n }\n\n /**\n * The swaps of the trade, i.e. which routes and how much is swapped in each that\n * make up the trade.\n */\n public readonly swaps: {\n route: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n\n /**\n * The type of the trade, either exact in or exact out.\n */\n public readonly tradeType: TTradeType\n\n /**\n * The cached result of the input amount computation\n * @private\n */\n private _inputAmount: CurrencyAmount<TInput> | undefined\n\n /**\n * The input amount for the trade assuming no slippage.\n */\n public get inputAmount(): CurrencyAmount<TInput> {\n if (this._inputAmount) {\n return this._inputAmount\n }\n\n const inputCurrency = this.swaps[0].inputAmount.currency\n const totalInputFromRoutes = this.swaps\n .map(({ inputAmount }) => inputAmount)\n .reduce((total, cur) => total.add(cur), CurrencyAmount.fromRawAmount(inputCurrency, 0))\n\n this._inputAmount = totalInputFromRoutes\n return this._inputAmount\n }\n\n /**\n * The cached result of the output amount computation\n * @private\n */\n private _outputAmount: CurrencyAmount<TOutput> | undefined\n\n /**\n * The output amount for the trade assuming no slippage.\n */\n public get outputAmount(): CurrencyAmount<TOutput> {\n if (this._outputAmount) {\n return this._outputAmount\n }\n\n const outputCurrency = this.swaps[0].outputAmount.currency\n const totalOutputFromRoutes = this.swaps\n .map(({ outputAmount }) => outputAmount)\n .reduce((total, cur) => total.add(cur), CurrencyAmount.fromRawAmount(outputCurrency, 0))\n\n this._outputAmount = totalOutputFromRoutes\n return this._outputAmount\n }\n\n /**\n * The cached result of the computed execution price\n * @private\n */\n private _executionPrice: Price<TInput, TOutput> | undefined\n\n /**\n * The price expressed in terms of output amount/input amount.\n */\n public get executionPrice(): Price<TInput, TOutput> {\n return (\n this._executionPrice ??\n (this._executionPrice = new Price(\n this.inputAmount.currency,\n this.outputAmount.currency,\n this.inputAmount.quotient,\n this.outputAmount.quotient\n ))\n )\n }\n\n /**\n * The cached result of the price impact computation\n * @private\n */\n private _priceImpact: Percent | undefined\n\n /**\n * Returns the percent difference between the route's mid price and the price impact\n */\n public get priceImpact(): Percent {\n if (this._priceImpact) {\n return this._priceImpact\n }\n\n let spotOutputAmount = CurrencyAmount.fromRawAmount(this.outputAmount.currency, 0)\n for (const { route, inputAmount } of this.swaps) {\n const midPrice = route.midPrice\n spotOutputAmount = spotOutputAmount.add(midPrice.quote(inputAmount))\n }\n\n const priceImpact = spotOutputAmount.subtract(this.outputAmount).divide(spotOutputAmount)\n this._priceImpact = new Percent(priceImpact.numerator, priceImpact.denominator)\n\n return this._priceImpact\n }\n\n /**\n * Constructs a trade by simulating swaps through the given route\n * @template TInput The input token, either Ether or an ERC-20.\n * @template TOutput The output token, either Ether or an ERC-20.\n * @template TTradeType The type of the trade, either exact in or exact out.\n * @param route route to swap through\n * @param amount the amount specified, either input or output, depending on tradeType\n * @param tradeType whether the trade is an exact input or exact output swap\n * @returns The route\n */\n public static async fromRoute<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(\n route: MixedRouteSDK<TInput, TOutput>,\n amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>,\n tradeType: TTradeType\n ): Promise<MixedRouteTrade<TInput, TOutput, TTradeType>> {\n const amounts: CurrencyAmount<Token>[] = new Array(route.path.length)\n let inputAmount: CurrencyAmount<TInput>\n let outputAmount: CurrencyAmount<TOutput>\n\n invariant(tradeType === TradeType.EXACT_INPUT, 'TRADE_TYPE')\n\n invariant(amount.currency.equals(route.input), 'INPUT')\n amounts[0] = amount.wrapped\n for (let i = 0; i < route.path.length - 1; i++) {\n const pool = route.pools[i]\n const [outputAmount] = await pool.getOutputAmount(amounts[i])\n amounts[i + 1] = outputAmount\n }\n inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator)\n outputAmount = CurrencyAmount.fromFractionalAmount(\n route.output,\n amounts[amounts.length - 1].numerator,\n amounts[amounts.length - 1].denominator\n )\n\n return new MixedRouteTrade({\n routes: [{ inputAmount, outputAmount, route }],\n tradeType,\n })\n }\n\n /**\n * Constructs a trade from routes by simulating swaps\n *\n * @template TInput The input token, either Ether or an ERC-20.\n * @template TOutput The output token, either Ether or an ERC-20.\n * @template TTradeType The type of the trade, either exact in or exact out.\n * @param routes the routes to swap through and how much of the amount should be routed through each\n * @param tradeType whether the trade is an exact input or exact output swap\n * @returns The trade\n */\n public static async fromRoutes<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(\n routes: {\n amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>\n route: MixedRouteSDK<TInput, TOutput>\n }[],\n tradeType: TTradeType\n ): Promise<MixedRouteTrade<TInput, TOutput, TTradeType>> {\n const populatedRoutes: {\n route: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n invariant(tradeType === TradeType.EXACT_INPUT, 'TRADE_TYPE')\n\n for (const { route, amount } of routes) {\n const amounts: CurrencyAmount<Token>[] = new Array(route.path.length)\n let inputAmount: CurrencyAmount<TInput>\n let outputAmount: CurrencyAmount<TOutput>\n\n invariant(amount.currency.equals(route.input), 'INPUT')\n inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator)\n amounts[0] = CurrencyAmount.fromFractionalAmount(route.input.wrapped, amount.numerator, amount.denominator)\n\n for (let i = 0; i < route.path.length - 1; i++) {\n const pool = route.pools[i]\n const [outputAmount] = await pool.getOutputAmount(amounts[i])\n amounts[i + 1] = outputAmount\n }\n\n outputAmount = CurrencyAmount.fromFractionalAmount(\n route.output,\n amounts[amounts.length - 1].numerator,\n amounts[amounts.length - 1].denominator\n )\n\n populatedRoutes.push({ route, inputAmount, outputAmount })\n }\n\n return new MixedRouteTrade({\n routes: populatedRoutes,\n tradeType,\n })\n }\n\n /**\n * Creates a trade without computing the result of swapping through the route. Useful when you have simulated the trade\n * elsewhere and do not have any tick data\n * @template TInput The input token, either Ether or an ERC-20\n * @template TOutput The output token, either Ether or an ERC-20\n * @template TTradeType The type of the trade, either exact in or exact out\n * @param constructorArguments The arguments passed to the trade constructor\n * @returns The unchecked trade\n */\n public static createUncheckedTrade<\n TInput extends Currency,\n TOutput extends Currency,\n TTradeType extends TradeType\n >(constructorArguments: {\n route: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n tradeType: TTradeType\n }): MixedRouteTrade<TInput, TOutput, TTradeType> {\n return new MixedRouteTrade({\n ...constructorArguments,\n routes: [\n {\n inputAmount: constructorArguments.inputAmount,\n outputAmount: constructorArguments.outputAmount,\n route: constructorArguments.route,\n },\n ],\n })\n }\n\n /**\n * Creates a trade without computing the result of swapping through the routes. Useful when you have simulated the trade\n * elsewhere and do not have any tick data\n * @template TInput The input token, either Ether or an ERC-20\n * @template TOutput The output token, either Ether or an ERC-20\n * @template TTradeType The type of the trade, either exact in or exact out\n * @param constructorArguments The arguments passed to the trade constructor\n * @returns The unchecked trade\n */\n public static createUncheckedTradeWithMultipleRoutes<\n TInput extends Currency,\n TOutput extends Currency,\n TTradeType extends TradeType\n >(constructorArguments: {\n routes: {\n route: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n tradeType: TTradeType\n }): MixedRouteTrade<TInput, TOutput, TTradeType> {\n return new MixedRouteTrade(constructorArguments)\n }\n\n /**\n * Construct a trade by passing in the pre-computed property values\n * @param routes The routes through which the trade occurs\n * @param tradeType The type of trade, exact input or exact output\n */\n private constructor({\n routes,\n tradeType,\n }: {\n routes: {\n route: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n tradeType: TTradeType\n }) {\n const inputCurrency = routes[0].inputAmount.currency\n const outputCurrency = routes[0].outputAmount.currency\n invariant(\n routes.every(({ route }) => inputCurrency.wrapped.equals(route.input.wrapped)),\n 'INPUT_CURRENCY_MATCH'\n )\n invariant(\n routes.every(({ route }) => outputCurrency.wrapped.equals(route.output.wrapped)),\n 'OUTPUT_CURRENCY_MATCH'\n )\n\n const numPools = routes.map(({ route }) => route.pools.length).reduce((total, cur) => total + cur, 0)\n const poolAddressSet = new Set<string>()\n for (const { route } of routes) {\n for (const pool of route.pools) {\n pool instanceof Pool\n ? poolAddressSet.add(Pool.getAddress(pool.token0, pool.token1, pool.fee))\n : poolAddressSet.add(Pair.getAddress(pool.token0, pool.token1))\n }\n }\n\n invariant(numPools == poolAddressSet.size, 'POOLS_DUPLICATED')\n\n invariant(tradeType === TradeType.EXACT_INPUT, 'TRADE_TYPE')\n\n this.swaps = routes\n this.tradeType = tradeType\n }\n\n /**\n * Get the minimum amount that must be received from this trade for the given slippage tolerance\n * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade\n * @returns The amount out\n */\n public minimumAmountOut(slippageTolerance: Percent, amountOut = this.outputAmount): CurrencyAmount<TOutput> {\n invariant(!slippageTolerance.lessThan(ZERO), 'SLIPPAGE_TOLERANCE')\n /// does not support exactOutput, as enforced in the constructor\n const slippageAdjustedAmountOut = new Fraction(ONE)\n .add(slippageTolerance)\n .invert()\n .multiply(amountOut.quotient).quotient\n return CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut)\n }\n\n /**\n * Get the maximum amount in that can be spent via this trade for the given slippage tolerance\n * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade\n * @returns The amount in\n */\n public maximumAmountIn(slippageTolerance: Percent, amountIn = this.inputAmount): CurrencyAmount<TInput> {\n invariant(!slippageTolerance.lessThan(ZERO), 'SLIPPAGE_TOLERANCE')\n return amountIn\n /// does not support exactOutput\n }\n\n /**\n * Return the execution price after accounting for slippage tolerance\n * @param slippageTolerance the allowed tolerated slippage\n * @returns The execution price\n */\n public worstExecutionPrice(slippageTolerance: Percent): Price<TInput, TOutput> {\n return new Price(\n this.inputAmount.currency,\n this.outputAmount.currency,\n this.maximumAmountIn(slippageTolerance).quotient,\n this.minimumAmountOut(slippageTolerance).quotient\n )\n }\n\n /**\n * Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token\n * amount to an output token, making at most `maxHops` hops.\n * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting\n * the amount in among multiple routes.\n * @param pools the pools to consider in finding the best trade\n * @param nextAmountIn exact amount of input currency to spend\n * @param currencyOut the desired currency out\n * @param maxNumResults maximum number of results to return\n * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool\n * @param currentPools used in recursion; the current list of pools\n * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter\n * @param bestTrades used in recursion; the current list of best trades\n * @returns The exact in trade\n */\n public static async bestTradeExactIn<TInput extends Currency, TOutput extends Currency>(\n pools: (Pool | Pair)[],\n currencyAmountIn: CurrencyAmount<TInput>,\n currencyOut: TOutput,\n { maxNumResults = 3, maxHops = 3 }: BestTradeOptions = {},\n // used in recursion.\n currentPools: (Pool | Pair)[] = [],\n nextAmountIn: CurrencyAmount<Currency> = currencyAmountIn,\n bestTrades: MixedRouteTrade<TInput, TOutput, TradeType.EXACT_INPUT>[] = []\n ): Promise<MixedRouteTrade<TInput, TOutput, TradeType.EXACT_INPUT>[]> {\n invariant(pools.length > 0, 'POOLS')\n invariant(maxHops > 0, 'MAX_HOPS')\n invariant(currencyAmountIn === nextAmountIn || currentPools.length > 0, 'INVALID_RECURSION')\n\n const amountIn = nextAmountIn.wrapped\n const tokenOut = currencyOut.wrapped\n for (let i = 0; i < pools.length; i++) {\n const pool = pools[i]\n // pool irrelevant\n if (!pool.token0.equals(amountIn.currency) && !pool.token1.equals(amountIn.currency)) continue\n if (pool instanceof Pair) {\n if ((pool as Pair).reserve0.equalTo(ZERO) || (pool as Pair).reserve1.equalTo(ZERO)) continue\n }\n\n let amountOut: CurrencyAmount<Token>\n try {\n ;[amountOut] = await pool.getOutputAmount(amountIn)\n } catch (error) {\n // input too low\n // @ts-ignore[2571] error is unknown\n if (error.isInsufficientInputAmountError) {\n continue\n }\n throw error\n }\n // we have arrived at the output token, so this is the final trade of one of the paths\n if (amountOut.currency.isToken && amountOut.currency.equals(tokenOut)) {\n sortedInsert(\n bestTrades,\n await MixedRouteTrade.fromRoute(\n new MixedRouteSDK([...currentPools, pool], currencyAmountIn.currency, currencyOut),\n currencyAmountIn,\n TradeType.EXACT_INPUT\n ),\n maxNumResults,\n tradeComparator\n )\n } else if (maxHops > 1 && pools.length > 1) {\n const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length))\n\n // otherwise, consider all the other paths that lead from this token as long as we have not exceeded maxHops\n await MixedRouteTrade.bestTradeExactIn(\n poolsExcludingThisPool,\n currencyAmountIn,\n currencyOut,\n {\n maxNumResults,\n maxHops: maxHops - 1,\n },\n [...currentPools, pool],\n amountOut,\n bestTrades\n )\n }\n }\n\n return bestTrades\n }\n}\n","export enum Protocol {\n V2 = 'V2',\n V3 = 'V3',\n MIXED = 'MIXED',\n}\n","// entities/route.ts\n\nimport { Route as V2RouteSDK, Pair } from '@uniswap/v2-sdk'\nimport { Route as V3RouteSDK, Pool } from '@uniswap/v3-sdk'\nimport { Protocol } from './protocol'\nimport { Currency, Price, Token } from '@uniswap/sdk-core'\nimport { MixedRouteSDK } from './mixedRoute/route'\n\nexport interface IRoute<TInput extends Currency, TOutput extends Currency, TPool extends Pool | Pair> {\n protocol: Protocol\n // array of pools if v3 or pairs if v2\n pools: TPool[]\n path: Token[]\n midPrice: Price<TInput, TOutput>\n input: TInput\n output: TOutput\n}\n\n// V2 route wrapper\nexport class RouteV2<TInput extends Currency, TOutput extends Currency>\n extends V2RouteSDK<TInput, TOutput>\n implements IRoute<TInput, TOutput, Pair>\n{\n public readonly protocol: Protocol = Protocol.V2\n public readonly pools: Pair[]\n\n constructor(v2Route: V2RouteSDK<TInput, TOutput>) {\n super(v2Route.pairs, v2Route.input, v2Route.output)\n this.pools = this.pairs\n }\n}\n\n// V3 route wrapper\nexport class RouteV3<TInput extends Currency, TOutput extends Currency>\n extends V3RouteSDK<TInput, TOutput>\n implements IRoute<TInput, TOutput, Pool>\n{\n public readonly protocol: Protocol = Protocol.V3\n public readonly path: Token[]\n\n constructor(v3Route: V3RouteSDK<TInput, TOutput>) {\n super(v3Route.pools, v3Route.input, v3Route.output)\n this.path = v3Route.tokenPath\n }\n}\n\n// Mixed route wrapper\nexport class MixedRoute<TInput extends Currency, TOutput extends Currency>\n extends MixedRouteSDK<TInput, TOutput>\n implements IRoute<TInput, TOutput, Pool | Pair>\n{\n public readonly protocol: Protocol = Protocol.MIXED\n\n constructor(mixedRoute: MixedRouteSDK<TInput, TOutput>) {\n super(mixedRoute.pools, mixedRoute.input, mixedRoute.output)\n }\n}\n","import { Currency, CurrencyAmount, Fraction, Percent, Price, TradeType } from '@uniswap/sdk-core'\nimport { Pair, Route as V2RouteSDK, Trade as V2TradeSDK } from '@uniswap/v2-sdk'\nimport { Pool, Route as V3RouteSDK, Trade as V3TradeSDK } from '@uniswap/v3-sdk'\nimport invariant from 'tiny-invariant'\nimport { ONE, ZERO, ZERO_PERCENT } from '../constants'\nimport { MixedRouteSDK } from './mixedRoute/route'\nimport { MixedRouteTrade as MixedRouteTradeSDK } from './mixedRoute/trade'\nimport { IRoute, MixedRoute, RouteV2, RouteV3 } from './route'\n\nexport class Trade<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType> {\n public readonly routes: IRoute<TInput, TOutput, Pair | Pool>[]\n public readonly tradeType: TTradeType\n private _outputAmount: CurrencyAmount<TOutput> | undefined\n private _inputAmount: CurrencyAmount<TInput> | undefined\n\n /**\n * The swaps of the trade, i.e. which routes and how much is swapped in each that\n * make up the trade. May consist of swaps in v2 or v3.\n */\n public readonly swaps: {\n route: IRoute<TInput, TOutput, Pair | Pool>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n\n // construct a trade across v2 and v3 routes from pre-computed amounts\n public constructor({\n v2Routes,\n v3Routes,\n tradeType,\n mixedRoutes,\n }: {\n v2Routes: {\n routev2: V2RouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n v3Routes: {\n routev3: V3RouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n tradeType: TTradeType\n mixedRoutes?: {\n mixedRoute: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[]\n }) {\n this.swaps = []\n this.routes = []\n // wrap v2 routes\n for (const { routev2, inputAmount, outputAmount } of v2Routes) {\n const route = new RouteV2(routev2)\n this.routes.push(route)\n this.swaps.push({\n route,\n inputAmount,\n outputAmount,\n })\n }\n // wrap v3 routes\n for (const { routev3, inputAmount, outputAmount } of v3Routes) {\n const route = new RouteV3(routev3)\n this.routes.push(route)\n this.swaps.push({\n route,\n inputAmount,\n outputAmount,\n })\n }\n // wrap mixedRoutes\n if (mixedRoutes) {\n for (const { mixedRoute, inputAmount, outputAmount } of mixedRoutes) {\n const route = new MixedRoute(mixedRoute)\n this.routes.push(route)\n this.swaps.push({\n route,\n inputAmount,\n outputAmount,\n })\n }\n }\n this.tradeType = tradeType\n\n // each route must have the same input and output currency\n const inputCurrency = this.swaps[0].inputAmount.currency\n const outputCurrency = this.swaps[0].outputAmount.currency\n invariant(\n this.swaps.every(({ route }) => inputCurrency.wrapped.equals(route.input.wrapped)),\n 'INPUT_CURRENCY_MATCH'\n )\n invariant(\n this.swaps.every(({ route }) => outputCurrency.wrapped.equals(route.output.wrapped)),\n 'OUTPUT_CURRENCY_MATCH'\n )\n\n // pools must be unique inter protocols\n const numPools = this.swaps.map(({ route }) => route.pools.length).reduce((total, cur) => total + cur, 0)\n const poolAddressSet = new Set<string>()\n for (const { route } of this.swaps) {\n for (const pool of route.pools) {\n if (pool instanceof Pool) {\n poolAddressSet.add(Pool.getAddress(pool.token0, pool.token1, (pool as Pool).fee))\n } else if (pool instanceof Pair) {\n const pair = pool\n poolAddressSet.add(Pair.getAddress(pair.token0, pair.token1))\n } else {\n throw new Error('Unexpected pool type in route when constructing trade object')\n }\n }\n }\n invariant(numPools == poolAddressSet.size, 'POOLS_DUPLICATED')\n }\n\n public get inputAmount(): CurrencyAmount<TInput> {\n if (this._inputAmount) {\n return this._inputAmount\n }\n\n const inputCurrency = this.swaps[0].inputAmount.currency\n const totalInputFromRoutes = this.swaps\n .map(({ inputAmount }) => inputAmount)\n .reduce((total, cur) => total.add(cur), CurrencyAmount.fromRawAmount(inputCurrency, 0))\n\n this._inputAmount = totalInputFromRoutes\n return this._inputAmount\n }\n\n public get outputAmount(): CurrencyAmount<TOutput> {\n if (this._outputAmount) {\n return this._outputAmount\n }\n\n const outputCurrency = this.swaps[0].outputAmount.currency\n const totalOutputFromRoutes = this.swaps\n .map(({ outputAmount }) => outputAmount)\n .reduce((total, cur) => total.add(cur), CurrencyAmount.fromRawAmount(outputCurrency, 0))\n\n this._outputAmount = totalOutputFromRoutes\n return this._outputAmount\n }\n\n private _executionPrice: Price<TInput, TOutput> | undefined\n\n /**\n * The price expressed in terms of output amount/input amount.\n */\n public get executionPrice(): Price<TInput, TOutput> {\n return (\n this._executionPrice ??\n (this._executionPrice = new Price(\n this.inputAmount.currency,\n this.outputAmount.currency,\n this.inputAmount.quotient,\n this.outputAmount.quotient\n ))\n )\n }\n\n /**\n * Returns the sell tax of the input token\n */\n public get inputTax(): Percent {\n const inputCurrency = this.inputAmount.currency\n if (inputCurrency.isNative || !inputCurrency.wrapped.sellFeeBps) return ZERO_PERCENT\n\n return new Percent(inputCurrency.wrapped.sellFeeBps.toNumber(), 10000)\n }\n\n /**\n * Returns the buy tax of the output token\n */\n public get outputTax(): Percent {\n const outputCurrency = this.outputAmount.currency\n if (outputCurrency.isNative || !outputCurrency.wrapped.buyFeeBps) return ZERO_PERCENT\n\n return new Percent(outputCurrency.wrapped.buyFeeBps.toNumber(), 10000)\n }\n\n /**\n * The cached result of the price impact computation\n * @private\n */\n private _priceImpact: Percent | undefined\n /**\n * Returns the percent difference between the route's mid price and the expected execution price\n * In order to exclude token taxes from the price impact calculation, the spot price is calculated\n * using a ratio of values that go into the pools, which are the post-tax input amount and pre-tax output amount.\n */\n public get priceImpact(): Percent {\n if (this._priceImpact) {\n return this._priceImpact\n }\n\n let spotOutputAmount = CurrencyAmount.fromRawAmount(this.outputAmount.currency, 0)\n for (const { route, inputAmount } of this.swaps) {\n const midPrice = route.midPrice\n const postTaxInputAmount = inputAmount.multiply(new Fraction(ONE).subtract(this.inputTax))\n spotOutputAmount = spotOutputAmount.add(midPrice.quote(postTaxInputAmount))\n }\n\n const preTaxOutputAmount = this.outputAmount.divide(new Fraction(ONE).subtract(this.outputTax))\n const priceImpact = spotOutputAmount.subtract(preTaxOutputAmount).divide(spotOutputAmount)\n this._priceImpact = new Percent(priceImpact.numerator, priceImpact.denominator)\n\n return this._priceImpact\n }\n\n /**\n * Get the minimum amount that must be received from this trade for the given slippage tolerance\n * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade\n * @returns The amount out\n */\n public minimumAmountOut(slippageTolerance: Percent, amountOut = this.outputAmount): CurrencyAmount<TOutput> {\n invariant(!slippageTolerance.lessThan(ZERO), 'SLIPPAGE_TOLERANCE')\n if (this.tradeType === TradeType.EXACT_OUTPUT) {\n return amountOut\n } else {\n const slippageAdjustedAmountOut = new Fraction(ONE)\n .add(slippageTolerance)\n .invert()\n .multiply(amountOut.quotient).quotient\n return CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut)\n }\n }\n\n /**\n * Get the maximum amount in that can be spent via this trade for the given slippage tolerance\n * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade\n * @returns The amount in\n */\n public maximumAmountIn(slippageTolerance: Percent, amountIn = this.inputAmount): CurrencyAmount<TInput> {\n invariant(!slippageTolerance.lessThan(ZERO), 'SLIPPAGE_TOLERANCE')\n if (this.tradeType === TradeType.EXACT_INPUT) {\n return amountIn\n } else {\n const slippageAdjustedAmountIn = new Fraction(ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient\n return CurrencyAmount.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn)\n }\n }\n\n /**\n * Return the execution price after accounting for slippage tolerance\n * @param slippageTolerance the allowed tolerated slippage\n * @returns The execution price\n */\n public worstExecutionPrice(slippageTolerance: Percent): Price<TInput, TOutput> {\n return new Price(\n this.inputAmount.currency,\n this.outputAmount.currency,\n this.maximumAmountIn(slippageTolerance).quotient,\n this.minimumAmountOut(slippageTolerance).quotient\n )\n }\n\n public static async fromRoutes<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(\n v2Routes: {\n routev2: V2RouteSDK<TInput, TOutput>\n amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>\n }[],\n v3Routes: {\n routev3: V3RouteSDK<TInput, TOutput>\n amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>\n }[],\n tradeType: TTradeType,\n mixedRoutes?: {\n mixedRoute: MixedRouteSDK<TInput, TOutput>\n amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>\n }[]\n ): Promise<Trade<TInput, TOutput, TTradeType>> {\n const populatedV2Routes: {\n routev2: V2RouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n const populatedV3Routes: {\n routev3: V3RouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n const populatedMixedRoutes: {\n mixedRoute: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n for (const { routev2, amount } of v2Routes) {\n const v2Trade = new V2TradeSDK(routev2, amount, tradeType)\n const { inputAmount, outputAmount } = v2Trade\n\n populatedV2Routes.push({\n routev2,\n inputAmount,\n outputAmount,\n })\n }\n\n for (const { routev3, amount } of v3Routes) {\n const v3Trade = await V3TradeSDK.fromRoute(routev3, amount, tradeType)\n const { inputAmount, outputAmount } = v3Trade\n\n populatedV3Routes.push({\n routev3,\n inputAmount,\n outputAmount,\n })\n }\n\n if (mixedRoutes) {\n for (const { mixedRoute, amount } of mixedRoutes) {\n const mixedRouteTrade = await MixedRouteTradeSDK.fromRoute(mixedRoute, amount, tradeType)\n const { inputAmount, outputAmount } = mixedRouteTrade\n\n populatedMixedRoutes.push({\n mixedRoute,\n inputAmount,\n outputAmount,\n })\n }\n }\n\n return new Trade({\n v2Routes: populatedV2Routes,\n v3Routes: populatedV3Routes,\n mixedRoutes: populatedMixedRoutes,\n tradeType,\n })\n }\n\n public static async fromRoute<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(\n route: V2RouteSDK<TInput, TOutput> | V3RouteSDK<TInput, TOutput> | MixedRouteSDK<TInput, TOutput>,\n amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>,\n tradeType: TTradeType\n ): Promise<Trade<TInput, TOutput, TTradeType>> {\n let v2Routes: {\n routev2: V2RouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n let v3Routes: {\n routev3: V3RouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n let mixedRoutes: {\n mixedRoute: MixedRouteSDK<TInput, TOutput>\n inputAmount: CurrencyAmount<TInput>\n outputAmount: CurrencyAmount<TOutput>\n }[] = []\n\n if (route instanceof V2RouteSDK) {\n const v2Trade = new V2TradeSDK(route, amount, tradeType)\n const { inputAmount, outputAmount } = v2Trade\n v2Routes = [{ routev2: route, inputAmount, outputAmount }]\n } else if (route instanceof V3RouteSDK) {\n const v3Trade = await V3TradeSDK.fromRoute(route, amount, tradeType)\n const { inputAmount, outputAmount } = v3Trade\n v3Routes = [{ routev3: route, inputAmount, outputAmount }]\n } else if (route instanceof MixedRouteSDK) {\n const mixedRouteTrade = await MixedRouteTradeSDK.fromRoute(route, amount, tradeType)\n const { inputAmount, outputAmount } = mixedRouteTrade\n mixedRoutes = [{ mixedRoute: route, inputAmount, outputAmount }]\n } else {\n throw new Error('Invalid route type')\n }\n\n return new Trade({\n v2Routes,\n v3Routes,\n mixedRoutes,\n tradeType,\n })\n }\n}\n","import { pack } from '@ethersproject/solidity'\nimport { Currency, Token } from '@uniswap/sdk-core'\nimport { Pool } from '@uniswap/v3-sdk'\nimport { Pair } from '@uniswap/v2-sdk'\nimport { MixedRouteSDK } from '../entities/mixedRoute/route'\nimport { V2_FEE_PATH_PLACEHOLDER } from '../constants'\n\n/**\n * Converts a route to a hex encoded path\n * @notice only supports exactIn route encodings\n * @param route the mixed path to convert to an encoded path\n * @returns the exactIn encoded path\n */\nexport function encodeMixedRouteToPath(route: MixedRouteSDK<Currency, Currency>): string {\n const firstInputToken: Token = route.input.wrapped\n\n const { path, types } = route.pools.reduce(\n (\n { inputToken, path, types }: { inputToken: Token; path: (string | number)[]; types: string[] },\n pool: Pool | Pair,\n index\n ): { inputToken: Token; path: (string | number)[]; types: string[] } => {\n const outputToken: Token = pool.token0.equals(inputToken) ? pool.token1 : pool.token0\n if (index === 0) {\n return {\n inputToken: outputToken,\n types: ['address', 'uint24', 'address'],\n path: [inputToken.address, pool instanceof Pool ? pool.fee : V2_FEE_PATH_PLACEHOLDER, outputToken.address],\n }\n } else {\n return {\n inputToken: outputToken,\n types: [...types, 'uint24', 'address'],\n path: [...path, pool instanceof Pool ? pool.fee : V2_FEE_PATH_PLACEHOLDER, outputToken.address],\n }\n }\n },\n { inputToken: firstInputToken, path: [], types: [] }\n )\n\n return pack(types, path)\n}\n","import { Currency, Token } from '@uniswap/sdk-core'\nimport { Pair } from '@uniswap/v2-sdk'\nimport { Pool } from '@uniswap/v3-sdk'\nimport { MixedRouteSDK } from '../entities/mixedRoute/route'\n\n/**\n * Utility function to return each consecutive section of Pools or Pairs in a MixedRoute\n * @param route\n * @returns a nested array of Pools or Pairs in the order of the route\n */\nexport const partitionMixedRouteByProtocol = (route: MixedRouteSDK<Currency, Currency>): (Pool | Pair)[][] => {\n let acc = []\n\n let left = 0\n let right = 0\n while (right < route.pools.length) {\n if (\n (route.pools[left] instanceof Pool && route.pools[right] instanceof Pair) ||\n (route.pools[left] instanceof Pair && route.pools[right] instanceof Pool)\n ) {\n acc.push(route.pools.slice(left, right))\n left = right\n }\n // seek forward with right pointer\n right++\n if (right === route.pools.length) {\n /// we reached the end, take the rest\n acc.push(route.pools.slice(left, right))\n }\n }\n return acc\n}\n\n/**\n * Simple utility function to get the output of an array of Pools or Pairs\n * @param pools\n * @param firstInputToken\n * @returns the output token of the last pool in the array\n */\nexport const getOutputOfPools = (pools: (Pool | Pair)[], firstInputToken: Token): Token => {\n const { inputToken: outputToken } = pools.reduce(\n ({ inputToken }, pool: Pool | Pair): { inputToken: Token } => {\n if (!pool.involvesToken(inputToken)) throw new Error('PATH')\n const outputToken: Token = pool.token0.equals(inputToken) ? pool.token1 : pool.token0\n return {\n inputToken: outputToken,\n }\n },\n { inputToken: firstInputToken }\n )\n return outputToken\n}\n","import { Interface } from '@ethersproject/abi'\nimport { Currency, CurrencyAmount, Percent, TradeType, validateAndParseAddress, WETH9 } from '@uniswap/sdk-core'\nimport { abi } from '@uniswap/swap-router-contracts/artifacts/contracts/interfaces/ISwapRouter02.sol/ISwapRouter02.json'\nimport { Trade as V2Trade } from '@uniswap/v2-sdk'\nimport {\n encodeRouteToPath,\n FeeOptions,\n MethodParameters,\n Payments,\n PermitOptions,\n Pool,\n Position,\n SelfPermit,\n toHex,\n Trade as V3Trade,\n} from '@uniswap/v3-sdk'\nimport invariant from 'tiny-invariant'\nimport JSBI from 'jsbi'\nimport { ADDRESS_THIS, MSG_SENDER } from './constants'\nimport { ApproveAndCall, ApprovalTypes, CondensedAddLiquidityOptions } from './approveAndCall'\nimport { Trade } from './entities/trade'\nimport { Protocol } from './entities/protocol'\nimport { MixedRoute, RouteV2, RouteV3 } from './entities/route'\nimport { MulticallExtended, Validation } from './multicallExtended'\nimport { PaymentsExtended } from './paymentsExtended'\nimport { MixedRouteTrade } from './entities/mixedRoute/trade'\nimport { encodeMixedRouteToPath } from './utils/encodeMixedRouteToPath'\nimport { MixedRouteSDK } from './entities/mixedRoute/route'\nimport { partitionMixedRouteByProtocol, getOutputOfPools } from './utils'\n\nconst ZERO = JSBI.BigInt(0)\nconst REFUND_ETH_PRICE_IMPACT_THRESHOLD = new Percent(JSBI.BigInt(50), JSBI.BigInt(100))\n\n/**\n * Options for producing the arguments to send calls to the router.\n */\nexport interface SwapOptions {\n /**\n * How much the execution price is allowed to move unfavorably from the trade execution price.\n */\n slippageTolerance: Percent\n\n /**\n * The account that should receive the output. If omitted, output is sent to msg.sender.\n */\n recipient?: string\n\n /**\n * Either deadline (when the transaction expires, in epoch seconds), or previousBlockhash.\n */\n deadlineOrPreviousBlockhash?: Validation\n\n /**\n * The optional permit parameters for spending the input.\n */\n inputTokenPermit?: PermitOptions\n\n /**\n * Optional information for taking a fee on output.\n */\n fee?: FeeOptions\n}\n\nexport interface SwapAndAddOptions extends SwapOptions {\n /**\n * The optional permit parameters for pulling in remaining output token.\n */\n outputTokenPermit?: PermitOptions\n}\n\ntype AnyTradeType =\n | Trade<Currency, Currency, TradeType>\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n | (\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n )[]\n\n/**\n * Represents the Uniswap V2 + V3 SwapRouter02, and has static methods for helping execute trades.\n */\nexport abstract class SwapRouter {\n public static INTERFACE: Interface = new Interface(abi)\n\n /**\n * Cannot be constructed.\n */\n private constructor() {}\n\n /**\n * @notice Generates the calldata for a Swap with a V2 Route.\n * @param trade The V2Trade to encode.\n * @param options SwapOptions to use for the trade.\n * @param routerMustCustody Flag for whether funds should be sent to the router\n * @param performAggregatedSlippageCheck Flag for whether we want to perform an aggregated slippage check\n * @returns A string array of calldatas for the trade.\n */\n private static encodeV2Swap(\n trade: V2Trade<Currency, Currency, TradeType>,\n options: SwapOptions,\n routerMustCustody: boolean,\n performAggregatedSlippageCheck: boolean\n ): string {\n const amountIn: string = toHex(trade.maximumAmountIn(options.slippageTolerance).quotient)\n const amountOut: string = toHex(trade.minimumAmountOut(options.slippageTolerance).quotient)\n\n const path = trade.route.path.map((token) => token.address)\n const recipient = routerMustCustody\n ? ADDRESS_THIS\n : typeof options.recipient === 'undefined'\n ? MSG_SENDER\n : validateAndParseAddress(options.recipient)\n\n if (trade.tradeType === TradeType.EXACT_INPUT) {\n const exactInputParams = [amountIn, performAggregatedSlippageCheck ? 0 : amountOut, path, recipient]\n\n return SwapRouter.INTERFACE.encodeFunctionData('swapExactTokensForTokens', exactInputParams)\n } else {\n const exactOutputParams = [amountOut, amountIn, path, recipient]\n\n return SwapRouter.INTERFACE.encodeFunctionData('swapTokensForExactTokens', exactOutputParams)\n }\n }\n\n /**\n * @notice Generates the calldata for a Swap with a V3 Route.\n * @param trade The V3Trade to encode.\n * @param options SwapOptions to use for the trade.\n * @param routerMustCustody Flag for whether funds should be sent to the router\n * @param performAggregatedSlippageCheck Flag for whether we want to perform an aggregated slippage check\n * @returns A string array of calldatas for the trade.\n */\n private static encodeV3Swap(\n trade: V3Trade<Currency, Currency, TradeType>,\n options: SwapOptions,\n routerMustCustody: boolean,\n performAggregatedSlippageCheck: boolean\n ): string[] {\n const calldatas: string[] = []\n\n for (const { route, inputAmount, outputAmount } of trade.swaps) {\n const amountIn: string = toHex(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient)\n const amountOut: string = toHex(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient)\n\n // flag for whether the trade is single hop or not\n const singleHop = route.pools.length === 1\n\n const recipient = routerMustCustody\n ? ADDRESS_THIS\n : typeof options.recipient === 'undefined'\n ? MSG_SENDER\n : validateAndParseAddress(options.recipient)\n\n if (singleHop) {\n if (trade.tradeType === TradeType.EXACT_INPUT) {\n const exactInputSingleParams = {\n tokenIn: route.tokenPath[0].address,\n tokenOut: route.tokenPath[1].address,\n fee: route.pools[0].fee,\n recipient,\n amountIn,\n amountOutMinimum: performAggregatedSlippageCheck ? 0 : amountOut,\n sqrtPriceLimitX96: 0,\n }\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInputSingle', [exactInputSingleParams]))\n } else {\n const exactOutputSingleParams = {\n tokenIn: route.tokenPath[0].address,\n tokenOut: route.tokenPath[1].address,\n fee: route.pools[0].fee,\n recipient,\n amountOut,\n amountInMaximum: amountIn,\n sqrtPriceLimitX96: 0,\n }\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutputSingle', [exactOutputSingleParams]))\n }\n } else {\n const path: string = encodeRouteToPath(route, trade.tradeType === TradeType.EXACT_OUTPUT)\n\n if (trade.tradeType === TradeType.EXACT_INPUT) {\n const exactInputParams = {\n path,\n recipient,\n amountIn,\n amountOutMinimum: performAggregatedSlippageCheck ? 0 : amountOut,\n }\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInput', [exactInputParams]))\n } else {\n const exactOutputParams = {\n path,\n recipient,\n amountOut,\n amountInMaximum: amountIn,\n }\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutput', [exactOutputParams]))\n }\n }\n }\n\n return calldatas\n }\n\n /**\n * @notice Generates the calldata for a MixedRouteSwap. Since single hop routes are not MixedRoutes, we will instead generate\n * them via the existing encodeV3Swap and encodeV2Swap methods.\n * @param trade The MixedRouteTrade to encode.\n * @param options SwapOptions to use for the trade.\n * @param routerMustCustody Flag for whether funds should be sent to the router\n * @param performAggregatedSlippageCheck Flag for whether we want to perform an aggregated slippage check\n * @returns A string array of calldatas for the trade.\n */\n private static encodeMixedRouteSwap(\n trade: MixedRouteTrade<Currency, Currency, TradeType>,\n options: SwapOptions,\n routerMustCustody: boolean,\n performAggregatedSlippageCheck: boolean\n ): string[] {\n const calldatas: string[] = []\n\n invariant(trade.tradeType === TradeType.EXACT_INPUT, 'TRADE_TYPE')\n\n for (const { route, inputAmount, outputAmount } of trade.swaps) {\n const amountIn: string = toHex(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient)\n const amountOut: string = toHex(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient)\n\n // flag for whether the trade is single hop or not\n const singleHop = route.pools.length === 1\n\n const recipient = routerMustCustody\n ? ADDRESS_THIS\n : typeof options.recipient === 'undefined'\n ? MSG_SENDER\n : validateAndParseAddress(options.recipient)\n\n const mixedRouteIsAllV3 = (route: MixedRouteSDK<Currency, Currency>) => {\n return route.pools.every((pool) => pool instanceof Pool)\n }\n\n if (singleHop) {\n /// For single hop, since it isn't really a mixedRoute, we'll just mimic behavior of V3 or V2\n /// We don't use encodeV3Swap() or encodeV2Swap() because casting the trade to a V3Trade or V2Trade is overcomplex\n if (mixedRouteIsAllV3(route)) {\n const exactInputSingleParams = {\n tokenIn: route.path[0].address,\n tokenOut: route.path[1].address,\n fee: (route.pools as Pool[])[0].fee,\n recipient,\n amountIn,\n amountOutMinimum: performAggregatedSlippageCheck ? 0 : amountOut,\n sqrtPriceLimitX96: 0,\n }\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInputSingle', [exactInputSingleParams]))\n } else {\n const path = route.path.map((token) => token.address)\n\n const exactInputParams = [amountIn, performAggregatedSlippageCheck ? 0 : amountOut, path, recipient]\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('swapExactTokensForTokens', exactInputParams))\n }\n } else {\n const sections = partitionMixedRouteByProtocol(route)\n\n const isLastSectionInRoute = (i: number) => {\n return i === sections.length - 1\n }\n\n let outputToken\n let inputToken = route.input.wrapped\n\n for (let i = 0; i < sections.length; i++) {\n const section = sections[i]\n /// Now, we get output of this section\n outputToken = getOutputOfPools(section, inputToken)\n\n const newRouteOriginal = new MixedRouteSDK(\n [...section],\n section[0].token0.equals(inputToken) ? section[0].token0 : section[0].token1,\n outputToken\n )\n const newRoute = new MixedRoute(newRouteOriginal)\n\n /// Previous output is now input\n inputToken = outputToken\n\n if (mixedRouteIsAllV3(newRoute)) {\n const path: string = encodeMixedRouteToPath(newRoute)\n const exactInputParams = {\n path,\n // By default router holds funds until the last swap, then it is sent to the recipient\n // special case exists where we are unwrapping WETH output, in which case `routerMustCustody` is set to true\n // and router still holds the funds. That logic bundled into how the value of `recipient` is calculated\n recipient: isLastSectionInRoute(i) ? recipient : ADDRESS_THIS,\n amountIn: i == 0 ? amountIn : 0,\n amountOutMinimum: !isLastSectionInRoute(i) ? 0 : amountOut,\n }\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInput', [exactInputParams]))\n } else {\n const exactInputParams = [\n i == 0 ? amountIn : 0, // amountIn\n !isLastSectionInRoute(i) ? 0 : amountOut, // amountOutMin\n newRoute.path.map((token) => token.address), // path\n isLastSectionInRoute(i) ? recipient : ADDRESS_THIS, // to\n ]\n\n calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('swapExactTokensForTokens', exactInputParams))\n }\n }\n }\n }\n\n return calldatas\n }\n\n private static encodeSwaps(\n trades: AnyTradeType,\n options: SwapOptions,\n isSwapAndAdd?: boolean\n ): {\n calldatas: string[]\n sampleTrade:\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n routerMustCustody: boolean\n inputIsNative: boolean\n outputIsNative: boolean\n totalAmountIn: CurrencyAmount<Currency>\n minimumAmountOut: CurrencyAmount<Currency>\n quoteAmountOut: CurrencyAmount<Currency>\n } {\n // If dealing with an instance of the aggregated Trade object, unbundle it to individual trade objects.\n if (trades instanceof Trade) {\n invariant(\n trades.swaps.every(\n (swap) =>\n swap.route.protocol == Protocol.V3 ||\n swap.route.protocol == Protocol.V2 ||\n swap.route.protocol == Protocol.MIXED\n ),\n 'UNSUPPORTED_PROTOCOL'\n )\n\n let individualTrades: (\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n )[] = []\n\n for (const { route, inputAmount, outputAmount } of trades.swaps) {\n if (route.protocol == Protocol.V2) {\n individualTrades.push(\n new V2Trade(\n route as RouteV2<Currency, Currency>,\n trades.tradeType == TradeType.EXACT_INPUT ? inputAmount : outputAmount,\n trades.tradeType\n )\n )\n } else if (route.protocol == Protocol.V3) {\n individualTrades.push(\n V3Trade.createUncheckedTrade({\n route: route as RouteV3<Currency, Currency>,\n inputAmount,\n outputAmount,\n tradeType: trades.tradeType,\n })\n )\n } else if (route.protocol == Protocol.MIXED) {\n individualTrades.push(\n /// we can change the naming of this function on MixedRouteTrade if needed\n MixedRouteTrade.createUncheckedTrade({\n route: route as MixedRoute<Currency, Currency>,\n inputAmount,\n outputAmount,\n tradeType: trades.tradeType,\n })\n )\n } else {\n throw new Error('UNSUPPORTED_TRADE_PROTOCOL')\n }\n }\n trades = individualTrades\n }\n\n if (!Array.isArray(trades)) {\n trades = [trades]\n }\n\n const numberOfTrades = trades.reduce(\n (numberOfTrades, trade) =>\n numberOfTrades + (trade instanceof V3Trade || trade instanceof MixedRouteTrade ? trade.swaps.length : 1),\n 0\n )\n\n const sampleTrade = trades[0]\n\n // All trades should have the same starting/ending currency and trade type\n invariant(\n trades.every((trade) => trade.inputAmount.currency.equals(sampleTrade.inputAmount.currency)),\n 'TOKEN_IN_DIFF'\n )\n invariant(\n trades.every((trade) => trade.outputAmount.currency.equals(sampleTrade.outputAmount.currency)),\n 'TOKEN_OUT_DIFF'\n )\n invariant(\n trades.every((trade) => trade.tradeType === sampleTrade.tradeType),\n 'TRADE_TYPE_DIFF'\n )\n\n const calldatas: string[] = []\n\n const inputIsNative = sampleTrade.inputAmount.currency.isNative\n const outputIsNative = sampleTrade.outputAmount.currency.isNative\n\n // flag for whether we want to perform an aggregated slippage check\n // 1. when there are >2 exact input trades. this is only a heuristic,\n // as it's still more gas-expensive even in this case, but has benefits\n // in that the reversion probability is lower\n const performAggregatedSlippageCheck = sampleTrade.tradeType === TradeType.EXACT_INPUT && numberOfTrades > 2\n // flag for whether funds should be send first to the router\n // 1. when receiving ETH (which much be unwrapped from WETH)\n // 2. when a fee on the output is being taken\n // 3. when performing swap and add\n // 4. when performing an aggregated slippage check\n const routerMustCustody = outputIsNative || !!options.fee || !!isSwapAndAdd || performAggregatedSlippageCheck\n\n // encode permit if necessary\n if (options.inputTokenPermit) {\n invariant(sampleTrade.inputAmount.currency.isToken, 'NON_TOKEN_PERMIT')\n calldatas.push(SelfPermit.encodePermit(sampleTrade.inputAmount.currency, options.inputTokenPermit))\n }\n\n for (const trade of trades) {\n if (trade instanceof V2Trade) {\n calldatas.push(SwapRouter.encodeV2Swap(trade, options, routerMustCustody, performAggregatedSlippageCheck))\n } else if (trade instanceof V3Trade) {\n for (const calldata of SwapRouter.encodeV3Swap(\n trade,\n options,\n routerMustCustody,\n performAggregatedSlippageCheck\n )) {\n calldatas.push(calldata)\n }\n } else if (trade instanceof MixedRouteTrade) {\n for (const calldata of SwapRouter.encodeMixedRouteSwap(\n trade,\n options,\n routerMustCustody,\n performAggregatedSlippageCheck\n )) {\n calldatas.push(calldata)\n }\n } else {\n throw new Error('Unsupported trade object')\n }\n }\n\n const ZERO_IN: CurrencyAmount<Currency> = CurrencyAmount.fromRawAmount(sampleTrade.inputAmount.currency, 0)\n const ZERO_OUT: CurrencyAmount<Currency> = CurrencyAmount.fromRawAmount(sampleTrade.outputAmount.currency, 0)\n\n const minimumAmountOut: CurrencyAmount<Currency> = trades.reduce(\n (sum, trade) => sum.add(trade.minimumAmountOut(options.slippageTolerance)),\n ZERO_OUT\n )\n\n const quoteAmountOut: CurrencyAmount<Currency> = trades.reduce(\n (sum, trade) => sum.add(trade.outputAmount),\n ZERO_OUT\n )\n\n const totalAmountIn: CurrencyAmount<Currency> = trades.reduce(\n (sum, trade) => sum.add(trade.maximumAmountIn(options.slippageTolerance)),\n ZERO_IN\n )\n\n return {\n calldatas,\n sampleTrade,\n routerMustCustody,\n inputIsNative,\n outputIsNative,\n totalAmountIn,\n minimumAmountOut,\n quoteAmountOut,\n }\n }\n\n /**\n * Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.\n * @param trades to produce call parameters for\n * @param options options for the call parameters\n */\n public static swapCallParameters(\n trades:\n | Trade<Currency, Currency, TradeType>\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n | (\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n )[],\n options: SwapOptions\n ): MethodParameters {\n const {\n calldatas,\n sampleTrade,\n routerMustCustody,\n inputIsNative,\n outputIsNative,\n totalAmountIn,\n minimumAmountOut,\n } = SwapRouter.encodeSwaps(trades, options)\n\n // unwrap or sweep\n if (routerMustCustody) {\n if (outputIsNative) {\n calldatas.push(PaymentsExtended.encodeUnwrapWETH9(minimumAmountOut.quotient, options.recipient, options.fee))\n } else {\n calldatas.push(\n PaymentsExtended.encodeSweepToken(\n sampleTrade.outputAmount.currency.wrapped,\n minimumAmountOut.quotient,\n options.recipient,\n options.fee\n )\n )\n }\n }\n\n // must refund when paying in ETH: either with an uncertain input amount OR if there's a chance of a partial fill.\n // unlike ERC20's, the full ETH value must be sent in the transaction, so the rest must be refunded.\n if (inputIsNative && (sampleTrade.tradeType === TradeType.EXACT_OUTPUT || SwapRouter.riskOfPartialFill(trades))) {\n calldatas.push(Payments.encodeRefundETH())\n }\n\n return {\n calldata: MulticallExtended.encodeMulticall(calldatas, options.deadlineOrPreviousBlockhash),\n value: toHex(inputIsNative ? totalAmountIn.quotient : ZERO),\n }\n }\n\n /**\n * Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.\n * @param trades to produce call parameters for\n * @param options options for the call parameters\n */\n public static swapAndAddCallParameters(\n trades: AnyTradeType,\n options: SwapAndAddOptions,\n position: Position,\n addLiquidityOptions: CondensedAddLiquidityOptions,\n tokenInApprovalType: ApprovalTypes,\n tokenOutApprovalType: ApprovalTypes\n ): MethodParameters {\n const {\n calldatas,\n inputIsNative,\n outputIsNative,\n sampleTrade,\n totalAmountIn: totalAmountSwapped,\n quoteAmountOut,\n minimumAmountOut,\n } = SwapRouter.encodeSwaps(trades, options, true)\n\n // encode output token permit if necessary\n if (options.outputTokenPermit) {\n invariant(quoteAmountOut.currency.isToken, 'NON_TOKEN_PERMIT_OUTPUT')\n calldatas.push(SelfPermit.encodePermit(quoteAmountOut.currency, options.outputTokenPermit))\n }\n\n const chainId = sampleTrade.route.chainId\n const zeroForOne = position.pool.token0.wrapped.address === totalAmountSwapped.currency.wrapped.address\n const { positionAmountIn, positionAmountOut } = SwapRouter.getPositionAmounts(position, zeroForOne)\n\n // if tokens are native they will be converted to WETH9\n const tokenIn = inputIsNative ? WETH9[chainId] : positionAmountIn.currency.wrapped\n const tokenOut = outputIsNative ? WETH9[chainId] : positionAmountOut.currency.wrapped\n\n // if swap output does not make up whole outputTokenBalanceDesired, pull in remaining tokens for adding liquidity\n const amountOutRemaining = positionAmountOut.subtract(quoteAmountOut.wrapped)\n if (amountOutRemaining.greaterThan(CurrencyAmount.fromRawAmount(positionAmountOut.currency, 0))) {\n // if output is native, this means the remaining portion is included as native value in the transaction\n // and must be wrapped. Otherwise, pull in remaining ERC20 token.\n outputIsNative\n ? calldatas.push(PaymentsExtended.encodeWrapETH(amountOutRemaining.quotient))\n : calldatas.push(PaymentsExtended.encodePull(tokenOut, amountOutRemaining.quotient))\n }\n\n // if input is native, convert to WETH9, else pull ERC20 token\n inputIsNative\n ? calldatas.push(PaymentsExtended.encodeWrapETH(positionAmountIn.quotient))\n : calldatas.push(PaymentsExtended.encodePull(tokenIn, positionAmountIn.quotient))\n\n // approve token balances to NFTManager\n if (tokenInApprovalType !== ApprovalTypes.NOT_REQUIRED)\n calldatas.push(ApproveAndCall.encodeApprove(tokenIn, tokenInApprovalType))\n if (tokenOutApprovalType !== ApprovalTypes.NOT_REQUIRED)\n calldatas.push(ApproveAndCall.encodeApprove(tokenOut, tokenOutApprovalType))\n\n // represents a position with token amounts resulting from a swap with maximum slippage\n // hence the minimal amount out possible.\n const minimalPosition = Position.fromAmounts({\n pool: position.pool,\n tickLower: position.tickLower,\n tickUpper: position.tickUpper,\n amount0: zeroForOne ? position.amount0.quotient.toString() : minimumAmountOut.quotient.toString(),\n amount1: zeroForOne ? minimumAmountOut.quotient.toString() : position.amount1.quotient.toString(),\n useFullPrecision: false,\n })\n\n // encode NFTManager add liquidity\n calldatas.push(\n ApproveAndCall.encodeAddLiquidity(position, minimalPosition, addLiquidityOptions, options.slippageTolerance)\n )\n\n // sweep remaining tokens\n inputIsNative\n ? calldatas.push(PaymentsExtended.encodeUnwrapWETH9(ZERO))\n : calldatas.push(PaymentsExtended.encodeSweepToken(tokenIn, ZERO))\n outputIsNative\n ? calldatas.push(PaymentsExtended.encodeUnwrapWETH9(ZERO))\n : calldatas.push(PaymentsExtended.encodeSweepToken(tokenOut, ZERO))\n\n let value: JSBI\n if (inputIsNative) {\n value = totalAmountSwapped.wrapped.add(positionAmountIn.wrapped).quotient\n } else if (outputIsNative) {\n value = amountOutRemaining.quotient\n } else {\n value = ZERO\n }\n\n return {\n calldata: MulticallExtended.encodeMulticall(calldatas, options.deadlineOrPreviousBlockhash),\n value: value.toString(),\n }\n }\n\n // if price impact is very high, there's a chance of hitting max/min prices resulting in a partial fill of the swap\n private static riskOfPartialFill(trades: AnyTradeType): boolean {\n if (Array.isArray(trades)) {\n return trades.some((trade) => {\n return SwapRouter.v3TradeWithHighPriceImpact(trade)\n })\n } else {\n return SwapRouter.v3TradeWithHighPriceImpact(trades)\n }\n }\n\n private static v3TradeWithHighPriceImpact(\n trade:\n | Trade<Currency, Currency, TradeType>\n | V2Trade<Currency, Currency, TradeType>\n | V3Trade<Currency, Currency, TradeType>\n | MixedRouteTrade<Currency, Currency, TradeType>\n ): boolean {\n return !(trade instanceof V2Trade) && trade.priceImpact.greaterThan(REFUND_ETH_PRICE_IMPACT_THRESHOLD)\n }\n\n private static getPositionAmounts(\n position: Position,\n zeroForOne: boolean\n ): {\n positionAmountIn: CurrencyAmount<Currency>\n positionAmountOut: CurrencyAmount<Currency>\n } {\n const { amount0, amount1 } = position.mintAmounts\n const currencyAmount0 = CurrencyAmount.fromRawAmount(position.pool.token0, amount0)\n const currencyAmount1 = CurrencyAmount.fromRawAmount(position.pool.token1, amount1)\n\n const [positionAmountIn, positionAmountOut] = zeroForOne\n ? [currencyAmount0, currencyAmount1]\n : [currencyAmount1, currencyAmount0]\n return { positionAmountIn, positionAmountOut }\n }\n}\n"],"names":["ApprovalTypes","MSG_SENDER","ADDRESS_THIS","ZERO","JSBI","BigInt","ONE","ZERO_PERCENT","Percent","isMint","options","Object","keys","some","k","ApproveAndCall","encodeApproveMax","token","INTERFACE","encodeFunctionData","address","encodeApproveMaxMinusOne","encodeApproveZeroThenMax","encodeApproveZeroThenMaxMinusOne","encodeCallPositionManager","calldatas","length","invariant","encodedMulticall","NonfungiblePositionManager","encodeAddLiquidity","position","minimalPosition","addLiquidityOptions","slippageTolerance","mintAmountsWithSlippage","amount0Min","amount0","amount1Min","amount1","lessThan","quotient","token0","pool","token1","fee","tickLower","tickUpper","toHex","recipient","tokenId","encodeApprove","approvalType","MAX","wrapped","MAX_MINUS_ONE","ZERO_THEN_MAX","ZERO_THEN_MAX_MINUS_ONE","Interface","abi","MulticallExtended","encodeMulticall","validation","Multicall","Array","isArray","startsWith","previousBlockhash","bytes32","match","Error","toLowerCase","validateAndParseBytes32","deadline","encodeFeeBips","multiply","PaymentsExtended","encodeUnwrapWETH9","amountMinimum","feeOptions","Payments","feeBips","feeRecipient","validateAndParseAddress","encodeSweepToken","encodePull","amount","encodeWrapETH","runtime","exports","Op","prototype","hasOwn","hasOwnProperty","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","define","obj","key","value","defineProperty","enumerable","configurable","writable","err","wrap","innerFn","outerFn","self","tryLocsList","generator","create","Generator","context","Context","_invoke","state","method","arg","undefined","done","delegate","delegateResult","maybeInvokeDelegate","ContinueSentinel","sent","_sent","dispatchException","abrupt","record","tryCatch","type","makeInvokeMethod","fn","call","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","this","getProto","getPrototypeOf","NativeIteratorPrototype","values","Gp","defineIteratorMethods","forEach","AsyncIterator","PromiseImpl","previousPromise","callInvokeWithMethodAndArg","resolve","reject","invoke","result","__await","then","unwrapped","error","TypeError","info","resultName","next","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","iterable","iteratorMethod","isNaN","i","doneResult","displayName","isGeneratorFunction","genFun","ctor","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","iter","object","reverse","pop","skipTempReset","prev","charAt","slice","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","catch","thrown","delegateYield","module","regeneratorRuntime","accidentalStrictMode","globalThis","Function","MixedRouteSDK","pools","input","output","chainId","every","wrappedInput","involvesToken","tokenPath","entries","currentInputToken","equals","nextToken","path","_midPrice","price","reduce","nextInput","token0Price","token1Price","Price","denominator","numerator","tradeComparator","a","b","inputAmount","currency","outputAmount","equalTo","swaps","total","cur","route","Protocol","MixedRouteTrade","routes","tradeType","inputCurrency","outputCurrency","numPools","map","poolAddressSet","Set","add","Pool","getAddress","Pair","size","TradeType","EXACT_INPUT","fromRoute","amounts","getOutputAmount","CurrencyAmount","fromFractionalAmount","fromRoutes","populatedRoutes","createUncheckedTrade","constructorArguments","createUncheckedTradeWithMultipleRoutes","minimumAmountOut","amountOut","slippageAdjustedAmountOut","Fraction","invert","fromRawAmount","maximumAmountIn","amountIn","worstExecutionPrice","bestTradeExactIn","currencyAmountIn","currencyOut","currentPools","nextAmountIn","bestTrades","maxNumResults","maxHops","tokenOut","reserve0","reserve1","_context3","isInsufficientInputAmountError","isToken","sortedInsert","poolsExcludingThisPool","concat","_inputAmount","totalInputFromRoutes","_outputAmount","totalOutputFromRoutes","_executionPrice","_priceImpact","spotOutputAmount","midPrice","quote","priceImpact","subtract","divide","RouteV2","v2Route","pairs","V2","_this","V2RouteSDK","RouteV3","v3Route","V3","V3RouteSDK","MixedRoute","mixedRoute","MIXED","Trade","v2Routes","v3Routes","mixedRoutes","routev2","routev3","EXACT_OUTPUT","slippageAdjustedAmountIn","populatedV2Routes","populatedV3Routes","populatedMixedRoutes","v2Trade","V2TradeSDK","V3TradeSDK","v3Trade","MixedRouteTradeSDK","mixedRouteTrade","isNative","sellFeeBps","toNumber","buyFeeBps","postTaxInputAmount","inputTax","preTaxOutputAmount","outputTax","encodeMixedRouteToPath","index","inputToken","types","outputToken","pack","partitionMixedRouteByProtocol","acc","left","right","getOutputOfPools","firstInputToken","REFUND_ETH_PRICE_IMPACT_THRESHOLD","SwapRouter","encodeV2Swap","trade","routerMustCustody","performAggregatedSlippageCheck","encodeV3Swap","singleHop","tokenIn","amountOutMinimum","sqrtPriceLimitX96","amountInMaximum","encodeRouteToPath","encodeMixedRouteSwap","mixedRouteIsAllV3","sections","isLastSectionInRoute","section","newRouteOriginal","newRoute","exactInputParams","encodeSwaps","trades","isSwapAndAdd","swap","protocol","individualTrades","V2Trade","V3Trade","numberOfTrades","sampleTrade","inputIsNative","outputIsNative","inputTokenPermit","SelfPermit","encodePermit","ZERO_IN","ZERO_OUT","sum","quoteAmountOut","totalAmountIn","swapCallParameters","riskOfPartialFill","encodeRefundETH","calldata","deadlineOrPreviousBlockhash","swapAndAddCallParameters","tokenInApprovalType","tokenOutApprovalType","totalAmountSwapped","outputTokenPermit","zeroForOne","getPositionAmounts","positionAmountIn","positionAmountOut","WETH9","amountOutRemaining","greaterThan","NOT_REQUIRED","Position","fromAmounts","toString","useFullPrecision","v3TradeWithHighPriceImpact","mintAmounts","currencyAmount0","currencyAmount1"],"mappings":"8IAgBYA,0sBCbCC,EAAa,6CACbC,EAAe,6CAEfC,EAAOC,EAAKC,OAAO,GACnBC,EAAMF,EAAKC,OAAO,GAKlBE,EAAe,IAAIC,UAAQL,YDaxBM,EAAOC,UACdC,OAAOC,KAAKF,GAASG,MAAK,SAACC,SAAY,cAANA,MAV9Bd,EAAAA,wBAAAA,4DAEVA,iBACAA,qCACAA,qCACAA,yDAQF,IAAsBe,oCAQNC,iBAAP,SAAwBC,UACtBF,EAAeG,UAAUC,mBAAmB,aAAc,CAACF,EAAMG,aAG5DC,yBAAP,SAAgCJ,UAC9BF,EAAeG,UAAUC,mBAAmB,qBAAsB,CAACF,EAAMG,aAGpEE,yBAAP,SAAgCL,UAC9BF,EAAeG,UAAUC,mBAAmB,qBAAsB,CAACF,EAAMG,aAGpEG,iCAAP,SAAwCN,UACtCF,EAAeG,UAAUC,mBAAmB,6BAA8B,CAACF,EAAMG,aAG5EI,0BAAP,SAAiCC,MAC5BA,EAAUC,OAAS,GAA7BC,MAEwB,GAApBF,EAAUC,cACLX,EAAeG,UAAUC,mBAAmB,sBAAuBM,OAEpEG,EAAmBC,6BAA2BX,UAAUC,mBAAmB,YAAa,CAACM,WACxFV,EAAeG,UAAUC,mBAAmB,sBAAuB,CAACS,OAUjEE,mBAAP,SACLC,EACAC,EACAC,EACAC,SAEmDH,EAASI,wBAAwBD,GAArEE,IAATC,QAA8BC,IAATC,eAKvBnC,EAAKoC,SAASR,EAAgBK,QAAQI,SAAUL,KAClDA,EAAaJ,EAAgBK,QAAQI,UAEnCrC,EAAKoC,SAASR,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