hermes-v2-sdk
Version:
⚒️ An SDK for building applications on top of Hermes V2
13,681 lines • 429 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var maiaCoreSdk = require('maia-core-sdk');
var JSBI = _interopDefault(require('jsbi'));
var abi = require('@ethersproject/abi');
var invariant = _interopDefault(require('tiny-invariant'));
var bignumber = require('@ethersproject/bignumber');
var bignumber_js = require('bignumber.js');
var constants = require('@ethersproject/constants');
var address = require('@ethersproject/address');
var cloneDeep = _interopDefault(require('lodash.clonedeep'));
var IMulticall = _interopDefault(require('@uniswap/v3-periphery/artifacts/contracts/interfaces/IMulticall.sol/IMulticall.json'));
var INonfungiblePositionManager = _interopDefault(require('@uniswap/v3-periphery/artifacts/contracts/NonfungiblePositionManager.sol/NonfungiblePositionManager.json'));
var IPeripheryPaymentsWithFee = _interopDefault(require('@uniswap/v3-periphery/artifacts/contracts/interfaces/IPeripheryPaymentsWithFee.sol/IPeripheryPaymentsWithFee.json'));
var solidity = require('@ethersproject/solidity');
var ISelfPermit = _interopDefault(require('@uniswap/v3-periphery/artifacts/contracts/interfaces/ISelfPermit.sol/ISelfPermit.json'));
var IQuoterV2 = _interopDefault(require('@uniswap/swap-router-contracts/artifacts/contracts/lens/QuoterV2.sol/QuoterV2.json'));
var IQuoter = _interopDefault(require('@uniswap/v3-periphery/artifacts/contracts/lens/Quoter.sol/Quoter.json'));
var IUniswapV3Staker = _interopDefault(require('@uniswap/v3-staker/artifacts/contracts/UniswapV3Staker.sol/UniswapV3Staker.json'));
var ISwapRouter = _interopDefault(require('@uniswap/v3-periphery/artifacts/contracts/SwapRouter.sol/SwapRouter.json'));
var _TICK_SPACINGS;
var FACTORY_ADDRESS = '0x1F98431c8aD98523631AE4a59f267346ea31F984';
var BALANCER_VAULT_ADDRESS = '0xBA12222222228d8Ba445958a75a0704d566BF2C8';
var ADDRESS_ZERO = maiaCoreSdk.ZERO_ADDRESS;
var MAX_RANGE = /*#__PURE__*/Math.pow(2, 256);
var TICK_INCREMENT = 1.0001;
var YEAR = 31536000;
var POOL_INIT_CODE_HASH = '0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54';
(function (FeeAmount) {
FeeAmount[FeeAmount["LOWEST"] = 100] = "LOWEST";
FeeAmount[FeeAmount["LOW"] = 500] = "LOW";
FeeAmount[FeeAmount["MEDIUM"] = 3000] = "MEDIUM";
FeeAmount[FeeAmount["HIGH"] = 10000] = "HIGH";
})(exports.FeeAmount || (exports.FeeAmount = {}));
/**
* The default factory tick spacings by fee amount.
*/
var TICK_SPACINGS = (_TICK_SPACINGS = {}, _TICK_SPACINGS[exports.FeeAmount.LOWEST] = 1, _TICK_SPACINGS[exports.FeeAmount.LOW] = 10, _TICK_SPACINGS[exports.FeeAmount.MEDIUM] = 60, _TICK_SPACINGS[exports.FeeAmount.HIGH] = 200, _TICK_SPACINGS);
(function (TradeType) {
TradeType[TradeType["EXACT_INPUT"] = 0] = "EXACT_INPUT";
TradeType[TradeType["EXACT_OUTPUT"] = 1] = "EXACT_OUTPUT";
})(exports.TradeType || (exports.TradeType = {}));
(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";
})(exports.Rounding || (exports.Rounding = {}));
// used in liquidity amount math.
var Q96 = /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(96));
var Q192 = /*#__PURE__*/JSBI.exponentiate(Q96, /*#__PURE__*/JSBI.BigInt(2));
var MINIMUM_LIQUIDITY = /*#__PURE__*/JSBI.BigInt(1000);
var bHermes = [
{
type: "constructor",
inputs: [
{
name: "_hermes",
type: "address",
internalType: "contract ERC20"
},
{
name: "_owner",
type: "address",
internalType: "address"
},
{
name: "_flywheelBooster",
type: "address",
internalType: "address"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "DOMAIN_SEPARATOR",
inputs: [
],
outputs: [
{
name: "",
type: "bytes32",
internalType: "bytes32"
}
],
stateMutability: "view"
},
{
type: "function",
name: "allowance",
inputs: [
{
name: "",
type: "address",
internalType: "address"
},
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "approve",
inputs: [
{
name: "spender",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "asset",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "contract ERC20"
}
],
stateMutability: "view"
},
{
type: "function",
name: "balanceOf",
inputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "claimBoost",
inputs: [
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "claimGovernance",
inputs: [
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "claimMultiple",
inputs: [
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "claimMultipleAmounts",
inputs: [
{
name: "weight",
type: "uint256",
internalType: "uint256"
},
{
name: "boost",
type: "uint256",
internalType: "uint256"
},
{
name: "_governance",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "claimOutstanding",
inputs: [
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "claimWeight",
inputs: [
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "convertToAssets",
inputs: [
{
name: "shares",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "convertToShares",
inputs: [
{
name: "assets",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "decimals",
inputs: [
],
outputs: [
{
name: "",
type: "uint8",
internalType: "uint8"
}
],
stateMutability: "view"
},
{
type: "function",
name: "deposit",
inputs: [
{
name: "assets",
type: "uint256",
internalType: "uint256"
},
{
name: "receiver",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "shares",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "forfeitBoost",
inputs: [
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "forfeitGovernance",
inputs: [
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "forfeitMultiple",
inputs: [
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "forfeitMultipleAmounts",
inputs: [
{
name: "weight",
type: "uint256",
internalType: "uint256"
},
{
name: "boost",
type: "uint256",
internalType: "uint256"
},
{
name: "_governance",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "forfeitOutstanding",
inputs: [
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "forfeitWeight",
inputs: [
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "gaugeBoost",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "contract bHermesBoost"
}
],
stateMutability: "view"
},
{
type: "function",
name: "gaugeWeight",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "contract bHermesGauges"
}
],
stateMutability: "view"
},
{
type: "function",
name: "governance",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "contract bHermesVotes"
}
],
stateMutability: "view"
},
{
type: "function",
name: "maxDeposit",
inputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "maxMint",
inputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "maxRedeem",
inputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "pure"
},
{
type: "function",
name: "maxWithdraw",
inputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "pure"
},
{
type: "function",
name: "mint",
inputs: [
{
name: "shares",
type: "uint256",
internalType: "uint256"
},
{
name: "receiver",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "assets",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "name",
inputs: [
],
outputs: [
{
name: "",
type: "string",
internalType: "string"
}
],
stateMutability: "view"
},
{
type: "function",
name: "nonces",
inputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "permit",
inputs: [
{
name: "owner",
type: "address",
internalType: "address"
},
{
name: "spender",
type: "address",
internalType: "address"
},
{
name: "value",
type: "uint256",
internalType: "uint256"
},
{
name: "deadline",
type: "uint256",
internalType: "uint256"
},
{
name: "v",
type: "uint8",
internalType: "uint8"
},
{
name: "r",
type: "bytes32",
internalType: "bytes32"
},
{
name: "s",
type: "bytes32",
internalType: "bytes32"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "previewDeposit",
inputs: [
{
name: "assets",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "previewMint",
inputs: [
{
name: "shares",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "previewRedeem",
inputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "pure"
},
{
type: "function",
name: "previewWithdraw",
inputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "pure"
},
{
type: "function",
name: "redeem",
inputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
},
{
name: "",
type: "address",
internalType: "address"
},
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "pure"
},
{
type: "function",
name: "symbol",
inputs: [
],
outputs: [
{
name: "",
type: "string",
internalType: "string"
}
],
stateMutability: "view"
},
{
type: "function",
name: "totalAssets",
inputs: [
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "totalSupply",
inputs: [
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "transfer",
inputs: [
{
name: "to",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "transferFrom",
inputs: [
{
name: "from",
type: "address",
internalType: "address"
},
{
name: "to",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "userClaimedBoost",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "claimedBoost",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "userClaimedGovernance",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "claimedGovernance",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "userClaimedWeight",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "claimedWeight",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "withdraw",
inputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
},
{
name: "",
type: "address",
internalType: "address"
},
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "pure"
},
{
type: "event",
name: "Approval",
inputs: [
{
name: "owner",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "spender",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: false,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "ClaimBoost",
inputs: [
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "ClaimGovernance",
inputs: [
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "ClaimWeight",
inputs: [
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "Deposit",
inputs: [
{
name: "caller",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "owner",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "assets",
type: "uint256",
indexed: true,
internalType: "uint256"
},
{
name: "shares",
type: "uint256",
indexed: false,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "ForfeitBoost",
inputs: [
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "ForfeitGovernance",
inputs: [
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "ForfeitWeight",
inputs: [
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "Transfer",
inputs: [
{
name: "from",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "to",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: false,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "Withdraw",
inputs: [
{
name: "caller",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "receiver",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "owner",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "assets",
type: "uint256",
indexed: false,
internalType: "uint256"
},
{
name: "shares",
type: "uint256",
indexed: false,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "error",
name: "DepositOnly",
inputs: [
]
},
{
type: "error",
name: "InsufficientShares",
inputs: [
]
},
{
type: "error",
name: "InsufficientUnderlying",
inputs: [
]
}
];
/**
* @title BHermes class
* @notice Provides a set of function to encode calldata for the different bHermes contract interactions.
* @author MaiaDAO
*/
var BHermes = /*#__PURE__*/function () {
/* eslint-disable @typescript-eslint/no-empty-function */
function BHermes() {}
/**
* Encodes the contract interaction calldata to burn $Hermes in exchange for $bHermes.
* @param amount amount of hermes that the user wants to burn.
* @param receiver receiver address of the burnt hermes.
* @returns the encoded calldata for the burn action.
*/
BHermes.encodeBurnCalldata = function encodeBurnCalldata(_ref) {
var amount = _ref.amount,
receiver = _ref.receiver;
// Check if the burn amount and receiver address is valid.
!(JSBI.BigInt(amount) >= maiaCoreSdk.ZERO) ? invariant(false, "Hermes amount can't be negative") : void 0;
!receiver ? invariant(false, 'Invalid receiver address') : void 0;
!(receiver !== maiaCoreSdk.ZERO_ADDRESS) ? invariant(false, 'Invalid receiver address') : void 0;
// Encode the burn action.
return BHermes.INTERFACE.encodeFunctionData('deposit', [amount.toString(), receiver]);
}
/**
* Encodes the contract interaction calldata to claim outstanding rewards.
* @returns the encoded calldata for the claimOutstanding action.
*/;
BHermes.encodeClaimOutstandingCalldata = function encodeClaimOutstandingCalldata() {
// Encode the claimOutstanding action.
return BHermes.INTERFACE.encodeFunctionData('claimOutstanding');
}
/**
* Encodes the contract interaction calldata to forfeit outstanding rewards.
* @returns the encoded calldata for the forfeitOutstanding action.
*/;
BHermes.encodeForfeitOutstandingCalldata = function encodeForfeitOutstandingCalldata() {
// Encode the forfeitOutstanding action.
return BHermes.INTERFACE.encodeFunctionData('forfeitOutstanding');
}
/**
* Encodes the contract interaction calldata to forfeit a certain amount of all types of rewards.
* @param amount amount of each utility token to forfeit.
* @returns the encoded calldata for the forfeitMultiple action.
*/;
BHermes.encodeForfeitMultipleCalldata = function encodeForfeitMultipleCalldata(_ref2) {
var amount = _ref2.amount;
// Check if the forfeit amount is valid.
!(JSBI.BigInt(amount) >= maiaCoreSdk.ZERO) ? invariant(false, "Forfeit amount can't be negative") : void 0;
// Encode the forfeitMultiple action.
return BHermes.INTERFACE.encodeFunctionData('forfeitMultiple', [amount.toString()]);
}
/**
* Encodes the contract interaction calldata to claim a certain amount of all types of rewards.
* @param weight amount of weight to claim.
* @param boost amount of boost to claim.
* @param governance amount of governance to claim.
* @returns the encoded calldata for the claimMultiple action.
*/;
BHermes.encodeForfeitMultipleAmoutnsCalldata = function encodeForfeitMultipleAmoutnsCalldata(_ref3) {
var weight = _ref3.weight,
boost = _ref3.boost,
governance = _ref3.governance;
// Check if the forfeit amount is valid.
!(JSBI.BigInt(weight) >= maiaCoreSdk.ZERO) ? invariant(false, "Forfeit amount can't be negative") : void 0;
!(JSBI.BigInt(boost) >= maiaCoreSdk.ZERO) ? invariant(false, "Forfeit amount can't be negative") : void 0;
!(JSBI.BigInt(governance) >= maiaCoreSdk.ZERO) ? invariant(false, "Forfeit amount can't be negative") : void 0;
// Encode the forfeitMultiple action.
return BHermes.INTERFACE.encodeFunctionData('forfeitMultipleAmounts', [weight.toString(), boost.toString(), governance.toString()]);
}
/**
* Encodes the contract interaction calldata to forfeit weight.
* @param amount amount of weight to forfeit.
* @returns the encoded calldata for the forfeitWeight action.
*/;
BHermes.encodeForfeitWeightCalldata = function encodeForfeitWeightCalldata(_ref4) {
var amount = _ref4.amount;
// Check if the forfeit amount is valid.
!(JSBI.BigInt(amount) >= maiaCoreSdk.ZERO) ? invariant(false, "Forfeit amount can't be negative") : void 0;
// Encode the forfeitWeight action.
return BHermes.INTERFACE.encodeFunctionData('forfeitWeight', [amount.toString()]);
}
/**
* Encodes the contract interaction calldata to forfeit boost.
* @param amount amount of boost to forfeit.
* @returns the encoded calldata for the forfeitBoost action.
*/;
BHermes.encodeForfeitBoostCalldata = function encodeForfeitBoostCalldata(_ref5) {
var amount = _ref5.amount;
// Check if the forfeit amount is valid.
!(JSBI.BigInt(amount) >= maiaCoreSdk.ZERO) ? invariant(false, "Forfeit amount can't be negative") : void 0;
// Encode the forfeitBoost action.
return BHermes.INTERFACE.encodeFunctionData('forfeitBoost', [amount.toString()]);
}
/**
* Encodes the contract interaction calldata to forfeit governance.
* @param amount amount of governance to forfeit.
* @returns the encoded calldata for the forfeitGovernance action.
*/;
BHermes.encodeForfeitGovernanceCalldata = function encodeForfeitGovernanceCalldata(_ref6) {
var amount = _ref6.amount;
// Check if the forfeit amount is valid.
!(JSBI.BigInt(amount) >= maiaCoreSdk.ZERO) ? invariant(false, "Forfeit amount can't be negative") : void 0;
// Encode the forfeitGovernance action.
return BHermes.INTERFACE.encodeFunctionData('forfeitGovernance', [amount.toString()]);
}
/**
* Encodes the contract interaction calldata to claim multiple.
* @param amount amount of each utility token to claim.
* @returns the encoded calldata for the claimMultiple action.
*/;
BHermes.encodeClaimMultipleCalldata = function encodeClaimMultipleCalldata(_ref7) {
var amount = _ref7.amount;
// Check if the claim amount is valid.
!(JSBI.BigInt(amount) >= maiaCoreSdk.ZERO) ? invariant(false, "Claim amount can't be negative") : void 0;
// Encode the claimMultiple action.
return BHermes.INTERFACE.encodeFunctionData('claimMultiple', [amount.toString()]);
}
/**
* Encodes the contract interaction calldata to claim multiple amounts.
* @param weight amount of weight to claim.
* @param boost amount of boost to claim.
* @param governance amount of governance to claim.
* @returns the encoded calldata for the claimMultipleAmounts action.
*/;
BHermes.encodeClaimMultipleAmountsCalldata = function encodeClaimMultipleAmountsCalldata(_ref8) {
var weight = _ref8.weight,
boost = _ref8.boost,
governance = _ref8.governance;
// Check if the claim amount is valid.
!(JSBI.BigInt(weight) >= maiaCoreSdk.ZERO) ? invariant(false, "Claim amount can't be negative") : void 0;
!(JSBI.BigInt(boost) >= maiaCoreSdk.ZERO) ? invariant(false, "Claim amount can't be negative") : void 0;
!(JSBI.BigInt(governance) >= maiaCoreSdk.ZERO) ? invariant(false, "Claim amount can't be negative") : void 0;
// Encode the claimMultipleAmounts action.
return BHermes.INTERFACE.encodeFunctionData('claimMultipleAmounts', [weight.toString(), boost.toString(), governance.toString()]);
}
/**
* Encodes the contract interaction calldata to claim weight.
* @param amount amount of weight to claim.
* @returns the encoded calldata for the claimWeight action.
*/;
BHermes.encodeClaimWeightCalldata = function encodeClaimWeightCalldata(_ref9) {
var amount = _ref9.amount;
// Check if the claim amount is valid.
!(JSBI.BigInt(amount) >= maiaCoreSdk.ZERO) ? invariant(false, "Claim amount can't be negative") : void 0;
// Encode the claimWeight action.
return BHermes.INTERFACE.encodeFunctionData('claimWeight', [amount.toString()]);
}
/**
* Encodes the contract interaction calldata to claim boost.
* @param amount amount of boost to claim.
* @returns the encoded calldata for the claimBoost action.
*/;
BHermes.encodeClaimBoostCalldata = function encodeClaimBoostCalldata(_ref10) {
var amount = _ref10.amount;
// Check if the claim amount is valid.
!(JSBI.BigInt(amount) >= maiaCoreSdk.ZERO) ? invariant(false, "Claim amount can't be negative") : void 0;
// Encode the claimBoost action.
return BHermes.INTERFACE.encodeFunctionData('claimBoost', [amount.toString()]);
}
/**
* Encodes the contract interaction calldata to claim governance.
* @param amount amount of governance to claim.
* @returns the encoded calldata for the claimGovernance action.
*/;
BHermes.encodeClaimGovernanceCalldata = function encodeClaimGovernanceCalldata(_ref11) {
var amount = _ref11.amount;
// Check if the claim amount is valid.
!(JSBI.BigInt(amount) >= maiaCoreSdk.ZERO) ? invariant(false, "Claim amount can't be negative") : void 0;
// Encode the claimGovernance action.
return BHermes.INTERFACE.encodeFunctionData('claimGovernance', [amount.toString()]);
};
return BHermes;
}();
BHermes.INTERFACE = /*#__PURE__*/new abi.Interface(bHermes);
var BHermesBoostABI = [
{
type: "constructor",
inputs: [
{
name: "_owner",
type: "address",
internalType: "address"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "DOMAIN_SEPARATOR",
inputs: [
],
outputs: [
{
name: "",
type: "bytes32",
internalType: "bytes32"
}
],
stateMutability: "view"
},
{
type: "function",
name: "addGauge",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "allowance",
inputs: [
{
name: "",
type: "address",
internalType: "address"
},
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "approve",
inputs: [
{
name: "spender",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "attach",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "bHermes",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
stateMutability: "view"
},
{
type: "function",
name: "balanceOf",
inputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "cancelOwnershipHandover",
inputs: [
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "completeOwnershipHandover",
inputs: [
{
name: "pendingOwner",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "decimals",
inputs: [
],
outputs: [
{
name: "",
type: "uint8",
internalType: "uint8"
}
],
stateMutability: "view"
},
{
type: "function",
name: "decrementAllGaugesAllBoost",
inputs: [
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "decrementAllGaugesBoost",
inputs: [
{
name: "boost",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "decrementGaugeAllBoost",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "decrementGaugeBoost",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
},
{
name: "boost",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "decrementGaugesBoostIndexed",
inputs: [
{
name: "boost",
type: "uint256",
internalType: "uint256"
},
{
name: "offset",
type: "uint256",
internalType: "uint256"
},
{
name: "num",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "deprecatedGauges",
inputs: [
],
outputs: [
{
name: "",
type: "address[]",
internalType: "address[]"
}
],
stateMutability: "view"
},
{
type: "function",
name: "detach",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "freeGaugeBoost",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "gauges",
inputs: [
{
name: "offset",
type: "uint256",
internalType: "uint256"
},
{
name: "num",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "values",
type: "address[]",
internalType: "address[]"
}
],
stateMutability: "view"
},
{
type: "function",
name: "gauges",
inputs: [
],
outputs: [
{
name: "",
type: "address[]",
internalType: "address[]"
}
],
stateMutability: "view"
},
{
type: "function",
name: "getUserBoost",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "boost",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "getUserGaugeBoost",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
},
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "userGaugeBoost",
type: "uint128",
internalType: "uint128"
},
{
name: "totalGaugeBoost",
type: "uint128",
internalType: "uint128"
}
],
stateMutability: "view"
},
{
type: "function",
name: "isGauge",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "view"
},
{
type: "function",
name: "isUserGauge",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
},
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "view"
},
{
type: "function",
name: "mint",
inputs: [
{
name: "to",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "name",
inputs: [
],
outputs: [
{
name: "",
type: "string",
internalType: "string"
}
],
stateMutability: "view"
},
{
type: "function",
name: "nonces",
inputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "numDeprecatedGauges",
inputs: [
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "numGauges",
inputs: [
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "numUserGauges",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "owner",
inputs: [
],
outputs: [
{
name: "result",
type: "address",
internalType: "address"
}
],
stateMutability: "view"
},
{
type: "function",
name: "ownershipHandoverExpiresAt",
inputs: [
{
name: "pendingOwner",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "result",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "permit",
inputs: [
{
name: "owner",
type: "address",
internalType: "address"
},
{
name: "spender",
type: "address",
internalType: "address"
},
{
name: "value",
type: "uint256",
internalType: "uint256"
},
{
name: "deadline",
type: "uint256",
internalType: "uint256"
},
{
name: "v",
type: "uint8",
internalType: "uint8"
},
{
name: "r",
type: "bytes32",
internalType: "bytes32"
},
{
name: "s",
type: "bytes32",
internalType: "bytes32"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "removeGauge",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "renounceOwnership",
inputs: [
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "replaceGauge",
inputs: [
{
name: "oldGauge",
type: "address",
internalType: "address"
},
{
name: "newGauge",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "requestOwnershipHandover",
inputs: [
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "symbol",
inputs: [
],
outputs: [
{
name: "",
type: "string",
internalType: "string"
}
],
stateMutability: "view"
},
{
type: "function",
name: "totalSupply",
inputs: [
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "transfer",
inputs: [
{
name: "to",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "transferFrom",
inputs: [
{
name: "from",
type: "address",
internalType: "address"
},
{
name: "to",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "transferOwnership",
inputs: [
{
name: "newOwner",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "updateUserBoost",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "userGauges",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "address[]",
internalType: "address[]"
}
],
stateMutability: "view"
},
{
type: "function",
name: "userGauges",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
},
{
name: "offset",
type: "uint256",
internalType: "uint256"
},
{
name: "num",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "values",
type: "address[]",
internalType: "address[]"
}
],
stateMutability: "view"
},
{
type: "event",
name: "AddGauge",
inputs: [
{
name: "gauge",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "Approval",
inputs: [
{
name: "owner",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "spender",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: false,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "Attach",
inputs: [
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "gauge",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "boost",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "DecrementUserGaugeBoost",
inputs: [
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "gauge",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "UpdatedBoost",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "Detach",
inputs: [
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "gauge",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "OwnershipHandoverCanceled",
inputs: [
{
name: "pendingOwner",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "OwnershipHandoverRequested",
inputs: [
{
name: "pendingOwner",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "OwnershipTransferred",
inputs: [
{
name: "oldOwner",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "newOwner",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "RemoveGauge",
inputs: [
{
name: "gauge",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "Transfer",
inputs: [
{
name: "from",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "to",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: false,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "UpdateUserBoost",
inputs: [
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "updatedBoost",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "error",
name: "AlreadyInitialized",
inputs: [
]
},
{
type: "error",
name: "AttachedBoost",
inputs: [
]
},
{
type: "error",
name: "GaugeAlreadyAttached",
inputs: [
]
},
{
type: "error",
name: "InvalidGauge",
inputs: [
]
},
{
type: "error",
name: "NewOwnerIsZeroAddress",
inputs: [
]
},
{
type: "error",
name: "NoHandoverRequest",
inputs: [
]
},
{
type: "error",
name: "NotbHermes",
inputs: [
]
},
{
type: "error",
name: "Unauthorized",
inputs: [
]
}
];
/**
* @title BHermesBoost class
* @notice Provides a set of function to encode calldata for the different bHermes gauges contract interactions.
* @dev Actions such as incrementing or decrementing gauge vote allocations.
* @author MaiaDAO
*/
var BHermesBoost = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
/* eslint-disable @typescript-eslint/no-empty-function */
function BHermesBoost() {}
/**
* Creates the necessary execution params to decrement boost on a single gauge.
* @param gauge The address of the gauge to decrement boost from.
* @param boost The amount of boost to decrement.
* @returns The encoded decrement decrement gauge boost params.
*/
BHermesBoost.encodeDecrementGaugeBoostCalldata = function encodeDecrementGaugeBoostCalldata(_ref) {
var gauge = _ref.gauge,
boost = _ref.boost;
// Check if the gauge address and boost amount is valid.
!gauge ? invariant(false, 'Invalid gauge address') : void 0;
!(gauge !== ADDRESS_ZERO) ? invariant(false, 'Invalid gauge address') : void 0;
!(JSBI.BigInt(boost) > maiaCoreSdk.ZERO) ? invariant(false, "Boost amount can't be negative or zero") : void 0;
// Encode the decrement gauge boost action.
return BHermesBoost.INTERFACE.encodeFunctionData('decrementGaugeBoost', [gauge, boost]);
}
/**
* Creates the necessary execution params to decrement all boost on a single gauge.
* @param gauge The address of the gauge to decrement all boost from.
* @returns The encoded decrement all gauge boost params.
*/;
BHermesBoost.encodeDecrementGaugeAllBoostCalldata = function encodeDecrementGaugeAllBoostCalldata(_ref2) {
var gauge = _ref2.gauge;
// Check if the gauge address is valid.
!gauge ? invariant(false, 'Invalid gauge address') : void 0;
!(gauge !== ADDRESS_ZERO) ? invariant(false, 'Invalid gauge address') : void 0;
// Encode the decrement all gauge boost action.
return BHermesBoost.INTERFACE.encodeFunctionData('decrementGaugeAllBoost', [gauge]);
}
/**
* Creates the necessary execution params to decrement boost from all gauges.
* @param boost The amount of boost to detach.
* @returns The encoded decrement all gauge boost params.
*/;
BHermesBoost.encodeDecrementAllGaugesBoostCalldata = function encodeDecrementAllGaugesBoostCalldata(_ref3) {
var boost = _ref3.boost;
// Check if the boost amount is valid.
!(JSBI.BigInt(boost) > maiaCoreSdk.ZERO) ? invariant(false, "Boost amount can't be negative or zero") : void 0;
// Encode the decrement all gauge boost action.
return BHermesBoost.INTERFACE.encodeFunctionData('decrementAllGaugesBoost', [boost]);
}
/**
* Creates the necessary execution params to decrement boost from a subset of atached gauges, useful to prevent OUT_OF_GAS when many gauges are attached.
* @param boost The amount of boost to detach.
* @param offset The offset to start from.
* @param num The number of gauges to detach boost from.
* @returns The encoded decrement all gauge boost params.
*/;
BHermesBoost.encodeDecrementGaugesBoostIndexedCalldata = function encodeDecrementGaugesBoostIndexedCalldata(_ref4) {
var boost = _ref4.boost,
offset = _ref4.offset,
num = _ref4.num;
// Check if the boost, offset and num are valid.
!(JSBI.BigInt(boost) > maiaCoreSdk.ZERO) ? invariant(false, "Boost amount can't be negative or zero") : void 0;
!(offset >= 0) ? invariant(false, "Offset can't be negative") : void 0;
!(num > 0) ? invariant(false, "Number of gauges can't be negative or zero") : void 0;
// Encode the decrement all gauge boost action.
return BHermesBoost.INTERFACE.encodeFunctionData('decrementGaugesBoostIndexed', [boost, offset, num]);
}
/**
* Creates the necessary execution params to decrement all boost from all gauges.
* @returns The encoded decrement all gauge boost params.
*/;
BHermesBoost.encodeDecrementAllGaugesAllBoostCalldata = function encodeDecrementAllGaugesAllBoostCalldata() {
return BHermesBoost.INTERFACE.encodeFunctionData('decrementAllGaugesAllBoost', []);
};
return BHermesBoost;
}();
BHermesBoost.INTERFACE = /*#__PURE__*/new abi.Interface(BHermesBoostABI);
var BHermesGaugesABI = [
{
type: "constructor",
inputs: [
{
name: "_owner",
type: "address",
internalType: "address"
},
{
name: "_flywheelBooster",
type: "address",
internalType: "address"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "DELEGATION_TYPEHASH",
inputs: [
],
outputs: [
{
name: "",
type: "bytes32",
internalType: "bytes32"
}
],
stateMutability: "view"
},
{
type: "function",
name: "DOMAIN_SEPARATOR",
inputs: [
],
outputs: [
{
name: "",
type: "bytes32",
internalType: "bytes32"
}
],
stateMutability: "view"
},
{
type: "function",
name: "addGauge",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint112",
internalType: "uint112"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "allowance",
inputs: [
{
name: "",
type: "address",
internalType: "address"
},
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "approve",
inputs: [
{
name: "spender",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "bHermes",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
stateMutability: "view"
},
{
type: "function",
name: "balanceOf",
inputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "calculateGaugeAllocation",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
},
{
name: "quantity",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "canContractExceedMaxDelegates",
inputs: [
{
name: "contractAddress",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "canExceedMaxGauges",
type: "bool",
internalType: "bool"
}
],
stateMutability: "view"
},
{
type: "function",
name: "canContractExceedMaxGauges",
inputs: [
{
name: "contractAddress",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "canExceedMaxGauges",
type: "bool",
internalType: "bool"
}
],
stateMutability: "view"
},
{
type: "function",
name: "cancelOwnershipHandover",
inputs: [
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "checkpoints",
inputs: [
{
name: "account",
type: "address",
internalType: "address"
},
{
name: "pos",
type: "uint32",
internalType: "uint32"
}
],
outputs: [
{
name: "",
type: "tuple",
internalType: "struct IERC20MultiVotes.Checkpoint",
components: [
{
name: "fromBlock",
type: "uint32",
internalType: "uint32"
},
{
name: "votes",
type: "uint224",
internalType: "uint224"
}
]
}
],
stateMutability: "view"
},
{
type: "function",
name: "completeOwnershipHandover",
inputs: [
{
name: "pendingOwner",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "decimals",
inputs: [
],
outputs: [
{
name: "",
type: "uint8",
internalType: "uint8"
}
],
stateMutability: "view"
},
{
type: "function",
name: "decrementGauge",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
},
{
name: "weight",
type: "uint112",
internalType: "uint112"
}
],
outputs: [
{
name: "newUserWeight",
type: "uint112",
internalType: "uint112"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "decrementGauges",
inputs: [
{
name: "gaugeList",
type: "address[]",
internalType: "address[]"
},
{
name: "weights",
type: "uint112[]",
internalType: "uint112[]"
}
],
outputs: [
{
name: "newUserWeight",
type: "uint112",
internalType: "uint112"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "delegate",
inputs: [
{
name: "newDelegatee",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "delegateBySig",
inputs: [
{
name: "delegatee",
type: "address",
internalType: "address"
},
{
name: "nonce",
type: "uint256",
internalType: "uint256"
},
{
name: "expiry",
type: "uint256",
internalType: "uint256"
},
{
name: "v",
type: "uint8",
internalType: "uint8"
},
{
name: "r",
type: "bytes32",
internalType: "bytes32"
},
{
name: "s",
type: "bytes32",
internalType: "bytes32"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "delegateCount",
inputs: [
{
name: "delegator",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "delegates",
inputs: [
{
name: "delegator",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "address[]",
internalType: "address[]"
}
],
stateMutability: "view"
},
{
type: "function",
name: "delegatesVotesCount",
inputs: [
{
name: "delegator",
type: "address",
internalType: "address"
},
{
name: "delegatee",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "deprecatedGauges",
inputs: [
],
outputs: [
{
name: "",
type: "address[]",
internalType: "address[]"
}
],
stateMutability: "view"
},
{
type: "function",
name: "flywheelBooster",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "contract IFlywheelBooster"
}
],
stateMutability: "view"
},
{
type: "function",
name: "freeVotes",
inputs: [
{
name: "account",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "gauges",
inputs: [
{
name: "offset",
type: "uint256",
internalType: "uint256"
},
{
name: "num",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "values",
type: "address[]",
internalType: "address[]"
}
],
stateMutability: "view"
},
{
type: "function",
name: "gauges",
inputs: [
],
outputs: [
{
name: "",
type: "address[]",
internalType: "address[]"
}
],
stateMutability: "view"
},
{
type: "function",
name: "getGaugeCycleEnd",
inputs: [
],
outputs: [
{
name: "",
type: "uint32",
internalType: "uint32"
}
],
stateMutability: "view"
},
{
type: "function",
name: "getGaugeWeight",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint112",
internalType: "uint112"
}
],
stateMutability: "view"
},
{
type: "function",
name: "getPriorVotes",
inputs: [
{
name: "account",
type: "address",
internalType: "address"
},
{
name: "blockNumber",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "getStoredGaugeWeight",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint112",
internalType: "uint112"
}
],
stateMutability: "view"
},
{
type: "function",
name: "getUserGaugeWeight",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
},
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "weight",
type: "uint112",
internalType: "uint112"
}
],
stateMutability: "view"
},
{
type: "function",
name: "getUserWeight",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "weight",
type: "uint112",
internalType: "uint112"
}
],
stateMutability: "view"
},
{
type: "function",
name: "getVotes",
inputs: [
{
name: "account",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "incrementDelegation",
inputs: [
{
name: "delegatee",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "incrementGauge",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
},
{
name: "weight",
type: "uint112",
internalType: "uint112"
}
],
outputs: [
{
name: "newUserWeight",
type: "uint112",
internalType: "uint112"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "incrementGauges",
inputs: [
{
name: "gaugeList",
type: "address[]",
internalType: "address[]"
},
{
name: "weights",
type: "uint112[]",
internalType: "uint112[]"
}
],
outputs: [
{
name: "newUserWeight",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "isGauge",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "view"
},
{
type: "function",
name: "isUserGauge",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
},
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "view"
},
{
type: "function",
name: "maxDelegates",
inputs: [
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "maxGauges",
inputs: [
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "mint",
inputs: [
{
name: "to",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "name",
inputs: [
],
outputs: [
{
name: "",
type: "string",
internalType: "string"
}
],
stateMutability: "view"
},
{
type: "function",
name: "nonces",
inputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "numCheckpoints",
inputs: [
{
name: "account",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint32",
internalType: "uint32"
}
],
stateMutability: "view"
},
{
type: "function",
name: "numDeprecatedGauges",
inputs: [
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "numGauges",
inputs: [
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "numUserGauges",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "owner",
inputs: [
],
outputs: [
{
name: "result",
type: "address",
internalType: "address"
}
],
stateMutability: "view"
},
{
type: "function",
name: "ownershipHandoverExpiresAt",
inputs: [
{
name: "pendingOwner",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "result",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "permit",
inputs: [
{
name: "owner",
type: "address",
internalType: "address"
},
{
name: "spender",
type: "address",
internalType: "address"
},
{
name: "value",
type: "uint256",
internalType: "uint256"
},
{
name: "deadline",
type: "uint256",
internalType: "uint256"
},
{
name: "v",
type: "uint8",
internalType: "uint8"
},
{
name: "r",
type: "bytes32",
internalType: "bytes32"
},
{
name: "s",
type: "bytes32",
internalType: "bytes32"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "removeGauge",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "renounceOwnership",
inputs: [
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "replaceGauge",
inputs: [
{
name: "oldGauge",
type: "address",
internalType: "address"
},
{
name: "newGauge",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "requestOwnershipHandover",
inputs: [
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "setContractExceedMaxDelegates",
inputs: [
{
name: "account",
type: "address",
internalType: "address"
},
{
name: "canExceedMax",
type: "bool",
internalType: "bool"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "setContractExceedMaxGauges",
inputs: [
{
name: "account",
type: "address",
internalType: "address"
},
{
name: "canExceedMax",
type: "bool",
internalType: "bool"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "setFlywheelBooster",
inputs: [
{
name: "newFlywheelBooster",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "setMaxDelegates",
inputs: [
{
name: "newMax",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "setMaxGauges",
inputs: [
{
name: "newMax",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "storedTotalWeight",
inputs: [
],
outputs: [
{
name: "",
type: "uint112",
internalType: "uint112"
}
],
stateMutability: "view"
},
{
type: "function",
name: "symbol",
inputs: [
],
outputs: [
{
name: "",
type: "string",
internalType: "string"
}
],
stateMutability: "view"
},
{
type: "function",
name: "totalSupply",
inputs: [
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "totalWeight",
inputs: [
],
outputs: [
{
name: "",
type: "uint112",
internalType: "uint112"
}
],
stateMutability: "view"
},
{
type: "function",
name: "transfer",
inputs: [
{
name: "to",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "transferFrom",
inputs: [
{
name: "from",
type: "address",
internalType: "address"
},
{
name: "to",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "transferOwnership",
inputs: [
{
name: "newOwner",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "undelegate",
inputs: [
{
name: "delegatee",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "userDelegatedVotes",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "votes",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "userGauges",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "address[]",
internalType: "address[]"
}
],
stateMutability: "view"
},
{
type: "function",
name: "userGauges",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
},
{
name: "offset",
type: "uint256",
internalType: "uint256"
},
{
name: "num",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "values",
type: "address[]",
internalType: "address[]"
}
],
stateMutability: "view"
},
{
type: "function",
name: "userUnusedVotes",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "event",
name: "AddGauge",
inputs: [
{
name: "gauge",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "Approval",
inputs: [
{
name: "owner",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "spender",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: false,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "CanContractExceedMaxDelegatesUpdate",
inputs: [
{
name: "account",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "canContractExceedMaxDelegates",
type: "bool",
indexed: true,
internalType: "bool"
}
],
anonymous: false
},
{
type: "event",
name: "CanContractExceedMaxGaugesUpdate",
inputs: [
{
name: "account",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "canContractExceedMaxGauges",
type: "bool",
indexed: true,
internalType: "bool"
}
],
anonymous: false
},
{
type: "event",
name: "DecrementGaugeWeight",
inputs: [
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "gauge",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "weight",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "DelegateChanged",
inputs: [
{
name: "delegator",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "fromDelegate",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "toDelegate",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "DelegateVotesChanged",
inputs: [
{
name: "delegate",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "previousBalance",
type: "uint256",
indexed: true,
internalType: "uint256"
},
{
name: "newBalance",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "Delegation",
inputs: [
{
name: "delegator",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "delegate",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "IncrementGaugeWeight",
inputs: [
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "gauge",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "weight",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "MaxDelegatesUpdate",
inputs: [
{
name: "oldMaxDelegates",
type: "uint256",
indexed: true,
internalType: "uint256"
},
{
name: "newMaxDelegates",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "MaxGaugesUpdate",
inputs: [
{
name: "oldMaxGauges",
type: "uint256",
indexed: true,
internalType: "uint256"
},
{
name: "newMaxGauges",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "OwnershipHandoverCanceled",
inputs: [
{
name: "pendingOwner",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "OwnershipHandoverRequested",
inputs: [
{
name: "pendingOwner",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "OwnershipTransferred",
inputs: [
{
name: "oldOwner",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "newOwner",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "RemoveGauge",
inputs: [
{
name: "gauge",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "SetFlywheelBooster",
inputs: [
{
name: "newFlywheelBooster",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "Transfer",
inputs: [
{
name: "from",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "to",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: false,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "Undelegation",
inputs: [
{
name: "delegator",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "delegate",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "error",
name: "AlreadyInitialized",
inputs: [
]
},
{
type: "error",
name: "BlockError",
inputs: [
]
},
{
type: "error",
name: "DelegationError",
inputs: [
]
},
{
type: "error",
name: "IncrementFreezeError",
inputs: [
]
},
{
type: "error",
name: "InvalidBooster",
inputs: [
]
},
{
type: "error",
name: "InvalidGaugeError",
inputs: [
]
},
{
type: "error",
name: "MaxGaugeError",
inputs: [
]
},
{
type: "error",
name: "NewOwnerIsZeroAddress",
inputs: [
]
},
{
type: "error",
name: "NoHandoverRequest",
inputs: [
]
},
{
type: "error",
name: "NonContractError",
inputs: [
]
},
{
type: "error",
name: "NotbHermes",
inputs: [
]
},
{
type: "error",
name: "OverWeightError",
inputs: [
]
},
{
type: "error",
name: "SizeMismatchError",
inputs: [
]
},
{
type: "error",
name: "Unauthorized",
inputs: [
]
},
{
type: "error",
name: "UndelegationVoteError",
inputs: [
]
}
];
/**
* @title BHermesGauges class
* @notice Provides a set of function to encode calldata for the different bHermes gauges contract interactions.
* @dev Actions such as incrementing or decrementing gauge vote allocations.
* @author MaiaDAO
*/
var BHermesGauges = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
/* eslint-disable @typescript-eslint/no-empty-function */
function BHermesGauges() {}
/**
* Creates the necessary execution params to increment weight on a single gauge.
* @param pool The address of the pool for which gauge to increment weight
* @param weight The amount of weight to increment
* @returns The encoded increment gauge votes params
*/
BHermesGauges.encodeIncrementGaugeCalldata = function encodeIncrementGaugeCalldata(_ref) {
var pool = _ref.pool,
weight = _ref.weight;
!pool ? invariant(false, 'Invalid pool') : void 0;
!(pool !== maiaCoreSdk.ZERO_ADDRESS) ? invariant(false, 'Invalid pool') : void 0;
!(JSBI.BigInt(weight) >= maiaCoreSdk.ZERO) ? invariant(false, 'Invalid votes') : void 0;
return BHermesGauges.INTERFACE.encodeFunctionData('incrementGauge', [pool, weight]);
}
/**
* Creates the necessary execution params to increment weight on multiple gauges.
* @param pools array of uniswap V3 pool addresses
* @param weights array of weight to be incremented
* @returns The encoded increment gauges params
*/;
BHermesGauges.encodeIncrementGaugesCalldata = function encodeIncrementGaugesCalldata(_ref2) {
var pools = _ref2.pools,
weights = _ref2.weights;
!pools ? invariant(false, 'Invalid address') : void 0;
!pools.every(function (pool) {
return pool !== maiaCoreSdk.ZERO_ADDRESS;
}) ? invariant(false, 'Invalid address cant be zero') : void 0;
!weights ? invariant(false, 'Invalid votes') : void 0;
!weights.every(function (weight) {
return JSBI.BigInt(weight) > maiaCoreSdk.ZERO;
}) ? invariant(false, 'Invalid votes cant be zero') : void 0;
return BHermesGauges.INTERFACE.encodeFunctionData('incrementGauges', [pools, weights]);
}
/**
* Creates the necessary execution params to decrement votes on a given gauge.
* @param pool The address of the pool for which gauge to decrement weight from
* @param weight The amount of weight to decrement
* @returns The encoded decrement gauge votes params
*/;
BHermesGauges.encodeDecrementGaugeCalldata = function encodeDecrementGaugeCalldata(_ref3) {
var pool = _ref3.pool,
weight = _ref3.weight;
!pool ? invariant(false, 'Invalid pool') : void 0;
!(pool !== maiaCoreSdk.ZERO_ADDRESS) ? invariant(false, 'Invalid pool') : void 0;
!(JSBI.BigInt(weight) >= maiaCoreSdk.ZERO) ? invariant(false, 'Invalid votes') : void 0;
return BHermesGauges.INTERFACE.encodeFunctionData('decrementGauge', [pool, weight]);
}
/**
* Creates the necessary execution params to decrement votes on multiple gauges.
* @param pools array of uniswap V3 pool addresses
* @param weights array of amount of weight to be decremented
* @returns The encoded decrement gauges params
*/;
BHermesGauges.encodeDecrementGaugesCalldata = function encodeDecrementGaugesCalldata(_ref4) {
var pools = _ref4.pools,
weights = _ref4.weights;
!pools ? invariant(false, 'Invalid address') : void 0;
!pools.every(function (pool) {
return pool !== maiaCoreSdk.ZERO_ADDRESS;
}) ? invariant(false, 'Invalid address cant be zero') : void 0;
!weights ? invariant(false, 'Invalid votes') : void 0;
!weights.every(function (weight) {
return JSBI.BigInt(weight) > maiaCoreSdk.ZERO;
}) ? invariant(false, 'Invalid votes cant be zero') : void 0;
return BHermesGauges.INTERFACE.encodeFunctionData('decrementGauges', [pools, weights]);
}
/**
* Creates the necessary execution params to delegate bHermes gauge weight to a given address.
* @param newDelegatee The address of the gauge to delegate votes to
*/;
BHermesGauges.encodeDelegateCalldata = function encodeDelegateCalldata(_ref5) {
var newDelegatee = _ref5.newDelegatee;
!newDelegatee ? invariant(false, 'Invalid address') : void 0;
!(newDelegatee !== maiaCoreSdk.ZERO_ADDRESS) ? invariant(false, 'Invalid address cant be zero') : void 0;
return BHermesGauges.INTERFACE.encodeFunctionData('delegate', [newDelegatee]);
}
/**
* Creates the necessary execution params to undelegate bHermes gauge weight from a given address.
* @param delegatee The address of the gauge to undelegate votes from
* @param weight The amount of gauge weight to undelegate
*/;
BHermesGauges.encodeUndelegateCalldata = function encodeUndelegateCalldata(_ref6) {
var delegatee = _ref6.delegatee,
weight = _ref6.weight;
!delegatee ? invariant(false, 'Invalid address') : void 0;
!(delegatee !== maiaCoreSdk.ZERO_ADDRESS) ? invariant(false, 'Invalid address cant be zero') : void 0;
return BHermesGauges.INTERFACE.encodeFunctionData('undelegate', [delegatee, weight]);
};
return BHermesGauges;
}();
BHermesGauges.INTERFACE = /*#__PURE__*/new abi.Interface(BHermesGaugesABI);
var BHermesVotesABI = [
{
type: "constructor",
inputs: [
{
name: "_owner",
type: "address",
internalType: "address"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "DELEGATION_TYPEHASH",
inputs: [
],
outputs: [
{
name: "",
type: "bytes32",
internalType: "bytes32"
}
],
stateMutability: "view"
},
{
type: "function",
name: "DOMAIN_SEPARATOR",
inputs: [
],
outputs: [
{
name: "",
type: "bytes32",
internalType: "bytes32"
}
],
stateMutability: "view"
},
{
type: "function",
name: "allowance",
inputs: [
{
name: "",
type: "address",
internalType: "address"
},
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "approve",
inputs: [
{
name: "spender",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "bHermes",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
stateMutability: "view"
},
{
type: "function",
name: "balanceOf",
inputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "burn",
inputs: [
{
name: "from",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "canContractExceedMaxDelegates",
inputs: [
{
name: "contractAddress",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "canExceedMaxGauges",
type: "bool",
internalType: "bool"
}
],
stateMutability: "view"
},
{
type: "function",
name: "cancelOwnershipHandover",
inputs: [
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "checkpoints",
inputs: [
{
name: "account",
type: "address",
internalType: "address"
},
{
name: "pos",
type: "uint32",
internalType: "uint32"
}
],
outputs: [
{
name: "",
type: "tuple",
internalType: "struct IERC20MultiVotes.Checkpoint",
components: [
{
name: "fromBlock",
type: "uint32",
internalType: "uint32"
},
{
name: "votes",
type: "uint224",
internalType: "uint224"
}
]
}
],
stateMutability: "view"
},
{
type: "function",
name: "completeOwnershipHandover",
inputs: [
{
name: "pendingOwner",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "decimals",
inputs: [
],
outputs: [
{
name: "",
type: "uint8",
internalType: "uint8"
}
],
stateMutability: "view"
},
{
type: "function",
name: "delegate",
inputs: [
{
name: "newDelegatee",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "delegateBySig",
inputs: [
{
name: "delegatee",
type: "address",
internalType: "address"
},
{
name: "nonce",
type: "uint256",
internalType: "uint256"
},
{
name: "expiry",
type: "uint256",
internalType: "uint256"
},
{
name: "v",
type: "uint8",
internalType: "uint8"
},
{
name: "r",
type: "bytes32",
internalType: "bytes32"
},
{
name: "s",
type: "bytes32",
internalType: "bytes32"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "delegateCount",
inputs: [
{
name: "delegator",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "delegates",
inputs: [
{
name: "delegator",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "address[]",
internalType: "address[]"
}
],
stateMutability: "view"
},
{
type: "function",
name: "delegatesVotesCount",
inputs: [
{
name: "delegator",
type: "address",
internalType: "address"
},
{
name: "delegatee",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "freeVotes",
inputs: [
{
name: "account",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "getPriorVotes",
inputs: [
{
name: "account",
type: "address",
internalType: "address"
},
{
name: "blockNumber",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "getVotes",
inputs: [
{
name: "account",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "incrementDelegation",
inputs: [
{
name: "delegatee",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "maxDelegates",
inputs: [
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "mint",
inputs: [
{
name: "to",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "name",
inputs: [
],
outputs: [
{
name: "",
type: "string",
internalType: "string"
}
],
stateMutability: "view"
},
{
type: "function",
name: "nonces",
inputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "numCheckpoints",
inputs: [
{
name: "account",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint32",
internalType: "uint32"
}
],
stateMutability: "view"
},
{
type: "function",
name: "owner",
inputs: [
],
outputs: [
{
name: "result",
type: "address",
internalType: "address"
}
],
stateMutability: "view"
},
{
type: "function",
name: "ownershipHandoverExpiresAt",
inputs: [
{
name: "pendingOwner",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "result",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "permit",
inputs: [
{
name: "owner",
type: "address",
internalType: "address"
},
{
name: "spender",
type: "address",
internalType: "address"
},
{
name: "value",
type: "uint256",
internalType: "uint256"
},
{
name: "deadline",
type: "uint256",
internalType: "uint256"
},
{
name: "v",
type: "uint8",
internalType: "uint8"
},
{
name: "r",
type: "bytes32",
internalType: "bytes32"
},
{
name: "s",
type: "bytes32",
internalType: "bytes32"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "renounceOwnership",
inputs: [
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "requestOwnershipHandover",
inputs: [
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "setContractExceedMaxDelegates",
inputs: [
{
name: "account",
type: "address",
internalType: "address"
},
{
name: "canExceedMax",
type: "bool",
internalType: "bool"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "setMaxDelegates",
inputs: [
{
name: "newMax",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "symbol",
inputs: [
],
outputs: [
{
name: "",
type: "string",
internalType: "string"
}
],
stateMutability: "view"
},
{
type: "function",
name: "totalSupply",
inputs: [
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "transfer",
inputs: [
{
name: "to",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "transferFrom",
inputs: [
{
name: "from",
type: "address",
internalType: "address"
},
{
name: "to",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "bool",
internalType: "bool"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "transferOwnership",
inputs: [
{
name: "newOwner",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "undelegate",
inputs: [
{
name: "delegatee",
type: "address",
internalType: "address"
},
{
name: "amount",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "userDelegatedVotes",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "votes",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "userUnusedVotes",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "event",
name: "Approval",
inputs: [
{
name: "owner",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "spender",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: false,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "CanContractExceedMaxDelegatesUpdate",
inputs: [
{
name: "account",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "canContractExceedMaxDelegates",
type: "bool",
indexed: true,
internalType: "bool"
}
],
anonymous: false
},
{
type: "event",
name: "DelegateChanged",
inputs: [
{
name: "delegator",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "fromDelegate",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "toDelegate",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "DelegateVotesChanged",
inputs: [
{
name: "delegate",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "previousBalance",
type: "uint256",
indexed: true,
internalType: "uint256"
},
{
name: "newBalance",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "Delegation",
inputs: [
{
name: "delegator",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "delegate",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "MaxDelegatesUpdate",
inputs: [
{
name: "oldMaxDelegates",
type: "uint256",
indexed: true,
internalType: "uint256"
},
{
name: "newMaxDelegates",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "OwnershipHandoverCanceled",
inputs: [
{
name: "pendingOwner",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "OwnershipHandoverRequested",
inputs: [
{
name: "pendingOwner",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "OwnershipTransferred",
inputs: [
{
name: "oldOwner",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "newOwner",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "Transfer",
inputs: [
{
name: "from",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "to",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: false,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "Undelegation",
inputs: [
{
name: "delegator",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "delegate",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "error",
name: "AlreadyInitialized",
inputs: [
]
},
{
type: "error",
name: "BlockError",
inputs: [
]
},
{
type: "error",
name: "DelegationError",
inputs: [
]
},
{
type: "error",
name: "NewOwnerIsZeroAddress",
inputs: [
]
},
{
type: "error",
name: "NoHandoverRequest",
inputs: [
]
},
{
type: "error",
name: "NonContractError",
inputs: [
]
},
{
type: "error",
name: "NotbHermes",
inputs: [
]
},
{
type: "error",
name: "Unauthorized",
inputs: [
]
},
{
type: "error",
name: "UndelegationVoteError",
inputs: [
]
}
];
/**
* @title BHermesVotes class
* @notice Provides a set of function to encode calldata for the different bHermes votes contract interactions.
* @dev Actions such as delegating or undelegating governance power.
* @author MaiaDAO
*/
var BHermesVotes = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
/* eslint-disable @typescript-eslint/no-empty-function */
function BHermesVotes() {}
/**
* Creates the necessary execution params to delegate bHermes governance power to a given address.
* @param newDelegatee The address of the gauge to delegate votes to.
*/
BHermesVotes.encodeDelegateCalldata = function encodeDelegateCalldata(_ref) {
var newDelegatee = _ref.newDelegatee;
// Check if the new delegatee address is valid.
!newDelegatee ? invariant(false, 'Invalid delegatee address') : void 0;
!(newDelegatee !== ADDRESS_ZERO) ? invariant(false, 'Invalid delegatee address can not be zero address') : void 0;
// Encode the delegate action.
return BHermesVotes.INTERFACE.encodeFunctionData('delegate', [newDelegatee]);
}
/**
* Creates the necessary execution params to undelegate bHermes governance power from a given address.
* @param delegatee The address of the gauge to undelegate votes from.
* @param amount The amount of votes to undelegate.
*/;
BHermesVotes.encodeUndelegateCalldata = function encodeUndelegateCalldata(_ref2) {
var delegatee = _ref2.delegatee,
amount = _ref2.amount;
// Check if the delegatee address and amount is valid.
!delegatee ? invariant(false, 'Invalid delegatee address') : void 0;
!(delegatee !== ADDRESS_ZERO) ? invariant(false, 'Invalid delegatee address can not be zero address') : void 0;
!(JSBI.BigInt(amount) > maiaCoreSdk.ZERO) ? invariant(false, "Amount can't be negative or zero") : void 0;
// Encode the undelegate action.
return BHermesVotes.INTERFACE.encodeFunctionData('undelegate', [delegatee, amount]);
};
return BHermesVotes;
}();
BHermesVotes.INTERFACE = /*#__PURE__*/new abi.Interface(BHermesVotesABI);
function _construct(t, e, r) {
if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
var o = [null];
o.push.apply(o, e);
var p = new (t.bind.apply(t, o))();
return r && _setPrototypeOf(p, r.prototype), p;
}
function _isNativeReflectConstruct() {
try {
var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
} catch (t) {}
return (_isNativeReflectConstruct = function () {
return !!t;
})();
}
function _regeneratorRuntime() {
_regeneratorRuntime = function () {
return e;
};
var t,
e = {},
r = Object.prototype,
n = r.hasOwnProperty,
o = Object.defineProperty || function (t, e, r) {
t[e] = r.value;
},
i = "function" == typeof Symbol ? Symbol : {},
a = i.iterator || "@@iterator",
c = i.asyncIterator || "@@asyncIterator",
u = i.toStringTag || "@@toStringTag";
function define(t, e, r) {
return Object.defineProperty(t, e, {
value: r,
enumerable: !0,
configurable: !0,
writable: !0
}), t[e];
}
try {
define({}, "");
} catch (t) {
define = function (t, e, r) {
return t[e] = r;
};
}
function wrap(t, e, r, n) {
var i = e && e.prototype instanceof Generator ? e : Generator,
a = Object.create(i.prototype),
c = new Context(n || []);
return o(a, "_invoke", {
value: makeInvokeMethod(t, r, c)
}), a;
}
function tryCatch(t, e, r) {
try {
return {
type: "normal",
arg: t.call(e, r)
};
} catch (t) {
return {
type: "throw",
arg: t
};
}
}
e.wrap = wrap;
var h = "suspendedStart",
l = "suspendedYield",
f = "executing",
s = "completed",
y = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var p = {};
define(p, a, function () {
return this;
});
var d = Object.getPrototypeOf,
v = d && d(d(values([])));
v && v !== r && n.call(v, a) && (p = v);
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
function defineIteratorMethods(t) {
["next", "throw", "return"].forEach(function (e) {
define(t, e, function (t) {
return this._invoke(e, t);
});
});
}
function AsyncIterator(t, e) {
function invoke(r, o, i, a) {
var c = tryCatch(t[r], t, o);
if ("throw" !== c.type) {
var u = c.arg,
h = u.value;
return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
invoke("next", t, i, a);
}, function (t) {
invoke("throw", t, i, a);
}) : e.resolve(h).then(function (t) {
u.value = t, i(u);
}, function (t) {
return invoke("throw", t, i, a);
});
}
a(c.arg);
}
var r;
o(this, "_invoke", {
value: function (t, n) {
function callInvokeWithMethodAndArg() {
return new e(function (e, r) {
invoke(t, n, e, r);
});
}
return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
}
});
}
function makeInvokeMethod(e, r, n) {
var o = h;
return function (i, a) {
if (o === f) throw new Error("Generator is already running");
if (o === s) {
if ("throw" === i) throw a;
return {
value: t,
done: !0
};
}
for (n.method = i, n.arg = a;;) {
var c = n.delegate;
if (c) {
var u = maybeInvokeDelegate(c, n);
if (u) {
if (u === y) continue;
return u;
}
}
if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
if (o === h) throw o = s, n.arg;
n.dispatchException(n.arg);
} else "return" === n.method && n.abrupt("return", n.arg);
o = f;
var p = tryCatch(e, r, n);
if ("normal" === p.type) {
if (o = n.done ? s : l, p.arg === y) continue;
return {
value: p.arg,
done: n.done
};
}
"throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
}
};
}
function maybeInvokeDelegate(e, r) {
var n = r.method,
o = e.iterator[n];
if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
var i = tryCatch(o, e.iterator, r.arg);
if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
var a = i.arg;
return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
}
function pushTryEntry(t) {
var e = {
tryLoc: t[0]
};
1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
}
function resetTryEntry(t) {
var e = t.completion || {};
e.type = "normal", delete e.arg, t.completion = e;
}
function Context(t) {
this.tryEntries = [{
tryLoc: "root"
}], t.forEach(pushTryEntry, this), this.reset(!0);
}
function values(e) {
if (e || "" === e) {
var r = e[a];
if (r) return r.call(e);
if ("function" == typeof e.next) return e;
if (!isNaN(e.length)) {
var o = -1,
i = function next() {
for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
return next.value = t, next.done = !0, next;
};
return i.next = i;
}
}
throw new TypeError(typeof e + " is not iterable");
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
value: GeneratorFunctionPrototype,
configurable: !0
}), o(GeneratorFunctionPrototype, "constructor", {
value: GeneratorFunction,
configurable: !0
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
var e = "function" == typeof t && t.constructor;
return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
}, e.mark = function (t) {
return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
}, e.awrap = function (t) {
return {
__await: t
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
return this;
}), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
void 0 === i && (i = Promise);
var a = new AsyncIterator(wrap(t, r, n, o), i);
return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
return t.done ? t.value : a.next();
});
}, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
return this;
}), define(g, "toString", function () {
return "[object Generator]";
}), e.keys = function (t) {
var e = Object(t),
r = [];
for (var n in e) r.push(n);
return r.reverse(), function next() {
for (; r.length;) {
var t = r.pop();
if (t in e) return next.value = t, next.done = !1, next;
}
return next.done = !0, next;
};
}, e.values = values, Context.prototype = {
constructor: Context,
reset: function (e) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
},
stop: function () {
this.done = !0;
var t = this.tryEntries[0].completion;
if ("throw" === t.type) throw t.arg;
return this.rval;
},
dispatchException: function (e) {
if (this.done) throw e;
var r = this;
function handle(n, o) {
return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
}
for (var o = this.tryEntries.length - 1; o >= 0; --o) {
var i = this.tryEntries[o],
a = i.completion;
if ("root" === i.tryLoc) return handle("end");
if (i.tryLoc <= this.prev) {
var c = n.call(i, "catchLoc"),
u = n.call(i, "finallyLoc");
if (c && u) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
} else if (c) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
} else {
if (!u) throw new Error("try statement without catch or finally");
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
}
}
}
},
abrupt: function (t, e) {
for (var r = this.tryEntries.length - 1; r >= 0; --r) {
var o = this.tryEntries[r];
if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
var i = o;
break;
}
}
i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
var a = i ? i.completion : {};
return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
},
complete: function (t, e) {
if ("throw" === t.type) throw t.arg;
return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
},
finish: function (t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
}
},
catch: function (t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.tryLoc === t) {
var n = r.completion;
if ("throw" === n.type) {
var o = n.arg;
resetTryEntry(r);
}
return o;
}
}
throw new Error("illegal catch attempt");
},
delegateYield: function (e, r, n) {
return this.delegate = {
iterator: values(e),
resultName: r,
nextLoc: n
}, "next" === this.method && (this.arg = t), y;
}
}, e;
}
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 : String(i);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _extends() {
_extends = Object.assign ? Object.assign.bind() : function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
_setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeFunction(fn) {
try {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
} catch (e) {
return typeof fn === "function";
}
}
function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined;
_wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction(Class)) return Class;
if (typeof Class !== "function") {
throw new TypeError("Super expression must either be null or a function");
}
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return _construct(Class, arguments, _getPrototypeOf(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
});
return _setPrototypeOf(Wrapper, Class);
};
return _wrapNativeSuper(Class);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelperLoose(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (it) return (it = it.call(o)).next.bind(it);
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var ComposableStablePool = /*#__PURE__*/function () {
function ComposableStablePool(tokenA, tokenB, pool, wrapper) {
var _ref = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA];
this.token0 = _ref[0];
this.token1 = _ref[1];
this._pool = pool;
this.wrapper = wrapper;
// If the wrapper is set, we can determine if the pool contains wrapped tokens
if (!!this.wrapper) {
if (this.wrapper.vault().equals(this.token0)) {
this.wrappedTokenIndex = 0;
} else if (this.wrapper.vault().equals(this.token1)) {
this.wrappedTokenIndex = 1;
} else {
// If the wrapper is set, but the vault is not one of the tokens, throw an error
throw Error('WRONG TOKENS');
}
} else {
this.wrappedTokenIndex = -1;
}
}
var _proto = ComposableStablePool.prototype;
// Methods similar to Uniswap's Pool class but using Balancer logic
/**
* Returns true if the token is either token0 or token1
* @param token The token to check
* @returns True if token is either token0 or token
*/
_proto.involvesToken = function involvesToken(token) {
return token.equals(this.token0) || token.equals(this.token1);
}
/**
* Returns the current mid price of the pool in terms of token0, i.e. the ratio of token1 over token0
*/;
_proto.getTokenPrice = function getTokenPrice(token, otherToken) {
// Case when neither of the tokens is wrapped.
if (this.wrappedTokenIndex === -1) {
return this.pool.priceOf(token, otherToken);
}
!this.wrapper ? invariant(false, 'WRAPPER NOT SET') : void 0;
var notWrappedToken = this.wrappedTokenIndex === 0 ? this.token1 : this.token0;
var bpt = this.wrapper.underlying();
// If other token is the bpt, then use the wrapper's rate to calculate the price
if (notWrappedToken.equals(bpt)) {
return this.wrapper.priceOf(token);
}
var zeroForOtherToken = notWrappedToken.equals(token);
// Get the price of the token in terms of the other token, using both the pool and the wrapper
var poolPrice = this.pool.priceOf(zeroForOtherToken ? token : bpt, zeroForOtherToken ? bpt : otherToken);
var wrapperPrice = this.wrapper.priceOf(zeroForOtherToken ? otherToken : token);
var price = poolPrice.quote(maiaCoreSdk.CurrencyAmount.fromRawAmount(zeroForOtherToken ? token : bpt, '1')).multiply(wrapperPrice);
return new maiaCoreSdk.Price(token, otherToken, price.denominator, price.numerator);
}
/**
* Return the price of the given token in terms of the other token in the pool.
* @param token The token to return price of
* @returns The price of the given token, in terms of the other.
*/;
_proto.priceOf = function priceOf(token) {
!this.involvesToken(token) ? invariant(false, 'TOKEN') : void 0;
return token.equals(this.token0) ? this.token0Price : this.token1Price;
}
/**
* Returns the chain ID of the tokens in the pair.
*/;
/**
* Given an input amount of a token, return the computed output amount, and a pool with state updated after the trade
* @param inputAmount The input amount for which to quote the output amount
* @returns The output amount and the pool with updated state
* @throws if token is not in the pool
*/
_proto.getOutputAmount =
/*#__PURE__*/
function () {
var _getOutputAmount = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(inputAmount) {
var zeroForOne, _yield$this$pool$getO, _outputAmount2, _updatedPool, notWrappedToken, bpt, _yield$this$wrapper$g, _outputAmount3, _updatedWrapper, _yield$this$wrapper$g2, unwrappedAmount, _updatedWrapper2, _yield$this$pool$getO2, _outputAmount4, _updatedPool2, _yield$this$pool$getO3, outputAmount, updatedPool, _yield$this$wrapper$g3, wrappedAmount, updatedWrapper;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
!this.involvesToken(inputAmount.currency) ? invariant(false, 'TOKEN') : void 0;
zeroForOne = inputAmount.currency.equals(this.token0); // Case when neither of the tokens is wrapped.
if (!(this.wrappedTokenIndex === -1)) {
_context.next = 9;
break;
}
_context.next = 5;
return this.pool.getOutputAmount(inputAmount, zeroForOne ? this.token1 : this.token0);
case 5:
_yield$this$pool$getO = _context.sent;
_outputAmount2 = _yield$this$pool$getO[0];
_updatedPool = _yield$this$pool$getO[1];
return _context.abrupt("return", [_outputAmount2, new ComposableStablePool(this.token0, this.token1, _updatedPool)]);
case 9:
!this.wrapper ? invariant(false, 'WRAPPER NOT SET') : void 0;
notWrappedToken = this.wrappedTokenIndex === 0 ? this.token1 : this.token0;
bpt = this.wrapper.underlying(); // If other token is the bpt, then use the wrapper's rate to calculate the output amount
if (!notWrappedToken.equals(bpt)) {
_context.next = 19;
break;
}
_context.next = 15;
return this.wrapper.getOutputAmount(inputAmount);
case 15:
_yield$this$wrapper$g = _context.sent;
_outputAmount3 = _yield$this$wrapper$g[0];
_updatedWrapper = _yield$this$wrapper$g[1];
return _context.abrupt("return", [_outputAmount3, new ComposableStablePool(this.token0, this.token1, this.pool, _updatedWrapper)]);
case 19:
if (!notWrappedToken.equals(inputAmount.currency)) {
_context.next = 31;
break;
}
_context.next = 22;
return this.wrapper.getOutputAmount(inputAmount);
case 22:
_yield$this$wrapper$g2 = _context.sent;
unwrappedAmount = _yield$this$wrapper$g2[0];
_updatedWrapper2 = _yield$this$wrapper$g2[1];
_context.next = 27;
return this.pool.getOutputAmount(unwrappedAmount, zeroForOne ? this.token1 : this.token0);
case 27:
_yield$this$pool$getO2 = _context.sent;
_outputAmount4 = _yield$this$pool$getO2[0];
_updatedPool2 = _yield$this$pool$getO2[1];
return _context.abrupt("return", [_outputAmount4, new ComposableStablePool(this.token0, this.token1, _updatedPool2, _updatedWrapper2)]);
case 31:
_context.next = 33;
return this.pool.getOutputAmount(inputAmount, zeroForOne ? this.token1 : this.token0);
case 33:
_yield$this$pool$getO3 = _context.sent;
outputAmount = _yield$this$pool$getO3[0];
updatedPool = _yield$this$pool$getO3[1];
_context.next = 38;
return this.wrapper.getInputAmount(outputAmount);
case 38:
_yield$this$wrapper$g3 = _context.sent;
wrappedAmount = _yield$this$wrapper$g3[0];
updatedWrapper = _yield$this$wrapper$g3[1];
return _context.abrupt("return", [wrappedAmount, new ComposableStablePool(this.token0, this.token1, updatedPool, updatedWrapper)]);
case 42:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function getOutputAmount(_x) {
return _getOutputAmount.apply(this, arguments);
}
return getOutputAmount;
}()
/**
* Given an output amount of a token, return the computed input amount, and a pool with state updated after the trade
* @param _outputAmount The output amount for which to quote the input amount
* @param inputToken The token from which the input amount should correspond (defaults to BPT if not specified)
* @returns The input amount and the pool with updated state
* @throws if token is not in the pool
* @throws if inputToken is not in the pool
* @throws if token and inputToken are the same
*/
;
_proto.getInputAmount =
/*#__PURE__*/
function () {
var _getInputAmount = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_outputAmount) {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
throw Error('INVALID EXACT TOKEN OUT');
case 1:
case "end":
return _context2.stop();
}
}, _callee2);
}));
function getInputAmount(_x2) {
return _getInputAmount.apply(this, arguments);
}
return getInputAmount;
}();
_createClass(ComposableStablePool, [{
key: "pool",
get: function get() {
return this._pool;
},
set: function set(value) {
this._pool = value;
}
}, {
key: "token0Price",
get: function get() {
var _this$_token0Price;
return (_this$_token0Price = this._token0Price) != null ? _this$_token0Price : this._token0Price = this.getTokenPrice(this.token0, this.token1);
}
/**
* Returns the current mid price of the pool in terms of token1, i.e. the ratio of token0 over token1
*/
}, {
key: "token1Price",
get: function get() {
var _this$_token1Price;
return (_this$_token1Price = this._token1Price) != null ? _this$_token1Price : this._token1Price = this.getTokenPrice(this.token1, this.token0);
}
}, {
key: "chainId",
get: function get() {
return this.token0.chainId;
}
}]);
return ComposableStablePool;
}();
bignumber_js.BigNumber.config({
EXPONENTIAL_AT: [-100, 100],
ROUNDING_MODE: 1,
DECIMAL_PLACES: 18
});
var ZERO = /*#__PURE__*/bnum(0);
var ONE = /*#__PURE__*/bnum(1);
function bnum(val) {
return new bignumber_js.BigNumber(val.toString());
}
var BZERO = /*#__PURE__*/BigInt(0);
var BONE = /*#__PURE__*/BigInt(1);
var ONE$1 = /*#__PURE__*/BigInt('1000000000000000000'); // 18 decimal places
var _require = function _require(b, message) {
if (!b) throw new Error(message);
};
/**
* @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if
* it had 18 decimals.
*/
function _computeScalingFactor(tokenDecimals) {
// Tokens with more than 18 decimals are not supported.
var decimalsDifference = BigInt(18) - tokenDecimals;
return ONE$1 * Math.pow(BigInt(10), decimalsDifference);
}
/**
* @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed
* scaling or not.
*/
function _upscale(amount, scalingFactor) {
// Upscale rounding wouldn't necessarily always go in the same direction: in a swap for example the balance of
// token in should be rounded up, and that of token out rounded down. This is the only place where we round in
// the same direction for all amounts, as the impact of this rounding is expected to be minimal (and there's no
// rounding error unless `_scalingFactor()` is overriden).
return MathSol.mulDownFixed(amount, scalingFactor);
}
/**
* @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on
* whether it needed scaling or not. The result is rounded down.
*/
function _downscaleDown(amount, scalingFactor) {
return MathSol.divDownFixed(amount, scalingFactor);
}
var MathSol = /*#__PURE__*/function () {
function MathSol() {}
/**
* @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.
*/
// add(a: bigint, b: bigint): bigint {
// const c = a + b;
// // _require(c >= a, Errors.ADD_OVERFLOW);
// return c;
// }
/**
* @dev Returns the addition of two signed integers, reverting on overflow.
*/
MathSol.add = function add(a, b) {
var c = a + b;
_require(b >= 0 && c >= a || b < 0 && c < a, 'Errors.ADD_OVERFLOW');
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.
*/;
MathSol.sub = function sub(a, b) {
_require(b <= a, 'Errors.SUB_OVERFLOW');
var c = a - b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on overflow.
*/
// sub(int256 a, int256 b) internal pure returns (int256) {
// int256 c = a - b;
// // _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW);
// return c;
// }
/**
* @dev Returns the largest of two numbers of 256 bits.
*/;
MathSol.max = function max(a, b) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers of 256 bits.
*/;
MathSol.min = function min(a, b) {
return a < b ? a : b;
};
MathSol.mul = function mul(a, b) {
var c = a * b;
_require(a == BZERO || c / a == b, 'Errors.MUL_OVERFLOW');
return c;
};
MathSol.div = function div(a, b, roundUp) {
return roundUp ? this.divUp(a, b) : this.divDown(a, b);
};
MathSol.divDown = function divDown(a, b) {
_require(b != BZERO, 'Errors.ZERO_DIVISION');
return a / b;
};
MathSol.divUp = function divUp(a, b) {
_require(b != BZERO, 'Errors.ZERO_DIVISION');
if (a == BZERO) {
return BZERO;
} else {
return BONE + (a - BONE) / b;
}
};
MathSol.mulUpFixed = function mulUpFixed(a, b) {
var product = a * b;
_require(a == BZERO || product / a == b, 'Errors.MUL_OVERFLOW');
if (product == BZERO) {
return BZERO;
} else {
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return (product - BONE) / this.ONE + BONE;
}
}
// Modification: Taken from the fixed point class
// Same as divDown in Smart Contract FixedPoint.sol
;
MathSol.divDownFixed = function divDownFixed(a, b) {
_require(b != BZERO, 'Errors.ZERO_DIVISION');
if (a == BZERO) {
return BZERO;
} else {
var aInflated = a * this.ONE;
// _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
return aInflated / b;
}
}
// Modification: Taken from the fixed point class
;
MathSol.divUpFixed = function divUpFixed(a, b) {
_require(b != BZERO, 'Errors.ZERO_DIVISION');
if (a == BZERO) {
return BZERO;
} else {
var aInflated = a * this.ONE;
_require(aInflated / a == this.ONE, 'Errors.DIV_INTERNAL'); // mul overflow
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return (aInflated - BONE) / b + BONE;
}
}
// Modification: Taken from the fixed point class
;
MathSol.complementFixed = function complementFixed(x) {
return x < this.ONE ? this.ONE - x : BZERO;
}
// This is the same as mulDown in Smart Contracts FixedPoint.sol
;
MathSol.mulDownFixed = function mulDownFixed(a, b) {
var product = a * b;
_require(a == BZERO || product / a == b, 'Errors.MUL_OVERFLOW');
return product / this.ONE;
};
return MathSol;
}();
// Modification: Taken from the fixed point class
MathSol.ONE = /*#__PURE__*/BigInt('1000000000000000000'); // 18 decimal places
MathSol.MAX_POW_RELATIVE_ERROR = /*#__PURE__*/BigInt(10000);
var isSameAddress = function isSameAddress(address1, address2) {
return address.getAddress(address1) === address.getAddress(address2);
};
// normalizes its balance as if it had 18 decimals taking price rate into consideration.
var normaliseBalance = function normaliseBalance(token) {
var _token$priceRate;
return bignumber.parseFixed(token.balance, 18).mul(bignumber.parseFixed((_token$priceRate = token.priceRate) != null ? _token$priceRate : '1', 18)).div(constants.WeiPerEther).toBigInt();
};
// normalizes amount as if it had 18 decimals taking price rate into consideration.
var normaliseAmount = function normaliseAmount(amount, token) {
var _token$priceRate2;
var scalingFactor = _computeScalingFactor(BigInt(token.decimals));
return bignumber.BigNumber.from(_upscale(amount, scalingFactor).toString()).mul(bignumber.parseFixed((_token$priceRate2 = token.priceRate) != null ? _token$priceRate2 : '1', 18)).div(constants.WeiPerEther).toBigInt();
};
// denormalises amount from 18 decimals to token decimals taking price rate into consideration.
var denormaliseAmount = function denormaliseAmount(amount, token) {
var _token$priceRate3;
var amountAfterRate = amount * ONE$1 / BigInt(bignumber.parseFixed((_token$priceRate3 = token.priceRate) != null ? _token$priceRate3 : '1', 18).toString());
var scalingFactor = _computeScalingFactor(BigInt(token.decimals));
return _downscaleDown(amountAfterRate, scalingFactor);
};
(function (SwapTypes) {
SwapTypes[SwapTypes["SwapExactIn"] = 0] = "SwapExactIn";
SwapTypes[SwapTypes["SwapExactOut"] = 1] = "SwapExactOut";
})(exports.SwapTypes || (exports.SwapTypes = {}));
(function (PoolTypes) {
PoolTypes[PoolTypes["Weighted"] = 0] = "Weighted";
PoolTypes[PoolTypes["Stable"] = 1] = "Stable";
PoolTypes[PoolTypes["Element"] = 2] = "Element";
PoolTypes[PoolTypes["MetaStable"] = 3] = "MetaStable";
PoolTypes[PoolTypes["Linear"] = 4] = "Linear";
PoolTypes[PoolTypes["Gyro2"] = 5] = "Gyro2";
PoolTypes[PoolTypes["Gyro3"] = 6] = "Gyro3";
PoolTypes[PoolTypes["GyroE"] = 7] = "GyroE";
PoolTypes[PoolTypes["Fx"] = 8] = "Fx";
})(exports.PoolTypes || (exports.PoolTypes = {}));
(function (PoolFilter) {
PoolFilter["All"] = "All";
PoolFilter["Weighted"] = "Weighted";
PoolFilter["Stable"] = "Stable";
PoolFilter["MetaStable"] = "MetaStable";
PoolFilter["LiquidityBootstrapping"] = "LiquidityBootstrapping";
PoolFilter["Investment"] = "Investment";
PoolFilter["Element"] = "Element";
PoolFilter["StablePhantom"] = "StablePhantom";
PoolFilter["ComposableStable"] = "ComposableStable";
PoolFilter["Gyro2"] = "Gyro2";
PoolFilter["Gyro3"] = "Gyro3";
PoolFilter["GyroE"] = "GyroE";
// Linear Pools defined below all operate the same mathematically but have different factories and names in Subgraph
PoolFilter["AaveLinear"] = "AaveLinear";
PoolFilter["Linear"] = "Linear";
PoolFilter["EulerLinear"] = "EulerLinear";
PoolFilter["ERC4626Linear"] = "ERC4626Linear";
PoolFilter["BeefyLinear"] = "BeefyLinear";
PoolFilter["GearboxLinear"] = "GearboxLinear";
PoolFilter["MidasLinear"] = "MidasLinear";
PoolFilter["ReaperLinear"] = "ReaperLinear";
PoolFilter["SiloLinear"] = "SiloLinear";
PoolFilter["TetuLinear"] = "TetuLinear";
PoolFilter["YearnLinear"] = "YearnLinear";
PoolFilter["FX"] = "FX";
})(exports.PoolFilter || (exports.PoolFilter = {}));
/*
It is possible to compute the normalized liquidity using another function already existing at every pool type, which is the derivative of spot price after swap.
https://quark-ceres-740.notion.site/SOR-Normalized-liquidity-and-highest-liquidity-pool-d81bd3db48e5482ab2275a8eecac33b4
*/
function universalNormalizedLiquidity(derivativeSpotPriceAtZero) {
var ans = bnum(1).div(derivativeSpotPriceAtZero);
if (ans.isNaN() || ans.lt(ZERO) || !ans.isFinite()) return ZERO;
return ans;
}
/*
Swap outcome and "spot price after swap" formulas for weighted, stable and linear pools.
Amounts are represented using bigint type. Swap outcomes formulas should
match exactly those from smart contracts.
Test cases are found in poolsMathWeighted.spec.ts, poolsMathStable.spec.ts poolsMathLinear.spec.ts.
It is necessary to review whether to use MathSol operations or native +,-,\*,/ case by case. MathSol operations are able to reproduce overflows while native operations produce a much more readable code. For instance, for "spot price after swap" native operations
are preferred since in this case there are not smart contract analogs, amount limits are assumed to have been checked elsewhere, and some formulas get complicated, specially for stable pools.
*/
var AMP_PRECISION = /*#__PURE__*/BigInt(1e3);
function _calculateInvariant(amp, balances) {
/**********************************************************************************************
// invariant //
// D = invariant D^(n+1) //
// A = amplification coefficient A n^n S + D = A D n^n + ----------- //
// S = sum of balances n^n P //
// P = product of balances //
// n = number of tokens //
*********x************************************************************************************/
// Always round down, to match Vyper's arithmetic (which always truncates).
var sum = BZERO;
var numTokens = balances.length;
for (var i = 0; i < numTokens; i++) {
sum = sum + balances[i];
}
if (sum == BZERO) {
return BZERO;
}
var prevInvariant = BZERO;
var invariant = sum;
var ampTimesTotal = amp * BigInt(numTokens);
for (var _i = 0; _i < 255; _i++) {
var D_P = invariant;
for (var j = 0; j < numTokens; j++) {
// (D_P * invariant) / (balances[j] * numTokens)
D_P = MathSol.divDown(MathSol.mul(D_P, invariant), MathSol.mul(balances[j], BigInt(numTokens)));
}
prevInvariant = invariant;
invariant = MathSol.divDown(MathSol.mul(
// (ampTimesTotal * sum) / AMP_PRECISION + D_P * numTokens
MathSol.divDown(MathSol.mul(ampTimesTotal, sum), AMP_PRECISION) + MathSol.mul(D_P, BigInt(numTokens)), invariant),
// ((ampTimesTotal - _AMP_PRECISION) * invariant) / _AMP_PRECISION + (numTokens + 1) * D_P
MathSol.divDown(MathSol.mul(ampTimesTotal - AMP_PRECISION, invariant), AMP_PRECISION) + MathSol.mul(BigInt(numTokens + 1), D_P));
if (invariant > prevInvariant) {
if (invariant - prevInvariant <= 1) {
return invariant;
}
} else if (prevInvariant - invariant <= 1) {
return invariant;
}
}
throw new Error('Errors.STABLE_INVARIANT_DIDNT_CONVERGE');
}
// PairType = 'token->token'
// SwapType = 'swapExactIn'
function _calcOutGivenIn(amp, balances, tokenIndexIn, tokenIndexOut, amountIn, fee) {
amountIn = subtractFee(amountIn, fee);
var invariant = _calculateInvariant(amp, balances);
var initBalance = balances[tokenIndexIn];
balances[tokenIndexIn] = initBalance + amountIn;
var finalBalanceOut = _getTokenBalanceGivenInvariantAndAllOtherBalances(amp, balances, invariant, tokenIndexOut);
return balances[tokenIndexOut] - finalBalanceOut - BigInt(1);
}
function _calcInGivenOut(amp, balances, tokenIndexIn, tokenIndexOut, amountOut, fee) {
var invariant = _calculateInvariant(amp, balances);
balances[tokenIndexOut] = MathSol.sub(balances[tokenIndexOut], amountOut);
var finalBalanceIn = _getTokenBalanceGivenInvariantAndAllOtherBalances(amp, balances, invariant, tokenIndexIn);
var amountIn = MathSol.add(MathSol.sub(finalBalanceIn, balances[tokenIndexIn]), BigInt(1));
amountIn = addFee(amountIn, fee);
return amountIn;
}
/**
* _calcBptOutGivenExactTokensIn
* @param amp Amplification parameter in EVM Scale
* @param balances Token balances in EVM Scale normalised to 18 decimals (Should not have value for BPT token)
* @param amountsIn Token amounts in EVM Scale normalised to 18 decimals (Should not have value for BPT token)
* @param bptTotalSupply BPT total supply in EVM Scale
* @param swapFeePercentage Swap fee percentage in EVM Scale
* @returns BPT out in EVM Scale
*/
function _calcBptOutGivenExactTokensIn(amp, balances, amountsIn, bptTotalSupply, swapFeePercentage) {
// BPT out, so we round down overall.
// First loop calculates the sum of all token balances, which will be used to calculate
// the current weights of each token, relative to this sum
var sumBalances = BigInt(0);
for (var i = 0; i < balances.length; i++) {
sumBalances = sumBalances + balances[i];
}
// Calculate the weighted balance ratio without considering fees
var balanceRatiosWithFee = new Array(amountsIn.length);
// The weighted sum of token balance ratios with fee
var invariantRatioWithFees = BigInt(0);
for (var _i2 = 0; _i2 < balances.length; _i2++) {
var currentWeight = MathSol.divDownFixed(balances[_i2], sumBalances);
balanceRatiosWithFee[_i2] = MathSol.divDownFixed(balances[_i2] + amountsIn[_i2], balances[_i2]);
invariantRatioWithFees = invariantRatioWithFees + MathSol.mulDownFixed(balanceRatiosWithFee[_i2], currentWeight);
}
// Second loop calculates new amounts in, taking into account the fee on the percentage excess
var newBalances = new Array(balances.length);
for (var _i3 = 0; _i3 < balances.length; _i3++) {
var amountInWithoutFee = void 0;
// Check if the balance ratio is greater than the ideal ratio to charge fees or not
if (balanceRatiosWithFee[_i3] > invariantRatioWithFees) {
var nonTaxableAmount = MathSol.mulDownFixed(balances[_i3], invariantRatioWithFees - MathSol.ONE);
var taxableAmount = amountsIn[_i3] - nonTaxableAmount;
// No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50%
amountInWithoutFee = nonTaxableAmount + MathSol.mulDownFixed(taxableAmount, MathSol.ONE - swapFeePercentage);
} else {
amountInWithoutFee = amountsIn[_i3];
}
newBalances[_i3] = balances[_i3] + amountInWithoutFee;
}
// Get current and new invariants, taking swap fees into account
var currentInvariant = _calculateInvariant(amp, balances);
var newInvariant = _calculateInvariant(amp, newBalances);
var invariantRatio = MathSol.divDownFixed(newInvariant, currentInvariant);
// If the invariant didn't increase for any reason, we simply don't mint BPT
if (invariantRatio > MathSol.ONE) {
return MathSol.mulDownFixed(bptTotalSupply, invariantRatio - MathSol.ONE);
} else {
return BigInt(0);
}
}
/**
* _calcTokenInGivenExactBptOut
* @param amp Amplification parameter in EVM Scale
* @param balances Token balances in EVM Scale normalised to 18 decimals (Should not have value for BPT token)
* @param tokenIndexIn Index of token in (from tokens array without BPT)
* @param bptAmountOut BPT amount out in EVM scale
* @param bptTotalSupply BPT total supply in EVM Scale
* @param fee Swap fee percentage in EVM Scale
* @returns token in EVM Scale normalised to 18 decimals
*/
function _calcTokenInGivenExactBptOut(amp, balances, tokenIndexIn, bptAmountOut, bptTotalSupply, fee) {
// Token in, so we round up overall.
var currentInvariant = _calculateInvariant(amp, balances);
var newInvariant = MathSol.mulUpFixed(MathSol.divUpFixed(MathSol.add(bptTotalSupply, bptAmountOut), bptTotalSupply), currentInvariant);
// Calculate amount in without fee.
var newBalanceTokenIndex = _getTokenBalanceGivenInvariantAndAllOtherBalances(amp, balances, newInvariant, tokenIndexIn);
var amountInWithoutFee = MathSol.sub(newBalanceTokenIndex, balances[tokenIndexIn]);
// First calculate the sum of all token balances, which will be used to calculate
// the current weight of each token
var sumBalances = BigInt(0);
for (var i = 0; i < balances.length; i++) {
sumBalances = MathSol.add(sumBalances, balances[i]);
}
// We can now compute how much extra balance is being deposited
// and used in virtual swaps, and charge swap fees accordingly.
var currentWeight = MathSol.divDownFixed(balances[tokenIndexIn], sumBalances);
var taxablePercentage = MathSol.complementFixed(currentWeight);
var taxableAmount = MathSol.mulUpFixed(amountInWithoutFee, taxablePercentage);
var nonTaxableAmount = MathSol.sub(amountInWithoutFee, taxableAmount);
return MathSol.add(nonTaxableAmount, MathSol.divUpFixed(taxableAmount, MathSol.sub(MathSol.ONE, fee)));
}
/*
Flow of calculations:
amountsTokenOut -> amountsOutProportional ->
amountOutPercentageExcess -> amountOutBeforeFee -> newInvariant -> amountBPTIn
*/
function _calcBptInGivenExactTokensOut(amp, balances, amountsOut, bptTotalSupply, swapFeePercentage) {
// BPT in, so we round up overall.
// First loop calculates the sum of all token balances, which will be used to calculate
// the current weights of each token relative to this sum
var sumBalances = BigInt(0);
for (var i = 0; i < balances.length; i++) {
sumBalances = sumBalances + balances[i];
}
// Calculate the weighted balance ratio without considering fees
var balanceRatiosWithoutFee = new Array(amountsOut.length);
var invariantRatioWithoutFees = BigInt(0);
for (var _i4 = 0; _i4 < balances.length; _i4++) {
var currentWeight = MathSol.divUpFixed(balances[_i4], sumBalances);
balanceRatiosWithoutFee[_i4] = MathSol.divUpFixed(balances[_i4] - amountsOut[_i4], balances[_i4]);
invariantRatioWithoutFees = invariantRatioWithoutFees + MathSol.mulUpFixed(balanceRatiosWithoutFee[_i4], currentWeight);
}
// Second loop calculates new amounts in, taking into account the fee on the percentage excess
var newBalances = new Array(balances.length);
for (var _i5 = 0; _i5 < balances.length; _i5++) {
// Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it to
// 'token out'. This results in slightly larger price impact.
var amountOutWithFee = void 0;
if (invariantRatioWithoutFees > balanceRatiosWithoutFee[_i5]) {
var nonTaxableAmount = MathSol.mulDownFixed(balances[_i5], MathSol.complementFixed(invariantRatioWithoutFees));
var taxableAmount = amountsOut[_i5] - nonTaxableAmount;
// No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50%
amountOutWithFee = nonTaxableAmount + MathSol.divUpFixed(taxableAmount, MathSol.ONE - swapFeePercentage);
} else {
amountOutWithFee = amountsOut[_i5];
}
newBalances[_i5] = balances[_i5] - amountOutWithFee;
}
// Get current and new invariants, taking into account swap fees
var currentInvariant = _calculateInvariant(amp, balances);
var newInvariant = _calculateInvariant(amp, newBalances);
var invariantRatio = MathSol.divDownFixed(newInvariant, currentInvariant);
// return amountBPTIn
return MathSol.mulUpFixed(bptTotalSupply, MathSol.complementFixed(invariantRatio));
}
function _calcTokenOutGivenExactBptIn(amp, balances, tokenIndex, bptAmountIn, bptTotalSupply, swapFeePercentage) {
// Token out, so we round down overall.
var currentInvariant = _calculateInvariant(amp, balances);
var newInvariant = MathSol.mulUpFixed(MathSol.divUpFixed(bptTotalSupply - bptAmountIn, bptTotalSupply), currentInvariant);
// Calculate amount out without fee
var newBalanceTokenIndex = _getTokenBalanceGivenInvariantAndAllOtherBalances(amp, balances, newInvariant, tokenIndex);
var amountOutWithoutFee = balances[tokenIndex] - newBalanceTokenIndex;
// First calculate the sum of all token balances, which will be used to calculate
// the current weight of each token
var sumBalances = BigInt(0);
for (var i = 0; i < balances.length; i++) {
sumBalances = sumBalances + balances[i];
}
// We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result
// in swap fees.
var currentWeight = MathSol.divDownFixed(balances[tokenIndex], sumBalances);
var taxablePercentage = MathSol.complementFixed(currentWeight);
// Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it
// to 'token out'. This results in slightly larger price impact. Fees are rounded up.
var taxableAmount = MathSol.mulUpFixed(amountOutWithoutFee, taxablePercentage);
var nonTaxableAmount = amountOutWithoutFee - taxableAmount;
// No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50%
return nonTaxableAmount + MathSol.mulDownFixed(taxableAmount, MathSol.ONE - swapFeePercentage);
}
function _calcTokensOutGivenExactBptIn(balances, bptAmountIn, bptTotalSupply) {
/**********************************************************************************************
// exactBPTInForTokensOut //
// (per token) //
// aO = tokenAmountOut / bptIn \ //
// b = tokenBalance a0 = b * | --------------------- | //
// bptIn = bptAmountIn \ bptTotalSupply / //
// bpt = bptTotalSupply //
**********************************************************************************************/
// Since we're computing an amount out, we round down overall. This means rounding down on both the
// multiplication and division.
var bptRatio = MathSol.divDownFixed(bptAmountIn, bptTotalSupply);
var amountsOut = new Array(balances.length);
for (var i = 0; i < balances.length; i++) {
amountsOut[i] = MathSol.mulDownFixed(balances[i], bptRatio);
}
return amountsOut;
}
function _getTokenBalanceGivenInvariantAndAllOtherBalances(amp, balances, invariant, tokenIndex) {
// Rounds result up overall
var ampTimesTotal = amp * BigInt(balances.length);
var sum = balances[0];
var P_D = balances[0] * BigInt(balances.length);
for (var j = 1; j < balances.length; j++) {
P_D = MathSol.divDown(MathSol.mul(MathSol.mul(P_D, balances[j]), BigInt(balances.length)), invariant);
sum = sum + balances[j];
}
// No need to use safe math, based on the loop above `sum` is greater than or equal to `balances[tokenIndex]`
sum = sum - balances[tokenIndex];
var inv2 = MathSol.mul(invariant, invariant);
// We remove the balance fromm c by multiplying it
var c = MathSol.mul(MathSol.mul(MathSol.divUp(inv2, MathSol.mul(ampTimesTotal, P_D)), AMP_PRECISION), balances[tokenIndex]);
var b = sum + MathSol.mul(MathSol.divDown(invariant, ampTimesTotal), AMP_PRECISION);
// We iterate to find the balance
var prevTokenBalance = BZERO;
// We multiply the first iteration outside the loop with the invariant to set the value of the
// initial approximation.
var tokenBalance = MathSol.divUp(inv2 + c, invariant + b);
for (var i = 0; i < 255; i++) {
prevTokenBalance = tokenBalance;
tokenBalance = MathSol.divUp(MathSol.mul(tokenBalance, tokenBalance) + c, MathSol.mul(tokenBalance, BigInt(2)) + b - invariant);
if (tokenBalance > prevTokenBalance) {
if (tokenBalance - prevTokenBalance <= 1) {
return tokenBalance;
}
} else if (prevTokenBalance - tokenBalance <= 1) {
return tokenBalance;
}
}
throw new Error('Errors.STABLE_GET_BALANCE_DIDNT_CONVERGE');
}
function subtractFee(amount, fee) {
var feeAmount = MathSol.mulUpFixed(amount, fee);
return amount - feeAmount;
}
function addFee(amount, fee) {
return MathSol.divUpFixed(amount, MathSol.complementFixed(fee));
}
// All functions are adapted from the solidity ones to be found on:
// https://github.com/balancer-labs/balancer-core-v2/blob/master/contracts/pools/stable/StableMath.sol
// TODO: implement all up and down rounding variations
/**********************************************************************************************
// invariant //
// D = invariant to compute //
// A = amplifier n * D^2 + A * n^n * S * (n^n * P / D^(n−1)) //
// S = sum of balances ____________________________________________ //
// P = product of balances (n+1) * D + ( A * n^n − 1)* (n^n * P / D^(n−1)) //
// n = number of tokens //
**********************************************************************************************/
var AMP_PRECISION_BNUM = /*#__PURE__*/bnum(1000);
function _invariant(A, balances // balances
) {
var sum = ZERO;
var totalCoins = balances.length;
for (var i = 0; i < totalCoins; i++) {
sum = sum.plus(balances[i]);
}
if (sum.isZero()) {
return ZERO;
}
var prevInv = ZERO;
var inv = sum;
// A is passed as an ethers bignumber while maths uses bignumber.js
var AAdjusted = bnum(bignumber.formatFixed(A, 3));
var ATimesNpowN = AAdjusted.times(Math.pow(totalCoins, totalCoins)); // A*n^n
for (var _i = 0; _i < 255; _i++) {
var P_D = bnum(totalCoins).times(balances[0]);
for (var j = 1; j < totalCoins; j++) {
//P_D is rounded up
P_D = P_D.times(balances[j]).times(totalCoins).div(inv);
}
prevInv = inv;
//inv is rounded up
inv = bnum(totalCoins).times(inv).times(inv).plus(ATimesNpowN.times(sum).times(P_D)).div(bnum(totalCoins + 1).times(inv).plus(ATimesNpowN.minus(1).times(P_D)));
// Equality with the precision of 1
if (inv.gt(prevInv)) {
if (inv.minus(prevInv).lt(bnum(Math.pow(10, -18)))) {
break;
}
} else if (prevInv.minus(inv).lt(bnum(Math.pow(10, -18)))) {
break;
}
}
//Result is rounded up
return inv;
}
// Adapted from StableMath.sol, _outGivenIn()
// * Added swap fee at very first line
/**********************************************************************************************
// outGivenIn token x for y - polynomial equation to solve //
// ay = amount out to calculate //
// by = balance token out //
// y = by - ay //
// D = invariant D D^(n+1) //
// A = amplifier y^2 + ( S - ---------- - 1) * y - ------------- = 0 //
// n = number of tokens (A * n^n) A * n^2n * P //
// S = sum of final balances but y //
// P = product of final balances but y //
**********************************************************************************************/
function _exactTokenInForTokenOut(amount, poolPairData) {
// The formula below returns some dust (due to rounding errors) but when
// we input zero the output should be zero
if (amount.isZero()) return amount;
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
tokenIndexIn = poolPairData.tokenIndexIn,
tokenIndexOut = poolPairData.tokenIndexOut,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var tokenAmountIn = amount;
tokenAmountIn = tokenAmountIn.times(constants.WeiPerEther.sub(swapFee).toString()).div(constants.WeiPerEther.toString());
//Invariant is rounded up
var inv = _invariant(A, balances);
var p = inv;
var sum = ZERO;
var totalCoins = bnum(balances.length);
var n_pow_n = ONE;
var x = ZERO;
for (var i = 0; i < balances.length; i++) {
n_pow_n = n_pow_n.times(totalCoins);
if (i == tokenIndexIn) {
x = balances[i].plus(tokenAmountIn);
} else if (i != tokenIndexOut) {
x = balances[i];
} else {
continue;
}
sum = sum.plus(x);
//Round up p
p = p.times(inv).div(x);
}
//Calculate out balance
var y = _solveAnalyticalBalance(sum, inv, A, n_pow_n, p);
//Result is rounded down
// return balances[tokenIndexOut] > y ? balances[tokenIndexOut].minus(y) : 0;
return balances[tokenIndexOut].minus(y);
}
// Adapted from StableMath.sol, _inGivenOut()
// * Added swap fee at very last line
/**********************************************************************************************
// inGivenOut token x for y - polynomial equation to solve //
// ax = amount in to calculate //
// bx = balance token in //
// x = bx + ax //
// D = invariant D D^(n+1) //
// A = amplifier x^2 + ( S - ---------- - 1) * x - ------------- = 0 //
// n = number of tokens (A * n^n) A * n^2n * P //
// S = sum of final balances but x //
// P = product of final balances but x //
**********************************************************************************************/
function _tokenInForExactTokenOut(amount, poolPairData) {
// The formula below returns some dust (due to rounding errors) but when
// we input zero the output should be zero
if (amount.isZero()) return amount;
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
tokenIndexIn = poolPairData.tokenIndexIn,
tokenIndexOut = poolPairData.tokenIndexOut,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var tokenAmountOut = amount;
//Invariant is rounded up
var inv = _invariant(A, balances);
var p = inv;
var sum = ZERO;
var totalCoins = bnum(balances.length);
var n_pow_n = ONE;
var x = ZERO;
for (var i = 0; i < balances.length; i++) {
n_pow_n = n_pow_n.times(totalCoins);
if (i == tokenIndexOut) {
x = balances[i].minus(tokenAmountOut);
} else if (i != tokenIndexIn) {
x = balances[i];
} else {
continue;
}
sum = sum.plus(x);
//Round up p
p = p.times(inv).div(x);
}
//Calculate in balance
var y = _solveAnalyticalBalance(sum, inv, A, n_pow_n, p);
//Result is rounded up
return y.minus(balances[tokenIndexIn]).multipliedBy(constants.WeiPerEther.toString()).div(constants.WeiPerEther.sub(swapFee).toString());
}
/*
Flow of calculations:
amountBPTOut -> newInvariant -> (amountInProportional, amountInAfterFee) ->
amountInPercentageExcess -> amountIn
*/
function _tokenInForExactBPTOut(amount, poolPairData) {
// The formula below returns some dust (due to rounding errors) but when
// we input zero the output should be zero
if (amount.isZero()) return amount;
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
virtualBptSupply = poolPairData.virtualBptSupply,
decimalsOut = poolPairData.decimalsOut,
tokenIndexIn = poolPairData.tokenIndexIn,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var bptAmountOut = amount;
// Get current invariant
var currentInvariant = _invariant(A, balances);
// Calculate new invariant
var bnumBalanceOut = bnum(bignumber.formatFixed(virtualBptSupply, decimalsOut));
var newInvariant = bnumBalanceOut.plus(bptAmountOut).div(bnumBalanceOut).times(currentInvariant);
// First calculate the sum of all token balances which will be used to calculate
// the current weight of token
var sumBalances = bnum(0);
for (var i = 0; i < balances.length; i++) {
sumBalances = sumBalances.plus(balances[i]);
}
// get amountInAfterFee
var newBalanceTokenIndex = _getTokenBalanceGivenInvariantAndAllOtherBalances$1(A, balances, newInvariant, tokenIndexIn);
var amountInAfterFee = newBalanceTokenIndex.minus(balances[tokenIndexIn]);
// Get tokenBalancePercentageExcess
var currentWeight = balances[tokenIndexIn].div(sumBalances);
var tokenBalancePercentageExcess = bnum(1).minus(currentWeight);
// return amountIn
var bnumSwapFee = bnum(bignumber.formatFixed(swapFee, 18));
return amountInAfterFee.div(bnum(1).minus(tokenBalancePercentageExcess.times(bnumSwapFee)));
}
function _BPTInForExactTokenOut(amount, poolPairData) {
// The formula below returns some dust (due to rounding errors) but when
// we input zero the output should be zero
if (amount.isZero()) return amount;
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
virtualBptSupply = poolPairData.virtualBptSupply,
decimalsIn = poolPairData.decimalsIn,
tokenIndexOut = poolPairData.tokenIndexOut,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var tokenAmountOut = amount;
// Get current invariant
var currentInvariant = _invariant(A, balances);
// First calculate the sum of all token balances which will be used to calculate
// the current weights of each token relative to the sum of all balances
var sumBalances = bnum(0);
for (var i = 0; i < balances.length; i++) {
sumBalances = sumBalances.plus(balances[i]);
}
// Calculate the weighted balance ratio without considering fees
var currentWeight = balances[tokenIndexOut].div(sumBalances);
var tokenBalanceRatioWithoutFee = balances[tokenIndexOut].minus(tokenAmountOut).div(balances[tokenIndexOut]);
var weightedBalanceRatio = bnum(1).minus(bnum(1).minus(tokenBalanceRatioWithoutFee).times(currentWeight));
// calculate new amounts in taking into account the fee on the % excess
var tokenBalancePercentageExcess = weightedBalanceRatio.minus(tokenBalanceRatioWithoutFee).div(bnum(1).minus(tokenBalanceRatioWithoutFee));
var bnumSwapFee = bnum(bignumber.formatFixed(swapFee, 18));
var amountOutBeforeFee = tokenAmountOut.div(bnum(1).minus(bnumSwapFee.times(tokenBalancePercentageExcess)));
balances[tokenIndexOut] = balances[tokenIndexOut].minus(amountOutBeforeFee);
// get new invariant taking into account swap fees
var newInvariant = _invariant(A, balances);
// return amountBPTIn
var bnumBalanceIn = bnum(bignumber.formatFixed(virtualBptSupply, decimalsIn));
return bnumBalanceIn.times(bnum(1).minus(newInvariant.div(currentInvariant)));
}
//This function calculates the balance of a given token (tokenIndex)
// given all the other balances and the invariant
function _getTokenBalanceGivenInvariantAndAllOtherBalances$1(A, balances, inv, tokenIndex) {
var p = inv;
var sum = ZERO;
var totalCoins = balances.length;
var nPowN = ONE;
var x = ZERO;
for (var i = 0; i < totalCoins; i++) {
nPowN = nPowN.times(totalCoins);
if (i != tokenIndex) {
x = balances[i];
} else {
continue;
}
sum = sum.plus(x);
//Round up p
p = p.times(inv).div(x);
}
// Calculate token balance
return _solveAnalyticalBalance(sum, inv, A, nPowN, p);
}
//This function calcuates the analytical solution to find the balance required
function _solveAnalyticalBalance(sum, inv, A, n_pow_n, p) {
// A is passed as an ethers bignumber while maths uses bignumber.js
var oldBN_A = bnum(bignumber.formatFixed(A, 3));
//Round up p
p = p.times(inv).div(oldBN_A.times(n_pow_n).times(n_pow_n));
//Round down b
var b = sum.plus(inv.div(oldBN_A.times(n_pow_n)));
//Round up c
// let c = inv >= b
// ? inv.minus(b).plus(Math.sqrtUp(inv.minus(b).times(inv.minus(b)).plus(p.times(4))))
// : Math.sqrtUp(b.minus(inv).times(b.minus(inv)).plus(p.times(4))).minus(b.minus(inv));
var c;
if (inv.gte(b)) {
c = inv.minus(b).plus(inv.minus(b).times(inv.minus(b)).plus(p.times(4)).sqrt());
} else {
c = b.minus(inv).times(b.minus(inv)).plus(p.times(4)).sqrt().minus(b.minus(inv));
}
//Round up y
return c.div(2);
}
//////////////////////
//// These functions have been added exclusively for the SORv2
//////////////////////
function _exactTokenInForBPTOut(amount, poolPairData) {
// The formula below returns some dust (due to rounding errors) but when
// we input zero the output should be zero
if (amount.isZero()) return amount;
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
virtualBptSupply = poolPairData.virtualBptSupply,
tokenIndexIn = poolPairData.tokenIndexIn,
swapFee = poolPairData.swapFee,
decimalsOut = poolPairData.decimalsOut;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var tokenAmountIn = amount;
// Get current invariant
var currentInvariant = _invariant(A, balances);
// First calculate the sum of all token balances which will be used to calculate
// the current weights of each token relative to the sum of all balances
var sumBalances = bnum(0);
for (var i = 0; i < balances.length; i++) {
sumBalances = sumBalances.plus(balances[i]);
}
// Calculate the weighted balance ratio without considering fees
var currentWeight = balances[tokenIndexIn].div(sumBalances);
var tokenBalanceRatioWithoutFee = balances[tokenIndexIn].plus(tokenAmountIn).div(balances[tokenIndexIn]);
var weightedBalanceRatio = bnum(1).plus(tokenBalanceRatioWithoutFee.minus(bnum(1)).times(currentWeight));
// calculate new amountIn taking into account the fee on the % excess
// Percentage of the amount supplied that will be implicitly swapped for other tokens in the pool
var tokenBalancePercentageExcess = tokenBalanceRatioWithoutFee.minus(weightedBalanceRatio).div(tokenBalanceRatioWithoutFee.minus(bnum(1)));
var bnumSwapFee = bnum(bignumber.formatFixed(swapFee, 18));
var amountInAfterFee = tokenAmountIn.times(bnum(1).minus(bnumSwapFee.times(tokenBalancePercentageExcess)));
balances[tokenIndexIn] = balances[tokenIndexIn].plus(amountInAfterFee);
// get new invariant taking into account swap fees
var newInvariant = _invariant(A, balances);
var bnumBalanceOut = bnum(bignumber.formatFixed(virtualBptSupply, decimalsOut));
return bnumBalanceOut.times(newInvariant.div(currentInvariant).minus(bnum(1)));
}
/*
Flow of calculations:
amountBPTin -> newInvariant -> (amountOutProportional, amountOutBeforeFee) ->
amountOutPercentageExcess -> amountOut
*/
function _exactBPTInForTokenOut(amount, poolPairData) {
// The formula below returns some dust (due to rounding errors) but when
// we input zero the output should be zero
if (amount.isZero()) return amount;
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
tokenIndexOut = poolPairData.tokenIndexOut,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var bptAmountIn = amount;
/**********************************************************************************************
// TODO description //
**********************************************************************************************/
// Get current invariant
var currentInvariant = _invariant(A, balances);
// Calculate new invariant
var bnumBalanceIn = bnum(bignumber.formatFixed(poolPairData.virtualBptSupply, 18));
var newInvariant = bnumBalanceIn.minus(bptAmountIn).div(bnumBalanceIn).times(currentInvariant);
// First calculate the sum of all token balances which will be used to calculate
// the current weight of token
var sumBalances = bnum(0);
for (var i = 0; i < balances.length; i++) {
sumBalances = sumBalances.plus(balances[i]);
}
var newBalanceTokenIndex = _getTokenBalanceGivenInvariantAndAllOtherBalances$1(A, balances, newInvariant, tokenIndexOut);
var amountOutBeforeFee = balances[tokenIndexOut].minus(newBalanceTokenIndex);
// Calculate tokenBalancePercentageExcess
var currentWeight = balances[tokenIndexOut].div(sumBalances);
var tokenBalancePercentageExcess = bnum(1).minus(currentWeight);
var ans = amountOutBeforeFee.times(ONE.minus(tokenBalancePercentageExcess.times(swapFee.toString()).div(constants.WeiPerEther.toString())));
return ans;
}
function _poolDerivatives(A, balances, tokenIndexIn, tokenIndexOut, is_first_derivative, wrt_out) {
var totalCoins = balances.length;
var D = _invariant(A, balances);
var S = ZERO;
for (var i = 0; i < totalCoins; i++) {
if (i != tokenIndexIn && i != tokenIndexOut) {
S = S.plus(balances[i]);
}
}
var x = balances[tokenIndexIn];
var y = balances[tokenIndexOut];
// A is passed as an ethers bignumber while maths uses bignumber.js
var AAdjusted = bnum(bignumber.formatFixed(A, 3));
var a = AAdjusted.times(Math.pow(totalCoins, totalCoins)); // = ATimesNpowN
var b = S.minus(D).times(a).plus(D);
var twoaxy = bnum(2).times(a).times(x).times(y);
var partial_x = twoaxy.plus(a.times(y).times(y)).plus(b.times(y));
var partial_y = twoaxy.plus(a.times(x).times(x)).plus(b.times(x));
var ans;
if (is_first_derivative) {
ans = partial_x.div(partial_y);
} else {
var partial_xx = bnum(2).times(a).times(y);
var partial_yy = bnum(2).times(a).times(x);
var partial_xy = partial_xx.plus(partial_yy).plus(b);
var numerator = bnum(2).times(partial_x).times(partial_y).times(partial_xy).minus(partial_xx.times(partial_y.pow(2))).minus(partial_yy.times(partial_x.pow(2)));
var denominator = partial_x.pow(2).times(partial_y);
ans = numerator.div(denominator);
if (wrt_out) {
ans = ans.times(partial_y).div(partial_x);
}
}
return ans;
}
/////////
/// SpotPriceAfterSwap
/////////
function _poolDerivativesBPT(A, balances, bptSupply, tokenIndexIn, is_first_derivative, is_BPT_out, wrt_out) {
var totalCoins = balances.length;
var D = _invariant(A, balances);
var S = ZERO;
var D_P = D.div(totalCoins);
for (var i = 0; i < totalCoins; i++) {
if (i != tokenIndexIn) {
S = S.plus(balances[i]);
D_P = D_P.times(D).div(balances[i].times(totalCoins));
}
}
var x = balances[tokenIndexIn];
var alpha = bnum(A.toString()).times(Math.pow(totalCoins, totalCoins)); // = ATimesNpowN
var beta = alpha.times(S);
var gamma = AMP_PRECISION_BNUM.minus(alpha);
var partial_x = bnum(2).times(alpha).times(x).plus(beta).plus(gamma.times(D));
var minus_partial_D = D_P.times(totalCoins + 1).times(AMP_PRECISION_BNUM).minus(gamma.times(x));
var partial_D = ZERO.minus(minus_partial_D);
var ans;
if (is_first_derivative) {
ans = partial_x.div(minus_partial_D).times(bptSupply).div(D);
} else {
var partial_xx = bnum(2).times(alpha);
var partial_xD = gamma;
var n_times_nplusone = totalCoins * (totalCoins + 1);
var partial_DD = ZERO.minus(D_P.times(n_times_nplusone).div(D));
if (is_BPT_out) {
var term1 = partial_xx.times(partial_D).div(partial_x.pow(2));
var term2 = bnum(2).times(partial_xD).div(partial_x);
var term3 = partial_DD.div(partial_D);
ans = term1.minus(term2).plus(term3).times(D).div(bptSupply);
if (wrt_out) {
var D_prime = ZERO.minus(partial_x.div(partial_D));
ans = ans.div(D_prime).times(D).div(bptSupply);
}
} else {
ans = bnum(2).times(partial_xD).div(partial_D).minus(partial_DD.times(partial_x).div(partial_D.pow(2))).minus(partial_xx.div(partial_x));
if (wrt_out) {
ans = ans.times(partial_x).div(minus_partial_D).times(bptSupply).div(D);
}
}
}
return ans;
}
// PairType = 'token->token'
// SwapType = 'swapExactIn'
function _spotPriceAfterSwapExactTokenInForTokenOut(amount, poolPairData) {
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
tokenIndexIn = poolPairData.tokenIndexIn,
tokenIndexOut = poolPairData.tokenIndexOut,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
balances[tokenIndexIn] = balances[tokenIndexIn].plus(amount.times(constants.WeiPerEther.sub(swapFee).toString()).div(constants.WeiPerEther.toString()));
balances[tokenIndexOut] = balances[tokenIndexOut].minus(_exactTokenInForTokenOut(amount, poolPairData));
var ans = _poolDerivatives(A, balances, tokenIndexIn, tokenIndexOut, true, false);
ans = ONE.div(ans.times(constants.WeiPerEther.sub(swapFee).toString()).div(constants.WeiPerEther.toString()));
return ans;
}
// PairType = 'token->token'
// SwapType = 'swapExactOut'
function _spotPriceAfterSwapTokenInForExactTokenOut(amount, poolPairData) {
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
tokenIndexIn = poolPairData.tokenIndexIn,
tokenIndexOut = poolPairData.tokenIndexOut,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var _in = _tokenInForExactTokenOut(amount, poolPairData).times(constants.WeiPerEther.sub(swapFee).toString()).div(constants.WeiPerEther.toString());
balances[tokenIndexIn] = balances[tokenIndexIn].plus(_in);
balances[tokenIndexOut] = balances[tokenIndexOut].minus(amount);
var ans = _poolDerivatives(A, balances, tokenIndexIn, tokenIndexOut, true, true);
ans = ONE.div(ans.times(constants.WeiPerEther.sub(swapFee).toString()).div(constants.WeiPerEther.toString()));
return ans;
}
function _feeFactor(balances, tokenIndex, swapFee) {
var sumBalances = ZERO;
for (var i = 0; i < balances.length; i++) {
sumBalances = sumBalances.plus(balances[i]);
}
var currentWeight = balances[tokenIndex].div(sumBalances);
var tokenBalancePercentageExcess = ONE.minus(currentWeight);
return ONE.minus(tokenBalancePercentageExcess.times(swapFee.toString()).div(constants.WeiPerEther.toString()));
}
// PairType = 'token->BPT'
// SwapType = 'swapExactIn'
function _spotPriceAfterSwapExactTokenInForBPTOut(amount, poolPairData) {
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
virtualBptSupply = poolPairData.virtualBptSupply,
decimalsOut = poolPairData.decimalsOut,
tokenIndexIn = poolPairData.tokenIndexIn,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var feeFactor = _feeFactor(balances, tokenIndexIn, swapFee);
var bnumBalanceOut = bnum(bignumber.formatFixed(virtualBptSupply, decimalsOut));
balances[tokenIndexIn] = balances[tokenIndexIn].plus(amount.times(feeFactor));
bnumBalanceOut = bnumBalanceOut.plus(_exactTokenInForBPTOut(amount, poolPairData));
var ans = _poolDerivativesBPT(A, balances, bnumBalanceOut, tokenIndexIn, true, true, false);
ans = bnum(1).div(ans.times(feeFactor));
return ans;
}
// PairType = 'token->BPT'
// SwapType = 'swapExactOut'
function _spotPriceAfterSwapTokenInForExactBPTOut(amount, poolPairData) {
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
virtualBptSupply = poolPairData.virtualBptSupply,
tokenIndexIn = poolPairData.tokenIndexIn,
decimalsOut = poolPairData.decimalsOut,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var _in = _tokenInForExactBPTOut(amount, poolPairData);
var feeFactor = _feeFactor(balances, tokenIndexIn, swapFee);
balances[tokenIndexIn] = balances[tokenIndexIn].plus(_in.times(feeFactor));
var bnumBalanceOut = bnum(bignumber.formatFixed(virtualBptSupply, decimalsOut));
bnumBalanceOut = bnumBalanceOut.plus(amount);
var ans = _poolDerivativesBPT(A, balances, bnumBalanceOut, tokenIndexIn, true, true, true);
ans = ONE.div(ans.times(feeFactor));
return ans;
}
// PairType = 'BPT->token'
// SwapType = 'swapExactIn'
function _spotPriceAfterSwapExactBPTInForTokenOut(amount, poolPairData) {
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
virtualBptSupply = poolPairData.virtualBptSupply,
tokenIndexOut = poolPairData.tokenIndexOut,
swapFee = poolPairData.swapFee,
decimalsIn = poolPairData.decimalsIn;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var _out = _exactBPTInForTokenOut(amount, poolPairData);
var feeFactor = _feeFactor(balances, tokenIndexOut, swapFee);
var bnumBalanceIn = bnum(bignumber.formatFixed(virtualBptSupply, decimalsIn));
balances[tokenIndexOut] = balances[tokenIndexOut].minus(_out.div(feeFactor));
bnumBalanceIn = bnumBalanceIn.minus(amount);
var ans = _poolDerivativesBPT(A, balances, bnumBalanceIn, tokenIndexOut, true, false, false).div(feeFactor);
return ans;
}
// PairType = 'BPT->token'
// SwapType = 'swapExactOut'
function _spotPriceAfterSwapBPTInForExactTokenOut(amount, poolPairData) {
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
virtualBptSupply = poolPairData.virtualBptSupply,
decimalsIn = poolPairData.decimalsIn,
tokenIndexOut = poolPairData.tokenIndexOut,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var feeFactor = _feeFactor(balances, tokenIndexOut, swapFee);
balances[tokenIndexOut] = balances[tokenIndexOut].minus(amount.div(feeFactor));
var bnumBalanceIn = bnum(bignumber.formatFixed(virtualBptSupply, decimalsIn));
bnumBalanceIn = bnumBalanceIn.minus(_BPTInForExactTokenOut(amount, poolPairData));
var ans = _poolDerivativesBPT(A, balances, bnumBalanceIn, tokenIndexOut, true, false, true).div(feeFactor);
return ans;
}
/////////
/// Derivatives of spotPriceAfterSwap
/////////
// PairType = 'token->token'
// SwapType = 'swapExactIn'
function _derivativeSpotPriceAfterSwapExactTokenInForTokenOut(amount, poolPairData) {
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
tokenIndexIn = poolPairData.tokenIndexIn,
tokenIndexOut = poolPairData.tokenIndexOut,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
balances[tokenIndexIn] = balances[tokenIndexIn].plus(amount.times(constants.WeiPerEther.sub(swapFee).toString()).div(constants.WeiPerEther.toString()));
balances[tokenIndexOut] = balances[tokenIndexOut].minus(_exactTokenInForTokenOut(amount, poolPairData));
return _poolDerivatives(A, balances, tokenIndexIn, tokenIndexOut, false, false);
}
// PairType = 'token->token'
// SwapType = 'swapExactOut'
function _derivativeSpotPriceAfterSwapTokenInForExactTokenOut(amount, poolPairData) {
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
tokenIndexIn = poolPairData.tokenIndexIn,
tokenIndexOut = poolPairData.tokenIndexOut,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var bnumSwapFee = bnum(bignumber.formatFixed(swapFee, 18));
var _in = _tokenInForExactTokenOut(amount, poolPairData).times(bnum(1).minus(bnumSwapFee));
balances[tokenIndexIn] = balances[tokenIndexIn].plus(_in);
balances[tokenIndexOut] = balances[tokenIndexOut].minus(amount);
var feeFactor = bnum(1).minus(bnumSwapFee);
return _poolDerivatives(A, balances, tokenIndexIn, tokenIndexOut, false, true).div(feeFactor);
}
// PairType = 'token->BPT'
// SwapType = 'swapExactIn'
function _derivativeSpotPriceAfterSwapExactTokenInForBPTOut(amount, poolPairData) {
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
balanceOut = poolPairData.balanceOut,
decimalsOut = poolPairData.decimalsOut,
tokenIndexIn = poolPairData.tokenIndexIn,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var feeFactor = _feeFactor(balances, tokenIndexIn, swapFee);
balances[tokenIndexIn] = balances[tokenIndexIn].plus(amount.times(feeFactor));
var bnumBalanceOut = bnum(bignumber.formatFixed(balanceOut, decimalsOut));
bnumBalanceOut = bnumBalanceOut.plus(_exactTokenInForBPTOut(amount, poolPairData));
var ans = _poolDerivativesBPT(A, balances, bnumBalanceOut, tokenIndexIn, false, true, false);
return ans;
}
// PairType = 'token->BPT'
// SwapType = 'swapExactOut'
function _derivativeSpotPriceAfterSwapTokenInForExactBPTOut(amount, poolPairData) {
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
balanceOut = poolPairData.balanceOut,
decimalsOut = poolPairData.decimalsOut,
tokenIndexIn = poolPairData.tokenIndexIn,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var _in = _tokenInForExactBPTOut(amount, poolPairData);
var feeFactor = _feeFactor(balances, tokenIndexIn, swapFee);
balances[tokenIndexIn] = balances[tokenIndexIn].plus(_in.times(feeFactor));
var bnumBalanceOut = bnum(bignumber.formatFixed(balanceOut, decimalsOut));
bnumBalanceOut = bnumBalanceOut.plus(amount);
return _poolDerivativesBPT(A, balances, bnumBalanceOut, tokenIndexIn, false, true, true).div(feeFactor);
}
// PairType = 'BPT->token'
// SwapType = 'swapExactOut'
function _derivativeSpotPriceAfterSwapBPTInForExactTokenOut(amount, poolPairData) {
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
balanceIn = poolPairData.balanceIn,
decimalsIn = poolPairData.decimalsIn,
tokenIndexOut = poolPairData.tokenIndexOut,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var _in = _BPTInForExactTokenOut(amount, poolPairData);
var feeFactor = _feeFactor(balances, tokenIndexOut, swapFee);
balances[tokenIndexOut] = balances[tokenIndexOut].minus(amount.div(feeFactor));
var bnumBalanceIn = bnum(bignumber.formatFixed(balanceIn, decimalsIn));
bnumBalanceIn = bnumBalanceIn.minus(_in);
var ans = _poolDerivativesBPT(A, balances, bnumBalanceIn, tokenIndexOut, false, false, true);
return ans.div(feeFactor.pow(2));
}
// PairType = 'BPT->token'
// SwapType = 'swapExactIn'
function _derivativeSpotPriceAfterSwapExactBPTInForTokenOut(amount, poolPairData) {
var amp = poolPairData.amp,
allBalances = poolPairData.allBalances,
balanceIn = poolPairData.balanceIn,
decimalsIn = poolPairData.decimalsIn,
tokenIndexOut = poolPairData.tokenIndexOut,
swapFee = poolPairData.swapFee;
var balances = [].concat(allBalances);
var n = balances.length;
var A = amp.div(Math.pow(n, n - 1));
var _out = _exactBPTInForTokenOut(amount, poolPairData);
var feeFactor = _feeFactor(balances, tokenIndexOut, swapFee);
balances[tokenIndexOut] = balances[tokenIndexOut].minus(_out.div(feeFactor));
var bnumBalanceIn = bnum(bignumber.formatFixed(balanceIn, decimalsIn));
bnumBalanceIn = bnumBalanceIn.minus(amount);
var ans = _poolDerivativesBPT(A, balances, bnumBalanceIn, tokenIndexOut, false, false, false);
return ans.div(feeFactor);
}
var PairTypes;
(function (PairTypes) {
PairTypes[PairTypes["BptToToken"] = 0] = "BptToToken";
PairTypes[PairTypes["TokenToBpt"] = 1] = "TokenToBpt";
PairTypes[PairTypes["TokenToToken"] = 2] = "TokenToToken";
})(PairTypes || (PairTypes = {}));
var PhantomStablePool = /*#__PURE__*/function () {
function PhantomStablePool(id, address, amp, swapFee, totalShares, tokens, tokensList) {
this.poolType = exports.PoolTypes.MetaStable;
this.ALMOST_ONE = bignumber.parseFixed('0.99', 18);
this.id = id;
this.address = address;
this.amp = bignumber.BigNumber.from(amp);
this.swapFee = bignumber.BigNumber.from(swapFee);
this.totalShares = bignumber.BigNumber.from(totalShares);
this.tokens = tokens;
this.tokensList = tokensList;
}
PhantomStablePool.fromPool = function fromPool(pool) {
if (!pool.amp) throw new Error('PhantomStablePool missing amp factor');
return new PhantomStablePool(pool.id, pool.address, pool.amp, pool.swapFee, pool.totalShares, pool.tokens, pool.tokensList);
}
// Remove BPT from Balances and update indices
;
PhantomStablePool.removeBPT = function removeBPT(poolPairData) {
var poolPairDataNoBpt = cloneDeep(poolPairData);
var bptIndex = poolPairData.bptIndex;
if (bptIndex != -1) {
poolPairDataNoBpt.allBalances.splice(bptIndex, 1);
poolPairDataNoBpt.allBalancesScaled.splice(bptIndex, 1);
if (bptIndex < poolPairData.tokenIndexIn) poolPairDataNoBpt.tokenIndexIn -= 1;
if (bptIndex < poolPairData.tokenIndexOut) poolPairDataNoBpt.tokenIndexOut -= 1;
}
return poolPairDataNoBpt;
};
var _proto = PhantomStablePool.prototype;
_proto.parsePoolPairData = function parsePoolPairData(tokenIn, tokenOut) {
var tokenIndexIn = this.tokens.findIndex(function (t) {
return address.getAddress(t.address) === address.getAddress(tokenIn);
});
if (tokenIndexIn < 0) throw 'Pool does not contain tokenIn';
var tI = this.tokens[tokenIndexIn];
var balanceIn = bnum(tI.balance).times(bnum(tI.priceRate)).dp(tI.decimals).toString();
var decimalsIn = tI.decimals;
var tokenInPriceRate = bignumber.parseFixed(tI.priceRate, 18);
var tokenIndexOut = this.tokens.findIndex(function (t) {
return address.getAddress(t.address) === address.getAddress(tokenOut);
});
if (tokenIndexOut < 0) throw 'Pool does not contain tokenOut';
var tO = this.tokens[tokenIndexOut];
var balanceOut = bnum(tO.balance).times(bnum(tO.priceRate)).dp(tO.decimals).toString();
var decimalsOut = tO.decimals;
var tokenOutPriceRate = bignumber.parseFixed(tO.priceRate, 18);
// Get all token balances
var allBalances = this.tokens.map(function (_ref) {
var balance = _ref.balance,
priceRate = _ref.priceRate;
return bnum(balance).times(bnum(priceRate));
});
var allBalancesScaled = this.tokens.map(function (_ref2) {
var balance = _ref2.balance,
priceRate = _ref2.priceRate;
return bignumber.parseFixed(balance, 18).mul(bignumber.parseFixed(priceRate, 18)).div(constants.WeiPerEther);
});
// Phantom pools allow trading between token and pool BPT
var pairType;
if (isSameAddress(tokenIn, this.address)) {
pairType = PairTypes.BptToToken;
} else if (isSameAddress(tokenOut, this.address)) {
pairType = PairTypes.TokenToBpt;
} else {
pairType = PairTypes.TokenToToken;
}
var bptIndex = this.tokensList.indexOf(this.address);
// VirtualBPTSupply must be used for the maths
var virtualBptSupply = this.totalShares;
var poolPairData = {
id: this.id,
address: this.address,
poolType: this.poolType,
pairType: pairType,
bptIndex: bptIndex,
tokenIn: tokenIn,
tokenOut: tokenOut,
balanceIn: bignumber.parseFixed(balanceIn, decimalsIn),
balanceOut: bignumber.parseFixed(balanceOut, decimalsOut),
swapFee: this.swapFee,
allBalances: allBalances,
allBalancesScaled: allBalancesScaled,
amp: this.amp,
tokenIndexIn: tokenIndexIn,
tokenIndexOut: tokenIndexOut,
decimalsIn: Number(decimalsIn),
decimalsOut: Number(decimalsOut),
tokenInPriceRate: tokenInPriceRate,
tokenOutPriceRate: tokenOutPriceRate,
virtualBptSupply: virtualBptSupply
};
return PhantomStablePool.removeBPT(poolPairData);
};
_proto.getNormalizedLiquidity = function getNormalizedLiquidity(poolPairData) {
return universalNormalizedLiquidity(this._derivativeSpotPriceAfterSwapExactTokenInForTokenOut(poolPairData, ZERO));
};
_proto.getLimitAmountSwap = function getLimitAmountSwap(poolPairData, swapType) {
// PoolPairData is using balances that have already been exchanged so need to convert back
if (swapType === exports.SwapTypes.SwapExactIn) {
// Return max valid amount of tokenIn
// As an approx - use almost the total balance of token out as we can add any amount of tokenIn and expect some back
return bnum(bignumber.formatFixed(poolPairData.balanceOut.mul(this.ALMOST_ONE).div(poolPairData.tokenOutPriceRate), poolPairData.decimalsOut));
} else {
// Return max amount of tokenOut - approx is almost all balance
return bnum(bignumber.formatFixed(poolPairData.balanceOut.mul(this.ALMOST_ONE).div(poolPairData.tokenOutPriceRate), poolPairData.decimalsOut));
}
}
// Updates the balance of a given token for the pool
;
_proto.updateTokenBalanceForPool = function updateTokenBalanceForPool(token, newBalance) {
// token is underlying in the pool
var T = this.tokens.find(function (t) {
return isSameAddress(t.address, token);
});
if (!T) throw Error('Pool does not contain this token');
// update total shares with BPT balance diff
if (isSameAddress(this.address, token)) {
var parsedTokenBalance = bignumber.parseFixed(T.balance, T.decimals);
var diff = parsedTokenBalance.sub(newBalance);
var newTotalShares = this.totalShares.add(diff);
this.updateTotalShares(newTotalShares);
}
// update token balance with new balance
T.balance = bignumber.formatFixed(newBalance, T.decimals);
};
_proto.updateTotalShares = function updateTotalShares(newTotalShares) {
this.totalShares = newTotalShares;
};
_proto._exactTokenInForTokenOut = function _exactTokenInForTokenOut(poolPairData, amount) {
try {
// This code assumes that decimalsIn and decimalsOut is 18
if (amount.isZero()) return ZERO;
// All values should use 1e18 fixed point
// i.e. 1USDC => 1e18 not 1e6
// In Phantom Pools every time there is a swap (token per token, bpt per token or token per bpt), we substract the fee from the amount in
var amtWithFeeEvm = this.subtractSwapFeeAmount(bignumber.parseFixed(amount.dp(18).toString(), 18), poolPairData.swapFee);
var amountConvertedEvm = amtWithFeeEvm.mul(poolPairData.tokenInPriceRate).div(constants.WeiPerEther);
var returnEvm;
if (poolPairData.pairType === PairTypes.TokenToBpt) {
var amountsInBigInt = Array(poolPairData.allBalancesScaled.length).fill(BigInt(0));
amountsInBigInt[poolPairData.tokenIndexIn] = amountConvertedEvm.toBigInt();
returnEvm = _calcBptOutGivenExactTokensIn(this.amp.toBigInt(), poolPairData.allBalancesScaled.map(function (b) {
return b.toBigInt();
}), amountsInBigInt, poolPairData.virtualBptSupply.toBigInt(), BigInt(0));
} else if (poolPairData.pairType === PairTypes.BptToToken) {
returnEvm = _calcTokenOutGivenExactBptIn(this.amp.toBigInt(), poolPairData.allBalancesScaled.map(function (b) {
return b.toBigInt();
}), poolPairData.tokenIndexOut, amountConvertedEvm.toBigInt(), poolPairData.virtualBptSupply.toBigInt(), BigInt(0));
} else {
returnEvm = _calcOutGivenIn(this.amp.toBigInt(), poolPairData.allBalancesScaled.map(function (b) {
return b.toBigInt();
}), poolPairData.tokenIndexIn, poolPairData.tokenIndexOut, amountConvertedEvm.toBigInt(), BigInt(0));
}
var returnEvmWithRate = bignumber.BigNumber.from(returnEvm).mul(constants.WeiPerEther).div(poolPairData.tokenOutPriceRate);
// Return human scaled
return bnum(bignumber.formatFixed(returnEvmWithRate, 18));
} catch (err) {
// console.error(`PhantomStable _evmoutGivenIn: ${err.message}`);
return ZERO;
}
};
_proto._tokenInForExactTokenOut = function _tokenInForExactTokenOut(poolPairData, amount) {
try {
// This code assumes that decimalsIn and decimalsOut is 18
if (amount.isZero()) return ZERO;
// All values should use 1e18 fixed point
// i.e. 1USDC => 1e18 not 1e6
var amountConvertedEvm = bignumber.parseFixed(amount.dp(18).toString(), 18).mul(poolPairData.tokenOutPriceRate).div(constants.WeiPerEther);
var returnEvm;
if (poolPairData.pairType === PairTypes.TokenToBpt) {
returnEvm = _calcTokenInGivenExactBptOut(this.amp.toBigInt(), poolPairData.allBalancesScaled.map(function (b) {
return b.toBigInt();
}), poolPairData.tokenIndexIn, amountConvertedEvm.toBigInt(), poolPairData.virtualBptSupply.toBigInt(), BigInt(0));
} else if (poolPairData.pairType === PairTypes.BptToToken) {
var amountsOutBigInt = Array(poolPairData.allBalancesScaled.length).fill(BigInt(0));
amountsOutBigInt[poolPairData.tokenIndexOut] = amountConvertedEvm.toBigInt();
returnEvm = _calcBptInGivenExactTokensOut(this.amp.toBigInt(), poolPairData.allBalancesScaled.map(function (b) {
return b.toBigInt();
}), amountsOutBigInt, poolPairData.virtualBptSupply.toBigInt(), BigInt(0) // Fee is handled below
);
} else {
returnEvm = _calcInGivenOut(this.amp.toBigInt(), poolPairData.allBalancesScaled.map(function (b) {
return b.toBigInt();
}), poolPairData.tokenIndexIn, poolPairData.tokenIndexOut, amountConvertedEvm.toBigInt(), BigInt(0) // Fee is handled below
);
}
// In Phantom Pools every time there is a swap (token per token, bpt per token or token per bpt), we substract the fee from the amount in
var returnEvmWithRate = bignumber.BigNumber.from(returnEvm).mul(constants.WeiPerEther).div(poolPairData.tokenInPriceRate);
var returnEvmWithFee = this.addSwapFeeAmount(returnEvmWithRate, poolPairData.swapFee);
// return human number
return bnum(bignumber.formatFixed(returnEvmWithFee, 18));
} catch (err) {
// console.error(`PhantomStable _evminGivenOut: ${err.message}`)
return ZERO;
}
}
/**
* _calcTokensOutGivenExactBptIn
* @param _bptAmountIn EVM scale.
* @returns EVM scale.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
;
_proto._calcTokensOutGivenExactBptIn = function _calcTokensOutGivenExactBptIn(_bptAmountIn) {
// PhantomStables can only be exited by using BPT > token swaps
throw new Error('PhantomPool does not have exit pool (_calcTokensOutGivenExactBptIn).');
}
/**
* _calcBptOutGivenExactTokensIn
* @param _amountsIn EVM Scale
* @returns EVM Scale
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
;
_proto._calcBptOutGivenExactTokensIn = function _calcBptOutGivenExactTokensIn(_amountsIn) {
// PhantomStables can only be joined by using token > BPT swaps
throw new Error('PhantomPool does not have join pool (_calcBptOutGivenExactTokensIn).');
}
// this is the multiplicative inverse of the derivative of _exactTokenInForTokenOut
;
_proto._spotPriceAfterSwapExactTokenInForTokenOut = function _spotPriceAfterSwapExactTokenInForTokenOut$1(poolPairData, amount) {
var priceRateIn = bnum(bignumber.formatFixed(poolPairData.tokenInPriceRate, 18));
var priceRateOut = bnum(bignumber.formatFixed(poolPairData.tokenOutPriceRate, 18));
var amountConverted = amount.times(bnum(bignumber.formatFixed(poolPairData.tokenInPriceRate, 18)));
var result;
if (poolPairData.pairType === PairTypes.TokenToBpt) {
result = _spotPriceAfterSwapExactTokenInForBPTOut(amountConverted, poolPairData);
} else if (poolPairData.pairType === PairTypes.BptToToken) {
result = _spotPriceAfterSwapExactBPTInForTokenOut(amountConverted, poolPairData);
} else {
result = _spotPriceAfterSwapExactTokenInForTokenOut(amountConverted, poolPairData);
}
return result.div(priceRateIn).times(priceRateOut);
}
// this is the multiplicative inverse of the derivative of _exactTokenInForTokenOut
;
_proto._spotPriceExactTokenInForTokenOut = function _spotPriceExactTokenInForTokenOut(poolPairData) {
var priceRateIn = bnum(bignumber.formatFixed(poolPairData.tokenInPriceRate, 18));
var priceRateOut = bnum(bignumber.formatFixed(poolPairData.tokenOutPriceRate, 18));
var result;
if (poolPairData.pairType === PairTypes.TokenToBpt) {
result = _spotPriceAfterSwapExactTokenInForBPTOut(ZERO, poolPairData);
} else if (poolPairData.pairType === PairTypes.BptToToken) {
result = _spotPriceAfterSwapExactBPTInForTokenOut(ZERO, poolPairData);
} else {
result = _spotPriceAfterSwapExactTokenInForTokenOut(ZERO, poolPairData);
}
return result.div(priceRateIn).times(priceRateOut);
}
// this is the derivative of _tokenInForExactTokenOut
;
_proto._spotPriceAfterSwapTokenInForExactTokenOut = function _spotPriceAfterSwapTokenInForExactTokenOut$1(poolPairData, amount) {
var priceRateIn = bnum(bignumber.formatFixed(poolPairData.tokenInPriceRate, 18));
var priceRateOut = bnum(bignumber.formatFixed(poolPairData.tokenOutPriceRate, 18));
var amountConverted = amount.times(bignumber.formatFixed(poolPairData.tokenOutPriceRate, 18));
var result;
if (poolPairData.pairType === PairTypes.TokenToBpt) {
result = _spotPriceAfterSwapTokenInForExactBPTOut(amountConverted, poolPairData);
} else if (poolPairData.pairType === PairTypes.BptToToken) {
result = _spotPriceAfterSwapBPTInForExactTokenOut(amountConverted, poolPairData);
} else {
result = _spotPriceAfterSwapTokenInForExactTokenOut(amountConverted, poolPairData);
}
return result.div(priceRateIn).times(priceRateOut);
};
_proto._derivativeSpotPriceAfterSwapExactTokenInForTokenOut = function _derivativeSpotPriceAfterSwapExactTokenInForTokenOut$1(poolPairData, amount) {
var priceRateOut = bnum(bignumber.formatFixed(poolPairData.tokenOutPriceRate, 18));
var amountConverted = amount.times(bignumber.formatFixed(poolPairData.tokenInPriceRate, 18));
var result;
if (poolPairData.pairType === PairTypes.TokenToBpt) {
result = _derivativeSpotPriceAfterSwapExactTokenInForBPTOut(amountConverted, poolPairData);
} else if (poolPairData.pairType === PairTypes.BptToToken) {
result = _derivativeSpotPriceAfterSwapExactBPTInForTokenOut(amountConverted, poolPairData);
} else {
result = _derivativeSpotPriceAfterSwapExactTokenInForTokenOut(amountConverted, poolPairData);
}
return result.times(priceRateOut);
};
_proto._derivativeSpotPriceAfterSwapTokenInForExactTokenOut = function _derivativeSpotPriceAfterSwapTokenInForExactTokenOut$1(poolPairData, amount) {
var priceRateIn = bnum(bignumber.formatFixed(poolPairData.tokenInPriceRate, 18));
var priceRateOut = bnum(bignumber.formatFixed(poolPairData.tokenOutPriceRate, 18));
var amountConverted = amount.times(bignumber.formatFixed(poolPairData.tokenOutPriceRate, 18));
var result;
if (poolPairData.pairType === PairTypes.TokenToBpt) {
result = _derivativeSpotPriceAfterSwapTokenInForExactBPTOut(amountConverted, poolPairData);
} else if (poolPairData.pairType === PairTypes.BptToToken) {
result = _derivativeSpotPriceAfterSwapBPTInForExactTokenOut(amountConverted, poolPairData);
} else {
result = _derivativeSpotPriceAfterSwapTokenInForExactTokenOut(amountConverted, poolPairData);
}
return result.div(priceRateIn).times(priceRateOut).times(priceRateOut);
};
_proto.subtractSwapFeeAmount = function subtractSwapFeeAmount(amount, swapFee) {
// https://github.com/balancer-labs/balancer-v2-monorepo/blob/c18ff2686c61a8cbad72cdcfc65e9b11476fdbc3/pkg/pool-utils/contracts/BasePool.sol#L466
var feeAmount = amount.mul(swapFee).add(constants.WeiPerEther.sub(1)).div(constants.WeiPerEther);
return amount.sub(feeAmount);
};
_proto.addSwapFeeAmount = function addSwapFeeAmount(amount, swapFee) {
// https://github.com/balancer-labs/balancer-v2-monorepo/blob/c18ff2686c61a8cbad72cdcfc65e9b11476fdbc3/pkg/pool-utils/contracts/BasePool.sol#L458
var feeAmount = constants.WeiPerEther.sub(swapFee);
return amount.mul(constants.WeiPerEther).add(feeAmount.sub(1)).div(feeAmount);
};
return PhantomStablePool;
}();
PhantomStablePool.AMP_DECIMALS = 3;
var ComposableStablePool$1 = /*#__PURE__*/function (_PhantomStablePool) {
_inheritsLoose(ComposableStablePool, _PhantomStablePool);
function ComposableStablePool(id, address, amp, swapFee, totalShares, tokens, tokensList) {
return _PhantomStablePool.call(this, id, address, amp, swapFee, totalShares, tokens, tokensList) || this;
}
ComposableStablePool.fromPool = function fromPool(pool) {
if (!pool.amp) throw new Error('ComposableStablePool missing amp factor');
return new ComposableStablePool(pool.id, pool.address, pool.amp, pool.swapFee, pool.totalShares, pool.tokens, pool.tokensList);
};
var _proto = ComposableStablePool.prototype;
_proto._exactTokenInForTokenOut = function _exactTokenInForTokenOut(poolPairData, amount) {
try {
// balances and amounts must be normalized to 1e18 fixed point - e.g. 1USDC => 1e18 not 1e6
// takes price rate into account
if (amount.isZero()) return ZERO;
var amountConvertedEvm = bignumber.parseFixed(amount.dp(18).toString(), 18).mul(poolPairData.tokenInPriceRate).div(constants.WeiPerEther);
var returnEvm;
if (poolPairData.pairType === PairTypes.TokenToBpt) {
var amountsInBigInt = Array(poolPairData.allBalancesScaled.length).fill(BigInt(0));
amountsInBigInt[poolPairData.tokenIndexIn] = amountConvertedEvm.toBigInt();
returnEvm = _calcBptOutGivenExactTokensIn(this.amp.toBigInt(), poolPairData.allBalancesScaled.map(function (b) {
return b.toBigInt();
}), amountsInBigInt, poolPairData.virtualBptSupply.toBigInt(), poolPairData.swapFee.toBigInt());
} else if (poolPairData.pairType === PairTypes.BptToToken) {
returnEvm = _calcTokenOutGivenExactBptIn(this.amp.toBigInt(), poolPairData.allBalancesScaled.map(function (b) {
return b.toBigInt();
}), poolPairData.tokenIndexOut, amountConvertedEvm.toBigInt(), poolPairData.virtualBptSupply.toBigInt(), poolPairData.swapFee.toBigInt());
} else {
returnEvm = _calcOutGivenIn(this.amp.toBigInt(), poolPairData.allBalancesScaled.map(function (b) {
return b.toBigInt();
}), poolPairData.tokenIndexIn, poolPairData.tokenIndexOut, amountConvertedEvm.toBigInt(), poolPairData.swapFee.toBigInt());
}
var returnEvmWithRate = bignumber.BigNumber.from(returnEvm).mul(constants.WeiPerEther).div(poolPairData.tokenOutPriceRate);
// Return human scaled
return bnum(bignumber.formatFixed(returnEvmWithRate, 18)).dp(poolPairData.decimalsOut);
} catch (err) {
// console.error(`PhantomStable _evmoutGivenIn: ${err.message}`);
return ZERO;
}
};
_proto._tokenInForExactTokenOut = function _tokenInForExactTokenOut(poolPairData, amount) {
try {
if (amount.isZero()) return ZERO;
// balances and amounts must be normalized to 1e18 fixed point - e.g. 1USDC => 1e18 not 1e6
// takes price rate into account
var amountConvertedEvm = bignumber.parseFixed(amount.dp(18).toString(), 18).mul(poolPairData.tokenOutPriceRate).div(constants.WeiPerEther);
var returnEvm;
if (poolPairData.pairType === PairTypes.TokenToBpt) {
returnEvm = _calcTokenInGivenExactBptOut(this.amp.toBigInt(), poolPairData.allBalancesScaled.map(function (b) {
return b.toBigInt();
}), poolPairData.tokenIndexIn, amountConvertedEvm.toBigInt(), poolPairData.virtualBptSupply.toBigInt(), poolPairData.swapFee.toBigInt());
} else if (poolPairData.pairType === PairTypes.BptToToken) {
var amountsOutBigInt = Array(poolPairData.allBalancesScaled.length).fill(BigInt(0));
amountsOutBigInt[poolPairData.tokenIndexOut] = amountConvertedEvm.toBigInt();
returnEvm = _calcBptInGivenExactTokensOut(this.amp.toBigInt(), poolPairData.allBalancesScaled.map(function (b) {
return b.toBigInt();
}), amountsOutBigInt, poolPairData.virtualBptSupply.toBigInt(), poolPairData.swapFee.toBigInt());
} else {
returnEvm = _calcInGivenOut(this.amp.toBigInt(), poolPairData.allBalancesScaled.map(function (b) {
return b.toBigInt();
}), poolPairData.tokenIndexIn, poolPairData.tokenIndexOut, amountConvertedEvm.toBigInt(), poolPairData.swapFee.toBigInt());
}
// In Phantom Pools every time there is a swap (token per token, bpt per token or token per bpt), we substract the fee from the amount in
var returnEvmWithRate = bignumber.BigNumber.from(returnEvm).mul(constants.WeiPerEther).div(poolPairData.tokenInPriceRate);
// return human number
return bnum(bignumber.formatFixed(returnEvmWithRate, 18)).dp(poolPairData.decimalsOut);
} catch (err) {
// console.error(`PhantomStable _evminGivenOut: ${err.message}`)
return ZERO;
}
}
/**
* _calcTokensOutGivenExactBptIn
* @param bptAmountIn EVM scale.
* @returns EVM scale.
*/;
_proto._calcTokensOutGivenExactBptIn = function _calcTokensOutGivenExactBptIn$1(bptAmountIn) {
var _this = this;
// balances and amounts must be normalized to 1e18 fixed point - e.g. 1USDC => 1e18 not 1e6
// takes price rate into account
var tokensWithoutBpt = this.tokens.filter(function (t) {
return !isSameAddress(t.address, _this.address);
});
var balancesNormalised = tokensWithoutBpt.map(function (t) {
return normaliseBalance(t);
});
try {
var amountsOutNormalised = _calcTokensOutGivenExactBptIn(balancesNormalised, bptAmountIn.toBigInt(), this.totalShares.toBigInt());
// We want to return denormalised amounts. e.g. 1USDC => 1e6 not 1e18
var amountsOut = amountsOutNormalised.map(function (a, i) {
return denormaliseAmount(a, tokensWithoutBpt[i]);
});
return amountsOut.map(function (a) {
return bignumber.BigNumber.from(a);
});
} catch (err) {
return new Array(balancesNormalised.length).fill(ZERO);
}
}
/**
* _calcBptOutGivenExactTokensIn
* @param amountsIn EVM Scale (Should not have value for BPT token)
* @returns EVM Scale
*/;
_proto._calcBptOutGivenExactTokensIn = function _calcBptOutGivenExactTokensIn$1(amountsIn) {
var _this2 = this;
try {
// balances and amounts must be normalized to 1e18 fixed point - e.g. 1USDC => 1e18 not 1e6
// takes price rate into account
var amountsInNormalised = new Array(amountsIn.length).fill(BigInt(0));
var balancesNormalised = new Array(amountsIn.length).fill(BigInt(0));
this.tokens.filter(function (t) {
return !isSameAddress(t.address, _this2.address);
}).forEach(function (token, i) {
amountsInNormalised[i] = normaliseAmount(BigInt(amountsIn[i].toString()), token);
balancesNormalised[i] = normaliseBalance(token);
});
var bptAmountOut = _calcBptOutGivenExactTokensIn(this.amp.toBigInt(), balancesNormalised, amountsInNormalised, this.totalShares.toBigInt(), this.swapFee.toBigInt());
return bignumber.BigNumber.from(bptAmountOut.toString());
} catch (err) {
console.error(err);
return constants.Zero;
}
};
return ComposableStablePool;
}(PhantomStablePool);
var BalancerComposableStablePool = /*#__PURE__*/function (_BalancerPool) {
_inheritsLoose(BalancerComposableStablePool, _BalancerPool);
function BalancerComposableStablePool(id, address, amp, swapFee, totalShares, tokens, tokensList) {
return _BalancerPool.call(this, id, address, amp, swapFee, totalShares, tokens, tokensList) || this; // Additional initialization
}
// Methods similar to Uniswap's Pool class but using Balancer logic
// Method to check if a token is in the pool
var _proto = BalancerComposableStablePool.prototype;
_proto.involvesToken = function involvesToken(token) {
return this.tokens.some(function (t) {
return t.address === token.address;
});
}
/**
* Return the price of the given token in terms of another token in the pool.
* @param inputToken token to return price of
* @param outputToken token to return price in terms of
* @returns price of the given token in terms of another token in the pool
* @throws if token is not in the pool
* @throws if otherToken is not in the pool
* @throws if token and otherToken are the same
*/;
_proto.priceOf = function priceOf(inputToken, outputToken) {
!this.involvesToken(inputToken) ? invariant(false, 'TOKEN') : void 0;
!this.involvesToken(outputToken) ? invariant(false, 'OTHER_TOKEN') : void 0;
!!inputToken.equals(outputToken) ? invariant(false, 'SAME_TOKEN') : void 0;
// Get price of inputToken in terms of outputToken
var poolPairData = this.parsePoolPairData(outputToken.address, inputToken.address);
var _this$_spotPriceExact = this._spotPriceExactTokenInForTokenOut(poolPairData).shiftedBy(poolPairData.decimalsIn - poolPairData.decimalsOut).toFraction(),
numerator = _this$_spotPriceExact[0],
denominator = _this$_spotPriceExact[1];
return new maiaCoreSdk.Price(inputToken, outputToken, denominator.toString(), numerator.toString());
}
/**
* Returns the chain ID of the tokens in the pair.
*/;
/**
* Given an input amount of a token, return the computed output amount, and a pool with state updated after the trade
* @param inputAmount The input amount for which to quote the output amount
* @param outputToken The token to which the output amount should correspond (defaults to BPT if not specified)
* @returns The output amount and the pool with updated state
* @throws if token is not in the pool
* @throws if outputToken is not in the pool
* @throws if token and outputToken are the same
*/
_proto.getOutputAmount =
/*#__PURE__*/
function () {
var _getOutputAmount = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(inputAmount, outputToken) {
var poolPairData, balanceIn, balanceOut, tokenIn, tokenOut, inputAmountOldBigNumber, outputAmount, updatedPool;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
outputToken = this._checkInput(inputAmount.currency, outputToken);
poolPairData = this.parsePoolPairData(inputAmount.currency.address, outputToken.address);
balanceIn = poolPairData.balanceIn, balanceOut = poolPairData.balanceOut, tokenIn = poolPairData.tokenIn, tokenOut = poolPairData.tokenOut;
inputAmountOldBigNumber = new bignumber_js.BigNumber(inputAmount.toExact());
outputAmount = this._exactTokenInForTokenOut(poolPairData, inputAmountOldBigNumber);
updatedPool = this.updateNewPool(tokenIn, balanceIn, inputAmountOldBigNumber, poolPairData, tokenOut, balanceOut, outputAmount);
return _context.abrupt("return", [maiaCoreSdk.CurrencyAmount.fromRawAmount(outputToken, outputAmount.toString()), updatedPool]);
case 7:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function getOutputAmount(_x, _x2) {
return _getOutputAmount.apply(this, arguments);
}
return getOutputAmount;
}()
/**
* Given an output amount of a token, return the computed input amount, and a pool with state updated after the trade
* @param outputAmount The output amount for which to quote the input amount
* @param inputToken The token from which the input amount should correspond (defaults to BPT if not specified)
* @returns The input amount and the pool with updated state
* @throws if token is not in the pool
* @throws if inputToken is not in the pool
* @throws if token and inputToken are the same
*/
;
_proto.getInputAmount =
/*#__PURE__*/
function () {
var _getInputAmount = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(outputAmount, inputToken) {
var poolPairData, balanceIn, balanceOut, tokenIn, tokenOut, outputAmountOldBigNumber, inputAmount, updatedPool;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
inputToken = this._checkInput(outputAmount.currency, inputToken);
poolPairData = this.parsePoolPairData(inputToken.address, outputAmount.currency.address);
balanceIn = poolPairData.balanceIn, balanceOut = poolPairData.balanceOut, tokenIn = poolPairData.tokenIn, tokenOut = poolPairData.tokenOut;
outputAmountOldBigNumber = new bignumber_js.BigNumber(outputAmount.toExact());
inputAmount = this._tokenInForExactTokenOut(poolPairData, outputAmountOldBigNumber);
updatedPool = this.updateNewPool(tokenIn, balanceIn, inputAmount, poolPairData, tokenOut, balanceOut, outputAmountOldBigNumber);
return _context2.abrupt("return", [maiaCoreSdk.CurrencyAmount.fromRawAmount(inputToken, inputAmount.toString()), updatedPool]);
case 7:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
function getInputAmount(_x3, _x4) {
return _getInputAmount.apply(this, arguments);
}
return getInputAmount;
}() // Additional Balancer-specific methods and properties
;
BalancerComposableStablePool.clonePool = function clonePool(poolInstance) {
// Extracting the properties from the existing instance
var id = poolInstance.id,
address = poolInstance.address,
amp = poolInstance.amp,
swapFee = poolInstance.swapFee,
totalShares = poolInstance.totalShares,
tokens = poolInstance.tokens,
tokensList = poolInstance.tokensList;
// Creating a new instance with the cloned and original properties
return new BalancerComposableStablePool(id, address, amp.toString(), swapFee.toString(), totalShares.toString(), tokens, tokensList);
};
_proto.clonePool = function clonePool() {
return BalancerComposableStablePool.clonePool(this);
};
_proto._checkInput = function _checkInput(specifiedToken, returnToken) {
!this.involvesToken(specifiedToken) ? invariant(false, 'TOKEN') : void 0;
if (returnToken) {
!this.involvesToken(returnToken) ? invariant(false, 'INPUT_TOKEN') : void 0;
} else {
returnToken = new maiaCoreSdk.NativeToken(maiaCoreSdk.ROOT_CHAIN_ID, this.address, 18);
}
!!specifiedToken.equals(returnToken) ? invariant(false, 'SAME_TOKEN') : void 0;
return returnToken;
};
_proto.updateNewPool = function updateNewPool(tokenIn, balanceIn, inputAmount, poolPairData, tokenOut, balanceOut, outputAmount) {
var updatedPool = this.clonePool();
// Update balances of tokenIn and tokenOut
updatedPool.updateTokenBalanceForPool(tokenIn, balanceIn.add(bignumber.parseFixed(inputAmount.dp(poolPairData.decimalsIn).toString(), poolPairData.decimalsIn)));
updatedPool.updateTokenBalanceForPool(tokenOut, balanceOut.sub(bignumber.parseFixed(outputAmount.dp(poolPairData.decimalsOut).toString(), poolPairData.decimalsOut)));
return updatedPool;
};
_createClass(BalancerComposableStablePool, [{
key: "chainId",
get: function get() {
return maiaCoreSdk.ROOT_CHAIN_ID;
}
}]);
return BalancerComposableStablePool;
}(ComposableStablePool$1);
var _WETH;
/**
* Known WETH9 implementation addresses, used in our implementation of Ether#wrapped
*/
var WETH9 = (_WETH = {}, _WETH[1] = /*#__PURE__*/new maiaCoreSdk.NativeToken(1, '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 18, 'WETH', 'Wrapped Ether'), _WETH[3] = /*#__PURE__*/new maiaCoreSdk.NativeToken(3, '0xc778417E063141139Fce010982780140Aa0cD5Ab', 18, 'WETH', 'Wrapped Ether'), _WETH[4] = /*#__PURE__*/new maiaCoreSdk.NativeToken(4, '0xc778417E063141139Fce010982780140Aa0cD5Ab', 18, 'WETH', 'Wrapped Ether'), _WETH[5] = /*#__PURE__*/new maiaCoreSdk.NativeToken(5, '0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6', 18, 'WETH', 'Wrapped Ether'), _WETH[42] = /*#__PURE__*/new maiaCoreSdk.NativeToken(42, '0xd0A1E359811322d97991E03f863a0C30C2cF029C', 18, 'WETH', 'Wrapped Ether'), _WETH[10] = /*#__PURE__*/new maiaCoreSdk.NativeToken(10, '0x4200000000000000000000000000000000000006', 18, 'WETH', 'Wrapped Ether'), _WETH[69] = /*#__PURE__*/new maiaCoreSdk.NativeToken(69, '0x4200000000000000000000000000000000000006', 18, 'WETH', 'Wrapped Ether'), _WETH[42161] = /*#__PURE__*/new maiaCoreSdk.NativeToken(42161, '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1', 18, 'WETH', 'Wrapped Ether'), _WETH[421611] = /*#__PURE__*/new maiaCoreSdk.NativeToken(421611, '0xB47e6A5f8b33b3F17603C83a0535A9dcD7E32681', 18, 'WETH', 'Wrapped Ether'), _WETH);
/**
* Ether is the main usage of a 'native' currency, i.e. for Ethereum mainnet and all testnets
*/
var Ether = /*#__PURE__*/function (_NativeCurrency) {
_inheritsLoose(Ether, _NativeCurrency);
function Ether(chainId) {
return _NativeCurrency.call(this, chainId, 18, 'ETH', 'Ether') || this;
}
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;
};
_createClass(Ether, [{
key: "wrapped",
get: function get() {
var weth9 = WETH9[this.chainId];
!!!weth9 ? invariant(false, 'WRAPPED') : void 0;
return weth9;
}
}]);
return Ether;
}(maiaCoreSdk.NativeCurrency);
Ether._etherCache = {};
var FlywheelABI = [
{
type: "function",
name: "accrue",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "accrue",
inputs: [
{
name: "strategy",
type: "address",
internalType: "contract ERC20"
},
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "accrue",
inputs: [
{
name: "strategy",
type: "address",
internalType: "contract ERC20"
},
{
name: "user",
type: "address",
internalType: "address"
},
{
name: "secondUser",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
},
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "addStrategyForRewards",
inputs: [
{
name: "strategy",
type: "address",
internalType: "contract ERC20"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "allStrategies",
inputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "",
type: "address",
internalType: "contract ERC20"
}
],
stateMutability: "view"
},
{
type: "function",
name: "cancelOwnershipHandover",
inputs: [
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "claimRewards",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "completeOwnershipHandover",
inputs: [
{
name: "pendingOwner",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "flywheelBooster",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "contract IFlywheelBooster"
}
],
stateMutability: "view"
},
{
type: "function",
name: "flywheelRewards",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
stateMutability: "view"
},
{
type: "function",
name: "getAllStrategies",
inputs: [
],
outputs: [
{
name: "",
type: "address[]",
internalType: "contract ERC20[]"
}
],
stateMutability: "view"
},
{
type: "function",
name: "owner",
inputs: [
],
outputs: [
{
name: "result",
type: "address",
internalType: "address"
}
],
stateMutability: "view"
},
{
type: "function",
name: "ownershipHandoverExpiresAt",
inputs: [
{
name: "pendingOwner",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "result",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "renounceOwnership",
inputs: [
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "requestOwnershipHandover",
inputs: [
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "rewardToken",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
stateMutability: "view"
},
{
type: "function",
name: "rewardsAccrued",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "userRewards",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "setBooster",
inputs: [
{
name: "newBooster",
type: "address",
internalType: "contract IFlywheelBooster"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "setFlywheelRewards",
inputs: [
{
name: "newFlywheelRewards",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "strategyIds",
inputs: [
{
name: "strategy",
type: "address",
internalType: "contract ERC20"
}
],
outputs: [
{
name: "strategyIds",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "strategyIndex",
inputs: [
{
name: "strategy",
type: "address",
internalType: "contract ERC20"
}
],
outputs: [
{
name: "index",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "transferOwnership",
inputs: [
{
name: "newOwner",
type: "address",
internalType: "address"
}
],
outputs: [
],
stateMutability: "payable"
},
{
type: "function",
name: "userIndex",
inputs: [
{
name: "strategy",
type: "address",
internalType: "contract ERC20"
},
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "index",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "event",
name: "AccrueRewards",
inputs: [
{
name: "strategy",
type: "address",
indexed: true,
internalType: "contract ERC20"
},
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "rewardsDelta",
type: "uint256",
indexed: true,
internalType: "uint256"
},
{
name: "rewardsIndex",
type: "uint256",
indexed: false,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "AddStrategy",
inputs: [
{
name: "newStrategy",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "ClaimRewards",
inputs: [
{
name: "user",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "amount",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "FlywheelBoosterUpdate",
inputs: [
{
name: "newBooster",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "FlywheelRewardsUpdate",
inputs: [
{
name: "newFlywheelRewards",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "OwnershipHandoverCanceled",
inputs: [
{
name: "pendingOwner",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "OwnershipHandoverRequested",
inputs: [
{
name: "pendingOwner",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "OwnershipTransferred",
inputs: [
{
name: "oldOwner",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "newOwner",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "error",
name: "AlreadyInitialized",
inputs: [
]
},
{
type: "error",
name: "NewOwnerIsZeroAddress",
inputs: [
]
},
{
type: "error",
name: "NoHandoverRequest",
inputs: [
]
},
{
type: "error",
name: "Unauthorized",
inputs: [
]
}
];
/**
* Class to handle the Flywheel functionalities, such as claiming rewards for a staked Talos positions and for claiming bribes.
*/
var Flywheel = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
/* eslint-disable @typescript-eslint/no-empty-function */
function Flywheel() {}
/**
* Encodes the contract interaction calldata to accrue rewards for a strategy and user.
* @param strategy address of the strategy to accrue rewards for.
* @param user address of the user to accrue rewards for.
* @returns the encoded calldata for the accrue action.
*/
Flywheel.encodeAccrueCalldata = function encodeAccrueCalldata(strategy, user) {
// Check if the strategy and user address are valid.
!strategy ? invariant(false, 'Invalid strategy address') : void 0;
!(strategy !== maiaCoreSdk.ZERO_ADDRESS) ? invariant(false, 'Invalid strategy address can not be zero address') : void 0;
!user ? invariant(false, 'Invalid user address') : void 0;
!(user !== maiaCoreSdk.ZERO_ADDRESS) ? invariant(false, 'Invalid user address can not be zero address') : void 0;
// Encode the accrue action.
return Flywheel.INTERFACE.encodeFunctionData('accrue', [strategy, user]);
}
/**
* Encodes the contract interaction calldata to claim rewards from a Flywheel contract.
* @param address address of the user to claim rewards for.
* @returns the encoded calldata for the claimRewards action.
*/;
Flywheel.encodeClaimRewardsCalldata = function encodeClaimRewardsCalldata(address) {
// Check if the user address is valid.
!address ? invariant(false, 'Invalid address') : void 0;
!(address !== maiaCoreSdk.ZERO_ADDRESS) ? invariant(false, 'Invalid address can not be zero address') : void 0;
// Encode the claimRewards action.
return Flywheel.INTERFACE.encodeFunctionData('claimRewards', [address]);
};
return Flywheel;
}();
Flywheel.INTERFACE = /*#__PURE__*/new abi.Interface(FlywheelABI);
//TODO: Change this class to accomodate for the new multicall / or create a new one for it
var Multicall = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
/* eslint-disable @typescript-eslint/no-empty-function */
function Multicall() {}
Multicall.encodeMulticall = function encodeMulticall(calldatas) {
if (!Array.isArray(calldatas)) {
calldatas = [calldatas];
}
return calldatas.length === 1 ? calldatas[0] : Multicall.INTERFACE.encodeFunctionData('multicall', [calldatas]);
};
return Multicall;
}();
Multicall.INTERFACE = /*#__PURE__*/new abi.Interface(IMulticall.abi);
/**
* Validates an address and returns the parsed (checksummed) version of that address
* @param address the unchecksummed hex address
*/
function validateAndParseAddress(address$1) {
try {
return address.getAddress(address$1);
} catch (error) {
throw new Error(address$1 + " 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.");
}
/**
* Checks if an address is valid by checking 0x prefix, length === 42 and hex encoding.
* @param address the unchecksummed hex address
*/
function checkIsValidAddress(address) {
if (startsWith0xLen42HexRegex.test(address)) {
return address;
}
return undefined;
}
var Payments = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
function Payments() {}
Payments.encodeFeeBips = function encodeFeeBips(fee) {
return maiaCoreSdk.toHex(fee.multiply(10000).quotient);
};
Payments.encodeUnwrapWETH9 = function encodeUnwrapWETH9(amountMinimum, recipient, feeOptions) {
recipient = validateAndParseAddress(recipient);
if (!!feeOptions) {
var feeBips = this.encodeFeeBips(feeOptions.fee);
var feeRecipient = validateAndParseAddress(feeOptions.recipient);
return Payments.INTERFACE.encodeFunctionData('unwrapWETH9WithFee', [maiaCoreSdk.toHex(amountMinimum), recipient, feeBips, feeRecipient]);
} else {
return Payments.INTERFACE.encodeFunctionData('unwrapWETH9', [maiaCoreSdk.toHex(amountMinimum), recipient]);
}
};
Payments.encodeSweepToken = function encodeSweepToken(token, amountMinimum, recipient, feeOptions) {
recipient = validateAndParseAddress(recipient);
if (!!feeOptions) {
var feeBips = this.encodeFeeBips(feeOptions.fee);
var feeRecipient = validateAndParseAddress(feeOptions.recipient);
return Payments.INTERFACE.encodeFunctionData('sweepTokenWithFee', [token.address, maiaCoreSdk.toHex(amountMinimum), recipient, feeBips, feeRecipient]);
} else {
return Payments.INTERFACE.encodeFunctionData('sweepToken', [token.address, maiaCoreSdk.toHex(amountMinimum), recipient]);
}
};
Payments.encodeRefundETH = function encodeRefundETH() {
return Payments.INTERFACE.encodeFunctionData('refundETH');
};
return Payments;
}();
Payments.INTERFACE = /*#__PURE__*/new abi.Interface(IPeripheryPaymentsWithFee.abi);
/**
* Computes a pool address
* @param factoryAddress The Uniswap V3 factory address
* @param tokenA The first token of the pair, irrespective of sort order
* @param tokenB The second token of the pair, irrespective of sort order
* @param fee The fee tier of the pool
* @param initCodeHashManualOverride Override the init code hash used to compute the pool address if necessary
* @returns The pool address
*/
function computePoolAddress(_ref) {
var factoryAddress = _ref.factoryAddress,
tokenA = _ref.tokenA,
tokenB = _ref.tokenB,
fee = _ref.fee,
initCodeHashManualOverride = _ref.initCodeHashManualOverride;
var _ref2 = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
token0 = _ref2[0],
token1 = _ref2[1]; // does safety checks
return address.getCreate2Address(factoryAddress, solidity.keccak256(['bytes'], [abi.defaultAbiCoder.encode(['address', 'address', 'uint24'], [token0.address, token1.address, fee])]), initCodeHashManualOverride != null ? initCodeHashManualOverride : POOL_INIT_CODE_HASH);
}
var LiquidityMath = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
function LiquidityMath() {}
LiquidityMath.addDelta = function addDelta(x, y) {
if (JSBI.lessThan(y, maiaCoreSdk.ZERO)) {
return JSBI.subtract(x, JSBI.multiply(y, maiaCoreSdk.NEGATIVE_ONE));
} else {
return JSBI.add(x, y);
}
};
return LiquidityMath;
}();
var _require$1 = function _require(b, message) {
if (!b) throw new Error(message);
};
var FullMath = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
function FullMath() {}
FullMath.mulDivRoundingUp = function mulDivRoundingUp(a, b, denominator) {
var product = JSBI.multiply(a, b);
var result = JSBI.divide(product, denominator);
if (JSBI.notEqual(JSBI.remainder(product, denominator), maiaCoreSdk.ZERO)) result = JSBI.add(result, maiaCoreSdk.ONE);
return result;
}
// This is the same as mulDown in Smart Contracts FixedPoint.sol
;
FullMath.mulDownFixed = function mulDownFixed(a, b) {
var product = JSBI.multiply(a, b);
_require$1(JSBI.equal(a, maiaCoreSdk.ZERO) || JSBI.equal(JSBI.divide(product, a), b), 'Errors.MUL_OVERFLOW');
return JSBI.divide(product, maiaCoreSdk.ONE_18);
};
FullMath.mulUpFixed = function mulUpFixed(a, b) {
var product = JSBI.multiply(a, b);
_require$1(JSBI.equal(a, maiaCoreSdk.ZERO) || JSBI.equal(JSBI.divide(product, a), b), 'Errors.MUL_OVERFLOW');
if (JSBI.equal(product, maiaCoreSdk.ZERO)) {
return maiaCoreSdk.ZERO;
} else {
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return JSBI.add(JSBI.divide(JSBI.subtract(product, maiaCoreSdk.ONE), maiaCoreSdk.ONE_18), maiaCoreSdk.ONE);
}
}
// Modification: Taken from the fixed point class
// Same as divDown in Smart Contract FixedPoint.sol
;
FullMath.divDownFixed = function divDownFixed(a, b) {
_require$1(b != maiaCoreSdk.ZERO, 'Errors.ZERO_DIVISION');
if (JSBI.equal(a, maiaCoreSdk.ZERO)) {
return maiaCoreSdk.ZERO;
} else {
var aInflated = JSBI.multiply(a, maiaCoreSdk.ONE_18);
// _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
return JSBI.divide(aInflated, b);
}
}
// Modification: Taken from the fixed point class
;
FullMath.divUpFixed = function divUpFixed(a, b) {
_require$1(b != maiaCoreSdk.ZERO, 'Errors.ZERO_DIVISION');
if (JSBI.equal(a, maiaCoreSdk.ZERO)) {
return maiaCoreSdk.ZERO;
} else {
var aInflated = JSBI.multiply(a, maiaCoreSdk.ONE_18);
_require$1(JSBI.equal(JSBI.divide(aInflated, a), maiaCoreSdk.ONE_18), 'Errors.DIV_INTERNAL'); // mul overflow
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return JSBI.add(JSBI.divide(JSBI.subtract(aInflated, maiaCoreSdk.ONE), b), maiaCoreSdk.ONE);
}
};
return FullMath;
}();
var MaxUint160 = /*#__PURE__*/JSBI.subtract( /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(160)), maiaCoreSdk.ONE);
function multiplyIn256(x, y) {
var product = JSBI.multiply(x, y);
return JSBI.bitwiseAnd(product, maiaCoreSdk.MaxUint256);
}
function addIn256(x, y) {
var sum = JSBI.add(x, y);
return JSBI.bitwiseAnd(sum, maiaCoreSdk.MaxUint256);
}
var SqrtPriceMath = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
function SqrtPriceMath() {}
SqrtPriceMath.getAmount0Delta = function getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) {
if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
var _ref = [sqrtRatioBX96, sqrtRatioAX96];
sqrtRatioAX96 = _ref[0];
sqrtRatioBX96 = _ref[1];
}
var numerator1 = JSBI.leftShift(liquidity, JSBI.BigInt(96));
var numerator2 = JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96);
return roundUp ? FullMath.mulDivRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), maiaCoreSdk.ONE, sqrtRatioAX96) : JSBI.divide(JSBI.divide(JSBI.multiply(numerator1, numerator2), sqrtRatioBX96), sqrtRatioAX96);
};
SqrtPriceMath.getAmount1Delta = function getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) {
if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
var _ref2 = [sqrtRatioBX96, sqrtRatioAX96];
sqrtRatioAX96 = _ref2[0];
sqrtRatioBX96 = _ref2[1];
}
return roundUp ? FullMath.mulDivRoundingUp(liquidity, JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96), Q96) : JSBI.divide(JSBI.multiply(liquidity, JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96)), Q96);
};
SqrtPriceMath.getNextSqrtPriceFromInput = function getNextSqrtPriceFromInput(sqrtPX96, liquidity, amountIn, zeroForOne) {
!JSBI.greaterThan(sqrtPX96, maiaCoreSdk.ZERO) ? invariant(false) : void 0;
!JSBI.greaterThan(liquidity, maiaCoreSdk.ZERO) ? invariant(false) : void 0;
return zeroForOne ? this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
};
SqrtPriceMath.getNextSqrtPriceFromOutput = function getNextSqrtPriceFromOutput(sqrtPX96, liquidity, amountOut, zeroForOne) {
!JSBI.greaterThan(sqrtPX96, maiaCoreSdk.ZERO) ? invariant(false) : void 0;
!JSBI.greaterThan(liquidity, maiaCoreSdk.ZERO) ? invariant(false) : void 0;
return zeroForOne ? this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
};
SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp = function getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amount, add) {
if (JSBI.equal(amount, maiaCoreSdk.ZERO)) return sqrtPX96;
var numerator1 = JSBI.leftShift(liquidity, JSBI.BigInt(96));
if (add) {
var product = multiplyIn256(amount, sqrtPX96);
if (JSBI.equal(JSBI.divide(product, amount), sqrtPX96)) {
var denominator = addIn256(numerator1, product);
if (JSBI.greaterThanOrEqual(denominator, numerator1)) {
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator);
}
}
return FullMath.mulDivRoundingUp(numerator1, maiaCoreSdk.ONE, JSBI.add(JSBI.divide(numerator1, sqrtPX96), amount));
} else {
var _product = multiplyIn256(amount, sqrtPX96);
!JSBI.equal(JSBI.divide(_product, amount), sqrtPX96) ? invariant(false) : void 0;
!JSBI.greaterThan(numerator1, _product) ? invariant(false) : void 0;
var _denominator = JSBI.subtract(numerator1, _product);
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, _denominator);
}
};
SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown = function getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amount, add) {
if (add) {
var quotient = JSBI.lessThanOrEqual(amount, MaxUint160) ? JSBI.divide(JSBI.leftShift(amount, JSBI.BigInt(96)), liquidity) : JSBI.divide(JSBI.multiply(amount, Q96), liquidity);
return JSBI.add(sqrtPX96, quotient);
} else {
var _quotient = FullMath.mulDivRoundingUp(amount, Q96, liquidity);
!JSBI.greaterThan(sqrtPX96, _quotient) ? invariant(false) : void 0;
return JSBI.subtract(sqrtPX96, _quotient);
}
};
return SqrtPriceMath;
}();
var MAX_FEE = /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(10), /*#__PURE__*/JSBI.BigInt(6));
var SwapMath = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
function SwapMath() {}
SwapMath.computeSwapStep = function computeSwapStep(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, amountRemaining, feePips) {
var returnValues = {};
var zeroForOne = JSBI.greaterThanOrEqual(sqrtRatioCurrentX96, sqrtRatioTargetX96);
var exactIn = JSBI.greaterThanOrEqual(amountRemaining, maiaCoreSdk.ZERO);
if (exactIn) {
var amountRemainingLessFee = JSBI.divide(JSBI.multiply(amountRemaining, JSBI.subtract(MAX_FEE, JSBI.BigInt(feePips))), MAX_FEE);
returnValues.amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
if (JSBI.greaterThanOrEqual(amountRemainingLessFee, returnValues.amountIn)) {
returnValues.sqrtRatioNextX96 = sqrtRatioTargetX96;
} else {
returnValues.sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(sqrtRatioCurrentX96, liquidity, amountRemainingLessFee, zeroForOne);
}
} else {
returnValues.amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
if (JSBI.greaterThanOrEqual(JSBI.multiply(amountRemaining, maiaCoreSdk.NEGATIVE_ONE), returnValues.amountOut)) {
returnValues.sqrtRatioNextX96 = sqrtRatioTargetX96;
} else {
returnValues.sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(sqrtRatioCurrentX96, liquidity, JSBI.multiply(amountRemaining, maiaCoreSdk.NEGATIVE_ONE), zeroForOne);
}
}
var max = JSBI.equal(sqrtRatioTargetX96, returnValues.sqrtRatioNextX96);
if (zeroForOne) {
returnValues.amountIn = max && exactIn ? returnValues.amountIn : SqrtPriceMath.getAmount0Delta(returnValues.sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);
returnValues.amountOut = max && !exactIn ? returnValues.amountOut : SqrtPriceMath.getAmount1Delta(returnValues.sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);
} else {
returnValues.amountIn = max && exactIn ? returnValues.amountIn : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, returnValues.sqrtRatioNextX96, liquidity, true);
returnValues.amountOut = max && !exactIn ? returnValues.amountOut : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, returnValues.sqrtRatioNextX96, liquidity, false);
}
if (!exactIn && JSBI.greaterThan(returnValues.amountOut, JSBI.multiply(amountRemaining, maiaCoreSdk.NEGATIVE_ONE))) {
returnValues.amountOut = JSBI.multiply(amountRemaining, maiaCoreSdk.NEGATIVE_ONE);
}
if (exactIn && JSBI.notEqual(returnValues.sqrtRatioNextX96, sqrtRatioTargetX96)) {
// we didn't reach the target, so take the remainder of the maximum input as fee
returnValues.feeAmount = JSBI.subtract(amountRemaining, returnValues.amountIn);
} else {
returnValues.feeAmount = FullMath.mulDivRoundingUp(returnValues.amountIn, JSBI.BigInt(feePips), JSBI.subtract(MAX_FEE, JSBI.BigInt(feePips)));
}
return [returnValues.sqrtRatioNextX96, returnValues.amountIn, returnValues.amountOut, returnValues.feeAmount];
};
return SwapMath;
}();
var TWO = /*#__PURE__*/JSBI.BigInt(2);
var POWERS_OF_2 = /*#__PURE__*/[128, 64, 32, 16, 8, 4, 2, 1].map(function (pow) {
return [pow, JSBI.exponentiate(TWO, JSBI.BigInt(pow))];
});
function mostSignificantBit(x) {
!JSBI.greaterThan(x, maiaCoreSdk.ZERO) ? invariant(false, 'ZERO') : void 0;
!JSBI.lessThanOrEqual(x, maiaCoreSdk.MaxUint256) ? invariant(false, 'MAX') : void 0;
var msb = 0;
for (var _iterator = _createForOfIteratorHelperLoose(POWERS_OF_2), _step; !(_step = _iterator()).done;) {
var _step$value = _step.value,
power = _step$value[0],
min = _step$value[1];
if (JSBI.greaterThanOrEqual(x, min)) {
x = JSBI.signedRightShift(x, JSBI.BigInt(power));
msb += power;
}
}
return msb;
}
function mulShift(val, mulBy) {
return JSBI.signedRightShift(JSBI.multiply(val, JSBI.BigInt(mulBy)), JSBI.BigInt(128));
}
var Q32 = /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(32));
var TickMath = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
function TickMath() {}
/**
* Returns the sqrt ratio as a Q64.96 for the given tick. The sqrt ratio is computed as sqrt(1.0001)^tick
* @param tick the tick for which to compute the sqrt ratio
*/
TickMath.getSqrtRatioAtTick = function getSqrtRatioAtTick(tick) {
!(tick >= TickMath.MIN_TICK && tick <= TickMath.MAX_TICK && Number.isInteger(tick)) ? invariant(false, 'TICK') : void 0;
var absTick = tick < 0 ? tick * -1 : tick;
var ratio = (absTick & 0x1) != 0 ? JSBI.BigInt('0xfffcb933bd6fad37aa2d162d1a594001') : JSBI.BigInt('0x100000000000000000000000000000000');
if ((absTick & 0x2) != 0) ratio = mulShift(ratio, '0xfff97272373d413259a46990580e213a');
if ((absTick & 0x4) != 0) ratio = mulShift(ratio, '0xfff2e50f5f656932ef12357cf3c7fdcc');
if ((absTick & 0x8) != 0) ratio = mulShift(ratio, '0xffe5caca7e10e4e61c3624eaa0941cd0');
if ((absTick & 0x10) != 0) ratio = mulShift(ratio, '0xffcb9843d60f6159c9db58835c926644');
if ((absTick & 0x20) != 0) ratio = mulShift(ratio, '0xff973b41fa98c081472e6896dfb254c0');
if ((absTick & 0x40) != 0) ratio = mulShift(ratio, '0xff2ea16466c96a3843ec78b326b52861');
if ((absTick & 0x80) != 0) ratio = mulShift(ratio, '0xfe5dee046a99a2a811c461f1969c3053');
if ((absTick & 0x100) != 0) ratio = mulShift(ratio, '0xfcbe86c7900a88aedcffc83b479aa3a4');
if ((absTick & 0x200) != 0) ratio = mulShift(ratio, '0xf987a7253ac413176f2b074cf7815e54');
if ((absTick & 0x400) != 0) ratio = mulShift(ratio, '0xf3392b0822b70005940c7a398e4b70f3');
if ((absTick & 0x800) != 0) ratio = mulShift(ratio, '0xe7159475a2c29b7443b29c7fa6e889d9');
if ((absTick & 0x1000) != 0) ratio = mulShift(ratio, '0xd097f3bdfd2022b8845ad8f792aa5825');
if ((absTick & 0x2000) != 0) ratio = mulShift(ratio, '0xa9f746462d870fdf8a65dc1f90e061e5');
if ((absTick & 0x4000) != 0) ratio = mulShift(ratio, '0x70d869a156d2a1b890bb3df62baf32f7');
if ((absTick & 0x8000) != 0) ratio = mulShift(ratio, '0x31be135f97d08fd981231505542fcfa6');
if ((absTick & 0x10000) != 0) ratio = mulShift(ratio, '0x9aa508b5b7a84e1c677de54f3e99bc9');
if ((absTick & 0x20000) != 0) ratio = mulShift(ratio, '0x5d6af8dedb81196699c329225ee604');
if ((absTick & 0x40000) != 0) ratio = mulShift(ratio, '0x2216e584f5fa1ea926041bedfe98');
if ((absTick & 0x80000) != 0) ratio = mulShift(ratio, '0x48a170391f7dc42444e8fa2');
if (tick > 0) ratio = JSBI.divide(maiaCoreSdk.MaxUint256, ratio);
// back to Q96
return JSBI.greaterThan(JSBI.remainder(ratio, Q32), maiaCoreSdk.ZERO) ? JSBI.add(JSBI.divide(ratio, Q32), maiaCoreSdk.ONE) : JSBI.divide(ratio, Q32);
}
/**
* Returns the tick corresponding to a given sqrt ratio, s.t. #getSqrtRatioAtTick(tick) <= sqrtRatioX96
* and #getSqrtRatioAtTick(tick + 1) > sqrtRatioX96
* @param sqrtRatioX96 the sqrt ratio as a Q64.96 for which to compute the tick
*/;
TickMath.getTickAtSqrtRatio = function getTickAtSqrtRatio(sqrtRatioX96) {
!(JSBI.greaterThanOrEqual(sqrtRatioX96, TickMath.MIN_SQRT_RATIO) && JSBI.lessThan(sqrtRatioX96, TickMath.MAX_SQRT_RATIO)) ? invariant(false, 'SQRT_RATIO') : void 0;
var sqrtRatioX128 = JSBI.leftShift(sqrtRatioX96, JSBI.BigInt(32));
var msb = mostSignificantBit(sqrtRatioX128);
var r;
if (JSBI.greaterThanOrEqual(JSBI.BigInt(msb), JSBI.BigInt(128))) {
r = JSBI.signedRightShift(sqrtRatioX128, JSBI.BigInt(msb - 127));
} else {
r = JSBI.leftShift(sqrtRatioX128, JSBI.BigInt(127 - msb));
}
var log_2 = JSBI.leftShift(JSBI.subtract(JSBI.BigInt(msb), JSBI.BigInt(128)), JSBI.BigInt(64));
for (var i = 0; i < 14; i++) {
r = JSBI.signedRightShift(JSBI.multiply(r, r), JSBI.BigInt(127));
var f = JSBI.signedRightShift(r, JSBI.BigInt(128));
log_2 = JSBI.bitwiseOr(log_2, JSBI.leftShift(f, JSBI.BigInt(63 - i)));
r = JSBI.signedRightShift(r, f);
}
var log_sqrt10001 = JSBI.multiply(log_2, JSBI.BigInt('255738958999603826347141'));
var tickLow = JSBI.toNumber(JSBI.signedRightShift(JSBI.subtract(log_sqrt10001, JSBI.BigInt('3402992956809132418596140100660247210')), JSBI.BigInt(128)));
var tickHigh = JSBI.toNumber(JSBI.signedRightShift(JSBI.add(log_sqrt10001, JSBI.BigInt('291339464771989622907027621153398088495')), JSBI.BigInt(128)));
return tickLow === tickHigh ? tickLow : JSBI.lessThanOrEqual(TickMath.getSqrtRatioAtTick(tickHigh), sqrtRatioX96) ? tickHigh : tickLow;
};
return TickMath;
}();
/**
* The minimum tick that can be used on any pool.
*/
TickMath.MIN_TICK = -887272;
/**
* The maximum tick that can be used on any pool.
*/
TickMath.MAX_TICK = -TickMath.MIN_TICK;
/**
* The sqrt ratio corresponding to the minimum tick that could be used on any pool.
*/
TickMath.MIN_SQRT_RATIO = /*#__PURE__*/JSBI.BigInt('4295128739');
/**
* The sqrt ratio corresponding to the maximum tick that could be used on any pool.
*/
TickMath.MAX_SQRT_RATIO = /*#__PURE__*/JSBI.BigInt('1461446703485210103287273052203988822378723970342');
/**
* This tick data provider does not know how to fetch any tick data. It throws whenever it is required. Useful if you
* do not need to load tick data for your use case.
*/
var NoTickDataProvider = /*#__PURE__*/function () {
function NoTickDataProvider() {}
var _proto = NoTickDataProvider.prototype;
_proto.getTick = /*#__PURE__*/function () {
var _getTick = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_tick) {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
throw new Error(NoTickDataProvider.ERROR_MESSAGE);
case 1:
case "end":
return _context.stop();
}
}, _callee);
}));
function getTick(_x) {
return _getTick.apply(this, arguments);
}
return getTick;
}();
_proto.nextInitializedTickWithinOneWord = /*#__PURE__*/function () {
var _nextInitializedTickWithinOneWord = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_tick, _lte, _tickSpacing) {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
throw new Error(NoTickDataProvider.ERROR_MESSAGE);
case 1:
case "end":
return _context2.stop();
}
}, _callee2);
}));
function nextInitializedTickWithinOneWord(_x2, _x3, _x4) {
return _nextInitializedTickWithinOneWord.apply(this, arguments);
}
return nextInitializedTickWithinOneWord;
}();
return NoTickDataProvider;
}();
NoTickDataProvider.ERROR_MESSAGE = 'No tick data provider was given';
/**
* Determines if a tick list is sorted
* @param list The tick list
* @param comparator The comparator
* @returns true if sorted
*/
function isSorted(list, comparator) {
for (var i = 0; i < list.length - 1; i++) {
if (comparator(list[i], list[i + 1]) > 0) {
return false;
}
}
return true;
}
function tickComparator(a, b) {
return a.index - b.index;
}
/**
* Utility methods for interacting with sorted lists of ticks
*/
var TickList = /*#__PURE__*/function () {
/**
* Cannot be constructed
*/
function TickList() {}
TickList.validateList = function validateList(ticks, tickSpacing) {
!(tickSpacing > 0) ? invariant(false, 'TICK_SPACING_NONZERO') : void 0;
// ensure ticks are spaced appropriately
!ticks.every(function (_ref) {
var index = _ref.index;
return index % tickSpacing === 0;
}) ? invariant(false, 'TICK_SPACING') : void 0;
// ensure tick liquidity deltas sum to 0
!JSBI.equal(ticks.reduce(function (accumulator, _ref2) {
var liquidityNet = _ref2.liquidityNet;
return JSBI.add(accumulator, liquidityNet);
}, maiaCoreSdk.ZERO), maiaCoreSdk.ZERO) ? invariant(false, 'ZERO_NET') : void 0;
!isSorted(ticks, tickComparator) ? invariant(false, 'SORTED') : void 0;
};
TickList.isBelowSmallest = function isBelowSmallest(ticks, tick) {
!(ticks.length > 0) ? invariant(false, 'LENGTH') : void 0;
return tick < ticks[0].index;
};
TickList.isAtOrAboveLargest = function isAtOrAboveLargest(ticks, tick) {
!(ticks.length > 0) ? invariant(false, 'LENGTH') : void 0;
return tick >= ticks[ticks.length - 1].index;
};
TickList.getTick = function getTick(ticks, index) {
var tick = ticks[this.binarySearch(ticks, index)];
!(tick.index === index) ? invariant(false, 'NOT_CONTAINED') : void 0;
return tick;
}
/**
* Finds the largest tick in the list of ticks that is less than or equal to tick
* @param ticks list of ticks
* @param tick tick to find the largest tick that is less than or equal to tick
* @private
*/;
TickList.binarySearch = function binarySearch(ticks, tick) {
!!this.isBelowSmallest(ticks, tick) ? invariant(false, 'BELOW_SMALLEST') : void 0;
var l = 0;
var r = ticks.length - 1;
var i;
while (true) {
i = Math.floor((l + r) / 2);
if (ticks[i].index <= tick && (i === ticks.length - 1 || ticks[i + 1].index > tick)) {
return i;
}
if (ticks[i].index < tick) {
l = i + 1;
} else {
r = i - 1;
}
}
};
TickList.nextInitializedTick = function nextInitializedTick(ticks, tick, lte) {
if (lte) {
!!TickList.isBelowSmallest(ticks, tick) ? invariant(false, 'BELOW_SMALLEST') : void 0;
if (TickList.isAtOrAboveLargest(ticks, tick)) {
return ticks[ticks.length - 1];
}
var index = this.binarySearch(ticks, tick);
return ticks[index];
} else {
!!this.isAtOrAboveLargest(ticks, tick) ? invariant(false, 'AT_OR_ABOVE_LARGEST') : void 0;
if (this.isBelowSmallest(ticks, tick)) {
return ticks[0];
}
var _index = this.binarySearch(ticks, tick);
return ticks[_index + 1];
}
};
TickList.nextInitializedTickWithinOneWord = function nextInitializedTickWithinOneWord(ticks, tick, lte, tickSpacing) {
var compressed = Math.floor(tick / tickSpacing); // matches rounding in the code
if (lte) {
var wordPos = compressed >> 8;
var minimum = (wordPos << 8) * tickSpacing;
if (TickList.isBelowSmallest(ticks, tick)) {
return [minimum, false];
}
var index = TickList.nextInitializedTick(ticks, tick, lte).index;
var nextInitializedTick = Math.max(minimum, index);
return [nextInitializedTick, nextInitializedTick === index];
} else {
var _wordPos = compressed + 1 >> 8;
var maximum = ((_wordPos + 1 << 8) - 1) * tickSpacing;
if (this.isAtOrAboveLargest(ticks, tick)) {
return [maximum, false];
}
var _index2 = this.nextInitializedTick(ticks, tick, lte).index;
var _nextInitializedTick = Math.min(maximum, _index2);
return [_nextInitializedTick, _nextInitializedTick === _index2];
}
};
return TickList;
}();
var Tick = function Tick(_ref) {
var index = _ref.index,
liquidityGross = _ref.liquidityGross,
liquidityNet = _ref.liquidityNet;
!(index >= TickMath.MIN_TICK && index <= TickMath.MAX_TICK) ? invariant(false, 'TICK') : void 0;
this.index = index;
this.liquidityGross = JSBI.BigInt(liquidityGross);
this.liquidityNet = JSBI.BigInt(liquidityNet);
};
/**
* A data provider for ticks that is backed by an in-memory array of ticks.
*/
var TickListDataProvider = /*#__PURE__*/function () {
function TickListDataProvider(ticks, tickSpacing) {
var ticksMapped = ticks.map(function (t) {
return t instanceof Tick ? t : new Tick(t);
});
TickList.validateList(ticksMapped, tickSpacing);
this.ticks = ticksMapped;
}
var _proto = TickListDataProvider.prototype;
_proto.getTick = /*#__PURE__*/function () {
var _getTick = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(tick) {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", TickList.getTick(this.ticks, tick));
case 1:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function getTick(_x) {
return _getTick.apply(this, arguments);
}
return getTick;
}();
_proto.nextInitializedTickWithinOneWord = /*#__PURE__*/function () {
var _nextInitializedTickWithinOneWord = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(tick, lte, tickSpacing) {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt("return", TickList.nextInitializedTickWithinOneWord(this.ticks, tick, lte, tickSpacing));
case 1:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
function nextInitializedTickWithinOneWord(_x2, _x3, _x4) {
return _nextInitializedTickWithinOneWord.apply(this, arguments);
}
return nextInitializedTickWithinOneWord;
}();
return TickListDataProvider;
}();
/**
* By default, pools will not allow operations that require ticks.
*/
var NO_TICK_DATA_PROVIDER_DEFAULT = /*#__PURE__*/new NoTickDataProvider();
/**
* Represents a V3 pool
*/
var Pool = /*#__PURE__*/function () {
/**
* Construct a pool
* @param tokenA One of the tokens in the pool
* @param tokenB The other token in the pool
* @param fee The fee in hundredths of a bips of the input amount of every swap that is collected by the pool
* @param sqrtRatioX96 The sqrt of the current ratio of amounts of token1 to token0
* @param liquidity The current value of in range liquidity
* @param tickCurrent The current tick of the pool
* @param ticks The current state of the pool ticks or a data provider that can return tick data
*/
function Pool(tokenA, tokenB, fee, sqrtRatioX96, liquidity, tickCurrent, ticks) {
if (ticks === void 0) {
ticks = NO_TICK_DATA_PROVIDER_DEFAULT;
}
!(Number.isInteger(fee) && fee < 1000000) ? invariant(false, 'FEE') : void 0;
var tickCurrentSqrtRatioX96 = TickMath.getSqrtRatioAtTick(tickCurrent);
var nextTickSqrtRatioX96 = TickMath.getSqrtRatioAtTick(tickCurrent + 1);
!(JSBI.greaterThanOrEqual(JSBI.BigInt(sqrtRatioX96), tickCurrentSqrtRatioX96) && JSBI.lessThanOrEqual(JSBI.BigInt(sqrtRatioX96), nextTickSqrtRatioX96)) ? invariant(false, 'PRICE_BOUNDS') : void 0;
var _ref = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA];
this.token0 = _ref[0];
this.token1 = _ref[1];
this.fee = fee;
this.sqrtRatioX96 = JSBI.BigInt(sqrtRatioX96);
this.liquidity = JSBI.BigInt(liquidity);
this.tickCurrent = tickCurrent;
this.tickDataProvider = Array.isArray(ticks) ? new TickListDataProvider(ticks, TICK_SPACINGS[fee]) : ticks;
}
Pool.getAddress = function getAddress(tokenA, tokenB, fee, initCodeHashManualOverride, factoryAddressOverride) {
return computePoolAddress({
factoryAddress: factoryAddressOverride != null ? factoryAddressOverride : FACTORY_ADDRESS,
fee: fee,
tokenA: tokenA,
tokenB: tokenB,
initCodeHashManualOverride: initCodeHashManualOverride
});
}
/**
* Returns true if the token is either token0 or token1
* @param token The token to check
* @returns True if token is either token0 or token
*/;
var _proto = Pool.prototype;
_proto.involvesToken = function involvesToken(token) {
return token.equals(this.token0) || token.equals(this.token1);
}
/**
* Returns the current mid price of the pool in terms of token0, i.e. the ratio of token1 over token0
*/;
/**
* Return the price of the given token in terms of the other token in the pool.
* @param token The token to return price of
* @returns The price of the given token, in terms of the other.
*/
_proto.priceOf = function priceOf(token) {
!this.involvesToken(token) ? invariant(false, 'TOKEN') : void 0;
return token.equals(this.token0) ? this.token0Price : this.token1Price;
}
/**
* Returns the chain ID of the tokens in the pool.
*/;
/**
* Given an input amount of a token, return the computed output amount, and a pool with state updated after the trade
* @param inputAmount The input amount for which to quote the output amount
* @param sqrtPriceLimitX96 The Q64.96 sqrt price limit
* @returns The output amount and the pool with updated state
*/
_proto.getOutputAmount =
/*#__PURE__*/
function () {
var _getOutputAmount = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(inputAmount, sqrtPriceLimitX96) {
var zeroForOne, _yield$this$swap, outputAmount, sqrtRatioX96, liquidity, tickCurrent, outputToken;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
!this.involvesToken(inputAmount.currency) ? invariant(false, 'TOKEN') : void 0;
zeroForOne = inputAmount.currency.equals(this.token0);
_context.next = 4;
return this.swap(zeroForOne, inputAmount.quotient, sqrtPriceLimitX96);
case 4:
_yield$this$swap = _context.sent;
outputAmount = _yield$this$swap.amountCalculated;
sqrtRatioX96 = _yield$this$swap.sqrtRatioX96;
liquidity = _yield$this$swap.liquidity;
tickCurrent = _yield$this$swap.tickCurrent;
outputToken = zeroForOne ? this.token1 : this.token0;
return _context.abrupt("return", [maiaCoreSdk.CurrencyAmount.fromRawAmount(outputToken, JSBI.multiply(outputAmount, maiaCoreSdk.NEGATIVE_ONE)), new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)]);
case 11:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function getOutputAmount(_x, _x2) {
return _getOutputAmount.apply(this, arguments);
}
return getOutputAmount;
}()
/**
* Given a desired output amount of a token, return the computed input amount and a pool with state updated after the trade
* @param outputAmount the output amount for which to quote the input amount
* @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap
* @returns The input amount and the pool with updated state
*/
;
_proto.getInputAmount =
/*#__PURE__*/
function () {
var _getInputAmount = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(outputAmount, sqrtPriceLimitX96) {
var zeroForOne, _yield$this$swap2, inputAmount, sqrtRatioX96, liquidity, tickCurrent, inputToken;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
!(outputAmount.currency.isToken && this.involvesToken(outputAmount.currency)) ? invariant(false, 'TOKEN') : void 0;
zeroForOne = outputAmount.currency.equals(this.token1);
_context2.next = 4;
return this.swap(zeroForOne, JSBI.multiply(outputAmount.quotient, maiaCoreSdk.NEGATIVE_ONE), sqrtPriceLimitX96);
case 4:
_yield$this$swap2 = _context2.sent;
inputAmount = _yield$this$swap2.amountCalculated;
sqrtRatioX96 = _yield$this$swap2.sqrtRatioX96;
liquidity = _yield$this$swap2.liquidity;
tickCurrent = _yield$this$swap2.tickCurrent;
inputToken = zeroForOne ? this.token0 : this.token1;
return _context2.abrupt("return", [maiaCoreSdk.CurrencyAmount.fromRawAmount(inputToken, inputAmount), new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)]);
case 11:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
function getInputAmount(_x3, _x4) {
return _getInputAmount.apply(this, arguments);
}
return getInputAmount;
}()
/**
* Executes a swap
* @param zeroForOne Whether the amount in is token0 or token1
* @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
* @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap
* @returns amountCalculated
* @returns sqrtRatioX96
* @returns liquidity
* @returns tickCurrent
*/
;
_proto.swap =
/*#__PURE__*/
function () {
var _swap = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(zeroForOne, amountSpecified, sqrtPriceLimitX96) {
var exactInput, state, step, _yield$this$tickDataP, _SwapMath$computeSwap, liquidityNet;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
if (!sqrtPriceLimitX96) sqrtPriceLimitX96 = zeroForOne ? JSBI.add(TickMath.MIN_SQRT_RATIO, maiaCoreSdk.ONE) : JSBI.subtract(TickMath.MAX_SQRT_RATIO, maiaCoreSdk.ONE);
if (zeroForOne) {
!JSBI.greaterThan(sqrtPriceLimitX96, TickMath.MIN_SQRT_RATIO) ? invariant(false, 'RATIO_MIN') : void 0;
!JSBI.lessThan(sqrtPriceLimitX96, this.sqrtRatioX96) ? invariant(false, 'RATIO_CURRENT') : void 0;
} else {
!JSBI.lessThan(sqrtPriceLimitX96, TickMath.MAX_SQRT_RATIO) ? invariant(false, 'RATIO_MAX') : void 0;
!JSBI.greaterThan(sqrtPriceLimitX96, this.sqrtRatioX96) ? invariant(false, 'RATIO_CURRENT') : void 0;
}
exactInput = JSBI.greaterThanOrEqual(amountSpecified, maiaCoreSdk.ZERO); // keep track of swap state
state = {
amountSpecifiedRemaining: amountSpecified,
amountCalculated: maiaCoreSdk.ZERO,
sqrtPriceX96: this.sqrtRatioX96,
tick: this.tickCurrent,
liquidity: this.liquidity
}; // start swap while loop
case 4:
if (!(JSBI.notEqual(state.amountSpecifiedRemaining, maiaCoreSdk.ZERO) && state.sqrtPriceX96 != sqrtPriceLimitX96)) {
_context3.next = 35;
break;
}
step = {};
step.sqrtPriceStartX96 = state.sqrtPriceX96;
_context3.next = 9;
return this.tickDataProvider.nextInitializedTickWithinOneWord(state.tick, zeroForOne, this.tickSpacing);
case 9:
_yield$this$tickDataP = _context3.sent;
step.tickNext = _yield$this$tickDataP[0];
step.initialized = _yield$this$tickDataP[1];
if (step.tickNext < TickMath.MIN_TICK) {
step.tickNext = TickMath.MIN_TICK;
} else if (step.tickNext > TickMath.MAX_TICK) {
step.tickNext = TickMath.MAX_TICK;
}
step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);
_SwapMath$computeSwap = SwapMath.computeSwapStep(state.sqrtPriceX96, (zeroForOne ? JSBI.lessThan(step.sqrtPriceNextX96, sqrtPriceLimitX96) : JSBI.greaterThan(step.sqrtPriceNextX96, sqrtPriceLimitX96)) ? sqrtPriceLimitX96 : step.sqrtPriceNextX96, state.liquidity, state.amountSpecifiedRemaining, this.fee);
state.sqrtPriceX96 = _SwapMath$computeSwap[0];
step.amountIn = _SwapMath$computeSwap[1];
step.amountOut = _SwapMath$computeSwap[2];
step.feeAmount = _SwapMath$computeSwap[3];
if (exactInput) {
state.amountSpecifiedRemaining = JSBI.subtract(state.amountSpecifiedRemaining, JSBI.add(step.amountIn, step.feeAmount));
state.amountCalculated = JSBI.subtract(state.amountCalculated, step.amountOut);
} else {
state.amountSpecifiedRemaining = JSBI.add(state.amountSpecifiedRemaining, step.amountOut);
state.amountCalculated = JSBI.add(state.amountCalculated, JSBI.add(step.amountIn, step.feeAmount));
}
// TODO
if (!JSBI.equal(state.sqrtPriceX96, step.sqrtPriceNextX96)) {
_context3.next = 32;
break;
}
if (!step.initialized) {
_context3.next = 29;
break;
}
_context3.t0 = JSBI;
_context3.next = 25;
return this.tickDataProvider.getTick(step.tickNext);
case 25:
_context3.t1 = _context3.sent.liquidityNet;
liquidityNet = _context3.t0.BigInt.call(_context3.t0, _context3.t1);
// if we're moving leftward, we interpret liquidityNet as the opposite sign
// safe because liquidityNet cannot be type(int128).min
if (zeroForOne) liquidityNet = JSBI.multiply(liquidityNet, maiaCoreSdk.NEGATIVE_ONE);
state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
case 29:
state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
_context3.next = 33;
break;
case 32:
if (JSBI.notEqual(state.sqrtPriceX96, step.sqrtPriceStartX96)) {
// updated comparison function
// recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
}
case 33:
_context3.next = 4;
break;
case 35:
return _context3.abrupt("return", {
amountCalculated: state.amountCalculated,
sqrtRatioX96: state.sqrtPriceX96,
liquidity: state.liquidity,
tickCurrent: state.tick
});
case 36:
case "end":
return _context3.stop();
}
}, _callee3, this);
}));
function swap(_x5, _x6, _x7) {
return _swap.apply(this, arguments);
}
return swap;
}();
_createClass(Pool, [{
key: "token0Price",
get: function get() {
var _this$_token0Price;
return (_this$_token0Price = this._token0Price) != null ? _this$_token0Price : this._token0Price = new maiaCoreSdk.Price(this.token0, this.token1, Q192, JSBI.multiply(this.sqrtRatioX96, this.sqrtRatioX96));
}
/**
* Returns the current mid price of the pool in terms of token1, i.e. the ratio of token0 over token1
*/
}, {
key: "token1Price",
get: function get() {
var _this$_token1Price;
return (_this$_token1Price = this._token1Price) != null ? _this$_token1Price : this._token1Price = new maiaCoreSdk.Price(this.token1, this.token0, JSBI.multiply(this.sqrtRatioX96, this.sqrtRatioX96), Q192);
}
}, {
key: "chainId",
get: function get() {
return this.token0.chainId;
}
}, {
key: "tickSpacing",
get: function get() {
return TICK_SPACINGS[this.fee];
}
}]);
return Pool;
}();
var MAX_SAFE_INTEGER = /*#__PURE__*/JSBI.BigInt(Number.MAX_SAFE_INTEGER);
var ZERO$1 = /*#__PURE__*/JSBI.BigInt(0);
var ONE$2 = /*#__PURE__*/JSBI.BigInt(1);
var TWO$1 = /*#__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$1) ? invariant(false, 'NEGATIVE') : 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$1), ONE$2);
while (JSBI.lessThan(x, z)) {
z = x;
x = JSBI.divide(JSBI.add(JSBI.divide(value, x), x), TWO$1);
}
return z;
}
/**
* Returns the sqrt ratio as a Q64.96 corresponding to a given ratio of amount1 and amount0
* @param amount1 The numerator amount i.e., the amount of token1
* @param amount0 The denominator amount i.e., the amount of token0
* @returns The sqrt ratio
*/
function encodeSqrtRatioX96(amount1, amount0) {
var numerator = JSBI.leftShift(JSBI.BigInt(amount1), JSBI.BigInt(192));
var denominator = JSBI.BigInt(amount0);
var ratioX192 = JSBI.divide(numerator, denominator);
return sqrt(ratioX192);
}
/**
* Returns an imprecise maximum amount of liquidity received for a given amount of token 0.
* This function is available to accommodate LiquidityAmounts#getLiquidityForAmount0 in the v3 periphery,
* which could be more precise by at least 32 bits by dividing by Q64 instead of Q96 in the intermediate step,
* and shifting the subtracted ratio left by 32 bits. This imprecise calculation will likely be replaced in a future
* v3 router contract.
* @param sqrtRatioAX96 The price at the lower boundary
* @param sqrtRatioBX96 The price at the upper boundary
* @param amount0 The token0 amount
* @returns liquidity for amount0, imprecise
*/
function maxLiquidityForAmount0Imprecise(sqrtRatioAX96, sqrtRatioBX96, amount0) {
if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
var _ref = [sqrtRatioBX96, sqrtRatioAX96];
sqrtRatioAX96 = _ref[0];
sqrtRatioBX96 = _ref[1];
}
var intermediate = JSBI.divide(JSBI.multiply(sqrtRatioAX96, sqrtRatioBX96), Q96);
return JSBI.divide(JSBI.multiply(JSBI.BigInt(amount0), intermediate), JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96));
}
/**
* Returns a precise maximum amount of liquidity received for a given amount of token 0 by dividing by Q64 instead of Q96 in the intermediate step,
* and shifting the subtracted ratio left by 32 bits.
* @param sqrtRatioAX96 The price at the lower boundary
* @param sqrtRatioBX96 The price at the upper boundary
* @param amount0 The token0 amount
* @returns liquidity for amount0, precise
*/
function maxLiquidityForAmount0Precise(sqrtRatioAX96, sqrtRatioBX96, amount0) {
if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
var _ref2 = [sqrtRatioBX96, sqrtRatioAX96];
sqrtRatioAX96 = _ref2[0];
sqrtRatioBX96 = _ref2[1];
}
var numerator = JSBI.multiply(JSBI.multiply(JSBI.BigInt(amount0), sqrtRatioAX96), sqrtRatioBX96);
var denominator = JSBI.multiply(Q96, JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96));
return JSBI.divide(numerator, denominator);
}
/**
* Computes the maximum amount of liquidity received for a given amount of token1
* @param sqrtRatioAX96 The price at the lower tick boundary
* @param sqrtRatioBX96 The price at the upper tick boundary
* @param amount1 The token1 amount
* @returns liquidity for amount1
*/
function maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1) {
if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
var _ref3 = [sqrtRatioBX96, sqrtRatioAX96];
sqrtRatioAX96 = _ref3[0];
sqrtRatioBX96 = _ref3[1];
}
return JSBI.divide(JSBI.multiply(JSBI.BigInt(amount1), Q96), JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96));
}
/**
* Computes the maximum amount of liquidity received for a given amount of token0, token1,
* and the prices at the tick boundaries.
* @param sqrtRatioCurrentX96 the current price
* @param sqrtRatioAX96 price at lower boundary
* @param sqrtRatioBX96 price at upper boundary
* @param amount0 token0 amount
* @param amount1 token1 amount
* @param useFullPrecision if false, liquidity will be maximized according to what the router can calculate,
* not what core can theoretically support
*/
function maxLiquidityForAmounts(sqrtRatioCurrentX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1, useFullPrecision) {
if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
var _ref4 = [sqrtRatioBX96, sqrtRatioAX96];
sqrtRatioAX96 = _ref4[0];
sqrtRatioBX96 = _ref4[1];
}
var maxLiquidityForAmount0 = useFullPrecision ? maxLiquidityForAmount0Precise : maxLiquidityForAmount0Imprecise;
if (JSBI.lessThanOrEqual(sqrtRatioCurrentX96, sqrtRatioAX96)) {
return maxLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (JSBI.lessThan(sqrtRatioCurrentX96, sqrtRatioBX96)) {
var liquidity0 = maxLiquidityForAmount0(sqrtRatioCurrentX96, sqrtRatioBX96, amount0);
var liquidity1 = maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioCurrentX96, amount1);
return JSBI.lessThan(liquidity0, liquidity1) ? liquidity0 : liquidity1;
} else {
return maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/**
* Returns a price object corresponding to the input tick and the base/quote token
* Inputs must be tokens because the address order is used to interpret the price represented by the tick
* @param baseToken the base token of the price
* @param quoteToken the quote token of the price
* @param tick the tick for which to return the price
*/
function tickToPrice(baseToken, quoteToken, tick) {
var sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
var ratioX192 = JSBI.multiply(sqrtRatioX96, sqrtRatioX96);
return baseToken.sortsBefore(quoteToken) ? new maiaCoreSdk.Price(baseToken, quoteToken, Q192, ratioX192) : new maiaCoreSdk.Price(baseToken, quoteToken, ratioX192, Q192);
}
/**
* Returns the first tick for which the given price is greater than or equal to the tick price
* @param price for which to return the closest tick that represents a price less than or equal to the input price,
* i.e. the price of the returned tick is less than or equal to the input price
*/
function priceToClosestTick(price) {
var sorted = price.baseCurrency.sortsBefore(price.quoteCurrency);
var sqrtRatioX96 = sorted ? encodeSqrtRatioX96(price.numerator, price.denominator) : encodeSqrtRatioX96(price.denominator, price.numerator);
var tick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
var nextTickPrice = tickToPrice(price.baseCurrency, price.quoteCurrency, tick + 1);
if (sorted) {
if (!price.lessThan(nextTickPrice)) {
tick++;
}
} else {
if (!price.greaterThan(nextTickPrice)) {
tick++;
}
}
return tick;
}
/**
* Represents a position on a Uniswap V3 Pool
*/
var Position = /*#__PURE__*/function () {
/**
* Constructs a position for a given pool with the given liquidity
* @param pool For which pool the liquidity is assigned
* @param liquidity The amount of liquidity that is in the position
* @param tickLower The lower tick of the position
* @param tickUpper The upper tick of the position
* TODO add staked to initializer
*/
function Position(_ref) {
var pool = _ref.pool,
liquidity = _ref.liquidity,
tickLower = _ref.tickLower,
tickUpper = _ref.tickUpper;
// cached resuts for the getters
this._token0Amount = null;
this._token1Amount = null;
this._mintAmounts = null;
!(tickLower < tickUpper) ? invariant(false, 'TICK_ORDER') : void 0;
!(tickLower >= TickMath.MIN_TICK && tickLower % pool.tickSpacing === 0) ? invariant(false, 'TICK_LOWER') : void 0;
!(tickUpper <= TickMath.MAX_TICK && tickUpper % pool.tickSpacing === 0) ? invariant(false, 'TICK_UPPER') : void 0;
this.pool = pool;
this.tickLower = tickLower;
this.tickUpper = tickUpper;
this.liquidity = JSBI.BigInt(liquidity);
this.staked = false;
}
/**
* Returns the price of token0 at the lower tick
*/
var _proto = Position.prototype;
/**
* Returns the lower and upper sqrt ratios if the price 'slips' up to slippage tolerance percentage
* @param slippageTolerance The amount by which the price can 'slip' before the transaction will revert
* @returns The sqrt ratios after slippage
*/
_proto.ratiosAfterSlippage = function ratiosAfterSlippage(slippageTolerance) {
if (this.pool instanceof Pool) {
var priceLower = this.pool.token0Price.asFraction.multiply(new maiaCoreSdk.Percent(1).subtract(slippageTolerance));
var priceUpper = this.pool.token0Price.asFraction.multiply(slippageTolerance.add(1));
var sqrtRatioX96Lower = encodeSqrtRatioX96(priceLower.numerator, priceLower.denominator);
if (JSBI.lessThanOrEqual(sqrtRatioX96Lower, TickMath.MIN_SQRT_RATIO)) {
sqrtRatioX96Lower = JSBI.add(TickMath.MIN_SQRT_RATIO, JSBI.BigInt(1));
}
var sqrtRatioX96Upper = encodeSqrtRatioX96(priceUpper.numerator, priceUpper.denominator);
if (JSBI.greaterThanOrEqual(sqrtRatioX96Upper, TickMath.MAX_SQRT_RATIO)) {
sqrtRatioX96Upper = JSBI.subtract(TickMath.MAX_SQRT_RATIO, JSBI.BigInt(1));
}
return {
sqrtRatioX96Lower: sqrtRatioX96Lower,
sqrtRatioX96Upper: sqrtRatioX96Upper
};
} else return undefined;
}
/**
* Returns the minimum amounts that must be sent in order to safely mint the amount of liquidity held by the position
* with the given slippage tolerance
* @param slippageTolerance Tolerance of unfavorable slippage from the current price
* @returns The amounts, with slippage
*/;
_proto.mintAmountsWithSlippage = function mintAmountsWithSlippage(slippageTolerance) {
if (this.pool instanceof Pool) {
// get lower/upper prices
var _this$ratiosAfterSlip = this.ratiosAfterSlippage(slippageTolerance),
sqrtRatioX96Upper = _this$ratiosAfterSlip.sqrtRatioX96Upper,
sqrtRatioX96Lower = _this$ratiosAfterSlip.sqrtRatioX96Lower;
// construct counterfactual pools
var poolLower = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, sqrtRatioX96Lower, 0 /* liquidity doesn't matter */, TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower));
var poolUpper = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, sqrtRatioX96Upper, 0 /* liquidity doesn't matter */, TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper));
// because the router is imprecise, we need to calculate the position that will be created (assuming no slippage)
var positionThatWillBeCreated = Position.fromAmounts(_extends({
pool: this.pool,
tickLower: this.tickLower,
tickUpper: this.tickUpper
}, this.mintAmounts, {
useFullPrecision: false
}));
// we want the smaller amounts...
// ...which occurs at the upper price for amount0...
var amount0 = new Position({
pool: poolUpper,
liquidity: positionThatWillBeCreated.liquidity,
tickLower: this.tickLower,
tickUpper: this.tickUpper
}).mintAmounts.amount0;
// ...and the lower for amount1
var amount1 = new Position({
pool: poolLower,
liquidity: positionThatWillBeCreated.liquidity,
tickLower: this.tickLower,
tickUpper: this.tickUpper
}).mintAmounts.amount1;
return {
amount0: amount0,
amount1: amount1
};
} else return {
amount0: undefined,
amount1: undefined
};
}
/**
* Returns the minimum amounts that should be requested in order to safely burn the amount of liquidity held by the
* position with the given slippage tolerance
* @param slippageTolerance tolerance of unfavorable slippage from the current price
* @returns The amounts, with slippage
*/;
_proto.burnAmountsWithSlippage = function burnAmountsWithSlippage(slippageTolerance) {
if (this.pool instanceof Pool) {
// get lower/upper prices
var _this$ratiosAfterSlip2 = this.ratiosAfterSlippage(slippageTolerance),
sqrtRatioX96Upper = _this$ratiosAfterSlip2.sqrtRatioX96Upper,
sqrtRatioX96Lower = _this$ratiosAfterSlip2.sqrtRatioX96Lower;
// construct counterfactual pools
var poolLower = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, sqrtRatioX96Lower, 0 /* liquidity doesn't matter */, TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower));
var poolUpper = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, sqrtRatioX96Upper, 0 /* liquidity doesn't matter */, TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper));
// we want the smaller amounts...
// ...which occurs at the upper price for amount0...
var amount0 = new Position({
pool: poolUpper,
liquidity: this.liquidity,
tickLower: this.tickLower,
tickUpper: this.tickUpper
}).amount0;
// ...and the lower for amount1
var amount1 = new Position({
pool: poolLower,
liquidity: this.liquidity,
tickLower: this.tickLower,
tickUpper: this.tickUpper
}).amount1;
return {
amount0: amount0 == null ? void 0 : amount0.quotient,
amount1: amount1 == null ? void 0 : amount1.quotient
};
} else return undefined;
}
/**
* Returns the minimum amounts that must be sent in order to mint the amount of liquidity held by the position at
* the current price for the pool
*/;
/**
* Computes the maximum amount of liquidity received for a given amount of token0, token1,
* and the prices at the tick boundaries.
* @param pool The pool for which the position should be created
* @param tickLower The lower tick of the position
* @param tickUpper The upper tick of the position
* @param amount0 token0 amount
* @param amount1 token1 amount
* @param useFullPrecision If false, liquidity will be maximized according to what the router can calculate,
* not what core can theoretically support
* @returns The amount of liquidity for the position
*/
Position.fromAmounts = function fromAmounts(_ref2) {
var pool = _ref2.pool,
tickLower = _ref2.tickLower,
tickUpper = _ref2.tickUpper,
amount0 = _ref2.amount0,
amount1 = _ref2.amount1,
useFullPrecision = _ref2.useFullPrecision;
var sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
var sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
return new Position({
pool: pool,
tickLower: tickLower,
tickUpper: tickUpper,
liquidity: maxLiquidityForAmounts(pool.sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1, useFullPrecision)
});
}
/**
* Computes a position with the maximum amount of liquidity received for a given amount of token0, assuming an unlimited amount of token1
* @param pool The pool for which the position is created
* @param tickLower The lower tick
* @param tickUpper The upper tick
* @param amount0 The desired amount of token0
* @param useFullPrecision If true, liquidity will be maximized according to what the router can calculate,
* not what core can theoretically support
* @returns The position
*/;
Position.fromAmount0 = function fromAmount0(_ref3) {
var pool = _ref3.pool,
tickLower = _ref3.tickLower,
tickUpper = _ref3.tickUpper,
amount0 = _ref3.amount0,
useFullPrecision = _ref3.useFullPrecision;
return Position.fromAmounts({
pool: pool,
tickLower: tickLower,
tickUpper: tickUpper,
amount0: amount0,
amount1: maiaCoreSdk.MaxUint256,
useFullPrecision: useFullPrecision
});
}
/**
* Computes a position with the maximum amount of liquidity received for a given amount of token1, assuming an unlimited amount of token0
* @param pool The pool for which the position is created
* @param tickLower The lower tick
* @param tickUpper The upper tick
* @param amount1 The desired amount of token1
* @returns The position
*/;
Position.fromAmount1 = function fromAmount1(_ref4) {
var pool = _ref4.pool,
tickLower = _ref4.tickLower,
tickUpper = _ref4.tickUpper,
amount1 = _ref4.amount1;
// this function always uses full precision,
return Position.fromAmounts({
pool: pool,
tickLower: tickLower,
tickUpper: tickUpper,
amount0: maiaCoreSdk.MaxUint256,
amount1: amount1,
useFullPrecision: true
});
};
_createClass(Position, [{
key: "token0PriceLower",
get: function get() {
return this.pool instanceof Pool ? tickToPrice(this.pool.token0, this.pool.token1, this.tickLower) : undefined;
}
/**
* Returns the price of token0 at the upper tick
*/
}, {
key: "token0PriceUpper",
get: function get() {
return this.pool instanceof Pool ? tickToPrice(this.pool.token0, this.pool.token1, this.tickUpper) : undefined;
}
/**
* Returns the amount of token0 that this position's liquidity could be burned for at the current pool price
*/
}, {
key: "amount0",
get: function get() {
if (this.pool instanceof Pool) {
if (this._token0Amount === null) {
if (this.pool.tickCurrent < this.tickLower) {
this._token0Amount = maiaCoreSdk.CurrencyAmount.fromRawAmount(this.pool.token0, SqrtPriceMath.getAmount0Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, false));
} else if (this.pool.tickCurrent < this.tickUpper) {
this._token0Amount = maiaCoreSdk.CurrencyAmount.fromRawAmount(this.pool.token0, SqrtPriceMath.getAmount0Delta(this.pool.sqrtRatioX96, TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, false));
} else {
this._token0Amount = maiaCoreSdk.CurrencyAmount.fromRawAmount(this.pool.token0, maiaCoreSdk.ZERO);
}
}
return this._token0Amount;
} else return undefined;
}
/**
* Returns the amount of token1 that this position's liquidity could be burned for at the current pool price
*/
}, {
key: "amount1",
get: function get() {
if (this.pool instanceof Pool) {
if (this._token1Amount === null) {
if (this.pool.tickCurrent < this.tickLower) {
this._token1Amount = maiaCoreSdk.CurrencyAmount.fromRawAmount(this.pool.token1, maiaCoreSdk.ZERO);
} else if (this.pool.tickCurrent < this.tickUpper) {
this._token1Amount = maiaCoreSdk.CurrencyAmount.fromRawAmount(this.pool.token1, SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), this.pool.sqrtRatioX96, this.liquidity, false));
} else {
this._token1Amount = maiaCoreSdk.CurrencyAmount.fromRawAmount(this.pool.token1, SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, false));
}
}
return this._token1Amount;
} else return undefined;
}
}, {
key: "mintAmounts",
get: function get() {
if (this.pool instanceof Pool) {
if (this._mintAmounts === null) {
if (this.pool.tickCurrent < this.tickLower) {
return {
amount0: SqrtPriceMath.getAmount0Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, true),
amount1: maiaCoreSdk.ZERO
};
} else if (this.pool.tickCurrent < this.tickUpper) {
return {
amount0: SqrtPriceMath.getAmount0Delta(this.pool.sqrtRatioX96, TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, true),
amount1: SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), this.pool.sqrtRatioX96, this.liquidity, true)
};
} else {
return {
amount0: maiaCoreSdk.ZERO,
amount1: SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, true)
};
}
}
return this._mintAmounts;
} else return undefined;
}
}]);
return Position;
}();
function isAllowedPermit(permitOptions) {
return 'nonce' in permitOptions;
}
var SelfPermit = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
function SelfPermit() {}
SelfPermit.encodePermit = function encodePermit(token, options) {
return isAllowedPermit(options) ? SelfPermit.INTERFACE.encodeFunctionData('selfPermitAllowed', [token.address, maiaCoreSdk.toHex(options.nonce), maiaCoreSdk.toHex(options.expiry), options.v, options.r, options.s]) : SelfPermit.INTERFACE.encodeFunctionData('selfPermit', [token.address, maiaCoreSdk.toHex(options.amount), maiaCoreSdk.toHex(options.deadline), options.v, options.r, options.s]);
};
return SelfPermit;
}();
SelfPermit.INTERFACE = /*#__PURE__*/new abi.Interface(ISelfPermit.abi);
var _excluded = ["expectedCurrencyOwed0", "expectedCurrencyOwed1"];
var MaxUint128 = /*#__PURE__*/maiaCoreSdk.toHex( /*#__PURE__*/JSBI.subtract( /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(128)), /*#__PURE__*/JSBI.BigInt(1)));
// type guard
function isMint(options) {
return Object.keys(options).some(function (k) {
return k === 'recipient';
});
}
var NonfungiblePositionManager = /*#__PURE__*/function () {
function NonfungiblePositionManager() {}
/**
* Encodes the parameters for the creation of a new uni v3 pool.
* @param pool pool to create
* @returns the calldata for the tx
* // TODO improve function naming
*/
NonfungiblePositionManager.encodeCreate = function encodeCreate(pool) {
return NonfungiblePositionManager.INTERFACE.encodeFunctionData('createAndInitializePoolIfNecessary', [pool.token0.address, pool.token1.address, pool.fee, maiaCoreSdk.toHex(pool.sqrtRatioX96)]);
}
/**
* Creates the necessary params to execute the creation of a new uni v3 pool
* @param pool pool details to create
* @returns calldata & value for the tx execution
* // TODO improve function naming
*/;
NonfungiblePositionManager.createCallParameters = function createCallParameters(pool) {
return {
calldata: this.encodeCreate(pool),
value: maiaCoreSdk.toHex(0)
};
}
/**
* Creates the native add liquidity call parameters for adding liquidity to a uni v3 position
* @param position holds the position details we want to create/add to
* @param options holds the options for the add liquidity call
* // TODO improve function naming
* @returns
*/;
NonfungiblePositionManager.addCallParameters = function addCallParameters(position, options) {
if (position.pool instanceof Pool) {
!JSBI.greaterThan(position.liquidity, maiaCoreSdk.ZERO) ? invariant(false, 'ZERO_LIQUIDITY') : void 0;
var calldatas = [];
// get amounts
var _position$mintAmounts = position.mintAmounts,
amount0Desired = _position$mintAmounts.amount0,
amount1Desired = _position$mintAmounts.amount1;
// adjust for slippage
var minimumAmounts = position.mintAmountsWithSlippage(options.slippageTolerance);
var amount0Min = maiaCoreSdk.toHex(minimumAmounts.amount0);
var amount1Min = maiaCoreSdk.toHex(minimumAmounts.amount1);
var deadline = maiaCoreSdk.toHex(options.deadline);
// create pool if needed
if (isMint(options) && options.createPool) {
calldatas.push(this.encodeCreate(position.pool));
}
// permits if necessary
if (options.token0Permit) {
calldatas.push(SelfPermit.encodePermit(position.pool.token0, options.token0Permit));
}
if (options.token1Permit) {
calldatas.push(SelfPermit.encodePermit(position.pool.token1, options.token1Permit));
}
// mint
if (isMint(options)) {
var recipient = validateAndParseAddress(options.recipient);
calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('mint', [{
token0: position.pool.token0.address,
token1: position.pool.token1.address,
fee: position.pool.fee,
tickLower: position.tickLower,
tickUpper: position.tickUpper,
amount0Desired: maiaCoreSdk.toHex(amount0Desired),
amount1Desired: maiaCoreSdk.toHex(amount1Desired),
amount0Min: amount0Min,
amount1Min: amount1Min,
recipient: recipient,
deadline: deadline
}]));
} else {
// increase
calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('increaseLiquidity', [{
tokenId: maiaCoreSdk.toHex(options.tokenId),
amount0Desired: maiaCoreSdk.toHex(amount0Desired),
amount1Desired: maiaCoreSdk.toHex(amount1Desired),
amount0Min: amount0Min,
amount1Min: amount1Min,
deadline: deadline
}]));
}
var value = maiaCoreSdk.toHex(0);
if (options.useNative) {
var wrapped = options.useNative.wrapped;
!(position.pool.token0.equals(wrapped) || position.pool.token1.equals(wrapped)) ? invariant(false, 'NO_WETH') : void 0;
var wrappedValue = position.pool.token0.equals(wrapped) ? amount0Desired : amount1Desired;
// we only need to refund if we're actually sending ETH
if (JSBI.greaterThan(wrappedValue, maiaCoreSdk.ZERO)) {
calldatas.push(Payments.encodeRefundETH());
}
value = maiaCoreSdk.toHex(wrappedValue);
}
// Tranfer the NFT at the end if requested and the position is not being minted
if (!isMint(options) && options.afterActionTransfer) {
var _options$afterActionT;
calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('safeTransferFrom(address,address,uint256)', [options.afterActionTransfer.owner, (_options$afterActionT = options.afterActionTransfer.recipient) != null ? _options$afterActionT : options.afterActionTransfer.owner, maiaCoreSdk.toHex(options.tokenId)]));
}
return {
calldata: Multicall.encodeMulticall(calldatas),
value: value
};
} else {
return {
calldata: '',
value: ''
};
}
}
/**
* Creates the native collect calldata for collection fees from a uni v3 position
* @param options holds the options for the collect call
* @returns
*/;
NonfungiblePositionManager.encodeCollect = function encodeCollect(options) {
var calldatas = [];
var tokenId = maiaCoreSdk.toHex(options.tokenId);
var involvesETH = options.expectedCurrencyOwed0.currency.isNative || options.expectedCurrencyOwed1.currency.isNative;
var recipient = validateAndParseAddress(options.recipient);
if (options.permit) {
calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('permit', [validateAndParseAddress(options.permit.spender), tokenId, maiaCoreSdk.toHex(options.permit.deadline), options.permit.v, options.permit.r, options.permit.s]));
}
// collect
calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('collect', [{
tokenId: tokenId,
recipient: involvesETH ? ADDRESS_ZERO : recipient,
amount0Max: MaxUint128,
amount1Max: MaxUint128
}]));
if (involvesETH) {
var ethAmount = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed0.quotient : options.expectedCurrencyOwed1.quotient;
var token = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed1.currency : options.expectedCurrencyOwed0.currency;
var tokenAmount = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed1.quotient : options.expectedCurrencyOwed0.quotient;
calldatas.push(Payments.encodeUnwrapWETH9(ethAmount, recipient));
calldatas.push(Payments.encodeSweepToken(token, tokenAmount, recipient));
}
// Tranfer the NFT at the end if requested
if (options.afterActionTransfer) {
var _options$afterActionT2;
calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('safeTransferFrom(address,address,uint256)', [options.afterActionTransfer.owner, (_options$afterActionT2 = options.afterActionTransfer.recipient) != null ? _options$afterActionT2 : options.afterActionTransfer.owner, maiaCoreSdk.toHex(options.tokenId)]));
}
return calldatas;
}
/**
* Produces the on chain calldata to perform a collect operation
* @param options holds the options for the collect liquidity call
* @returns
* // TODO improve function naming
*/;
NonfungiblePositionManager.collectCallParameters = function collectCallParameters(options) {
var calldatas = NonfungiblePositionManager.encodeCollect(options);
return {
calldata: Multicall.encodeMulticall(calldatas),
value: maiaCoreSdk.toHex(0)
};
}
/**
* Produces the native uni v3 calldata for completely or partially exiting a position
* @param position The position to exit
* @param options Additional information necessary for generating the calldata
* @returns The call parameters
* // TODO improve function naming
*/;
NonfungiblePositionManager.removeCallParameters = function removeCallParameters(position, options) {
var calldatas = [];
var deadline = maiaCoreSdk.toHex(options.deadline);
var tokenId = maiaCoreSdk.toHex(options.tokenId);
// construct a partial position with a percentage of liquidity
var partialPosition = new Position({
pool: position.pool,
liquidity: options.liquidityPercentage.multiply(position.liquidity).quotient,
tickLower: position.tickLower,
tickUpper: position.tickUpper
});
!JSBI.greaterThan(partialPosition.liquidity, maiaCoreSdk.ZERO) ? invariant(false, 'ZERO_LIQUIDITY') : void 0;
// slippage-adjusted underlying amounts
var _partialPosition$burn = partialPosition.burnAmountsWithSlippage(options.slippageTolerance),
amount0Min = _partialPosition$burn.amount0,
amount1Min = _partialPosition$burn.amount1;
if (options.permit) {
calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('permit', [validateAndParseAddress(options.permit.spender), tokenId, maiaCoreSdk.toHex(options.permit.deadline), options.permit.v, options.permit.r, options.permit.s]));
}
// remove liquidity
calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('decreaseLiquidity', [{
tokenId: tokenId,
liquidity: maiaCoreSdk.toHex(partialPosition.liquidity),
amount0Min: maiaCoreSdk.toHex(amount0Min),
amount1Min: maiaCoreSdk.toHex(amount1Min),
deadline: deadline
}]));
var _options$collectOptio = options.collectOptions,
expectedCurrencyOwed0 = _options$collectOptio.expectedCurrencyOwed0,
expectedCurrencyOwed1 = _options$collectOptio.expectedCurrencyOwed1,
rest = _objectWithoutPropertiesLoose(_options$collectOptio, _excluded);
calldatas.push.apply(calldatas, NonfungiblePositionManager.encodeCollect(_extends({
tokenId: maiaCoreSdk.toHex(options.tokenId),
// add the underlying value to the expected currency already owed
expectedCurrencyOwed0: expectedCurrencyOwed0.add(maiaCoreSdk.CurrencyAmount.fromRawAmount(expectedCurrencyOwed0.currency, amount0Min)),
expectedCurrencyOwed1: expectedCurrencyOwed1.add(maiaCoreSdk.CurrencyAmount.fromRawAmount(expectedCurrencyOwed1.currency, amount1Min))
}, rest)));
if (options.liquidityPercentage.equalTo(maiaCoreSdk.ONE)) {
if (options.burnToken) {
calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('burn', [tokenId]));
}
} else {
!(options.burnToken !== true) ? invariant(false, 'CANNOT_BURN') : void 0;
// Tranfer the NFT at the end if requested
if (options.afterActionTransfer) {
var _options$afterActionT3;
calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('safeTransferFrom(address,address,uint256)', [options.afterActionTransfer.owner, (_options$afterActionT3 = options.afterActionTransfer.recipient) != null ? _options$afterActionT3 : options.afterActionTransfer.owner, maiaCoreSdk.toHex(options.tokenId)]));
}
}
return {
calldata: Multicall.encodeMulticall(calldatas),
value: maiaCoreSdk.toHex(0)
};
};
NonfungiblePositionManager.encodeSafeTransferFrom = function encodeSafeTransferFrom(options) {
var recipient = validateAndParseAddress(options.recipient);
var sender = validateAndParseAddress(options.sender);
var permitCalldata;
if (options.permit) {
permitCalldata = NonfungiblePositionManager.INTERFACE.encodeFunctionData('permit', [validateAndParseAddress(options.permit.spender), options.tokenId, maiaCoreSdk.toHex(options.permit.deadline), options.permit.v, options.permit.r, options.permit.s]);
}
var calldata;
if (options.data) {
calldata = NonfungiblePositionManager.INTERFACE.encodeFunctionData('safeTransferFrom(address,address,uint256,bytes)', [sender, recipient, maiaCoreSdk.toHex(options.tokenId), options.data]);
} else {
calldata = NonfungiblePositionManager.INTERFACE.encodeFunctionData('safeTransferFrom(address,address,uint256)', [sender, recipient, maiaCoreSdk.toHex(options.tokenId)]);
}
return {
permitCalldata: permitCalldata,
calldata: calldata
};
};
NonfungiblePositionManager.safeTransferFromParameters = function safeTransferFromParameters(options) {
var _NonfungiblePositionM = NonfungiblePositionManager.encodeSafeTransferFrom(options),
permitCalldata = _NonfungiblePositionM.permitCalldata,
calldata = _NonfungiblePositionM.calldata;
return {
calldata: options.permit && permitCalldata ? Multicall.encodeMulticall([permitCalldata, calldata]) : calldata,
value: maiaCoreSdk.toHex(0)
};
};
NonfungiblePositionManager.safeTransferFromMultipleParameters = function safeTransferFromMultipleParameters(options) {
!(options.length > 0) ? invariant(false, 'NO_OPTIONS_PROVIDED') : void 0;
if (options.length === 1) return NonfungiblePositionManager.safeTransferFromParameters(options[0]);
var calldatas = [];
for (var _iterator = _createForOfIteratorHelperLoose(options), _step; !(_step = _iterator()).done;) {
var option = _step.value;
var _NonfungiblePositionM2 = NonfungiblePositionManager.encodeSafeTransferFrom(option),
permitCalldata = _NonfungiblePositionM2.permitCalldata,
calldata = _NonfungiblePositionM2.calldata;
if (option.permit && permitCalldata) calldatas.push(permitCalldata);
calldatas.push(calldata);
}
return {
calldata: Multicall.encodeMulticall(calldatas),
value: maiaCoreSdk.toHex(0)
};
};
return NonfungiblePositionManager;
}();
NonfungiblePositionManager.INTERFACE = /*#__PURE__*/new abi.Interface(INonfungiblePositionManager.abi);
// see https://stackoverflow.com/a/41102306
var CAN_SET_PROTOTYPE = ('setPrototypeOf' in Object);
/**
* Indicates that the pair has insufficient reserves for a desired output amount. I.e. the amount of output cannot be
* obtained by sending any amount of input.
*/
var InsufficientReservesError = /*#__PURE__*/function (_Error) {
_inheritsLoose(InsufficientReservesError, _Error);
function InsufficientReservesError() {
var _this;
_this = _Error.call(this) || this;
_this.isInsufficientReservesError = true;
_this.name = _this.constructor.name;
if (CAN_SET_PROTOTYPE) Object.setPrototypeOf(_assertThisInitialized(_this), (this instanceof InsufficientReservesError ? this.constructor : void 0).prototype);
return _this;
}
return InsufficientReservesError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
/**
* Indicates that the input amount is too small to produce any amount of output. I.e. the amount of input sent is less
* than the price of a single unit of output after fees.
*/
var InsufficientInputAmountError = /*#__PURE__*/function (_Error2) {
_inheritsLoose(InsufficientInputAmountError, _Error2);
function InsufficientInputAmountError() {
var _this2;
_this2 = _Error2.call(this) || this;
_this2.isInsufficientInputAmountError = true;
_this2.name = _this2.constructor.name;
if (CAN_SET_PROTOTYPE) Object.setPrototypeOf(_assertThisInitialized(_this2), (this instanceof InsufficientInputAmountError ? this.constructor : void 0).prototype);
return _this2;
}
return InsufficientInputAmountError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
var computePairAddress = function computePairAddress(_ref) {
var factoryAddress = _ref.factoryAddress,
tokenA = _ref.tokenA,
tokenB = _ref.tokenB;
var _ref2 = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
token0 = _ref2[0],
token1 = _ref2[1]; // does safety checks
return address.getCreate2Address(factoryAddress, solidity.keccak256(['bytes'], [solidity.pack(['address', 'address'], [token0.address, token1.address])]), POOL_INIT_CODE_HASH);
};
var Pair = /*#__PURE__*/function () {
function Pair(currencyAmountA, tokenAmountB) {
var tokenAmounts = currencyAmountA.currency.sortsBefore(tokenAmountB.currency) // does safety checks
? [currencyAmountA, tokenAmountB] : [tokenAmountB, currencyAmountA];
this.liquidityToken = new maiaCoreSdk.NativeToken(tokenAmounts[0].currency.chainId, Pair.getAddress(tokenAmounts[0].currency, tokenAmounts[1].currency), 18, 'UNI-V2', 'Uniswap V2');
this.tokenAmounts = tokenAmounts;
}
Pair.getAddress = function getAddress(tokenA, tokenB) {
return computePairAddress({
factoryAddress: FACTORY_ADDRESS,
tokenA: tokenA,
tokenB: tokenB
});
}
/**
* Returns true if the token is either token0 or token1
* @param token to check
*/;
var _proto = Pair.prototype;
_proto.involvesToken = function involvesToken(token) {
return token.equals(this.token0) || token.equals(this.token1);
}
/**
* Returns the current mid price of the pair in terms of token0, i.e. the ratio of reserve1 to reserve0
*/;
/**
* Return the price of the given token in terms of the other token in the pair.
* @param token token to return price of
*/
_proto.priceOf = function priceOf(token) {
!this.involvesToken(token) ? invariant(false, 'TOKEN') : void 0;
return token.equals(this.token0) ? this.token0Price : this.token1Price;
}
/**
* Returns the chain ID of the tokens in the pair.
*/;
_proto.reserveOf = function reserveOf(token) {
!this.involvesToken(token) ? invariant(false, 'TOKEN') : void 0;
return token.equals(this.token0) ? this.reserve0 : this.reserve1;
};
_proto.getOutputAmount = function getOutputAmount(inputAmount) {
!this.involvesToken(inputAmount.currency) ? invariant(false, 'TOKEN') : void 0;
if (JSBI.equal(this.reserve0.quotient, maiaCoreSdk.ZERO) || JSBI.equal(this.reserve1.quotient, maiaCoreSdk.ZERO)) {
throw new InsufficientReservesError();
}
var inputReserve = this.reserveOf(inputAmount.currency);
var outputReserve = this.reserveOf(inputAmount.currency.equals(this.token0) ? this.token1 : this.token0);
var inputAmountWithFee = JSBI.multiply(inputAmount.quotient, maiaCoreSdk._997);
var numerator = JSBI.multiply(inputAmountWithFee, outputReserve.quotient);
var denominator = JSBI.add(JSBI.multiply(inputReserve.quotient, maiaCoreSdk._1000), inputAmountWithFee);
var outputAmount = maiaCoreSdk.CurrencyAmount.fromRawAmount(inputAmount.currency.equals(this.token0) ? this.token1 : this.token0, JSBI.divide(numerator, denominator));
if (JSBI.equal(outputAmount.quotient, maiaCoreSdk.ZERO)) {
throw new InsufficientInputAmountError();
}
return [outputAmount, new Pair(inputReserve.add(inputAmount), outputReserve.subtract(outputAmount))];
};
_proto.getInputAmount = function getInputAmount(outputAmount) {
!this.involvesToken(outputAmount.currency) ? invariant(false, 'TOKEN') : void 0;
if (JSBI.equal(this.reserve0.quotient, maiaCoreSdk.ZERO) || JSBI.equal(this.reserve1.quotient, maiaCoreSdk.ZERO) || JSBI.greaterThanOrEqual(outputAmount.quotient, this.reserveOf(outputAmount.currency).quotient)) {
throw new InsufficientReservesError();
}
var outputReserve = this.reserveOf(outputAmount.currency);
var inputReserve = this.reserveOf(outputAmount.currency.equals(this.token0) ? this.token1 : this.token0);
var numerator = JSBI.multiply(JSBI.multiply(inputReserve.quotient, outputAmount.quotient), maiaCoreSdk._1000);
var denominator = JSBI.multiply(JSBI.subtract(outputReserve.quotient, outputAmount.quotient), maiaCoreSdk._997);
var inputAmount = maiaCoreSdk.CurrencyAmount.fromRawAmount(outputAmount.currency.equals(this.token0) ? this.token1 : this.token0, JSBI.add(JSBI.divide(numerator, denominator), maiaCoreSdk.ONE));
return [inputAmount, new Pair(inputReserve.add(inputAmount), outputReserve.subtract(outputAmount))];
};
_proto.getLiquidityMinted = function getLiquidityMinted(totalSupply, tokenAmountA, tokenAmountB) {
!totalSupply.currency.equals(this.liquidityToken) ? invariant(false, 'LIQUIDITY') : void 0;
var tokenAmounts = tokenAmountA.currency.sortsBefore(tokenAmountB.currency) // does safety checks
? [tokenAmountA, tokenAmountB] : [tokenAmountB, tokenAmountA];
!(tokenAmounts[0].currency.equals(this.token0) && tokenAmounts[1].currency.equals(this.token1)) ? invariant(false, 'TOKEN') : void 0;
var liquidity;
if (JSBI.equal(totalSupply.quotient, maiaCoreSdk.ZERO)) {
liquidity = JSBI.subtract(sqrt(JSBI.multiply(tokenAmounts[0].quotient, tokenAmounts[1].quotient)), MINIMUM_LIQUIDITY);
} else {
var amount0 = JSBI.divide(JSBI.multiply(tokenAmounts[0].quotient, totalSupply.quotient), this.reserve0.quotient);
var amount1 = JSBI.divide(JSBI.multiply(tokenAmounts[1].quotient, totalSupply.quotient), this.reserve1.quotient);
liquidity = JSBI.lessThanOrEqual(amount0, amount1) ? amount0 : amount1;
}
if (!JSBI.greaterThan(liquidity, maiaCoreSdk.ZERO)) {
throw new InsufficientInputAmountError();
}
return maiaCoreSdk.CurrencyAmount.fromRawAmount(this.liquidityToken, liquidity);
};
_proto.getLiquidityValue = function getLiquidityValue(token, totalSupply, liquidity, feeOn, kLast) {
if (feeOn === void 0) {
feeOn = false;
}
!this.involvesToken(token) ? invariant(false, 'TOKEN') : void 0;
!totalSupply.currency.equals(this.liquidityToken) ? invariant(false, 'TOTAL_SUPPLY') : void 0;
!liquidity.currency.equals(this.liquidityToken) ? invariant(false, 'LIQUIDITY') : void 0;
!JSBI.lessThanOrEqual(liquidity.quotient, totalSupply.quotient) ? invariant(false, 'LIQUIDITY') : void 0;
var totalSupplyAdjusted;
if (!feeOn) {
totalSupplyAdjusted = totalSupply;
} else {
!!!kLast ? invariant(false, 'K_LAST') : void 0;
var kLastParsed = JSBI.BigInt(kLast);
if (!JSBI.equal(kLastParsed, maiaCoreSdk.ZERO)) {
var rootK = sqrt(JSBI.multiply(this.reserve0.quotient, this.reserve1.quotient));
var rootKLast = sqrt(kLastParsed);
if (JSBI.greaterThan(rootK, rootKLast)) {
var numerator = JSBI.multiply(totalSupply.quotient, JSBI.subtract(rootK, rootKLast));
var denominator = JSBI.add(JSBI.multiply(rootK, maiaCoreSdk.FIVE), rootKLast);
var feeLiquidity = JSBI.divide(numerator, denominator);
totalSupplyAdjusted = totalSupply.add(maiaCoreSdk.CurrencyAmount.fromRawAmount(this.liquidityToken, feeLiquidity));
} else {
totalSupplyAdjusted = totalSupply;
}
} else {
totalSupplyAdjusted = totalSupply;
}
}
return maiaCoreSdk.CurrencyAmount.fromRawAmount(token, JSBI.divide(JSBI.multiply(liquidity.quotient, this.reserveOf(token).quotient), totalSupplyAdjusted.quotient));
};
_createClass(Pair, [{
key: "token0Price",
get: function get() {
var result = this.tokenAmounts[1].divide(this.tokenAmounts[0]);
return new maiaCoreSdk.Price(this.token0, this.token1, result.denominator, result.numerator);
}
/**
* Returns the current mid price of the pair in terms of token1, i.e. the ratio of reserve0 to reserve1
*/
}, {
key: "token1Price",
get: function get() {
var result = this.tokenAmounts[0].divide(this.tokenAmounts[1]);
return new maiaCoreSdk.Price(this.token1, this.token0, result.denominator, result.numerator);
}
}, {
key: "chainId",
get: function get() {
return this.token0.chainId;
}
}, {
key: "token0",
get: function get() {
return this.tokenAmounts[0].currency;
}
}, {
key: "token1",
get: function get() {
return this.tokenAmounts[1].currency;
}
}, {
key: "reserve0",
get: function get() {
return this.tokenAmounts[0];
}
}, {
key: "reserve1",
get: function get() {
return this.tokenAmounts[1];
}
}]);
return Pair;
}();
/**
* Converts a route to a hex encoded path
* @param route the v3 path to convert to an encoded path
* @param exactOutput whether the route should be encoded in reverse, for making exact output swaps
*/
function encodeRouteToPath(route, exactOutput) {
var firstInputToken = route.input.wrapped;
var _route$pools$reduce = route.pools.reduce(function (_ref, pool, index) {
var inputToken = _ref.inputToken,
path = _ref.path,
types = _ref.types;
var outputToken = pool.token0.equals(inputToken) ? pool.token1 : pool.token0;
if (index === 0) {
return {
inputToken: outputToken,
types: ['address', 'uint24', 'address'],
path: [inputToken.address, pool.fee, outputToken.address]
};
} else {
return {
inputToken: outputToken,
types: [].concat(types, ['uint24', 'address']),
path: [].concat(path, [pool.fee, outputToken.address])
};
}
}, {
inputToken: firstInputToken,
path: [],
types: []
}),
path = _route$pools$reduce.path,
types = _route$pools$reduce.types;
return exactOutput ? solidity.pack(types.reverse(), path.reverse()) : solidity.pack(types, path);
}
/**
* Represents the Uniswap V3 QuoterV1 contract with a method for returning the formatted
* calldata needed to call the quoter contract.
*/
var SwapQuoter = /*#__PURE__*/function () {
function SwapQuoter() {}
/**
* Produces the on-chain method name of the appropriate function within QuoterV2,
* and the relevant hex encoded parameters.
* @template TInput The input token, either Ether or an ERC-20
* @template TOutput The output token, either Ether or an ERC-20
* @param route The swap route, a list of pools through which a swap can occur
* @param amount The amount of the quote, either an amount in, or an amount out
* @param tradeType The trade type, either exact input or exact output
* @param options The optional params including price limit and Quoter contract switch
* @returns The formatted calldata
*/
SwapQuoter.quoteCallParameters = function quoteCallParameters(route, amount, tradeType, options) {
if (options === void 0) {
options = {};
}
var singleHop = route.pools.length === 1;
var quoteAmount = maiaCoreSdk.toHex(amount.quotient);
var calldata;
var swapInterface = options.useQuoterV2 ? this.V2INTERFACE : this.V1INTERFACE;
if (singleHop) {
var _options$sqrtPriceLim, _options;
var baseQuoteParams = {
tokenIn: route.tokenPath[0].address,
tokenOut: route.tokenPath[1].address,
fee: route.pools[0].fee,
sqrtPriceLimitX96: maiaCoreSdk.toHex((_options$sqrtPriceLim = (_options = options) == null ? void 0 : _options.sqrtPriceLimitX96) != null ? _options$sqrtPriceLim : 0)
};
var v2QuoteParams = _extends({}, baseQuoteParams, tradeType == exports.TradeType.EXACT_INPUT ? {
amountIn: quoteAmount
} : {
amount: quoteAmount
});
var v1QuoteParams = [baseQuoteParams.tokenIn, baseQuoteParams.tokenOut, baseQuoteParams.fee, quoteAmount, baseQuoteParams.sqrtPriceLimitX96];
var tradeTypeFunctionName = tradeType === exports.TradeType.EXACT_INPUT ? 'quoteExactInputSingle' : 'quoteExactOutputSingle';
calldata = swapInterface.encodeFunctionData(tradeTypeFunctionName, options.useQuoterV2 ? [v2QuoteParams] : v1QuoteParams);
} else {
var _options2;
!(((_options2 = options) == null ? void 0 : _options2.sqrtPriceLimitX96) === undefined) ? invariant(false, 'MULTIHOP_PRICE_LIMIT') : void 0;
var path = encodeRouteToPath(route, tradeType === exports.TradeType.EXACT_OUTPUT);
var _tradeTypeFunctionName = tradeType === exports.TradeType.EXACT_INPUT ? 'quoteExactInput' : 'quoteExactOutput';
calldata = swapInterface.encodeFunctionData(_tradeTypeFunctionName, [path, quoteAmount]);
}
return {
calldata: calldata,
value: maiaCoreSdk.toHex(0)
};
};
return SwapQuoter;
}();
SwapQuoter.V1INTERFACE = /*#__PURE__*/new abi.Interface(IQuoter.abi);
SwapQuoter.V2INTERFACE = /*#__PURE__*/new abi.Interface(IQuoterV2.abi);
/**
* Represents a list of pools through which a swap can occur
* @template TInput The input token
* @template TOutput The output token
*/
var Route = /*#__PURE__*/function () {
/**
* Creates an instance of route.
* @param pools An array of `Pool` objects, ordered by the route the swap will take
* @param input The input token
* @param output The output token
*/
function Route(pools, input, output) {
this._midPrice = null;
!(pools.length > 0) ? invariant(false, 'POOLS') : void 0;
var chainId = pools[0].chainId;
var allOnSameChain = pools.every(function (pool) {
return pool.chainId === chainId;
});
!allOnSameChain ? invariant(false, 'CHAIN_IDS') : void 0;
var wrappedInput = input.wrapped;
!pools[0].involvesToken(wrappedInput) ? invariant(false, 'INPUT') : void 0;
!pools[pools.length - 1].involvesToken(output.wrapped) ? invariant(false, 'OUTPUT') : void 0;
/**
* Normalizes token0-token1 order and selects the next token/fee step to add to the path
* */
var tokenPath = [wrappedInput];
for (var _iterator = _createForOfIteratorHelperLoose(pools.entries()), _step; !(_step = _iterator()).done;) {
var _step$value = _step.value,
i = _step$value[0],
pool = _step$value[1];
var currentInputToken = tokenPath[i];
!(currentInputToken.equals(pool.token0) || currentInputToken.equals(pool.token1)) ? invariant(false, 'PATH') : void 0;
var nextToken = currentInputToken.equals(pool.token0) ? pool.token1 : pool.token0;
tokenPath.push(nextToken);
}
this.pools = pools;
this.tokenPath = tokenPath;
this.input = input;
this.output = output != null ? output : tokenPath[tokenPath.length - 1];
}
_createClass(Route, [{
key: "chainId",
get: function get() {
return this.pools[0].chainId;
}
/**
* Returns the mid price of the route
*/
}, {
key: "midPrice",
get: function get() {
if (this._midPrice !== null) return this._midPrice;
var price = this.pools.slice(1).reduce(function (_ref, pool) {
var nextInput = _ref.nextInput,
price = _ref.price;
return nextInput.equals(pool.token0) ? {
nextInput: pool.token1,
price: price.multiply(pool.token0Price)
} : {
nextInput: pool.token0,
price: price.multiply(pool.token1Price)
};
}, this.pools[0].token0.equals(this.input.wrapped) ? {
nextInput: this.pools[0].token1,
price: this.pools[0].token0Price
} : {
nextInput: this.pools[0].token0,
price: this.pools[0].token1Price
}).price;
return this._midPrice = new maiaCoreSdk.Price(this.input, this.output, price.denominator, price.numerator);
}
}]);
return Route;
}();
var Route$1 = /*#__PURE__*/function () {
function Route(pairs, input, output) {
this._midPrice = null;
!(pairs.length > 0) ? invariant(false, 'PAIRS') : void 0;
var chainId = pairs[0].chainId;
!pairs.every(function (pair) {
return pair.chainId === chainId;
}) ? invariant(false, 'CHAIN_IDS') : void 0;
var wrappedInput = input.wrapped;
!pairs[0].involvesToken(wrappedInput) ? invariant(false, 'INPUT') : void 0;
!(typeof output === 'undefined' || pairs[pairs.length - 1].involvesToken(output.wrapped)) ? invariant(false, 'OUTPUT') : void 0;
var path = [wrappedInput];
for (var _iterator = _createForOfIteratorHelperLoose(pairs.entries()), _step; !(_step = _iterator()).done;) {
var _step$value = _step.value,
i = _step$value[0],
pair = _step$value[1];
var currentInput = path[i];
!(currentInput.equals(pair.token0) || currentInput.equals(pair.token1)) ? invariant(false, 'PATH') : void 0;
var _output = currentInput.equals(pair.token0) ? pair.token1 : pair.token0;
path.push(_output);
}
this.pairs = pairs;
this.path = path;
this.input = input;
this.output = output;
}
_createClass(Route, [{
key: "midPrice",
get: function get() {
if (this._midPrice !== null) return this._midPrice;
var prices = [];
for (var _iterator2 = _createForOfIteratorHelperLoose(this.pairs.entries()), _step2; !(_step2 = _iterator2()).done;) {
var _step2$value = _step2.value,
i = _step2$value[0],
pair = _step2$value[1];
prices.push(this.path[i].equals(pair.token0) ? new maiaCoreSdk.Price(pair.reserve0.currency, pair.reserve1.currency, pair.reserve0.quotient, pair.reserve1.quotient) : new maiaCoreSdk.Price(pair.reserve1.currency, pair.reserve0.currency, pair.reserve1.quotient, pair.reserve0.quotient));
}
var reduced = prices.slice(1).reduce(function (accumulator, currentValue) {
return accumulator.multiply(currentValue);
}, prices[0]);
return this._midPrice = new maiaCoreSdk.Price(this.input, this.output, reduced.denominator, reduced.numerator);
}
}, {
key: "chainId",
get: function get() {
return this.pairs[0].chainId;
}
}]);
return Route;
}();
var Staker = /*#__PURE__*/function () {
function Staker() {}
/**
* To claim rewards, must unstake and then claim.
* @param incentiveKey The unique identifier of a staking program.
* @param options Options for producing the calldata to claim. Can't claim unless you unstake.
* @returns The calldatas for 'unstakeToken' and 'claimReward'.
*/
Staker.encodeClaim = function encodeClaim(incentiveKey, options) {
var _options$amount;
var calldatas = [];
calldatas.push(Staker.INTERFACE.encodeFunctionData('unstakeToken', [this._encodeIncentiveKey(incentiveKey), maiaCoreSdk.toHex(options.tokenId)]));
var recipient = validateAndParseAddress(options.recipient);
var amount = (_options$amount = options.amount) != null ? _options$amount : 0;
calldatas.push(Staker.INTERFACE.encodeFunctionData('claimReward', [incentiveKey.rewardToken.address, recipient, maiaCoreSdk.toHex(amount)]));
return calldatas;
}
/**
*
* Note: A `tokenId` can be staked in many programs but to claim rewards and continue the program you must unstake, claim, and then restake.
* @param incentiveKeys An IncentiveKey or array of IncentiveKeys that `tokenId` is staked in.
* Input an array of IncentiveKeys to claim rewards for each program.
* @param options ClaimOptions to specify tokenId, recipient, and amount wanting to collect.
* Note that you can only specify one amount and one recipient across the various programs if you are collecting from multiple programs at once.
* @returns
*/;
Staker.collectRewards = function collectRewards(incentiveKeys, options) {
incentiveKeys = Array.isArray(incentiveKeys) ? incentiveKeys : [incentiveKeys];
var calldatas = [];
for (var _iterator = _createForOfIteratorHelperLoose(incentiveKeys), _step; !(_step = _iterator()).done;) {
var element = _step.value;
// the unique program tokenId is staked in
var incentiveKey = element;
// unstakes and claims for the unique program
calldatas = calldatas.concat(this.encodeClaim(incentiveKey, options));
// re-stakes the position for the unique program
calldatas.push(Staker.INTERFACE.encodeFunctionData('stakeToken', [this._encodeIncentiveKey(incentiveKey), maiaCoreSdk.toHex(options.tokenId)]));
}
return {
calldata: Multicall.encodeMulticall(calldatas),
value: maiaCoreSdk.toHex(0)
};
}
/**
*
* @param incentiveKeys A list of incentiveKeys to unstake from. Should include all incentiveKeys (unique staking programs) that `options.tokenId` is staked in.
* @param withdrawOptions Options for producing claim calldata and withdraw calldata. Can't withdraw without unstaking all programs for `tokenId`.
* @returns Calldata for unstaking, claiming, and withdrawing.
*/;
Staker.withdrawToken = function withdrawToken(incentiveKeys, withdrawOptions) {
var calldatas = [];
incentiveKeys = Array.isArray(incentiveKeys) ? incentiveKeys : [incentiveKeys];
var claimOptions = {
tokenId: withdrawOptions.tokenId,
recipient: withdrawOptions.recipient,
amount: withdrawOptions.amount
};
for (var _iterator2 = _createForOfIteratorHelperLoose(incentiveKeys), _step2; !(_step2 = _iterator2()).done;) {
var element = _step2.value;
var incentiveKey = element;
calldatas = calldatas.concat(this.encodeClaim(incentiveKey, claimOptions));
}
var owner = validateAndParseAddress(withdrawOptions.owner);
calldatas.push(Staker.INTERFACE.encodeFunctionData('withdrawToken', [maiaCoreSdk.toHex(withdrawOptions.tokenId), owner, withdrawOptions.data ? withdrawOptions.data : maiaCoreSdk.toHex(0)]));
return {
calldata: Multicall.encodeMulticall(calldatas),
value: maiaCoreSdk.toHex(0)
};
}
/**
*
* @param incentiveKeys A single IncentiveKey or array of IncentiveKeys to be encoded and used in the data parameter in `safeTransferFrom`
* @returns An IncentiveKey as a string
*/;
Staker.encodeDeposit = function encodeDeposit(incentiveKeys) {
incentiveKeys = Array.isArray(incentiveKeys) ? incentiveKeys : [incentiveKeys];
var data;
if (incentiveKeys.length > 1) {
var keys = [];
for (var _iterator3 = _createForOfIteratorHelperLoose(incentiveKeys), _step3; !(_step3 = _iterator3()).done;) {
var element = _step3.value;
var incentiveKey = element;
keys.push(this._encodeIncentiveKey(incentiveKey));
}
data = abi.defaultAbiCoder.encode([Staker.INCENTIVE_KEY_ABI + "[]"], [keys]);
} else {
data = abi.defaultAbiCoder.encode([Staker.INCENTIVE_KEY_ABI], [this._encodeIncentiveKey(incentiveKeys[0])]);
}
return data;
}
/**
*
* @param incentiveKey An `IncentiveKey` which represents a unique staking program.
* @returns An encoded IncentiveKey to be read by ethers
*/;
Staker._encodeIncentiveKey = function _encodeIncentiveKey(incentiveKey) {
var _incentiveKey$pool = incentiveKey.pool,
token0 = _incentiveKey$pool.token0,
token1 = _incentiveKey$pool.token1,
fee = _incentiveKey$pool.fee;
var refundee = validateAndParseAddress(incentiveKey.refundee);
return {
rewardToken: incentiveKey.rewardToken.address,
pool: Pool.getAddress(token0, token1, fee),
startTime: maiaCoreSdk.toHex(incentiveKey.startTime),
endTime: maiaCoreSdk.toHex(incentiveKey.endTime),
refundee: refundee
};
};
return Staker;
}();
Staker.INTERFACE = /*#__PURE__*/new abi.Interface(IUniswapV3Staker.abi);
Staker.INCENTIVE_KEY_ABI = 'tuple(address rewardToken, address pool, uint256 startTime, uint256 endTime, address refundee)';
/**
* Represents the Uniswap V3 SwapRouter, and has static methods for helping execute trades.
*/
var SwapRouter = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
function SwapRouter() {}
/**
* Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.
* @param trade to produce call parameters for
* @param options options for the call parameters
*/
SwapRouter.swapCallParameters = function swapCallParameters(trades, options) {
if (!Array.isArray(trades)) {
trades = [trades];
}
var sampleTrade = trades[0];
var tokenIn = sampleTrade.inputAmount.currency.wrapped;
var tokenOut = sampleTrade.outputAmount.currency.wrapped;
// All trades should have the same starting and ending token.
!trades.every(function (trade) {
return trade.inputAmount.currency.wrapped.equals(tokenIn);
}) ? invariant(false, 'TOKEN_IN_DIFF') : void 0;
!trades.every(function (trade) {
return trade.outputAmount.currency.wrapped.equals(tokenOut);
}) ? invariant(false, 'TOKEN_OUT_DIFF') : void 0;
var calldatas = [];
var ZERO_IN = maiaCoreSdk.CurrencyAmount.fromRawAmount(trades[0].inputAmount.currency, 0);
var ZERO_OUT = maiaCoreSdk.CurrencyAmount.fromRawAmount(trades[0].outputAmount.currency, 0);
var totalAmountOut = trades.reduce(function (sum, trade) {
return sum.add(trade.minimumAmountOut(options.slippageTolerance));
}, ZERO_OUT);
// flag for whether a refund needs to happen
var mustRefund = sampleTrade.inputAmount.currency.isNative && sampleTrade.tradeType === exports.TradeType.EXACT_OUTPUT;
var inputIsNative = sampleTrade.inputAmount.currency.isNative;
// flags for whether funds should be send first to the router
var outputIsNative = sampleTrade.outputAmount.currency.isNative;
var routerMustCustody = outputIsNative || !!options.fee;
var totalValue = inputIsNative ? trades.reduce(function (sum, trade) {
return sum.add(trade.maximumAmountIn(options.slippageTolerance));
}, ZERO_IN) : ZERO_IN;
// encode permit if necessary
if (options.inputTokenPermit) {
!sampleTrade.inputAmount.currency.isToken ? invariant(false, 'NON_TOKEN_PERMIT') : void 0;
calldatas.push(SelfPermit.encodePermit(sampleTrade.inputAmount.currency, options.inputTokenPermit));
}
var recipient = validateAndParseAddress(options.recipient);
var deadline = maiaCoreSdk.toHex(options.deadline);
for (var _iterator = _createForOfIteratorHelperLoose(trades), _step; !(_step = _iterator()).done;) {
var trade = _step.value;
for (var _iterator2 = _createForOfIteratorHelperLoose(trade.swaps), _step2; !(_step2 = _iterator2()).done;) {
var _step2$value = _step2.value,
route = _step2$value.route,
inputAmount = _step2$value.inputAmount,
outputAmount = _step2$value.outputAmount;
var amountIn = maiaCoreSdk.toHex(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient);
var amountOut = maiaCoreSdk.toHex(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient);
// flag for whether the trade is single hop or not
var singleHop = route.pools.length === 1;
if (singleHop) {
if (trade.tradeType === exports.TradeType.EXACT_INPUT) {
var _options$sqrtPriceLim;
var exactInputSingleParams = {
tokenIn: route.tokenPath[0].address,
tokenOut: route.tokenPath[1].address,
fee: route.pools[0].fee,
recipient: routerMustCustody ? ADDRESS_ZERO : recipient,
deadline: deadline,
amountIn: amountIn,
amountOutMinimum: amountOut,
sqrtPriceLimitX96: maiaCoreSdk.toHex((_options$sqrtPriceLim = options.sqrtPriceLimitX96) != null ? _options$sqrtPriceLim : 0)
};
calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInputSingle', [exactInputSingleParams]));
} else {
var _options$sqrtPriceLim2;
var exactOutputSingleParams = {
tokenIn: route.tokenPath[0].address,
tokenOut: route.tokenPath[1].address,
fee: route.pools[0].fee,
recipient: routerMustCustody ? ADDRESS_ZERO : recipient,
deadline: deadline,
amountOut: amountOut,
amountInMaximum: amountIn,
sqrtPriceLimitX96: maiaCoreSdk.toHex((_options$sqrtPriceLim2 = options.sqrtPriceLimitX96) != null ? _options$sqrtPriceLim2 : 0)
};
calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutputSingle', [exactOutputSingleParams]));
}
} else {
!(options.sqrtPriceLimitX96 === undefined) ? invariant(false, 'MULTIHOP_PRICE_LIMIT') : void 0;
var path = encodeRouteToPath(route, trade.tradeType === exports.TradeType.EXACT_OUTPUT);
if (trade.tradeType === exports.TradeType.EXACT_INPUT) {
var exactInputParams = {
path: path,
recipient: routerMustCustody ? ADDRESS_ZERO : recipient,
deadline: deadline,
amountIn: amountIn,
amountOutMinimum: amountOut
};
calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInput', [exactInputParams]));
} else {
var exactOutputParams = {
path: path,
recipient: routerMustCustody ? ADDRESS_ZERO : recipient,
deadline: deadline,
amountOut: amountOut,
amountInMaximum: amountIn
};
calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutput', [exactOutputParams]));
}
}
}
}
// unwrap
if (routerMustCustody) {
if (options.fee) {
if (outputIsNative) {
calldatas.push(Payments.encodeUnwrapWETH9(totalAmountOut.quotient, recipient, options.fee));
} else {
calldatas.push(Payments.encodeSweepToken(sampleTrade.outputAmount.currency.wrapped, totalAmountOut.quotient, recipient, options.fee));
}
} else {
calldatas.push(Payments.encodeUnwrapWETH9(totalAmountOut.quotient, recipient));
}
}
// refund
if (mustRefund) {
calldatas.push(Payments.encodeRefundETH());
}
return {
calldata: Multicall.encodeMulticall(calldatas),
value: maiaCoreSdk.toHex(totalValue.quotient)
};
};
return SwapRouter;
}();
SwapRouter.INTERFACE = /*#__PURE__*/new abi.Interface(ISwapRouter.abi);
// 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) ? invariant(false, 'MAX_SIZE_ZERO') : void 0;
// this is an invariant because the interface cannot return multiple removed items if items.length exceeds maxSize
!(items.length <= maxSize) ? invariant(false, 'ITEMS_SIZE') : 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;
}
}
/**
* Computes a vault address
* @param factoryAddress The Vault factory address
* @param underlying The underlying token of the vault
* @param initCodeHash The init code hash used to compute the vault address
* @returns The vault address
*/
function computeVaultAddress(_ref) {
var factoryAddress = _ref.factoryAddress,
underlying = _ref.underlying,
initCodeHash = _ref.initCodeHash;
!!!factoryAddress ? invariant(false, 'Invalid factory address') : void 0;
!!!initCodeHash ? invariant(false, 'Invalid init code hash') : void 0;
return address.getCreate2Address(factoryAddress, underlying.concat('000000000000000000000000'), initCodeHash);
}
/**
* Represents an ERC4626 vault.
*/
var Vault = /*#__PURE__*/function () {
/**
* Construct a vault
* @param underlying One of the tokens in the vault, the underlying token
* @param vault The other token in the vault, the vault's address
* @param fee The fee in hundredths of a bips of the input amount of every swap that is collected by the vault
*/
function Vault(underlying, vault, fee // Default fee is 0
) {
var _ref = underlying.sortsBefore(vault) ? [underlying, vault] : [vault, underlying];
this.token0 = _ref[0];
this.token1 = _ref[1];
this.fee = fee != null ? fee : new maiaCoreSdk.Percent(0);
this.vaultIsToken0 = this.token0.equals(vault);
}
// Only one token used to get Address since the other is the Vault's address
Vault.getAddress = function getAddress(underlying, initCodeHashManualOverride, factoryAddressOverride) {
return computeVaultAddress({
factoryAddress: factoryAddressOverride != null ? factoryAddressOverride : maiaCoreSdk.BalancerAddresses[underlying.chainId].ComposableStablePoolWrapperFactory,
underlying: underlying.address,
initCodeHash: initCodeHashManualOverride != null ? initCodeHashManualOverride : maiaCoreSdk.BalancerAddresses[underlying.chainId].ComposableStablePoolWrapperInitCodeHash
});
}
/**
* Returns the vault token
* @returns The vault token
*/;
var _proto = Vault.prototype;
_proto.vault = function vault() {
return this.vaultIsToken0 ? this.token0 : this.token1;
}
/**
* Returns the underlying token
* @returns The underlying token
*/;
_proto.underlying = function underlying() {
return this.vaultIsToken0 ? this.token1 : this.token0;
}
/**
* Returns true if the token is either token0 or token1
* @param token The token to check
* @returns True if token is either token0 or token
*/;
_proto.involvesToken = function involvesToken(token) {
return token.equals(this.token0) || token.equals(this.token1);
}
/**
* Return the price of the given token in terms of the other token in the vault.
* @param token The token to return price of
* @returns The price of the given token, in terms of the other.
*/;
_proto.priceOf = function priceOf(token) {
!this.involvesToken(token) ? invariant(false, 'TOKEN') : void 0;
return token.equals(this.token0) ? this.token0Price : this.token1Price;
}
/**
* Returns the chain ID of the tokens in the vault.
*/;
_createClass(Vault, [{
key: "chainId",
get: function get() {
return this.token0.chainId;
}
}]);
return Vault;
}();
/**
* Trades comparator, an extension of the input output comparator that also considers other dimensions of the trade in ranking them
* @template TInput The input token, either Ether or an ERC-20
* @template TOutput The output token, either Ether or an ERC-20
* @template TTradeType The trade type, either exact input or exact output
* @param a The first trade to compare
* @param b The second trade to compare
* @returns A sorted ordering for two neighboring elements in a trade array
*/
function tradeComparator(a, b) {
// must have same input and output token for comparison
!a.inputAmount.currency.equals(b.inputAmount.currency) ? invariant(false, 'INPUT_CURRENCY') : void 0;
!a.outputAmount.currency.equals(b.outputAmount.currency) ? invariant(false, 'OUTPUT_CURRENCY') : void 0;
if (a.outputAmount.equalTo(b.outputAmount)) {
if (a.inputAmount.equalTo(b.inputAmount)) {
// consider the number of hops since each hop costs gas
var aHops = a.swaps.reduce(function (total, cur) {
return total + cur.route.tokenPath.length;
}, 0);
var bHops = b.swaps.reduce(function (total, cur) {
return total + cur.route.tokenPath.length;
}, 0);
return aHops - bHops;
}
// trade A requires less input than trade B, so A should come first
if (a.inputAmount.lessThan(b.inputAmount)) {
return -1;
} else {
return 1;
}
// tradeA has less output than trade B, so should come second
} else if (a.outputAmount.lessThan(b.outputAmount)) {
return 1;
} else {
return -1;
}
}
/**
* Represents a trade executed against a set of routes where some percentage of the input is
* split across each route.
*
* Each route has its own set of pools. Pools can not be re-used across routes.
*
* Does not account for slippage, i.e., changes in price environment that can occur between
* the time the trade is submitted and when it is executed.
* @template TInput The input token, either Ether or an ERC-20
* @template TOutput The output token, either Ether or an ERC-20
* @template TTradeType The trade type, either exact input or exact output
*/
var Trade = /*#__PURE__*/function () {
/**
* Construct a trade by passing in the pre-computed property values
* @param routes The routes through which the trade occurs
* @param tradeType The type of trade, exact input or exact output
*/
function Trade(_ref) {
var routes = _ref.routes,
tradeType = _ref.tradeType;
var inputCurrency = routes[0].inputAmount.currency;
var outputCurrency = routes[0].outputAmount.currency;
!routes.every(function (_ref2) {
var route = _ref2.route;
return inputCurrency.wrapped.equals(route.input.wrapped);
}) ? invariant(false, 'INPUT_CURRENCY_MATCH') : void 0;
!routes.every(function (_ref3) {
var route = _ref3.route;
return outputCurrency.wrapped.equals(route.output.wrapped);
}) ? invariant(false, 'OUTPUT_CURRENCY_MATCH') : void 0;
var numPools = routes.map(function (_ref4) {
var route = _ref4.route;
return route.pools.length;
}).reduce(function (total, cur) {
return total + cur;
}, 0);
var poolAddressSet = new Set();
for (var _iterator = _createForOfIteratorHelperLoose(routes), _step; !(_step = _iterator()).done;) {
var route = _step.value.route;
for (var _iterator2 = _createForOfIteratorHelperLoose(route.pools), _step2; !(_step2 = _iterator2()).done;) {
var pool = _step2.value;
if (pool instanceof Pool) poolAddressSet.add(Pool.getAddress(pool.token0, pool.token1, pool.fee));
if (pool instanceof ComposableStablePool) poolAddressSet.add(pool.pool.address);
if (pool instanceof Vault) poolAddressSet.add(pool.vault().address);
}
}
!(numPools == poolAddressSet.size) ? invariant(false, 'POOLS_DUPLICATED') : void 0;
this.swaps = routes;
this.tradeType = tradeType;
}
/**
* @deprecated Deprecated in favor of 'swaps' property. If the trade consists of multiple routes
* this will return an error.
*
* When the trade consists of just a single route, this returns the route of the trade,
* i.e. which pools the trade goes through.
*/
/**
* Constructs an exact in trade with the given amount in and route
* @template TInput The input token, either Ether or an ERC-20
* @template TOutput The output token, either Ether or an ERC-20
* @param route The route of the exact in trade
* @param amountIn The amount being passed in
* @returns The exact in trade
*/
Trade.exactIn =
/*#__PURE__*/
function () {
var _exactIn = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(route, amountIn) {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", Trade.fromRoute(route, amountIn, exports.TradeType.EXACT_INPUT));
case 1:
case "end":
return _context.stop();
}
}, _callee);
}));
function exactIn(_x, _x2) {
return _exactIn.apply(this, arguments);
}
return exactIn;
}()
/**
* Constructs an exact out trade with the given amount out and route
* @template TInput The input token, either Ether or an ERC-20
* @template TOutput The output token, either Ether or an ERC-20
* @param route The route of the exact out trade
* @param amountOut The amount returned by the trade
* @returns The exact out trade
*/
;
Trade.exactOut =
/*#__PURE__*/
function () {
var _exactOut = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(route, amountOut) {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt("return", Trade.fromRoute(route, amountOut, exports.TradeType.EXACT_OUTPUT));
case 1:
case "end":
return _context2.stop();
}
}, _callee2);
}));
function exactOut(_x3, _x4) {
return _exactOut.apply(this, arguments);
}
return exactOut;
}()
/**
* Constructs a trade by simulating swaps through the given route
* @template TInput The input token, either Ether or an ERC-20.
* @template TOutput The output token, either Ether or an ERC-20.
* @template TTradeType The type of the trade, either exact in or exact out.
* @param route route to swap through
* @param amount the amount specified, either input or output, depending on tradeType
* @param tradeType whether the trade is an exact input or exact output swap
* @returns The route
*/
;
Trade.fromRoute =
/*#__PURE__*/
function () {
var _fromRoute = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(route, amount, tradeType) {
var amounts, inputAmount, outputAmount, i, pool, _yield$pool$getOutput, _outputAmount, _i, _pool, _yield$_pool$getInput, _inputAmount;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
amounts = new Array(route.tokenPath.length);
if (!(tradeType === exports.TradeType.EXACT_INPUT)) {
_context3.next = 19;
break;
}
!amount.currency.equals(route.input) ? invariant(false, 'INPUT') : void 0;
amounts[0] = amount.wrapped;
i = 0;
case 5:
if (!(i < route.tokenPath.length - 1)) {
_context3.next = 15;
break;
}
pool = route.pools[i];
_context3.next = 9;
return pool.getOutputAmount(amounts[i]);
case 9:
_yield$pool$getOutput = _context3.sent;
_outputAmount = _yield$pool$getOutput[0];
amounts[i + 1] = _outputAmount;
case 12:
i++;
_context3.next = 5;
break;
case 15:
inputAmount = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
outputAmount = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.output, amounts[amounts.length - 1].numerator, amounts[amounts.length - 1].denominator);
_context3.next = 34;
break;
case 19:
!amount.currency.equals(route.output) ? invariant(false, 'OUTPUT') : void 0;
amounts[amounts.length - 1] = amount.wrapped;
_i = route.tokenPath.length - 1;
case 22:
if (!(_i > 0)) {
_context3.next = 32;
break;
}
_pool = route.pools[_i - 1];
_context3.next = 26;
return _pool.getInputAmount(amounts[_i]);
case 26:
_yield$_pool$getInput = _context3.sent;
_inputAmount = _yield$_pool$getInput[0];
amounts[_i - 1] = _inputAmount;
case 29:
_i--;
_context3.next = 22;
break;
case 32:
inputAmount = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.input, amounts[0].numerator, amounts[0].denominator);
outputAmount = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
case 34:
return _context3.abrupt("return", new Trade({
routes: [{
inputAmount: inputAmount,
outputAmount: outputAmount,
route: route
}],
tradeType: tradeType
}));
case 35:
case "end":
return _context3.stop();
}
}, _callee3);
}));
function fromRoute(_x5, _x6, _x7) {
return _fromRoute.apply(this, arguments);
}
return fromRoute;
}()
/**
* Constructs a trade from routes by simulating swaps
*
* @template TInput The input token, either Ether or an ERC-20.
* @template TOutput The output token, either Ether or an ERC-20.
* @template TTradeType The type of the trade, either exact in or exact out.
* @param routes the routes to swap through and how much of the amount should be routed through each
* @param tradeType whether the trade is an exact input or exact output swap
* @returns The trade
*/
;
Trade.fromRoutes =
/*#__PURE__*/
function () {
var _fromRoutes = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(routes, tradeType) {
var populatedRoutes, _iterator3, _step3, _step3$value, route, amount, amounts, inputAmount, outputAmount, i, pool, _yield$pool$getOutput2, _outputAmount2, _i2, _pool2, _yield$_pool2$getInpu, _inputAmount2;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
populatedRoutes = [];
_iterator3 = _createForOfIteratorHelperLoose(routes);
case 2:
if ((_step3 = _iterator3()).done) {
_context4.next = 43;
break;
}
_step3$value = _step3.value, route = _step3$value.route, amount = _step3$value.amount;
amounts = new Array(route.tokenPath.length);
inputAmount = void 0;
outputAmount = void 0;
if (!(tradeType === exports.TradeType.EXACT_INPUT)) {
_context4.next = 25;
break;
}
!amount.currency.equals(route.input) ? invariant(false, 'INPUT') : void 0;
inputAmount = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
amounts[0] = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.input.wrapped, amount.numerator, amount.denominator);
i = 0;
case 12:
if (!(i < route.tokenPath.length - 1)) {
_context4.next = 22;
break;
}
pool = route.pools[i];
_context4.next = 16;
return pool.getOutputAmount(amounts[i]);
case 16:
_yield$pool$getOutput2 = _context4.sent;
_outputAmount2 = _yield$pool$getOutput2[0];
amounts[i + 1] = _outputAmount2;
case 19:
i++;
_context4.next = 12;
break;
case 22:
outputAmount = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.output, amounts[amounts.length - 1].numerator, amounts[amounts.length - 1].denominator);
_context4.next = 40;
break;
case 25:
!amount.currency.equals(route.output) ? invariant(false, 'OUTPUT') : void 0;
outputAmount = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
amounts[amounts.length - 1] = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.output.wrapped, amount.numerator, amount.denominator);
_i2 = route.tokenPath.length - 1;
case 29:
if (!(_i2 > 0)) {
_context4.next = 39;
break;
}
_pool2 = route.pools[_i2 - 1];
_context4.next = 33;
return _pool2.getInputAmount(amounts[_i2]);
case 33:
_yield$_pool2$getInpu = _context4.sent;
_inputAmount2 = _yield$_pool2$getInpu[0];
amounts[_i2 - 1] = _inputAmount2;
case 36:
_i2--;
_context4.next = 29;
break;
case 39:
inputAmount = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.input, amounts[0].numerator, amounts[0].denominator);
case 40:
populatedRoutes.push({
route: route,
inputAmount: inputAmount,
outputAmount: outputAmount
});
case 41:
_context4.next = 2;
break;
case 43:
return _context4.abrupt("return", new Trade({
routes: populatedRoutes,
tradeType: tradeType
}));
case 44:
case "end":
return _context4.stop();
}
}, _callee4);
}));
function fromRoutes(_x8, _x9) {
return _fromRoutes.apply(this, arguments);
}
return fromRoutes;
}()
/**
* Creates a trade without computing the result of swapping through the route. Useful when you have simulated the trade
* elsewhere and do not have any tick data
* @template TInput The input token, either Ether or an ERC-20
* @template TOutput The output token, either Ether or an ERC-20
* @template TTradeType The type of the trade, either exact in or exact out
* @param constructorArguments The arguments passed to the trade constructor
* @returns The unchecked trade
*/
;
Trade.createUncheckedTrade = function createUncheckedTrade(constructorArguments) {
return new Trade(_extends({}, constructorArguments, {
routes: [{
inputAmount: constructorArguments.inputAmount,
outputAmount: constructorArguments.outputAmount,
route: constructorArguments.route
}]
}));
}
/**
* Creates a trade without computing the result of swapping through the routes. Useful when you have simulated the trade
* elsewhere and do not have any tick data
* @template TInput The input token, either Ether or an ERC-20
* @template TOutput The output token, either Ether or an ERC-20
* @template TTradeType The type of the trade, either exact in or exact out
* @param constructorArguments The arguments passed to the trade constructor
* @returns The unchecked trade
*/;
Trade.createUncheckedTradeWithMultipleRoutes = function createUncheckedTradeWithMultipleRoutes(constructorArguments) {
return new Trade(constructorArguments);
}
/**
* Get the minimum amount that must be received from this trade for the given slippage tolerance
* @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
* @returns The amount out
*/;
var _proto = Trade.prototype;
_proto.minimumAmountOut = function minimumAmountOut(slippageTolerance, amountOut) {
if (amountOut === void 0) {
amountOut = this.outputAmount;
}
!!slippageTolerance.lessThan(maiaCoreSdk.ZERO) ? invariant(false, 'SLIPPAGE_TOLERANCE') : void 0;
if (this.tradeType === exports.TradeType.EXACT_OUTPUT) {
return amountOut;
} else {
var slippageAdjustedAmountOut = new maiaCoreSdk.Fraction(maiaCoreSdk.ONE).add(slippageTolerance).invert().multiply(amountOut.quotient).quotient;
return maiaCoreSdk.CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut);
}
}
/**
* Get the maximum amount in that can be spent via this trade for the given slippage tolerance
* @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
* @returns The amount in
*/;
_proto.maximumAmountIn = function maximumAmountIn(slippageTolerance, amountIn) {
if (amountIn === void 0) {
amountIn = this.inputAmount;
}
!!slippageTolerance.lessThan(maiaCoreSdk.ZERO) ? invariant(false, 'SLIPPAGE_TOLERANCE') : void 0;
if (this.tradeType === exports.TradeType.EXACT_INPUT) {
return amountIn;
} else {
var slippageAdjustedAmountIn = new maiaCoreSdk.Fraction(maiaCoreSdk.ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient;
return maiaCoreSdk.CurrencyAmount.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn);
}
}
/**
* Return the execution price after accounting for slippage tolerance
* @param slippageTolerance the allowed tolerated slippage
* @returns The execution price
*/;
_proto.worstExecutionPrice = function worstExecutionPrice(slippageTolerance) {
return new maiaCoreSdk.Price(this.inputAmount.currency, this.outputAmount.currency, this.maximumAmountIn(slippageTolerance).quotient, this.minimumAmountOut(slippageTolerance).quotient);
}
/**
* Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
* amount to an output token, making at most `maxHops` hops.
* Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
* the amount in among multiple routes.
* @param pools the pools to consider in finding the best trade
* @param nextAmountIn exact amount of input currency to spend
* @param currencyOut the desired currency out
* @param maxNumResults maximum number of results to return
* @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
* @param currentPools used in recursion; the current list of pools
* @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
* @param bestTrades used in recursion; the current list of best trades
* @returns The exact in trade
*/;
Trade.bestTradeExactIn =
/*#__PURE__*/
function () {
var _bestTradeExactIn = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(pools, currencyAmountIn, currencyOut, _temp,
// used in recursion.
currentPools, nextAmountIn, bestTrades) {
var _ref5, _ref5$maxNumResults, maxNumResults, _ref5$maxHops, maxHops, amountIn, tokenOut, i, pool, amountOut, _yield$pool$getOutput3, poolsExcludingThisPool;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
_ref5 = _temp === void 0 ? {} : _temp, _ref5$maxNumResults = _ref5.maxNumResults, maxNumResults = _ref5$maxNumResults === void 0 ? 3 : _ref5$maxNumResults, _ref5$maxHops = _ref5.maxHops, maxHops = _ref5$maxHops === void 0 ? 3 : _ref5$maxHops;
if (currentPools === void 0) {
currentPools = [];
}
if (nextAmountIn === void 0) {
nextAmountIn = currencyAmountIn;
}
if (bestTrades === void 0) {
bestTrades = [];
}
!(pools.length > 0) ? invariant(false, 'POOLS') : void 0;
!(maxHops > 0) ? invariant(false, 'MAX_HOPS') : void 0;
!(currencyAmountIn === nextAmountIn || currentPools.length > 0) ? invariant(false, 'INVALID_RECURSION') : void 0;
amountIn = nextAmountIn.wrapped;
tokenOut = currencyOut.wrapped;
i = 0;
case 10:
if (!(i < pools.length)) {
_context5.next = 46;
break;
}
pool = pools[i]; // pool irrelevant
if (!(!pool.token0.equals(amountIn.currency) && !pool.token1.equals(amountIn.currency))) {
_context5.next = 14;
break;
}
return _context5.abrupt("continue", 43);
case 14:
amountOut = void 0;
_context5.prev = 15;
_context5.next = 19;
return pool.getOutputAmount(amountIn);
case 19:
_yield$pool$getOutput3 = _context5.sent;
amountOut = _yield$pool$getOutput3[0];
_context5.next = 28;
break;
case 23:
_context5.prev = 23;
_context5.t0 = _context5["catch"](15);
if (!(_context5.t0 instanceof InsufficientInputAmountError)) {
_context5.next = 27;
break;
}
return _context5.abrupt("continue", 43);
case 27:
throw _context5.t0;
case 28:
if (!(amountOut.currency.isToken && amountOut.currency.equals(tokenOut))) {
_context5.next = 39;
break;
}
_context5.t1 = sortedInsert;
_context5.t2 = bestTrades;
_context5.next = 33;
return Trade.fromRoute(new Route([].concat(currentPools, [pool]), currencyAmountIn.currency, currencyOut), currencyAmountIn, exports.TradeType.EXACT_INPUT);
case 33:
_context5.t3 = _context5.sent;
_context5.t4 = maxNumResults;
_context5.t5 = tradeComparator;
(0, _context5.t1)(_context5.t2, _context5.t3, _context5.t4, _context5.t5);
_context5.next = 43;
break;
case 39:
if (!(maxHops > 1 && pools.length > 1)) {
_context5.next = 43;
break;
}
poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length)); // otherwise, consider all the other paths that lead from this token as long as we have not exceeded maxHops
_context5.next = 43;
return Trade.bestTradeExactIn(poolsExcludingThisPool, currencyAmountIn, currencyOut, {
maxNumResults: maxNumResults,
maxHops: maxHops - 1
}, [].concat(currentPools, [pool]), amountOut, bestTrades);
case 43:
i++;
_context5.next = 10;
break;
case 46:
return _context5.abrupt("return", bestTrades);
case 47:
case "end":
return _context5.stop();
}
}, _callee5, null, [[15, 23]]);
}));
function bestTradeExactIn(_x10, _x11, _x12, _x13, _x14, _x15, _x16) {
return _bestTradeExactIn.apply(this, arguments);
}
return bestTradeExactIn;
}()
/**
* similar to the above method but instead targets a fixed output amount
* given a list of pools, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
* to an output token amount, making at most `maxHops` hops
* note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
* the amount in among multiple routes.
* @param pools the pools to consider in finding the best trade
* @param currencyIn the currency to spend
* @param currencyAmountOut the desired currency amount out
* @param nextAmountOut the exact amount of currency out
* @param maxNumResults maximum number of results to return
* @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
* @param currentPools used in recursion; the current list of pools
* @param bestTrades used in recursion; the current list of best trades
* @returns The exact out trade
*/
;
Trade.bestTradeExactOut =
/*#__PURE__*/
function () {
var _bestTradeExactOut = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(pools, currencyIn, currencyAmountOut, _temp2,
// used in recursion.
currentPools, nextAmountOut, bestTrades) {
var _ref6, _ref6$maxNumResults, maxNumResults, _ref6$maxHops, maxHops, amountOut, tokenIn, i, pool, amountIn, _yield$pool$getInputA, poolsExcludingThisPool;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
_ref6 = _temp2 === void 0 ? {} : _temp2, _ref6$maxNumResults = _ref6.maxNumResults, maxNumResults = _ref6$maxNumResults === void 0 ? 3 : _ref6$maxNumResults, _ref6$maxHops = _ref6.maxHops, maxHops = _ref6$maxHops === void 0 ? 3 : _ref6$maxHops;
if (currentPools === void 0) {
currentPools = [];
}
if (nextAmountOut === void 0) {
nextAmountOut = currencyAmountOut;
}
if (bestTrades === void 0) {
bestTrades = [];
}
!(pools.length > 0) ? invariant(false, 'POOLS') : void 0;
!(maxHops > 0) ? invariant(false, 'MAX_HOPS') : void 0;
!(currencyAmountOut === nextAmountOut || currentPools.length > 0) ? invariant(false, 'INVALID_RECURSION') : void 0;
amountOut = nextAmountOut.wrapped;
tokenIn = currencyIn.wrapped;
i = 0;
case 10:
if (!(i < pools.length)) {
_context6.next = 46;
break;
}
pool = pools[i]; // pool irrelevant
if (!(!pool.token0.equals(amountOut.currency) && !pool.token1.equals(amountOut.currency))) {
_context6.next = 14;
break;
}
return _context6.abrupt("continue", 43);
case 14:
amountIn = void 0;
_context6.prev = 15;
_context6.next = 19;
return pool.getInputAmount(amountOut);
case 19:
_yield$pool$getInputA = _context6.sent;
amountIn = _yield$pool$getInputA[0];
_context6.next = 28;
break;
case 23:
_context6.prev = 23;
_context6.t0 = _context6["catch"](15);
if (!(_context6.t0 instanceof InsufficientReservesError)) {
_context6.next = 27;
break;
}
return _context6.abrupt("continue", 43);
case 27:
throw _context6.t0;
case 28:
if (!amountIn.currency.equals(tokenIn)) {
_context6.next = 39;
break;
}
_context6.t1 = sortedInsert;
_context6.t2 = bestTrades;
_context6.next = 33;
return Trade.fromRoute(new Route([pool].concat(currentPools), currencyIn, currencyAmountOut.currency), currencyAmountOut, exports.TradeType.EXACT_OUTPUT);
case 33:
_context6.t3 = _context6.sent;
_context6.t4 = maxNumResults;
_context6.t5 = tradeComparator;
(0, _context6.t1)(_context6.t2, _context6.t3, _context6.t4, _context6.t5);
_context6.next = 43;
break;
case 39:
if (!(maxHops > 1 && pools.length > 1)) {
_context6.next = 43;
break;
}
poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length)); // otherwise, consider all the other paths that arrive at this token as long as we have not exceeded maxHops
_context6.next = 43;
return Trade.bestTradeExactOut(poolsExcludingThisPool, currencyIn, currencyAmountOut, {
maxNumResults: maxNumResults,
maxHops: maxHops - 1
}, [pool].concat(currentPools), amountIn, bestTrades);
case 43:
i++;
_context6.next = 10;
break;
case 46:
return _context6.abrupt("return", bestTrades);
case 47:
case "end":
return _context6.stop();
}
}, _callee6, null, [[15, 23]]);
}));
function bestTradeExactOut(_x17, _x18, _x19, _x20, _x21, _x22, _x23) {
return _bestTradeExactOut.apply(this, arguments);
}
return bestTradeExactOut;
}();
_createClass(Trade, [{
key: "route",
get: function get() {
!(this.swaps.length == 1) ? invariant(false, 'MULTIPLE_ROUTES') : void 0;
return this.swaps[0].route;
}
/**
* The input amount for the trade assuming no slippage.
*/
}, {
key: "inputAmount",
get: function get() {
if (this._inputAmount) {
return this._inputAmount;
}
var inputCurrency = this.swaps[0].inputAmount.currency;
var totalInputFromRoutes = this.swaps.map(function (_ref7) {
var inputAmount = _ref7.inputAmount;
return inputAmount;
}).reduce(function (total, cur) {
return total.add(cur);
}, maiaCoreSdk.CurrencyAmount.fromRawAmount(inputCurrency, 0));
this._inputAmount = totalInputFromRoutes;
return this._inputAmount;
}
/**
* The output amount for the trade assuming no slippage.
*/
}, {
key: "outputAmount",
get: function get() {
if (this._outputAmount) {
return this._outputAmount;
}
var outputCurrency = this.swaps[0].outputAmount.currency;
var totalOutputFromRoutes = this.swaps.map(function (_ref8) {
var outputAmount = _ref8.outputAmount;
return outputAmount;
}).reduce(function (total, cur) {
return total.add(cur);
}, maiaCoreSdk.CurrencyAmount.fromRawAmount(outputCurrency, 0));
this._outputAmount = totalOutputFromRoutes;
return this._outputAmount;
}
/**
* The price expressed in terms of output amount/input amount.
*/
}, {
key: "executionPrice",
get: function get() {
var _this$_executionPrice;
return (_this$_executionPrice = this._executionPrice) != null ? _this$_executionPrice : this._executionPrice = new maiaCoreSdk.Price(this.inputAmount.currency, this.outputAmount.currency, this.inputAmount.quotient, this.outputAmount.quotient);
}
/**
* Returns the percent difference between the route's mid price and the price impact
*/
}, {
key: "priceImpact",
get: function get() {
if (this._priceImpact) {
return this._priceImpact;
}
var spotOutputAmount = maiaCoreSdk.CurrencyAmount.fromRawAmount(this.outputAmount.currency, 0);
for (var _iterator4 = _createForOfIteratorHelperLoose(this.swaps), _step4; !(_step4 = _iterator4()).done;) {
var _step4$value = _step4.value,
route = _step4$value.route,
inputAmount = _step4$value.inputAmount;
var midPrice = route.midPrice;
spotOutputAmount = spotOutputAmount.add(midPrice.quote(inputAmount));
}
var priceImpact = spotOutputAmount.subtract(this.outputAmount).divide(spotOutputAmount);
this._priceImpact = new maiaCoreSdk.Percent(priceImpact.numerator, priceImpact.denominator);
return this._priceImpact;
}
}]);
return Trade;
}();
/**
* 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 maiaCoreSdk.Percent(priceImpact.numerator, priceImpact.denominator);
}
// comparator function that allows sorting trades by their output amounts, in decreasing order, and then input amounts
// in increasing order. i.e. the best trades have the most outputs for the least inputs and are sorted first
function inputOutputComparator(a, b) {
// must have same input and output token for comparison
!a.inputAmount.currency.equals(b.inputAmount.currency) ? invariant(false, 'INPUT_CURRENCY') : void 0;
!a.outputAmount.currency.equals(b.outputAmount.currency) ? invariant(false, 'OUTPUT_CURRENCY') : void 0;
if (a.outputAmount.equalTo(b.outputAmount)) {
if (a.inputAmount.equalTo(b.inputAmount)) {
return 0;
}
// trade A requires less input than trade B, so A should come first
if (a.inputAmount.lessThan(b.inputAmount)) {
return -1;
} else {
return 1;
}
} else {
// tradeA has less output than trade B, so should come second
if (a.outputAmount.lessThan(b.outputAmount)) {
return 1;
} else {
return -1;
}
}
}
// extension of the input output comparator that also considers other dimensions of the trade in ranking them
function tradeComparator$1(a, b) {
var ioComp = inputOutputComparator(a, b);
if (ioComp !== 0) {
return ioComp;
}
// consider lowest slippage next, since these are less likely to fail
if (a.priceImpact.lessThan(b.priceImpact)) {
return -1;
} else if (a.priceImpact.greaterThan(b.priceImpact)) {
return 1;
}
// finally consider the number of hops since each hop costs gas
return a.route.path.length - b.route.path.length;
}
/**
* Represents a trade executed against a list of pairs.
* Does not account for slippage, i.e. trades that front run this trade and move the price.
*/
var Trade$1 = /*#__PURE__*/function () {
function Trade(route, amount, tradeType) {
this.route = route;
this.tradeType = tradeType;
var tokenAmounts = new Array(route.path.length);
if (tradeType === exports.TradeType.EXACT_INPUT) {
!amount.currency.equals(route.input) ? invariant(false, 'INPUT') : void 0;
tokenAmounts[0] = amount.wrapped;
for (var i = 0; i < route.path.length - 1; i++) {
var pair = route.pairs[i];
var _pair$getOutputAmount = pair.getOutputAmount(tokenAmounts[i]),
outputAmount = _pair$getOutputAmount[0];
tokenAmounts[i + 1] = outputAmount;
}
this.inputAmount = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
this.outputAmount = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.output, tokenAmounts[tokenAmounts.length - 1].numerator, tokenAmounts[tokenAmounts.length - 1].denominator);
} else {
!amount.currency.equals(route.output) ? invariant(false, 'OUTPUT') : void 0;
tokenAmounts[tokenAmounts.length - 1] = amount.wrapped;
for (var _i = route.path.length - 1; _i > 0; _i--) {
var _pair = route.pairs[_i - 1];
var _pair$getInputAmount = _pair.getInputAmount(tokenAmounts[_i]),
inputAmount = _pair$getInputAmount[0];
tokenAmounts[_i - 1] = inputAmount;
}
this.inputAmount = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.input, tokenAmounts[0].numerator, tokenAmounts[0].denominator);
this.outputAmount = maiaCoreSdk.CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
}
this.executionPrice = new maiaCoreSdk.Price(this.inputAmount.currency, this.outputAmount.currency, this.inputAmount.quotient, this.outputAmount.quotient);
this.priceImpact = computePriceImpact(route.midPrice, this.inputAmount, this.outputAmount);
}
/**
* Constructs an exact in trade with the given amount in and route
* @param route route of the exact in trade
* @param amountIn the amount being passed in
*/
Trade.exactIn = function exactIn(route, amountIn) {
return new Trade(route, amountIn, exports.TradeType.EXACT_INPUT);
}
/**
* Constructs an exact out trade with the given amount out and route
* @param route route of the exact out trade
* @param amountOut the amount returned by the trade
*/;
Trade.exactOut = function exactOut(route, amountOut) {
return new Trade(route, amountOut, exports.TradeType.EXACT_OUTPUT);
}
/**
* Get the minimum amount that must be received from this trade for the given slippage tolerance
* @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
*/;
var _proto = Trade.prototype;
_proto.minimumAmountOut = function minimumAmountOut(slippageTolerance) {
!!slippageTolerance.lessThan(maiaCoreSdk.ZERO) ? invariant(false, 'SLIPPAGE_TOLERANCE') : void 0;
if (this.tradeType === exports.TradeType.EXACT_OUTPUT) {
return this.outputAmount;
} else {
var slippageAdjustedAmountOut = new maiaCoreSdk.Fraction(maiaCoreSdk.ONE).add(slippageTolerance).invert().multiply(this.outputAmount.quotient).quotient;
return maiaCoreSdk.CurrencyAmount.fromRawAmount(this.outputAmount.currency, slippageAdjustedAmountOut);
}
}
/**
* Get the maximum amount in that can be spent via this trade for the given slippage tolerance
* @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
*/;
_proto.maximumAmountIn = function maximumAmountIn(slippageTolerance) {
!!slippageTolerance.lessThan(maiaCoreSdk.ZERO) ? invariant(false, 'SLIPPAGE_TOLERANCE') : void 0;
if (this.tradeType === exports.TradeType.EXACT_INPUT) {
return this.inputAmount;
} else {
var slippageAdjustedAmountIn = new maiaCoreSdk.Fraction(maiaCoreSdk.ONE).add(slippageTolerance).multiply(this.inputAmount.quotient).quotient;
return maiaCoreSdk.CurrencyAmount.fromRawAmount(this.inputAmount.currency, slippageAdjustedAmountIn);
}
}
/**
* Given a list of pairs, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
* amount to an output token, making at most `maxHops` hops.
* Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
* the amount in among multiple routes.
* @param pairs the pairs to consider in finding the best trade
* @param nextAmountIn exact amount of input currency to spend
* @param currencyOut the desired currency out
* @param maxNumResults maximum number of results to return
* @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
* @param currentPairs used in recursion; the current list of pairs
* @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
* @param bestTrades used in recursion; the current list of best trades
*/;
Trade.bestTradeExactIn = function bestTradeExactIn(pairs, currencyAmountIn, currencyOut, _temp,
// used in recursion.
currentPairs, nextAmountIn, bestTrades) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$maxNumResults = _ref.maxNumResults,
maxNumResults = _ref$maxNumResults === void 0 ? 3 : _ref$maxNumResults,
_ref$maxHops = _ref.maxHops,
maxHops = _ref$maxHops === void 0 ? 3 : _ref$maxHops;
if (currentPairs === void 0) {
currentPairs = [];
}
if (nextAmountIn === void 0) {
nextAmountIn = currencyAmountIn;
}
if (bestTrades === void 0) {
bestTrades = [];
}
!(pairs.length > 0) ? invariant(false, 'PAIRS') : void 0;
!(maxHops > 0) ? invariant(false, 'MAX_HOPS') : void 0;
!(currencyAmountIn === nextAmountIn || currentPairs.length > 0) ? invariant(false, 'INVALID_RECURSION') : void 0;
var amountIn = nextAmountIn.wrapped;
var tokenOut = currencyOut.wrapped;
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i];
// pair irrelevant
if (!pair.token0.equals(amountIn.currency) && !pair.token1.equals(amountIn.currency)) continue;
if (pair.reserve0.equalTo(maiaCoreSdk.ZERO) || pair.reserve1.equalTo(maiaCoreSdk.ZERO)) continue;
var amountOut = void 0;
try {
;
var _pair$getOutputAmount2 = pair.getOutputAmount(amountIn);
amountOut = _pair$getOutputAmount2[0];
} catch (error) {
// input too low
if (error instanceof InsufficientInputAmountError) {
continue;
}
throw error;
}
// we have arrived at the output token, so this is the final trade of one of the paths
if (amountOut.currency.equals(tokenOut)) {
sortedInsert(bestTrades, new Trade(new Route$1([].concat(currentPairs, [pair]), currencyAmountIn.currency, currencyOut), currencyAmountIn, exports.TradeType.EXACT_INPUT), maxNumResults, tradeComparator$1);
} else if (maxHops > 1 && pairs.length > 1) {
var pairsExcludingThisPair = pairs.slice(0, i).concat(pairs.slice(i + 1, pairs.length));
// otherwise, consider all the other paths that lead from this token as long as we have not exceeded maxHops
Trade.bestTradeExactIn(pairsExcludingThisPair, currencyAmountIn, currencyOut, {
maxNumResults: maxNumResults,
maxHops: maxHops - 1
}, [].concat(currentPairs, [pair]), amountOut, bestTrades);
}
}
return bestTrades;
}
/**
* Return the execution price after accounting for slippage tolerance
* @param slippageTolerance the allowed tolerated slippage
*/;
_proto.worstExecutionPrice = function worstExecutionPrice(slippageTolerance) {
return new maiaCoreSdk.Price(this.inputAmount.currency, this.outputAmount.currency, this.maximumAmountIn(slippageTolerance).quotient, this.minimumAmountOut(slippageTolerance).quotient);
}
/**
* similar to the above method but instead targets a fixed output amount
* given a list of pairs, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
* to an output token amount, making at most `maxHops` hops
* note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
* the amount in among multiple routes.
* @param pairs the pairs to consider in finding the best trade
* @param currencyIn the currency to spend
* @param nextAmountOut the exact amount of currency out
* @param maxNumResults maximum number of results to return
* @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
* @param currentPairs used in recursion; the current list of pairs
* @param currencyAmountOut used in recursion; the original value of the currencyAmountOut parameter
* @param bestTrades used in recursion; the current list of best trades
*/;
Trade.bestTradeExactOut = function bestTradeExactOut(pairs, currencyIn, currencyAmountOut, _temp2,
// used in recursion.
currentPairs, nextAmountOut, bestTrades) {
var _ref2 = _temp2 === void 0 ? {} : _temp2,
_ref2$maxNumResults = _ref2.maxNumResults,
maxNumResults = _ref2$maxNumResults === void 0 ? 3 : _ref2$maxNumResults,
_ref2$maxHops = _ref2.maxHops,
maxHops = _ref2$maxHops === void 0 ? 3 : _ref2$maxHops;
if (currentPairs === void 0) {
currentPairs = [];
}
if (nextAmountOut === void 0) {
nextAmountOut = currencyAmountOut;
}
if (bestTrades === void 0) {
bestTrades = [];
}
!(pairs.length > 0) ? invariant(false, 'PAIRS') : void 0;
!(maxHops > 0) ? invariant(false, 'MAX_HOPS') : void 0;
!(currencyAmountOut === nextAmountOut || currentPairs.length > 0) ? invariant(false, 'INVALID_RECURSION') : void 0;
var amountOut = nextAmountOut.wrapped;
var tokenIn = currencyIn.wrapped;
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i];
// pair irrelevant
if (!pair.token0.equals(amountOut.currency) && !pair.token1.equals(amountOut.currency)) continue;
if (pair.reserve0.equalTo(maiaCoreSdk.ZERO) || pair.reserve1.equalTo(maiaCoreSdk.ZERO)) continue;
var amountIn = void 0;
try {
;
var _pair$getInputAmount2 = pair.getInputAmount(amountOut);
amountIn = _pair$getInputAmount2[0];
} catch (error) {
// not enough liquidity in this pair
if (error instanceof InsufficientReservesError) {
continue;
}
throw error;
}
// we have arrived at the input token, so this is the first trade of one of the paths
if (amountIn.currency.equals(tokenIn)) {
sortedInsert(bestTrades, new Trade(new Route$1([pair].concat(currentPairs), currencyIn, currencyAmountOut.currency), currencyAmountOut, exports.TradeType.EXACT_OUTPUT), maxNumResults, tradeComparator$1);
} else if (maxHops > 1 && pairs.length > 1) {
var pairsExcludingThisPair = pairs.slice(0, i).concat(pairs.slice(i + 1, pairs.length));
// otherwise, consider all the other paths that arrive at this token as long as we have not exceeded maxHops
Trade.bestTradeExactOut(pairsExcludingThisPair, currencyIn, currencyAmountOut, {
maxNumResults: maxNumResults,
maxHops: maxHops - 1
}, [pair].concat(currentPairs), amountIn, bestTrades);
}
}
return bestTrades;
};
return Trade;
}();
/**
* UniswapV3Gauge entity
*/
var UniswapV3Gauge = function UniswapV3Gauge(pool, isActive, currentGaugeWeight, currentBoost, minWidth, currentIncentive) {
this.pool = pool;
this.isActive = isActive;
this.currentGaugeWeight = currentGaugeWeight;
this.currentBoost = currentBoost;
this.currentIncentive = currentIncentive != null ? currentIncentive : undefined;
this.minWidth = minWidth;
};
var UniswapV3StakerABI = [
{
type: "constructor",
inputs: [
{
name: "_factory",
type: "address",
internalType: "contract IUniswapV3Factory"
},
{
name: "_nonfungiblePositionManager",
type: "address",
internalType: "contract INonfungiblePositionManager"
},
{
name: "_uniswapV3GaugeFactory",
type: "address",
internalType: "contract IUniswapV3GaugeFactory"
},
{
name: "_hermesGaugeBoost",
type: "address",
internalType: "contract bHermesBoost"
},
{
name: "_maxIncentiveStartLeadTime",
type: "uint256",
internalType: "uint256"
},
{
name: "_minter",
type: "address",
internalType: "address"
},
{
name: "_hermes",
type: "address",
internalType: "address"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "bribeDepots",
inputs: [
{
name: "pool",
type: "address",
internalType: "contract IUniswapV3Pool"
}
],
outputs: [
{
name: "depot",
type: "address",
internalType: "address"
}
],
stateMutability: "view"
},
{
type: "function",
name: "claimAllRewards",
inputs: [
{
name: "to",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "reward",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "claimReward",
inputs: [
{
name: "to",
type: "address",
internalType: "address"
},
{
name: "amountRequested",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "reward",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "createIncentive",
inputs: [
{
name: "key",
type: "tuple",
internalType: "struct IUniswapV3Staker.IncentiveKey",
components: [
{
name: "pool",
type: "address",
internalType: "contract IUniswapV3Pool"
},
{
name: "startTime",
type: "uint96",
internalType: "uint96"
}
]
},
{
name: "reward",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "createIncentiveFromGauge",
inputs: [
{
name: "reward",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "deposits",
inputs: [
{
name: "tokenId",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "owner",
type: "address",
internalType: "address"
},
{
name: "tickLower",
type: "int24",
internalType: "int24"
},
{
name: "tickUpper",
type: "int24",
internalType: "int24"
},
{
name: "stakedTimestamp",
type: "uint40",
internalType: "uint40"
}
],
stateMutability: "view"
},
{
type: "function",
name: "endIncentive",
inputs: [
{
name: "key",
type: "tuple",
internalType: "struct IUniswapV3Staker.IncentiveKey",
components: [
{
name: "pool",
type: "address",
internalType: "contract IUniswapV3Pool"
},
{
name: "startTime",
type: "uint96",
internalType: "uint96"
}
]
}
],
outputs: [
{
name: "refund",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "factory",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "contract IUniswapV3Factory"
}
],
stateMutability: "view"
},
{
type: "function",
name: "gaugePool",
inputs: [
{
name: "gauge",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "pool",
type: "address",
internalType: "contract IUniswapV3Pool"
}
],
stateMutability: "view"
},
{
type: "function",
name: "gauges",
inputs: [
{
name: "pool",
type: "address",
internalType: "contract IUniswapV3Pool"
}
],
outputs: [
{
name: "gauge",
type: "address",
internalType: "contract UniswapV3Gauge"
}
],
stateMutability: "view"
},
{
type: "function",
name: "getRewardInfo",
inputs: [
{
name: "key",
type: "tuple",
internalType: "struct IUniswapV3Staker.IncentiveKey",
components: [
{
name: "pool",
type: "address",
internalType: "contract IUniswapV3Pool"
},
{
name: "startTime",
type: "uint96",
internalType: "uint96"
}
]
},
{
name: "tokenId",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "reward",
type: "uint256",
internalType: "uint256"
},
{
name: "secondsInsideX128",
type: "uint160",
internalType: "uint160"
}
],
stateMutability: "view"
},
{
type: "function",
name: "hermes",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
stateMutability: "view"
},
{
type: "function",
name: "hermesGaugeBoost",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "contract bHermesBoost"
}
],
stateMutability: "view"
},
{
type: "function",
name: "incentives",
inputs: [
{
name: "incentiveId",
type: "bytes32",
internalType: "bytes32"
}
],
outputs: [
{
name: "totalRewardUnclaimed",
type: "uint256",
internalType: "uint256"
},
{
name: "totalSecondsClaimedX128",
type: "uint160",
internalType: "uint160"
},
{
name: "numberOfStakes",
type: "uint96",
internalType: "uint96"
}
],
stateMutability: "view"
},
{
type: "function",
name: "maxIncentiveStartLeadTime",
inputs: [
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "minter",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "address"
}
],
stateMutability: "view"
},
{
type: "function",
name: "multicall",
inputs: [
{
name: "data",
type: "bytes[]",
internalType: "bytes[]"
}
],
outputs: [
{
name: "",
type: "bytes[]",
internalType: "bytes[]"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "nonfungiblePositionManager",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "contract INonfungiblePositionManager"
}
],
stateMutability: "view"
},
{
type: "function",
name: "onERC721Received",
inputs: [
{
name: "",
type: "address",
internalType: "address"
},
{
name: "from",
type: "address",
internalType: "address"
},
{
name: "tokenId",
type: "uint256",
internalType: "uint256"
},
{
name: "",
type: "bytes",
internalType: "bytes"
}
],
outputs: [
{
name: "",
type: "bytes4",
internalType: "bytes4"
}
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "poolsMinimumWidth",
inputs: [
{
name: "pool",
type: "address",
internalType: "contract IUniswapV3Pool"
}
],
outputs: [
{
name: "minimumWidth",
type: "uint24",
internalType: "uint24"
}
],
stateMutability: "view"
},
{
type: "function",
name: "restakeToken",
inputs: [
{
name: "tokenId",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "rewards",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
}
],
outputs: [
{
name: "rewardAmount",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "stakeToken",
inputs: [
{
name: "tokenId",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "stakes",
inputs: [
{
name: "tokenId",
type: "uint256",
internalType: "uint256"
},
{
name: "incentiveId",
type: "bytes32",
internalType: "bytes32"
}
],
outputs: [
{
name: "secondsPerLiquidityInsideInitialX128",
type: "uint160",
internalType: "uint160"
},
{
name: "liquidity",
type: "uint128",
internalType: "uint128"
}
],
stateMutability: "view"
},
{
type: "function",
name: "tokenIdRewards",
inputs: [
{
name: "tokenId",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
{
name: "rewardAmount",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "uniswapV3GaugeFactory",
inputs: [
],
outputs: [
{
name: "",
type: "address",
internalType: "contract IUniswapV3GaugeFactory"
}
],
stateMutability: "view"
},
{
type: "function",
name: "unstakeToken",
inputs: [
{
name: "tokenId",
type: "uint256",
internalType: "uint256"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "updateBribeDepot",
inputs: [
{
name: "uniswapV3Pool",
type: "address",
internalType: "contract IUniswapV3Pool"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "updateGauges",
inputs: [
{
name: "uniswapV3Pool",
type: "address",
internalType: "contract IUniswapV3Pool"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "updatePoolMinimumWidth",
inputs: [
{
name: "uniswapV3Pool",
type: "address",
internalType: "contract IUniswapV3Pool"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "function",
name: "userAttachements",
inputs: [
{
name: "user",
type: "address",
internalType: "address"
},
{
name: "pool",
type: "address",
internalType: "contract IUniswapV3Pool"
}
],
outputs: [
{
name: "",
type: "uint256",
internalType: "uint256"
}
],
stateMutability: "view"
},
{
type: "function",
name: "withdrawToken",
inputs: [
{
name: "tokenId",
type: "uint256",
internalType: "uint256"
},
{
name: "to",
type: "address",
internalType: "address"
},
{
name: "data",
type: "bytes",
internalType: "bytes"
}
],
outputs: [
],
stateMutability: "nonpayable"
},
{
type: "event",
name: "BribeDepotUpdated",
inputs: [
{
name: "uniswapV3Pool",
type: "address",
indexed: true,
internalType: "contract IUniswapV3Pool"
},
{
name: "bribeDepot",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "DepositTransferred",
inputs: [
{
name: "tokenId",
type: "uint256",
indexed: true,
internalType: "uint256"
},
{
name: "newOwner",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "GaugeUpdated",
inputs: [
{
name: "uniswapV3Pool",
type: "address",
indexed: true,
internalType: "contract IUniswapV3Pool"
},
{
name: "uniswapV3Gauge",
type: "address",
indexed: true,
internalType: "address"
}
],
anonymous: false
},
{
type: "event",
name: "IncentiveCreated",
inputs: [
{
name: "pool",
type: "address",
indexed: true,
internalType: "contract IUniswapV3Pool"
},
{
name: "startTime",
type: "uint256",
indexed: true,
internalType: "uint256"
},
{
name: "reward",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "IncentiveEnded",
inputs: [
{
name: "incentiveId",
type: "bytes32",
indexed: true,
internalType: "bytes32"
},
{
name: "refund",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "PoolMinimumWidthUpdated",
inputs: [
{
name: "uniswapV3Pool",
type: "address",
indexed: true,
internalType: "contract IUniswapV3Pool"
},
{
name: "poolMinimumWidth",
type: "uint24",
indexed: true,
internalType: "uint24"
}
],
anonymous: false
},
{
type: "event",
name: "RewardClaimed",
inputs: [
{
name: "to",
type: "address",
indexed: true,
internalType: "address"
},
{
name: "reward",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "event",
name: "TokenStaked",
inputs: [
{
name: "tokenId",
type: "uint256",
indexed: true,
internalType: "uint256"
},
{
name: "incentiveId",
type: "bytes32",
indexed: true,
internalType: "bytes32"
},
{
name: "isBoosted",
type: "bool",
indexed: true,
internalType: "bool"
}
],
anonymous: false
},
{
type: "event",
name: "TokenUnstaked",
inputs: [
{
name: "tokenId",
type: "uint256",
indexed: true,
internalType: "uint256"
},
{
name: "reward",
type: "uint256",
indexed: true,
internalType: "uint256"
}
],
anonymous: false
},
{
type: "error",
name: "EndIncentiveBeforeEndTime",
inputs: [
]
},
{
type: "error",
name: "EndIncentiveNoRefundAvailable",
inputs: [
]
},
{
type: "error",
name: "EndIncentiveWhileStakesArePresent",
inputs: [
]
},
{
type: "error",
name: "IncentiveCallerMustBeRegisteredGauge",
inputs: [
]
},
{
type: "error",
name: "IncentiveCannotBeCreatedForPoolWithNoGauge",
inputs: [
]
},
{
type: "error",
name: "IncentiveRewardMustBeGreaterThanZero",
inputs: [
]
},
{
type: "error",
name: "IncentiveStartTimeMustBeNowOrInTheFuture",
inputs: [
]
},
{
type: "error",
name: "IncentiveStartTimeNotAtEndOfAnEpoch",
inputs: [
]
},
{
type: "error",
name: "IncentiveStartTimeTooFarIntoFuture",
inputs: [
]
},
{
type: "error",
name: "InvalidGauge",
inputs: [
]
},
{
type: "error",
name: "InvalidRecipient",
inputs: [
]
},
{
type: "error",
name: "InvalidStartTime",
inputs: [
]
},
{
type: "error",
name: "NoLiquidityError",
inputs: [
]
},
{
type: "error",
name: "NonExistentIncentiveError",
inputs: [
]
},
{
type: "error",
name: "NotCalledByOwner",
inputs: [
]
},
{
type: "error",
name: "RangeTooSmallError",
inputs: [
]
},
{
type: "error",
name: "TokenNotDeposited",
inputs: [
]
},
{
type: "error",
name: "TokenNotStaked",
inputs: [
]
},
{
type: "error",
name: "TokenNotUniswapV3NFT",
inputs: [
]
},
{
type: "error",
name: "TokenStakedError",
inputs: [
]
}
];
var UniswapV3Staker = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
/* eslint-disable @typescript-eslint/no-empty-function */
function UniswapV3Staker() {}
/**
* Encodes the contract interaction calldata to create an incentive for a pool.
* @param pool address of the pool to incentivize.
* @param startTime start time of the incentive.
* @param reward reward amount for the incentive.
* @returns the encoded calldata for the createIncentive action.
*/
UniswapV3Staker.encodeCreateIncentiveCalldata = function encodeCreateIncentiveCalldata(_ref) {
var pool = _ref.pool,
startTime = _ref.startTime,
reward = _ref.reward;
// Check if the pool address, start time and reward amount are valid.
!pool ? invariant(false, 'Invalid pool address') : void 0;
!(pool != ADDRESS_ZERO) ? invariant(false, 'Invalid pool address') : void 0;
!(startTime > maiaCoreSdk.ZERO) ? invariant(false, 'Invalid start time') : void 0;
!(reward > maiaCoreSdk.ZERO) ? invariant(false, 'Invalid reward amount') : void 0;
// Encode the createIncentive action.
return UniswapV3Staker.INTERFACE.encodeFunctionData('createIncentive', [{
pool: pool,
startTime: startTime
}, reward]);
}
/**
* Encodes the contract interaction calldata to withdraw a token from the staker.
* @param tokenId id of the token to withdraw.
* @param to address to withdraw the token to.
* @returns the encoded calldata for the withdrawToken action.
*/;
UniswapV3Staker.encodeWithdrawTokenCalldata = function encodeWithdrawTokenCalldata(_ref2) {
var tokenId = _ref2.tokenId,
to = _ref2.to;
// Check if the token id and recipient address are valid.
!tokenId ? invariant(false, 'Invalid token id') : void 0;
!to ? invariant(false, 'Invalid recipient address') : void 0;
!(to != ADDRESS_ZERO) ? invariant(false, 'Invalid recipient address') : void 0;
// Encode the withdrawToken action.
return UniswapV3Staker.INTERFACE.encodeFunctionData('withdrawToken', [tokenId, to]);
}
/**
* Encodes the contract interaction calldata to unstake a token from the staker.
* @param tokenId id of the token to unstake.
* @returns the encoded calldata for the unstakeToken action.
*/;
UniswapV3Staker.encodeUnstakeTokenCalldata = function encodeUnstakeTokenCalldata(_ref3) {
var tokenId = _ref3.tokenId;
// Check if the token id is valid.
!tokenId ? invariant(false, 'Invalid token id') : void 0;
// Encode the unstakeToken action.
return UniswapV3Staker.INTERFACE.encodeFunctionData('unstakeToken', [tokenId]);
}
/**
* Encodes the contract interaction calldata to stake a token in the staker.
* @param tokenId id of the token to stake.
* @returns the encoded calldata for the stake action.
*/;
UniswapV3Staker.encodeStakeTokenCalldata = function encodeStakeTokenCalldata(_ref4) {
var tokenId = _ref4.tokenId;
// Check if the token id is valid.
!tokenId ? invariant(false, 'Invalid token id') : void 0;
// Encode the stake action.
return UniswapV3Staker.INTERFACE.encodeFunctionData('stakeToken', [tokenId]);
}
/**
* Encodes the contract interaction calldata to restake a token in the staker.
* @param tokenId id of the token to restake.
* @returns the encoded calldata for the restake action.
*/;
UniswapV3Staker.encodeRestakeTokenCalldata = function encodeRestakeTokenCalldata(_ref5) {
var tokenId = _ref5.tokenId;
// Check if the token id is valid.
!tokenId ? invariant(false, 'Invalid token id') : void 0;
// Encode the restake action.
return UniswapV3Staker.INTERFACE.encodeFunctionData('restakeToken', [tokenId]);
}
/**
* Encodes the contract interaction calldata to claim reward from the staker.
* @param recipient address of the recipient of the reward.
* @param amount amount of reward to claim.
* @returns the encoded calldata for the claimReward action.
*/;
UniswapV3Staker.encodeClaimRewardCalldata = function encodeClaimRewardCalldata(_ref6) {
var recipient = _ref6.recipient,
amount = _ref6.amount;
// Check if the recipient address and amount requested are valid.
!recipient ? invariant(false, 'Invalid recipient address') : void 0;
!(recipient != ADDRESS_ZERO) ? invariant(false, 'Invalid recipient address') : void 0;
!(amount > maiaCoreSdk.ZERO) ? invariant(false, 'Invalid amount requested') : void 0;
// Encode the claimReward action.
return UniswapV3Staker.INTERFACE.encodeFunctionData('claimReward', [recipient, amount]);
}
/**
* Encodes the contract interaction calldata to claim all rewards from the staker.
* @param recipient address of the recipient of the reward.
* @returns the encoded calldata for the claimAllRewards action.
*/;
UniswapV3Staker.encodeClaimAllRewardsCalldata = function encodeClaimAllRewardsCalldata(_ref7) {
var recipient = _ref7.recipient;
// Check if the recipient address is valid.
!recipient ? invariant(false, 'Invalid recipient address') : void 0;
!(recipient != ADDRESS_ZERO) ? invariant(false, 'Invalid recipient address') : void 0;
// Encode the claimAllRewards action.
return UniswapV3Staker.INTERFACE.encodeFunctionData('claimAllRewards', [recipient]);
};
return UniswapV3Staker;
}();
UniswapV3Staker.INTERFACE = /*#__PURE__*/new abi.Interface(UniswapV3StakerABI);
/**
* Represents an ERC4626 ComposableStablePoolWrapper
*/
var ComposableStablePoolWrapper = /*#__PURE__*/function (_Vault) {
_inheritsLoose(ComposableStablePoolWrapper, _Vault);
/**
* Construct a vault
* @param underlying One of the tokens in the vault, the underlying token
* @param vault The other token in the vault, the vault's address
* @param rate The exchange rate of the underlying token to the vault token
*/
function ComposableStablePoolWrapper(underlying, vault, rate) {
var _this;
_this = _Vault.call(this, underlying, vault) || this;
_this.rate = rate;
return _this;
}
/**
* Returns the price of the vault token in terms of the underlying token
* @param underlying One of the tokens in the vault, the underlying token
* @param vault The other token in the vault, the vault's address
* @param rate The exchange rate of the underlying token to the vault token
* @returns The price of the vault token in terms of the underlying token
*/
ComposableStablePoolWrapper.priceOfVault = function priceOfVault(underlying, vault, rate) {
return new maiaCoreSdk.Price(vault, underlying, rate, maiaCoreSdk.ONE_18);
}
/**
* Returns the price of the underlying token in terms of the vault token
* @param underlying One of the tokens in the vault, the underlying token
* @param vault The other token in the vault, the vault's address
* @param rate The exchange rate of the underlying token to the vault token
* @returns The price of the underlying token in terms of the vault token
*/;
ComposableStablePoolWrapper.priceOfUnderlying = function priceOfUnderlying(underlying, vault, rate) {
return new maiaCoreSdk.Price(underlying, vault, maiaCoreSdk.ONE_18, rate);
}
/**
* Returns the current mid price of the vault in terms of token0, i.e. the ratio of token1 over token0
*/;
var _proto = ComposableStablePoolWrapper.prototype;
/**
* Given an input amount of a token, return the computed output amount, and a vault with state updated after the trade
* @param inputAmount The input amount for which to quote the output amount
* @param rate The exchange rate of the underlying token to the vault token
* @returns The output amount and the vault with updated state
* @NOTE Call this when calculating "deposit" and "redeem" amounts
*/
_proto.getOutputAmount =
/*#__PURE__*/
function () {
var _getOutputAmount = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(inputAmount, rate) {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", this.getAmount(inputAmount, rate, true));
case 1:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function getOutputAmount(_x, _x2) {
return _getOutputAmount.apply(this, arguments);
}
return getOutputAmount;
}()
/**
* Given a desired output amount of a token, return the computed input amount and a vault with state updated after the trade
* @param outputAmount the output amount for which to quote the input amount
* @param rate The exchange rate of the underlying token to the vault token
* @returns The input amount and the vault with updated state
* @NOTE Call this when calculating "mint" and "withdraw" amounts
*/
;
_proto.getInputAmount =
/*#__PURE__*/
function () {
var _getInputAmount = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(outputAmount, rate) {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt("return", this.getAmount(outputAmount, rate, false));
case 1:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
function getInputAmount(_x3, _x4) {
return _getInputAmount.apply(this, arguments);
}
return getInputAmount;
}()
/**
* Given an amount of a token, return the computed amount of the other token and a vault with state updated after the trade
* @param amount The amount for which to quote the other amount
* @param rate The exchange rate of the underlying token to the vault token
* @param roundDown Whether to round down or not
* @returns The other amount and the vault with updated state
*/
;
_proto.getAmount =
/*#__PURE__*/
function () {
var _getAmount = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(amount, rate, roundDown) {
var otherAmounnt;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
!this.involvesToken(amount.currency) ? invariant(false, 'TOKEN') : void 0;
if (!rate) rate = this.rate;
otherAmounnt = ComposableStablePoolWrapper.getOtherAmount(amount, this.underlying(), this.vault(), rate, roundDown);
return _context3.abrupt("return", [otherAmounnt, new ComposableStablePoolWrapper(this.underlying(), this.vault(), this.rate)]);
case 4:
case "end":
return _context3.stop();
}
}, _callee3, this);
}));
function getAmount(_x5, _x6, _x7) {
return _getAmount.apply(this, arguments);
}
return getAmount;
}()
/**
* Returns the price of the underlying token in terms of the vault token
* @param amount
* @param underlying
* @param vault
* @param rate
* @returns
*/
;
ComposableStablePoolWrapper.getOtherAmount = function getOtherAmount(amount, underlying, vault, rate, roundDown) {
// Check if the currency of the amount is the same as the vault
var tokenIsVault = amount.currency.equals(vault);
// Decide the operation based on whether the token is the vault or not
var resultAmount;
if (roundDown) {
resultAmount = tokenIsVault ? FullMath.divDownFixed(amount.quotient, rate) : FullMath.mulDownFixed(amount.quotient, rate);
} else {
resultAmount = tokenIsVault ? FullMath.divUpFixed(amount.quotient, rate) : FullMath.mulUpFixed(amount.quotient, rate);
}
// Return the new CurrencyAmount with the underlying or vault currency and calculated numerator and denominator
return maiaCoreSdk.CurrencyAmount.fromRawAmount(tokenIsVault ? underlying : vault, resultAmount);
};
_createClass(ComposableStablePoolWrapper, [{
key: "token0Price",
get: function get() {
var _this$_token0Price;
return (_this$_token0Price = this._token0Price) != null ? _this$_token0Price : this._token0Price = this.vaultIsToken0 ? ComposableStablePoolWrapper.priceOfVault(this.token1, this.token0, this.rate) : ComposableStablePoolWrapper.priceOfUnderlying(this.token0, this.token1, this.rate);
}
/**
* Returns the current mid price of the vault in terms of token1, i.e. the ratio of token0 over token1
*/
}, {
key: "token1Price",
get: function get() {
var _this$_token1Price;
return (_this$_token1Price = this._token1Price) != null ? _this$_token1Price : this._token1Price = this.vaultIsToken0 ? ComposableStablePoolWrapper.priceOfUnderlying(this.token1, this.token0, this.rate) : ComposableStablePoolWrapper.priceOfVault(this.token0, this.token1, this.rate);
}
}]);
return ComposableStablePoolWrapper;
}(Vault);
function aprPercentage(row) {
if (row.tokenPriceUSD == 0) return '0% - 0%';
// 31536000 = 365 days in seconds
var multiplier = YEAR / (row.endTime - row.startTime) * 100;
var rewardsUSD = row.reward * row.tokenPriceUSD;
var firstPercentage = row.fullRangeLiquidityUSD > 0 && (apr(rewardsUSD, row.fullRangeLiquidityUSD, multiplier) * 0.4).toFixed(2) || '0';
var secondPercentage = row.activeLiquidityUSD > 0 && apr(rewardsUSD, row.activeLiquidityUSD, multiplier).toFixed(2) || '0';
return firstPercentage + "% - " + secondPercentage + "%";
}
function apr(rewardsUSD, liquidityUSD, multiplier) {
return rewardsUSD / liquidityUSD * multiplier;
}
// If the width is greater than 2^20, the efficiency is equivalent to full range, the least efficient.
var MAX_WIDTH_FOR_EFFICIENCY = /*#__PURE__*/Math.pow(2, 20);
// Depending on fee tier and min width, we calculate the efficiency of the position.
// The value can go from 40k (1 tick) to 1 (full range).
function positionEfficiency(feeTier, minWidth) {
var tickSpacing = feeTierToTickSpacing(feeTier);
var priceRatio = calculatePriceRatio(minWidth, tickSpacing);
// C.E. = 1/(1-(Pa/Pb)^0.25)
return 1 / (1 - Math.pow(priceRatio, 1 / 4));
}
function calculatePriceRatio(minWidth, tickSpacing) {
// We assume price is 1. To get price ratio at tick `i`: Pa/Pb = 1 / (1.0001)^i
// If minWidth is too large, we assume the ratio is zero (1 / infinity = 0).
return minWidth >= MAX_WIDTH_FOR_EFFICIENCY ? 0 : 1 / Math.pow(TICK_INCREMENT, getLargerInTicks(tickSpacing, minWidth));
}
function getLargerInTicks(tickSpacing, minWidth) {
return Math.max(tickSpacing, Math.ceil(minWidth / tickSpacing) * tickSpacing);
}
function feeTierToTickSpacing(feeTier) {
if (feeTier == 100) return 1;
if (feeTier == 500) return 10;
if (feeTier == 3000) return 60;
if (feeTier == 10000) return 200;
return 0;
}
function convertBasedOnEfficiency(amount, feeTier, minWidth) {
return amount * positionEfficiency(feeTier, 0) / positionEfficiency(feeTier, minWidth);
}
function getAmountsCurrentTickUSD(sqrtPriceX96, tickCurrent, liquidity, feeTier, decimals0, decimals1, price0, price1) {
var tickSpacing = feeTierToTickSpacing(feeTier);
if (tickCurrent === undefined || isNaN(tickCurrent)) return 0;
var amount0 = getAmountsCurrentTick(false, sqrtPriceX96, tickCurrent, liquidity, feeTier, tickSpacing);
var amount1 = getAmountsCurrentTick(true, sqrtPriceX96, tickCurrent, liquidity, feeTier, tickSpacing);
return amount0 / Math.pow(10, decimals0) * price0 + amount1 / Math.pow(10, decimals1) * price1;
}
var LARGE_NUMBER_FOR_SWAP = /*#__PURE__*/JSBI.BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
/**
* The default factory tick spacings by fee amount.
*/
var FEES = {
100: exports.FeeAmount.LOWEST,
500: exports.FeeAmount.LOW,
3000: exports.FeeAmount.MEDIUM,
10000: exports.FeeAmount.HIGH
};
/**
* Executes a swap
* @param zeroForOne Whether the amount in is token0 or token1
* @returns amountCalculated
*/
function getAmountsCurrentTick(zeroForOne, sqrtPriceX96, tickCurrent, liquidity, feeTier, tickSpacing) {
var _JSBI$toNumber;
var _SwapMath$computeSwap = SwapMath.computeSwapStep(JSBI.BigInt(sqrtPriceX96), getSqrtPriceNext(zeroForOne, tickCurrent, tickSpacing), JSBI.BigInt(liquidity), LARGE_NUMBER_FOR_SWAP, FEES[feeTier]),
amountOut = _SwapMath$computeSwap[2];
return (_JSBI$toNumber = JSBI.toNumber(amountOut)) != null ? _JSBI$toNumber : 0;
}
function getSqrtPriceNext(zeroForOne, tickCurrent, tickSpacing) {
var tickNext = zeroForOne ? (Math.ceil(tickCurrent / tickSpacing) - 1) * tickSpacing : (Math.floor(tickCurrent / tickSpacing) + 1) * tickSpacing;
if (tickNext < TickMath.MIN_TICK) {
tickNext = TickMath.MIN_TICK;
} else if (tickNext > TickMath.MAX_TICK) {
tickNext = TickMath.MAX_TICK;
}
return TickMath.getSqrtRatioAtTick(tickNext);
}
// Calculate the liquidity data for the active and full range of the pool based on the current tick
function calculateLiquidityData(pool, incentive, token0USD, token1USD) {
var _pool$token, _pool$token2, _incentive$minWidth;
var activeTickLiquidityUSD = getAmountsCurrentTickUSD(Number(pool == null ? void 0 : pool.sqrtPrice), Number(pool == null ? void 0 : pool.tick), Number(pool == null ? void 0 : pool.liquidity), Number(pool == null ? void 0 : pool.feeTier), Number(pool == null || (_pool$token = pool.token0) == null ? void 0 : _pool$token.decimals), Number(pool == null || (_pool$token2 = pool.token1) == null ? void 0 : _pool$token2.decimals), Number(token0USD), Number(token1USD));
var activeLiquidityUSD = convertBasedOnEfficiency(activeTickLiquidityUSD, pool == null ? void 0 : pool.feeTier, (_incentive$minWidth = incentive == null ? void 0 : incentive.minWidth) != null ? _incentive$minWidth : 0);
var fullRangeLiquidityUSD = convertBasedOnEfficiency(activeTickLiquidityUSD, pool == null ? void 0 : pool.feeTier, MAX_RANGE);
return {
activeLiquidityUSD: activeLiquidityUSD,
fullRangeLiquidityUSD: fullRangeLiquidityUSD
};
}
//range must be a number equivalent to the range of the pool
function calculateCustomLiquidityData(pool, incentive, token0USD, token1USD, range) {
var _pool$token3, _pool$token4, _incentive$minWidth2;
var activeTickLiquidityUSD = getAmountsCurrentTickUSD(Number(pool == null ? void 0 : pool.sqrtPrice), Number(pool == null ? void 0 : pool.tick), Number(pool == null ? void 0 : pool.liquidity), Number(pool == null ? void 0 : pool.feeTier), Number(pool == null || (_pool$token3 = pool.token0) == null ? void 0 : _pool$token3.decimals), Number(pool == null || (_pool$token4 = pool.token1) == null ? void 0 : _pool$token4.decimals), Number(token0USD), Number(token1USD));
var activeLiquidityUSD = convertBasedOnEfficiency(activeTickLiquidityUSD, pool == null ? void 0 : pool.feeTier, (_incentive$minWidth2 = incentive == null ? void 0 : incentive.minWidth) != null ? _incentive$minWidth2 : 0);
// Calculate custom range liquidity based on the provided range
var customRangeLiquidityUSD = convertBasedOnEfficiency(activeTickLiquidityUSD, pool == null ? void 0 : pool.feeTier, range);
return {
activeLiquidityUSD: activeLiquidityUSD,
customRangeLiquidityUSD: customRangeLiquidityUSD
};
}
/**
* Returns the closest tick that is nearest a given tick and usable for the given tick spacing
* @param tick the target tick
* @param tickSpacing the spacing of the pool
*/
function nearestUsableTick(tick, tickSpacing) {
!(Number.isInteger(tick) && Number.isInteger(tickSpacing)) ? invariant(false, 'INTEGERS') : void 0;
!(tickSpacing > 0) ? invariant(false, 'TICK_SPACING') : void 0;
!(tick >= TickMath.MIN_TICK && tick <= TickMath.MAX_TICK) ? invariant(false, 'TICK_BOUND') : void 0;
var rounded = Math.round(tick / tickSpacing) * tickSpacing;
if (rounded < TickMath.MIN_TICK) return rounded + tickSpacing;else if (rounded > TickMath.MAX_TICK) return rounded - tickSpacing;else return rounded;
}
function getPositionAmounts(tickCurrent, tickLower, tickUpper, liquidity, sqrtRatioX96) {
return _getPositionAmounts(Number(tickCurrent), Number(tickLower), Number(tickUpper), JSBI.BigInt(liquidity), JSBI.BigInt(sqrtRatioX96));
}
function _getPositionAmounts(tickCurrent, tickLower, tickUpper, liquidity, sqrtRatioX96) {
var amount0 = getAmount0(tickCurrent, tickLower, tickUpper, liquidity, sqrtRatioX96);
var amount1 = getAmount1(tickCurrent, tickLower, tickUpper, liquidity, sqrtRatioX96);
return [JSBI.toNumber(amount0), JSBI.toNumber(amount1)];
}
/**
* Returns the amount of token0 that this position's liquidity could be burned for at the current pool price
*/
function getAmount0(tickCurrent, tickLower, tickUpper, liquidity, sqrtRatioX96) {
if (tickCurrent < tickLower) {
return SqrtPriceMath.getAmount0Delta(TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidity, false);
} else if (tickCurrent < tickUpper) {
return SqrtPriceMath.getAmount0Delta(sqrtRatioX96, TickMath.getSqrtRatioAtTick(tickUpper), liquidity, false);
} else {
return JSBI.BigInt(maiaCoreSdk.ZERO);
}
}
/**
* Returns the amount of token1 that this position's liquidity could be burned for at the current pool price
*/
function getAmount1(tickCurrent, tickLower, tickUpper, liquidity, sqrtRatioX96) {
if (tickCurrent < tickLower) {
return JSBI.BigInt(maiaCoreSdk.ZERO);
} else if (tickCurrent < tickUpper) {
return SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(tickLower), sqrtRatioX96, liquidity, false);
} else {
return SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidity, false);
}
}
var Q256 = /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(256));
function subIn256(x, y) {
var difference = JSBI.subtract(x, y);
if (JSBI.lessThan(difference, maiaCoreSdk.ZERO)) {
return JSBI.add(Q256, difference);
} else {
return difference;
}
}
var TickLibrary = /*#__PURE__*/function () {
/**
* Cannot be constructed.
*/
function TickLibrary() {}
TickLibrary.getFeeGrowthInside = function getFeeGrowthInside(feeGrowthOutsideLower, feeGrowthOutsideUpper, tickLower, tickUpper, tickCurrent, feeGrowthGlobal0X128, feeGrowthGlobal1X128) {
var feeGrowthBelow0X128;
var feeGrowthBelow1X128;
if (tickCurrent >= tickLower) {
feeGrowthBelow0X128 = feeGrowthOutsideLower.feeGrowthOutside0X128;
feeGrowthBelow1X128 = feeGrowthOutsideLower.feeGrowthOutside1X128;
} else {
feeGrowthBelow0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideLower.feeGrowthOutside0X128);
feeGrowthBelow1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideLower.feeGrowthOutside1X128);
}
var feeGrowthAbove0X128;
var feeGrowthAbove1X128;
if (tickCurrent < tickUpper) {
feeGrowthAbove0X128 = feeGrowthOutsideUpper.feeGrowthOutside0X128;
feeGrowthAbove1X128 = feeGrowthOutsideUpper.feeGrowthOutside1X128;
} else {
feeGrowthAbove0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideUpper.feeGrowthOutside0X128);
feeGrowthAbove1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideUpper.feeGrowthOutside1X128);
}
return [subIn256(subIn256(feeGrowthGlobal0X128, feeGrowthBelow0X128), feeGrowthAbove0X128), subIn256(subIn256(feeGrowthGlobal1X128, feeGrowthBelow1X128), feeGrowthAbove1X128)];
};
return TickLibrary;
}();
exports.ADDRESS_ZERO = ADDRESS_ZERO;
exports.BALANCER_VAULT_ADDRESS = BALANCER_VAULT_ADDRESS;
exports.BHermes = BHermes;
exports.BHermesBoost = BHermesBoost;
exports.BHermesGauges = BHermesGauges;
exports.BHermesVotes = BHermesVotes;
exports.BalancerComposableStablePool = BalancerComposableStablePool;
exports.ComposableStablePool = ComposableStablePool;
exports.ComposableStablePoolWrapper = ComposableStablePoolWrapper;
exports.Ether = Ether;
exports.FACTORY_ADDRESS = FACTORY_ADDRESS;
exports.Flywheel = Flywheel;
exports.FullMath = FullMath;
exports.InsufficientInputAmountError = InsufficientInputAmountError;
exports.InsufficientReservesError = InsufficientReservesError;
exports.LiquidityMath = LiquidityMath;
exports.MAX_SAFE_INTEGER = MAX_SAFE_INTEGER;
exports.MINIMUM_LIQUIDITY = MINIMUM_LIQUIDITY;
exports.Multicall = Multicall;
exports.NoTickDataProvider = NoTickDataProvider;
exports.NonfungiblePositionManager = NonfungiblePositionManager;
exports.POOL_INIT_CODE_HASH = POOL_INIT_CODE_HASH;
exports.Pair = Pair;
exports.Payments = Payments;
exports.Pool = Pool;
exports.Position = Position;
exports.Q192 = Q192;
exports.Q96 = Q96;
exports.Route = Route;
exports.SelfPermit = SelfPermit;
exports.SqrtPriceMath = SqrtPriceMath;
exports.Staker = Staker;
exports.SwapMath = SwapMath;
exports.SwapQuoter = SwapQuoter;
exports.SwapRouter = SwapRouter;
exports.TICK_SPACINGS = TICK_SPACINGS;
exports.Tick = Tick;
exports.TickLibrary = TickLibrary;
exports.TickList = TickList;
exports.TickListDataProvider = TickListDataProvider;
exports.TickMath = TickMath;
exports.Trade = Trade;
exports.UniswapV3Gauge = UniswapV3Gauge;
exports.UniswapV3Staker = UniswapV3Staker;
exports.V2RouteSDK = Route$1;
exports.V2Trade = Trade$1;
exports.Vault = Vault;
exports.WETH9 = WETH9;
exports.aprPercentage = aprPercentage;
exports.calculateCustomLiquidityData = calculateCustomLiquidityData;
exports.calculateLiquidityData = calculateLiquidityData;
exports.checkIsValidAddress = checkIsValidAddress;
exports.checkValidAddress = checkValidAddress;
exports.computePairAddress = computePairAddress;
exports.computePoolAddress = computePoolAddress;
exports.computeVaultAddress = computeVaultAddress;
exports.convertBasedOnEfficiency = convertBasedOnEfficiency;
exports.encodeRouteToPath = encodeRouteToPath;
exports.encodeSqrtRatioX96 = encodeSqrtRatioX96;
exports.getPositionAmounts = getPositionAmounts;
exports.inputOutputComparator = inputOutputComparator;
exports.isSorted = isSorted;
exports.maxLiquidityForAmounts = maxLiquidityForAmounts;
exports.mostSignificantBit = mostSignificantBit;
exports.nearestUsableTick = nearestUsableTick;
exports.priceToClosestTick = priceToClosestTick;
exports.sortedInsert = sortedInsert;
exports.sqrt = sqrt;
exports.subIn256 = subIn256;
exports.tickToPrice = tickToPrice;
exports.tradeComparator = tradeComparator;
exports.validateAndParseAddress = validateAndParseAddress;
//# sourceMappingURL=hermes-v2-sdk.cjs.development.js.map