UNPKG

@energiswap/sdk-core

Version:

⚒️ An SDK for building applications on top of Energiswap V3

737 lines (717 loc) 32.6 kB
import JSBI from 'jsbi'; import invariant from 'tiny-invariant'; import _Decimal from 'decimal.js-light'; import _Big from 'big.js'; import toFormat from 'toformat'; import { BigNumber } from '@ethersproject/bignumber'; import { getAddress } from '@ethersproject/address'; import { concat, hexZeroPad } from '@ethersproject/bytes'; import { keccak256 } from '@ethersproject/keccak256'; import { toUtf8Bytes } from '@ethersproject/strings'; function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } var ChainId; (function (ChainId) { ChainId[ChainId["ENERGI"] = 39797] = "ENERGI"; ChainId[ChainId["ENERGI_TESTNET"] = 49797] = "ENERGI_TESTNET"; })(ChainId || (ChainId = {})); var SUPPORTED_CHAINS = [ChainId.ENERGI, ChainId.ENERGI_TESTNET]; var NativeCurrencyName; (function (NativeCurrencyName) { NativeCurrencyName["ENERGI"] = "NRG"; })(NativeCurrencyName || (NativeCurrencyName = {})); var _UNI_ADDRESSES, _V2_FACTORY_ADDRESSES, _V2_ROUTER_ADDRESSES, _CHAIN_TO_ADDRESSES_M; var DEFAULT_NETWORKS = [ChainId.ENERGI, ChainId.ENERGI_TESTNET]; function constructSameAddressMap(address, additionalNetworks) { if (additionalNetworks === void 0) { additionalNetworks = []; } return DEFAULT_NETWORKS.concat(additionalNetworks).reduce(function (memo, chainId) { memo[chainId] = address; return memo; }, {}); } var UNI_ADDRESSES = (_UNI_ADDRESSES = {}, _UNI_ADDRESSES[ChainId.ENERGI] = '0x665B3A802979eC24e076c80025bFF33c18eB6007', _UNI_ADDRESSES[ChainId.ENERGI_TESTNET] = '0xDFf7a6F2CDdD46c1a36Ae760fEbc399208e86E0A', _UNI_ADDRESSES); var UNISWAP_NFT_AIRDROP_CLAIM_ADDRESS = '0x8B799381ac40b838BBA4131ffB26197C432AFe78'; /** * @deprecated use V2_FACTORY_ADDRESSES instead */ var V2_FACTORY_ADDRESS = '0xa2dAE9e70D5A08B781DeE134617Cf5E7D23043c2'; var V2_FACTORY_ADDRESSES = (_V2_FACTORY_ADDRESSES = {}, _V2_FACTORY_ADDRESSES[ChainId.ENERGI] = '0xa2dAE9e70D5A08B781DeE134617Cf5E7D23043c2', _V2_FACTORY_ADDRESSES[ChainId.ENERGI_TESTNET] = '0xb1F94d0d737755342a9d0cD84f5eBEAB4c2DaA54', _V2_FACTORY_ADDRESSES); /** * @deprecated use V2_ROUTER_ADDRESSES instead */ var V2_ROUTER_ADDRESS = '0x2D4eB90118f6FBA1191F26Eb39f7FF0573F63C22'; var V2_ROUTER_ADDRESSES = (_V2_ROUTER_ADDRESSES = {}, _V2_ROUTER_ADDRESSES[ChainId.ENERGI] = '0x2D4eB90118f6FBA1191F26Eb39f7FF0573F63C22', _V2_ROUTER_ADDRESSES[ChainId.ENERGI_TESTNET] = '0x07CC883c0B6E45B00E91840dcCdF99D66551Fa81', _V2_ROUTER_ADDRESSES); var DEFAULT_ADDRESSES = { v3CoreFactoryAddress: '0x2BfD24B00413Fd35089cc9E3E6Aa285e4Bd7904d', multicallAddress: '0x51dd6b5596ca240FDe76698785cBFCDCa2E3ddb7', quoterAddress: '0xF20BC258323Df9d9c26Ef1A961FDCC4E8CEb71Bc', v3MigratorAddress: '0x5eeB515207a81dc55C1a29c0f57824D19Bc148B7', nonfungiblePositionManagerAddress: '0x47b4452CA33FEAcaD064eEDC210AF611516756F4' }; var ENERGI_ADDRESSES = /*#__PURE__*/_extends({}, DEFAULT_ADDRESSES, { /**NOTE: IGNORE**/ mixedRouteQuoterV1Address: '0x84E44095eeBfEC7793Cd7d5b57B7e401D7f1cA2E', v4PoolManagerAddress: '0x000000000004444c5dc75cB358380D2e3dE08A90', v4PositionManagerAddress: '0xbd216513d74c8cf14cf4747e6aaa6420ff64ee9e', v4StateView: '0x7ffe42c4a5deea5b0fec41c94c136cf115597227', v4QuoterAddress: '0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203' /**NOTE: IGNORE**/ }); var ENERGI_TESTNET_ADDRESSES = /*#__PURE__*/_extends({}, DEFAULT_ADDRESSES, { /**NOTE: IGNORE**/ mixedRouteQuoterV1Address: '0xBa60b6e6fF25488308789E6e0A65D838be34194e' /**NOTE: IGNORE**/ }); var CHAIN_TO_ADDRESSES_MAP = (_CHAIN_TO_ADDRESSES_M = {}, _CHAIN_TO_ADDRESSES_M[ChainId.ENERGI] = ENERGI_ADDRESSES, _CHAIN_TO_ADDRESSES_M[ChainId.ENERGI_TESTNET] = ENERGI_TESTNET_ADDRESSES, _CHAIN_TO_ADDRESSES_M); /* V3 Contract Addresses */ var V3_CORE_FACTORY_ADDRESSES = /*#__PURE__*/_extends({}, /*#__PURE__*/SUPPORTED_CHAINS.reduce(function (memo, chainId) { memo[chainId] = CHAIN_TO_ADDRESSES_MAP[chainId].v3CoreFactoryAddress; return memo; }, {})); var V3_MIGRATOR_ADDRESSES = /*#__PURE__*/_extends({}, /*#__PURE__*/SUPPORTED_CHAINS.reduce(function (memo, chainId) { var v3MigratorAddress = CHAIN_TO_ADDRESSES_MAP[chainId].v3MigratorAddress; if (v3MigratorAddress) { memo[chainId] = v3MigratorAddress; } return memo; }, {})); var MULTICALL_ADDRESSES = /*#__PURE__*/_extends({}, /*#__PURE__*/SUPPORTED_CHAINS.reduce(function (memo, chainId) { memo[chainId] = CHAIN_TO_ADDRESSES_MAP[chainId].multicallAddress; return memo; }, {})); var QUOTER_ADDRESSES = /*#__PURE__*/_extends({}, /*#__PURE__*/SUPPORTED_CHAINS.reduce(function (memo, chainId) { memo[chainId] = CHAIN_TO_ADDRESSES_MAP[chainId].quoterAddress; return memo; }, {})); var NONFUNGIBLE_POSITION_MANAGER_ADDRESSES = /*#__PURE__*/_extends({}, /*#__PURE__*/SUPPORTED_CHAINS.reduce(function (memo, chainId) { var nonfungiblePositionManagerAddress = CHAIN_TO_ADDRESSES_MAP[chainId].nonfungiblePositionManagerAddress; if (nonfungiblePositionManagerAddress) { memo[chainId] = nonfungiblePositionManagerAddress; } return memo; }, {})); var ENS_REGISTRAR_ADDRESSES = /*#__PURE__*/_extends({}, /*#__PURE__*/constructSameAddressMap('0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e')); var TICK_LENS_ADDRESSES = /*#__PURE__*/_extends({}, /*#__PURE__*/SUPPORTED_CHAINS.reduce(function (memo, chainId) { var tickLensAddress = CHAIN_TO_ADDRESSES_MAP[chainId].tickLensAddress; if (tickLensAddress) { memo[chainId] = tickLensAddress; } return memo; }, {})); var MIXED_ROUTE_QUOTER_V1_ADDRESSES = /*#__PURE__*/SUPPORTED_CHAINS.reduce(function (memo, chainId) { var mixedRouteQuoterV1Address = CHAIN_TO_ADDRESSES_MAP[chainId].mixedRouteQuoterV1Address; if (mixedRouteQuoterV1Address) { memo[chainId] = mixedRouteQuoterV1Address; } return memo; }, {}); var SWAP_ROUTER_02_ADDRESSES = function SWAP_ROUTER_02_ADDRESSES(chainId) { if (SUPPORTED_CHAINS.includes(chainId)) { var _CHAIN_TO_ADDRESSES_M2; var id = chainId; return (_CHAIN_TO_ADDRESSES_M2 = CHAIN_TO_ADDRESSES_MAP[id].swapRouter02Address) != null ? _CHAIN_TO_ADDRESSES_M2 : '0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45'; } return ''; }; var TradeType; (function (TradeType) { TradeType[TradeType["EXACT_INPUT"] = 0] = "EXACT_INPUT"; TradeType[TradeType["EXACT_OUTPUT"] = 1] = "EXACT_OUTPUT"; })(TradeType || (TradeType = {})); var Rounding; (function (Rounding) { Rounding[Rounding["ROUND_DOWN"] = 0] = "ROUND_DOWN"; Rounding[Rounding["ROUND_HALF_UP"] = 1] = "ROUND_HALF_UP"; Rounding[Rounding["ROUND_UP"] = 2] = "ROUND_UP"; })(Rounding || (Rounding = {})); var MaxUint256 = /*#__PURE__*/JSBI.BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); var _toSignificantRoundin, _toFixedRounding; var Decimal = /*#__PURE__*/toFormat(_Decimal); var Big = /*#__PURE__*/toFormat(_Big); var toSignificantRounding = (_toSignificantRoundin = {}, _toSignificantRoundin[Rounding.ROUND_DOWN] = Decimal.ROUND_DOWN, _toSignificantRoundin[Rounding.ROUND_HALF_UP] = Decimal.ROUND_HALF_UP, _toSignificantRoundin[Rounding.ROUND_UP] = Decimal.ROUND_UP, _toSignificantRoundin); var toFixedRounding = (_toFixedRounding = {}, _toFixedRounding[Rounding.ROUND_DOWN] = 0, _toFixedRounding[Rounding.ROUND_HALF_UP] = 1, _toFixedRounding[Rounding.ROUND_UP] = 3, _toFixedRounding); var Fraction = /*#__PURE__*/function () { function Fraction(numerator, denominator) { if (denominator === void 0) { denominator = JSBI.BigInt(1); } this.numerator = JSBI.BigInt(numerator); this.denominator = JSBI.BigInt(denominator); } Fraction.tryParseFraction = function tryParseFraction(fractionish) { if (fractionish instanceof JSBI || typeof fractionish === 'number' || typeof fractionish === 'string') return new Fraction(fractionish); if ('numerator' in fractionish && 'denominator' in fractionish) return fractionish; throw new Error('Could not parse fraction'); } // performs floor division ; var _proto = Fraction.prototype; _proto.invert = function invert() { return new Fraction(this.denominator, this.numerator); }; _proto.add = function add(other) { var otherParsed = Fraction.tryParseFraction(other); if (JSBI.equal(this.denominator, otherParsed.denominator)) { return new Fraction(JSBI.add(this.numerator, otherParsed.numerator), this.denominator); } return new Fraction(JSBI.add(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator)), JSBI.multiply(this.denominator, otherParsed.denominator)); }; _proto.subtract = function subtract(other) { var otherParsed = Fraction.tryParseFraction(other); if (JSBI.equal(this.denominator, otherParsed.denominator)) { return new Fraction(JSBI.subtract(this.numerator, otherParsed.numerator), this.denominator); } return new Fraction(JSBI.subtract(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator)), JSBI.multiply(this.denominator, otherParsed.denominator)); }; _proto.lessThan = function lessThan(other) { var otherParsed = Fraction.tryParseFraction(other); return JSBI.lessThan(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator)); }; _proto.equalTo = function equalTo(other) { var otherParsed = Fraction.tryParseFraction(other); return JSBI.equal(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator)); }; _proto.greaterThan = function greaterThan(other) { var otherParsed = Fraction.tryParseFraction(other); return JSBI.greaterThan(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator)); }; _proto.multiply = function multiply(other) { var otherParsed = Fraction.tryParseFraction(other); return new Fraction(JSBI.multiply(this.numerator, otherParsed.numerator), JSBI.multiply(this.denominator, otherParsed.denominator)); }; _proto.divide = function divide(other) { var otherParsed = Fraction.tryParseFraction(other); return new Fraction(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(this.denominator, otherParsed.numerator)); }; _proto.toSignificant = function toSignificant(significantDigits, format, rounding) { if (format === void 0) { format = { groupSeparator: '' }; } if (rounding === void 0) { rounding = Rounding.ROUND_HALF_UP; } !Number.isInteger(significantDigits) ? process.env.NODE_ENV !== "production" ? invariant(false, significantDigits + " is not an integer.") : invariant(false) : void 0; !(significantDigits > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, significantDigits + " is not positive.") : invariant(false) : void 0; Decimal.set({ precision: significantDigits + 1, rounding: toSignificantRounding[rounding] }); var quotient = new Decimal(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(significantDigits); return quotient.toFormat(quotient.decimalPlaces(), format); }; _proto.toFixed = function toFixed(decimalPlaces, format, rounding) { if (format === void 0) { format = { groupSeparator: '' }; } if (rounding === void 0) { rounding = Rounding.ROUND_HALF_UP; } !Number.isInteger(decimalPlaces) ? process.env.NODE_ENV !== "production" ? invariant(false, decimalPlaces + " is not an integer.") : invariant(false) : void 0; !(decimalPlaces >= 0) ? process.env.NODE_ENV !== "production" ? invariant(false, decimalPlaces + " is negative.") : invariant(false) : void 0; Big.DP = decimalPlaces; Big.RM = toFixedRounding[rounding]; return new Big(this.numerator.toString()).div(this.denominator.toString()).toFormat(decimalPlaces, format); } /** * Helper method for converting any super class back to a fraction */; return _createClass(Fraction, [{ key: "quotient", get: function get() { return JSBI.divide(this.numerator, this.denominator); } // remainder after floor division }, { key: "remainder", get: function get() { return new Fraction(JSBI.remainder(this.numerator, this.denominator), this.denominator); } }, { key: "asFraction", get: function get() { return new Fraction(this.numerator, this.denominator); } }]); }(); var Big$1 = /*#__PURE__*/toFormat(_Big); var CurrencyAmount = /*#__PURE__*/function (_Fraction) { function CurrencyAmount(currency, numerator, denominator) { var _this; _this = _Fraction.call(this, numerator, denominator) || this; !JSBI.lessThanOrEqual(_this.quotient, MaxUint256) ? process.env.NODE_ENV !== "production" ? invariant(false, 'AMOUNT') : invariant(false) : void 0; _this.currency = currency; _this.decimalScale = JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(currency.decimals)); return _this; } /** * Returns a new currency amount instance from the unitless amount of token, i.e. the raw amount * @param currency the currency in the amount * @param rawAmount the raw token or ether amount */ _inheritsLoose(CurrencyAmount, _Fraction); CurrencyAmount.fromRawAmount = function fromRawAmount(currency, rawAmount) { return new CurrencyAmount(currency, rawAmount); } /** * Construct a currency amount with a denominator that is not equal to 1 * @param currency the currency * @param numerator the numerator of the fractional token amount * @param denominator the denominator of the fractional token amount */; CurrencyAmount.fromFractionalAmount = function fromFractionalAmount(currency, numerator, denominator) { return new CurrencyAmount(currency, numerator, denominator); }; var _proto = CurrencyAmount.prototype; _proto.add = function add(other) { !this.currency.equals(other.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CURRENCY') : invariant(false) : void 0; var added = _Fraction.prototype.add.call(this, other); return CurrencyAmount.fromFractionalAmount(this.currency, added.numerator, added.denominator); }; _proto.subtract = function subtract(other) { !this.currency.equals(other.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CURRENCY') : invariant(false) : void 0; var subtracted = _Fraction.prototype.subtract.call(this, other); return CurrencyAmount.fromFractionalAmount(this.currency, subtracted.numerator, subtracted.denominator); }; _proto.multiply = function multiply(other) { var multiplied = _Fraction.prototype.multiply.call(this, other); return CurrencyAmount.fromFractionalAmount(this.currency, multiplied.numerator, multiplied.denominator); }; _proto.divide = function divide(other) { var divided = _Fraction.prototype.divide.call(this, other); return CurrencyAmount.fromFractionalAmount(this.currency, divided.numerator, divided.denominator); }; _proto.toSignificant = function toSignificant(significantDigits, format, rounding) { if (significantDigits === void 0) { significantDigits = 6; } if (rounding === void 0) { rounding = Rounding.ROUND_DOWN; } return _Fraction.prototype.divide.call(this, this.decimalScale).toSignificant(significantDigits, format, rounding); }; _proto.toFixed = function toFixed(decimalPlaces, format, rounding) { if (decimalPlaces === void 0) { decimalPlaces = this.currency.decimals; } if (rounding === void 0) { rounding = Rounding.ROUND_DOWN; } !(decimalPlaces <= this.currency.decimals) ? process.env.NODE_ENV !== "production" ? invariant(false, 'DECIMALS') : invariant(false) : void 0; return _Fraction.prototype.divide.call(this, this.decimalScale).toFixed(decimalPlaces, format, rounding); }; _proto.toExact = function toExact(format) { if (format === void 0) { format = { groupSeparator: '' }; } Big$1.DP = this.currency.decimals; return new Big$1(this.quotient.toString()).div(this.decimalScale.toString()).toFormat(format); }; return _createClass(CurrencyAmount, [{ key: "wrapped", get: function get() { if (this.currency.isToken) return this; return CurrencyAmount.fromFractionalAmount(this.currency.wrapped, this.numerator, this.denominator); } }]); }(Fraction); var ONE_HUNDRED = /*#__PURE__*/new Fraction(/*#__PURE__*/JSBI.BigInt(100)); /** * Converts a fraction to a percent * @param fraction the fraction to convert */ function toPercent(fraction) { return new Percent(fraction.numerator, fraction.denominator); } var Percent = /*#__PURE__*/function (_Fraction) { function Percent() { var _this; _this = _Fraction.apply(this, arguments) || this; /** * This boolean prevents a fraction from being interpreted as a Percent */ _this.isPercent = true; return _this; } _inheritsLoose(Percent, _Fraction); var _proto = Percent.prototype; _proto.add = function add(other) { return toPercent(_Fraction.prototype.add.call(this, other)); }; _proto.subtract = function subtract(other) { return toPercent(_Fraction.prototype.subtract.call(this, other)); }; _proto.multiply = function multiply(other) { return toPercent(_Fraction.prototype.multiply.call(this, other)); }; _proto.divide = function divide(other) { return toPercent(_Fraction.prototype.divide.call(this, other)); }; _proto.toSignificant = function toSignificant(significantDigits, format, rounding) { if (significantDigits === void 0) { significantDigits = 5; } return _Fraction.prototype.multiply.call(this, ONE_HUNDRED).toSignificant(significantDigits, format, rounding); }; _proto.toFixed = function toFixed(decimalPlaces, format, rounding) { if (decimalPlaces === void 0) { decimalPlaces = 2; } return _Fraction.prototype.multiply.call(this, ONE_HUNDRED).toFixed(decimalPlaces, format, rounding); }; return Percent; }(Fraction); var Price = /*#__PURE__*/function (_Fraction) { /** * Construct a price, either with the base and quote currency amount, or the * @param args */ function Price() { var _this; var baseCurrency, quoteCurrency, denominator, numerator; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length === 4) { baseCurrency = args[0]; quoteCurrency = args[1]; denominator = args[2]; numerator = args[3]; } else { var result = args[0].quoteAmount.divide(args[0].baseAmount); var _ref = [args[0].baseAmount.currency, args[0].quoteAmount.currency, result.denominator, result.numerator]; baseCurrency = _ref[0]; quoteCurrency = _ref[1]; denominator = _ref[2]; numerator = _ref[3]; } _this = _Fraction.call(this, numerator, denominator) || this; _this.baseCurrency = baseCurrency; _this.quoteCurrency = quoteCurrency; _this.scalar = new Fraction(JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(baseCurrency.decimals)), JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(quoteCurrency.decimals))); return _this; } /** * Flip the price, switching the base and quote currency */ _inheritsLoose(Price, _Fraction); var _proto = Price.prototype; _proto.invert = function invert() { return new Price(this.quoteCurrency, this.baseCurrency, this.numerator, this.denominator); } /** * Multiply the price by another price, returning a new price. The other price must have the same base currency as this price's quote currency * @param other the other price */; _proto.multiply = function multiply(other) { !this.quoteCurrency.equals(other.baseCurrency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0; var fraction = _Fraction.prototype.multiply.call(this, other); return new Price(this.baseCurrency, other.quoteCurrency, fraction.denominator, fraction.numerator); } /** * Return the amount of quote currency corresponding to a given amount of the base currency * @param currencyAmount the amount of base currency to quote against the price */; _proto.quote = function quote(currencyAmount) { !currencyAmount.currency.equals(this.baseCurrency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0; var result = _Fraction.prototype.multiply.call(this, currencyAmount); return CurrencyAmount.fromFractionalAmount(this.quoteCurrency, result.numerator, result.denominator); } /** * Get the value scaled by decimals for formatting * @private */; _proto.toSignificant = function toSignificant(significantDigits, format, rounding) { if (significantDigits === void 0) { significantDigits = 6; } return this.adjustedForDecimals.toSignificant(significantDigits, format, rounding); }; _proto.toFixed = function toFixed(decimalPlaces, format, rounding) { if (decimalPlaces === void 0) { decimalPlaces = 4; } return this.adjustedForDecimals.toFixed(decimalPlaces, format, rounding); }; return _createClass(Price, [{ key: "adjustedForDecimals", get: function get() { return _Fraction.prototype.multiply.call(this, this.scalar); } }]); }(Fraction); /** * A currency is any fungible financial instrument, including Ether, all ERC20 tokens, and other chain-native currencies */ var BaseCurrency = /** * Constructs an instance of the base class `BaseCurrency`. * @param chainId the chain ID on which this currency resides * @param decimals decimals of the currency * @param symbol symbol of the currency * @param name of the currency */ function BaseCurrency(chainId, decimals, symbol, name) { !Number.isSafeInteger(chainId) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_ID') : invariant(false) : void 0; !(decimals >= 0 && decimals < 255 && Number.isInteger(decimals)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'DECIMALS') : invariant(false) : void 0; this.chainId = chainId; this.decimals = decimals; this.symbol = symbol; this.name = name; }; /** * Represents the native currency of the chain on which it resides, e.g. */ var NativeCurrency = /*#__PURE__*/function (_BaseCurrency) { function NativeCurrency() { var _this; _this = _BaseCurrency.apply(this, arguments) || this; _this.isNative = true; _this.isToken = false; return _this; } _inheritsLoose(NativeCurrency, _BaseCurrency); return NativeCurrency; }(BaseCurrency); /** * Validates an address and returns the parsed (checksummed) version of that address * @param address the unchecksummed hex address */ function validateAndParseAddress(address) { try { return getAddress(address); } catch (error) { throw new Error(address + " is not a valid address."); } } // Checks a string starts with 0x, is 42 characters long and contains only hex characters after 0x var startsWith0xLen42HexRegex = /^0x[0-9a-fA-F]{40}$/; /** * Checks if an address is valid by checking 0x prefix, length === 42 and hex encoding. * @param address the unchecksummed hex address */ function checkValidAddress(address) { if (startsWith0xLen42HexRegex.test(address)) { return address; } throw new Error(address + " is not a valid address."); } /** * Represents an ERC20 token with a unique address and some metadata. */ var Token = /*#__PURE__*/function (_BaseCurrency) { /** * * @param chainId {@link BaseCurrency#chainId} * @param address The contract address on the chain on which this token lives * @param decimals {@link BaseCurrency#decimals} * @param symbol {@link BaseCurrency#symbol} * @param name {@link BaseCurrency#name} * @param bypassChecksum If true it only checks for length === 42, startsWith 0x and contains only hex characters * @param buyFeeBps Buy fee tax for FOT tokens, in basis points * @param sellFeeBps Sell fee tax for FOT tokens, in basis points */ function Token(chainId, address, decimals, symbol, name, bypassChecksum, buyFeeBps, sellFeeBps) { var _this; _this = _BaseCurrency.call(this, chainId, decimals, symbol, name) || this; _this.isNative = false; _this.isToken = true; if (bypassChecksum) { _this.address = checkValidAddress(address); } else { _this.address = validateAndParseAddress(address); } if (buyFeeBps) { !buyFeeBps.gte(BigNumber.from(0)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'NON-NEGATIVE FOT FEES') : invariant(false) : void 0; } if (sellFeeBps) { !sellFeeBps.gte(BigNumber.from(0)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'NON-NEGATIVE FOT FEES') : invariant(false) : void 0; } _this.buyFeeBps = buyFeeBps; _this.sellFeeBps = sellFeeBps; return _this; } /** * Returns true if the two tokens are equivalent, i.e. have the same chainId and address. * @param other other token to compare */ _inheritsLoose(Token, _BaseCurrency); var _proto = Token.prototype; _proto.equals = function equals(other) { return other.isToken && this.chainId === other.chainId && this.address.toLowerCase() === other.address.toLowerCase(); } /** * Returns true if the address of this token sorts before the address of the other token * @param other other token to compare * @throws if the tokens have the same address * @throws if the tokens are on different chains */; _proto.sortsBefore = function sortsBefore(other) { !(this.chainId === other.chainId) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_IDS') : invariant(false) : void 0; !(this.address.toLowerCase() !== other.address.toLowerCase()) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ADDRESSES') : invariant(false) : void 0; return this.address.toLowerCase() < other.address.toLowerCase(); } /** * Return this token, which does not need to be wrapped */; return _createClass(Token, [{ key: "wrapped", get: function get() { return this; } }]); }(BaseCurrency); /** * Known WETH9 implementation addresses, used in our implementation of Ether#wrapped */ var WETH9 = { 39797: /*#__PURE__*/new Token(39797, '0xA55F26319462355474A9F2c8790860776a329aA4', 18, 'WNRG', 'Wrapped Energi'), 49797: /*#__PURE__*/new Token(49797, '0x184F7b12f29d675f34ff816528ADBfd0E0501Ad4', 18, 'WNRG', 'Wrapped Energi') }; var Ether = /*#__PURE__*/function (_NativeCurrency) { function Ether(chainId) { return _NativeCurrency.call(this, chainId, 18, 'NRG', 'Energi') || this; } _inheritsLoose(Ether, _NativeCurrency); Ether.onChain = function onChain(chainId) { var _this$_etherCache$cha; return (_this$_etherCache$cha = this._etherCache[chainId]) != null ? _this$_etherCache$cha : this._etherCache[chainId] = new Ether(chainId); }; var _proto = Ether.prototype; _proto.equals = function equals(other) { return other.isNative && other.chainId === this.chainId; }; return _createClass(Ether, [{ key: "wrapped", get: function get() { var weth9 = WETH9[this.chainId]; !!!weth9 ? process.env.NODE_ENV !== "production" ? invariant(false, 'WRAPPED') : invariant(false) : void 0; return weth9; } }]); }(NativeCurrency); Ether._etherCache = {}; /** * Returns the percent difference between the mid price and the execution price, i.e. price impact. * @param midPrice mid price before the trade * @param inputAmount the input amount of the trade * @param outputAmount the output amount of the trade */ function computePriceImpact(midPrice, inputAmount, outputAmount) { var quotedOutputAmount = midPrice.quote(inputAmount); // calculate price impact := (exactQuote - outputAmount) / exactQuote var priceImpact = quotedOutputAmount.subtract(outputAmount).divide(quotedOutputAmount); return new Percent(priceImpact.numerator, priceImpact.denominator); } function computeZksyncCreate2Address(sender, bytecodeHash, salt, input) { if (input === void 0) { input = '0x'; } var prefix = keccak256(toUtf8Bytes('zksyncCreate2')); var inputHash = keccak256(input); var addressBytes = keccak256(concat([prefix, hexZeroPad(sender, 32), salt, bytecodeHash, inputHash])).slice(26); return getAddress(addressBytes); } // given an array of items sorted by `comparator`, insert an item into its sort index and constrain the size to // `maxSize` by removing the last item function sortedInsert(items, add, maxSize, comparator) { !(maxSize > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_SIZE_ZERO') : invariant(false) : void 0; // this is an invariant because the interface cannot return multiple removed items if items.length exceeds maxSize !(items.length <= maxSize) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ITEMS_SIZE') : invariant(false) : void 0; // short circuit first item add if (items.length === 0) { items.push(add); return null; } else { var isFull = items.length === maxSize; // short circuit if full and the additional item does not come before the last item if (isFull && comparator(items[items.length - 1], add) <= 0) { return add; } var lo = 0, hi = items.length; while (lo < hi) { var mid = lo + hi >>> 1; if (comparator(items[mid], add) <= 0) { lo = mid + 1; } else { hi = mid; } } items.splice(lo, 0, add); return isFull ? items.pop() : null; } } var MAX_SAFE_INTEGER = /*#__PURE__*/JSBI.BigInt(Number.MAX_SAFE_INTEGER); var ZERO = /*#__PURE__*/JSBI.BigInt(0); var ONE = /*#__PURE__*/JSBI.BigInt(1); var TWO = /*#__PURE__*/JSBI.BigInt(2); /** * Computes floor(sqrt(value)) * @param value the value for which to compute the square root, rounded down */ function sqrt(value) { !JSBI.greaterThanOrEqual(value, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'NEGATIVE') : invariant(false) : void 0; // rely on built in sqrt if possible if (JSBI.lessThan(value, MAX_SAFE_INTEGER)) { return JSBI.BigInt(Math.floor(Math.sqrt(JSBI.toNumber(value)))); } var z; var x; z = value; x = JSBI.add(JSBI.divide(value, TWO), ONE); while (JSBI.lessThan(x, z)) { z = x; x = JSBI.divide(JSBI.add(JSBI.divide(value, x), x), TWO); } return z; } export { CHAIN_TO_ADDRESSES_MAP, ChainId, CurrencyAmount, ENS_REGISTRAR_ADDRESSES, Ether, Fraction, MIXED_ROUTE_QUOTER_V1_ADDRESSES, MULTICALL_ADDRESSES, MaxUint256, NONFUNGIBLE_POSITION_MANAGER_ADDRESSES, NativeCurrency, NativeCurrencyName, Percent, Price, QUOTER_ADDRESSES, Rounding, SUPPORTED_CHAINS, SWAP_ROUTER_02_ADDRESSES, TICK_LENS_ADDRESSES, Token, TradeType, UNISWAP_NFT_AIRDROP_CLAIM_ADDRESS, UNI_ADDRESSES, V2_FACTORY_ADDRESS, V2_FACTORY_ADDRESSES, V2_ROUTER_ADDRESS, V2_ROUTER_ADDRESSES, V3_CORE_FACTORY_ADDRESSES, V3_MIGRATOR_ADDRESSES, WETH9, computePriceImpact, computeZksyncCreate2Address, sortedInsert, sqrt, validateAndParseAddress }; //# sourceMappingURL=sdk-core.esm.js.map