Transaction Hash:
Block:
22202935 at Apr-05-2025 01:13:11 PM +UTC
Transaction Fee:
0.000113275593858618 ETH
$0.23
Gas Used:
259,057 Gas / 0.437261274 Gwei
Emitted Events:
| 393 |
WETH9.Transfer( src=[Receiver] TwapDelay, dst=TwapPair, wad=26497330474508002540 )
|
| 394 |
WBTC.Transfer( from=TwapPair, to=Proxy, value=57231710 )
|
| 395 |
TwapPair.Swap( sender=[Receiver] TwapDelay, amount0In=0, amount1In=26497330474508002540, amount0Out=57231710, amount1Out=0, to=Proxy )
|
| 396 |
TwapDelay.EthRefund( to=[Sender] 0x3a1d749fa4a9e650fce844ff1c58c5faf7e2a9d1, success=True, value=129896768270117 )
|
| 397 |
TwapDelay.EthRefund( to=Proxy, success=True, value=282522260849883 )
|
| 398 |
TwapDelay.OrderExecuted( id=40282, success=True, data=0x, gasSpent=225343, ethRefunded=282522260849883 )
|
Account State Difference:
| Address | Before | After | State Difference | ||
|---|---|---|---|---|---|
| 0x2260FAC5...93bc2C599 | |||||
| 0x37F6dF71...682Df1ebF | |||||
| 0x3a1D749f...af7e2a9D1 |
1.569522582806532458 Eth
Nonce: 55624
|
1.569539203980943957 Eth
Nonce: 55625
| 0.000016621174411499 | ||
|
0x4838B106...B0BAD5f97
Miner
| (Titan Builder) | 25.874733833756300524 Eth | 25.874735129041300524 Eth | 0.000001295285 | |
| 0xC02aaA39...83C756Cc2 | |||||
| 0xc3a99a85...e0bEbEe24 | (Integral: TwapDelay) | 0.0016459559451 Eth | 0.00123353691598 Eth | 0.00041241902912 | |
| 0xd17b3c97...3BcD81e2E | (Integral: TWAP Relayer) | 4.191079700772419219 Eth | 4.191362223033269102 Eth | 0.000282522260849883 |
Execution Trace
TwapDelay.execute( _orders= )
-
Orders.2e548b5b( ) TwapDelay._executeSell( order=[{name:orderId, type:uint256, order:1, indexed:false, value:40282, valueString:40282}, {name:orderType, type:uint8, order:2, indexed:false, value:3, valueString:3}, {name:inverted, type:bool, order:3, indexed:false, value:true, valueString:True}, {name:validAfterTimestamp, type:uint256, order:4, indexed:false, value:1743858731, valueString:1743858731}, {name:unwrap, type:bool, order:5, indexed:false, value:false, valueString:False}, {name:timestamp, type:uint256, order:6, indexed:false, value:1743856931, valueString:1743856931}, {name:gasLimit, type:uint256, order:7, indexed:false, value:710000, valueString:710000}, {name:gasPrice, type:uint256, order:8, indexed:false, value:580871872, valueString:580871872}, {name:liquidity, type:uint256, order:9, indexed:false, value:0, valueString:0}, {name:value0, type:uint256, order:10, indexed:false, value:26497330474508002540, valueString:26497330474508002540}, {name:value1, type:uint256, order:11, indexed:false, value:0, valueString:0}, {name:token0, type:address, order:12, indexed:false, value:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, valueString:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2}, {name:token1, type:address, order:13, indexed:false, value:0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, valueString:0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599}, {name:to, type:address, order:14, indexed:false, value:0xd17b3c9784510E33cD5B87b490E79253BcD81e2E, valueString:0xd17b3c9784510E33cD5B87b490E79253BcD81e2E}, {name:minSwapPrice, type:uint256, order:15, indexed:false, value:0, valueString:0}, {name:maxSwapPrice, type:uint256, order:16, indexed:false, value:0, valueString:0}, {name:swap, type:bool, order:17, indexed:false, value:false, valueString:False}, {name:priceAccumulator, type:uint256, order:18, indexed:false, value:0, valueString:0}, {name:amountLimit0, type:uint256, order:19, indexed:false, value:26497330474508002540, valueString:26497330474508002540}, {name:amountLimit1, type:uint256, order:20, indexed:false, value:0, valueString:0}] )-
TwapFactory.getPair( 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599 ) => ( 0x37F6dF71b40c50b2038329CaBf5FDa3682Df1ebF )
TwapPair.CALL( )
-
WBTC.balanceOf( _owner=0x37F6dF71b40c50b2038329CaBf5FDa3682Df1ebF ) => ( 250441202 )
-
WETH9.balanceOf( 0x37F6dF71b40c50b2038329CaBf5FDa3682Df1ebF ) => ( 85085696295489371891 )
-
ExecutionHelper.143d9d38( )-
TwapPair.STATICCALL( )
TwapOracleV3.getAveragePrice( 0, 1743856931 ) => ( 46293707725216421302 )-
Uniswap V3: WBTC 2.883bdbfd( )
-
-
TwapPair.STATICCALL( )
-
TwapPair.STATICCALL( )
-
TwapPair.STATICCALL( )
-
TokenShares.a8d669b4( ) -
TwapOracleV3.getSwapAmount0Out( swapFee=100000000000000, amount1In=26497330474508002540, data=0x000000000000000000000000000000000000000000000002827449E6C94815B6 ) => ( amount0Out=57231710 ) -
WETH9.transfer( dst=0x37F6dF71b40c50b2038329CaBf5FDa3682Df1ebF, wad=26497330474508002540 ) => ( True )
TwapPair.swap( amount0Out=57231710, amount1Out=0, to=0xd17b3c9784510E33cD5B87b490E79253BcD81e2E, data=0x000000000000000000000000000000000000000000000002827449E6C94815B6 )
-
WBTC.transfer( _to=0xd17b3c9784510E33cD5B87b490E79253BcD81e2E, _value=57231710 ) => ( True )
-
WBTC.balanceOf( _owner=0x37F6dF71b40c50b2038329CaBf5FDa3682Df1ebF ) => ( 193209492 )
-
WETH9.balanceOf( 0x37F6dF71b40c50b2038329CaBf5FDa3682Df1ebF ) => ( 111583026769997374431 )
-
TwapOracleV3.tradeY( yAfter=108732199010951805610, xBefore=241656839, yBefore=82237518269491253870, data=0x000000000000000000000000000000000000000000000002827449E6C94815B6 ) => ( xAfter=184425129 )
-
-
-
- ETH 0.000129896768270117
0x3a1d749fa4a9e650fce844ff1c58c5faf7e2a9d1.CALL( ) ETH 0.000282522260849883
Proxy.CALL( )- ETH 0.000282522260849883
TwapRelayer.DELEGATECALL( )
- ETH 0.000282522260849883
-
Orders.9db74df1( )
execute[TwapDelay (ln:1713)]
gasleft[TwapDelay (ln:1715)]dequeueOrder[TwapDelay (ln:1723)]verifyOrder[TwapDelay (ln:1726)]executeDeposit[TwapDelay (ln:1734)]gasleft[TwapDelay (ln:1749)]dequeueOrder[TwapDelay (ln:1750)]call[TwapDelay (ln:1751)]sub[TwapDelay (ln:1752)]getTransferGasCost[TwapDelay (ln:1754)]getTransferGasCost[TwapDelay (ln:1755)]encodeWithSelector[TwapDelay (ln:1757)]refundTokens[TwapDelay (ln:1760)]call[TwapDelay (ln:1874)]gasleft[TwapDelay (ln:1876)]getTransferGasCost[TwapDelay (ln:1879)]getTransferGasCost[TwapDelay (ln:1880)]encodeWithSelector[TwapDelay (ln:1881)]RefundFailed[TwapDelay (ln:1883)]RefundFailed[TwapDelay (ln:1884)]
finalizeOrder[TwapDelay (ln:1770)]markRefundFailed[TwapDelay (ln:1822)]forgetLastProcessedOrder[TwapDelay (ln:1824)]
refund[TwapDelay (ln:1771)]mul[TwapDelay (ln:1833)]add[TwapDelay (ln:1834)]sub[TwapDelay (ln:1834)]gasleft[TwapDelay (ln:1834)]min[TwapDelay (ln:1835)]mul[TwapDelay (ln:1835)]sub[TwapDelay (ln:1836)]refundEth[TwapDelay (ln:1837)]transferETH[TwapDelay (ln:1844)]getTransferGasCost[TwapDelay (ln:1844)]EthRefund[TwapDelay (ln:1845)]
refundEth[TwapDelay (ln:1838)]transferETH[TwapDelay (ln:1844)]getTransferGasCost[TwapDelay (ln:1844)]EthRefund[TwapDelay (ln:1845)]
payable[TwapDelay (ln:1838)]
OrderExecuted[TwapDelay (ln:1772)]
executeWithdraw[TwapDelay (ln:1736)]gasleft[TwapDelay (ln:1776)]dequeueOrder[TwapDelay (ln:1777)]call[TwapDelay (ln:1778)]sub[TwapDelay (ln:1779)]encodeWithSelector[TwapDelay (ln:1780)]getPair[TwapDelay (ln:1783)]getPair[Orders (ln:818)]
refundLiquidity[TwapDelay (ln:1784)]call[Orders (ln:1189)]encodeWithSelector[Orders (ln:1190)]RefundFailed[Orders (ln:1193)]
finalizeOrder[TwapDelay (ln:1786)]markRefundFailed[TwapDelay (ln:1822)]forgetLastProcessedOrder[TwapDelay (ln:1824)]
refund[TwapDelay (ln:1787)]mul[TwapDelay (ln:1833)]add[TwapDelay (ln:1834)]sub[TwapDelay (ln:1834)]gasleft[TwapDelay (ln:1834)]min[TwapDelay (ln:1835)]mul[TwapDelay (ln:1835)]sub[TwapDelay (ln:1836)]refundEth[TwapDelay (ln:1837)]transferETH[TwapDelay (ln:1844)]getTransferGasCost[TwapDelay (ln:1844)]EthRefund[TwapDelay (ln:1845)]
refundEth[TwapDelay (ln:1838)]transferETH[TwapDelay (ln:1844)]getTransferGasCost[TwapDelay (ln:1844)]EthRefund[TwapDelay (ln:1845)]
payable[TwapDelay (ln:1838)]
OrderExecuted[TwapDelay (ln:1788)]
executeSell[TwapDelay (ln:1738)]gasleft[TwapDelay (ln:1792)]dequeueOrder[TwapDelay (ln:1793)]call[TwapDelay (ln:1794)]sub[TwapDelay (ln:1795)]getTransferGasCost[TwapDelay (ln:1795)]encodeWithSelector[TwapDelay (ln:1796)]refundToken[TwapDelay (ln:1799)]call[TwapDelay (ln:1857)]gasleft[TwapDelay (ln:1858)]getTransferGasCost[TwapDelay (ln:1858)]encodeWithSelector[TwapDelay (ln:1859)]RefundFailed[TwapDelay (ln:1861)]
finalizeOrder[TwapDelay (ln:1801)]markRefundFailed[TwapDelay (ln:1822)]forgetLastProcessedOrder[TwapDelay (ln:1824)]
refund[TwapDelay (ln:1802)]mul[TwapDelay (ln:1833)]add[TwapDelay (ln:1834)]sub[TwapDelay (ln:1834)]gasleft[TwapDelay (ln:1834)]min[TwapDelay (ln:1835)]mul[TwapDelay (ln:1835)]sub[TwapDelay (ln:1836)]refundEth[TwapDelay (ln:1837)]transferETH[TwapDelay (ln:1844)]getTransferGasCost[TwapDelay (ln:1844)]EthRefund[TwapDelay (ln:1845)]
refundEth[TwapDelay (ln:1838)]transferETH[TwapDelay (ln:1844)]getTransferGasCost[TwapDelay (ln:1844)]EthRefund[TwapDelay (ln:1845)]
payable[TwapDelay (ln:1838)]
OrderExecuted[TwapDelay (ln:1803)]
executeBuy[TwapDelay (ln:1740)]gasleft[TwapDelay (ln:1807)]dequeueOrder[TwapDelay (ln:1808)]call[TwapDelay (ln:1809)]sub[TwapDelay (ln:1810)]getTransferGasCost[TwapDelay (ln:1810)]encodeWithSelector[TwapDelay (ln:1811)]refundToken[TwapDelay (ln:1814)]call[TwapDelay (ln:1857)]gasleft[TwapDelay (ln:1858)]getTransferGasCost[TwapDelay (ln:1858)]encodeWithSelector[TwapDelay (ln:1859)]RefundFailed[TwapDelay (ln:1861)]
finalizeOrder[TwapDelay (ln:1816)]markRefundFailed[TwapDelay (ln:1822)]forgetLastProcessedOrder[TwapDelay (ln:1824)]
refund[TwapDelay (ln:1817)]mul[TwapDelay (ln:1833)]add[TwapDelay (ln:1834)]sub[TwapDelay (ln:1834)]gasleft[TwapDelay (ln:1834)]min[TwapDelay (ln:1835)]mul[TwapDelay (ln:1835)]sub[TwapDelay (ln:1836)]refundEth[TwapDelay (ln:1837)]transferETH[TwapDelay (ln:1844)]getTransferGasCost[TwapDelay (ln:1844)]EthRefund[TwapDelay (ln:1845)]
refundEth[TwapDelay (ln:1838)]transferETH[TwapDelay (ln:1844)]getTransferGasCost[TwapDelay (ln:1844)]EthRefund[TwapDelay (ln:1845)]
payable[TwapDelay (ln:1838)]
OrderExecuted[TwapDelay (ln:1818)]
updateGasPrice[TwapDelay (ln:1744)]sub[TwapDelay (ln:1744)]gasleft[TwapDelay (ln:1744)]
File 1 of 11: TwapDelay
File 2 of 11: TwapPair
File 3 of 11: WETH9
File 4 of 11: Proxy
File 5 of 11: WBTC
File 6 of 11: Orders
File 7 of 11: TwapFactory
File 8 of 11: ExecutionHelper
File 9 of 11: TwapOracleV3
File 10 of 11: TokenShares
File 11 of 11: TwapRelayer
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IReserves {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1);
function getFees() external view returns (uint256 fee0, uint256 fee1);
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import '../libraries/Orders.sol';
interface ITwapDelay {
event OrderExecuted(uint256 indexed id, bool indexed success, bytes data, uint256 gasSpent, uint256 ethRefunded);
event EthRefund(address indexed to, bool indexed success, uint256 value);
event OwnerSet(address owner);
event FactoryGovernorSet(address factoryGovernor);
event BotSet(address bot, bool isBot);
event DelaySet(uint256 delay);
event RelayerSet(address relayer);
event MaxGasLimitSet(uint256 maxGasLimit);
event GasPriceInertiaSet(uint256 gasPriceInertia);
event MaxGasPriceImpactSet(uint256 maxGasPriceImpact);
event TransferGasCostSet(address token, uint256 gasCost);
event ToleranceSet(address pair, uint16 amount);
event NonRebasingTokenSet(address token, bool isNonRebasing);
function factory() external view returns (address);
function factoryGovernor() external view returns (address);
function relayer() external view returns (address);
function owner() external view returns (address);
function isBot(address bot) external view returns (bool);
function getTolerance(address pair) external view returns (uint16);
function isNonRebasingToken(address token) external view returns (bool);
function gasPriceInertia() external view returns (uint256);
function gasPrice() external view returns (uint256);
function maxGasPriceImpact() external view returns (uint256);
function maxGasLimit() external view returns (uint256);
function delay() external view returns (uint256);
function totalShares(address token) external view returns (uint256);
function weth() external view returns (address);
function getTransferGasCost(address token) external pure returns (uint256);
function getDepositDisabled(address pair) external view returns (bool);
function getWithdrawDisabled(address pair) external view returns (bool);
function getBuyDisabled(address pair) external view returns (bool);
function getSellDisabled(address pair) external view returns (bool);
function getOrderStatus(uint256 orderId, uint256 validAfterTimestamp) external view returns (Orders.OrderStatus);
function setOrderTypesDisabled(address pair, Orders.OrderType[] calldata orderTypes, bool disabled) external;
function setOwner(address _owner) external;
function setFactoryGovernor(address _factoryGovernor) external;
function setBot(address _bot, bool _isBot) external;
function deposit(Orders.DepositParams memory depositParams) external payable returns (uint256 orderId);
function withdraw(Orders.WithdrawParams memory withdrawParams) external payable returns (uint256 orderId);
function sell(Orders.SellParams memory sellParams) external payable returns (uint256 orderId);
function relayerSell(Orders.SellParams memory sellParams) external payable returns (uint256 orderId);
function buy(Orders.BuyParams memory buyParams) external payable returns (uint256 orderId);
function execute(Orders.Order[] calldata orders) external payable;
function retryRefund(Orders.Order calldata order) external;
function cancelOrder(Orders.Order calldata order) external;
function syncPair(address token0, address token1) external returns (address pairAddress);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './IERC20.sol';
interface ITwapERC20 is IERC20 {
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface ITwapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
event OwnerSet(address owner);
function owner() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB, address oracle, address trader) external returns (address pair);
function setOwner(address) external;
function setMintFee(address tokenA, address tokenB, uint256 fee) external;
function setBurnFee(address tokenA, address tokenB, uint256 fee) external;
function setSwapFee(address tokenA, address tokenB, uint256 fee) external;
function setOracle(address tokenA, address tokenB, address oracle) external;
function setTrader(address tokenA, address tokenB, address trader) external;
function collect(address tokenA, address tokenB, address to) external;
function withdraw(address tokenA, address tokenB, uint256 amount, address to) external;
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface ITwapFactoryGovernor {
event FactorySet(address factory);
event DelaySet(address delay);
event ProtocolFeeRatioSet(uint256 protocolFeeRatio);
event EthTransferCostSet(uint256 ethTransferCost);
event FeeDistributed(address indexed token, address indexed pair, uint256 lpAmount, uint256 protocolAmount);
event OwnerSet(address owner);
event WithdrawToken(address token, address to, uint256 amount);
function owner() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function factory() external view returns (address);
function delay() external view returns (address);
function protocolFeeRatio() external view returns (uint256);
function ethTransferCost() external view returns (uint256);
function setFactoryOwner(address) external;
function setFactory(address) external;
function setOwner(address) external;
function setMintFee(address tokenA, address tokenB, uint256 fee) external;
function setBurnFee(address tokenA, address tokenB, uint256 fee) external;
function setSwapFee(address tokenA, address tokenB, uint256 fee) external;
function setOracle(address tokenA, address tokenB, address oracle) external;
function setTrader(address tokenA, address tokenB, address trader) external;
function setDelay(address) external;
function setProtocolFeeRatio(uint256 _protocolFeeRatio) external;
function setEthTransferCost(uint256 _ethTransferCost) external;
function createPair(address tokenA, address tokenB, address oracle, address trader) external returns (address pair);
function collectFees(address tokenA, address tokenB, address to) external;
function withdrawLiquidity(address tokenA, address tokenB, uint256 amount, address to) external;
function withdrawToken(address token, uint256 amount, address to) external;
function distributeFees(address tokenA, address tokenB) external;
function distributeFees(address tokenA, address tokenB, address pairAddress) external;
function feesToDistribute(
address tokenA,
address tokenB
) external view returns (uint256 fee0ToDistribute, uint256 fee1ToDistribute);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface ITwapOracle {
event OwnerSet(address owner);
event UniswapPairSet(address uniswapPair);
function decimalsConverter() external view returns (int256);
function xDecimals() external view returns (uint8);
function yDecimals() external view returns (uint8);
function owner() external view returns (address);
function uniswapPair() external view returns (address);
function getPriceInfo() external view returns (uint256 priceAccumulator, uint256 priceTimestamp);
function getSpotPrice() external view returns (uint256);
function getAveragePrice(uint256 priceAccumulator, uint256 priceTimestamp) external view returns (uint256);
function setOwner(address _owner) external;
function setUniswapPair(address _uniswapPair) external;
function tradeX(
uint256 xAfter,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 yAfter);
function tradeY(
uint256 yAfter,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 xAfter);
function depositTradeXIn(
uint256 xLeft,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 xIn);
function depositTradeYIn(
uint256 yLeft,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 yIn);
function getSwapAmount0Out(
uint256 swapFee,
uint256 amount1In,
bytes calldata data
) external view returns (uint256 amount0Out);
function getSwapAmount1Out(
uint256 swapFee,
uint256 amount0In,
bytes calldata data
) external view returns (uint256 amount1Out);
function getSwapAmountInMaxOut(
bool inverse,
uint256 swapFee,
uint256 _amountOut,
bytes calldata data
) external view returns (uint256 amountIn, uint256 amountOut);
function getSwapAmountInMinOut(
bool inverse,
uint256 swapFee,
uint256 _amountOut,
bytes calldata data
) external view returns (uint256 amountIn, uint256 amountOut);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './ITwapERC20.sol';
import './IReserves.sol';
interface ITwapPair is ITwapERC20, IReserves {
event Mint(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 liquidityOut, address indexed to);
event Burn(address indexed sender, uint256 amount0Out, uint256 amount1Out, uint256 liquidityIn, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event SetMintFee(uint256 fee);
event SetBurnFee(uint256 fee);
event SetSwapFee(uint256 fee);
event SetOracle(address account);
event SetTrader(address trader);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function oracle() external view returns (address);
function trader() external view returns (address);
function mintFee() external view returns (uint256);
function setMintFee(uint256 fee) external;
function mint(address to) external returns (uint256 liquidity);
function burnFee() external view returns (uint256);
function setBurnFee(uint256 fee) external;
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swapFee() external view returns (uint256);
function setSwapFee(uint256 fee) external;
function setOracle(address account) external;
function setTrader(address account) external;
function collect(address to) external;
function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
function sync() external;
function initialize(address _token0, address _token1, address _oracle, address _trader) external;
function getSwapAmount0In(uint256 amount1Out, bytes calldata data) external view returns (uint256 swapAmount0In);
function getSwapAmount1In(uint256 amount0Out, bytes calldata data) external view returns (uint256 swapAmount1In);
function getSwapAmount0Out(uint256 amount1In, bytes calldata data) external view returns (uint256 swapAmount0Out);
function getSwapAmount1Out(uint256 amount0In, bytes calldata data) external view returns (uint256 swapAmount1Out);
function getDepositAmount0In(uint256 amount0, bytes calldata data) external view returns (uint256 depositAmount0In);
function getDepositAmount1In(uint256 amount1, bytes calldata data) external view returns (uint256 depositAmount1In);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './TransferHelper.sol';
import './SafeMath.sol';
import './Math.sol';
import '../interfaces/ITwapPair.sol';
import '../interfaces/ITwapOracle.sol';
library AddLiquidity {
using SafeMath for uint256;
function addLiquidity(
address pair,
uint256 amount0Desired,
uint256 amount1Desired
) internal view returns (uint256 amount0, uint256 amount1, uint256 swapToken) {
if (amount0Desired == 0 || amount1Desired == 0) {
if (amount0Desired > 0) {
swapToken = 1;
} else if (amount1Desired > 0) {
swapToken = 2;
}
return (0, 0, swapToken);
}
(uint256 reserve0, uint256 reserve1) = ITwapPair(pair).getReserves();
if (reserve0 == 0 && reserve1 == 0) {
(amount0, amount1) = (amount0Desired, amount1Desired);
} else {
require(reserve0 > 0 && reserve1 > 0, 'AL07');
uint256 amount1Optimal = amount0Desired.mul(reserve1) / reserve0;
if (amount1Optimal <= amount1Desired) {
swapToken = 2;
(amount0, amount1) = (amount0Desired, amount1Optimal);
} else {
uint256 amount0Optimal = amount1Desired.mul(reserve0) / reserve1;
assert(amount0Optimal <= amount0Desired);
swapToken = 1;
(amount0, amount1) = (amount0Optimal, amount1Desired);
}
uint256 totalSupply = ITwapPair(pair).totalSupply();
uint256 liquidityOut = Math.min(amount0.mul(totalSupply) / reserve0, amount1.mul(totalSupply) / reserve1);
if (liquidityOut == 0) {
amount0 = 0;
amount1 = 0;
}
}
}
function addLiquidityAndMint(
address pair,
address to,
address token0,
address token1,
uint256 amount0Desired,
uint256 amount1Desired
) external returns (uint256 amount0Left, uint256 amount1Left, uint256 swapToken) {
uint256 amount0;
uint256 amount1;
(amount0, amount1, swapToken) = addLiquidity(pair, amount0Desired, amount1Desired);
if (amount0 == 0 || amount1 == 0) {
return (amount0Desired, amount1Desired, swapToken);
}
TransferHelper.safeTransfer(token0, pair, amount0);
TransferHelper.safeTransfer(token1, pair, amount1);
ITwapPair(pair).mint(to);
amount0Left = amount0Desired.sub(amount0);
amount1Left = amount1Desired.sub(amount1);
}
function swapDeposit0(
address pair,
address token0,
uint256 amount0,
uint256 minSwapPrice,
uint16 tolerance,
bytes calldata data
) external returns (uint256 amount0Left, uint256 amount1Left) {
uint256 amount0In = ITwapPair(pair).getDepositAmount0In(amount0, data);
amount1Left = ITwapPair(pair).getSwapAmount1Out(amount0In, data).sub(tolerance);
if (amount1Left == 0) {
return (amount0, amount1Left);
}
uint256 price = getPrice(amount0In, amount1Left, pair);
require(minSwapPrice == 0 || price >= minSwapPrice, 'AL15');
TransferHelper.safeTransfer(token0, pair, amount0In);
ITwapPair(pair).swap(0, amount1Left, address(this), data);
amount0Left = amount0.sub(amount0In);
}
function swapDeposit1(
address pair,
address token1,
uint256 amount1,
uint256 maxSwapPrice,
uint16 tolerance,
bytes calldata data
) external returns (uint256 amount0Left, uint256 amount1Left) {
uint256 amount1In = ITwapPair(pair).getDepositAmount1In(amount1, data);
amount0Left = ITwapPair(pair).getSwapAmount0Out(amount1In, data).sub(tolerance);
if (amount0Left == 0) {
return (amount0Left, amount1);
}
uint256 price = getPrice(amount0Left, amount1In, pair);
require(maxSwapPrice == 0 || price <= maxSwapPrice, 'AL16');
TransferHelper.safeTransfer(token1, pair, amount1In);
ITwapPair(pair).swap(amount0Left, 0, address(this), data);
amount1Left = amount1.sub(amount1In);
}
function getPrice(uint256 amount0, uint256 amount1, address pair) internal view returns (uint256) {
ITwapOracle oracle = ITwapOracle(ITwapPair(pair).oracle());
return amount1.mul(uint256(oracle.decimalsConverter())).div(amount0);
}
function _refundDeposit(address to, address token0, address token1, uint256 amount0, uint256 amount1) internal {
if (amount0 > 0) {
TransferHelper.safeTransfer(token0, to, amount0);
}
if (amount1 > 0) {
TransferHelper.safeTransfer(token1, to, amount1);
}
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import '../interfaces/ITwapOracle.sol';
import '../interfaces/ITwapPair.sol';
import '../interfaces/IWETH.sol';
import '../libraries/SafeMath.sol';
import '../libraries/Orders.sol';
import '../libraries/TokenShares.sol';
import '../libraries/AddLiquidity.sol';
import '../libraries/WithdrawHelper.sol';
library ExecutionHelper {
using SafeMath for uint256;
using TransferHelper for address;
using Orders for Orders.Data;
using TokenShares for TokenShares.Data;
uint256 private constant ORDER_LIFESPAN = 48 hours;
struct ExecuteBuySellParams {
Orders.Order order;
address pairAddress;
uint16 pairTolerance;
}
function executeDeposit(
Orders.Order calldata order,
address pairAddress,
uint16 pairTolerance,
TokenShares.Data storage tokenShares
) external {
require(order.validAfterTimestamp + ORDER_LIFESPAN >= block.timestamp, 'EH04');
(uint256 amount0Left, uint256 amount1Left, uint256 swapToken) = _initialDeposit(
order,
pairAddress,
tokenShares
);
if (order.swap && swapToken != 0) {
bytes memory data = encodePriceInfo(pairAddress, order.priceAccumulator, order.timestamp);
if (amount0Left != 0 && swapToken == 1) {
uint256 extraAmount1;
(amount0Left, extraAmount1) = AddLiquidity.swapDeposit0(
pairAddress,
order.token0,
amount0Left,
order.minSwapPrice,
pairTolerance,
data
);
amount1Left = amount1Left.add(extraAmount1);
} else if (amount1Left != 0 && swapToken == 2) {
uint256 extraAmount0;
(extraAmount0, amount1Left) = AddLiquidity.swapDeposit1(
pairAddress,
order.token1,
amount1Left,
order.maxSwapPrice,
pairTolerance,
data
);
amount0Left = amount0Left.add(extraAmount0);
}
}
if (amount0Left != 0 && amount1Left != 0) {
(amount0Left, amount1Left, ) = AddLiquidity.addLiquidityAndMint(
pairAddress,
order.to,
order.token0,
order.token1,
amount0Left,
amount1Left
);
}
AddLiquidity._refundDeposit(order.to, order.token0, order.token1, amount0Left, amount1Left);
}
function _initialDeposit(
Orders.Order calldata order,
address pairAddress,
TokenShares.Data storage tokenShares
) private returns (uint256 amount0Left, uint256 amount1Left, uint256 swapToken) {
uint256 amount0Desired = tokenShares.sharesToAmount(order.token0, order.value0, order.amountLimit0, order.to);
uint256 amount1Desired = tokenShares.sharesToAmount(order.token1, order.value1, order.amountLimit1, order.to);
(amount0Left, amount1Left, swapToken) = AddLiquidity.addLiquidityAndMint(
pairAddress,
order.to,
order.token0,
order.token1,
amount0Desired,
amount1Desired
);
}
function executeWithdraw(Orders.Order calldata order) external {
require(order.validAfterTimestamp + ORDER_LIFESPAN >= block.timestamp, 'EH04');
(address pairAddress, ) = Orders.getPair(order.token0, order.token1);
TransferHelper.safeTransfer(pairAddress, pairAddress, order.liquidity);
uint256 wethAmount;
uint256 amount0;
uint256 amount1;
if (order.unwrap && (order.token0 == TokenShares.WETH_ADDRESS || order.token1 == TokenShares.WETH_ADDRESS)) {
bool success;
(success, wethAmount, amount0, amount1) = WithdrawHelper.withdrawAndUnwrap(
order.token0,
order.token1,
pairAddress,
TokenShares.WETH_ADDRESS,
order.to,
Orders.getTransferGasCost(Orders.NATIVE_CURRENCY_SENTINEL)
);
if (!success) {
TokenShares.onUnwrapFailed(order.to, wethAmount);
}
} else {
(amount0, amount1) = ITwapPair(pairAddress).burn(order.to);
}
require(amount0 >= order.value0 && amount1 >= order.value1, 'EH03');
}
function executeBuy(ExecuteBuySellParams memory orderParams, TokenShares.Data storage tokenShares) external {
require(orderParams.order.validAfterTimestamp + ORDER_LIFESPAN >= block.timestamp, 'EH04');
uint256 amountInMax = tokenShares.sharesToAmount(
orderParams.order.token0,
orderParams.order.value0,
orderParams.order.amountLimit0,
orderParams.order.to
);
bytes memory priceInfo = encodePriceInfo(
orderParams.pairAddress,
orderParams.order.priceAccumulator,
orderParams.order.timestamp
);
uint256 amountIn;
uint256 amountOut;
uint256 reserveOut;
bool inverted = orderParams.order.inverted;
{
// scope for reserve out logic, avoids stack too deep errors
(uint112 reserve0, uint112 reserve1) = ITwapPair(orderParams.pairAddress).getReserves();
// subtract 1 to prevent reserve going to 0
reserveOut = uint256(inverted ? reserve0 : reserve1).sub(1);
}
{
// scope for partial fill logic, avoids stack too deep errors
address oracle = ITwapPair(orderParams.pairAddress).oracle();
uint256 swapFee = ITwapPair(orderParams.pairAddress).swapFee();
(amountIn, amountOut) = ITwapOracle(oracle).getSwapAmountInMaxOut(
inverted,
swapFee,
orderParams.order.value1,
priceInfo
);
uint256 amountInMaxScaled;
if (amountOut > reserveOut) {
amountInMaxScaled = amountInMax.mul(reserveOut).ceil_div(orderParams.order.value1);
(amountIn, amountOut) = ITwapOracle(oracle).getSwapAmountInMinOut(
inverted,
swapFee,
reserveOut,
priceInfo
);
} else {
amountInMaxScaled = amountInMax;
amountOut = orderParams.order.value1; // Truncate to desired out
}
require(amountInMaxScaled >= amountIn, 'EH08');
if (amountInMax > amountIn) {
if (orderParams.order.token0 == TokenShares.WETH_ADDRESS && orderParams.order.unwrap) {
forceEtherTransfer(orderParams.order.to, amountInMax.sub(amountIn));
} else {
TransferHelper.safeTransfer(
orderParams.order.token0,
orderParams.order.to,
amountInMax.sub(amountIn)
);
}
}
TransferHelper.safeTransfer(orderParams.order.token0, orderParams.pairAddress, amountIn);
}
amountOut = amountOut.sub(orderParams.pairTolerance);
uint256 amount0Out;
uint256 amount1Out;
if (inverted) {
amount0Out = amountOut;
} else {
amount1Out = amountOut;
}
if (orderParams.order.token1 == TokenShares.WETH_ADDRESS && orderParams.order.unwrap) {
ITwapPair(orderParams.pairAddress).swap(amount0Out, amount1Out, address(this), priceInfo);
forceEtherTransfer(orderParams.order.to, amountOut);
} else {
ITwapPair(orderParams.pairAddress).swap(amount0Out, amount1Out, orderParams.order.to, priceInfo);
}
}
function executeSell(ExecuteBuySellParams memory orderParams, TokenShares.Data storage tokenShares) external {
require(orderParams.order.validAfterTimestamp + ORDER_LIFESPAN >= block.timestamp, 'EH04');
bytes memory priceInfo = encodePriceInfo(
orderParams.pairAddress,
orderParams.order.priceAccumulator,
orderParams.order.timestamp
);
uint256 amountOut = _executeSellHelper(orderParams, priceInfo, tokenShares);
(uint256 amount0Out, uint256 amount1Out) = orderParams.order.inverted
? (amountOut, uint256(0))
: (uint256(0), amountOut);
if (orderParams.order.token1 == TokenShares.WETH_ADDRESS && orderParams.order.unwrap) {
ITwapPair(orderParams.pairAddress).swap(amount0Out, amount1Out, address(this), priceInfo);
forceEtherTransfer(orderParams.order.to, amountOut);
} else {
ITwapPair(orderParams.pairAddress).swap(amount0Out, amount1Out, orderParams.order.to, priceInfo);
}
}
function _executeSellHelper(
ExecuteBuySellParams memory orderParams,
bytes memory priceInfo,
TokenShares.Data storage tokenShares
) internal returns (uint256 amountOut) {
uint256 reserveOut;
{
// scope for determining reserve out, avoids stack too deep errors
(uint112 reserve0, uint112 reserve1) = ITwapPair(orderParams.pairAddress).getReserves();
// subtract 1 to prevent reserve going to 0
reserveOut = uint256(orderParams.order.inverted ? reserve0 : reserve1).sub(1);
}
{
// scope for calculations, avoids stack too deep errors
address oracle = ITwapPair(orderParams.pairAddress).oracle();
uint256 swapFee = ITwapPair(orderParams.pairAddress).swapFee();
uint256 amountIn = tokenShares.sharesToAmount(
orderParams.order.token0,
orderParams.order.value0,
orderParams.order.amountLimit0,
orderParams.order.to
);
amountOut = orderParams.order.inverted
? ITwapOracle(oracle).getSwapAmount0Out(swapFee, amountIn, priceInfo)
: ITwapOracle(oracle).getSwapAmount1Out(swapFee, amountIn, priceInfo);
uint256 amountOutMinScaled;
if (amountOut > reserveOut) {
amountOutMinScaled = orderParams.order.value1.mul(reserveOut).div(amountOut);
uint256 _amountIn = amountIn;
(amountIn, amountOut) = ITwapOracle(oracle).getSwapAmountInMinOut(
orderParams.order.inverted,
swapFee,
reserveOut,
priceInfo
);
if (orderParams.order.token0 == TokenShares.WETH_ADDRESS && orderParams.order.unwrap) {
forceEtherTransfer(orderParams.order.to, _amountIn.sub(amountIn));
} else {
TransferHelper.safeTransfer(
orderParams.order.token0,
orderParams.order.to,
_amountIn.sub(amountIn)
);
}
} else {
amountOutMinScaled = orderParams.order.value1;
}
amountOut = amountOut.sub(orderParams.pairTolerance);
require(amountOut >= amountOutMinScaled, 'EH37');
TransferHelper.safeTransfer(orderParams.order.token0, orderParams.pairAddress, amountIn);
}
}
function encodePriceInfo(
address pairAddress,
uint256 priceAccumulator,
uint256 priceTimestamp
) internal view returns (bytes memory data) {
uint256 price = ITwapOracle(ITwapPair(pairAddress).oracle()).getAveragePrice(priceAccumulator, priceTimestamp);
// Pack everything as 32 bytes / uint256 to simplify decoding
data = abi.encode(price);
}
function forceEtherTransfer(address to, uint256 amount) internal {
IWETH(TokenShares.WETH_ADDRESS).withdraw(amount);
(bool success, ) = to.call{ value: amount, gas: Orders.getTransferGasCost(Orders.NATIVE_CURRENCY_SENTINEL) }(
''
);
if (!success) {
TokenShares.onUnwrapFailed(to, amount);
}
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// a library for performing various math operations
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x > y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './SafeMath.sol';
import '../libraries/Math.sol';
import '../interfaces/ITwapFactory.sol';
import '../interfaces/ITwapPair.sol';
import '../interfaces/ITwapOracle.sol';
import '../libraries/TokenShares.sol';
library Orders {
using SafeMath for uint256;
using TokenShares for TokenShares.Data;
using TransferHelper for address;
enum OrderType {
Empty,
Deposit,
Withdraw,
Sell,
Buy
}
enum OrderStatus {
NonExistent,
EnqueuedWaiting,
EnqueuedReady,
ExecutedSucceeded,
ExecutedFailed,
Canceled
}
event DepositEnqueued(uint256 indexed orderId, Order order);
event WithdrawEnqueued(uint256 indexed orderId, Order order);
event SellEnqueued(uint256 indexed orderId, Order order);
event BuyEnqueued(uint256 indexed orderId, Order order);
event OrderTypesDisabled(address pair, Orders.OrderType[] orderTypes, bool disabled);
event RefundFailed(address indexed to, address indexed token, uint256 amount, bytes data);
// Note on gas estimation for the full order execution in the UI:
// Add (*_ORDER_BASE_COST + token transfer costs) to the actual gas usage
// of the TwapDelay._execute* functions when updating gas cost in the UI.
// Remember that ETH unwrap is part of those functions. It is optional,
// but also needs to be included in the estimate.
uint256 public constant ETHER_TRANSFER_COST = ETHER_TRANSFER_CALL_COST + 2600 + 1504; // Std cost + EIP-2929 acct access cost + Gnosis Safe receive ETH cost
uint256 private constant BOT_ETHER_TRANSFER_COST = 10_000;
uint256 private constant BUFFER_COST = 10_000;
uint256 private constant ORDER_EXECUTED_EVENT_COST = 3700;
uint256 private constant EXECUTE_PREPARATION_COST = 30_000; // dequeue + gas calculation before calls to _execute* functions
uint256 public constant ETHER_TRANSFER_CALL_COST = 10_000;
uint256 public constant PAIR_TRANSFER_COST = 55_000;
uint256 public constant REFUND_BASE_COST =
BOT_ETHER_TRANSFER_COST + ETHER_TRANSFER_COST + BUFFER_COST + ORDER_EXECUTED_EVENT_COST;
uint256 private constant ORDER_BASE_COST = EXECUTE_PREPARATION_COST + REFUND_BASE_COST;
uint256 public constant TOKEN_REFUND_BASE_COST = 20_000; // cost of performing token refund logic (excluding token transfer)
uint256 public constant DEPOSIT_ORDER_BASE_COST = ORDER_BASE_COST + 2 * TOKEN_REFUND_BASE_COST;
uint256 public constant WITHDRAW_ORDER_BASE_COST = ORDER_BASE_COST;
uint256 public constant SELL_ORDER_BASE_COST = ORDER_BASE_COST + TOKEN_REFUND_BASE_COST;
uint256 public constant BUY_ORDER_BASE_COST = ORDER_BASE_COST + TOKEN_REFUND_BASE_COST;
// Masks used for setting order disabled
// Different bits represent different order types
uint8 private constant DEPOSIT_MASK = uint8(1 << uint8(OrderType.Deposit)); // 00000010
uint8 private constant WITHDRAW_MASK = uint8(1 << uint8(OrderType.Withdraw)); // 00000100
uint8 private constant SELL_MASK = uint8(1 << uint8(OrderType.Sell)); // 00001000
uint8 private constant BUY_MASK = uint8(1 << uint8(OrderType.Buy)); // 00010000
address public constant FACTORY_ADDRESS = 0xC480b33eE5229DE3FbDFAD1D2DCD3F3BAD0C56c6;
uint256 public constant MAX_GAS_LIMIT = 5000000;
uint256 public constant GAS_PRICE_INERTIA = 20000000;
uint256 public constant MAX_GAS_PRICE_IMPACT = 1000000;
uint256 public constant DELAY = 1800;
address public constant NATIVE_CURRENCY_SENTINEL = address(0); // A sentinel value for the native currency to distinguish it from ERC20 tokens
struct Data {
uint256 newestOrderId;
uint256 lastProcessedOrderId;
mapping(uint256 => bytes32) orderQueue;
uint256 gasPrice;
mapping(uint256 => bool) canceled;
// Bit on specific positions indicates whether order type is disabled (1) or enabled (0) on specific pair
mapping(address => uint8) orderTypesDisabled;
mapping(uint256 => bool) refundFailed;
}
struct Order {
uint256 orderId;
OrderType orderType;
bool inverted;
uint256 validAfterTimestamp;
bool unwrap;
uint256 timestamp;
uint256 gasLimit;
uint256 gasPrice;
uint256 liquidity;
uint256 value0; // Deposit: share0, Withdraw: amount0Min, Sell: shareIn, Buy: shareInMax
uint256 value1; // Deposit: share1, Withdraw: amount1Min, Sell: amountOutMin, Buy: amountOut
address token0; // Sell: tokenIn, Buy: tokenIn
address token1; // Sell: tokenOut, Buy: tokenOut
address to;
uint256 minSwapPrice;
uint256 maxSwapPrice;
bool swap;
uint256 priceAccumulator;
uint256 amountLimit0;
uint256 amountLimit1;
}
function getOrderStatus(
Data storage data,
uint256 orderId,
uint256 validAfterTimestamp
) internal view returns (OrderStatus) {
if (orderId > data.newestOrderId) {
return OrderStatus.NonExistent;
}
if (data.canceled[orderId]) {
return OrderStatus.Canceled;
}
if (data.refundFailed[orderId]) {
return OrderStatus.ExecutedFailed;
}
if (data.orderQueue[orderId] == bytes32(0)) {
return OrderStatus.ExecutedSucceeded;
}
if (validAfterTimestamp >= block.timestamp) {
return OrderStatus.EnqueuedWaiting;
}
return OrderStatus.EnqueuedReady;
}
function getPair(address tokenA, address tokenB) internal view returns (address pair, bool inverted) {
pair = ITwapFactory(FACTORY_ADDRESS).getPair(tokenA, tokenB);
require(pair != address(0), 'OS17');
inverted = tokenA > tokenB;
}
function getDepositDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & DEPOSIT_MASK != 0;
}
function getWithdrawDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & WITHDRAW_MASK != 0;
}
function getSellDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & SELL_MASK != 0;
}
function getBuyDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & BUY_MASK != 0;
}
function setOrderTypesDisabled(
Data storage data,
address pair,
Orders.OrderType[] calldata orderTypes,
bool disabled
) external {
uint256 orderTypesLength = orderTypes.length;
uint8 currentSettings = data.orderTypesDisabled[pair];
uint8 combinedMask;
for (uint256 i; i < orderTypesLength; ++i) {
Orders.OrderType orderType = orderTypes[i];
require(orderType != Orders.OrderType.Empty, 'OS32');
// zeros with 1 bit set at position specified by orderType
// e.g. for SELL order type
// mask for SELL = 00001000
// combinedMask = 00000110 (DEPOSIT and WITHDRAW masks set in previous iterations)
// the result of OR = 00001110 (DEPOSIT, WITHDRAW and SELL combined mask)
combinedMask = combinedMask | uint8(1 << uint8(orderType));
}
// set/unset a bit accordingly to 'disabled' value
if (disabled) {
// OR operation to disable order
// e.g. for disable DEPOSIT
// currentSettings = 00010100 (BUY and WITHDRAW disabled)
// mask for DEPOSIT = 00000010
// the result of OR = 00010110
currentSettings = currentSettings | combinedMask;
} else {
// AND operation with a mask negation to enable order
// e.g. for enable DEPOSIT
// currentSettings = 00010100 (BUY and WITHDRAW disabled)
// 0xff = 11111111
// mask for Deposit = 00000010
// mask negation = 11111101
// the result of AND = 00010100
currentSettings = currentSettings & (combinedMask ^ 0xff);
}
require(currentSettings != data.orderTypesDisabled[pair], 'OS01');
data.orderTypesDisabled[pair] = currentSettings;
emit OrderTypesDisabled(pair, orderTypes, disabled);
}
function markRefundFailed(Data storage data) internal {
data.refundFailed[data.lastProcessedOrderId] = true;
}
/// @dev The passed in order.oderId is ignored and overwritten with the correct value, i.e. an updated data.newestOrderId.
/// This is done to ensure atomicity of these two actions while optimizing gas usage - adding an order to the queue and incrementing
/// data.newestOrderId (which should not be done anywhere else in the contract).
/// Must only be called on verified orders.
function enqueueOrder(Data storage data, Order memory order) internal {
order.orderId = ++data.newestOrderId;
data.orderQueue[order.orderId] = getOrderDigest(order);
}
struct DepositParams {
address token0;
address token1;
uint256 amount0;
uint256 amount1;
uint256 minSwapPrice;
uint256 maxSwapPrice;
bool wrap;
bool swap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function deposit(
Data storage data,
DepositParams calldata depositParams,
TokenShares.Data storage tokenShares
) external {
checkOrderParams(
depositParams.to,
depositParams.gasLimit,
depositParams.submitDeadline,
DEPOSIT_ORDER_BASE_COST +
getTransferGasCost(depositParams.token0) +
getTransferGasCost(depositParams.token1)
);
require(depositParams.amount0 != 0 || depositParams.amount1 != 0, 'OS25');
(address pairAddress, bool inverted) = getPair(depositParams.token0, depositParams.token1);
require(!getDepositDisabled(data, pairAddress), 'OS46');
{
// scope for value, avoids stack too deep errors
uint256 value = msg.value;
// allocate gas refund
if (depositParams.wrap) {
if (depositParams.token0 == TokenShares.WETH_ADDRESS) {
value = msg.value.sub(depositParams.amount0, 'OS1E');
} else if (depositParams.token1 == TokenShares.WETH_ADDRESS) {
value = msg.value.sub(depositParams.amount1, 'OS1E');
}
}
allocateGasRefund(data, value, depositParams.gasLimit);
}
uint256 shares0 = tokenShares.amountToShares(
inverted ? depositParams.token1 : depositParams.token0,
inverted ? depositParams.amount1 : depositParams.amount0,
depositParams.wrap
);
uint256 shares1 = tokenShares.amountToShares(
inverted ? depositParams.token0 : depositParams.token1,
inverted ? depositParams.amount0 : depositParams.amount1,
depositParams.wrap
);
(uint256 priceAccumulator, uint256 timestamp) = ITwapOracle(ITwapPair(pairAddress).oracle()).getPriceInfo();
Order memory order = Order(
0,
OrderType.Deposit,
inverted,
timestamp + DELAY, // validAfterTimestamp
depositParams.wrap,
timestamp,
depositParams.gasLimit,
data.gasPrice,
0, // liquidity
shares0,
shares1,
inverted ? depositParams.token1 : depositParams.token0,
inverted ? depositParams.token0 : depositParams.token1,
depositParams.to,
depositParams.minSwapPrice,
depositParams.maxSwapPrice,
depositParams.swap,
priceAccumulator,
inverted ? depositParams.amount1 : depositParams.amount0,
inverted ? depositParams.amount0 : depositParams.amount1
);
enqueueOrder(data, order);
emit DepositEnqueued(order.orderId, order);
}
struct WithdrawParams {
address token0;
address token1;
uint256 liquidity;
uint256 amount0Min;
uint256 amount1Min;
bool unwrap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function withdraw(Data storage data, WithdrawParams calldata withdrawParams) external {
(address pair, bool inverted) = getPair(withdrawParams.token0, withdrawParams.token1);
require(!getWithdrawDisabled(data, pair), 'OS0A');
checkOrderParams(
withdrawParams.to,
withdrawParams.gasLimit,
withdrawParams.submitDeadline,
WITHDRAW_ORDER_BASE_COST + PAIR_TRANSFER_COST
);
require(withdrawParams.liquidity != 0, 'OS22');
allocateGasRefund(data, msg.value, withdrawParams.gasLimit);
pair.safeTransferFrom(msg.sender, address(this), withdrawParams.liquidity);
Order memory order = Order(
0,
OrderType.Withdraw,
inverted,
block.timestamp + DELAY, // validAfterTimestamp
withdrawParams.unwrap,
0, // timestamp
withdrawParams.gasLimit,
data.gasPrice,
withdrawParams.liquidity,
inverted ? withdrawParams.amount1Min : withdrawParams.amount0Min,
inverted ? withdrawParams.amount0Min : withdrawParams.amount1Min,
inverted ? withdrawParams.token1 : withdrawParams.token0,
inverted ? withdrawParams.token0 : withdrawParams.token1,
withdrawParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
0, // priceAccumulator
0, // amountLimit0
0 // amountLimit1
);
enqueueOrder(data, order);
emit WithdrawEnqueued(order.orderId, order);
}
struct SellParams {
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 amountOutMin;
bool wrapUnwrap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function sell(Data storage data, SellParams calldata sellParams, TokenShares.Data storage tokenShares) external {
checkOrderParams(
sellParams.to,
sellParams.gasLimit,
sellParams.submitDeadline,
SELL_ORDER_BASE_COST + getTransferGasCost(sellParams.tokenIn)
);
(address pairAddress, bool inverted) = sellHelper(data, sellParams);
(uint256 priceAccumulator, uint256 timestamp) = ITwapOracle(ITwapPair(pairAddress).oracle()).getPriceInfo();
uint256 shares = tokenShares.amountToShares(sellParams.tokenIn, sellParams.amountIn, sellParams.wrapUnwrap);
Order memory order = Order(
0,
OrderType.Sell,
inverted,
timestamp + DELAY, // validAfterTimestamp
sellParams.wrapUnwrap,
timestamp,
sellParams.gasLimit,
data.gasPrice,
0, // liquidity
shares,
sellParams.amountOutMin,
sellParams.tokenIn,
sellParams.tokenOut,
sellParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
priceAccumulator,
sellParams.amountIn,
0 // amountLimit1
);
enqueueOrder(data, order);
emit SellEnqueued(order.orderId, order);
}
function relayerSell(
Data storage data,
SellParams calldata sellParams,
TokenShares.Data storage tokenShares
) external {
checkOrderParams(
sellParams.to,
sellParams.gasLimit,
sellParams.submitDeadline,
SELL_ORDER_BASE_COST + getTransferGasCost(sellParams.tokenIn)
);
(, bool inverted) = sellHelper(data, sellParams);
uint256 shares = tokenShares.amountToSharesWithoutTransfer(
sellParams.tokenIn,
sellParams.amountIn,
sellParams.wrapUnwrap
);
Order memory order = Order(
0,
OrderType.Sell,
inverted,
block.timestamp + DELAY, // validAfterTimestamp
false, // Never wrap/unwrap
block.timestamp,
sellParams.gasLimit,
data.gasPrice,
0, // liquidity
shares,
sellParams.amountOutMin,
sellParams.tokenIn,
sellParams.tokenOut,
sellParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
0, // priceAccumulator - oracleV3 pairs don't need priceAccumulator
sellParams.amountIn,
0 // amountLimit1
);
enqueueOrder(data, order);
emit SellEnqueued(order.orderId, order);
}
function sellHelper(
Data storage data,
SellParams calldata sellParams
) internal returns (address pairAddress, bool inverted) {
require(sellParams.amountIn != 0, 'OS24');
(pairAddress, inverted) = getPair(sellParams.tokenIn, sellParams.tokenOut);
require(!getSellDisabled(data, pairAddress), 'OS13');
// allocate gas refund
uint256 value = msg.value;
if (sellParams.wrapUnwrap && sellParams.tokenIn == TokenShares.WETH_ADDRESS) {
value = msg.value.sub(sellParams.amountIn, 'OS1E');
}
allocateGasRefund(data, value, sellParams.gasLimit);
}
struct BuyParams {
address tokenIn;
address tokenOut;
uint256 amountInMax;
uint256 amountOut;
bool wrapUnwrap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function buy(Data storage data, BuyParams calldata buyParams, TokenShares.Data storage tokenShares) external {
checkOrderParams(
buyParams.to,
buyParams.gasLimit,
buyParams.submitDeadline,
BUY_ORDER_BASE_COST + getTransferGasCost(buyParams.tokenIn)
);
require(buyParams.amountOut != 0, 'OS23');
(address pairAddress, bool inverted) = getPair(buyParams.tokenIn, buyParams.tokenOut);
require(!getBuyDisabled(data, pairAddress), 'OS49');
uint256 value = msg.value;
// allocate gas refund
if (buyParams.tokenIn == TokenShares.WETH_ADDRESS && buyParams.wrapUnwrap) {
value = msg.value.sub(buyParams.amountInMax, 'OS1E');
}
allocateGasRefund(data, value, buyParams.gasLimit);
uint256 shares = tokenShares.amountToShares(buyParams.tokenIn, buyParams.amountInMax, buyParams.wrapUnwrap);
(uint256 priceAccumulator, uint256 timestamp) = ITwapOracle(ITwapPair(pairAddress).oracle()).getPriceInfo();
Order memory order = Order(
0,
OrderType.Buy,
inverted,
timestamp + DELAY, // validAfterTimestamp
buyParams.wrapUnwrap,
timestamp,
buyParams.gasLimit,
data.gasPrice,
0, // liquidity
shares,
buyParams.amountOut,
buyParams.tokenIn,
buyParams.tokenOut,
buyParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
priceAccumulator,
buyParams.amountInMax,
0 // amountLimit1
);
enqueueOrder(data, order);
emit BuyEnqueued(order.orderId, order);
}
function checkOrderParams(address to, uint256 gasLimit, uint32 submitDeadline, uint256 minGasLimit) private view {
require(submitDeadline >= block.timestamp, 'OS04');
require(gasLimit <= MAX_GAS_LIMIT, 'OS3E');
require(gasLimit >= minGasLimit, 'OS3D');
require(to != address(0), 'OS26');
}
function allocateGasRefund(Data storage data, uint256 value, uint256 gasLimit) private returns (uint256 futureFee) {
futureFee = data.gasPrice.mul(gasLimit);
require(value >= futureFee, 'OS1E');
if (value > futureFee) {
TransferHelper.safeTransferETH(msg.sender, value - futureFee, getTransferGasCost(NATIVE_CURRENCY_SENTINEL));
}
}
function updateGasPrice(Data storage data, uint256 gasUsed) external {
uint256 scale = Math.min(gasUsed, MAX_GAS_PRICE_IMPACT);
data.gasPrice = data.gasPrice.mul(GAS_PRICE_INERTIA.sub(scale)).add(tx.gasprice.mul(scale)).div(
GAS_PRICE_INERTIA
);
}
function refundLiquidity(address pair, address to, uint256 liquidity, bytes4 selector) internal returns (bool) {
if (liquidity == 0) {
return true;
}
(bool success, bytes memory data) = address(this).call{ gas: PAIR_TRANSFER_COST }(
abi.encodeWithSelector(selector, pair, to, liquidity, false)
);
if (!success) {
emit RefundFailed(to, pair, liquidity, data);
}
return success;
}
function dequeueOrder(Data storage data, uint256 orderId) internal {
++data.lastProcessedOrderId;
require(orderId == data.lastProcessedOrderId, 'OS72');
}
function forgetOrder(Data storage data, uint256 orderId) internal {
delete data.orderQueue[orderId];
}
function forgetLastProcessedOrder(Data storage data) internal {
delete data.orderQueue[data.lastProcessedOrderId];
}
function getOrderDigest(Order memory order) internal pure returns (bytes32) {
// Used to avoid the 'stack too deep' error.
bytes memory partialOrderData = abi.encodePacked(
order.orderId,
order.orderType,
order.inverted,
order.validAfterTimestamp,
order.unwrap,
order.timestamp,
order.gasLimit,
order.gasPrice,
order.liquidity,
order.value0,
order.value1,
order.token0,
order.token1,
order.to
);
return
keccak256(
abi.encodePacked(
partialOrderData,
order.minSwapPrice,
order.maxSwapPrice,
order.swap,
order.priceAccumulator,
order.amountLimit0,
order.amountLimit1
)
);
}
function verifyOrder(Data storage data, Order memory order) external view {
require(getOrderDigest(order) == data.orderQueue[order.orderId], 'OS71');
}
// constant mapping for transferGasCost
/**
* @dev This function should either return a default value != 0 or revert.
*/
function getTransferGasCost(address token) internal pure returns (uint256) {
if (token == NATIVE_CURRENCY_SENTINEL) return ETHER_TRANSFER_CALL_COST;
if (token == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) return 31000;
if (token == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 42000;
if (token == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return 66000;
if (token == 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599) return 34000;
if (token == 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B) return 31000;
if (token == 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2) return 31000;
if (token == 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84) return 68000;
if (token == 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0) return 31000;
if (token == 0xD33526068D116cE69F19A9ee46F0bd304F21A51f) return 31000;
if (token == 0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2) return 40000;
if (token == 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32) return 149000;
if (token == 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2) return 34000;
if (token == 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984) return 37000;
if (token == 0x514910771AF9Ca656af840dff83E8264EcF986CA) return 32000;
if (token == 0x3c3a81e81dc49A522A592e7622A7E711c06bf354) return 34000;
return 60000;
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
int256 private constant _INT256_MIN = -2 ** 255;
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'SM4E');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = sub(x, y, 'SM12');
}
function sub(uint256 x, uint256 y, string memory message) internal pure returns (uint256 z) {
require((z = x - y) <= x, message);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'SM2A');
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SM43');
return a / b;
}
function ceil_div(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = div(a, b);
if (a != mul(b, c)) {
return add(c, 1);
}
}
function toUint32(uint256 n) internal pure returns (uint32) {
require(n <= type(uint32).max, 'SM50');
return uint32(n);
}
function toUint64(uint256 n) internal pure returns (uint64) {
require(n <= type(uint64).max, 'SM54');
return uint64(n);
}
function toUint112(uint256 n) internal pure returns (uint112) {
require(n <= type(uint112).max, 'SM51');
return uint112(n);
}
function toInt256(uint256 unsigned) internal pure returns (int256 signed) {
require(unsigned <= uint256(type(int256).max), 'SM34');
signed = int256(unsigned);
}
// int256
function add(int256 a, int256 b) internal pure returns (int256 c) {
c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), 'SM4D');
}
function sub(int256 a, int256 b) internal pure returns (int256 c) {
c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), 'SM11');
}
function mul(int256 a, int256 b) internal pure returns (int256 c) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), 'SM29');
c = a * b;
require(c / a == b, 'SM29');
}
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, 'SM43');
require(!(b == -1 && a == _INT256_MIN), 'SM42');
return a / b;
}
function neg_floor_div(int256 a, int256 b) internal pure returns (int256 c) {
c = div(a, b);
if ((a < 0 && b > 0) || (a >= 0 && b < 0)) {
if (a != mul(b, c)) {
c = sub(c, 1);
}
}
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import '../interfaces/IERC20.sol';
import '../interfaces/IWETH.sol';
import './SafeMath.sol';
import './TransferHelper.sol';
library TokenShares {
using SafeMath for uint256;
using TransferHelper for address;
uint256 private constant PRECISION = 10 ** 18;
uint256 private constant TOLERANCE = 10 ** 18 + 10 ** 16;
uint256 private constant TOTAL_SHARES_PRECISION = 10 ** 18;
event UnwrapFailed(address to, uint256 amount);
// represents wrapped native currency (WETH or WMATIC)
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
struct Data {
mapping(address => uint256) totalShares;
}
function sharesToAmount(
Data storage data,
address token,
uint256 share,
uint256 amountLimit,
address refundTo
) external returns (uint256) {
if (share == 0) {
return 0;
}
if (token == WETH_ADDRESS || isNonRebasing(token)) {
return share;
}
uint256 totalTokenShares = data.totalShares[token];
require(totalTokenShares >= share, 'TS3A');
uint256 balance = IERC20(token).balanceOf(address(this));
uint256 value = balance.mul(share).div(totalTokenShares);
data.totalShares[token] = totalTokenShares.sub(share);
if (amountLimit > 0) {
uint256 amountLimitWithTolerance = amountLimit.mul(TOLERANCE).div(PRECISION);
if (value > amountLimitWithTolerance) {
TransferHelper.safeTransfer(token, refundTo, value.sub(amountLimitWithTolerance));
return amountLimitWithTolerance;
}
}
return value;
}
function amountToShares(Data storage data, address token, uint256 amount, bool wrap) external returns (uint256) {
if (amount == 0) {
return 0;
}
if (token == WETH_ADDRESS) {
if (wrap) {
require(msg.value >= amount, 'TS03');
IWETH(token).deposit{ value: amount }();
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
return amount;
} else if (isNonRebasing(token)) {
token.safeTransferFrom(msg.sender, address(this), amount);
return amount;
} else {
uint256 balanceBefore = IERC20(token).balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), amount);
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
return amountToSharesHelper(data, token, balanceBefore, balanceAfter);
}
}
function amountToSharesWithoutTransfer(
Data storage data,
address token,
uint256 amount,
bool wrap
) external returns (uint256) {
if (token == WETH_ADDRESS) {
if (wrap) {
// require(msg.value >= amount, 'TS03'); // Duplicate check in TwapRelayer.sell
IWETH(token).deposit{ value: amount }();
}
return amount;
} else if (isNonRebasing(token)) {
return amount;
} else {
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
uint256 balanceBefore = balanceAfter.sub(amount);
return amountToSharesHelper(data, token, balanceBefore, balanceAfter);
}
}
function amountToSharesHelper(
Data storage data,
address token,
uint256 balanceBefore,
uint256 balanceAfter
) internal returns (uint256) {
uint256 totalTokenShares = data.totalShares[token];
require(balanceBefore > 0 || totalTokenShares == 0, 'TS30');
require(balanceAfter > balanceBefore, 'TS2C');
if (balanceBefore > 0) {
if (totalTokenShares == 0) {
totalTokenShares = balanceBefore.mul(TOTAL_SHARES_PRECISION);
}
uint256 newShares = totalTokenShares.mul(balanceAfter).div(balanceBefore);
require(balanceAfter < type(uint256).max.div(newShares), 'TS73'); // to prevent overflow at execution
data.totalShares[token] = newShares;
return newShares - totalTokenShares;
} else {
totalTokenShares = balanceAfter.mul(TOTAL_SHARES_PRECISION);
require(totalTokenShares < type(uint256).max.div(totalTokenShares), 'TS73'); // to prevent overflow at execution
data.totalShares[token] = totalTokenShares;
return totalTokenShares;
}
}
function onUnwrapFailed(address to, uint256 amount) external {
emit UnwrapFailed(to, amount);
IWETH(WETH_ADDRESS).deposit{ value: amount }();
TransferHelper.safeTransfer(WETH_ADDRESS, to, amount);
}
// constant mapping for nonRebasingToken
function isNonRebasing(address token) internal pure returns (bool) {
if (token == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) return true;
if (token == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return true;
if (token == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return true;
if (token == 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599) return true;
if (token == 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B) return true;
if (token == 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2) return true;
if (token == 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0) return true;
if (token == 0xD33526068D116cE69F19A9ee46F0bd304F21A51f) return true;
if (token == 0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2) return true;
if (token == 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32) return true;
if (token == 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2) return true;
if (token == 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984) return true;
if (token == 0x514910771AF9Ca656af840dff83E8264EcF986CA) return true;
if (token == 0x3c3a81e81dc49A522A592e7622A7E711c06bf354) return true;
return false;
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint256 value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH4B');
}
function safeTransfer(address token, address to, uint256 value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH05');
}
function safeTransferFrom(address token, address from, address to, uint256 value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH0E');
}
function safeTransferETH(address to, uint256 value, uint256 gasLimit) internal {
(bool success, ) = to.call{ value: value, gas: gasLimit }('');
require(success, 'TH3F');
}
function transferETH(address to, uint256 value, uint256 gasLimit) internal returns (bool success) {
(success, ) = to.call{ value: value, gas: gasLimit }('');
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import '../interfaces/ITwapPair.sol';
import '../interfaces/IWETH.sol';
import './Orders.sol';
library WithdrawHelper {
using SafeMath for uint256;
function _transferToken(uint256 balanceBefore, address token, address to) internal {
uint256 tokenAmount = IERC20(token).balanceOf(address(this)).sub(balanceBefore);
TransferHelper.safeTransfer(token, to, tokenAmount);
}
// unwraps wrapped native currency
function _unwrapWeth(uint256 ethAmount, address weth, address to, uint256 gasLimit) internal returns (bool) {
IWETH(weth).withdraw(ethAmount);
(bool success, ) = to.call{ value: ethAmount, gas: gasLimit }('');
return success;
}
function withdrawAndUnwrap(
address token0,
address token1,
address pair,
address weth,
address to,
uint256 gasLimit
) external returns (bool, uint256, uint256, uint256) {
bool isToken0Weth = token0 == weth;
address otherToken = isToken0Weth ? token1 : token0;
uint256 balanceBefore = IERC20(otherToken).balanceOf(address(this));
(uint256 amount0, uint256 amount1) = ITwapPair(pair).burn(address(this));
_transferToken(balanceBefore, otherToken, to);
bool success = _unwrapWeth(isToken0Weth ? amount0 : amount1, weth, to, gasLimit);
return (success, isToken0Weth ? amount0 : amount1, amount0, amount1);
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './interfaces/ITwapPair.sol';
import './interfaces/ITwapDelay.sol';
import './interfaces/IWETH.sol';
import './libraries/SafeMath.sol';
import './libraries/Orders.sol';
import './libraries/TokenShares.sol';
import './libraries/AddLiquidity.sol';
import './libraries/WithdrawHelper.sol';
import './libraries/ExecutionHelper.sol';
import './interfaces/ITwapFactoryGovernor.sol';
contract TwapDelay is ITwapDelay {
using SafeMath for uint256;
using Orders for Orders.Data;
using TokenShares for TokenShares.Data;
Orders.Data internal orders;
TokenShares.Data internal tokenShares;
uint256 private constant ORDER_CANCEL_TIME = 24 hours;
uint256 private constant BOT_EXECUTION_TIME = 20 minutes;
address public override owner;
address public override factoryGovernor;
address public constant RELAYER_ADDRESS = 0xd17b3c9784510E33cD5B87b490E79253BcD81e2E;
mapping(address => bool) public override isBot;
constructor(address _factoryGovernor, address _bot) {
_setOwner(msg.sender);
_setFactoryGovernor(_factoryGovernor);
_setBot(_bot, true);
orders.gasPrice = tx.gasprice;
_emitEventWithDefaults();
}
function getTransferGasCost(address token) external pure override returns (uint256 gasCost) {
return Orders.getTransferGasCost(token);
}
function getDepositDisabled(address pair) external view override returns (bool) {
return orders.getDepositDisabled(pair);
}
function getWithdrawDisabled(address pair) external view override returns (bool) {
return orders.getWithdrawDisabled(pair);
}
function getBuyDisabled(address pair) external view override returns (bool) {
return orders.getBuyDisabled(pair);
}
function getSellDisabled(address pair) external view override returns (bool) {
return orders.getSellDisabled(pair);
}
function getOrderStatus(
uint256 orderId,
uint256 validAfterTimestamp
) external view override returns (Orders.OrderStatus) {
return orders.getOrderStatus(orderId, validAfterTimestamp);
}
uint256 private locked = 1;
modifier lock() {
require(locked == 1, 'TD06');
locked = 2;
_;
locked = 1;
}
function factory() external pure override returns (address) {
return Orders.FACTORY_ADDRESS;
}
function totalShares(address token) external view override returns (uint256) {
return tokenShares.totalShares[token];
}
// returns wrapped native currency for particular blockchain (WETH or WMATIC)
function weth() external pure override returns (address) {
return TokenShares.WETH_ADDRESS;
}
function relayer() external pure override returns (address) {
return RELAYER_ADDRESS;
}
function isNonRebasingToken(address token) external pure override returns (bool) {
return TokenShares.isNonRebasing(token);
}
function delay() external pure override returns (uint256) {
return Orders.DELAY;
}
function lastProcessedOrderId() external view returns (uint256) {
return orders.lastProcessedOrderId;
}
function newestOrderId() external view returns (uint256) {
return orders.newestOrderId;
}
function isOrderCanceled(uint256 orderId) external view returns (bool) {
return orders.canceled[orderId];
}
function maxGasLimit() external pure override returns (uint256) {
return Orders.MAX_GAS_LIMIT;
}
function maxGasPriceImpact() external pure override returns (uint256) {
return Orders.MAX_GAS_PRICE_IMPACT;
}
function gasPriceInertia() external pure override returns (uint256) {
return Orders.GAS_PRICE_INERTIA;
}
function gasPrice() external view override returns (uint256) {
return orders.gasPrice;
}
function setOrderTypesDisabled(
address pair,
Orders.OrderType[] calldata orderTypes,
bool disabled
) external override {
require(msg.sender == owner, 'TD00');
orders.setOrderTypesDisabled(pair, orderTypes, disabled);
}
function setOwner(address _owner) external override {
require(msg.sender == owner, 'TD00');
_setOwner(_owner);
}
function _setOwner(address _owner) internal {
require(_owner != owner, 'TD01');
require(_owner != address(0), 'TD02');
owner = _owner;
emit OwnerSet(_owner);
}
function setFactoryGovernor(address _factoryGovernor) external override {
require(msg.sender == owner, 'TD00');
_setFactoryGovernor(_factoryGovernor);
}
function _setFactoryGovernor(address _factoryGovernor) internal {
require(_factoryGovernor != factoryGovernor, 'TD01');
require(_factoryGovernor != address(0), 'TD02');
factoryGovernor = _factoryGovernor;
emit FactoryGovernorSet(_factoryGovernor);
}
function setBot(address _bot, bool _isBot) external override {
require(msg.sender == owner, 'TD00');
_setBot(_bot, _isBot);
}
function _setBot(address _bot, bool _isBot) internal {
require(_isBot != isBot[_bot], 'TD01');
isBot[_bot] = _isBot;
emit BotSet(_bot, _isBot);
}
function deposit(
Orders.DepositParams calldata depositParams
) external payable override lock returns (uint256 orderId) {
orders.deposit(depositParams, tokenShares);
return orders.newestOrderId;
}
function withdraw(
Orders.WithdrawParams calldata withdrawParams
) external payable override lock returns (uint256 orderId) {
orders.withdraw(withdrawParams);
return orders.newestOrderId;
}
function sell(Orders.SellParams calldata sellParams) external payable override lock returns (uint256 orderId) {
orders.sell(sellParams, tokenShares);
return orders.newestOrderId;
}
function relayerSell(
Orders.SellParams calldata sellParams
) external payable override lock returns (uint256 orderId) {
require(msg.sender == RELAYER_ADDRESS, 'TD00');
orders.relayerSell(sellParams, tokenShares);
return orders.newestOrderId;
}
function buy(Orders.BuyParams calldata buyParams) external payable override lock returns (uint256 orderId) {
orders.buy(buyParams, tokenShares);
return orders.newestOrderId;
}
/// @dev This implementation processes orders sequentially and skips orders that have already been executed.
/// If it encounters an order that is not yet valid, it stops execution since subsequent orders will also be invalid
/// at the time.
function execute(Orders.Order[] calldata _orders) external payable override lock {
uint256 ordersLength = _orders.length;
uint256 gasBefore = gasleft();
bool orderExecuted;
bool senderCanExecute = isBot[msg.sender] || isBot[address(0)];
for (uint256 i; i < ordersLength; ++i) {
if (_orders[i].orderId <= orders.lastProcessedOrderId) {
continue;
}
if (orders.canceled[_orders[i].orderId]) {
orders.dequeueOrder(_orders[i].orderId);
continue;
}
orders.verifyOrder(_orders[i]);
uint256 validAfterTimestamp = _orders[i].validAfterTimestamp;
if (validAfterTimestamp >= block.timestamp) {
break;
}
require(senderCanExecute || block.timestamp >= validAfterTimestamp + BOT_EXECUTION_TIME, 'TD00');
orderExecuted = true;
if (_orders[i].orderType == Orders.OrderType.Deposit) {
executeDeposit(_orders[i]);
} else if (_orders[i].orderType == Orders.OrderType.Withdraw) {
executeWithdraw(_orders[i]);
} else if (_orders[i].orderType == Orders.OrderType.Sell) {
executeSell(_orders[i]);
} else if (_orders[i].orderType == Orders.OrderType.Buy) {
executeBuy(_orders[i]);
}
}
if (orderExecuted) {
orders.updateGasPrice(gasBefore.sub(gasleft()));
}
}
/// @dev The `order` must be verified by calling `Orders.verifyOrder` before calling this function.
function executeDeposit(Orders.Order calldata order) internal {
uint256 gasStart = gasleft();
orders.dequeueOrder(order.orderId);
(bool executionSuccess, bytes memory data) = address(this).call{
gas: order.gasLimit.sub(
Orders.DEPOSIT_ORDER_BASE_COST +
Orders.getTransferGasCost(order.token0) +
Orders.getTransferGasCost(order.token1)
)
}(abi.encodeWithSelector(this._executeDeposit.selector, order));
bool refundSuccess = true;
if (!executionSuccess) {
refundSuccess = refundTokens(
order.to,
order.token0,
order.value0,
order.token1,
order.value1,
order.unwrap,
false
);
}
finalizeOrder(refundSuccess);
(uint256 gasUsed, uint256 ethRefund) = refund(order.gasLimit, order.gasPrice, gasStart, order.to);
emit OrderExecuted(orders.lastProcessedOrderId, executionSuccess, data, gasUsed, ethRefund);
}
/// @dev The `order` must be verified by calling `Orders.verifyOrder` before calling this function.
function executeWithdraw(Orders.Order calldata order) internal {
uint256 gasStart = gasleft();
orders.dequeueOrder(order.orderId);
(bool executionSuccess, bytes memory data) = address(this).call{
gas: order.gasLimit.sub(Orders.WITHDRAW_ORDER_BASE_COST + Orders.PAIR_TRANSFER_COST)
}(abi.encodeWithSelector(this._executeWithdraw.selector, order));
bool refundSuccess = true;
if (!executionSuccess) {
(address pair, ) = Orders.getPair(order.token0, order.token1);
refundSuccess = Orders.refundLiquidity(pair, order.to, order.liquidity, this._refundLiquidity.selector);
}
finalizeOrder(refundSuccess);
(uint256 gasUsed, uint256 ethRefund) = refund(order.gasLimit, order.gasPrice, gasStart, order.to);
emit OrderExecuted(orders.lastProcessedOrderId, executionSuccess, data, gasUsed, ethRefund);
}
/// @dev The `order` must be verified by calling `Orders.verifyOrder` before calling this function.
function executeSell(Orders.Order calldata order) internal {
uint256 gasStart = gasleft();
orders.dequeueOrder(order.orderId);
(bool executionSuccess, bytes memory data) = address(this).call{
gas: order.gasLimit.sub(Orders.SELL_ORDER_BASE_COST + Orders.getTransferGasCost(order.token0))
}(abi.encodeWithSelector(this._executeSell.selector, order));
bool refundSuccess = true;
if (!executionSuccess) {
refundSuccess = refundToken(order.token0, order.to, order.value0, order.unwrap, false);
}
finalizeOrder(refundSuccess);
(uint256 gasUsed, uint256 ethRefund) = refund(order.gasLimit, order.gasPrice, gasStart, order.to);
emit OrderExecuted(orders.lastProcessedOrderId, executionSuccess, data, gasUsed, ethRefund);
}
/// @dev The `order` must be verified by calling `Orders.verifyOrder` before calling this function.
function executeBuy(Orders.Order calldata order) internal {
uint256 gasStart = gasleft();
orders.dequeueOrder(order.orderId);
(bool executionSuccess, bytes memory data) = address(this).call{
gas: order.gasLimit.sub(Orders.BUY_ORDER_BASE_COST + Orders.getTransferGasCost(order.token0))
}(abi.encodeWithSelector(this._executeBuy.selector, order));
bool refundSuccess = true;
if (!executionSuccess) {
refundSuccess = refundToken(order.token0, order.to, order.value0, order.unwrap, false);
}
finalizeOrder(refundSuccess);
(uint256 gasUsed, uint256 ethRefund) = refund(order.gasLimit, order.gasPrice, gasStart, order.to);
emit OrderExecuted(orders.lastProcessedOrderId, executionSuccess, data, gasUsed, ethRefund);
}
function finalizeOrder(bool refundSuccess) private {
if (!refundSuccess) {
orders.markRefundFailed();
} else {
orders.forgetLastProcessedOrder();
}
}
function refund(
uint256 gasLimit,
uint256 gasPriceInOrder,
uint256 gasStart,
address to
) private returns (uint256 gasUsed, uint256 leftOver) {
uint256 feeCollected = gasLimit.mul(gasPriceInOrder);
gasUsed = gasStart.sub(gasleft()).add(Orders.REFUND_BASE_COST);
uint256 actualRefund = Math.min(feeCollected, gasUsed.mul(orders.gasPrice));
leftOver = feeCollected.sub(actualRefund);
require(refundEth(msg.sender, actualRefund), 'TD40');
refundEth(payable(to), leftOver);
}
function refundEth(address payable to, uint256 value) internal returns (bool success) {
if (value == 0) {
return true;
}
success = TransferHelper.transferETH(to, value, Orders.getTransferGasCost(Orders.NATIVE_CURRENCY_SENTINEL));
emit EthRefund(to, success, value);
}
function refundToken(
address token,
address to,
uint256 share,
bool unwrap,
bool forwardAllGas
) private returns (bool) {
if (share == 0) {
return true;
}
(bool success, bytes memory data) = address(this).call{
gas: forwardAllGas ? gasleft() : Orders.TOKEN_REFUND_BASE_COST + Orders.getTransferGasCost(token)
}(abi.encodeWithSelector(this._refundToken.selector, token, to, share, unwrap));
if (!success) {
emit Orders.RefundFailed(to, token, share, data);
}
return success;
}
function refundTokens(
address to,
address token0,
uint256 share0,
address token1,
uint256 share1,
bool unwrap,
bool forwardAllGas
) private returns (bool) {
(bool success, bytes memory data) = address(this).call{
gas: forwardAllGas
? gasleft()
: 2 *
Orders.TOKEN_REFUND_BASE_COST +
Orders.getTransferGasCost(token0) +
Orders.getTransferGasCost(token1)
}(abi.encodeWithSelector(this._refundTokens.selector, to, token0, share0, token1, share1, unwrap));
if (!success) {
emit Orders.RefundFailed(to, token0, share0, data);
emit Orders.RefundFailed(to, token1, share1, data);
}
return success;
}
function _refundTokens(
address to,
address token0,
uint256 share0,
address token1,
uint256 share1,
bool unwrap
) external payable {
// no need to check sender, because it is checked in _refundToken
_refundToken(token0, to, share0, unwrap);
_refundToken(token1, to, share1, unwrap);
}
function _refundToken(address token, address to, uint256 share, bool unwrap) public payable {
require(msg.sender == address(this), 'TD00');
if (token == TokenShares.WETH_ADDRESS && unwrap) {
uint256 amount = tokenShares.sharesToAmount(token, share, 0, to);
IWETH(TokenShares.WETH_ADDRESS).withdraw(amount);
TransferHelper.safeTransferETH(to, amount, Orders.getTransferGasCost(Orders.NATIVE_CURRENCY_SENTINEL));
} else {
TransferHelper.safeTransfer(token, to, tokenShares.sharesToAmount(token, share, 0, to));
}
}
function _refundLiquidity(address pair, address to, uint256 liquidity) external payable {
require(msg.sender == address(this), 'TD00');
return TransferHelper.safeTransfer(pair, to, liquidity);
}
function _executeDeposit(Orders.Order calldata order) external payable {
require(msg.sender == address(this), 'TD00');
(address pairAddress, ) = Orders.getPair(order.token0, order.token1);
ITwapPair(pairAddress).sync();
ITwapFactoryGovernor(factoryGovernor).distributeFees(order.token0, order.token1, pairAddress);
ITwapPair(pairAddress).sync();
ExecutionHelper.executeDeposit(order, pairAddress, getTolerance(pairAddress), tokenShares);
}
function _executeWithdraw(Orders.Order calldata order) external payable {
require(msg.sender == address(this), 'TD00');
(address pairAddress, ) = Orders.getPair(order.token0, order.token1);
ITwapPair(pairAddress).sync();
ITwapFactoryGovernor(factoryGovernor).distributeFees(order.token0, order.token1, pairAddress);
ITwapPair(pairAddress).sync();
ExecutionHelper.executeWithdraw(order);
}
function _executeBuy(Orders.Order calldata order) external payable {
require(msg.sender == address(this), 'TD00');
(address pairAddress, ) = Orders.getPair(order.token0, order.token1);
ExecutionHelper.ExecuteBuySellParams memory orderParams;
orderParams.order = order;
orderParams.pairAddress = pairAddress;
orderParams.pairTolerance = getTolerance(pairAddress);
ITwapPair(pairAddress).sync();
ExecutionHelper.executeBuy(orderParams, tokenShares);
}
function _executeSell(Orders.Order calldata order) external payable {
require(msg.sender == address(this), 'TD00');
(address pairAddress, ) = Orders.getPair(order.token0, order.token1);
ExecutionHelper.ExecuteBuySellParams memory orderParams;
orderParams.order = order;
orderParams.pairAddress = pairAddress;
orderParams.pairTolerance = getTolerance(pairAddress);
ITwapPair(pairAddress).sync();
ExecutionHelper.executeSell(orderParams, tokenShares);
}
/// @dev The `order` must be verified by calling `Orders.verifyOrder` before calling this function.
function performRefund(Orders.Order calldata order, bool shouldRefundEth) internal {
bool canOwnerRefund = order.validAfterTimestamp.add(365 days) < block.timestamp;
if (order.orderType == Orders.OrderType.Deposit) {
address to = canOwnerRefund ? owner : order.to;
require(
refundTokens(to, order.token0, order.value0, order.token1, order.value1, order.unwrap, true),
'TD14'
);
if (shouldRefundEth) {
require(refundEth(payable(to), order.gasPrice.mul(order.gasLimit)), 'TD40');
}
} else if (order.orderType == Orders.OrderType.Withdraw) {
(address pair, ) = Orders.getPair(order.token0, order.token1);
address to = canOwnerRefund ? owner : order.to;
require(Orders.refundLiquidity(pair, to, order.liquidity, this._refundLiquidity.selector), 'TD14');
if (shouldRefundEth) {
require(refundEth(payable(to), order.gasPrice.mul(order.gasLimit)), 'TD40');
}
} else if (order.orderType == Orders.OrderType.Sell) {
address to = canOwnerRefund ? owner : order.to;
require(refundToken(order.token0, to, order.value0, order.unwrap, true), 'TD14');
if (shouldRefundEth) {
require(refundEth(payable(to), order.gasPrice.mul(order.gasLimit)), 'TD40');
}
} else if (order.orderType == Orders.OrderType.Buy) {
address to = canOwnerRefund ? owner : order.to;
require(refundToken(order.token0, to, order.value0, order.unwrap, true), 'TD14');
if (shouldRefundEth) {
require(refundEth(payable(to), order.gasPrice.mul(order.gasLimit)), 'TD40');
}
} else {
return;
}
orders.forgetOrder(order.orderId);
}
function retryRefund(Orders.Order calldata order) external override lock {
orders.verifyOrder(order);
require(orders.refundFailed[order.orderId], 'TD21');
performRefund(order, false);
}
function cancelOrder(Orders.Order calldata order) external override lock {
orders.verifyOrder(order);
require(
orders.getOrderStatus(order.orderId, order.validAfterTimestamp) == Orders.OrderStatus.EnqueuedReady,
'TD52'
);
require(order.validAfterTimestamp.sub(Orders.DELAY).add(ORDER_CANCEL_TIME) < block.timestamp, 'TD1C');
orders.canceled[order.orderId] = true;
performRefund(order, true);
}
function syncPair(address token0, address token1) external override returns (address pairAddress) {
require(msg.sender == factoryGovernor, 'TD00');
(pairAddress, ) = Orders.getPair(token0, token1);
ITwapPair(pairAddress).sync();
}
function _emitEventWithDefaults() internal {
emit MaxGasLimitSet(Orders.MAX_GAS_LIMIT);
emit GasPriceInertiaSet(Orders.GAS_PRICE_INERTIA);
emit MaxGasPriceImpactSet(Orders.MAX_GAS_PRICE_IMPACT);
emit DelaySet(Orders.DELAY);
emit RelayerSet(RELAYER_ADDRESS);
emit ToleranceSet(0x2fe16Dd18bba26e457B7dD2080d5674312b026a2, 0);
emit ToleranceSet(0x048f0e7ea2CFD522a4a058D1b1bDd574A0486c46, 0);
emit ToleranceSet(0x37F6dF71b40c50b2038329CaBf5FDa3682Df1ebF, 0);
emit ToleranceSet(0x6ec472b613012a492693697FA551420E60567eA7, 0);
emit ToleranceSet(0x43f0E5f2304F261DfA5359a0b74Ff030E498D904, 0);
emit ToleranceSet(0xD66f214fB49f81Ac5610e0339A351D7e1c67c35e, 0);
emit ToleranceSet(0xD4d2140eD70DCF8794A986F0CFD07560ee738C71, 4);
emit ToleranceSet(0x29b57D56a114aE5BE3c129240898B3321A70A300, 0);
emit ToleranceSet(0x61fA1CEe13CEEAF20C30611c5e6dA48c595F7dB2, 0);
emit ToleranceSet(0x045950A37c59d75496BB4Af68c05f9066A4C7e27, 0);
emit ToleranceSet(0xbEE7Ef1adfaa628536Ebc0C1EBF082DbDC27265F, 0);
emit ToleranceSet(0x51baDc1622C63d1E448A4F1aC1DC008b8a27Fe67, 0);
emit ToleranceSet(0x0e52DB138Df9CE54Bc9D9330f418015eD512830A, 0);
emit ToleranceSet(0xDDE7684D88E0B482B2b455936fe0D22dd48CDcb3, 0);
emit ToleranceSet(0x43102f07414D95eF71EC9aEbA011b8595BA010D0, 0);
emit TransferGasCostSet(Orders.NATIVE_CURRENCY_SENTINEL, Orders.ETHER_TRANSFER_CALL_COST);
emit TransferGasCostSet(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 31000);
emit TransferGasCostSet(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 42000);
emit TransferGasCostSet(0xdAC17F958D2ee523a2206206994597C13D831ec7, 66000);
emit TransferGasCostSet(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, 34000);
emit TransferGasCostSet(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B, 31000);
emit TransferGasCostSet(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2, 31000);
emit TransferGasCostSet(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84, 68000);
emit TransferGasCostSet(0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0, 31000);
emit TransferGasCostSet(0xD33526068D116cE69F19A9ee46F0bd304F21A51f, 31000);
emit TransferGasCostSet(0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2, 40000);
emit TransferGasCostSet(0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32, 149000);
emit TransferGasCostSet(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2, 34000);
emit TransferGasCostSet(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984, 37000);
emit TransferGasCostSet(0x514910771AF9Ca656af840dff83E8264EcF986CA, 32000);
emit TransferGasCostSet(0x3c3a81e81dc49A522A592e7622A7E711c06bf354, 34000);
emit NonRebasingTokenSet(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, true);
emit NonRebasingTokenSet(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, true);
emit NonRebasingTokenSet(0xdAC17F958D2ee523a2206206994597C13D831ec7, true);
emit NonRebasingTokenSet(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, true);
emit NonRebasingTokenSet(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B, true);
emit NonRebasingTokenSet(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2, true);
emit NonRebasingTokenSet(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84, false);
emit NonRebasingTokenSet(0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0, true);
emit NonRebasingTokenSet(0xD33526068D116cE69F19A9ee46F0bd304F21A51f, true);
emit NonRebasingTokenSet(0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2, true);
emit NonRebasingTokenSet(0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32, true);
emit NonRebasingTokenSet(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2, true);
emit NonRebasingTokenSet(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984, true);
emit NonRebasingTokenSet(0x514910771AF9Ca656af840dff83E8264EcF986CA, true);
emit NonRebasingTokenSet(0x3c3a81e81dc49A522A592e7622A7E711c06bf354, true);
}
// constant mapping for tolerance
function getTolerance(address pair) public virtual view override returns (uint16 tolerance) {
if (pair == 0xD4d2140eD70DCF8794A986F0CFD07560ee738C71) return 4;
return 0;
}
receive() external payable {}
}
File 2 of 11: TwapPair
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import './interfaces/ITwapPair.sol';
import './libraries/Reserves.sol';
import './TwapLPToken.sol';
import './libraries/Math.sol';
import './interfaces/IERC20.sol';
import './interfaces/ITwapFactory.sol';
import './interfaces/ITwapOracle.sol';
contract TwapPair is Reserves, TwapLPToken, ITwapPair {
using SafeMath for uint256;
uint256 private constant PRECISION = 10**18;
uint256 public override mintFee = 0;
uint256 public override burnFee = 0;
uint256 public override swapFee = 0;
uint256 public constant override MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public immutable override factory;
address public override token0;
address public override token1;
address public override oracle;
address public override trader;
uint256 private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'TP06');
unlocked = 0;
_;
unlocked = 1;
}
function isContract(address addr) private view returns (bool) {
uint256 size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
function setMintFee(uint256 fee) external override {
require(msg.sender == factory, 'TP00');
require(fee != mintFee, 'TP01');
mintFee = fee;
emit SetMintFee(fee);
}
function setBurnFee(uint256 fee) external override {
require(msg.sender == factory, 'TP00');
require(fee != burnFee, 'TP01');
burnFee = fee;
emit SetBurnFee(fee);
}
function setSwapFee(uint256 fee) external override {
require(msg.sender == factory, 'TP00');
require(fee != swapFee, 'TP01');
swapFee = fee;
emit SetSwapFee(fee);
}
function setOracle(address _oracle) external override {
require(msg.sender == factory, 'TP00');
require(_oracle != oracle, 'TP01');
require(_oracle != address(0), 'TP02');
require(isContract(_oracle), 'TP1D');
oracle = _oracle;
emit SetOracle(_oracle);
}
function setTrader(address _trader) external override {
require(msg.sender == factory, 'TP00');
require(_trader != trader, 'TP01');
// Allow trader to be set as address(0) to disable interaction
trader = _trader;
emit SetTrader(_trader);
}
function collect(address to) external override lock {
require(msg.sender == factory, 'TP00');
require(to != address(0), 'TP02');
(uint256 fee0, uint256 fee1) = getFees();
if (fee0 > 0) _safeTransfer(token0, to, fee0);
if (fee1 > 0) _safeTransfer(token1, to, fee1);
setFees(0, 0);
_sync();
}
function _safeTransfer(
address token,
address to,
uint256 value
) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TP05');
}
function canTrade(address user) private view returns (bool) {
return user == trader || user == factory;
}
constructor() {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(
address _token0,
address _token1,
address _oracle,
address _trader
) external override {
require(msg.sender == factory, 'TP00');
require(_oracle != address(0), 'TP02');
require(isContract(_oracle), 'TP1D');
require(isContract(_token0) && isContract(_token1), 'TP10');
token0 = _token0;
token1 = _token1;
oracle = _oracle;
trader = _trader;
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external override lock returns (uint256 liquidityOut) {
require(canTrade(msg.sender), 'TP0C');
require(to != address(0), 'TP02');
(uint112 reserve0, uint112 reserve1) = getReserves();
(uint256 balance0, uint256 balance1) = getBalances(token0, token1);
uint256 amount0In = balance0.sub(reserve0);
uint256 amount1In = balance1.sub(reserve1);
uint256 _totalSupply = totalSupply; // gas savings
if (_totalSupply == 0) {
liquidityOut = Math.sqrt(amount0In.mul(amount1In)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidityOut = Math.min(amount0In.mul(_totalSupply) / reserve0, amount1In.mul(_totalSupply) / reserve1);
}
require(liquidityOut > 0, 'TP38');
if (mintFee > 0) {
uint256 fee = liquidityOut.mul(mintFee).div(PRECISION);
liquidityOut = liquidityOut.sub(fee);
_mint(factory, fee);
}
_mint(to, liquidityOut);
setReserves(balance0, balance1);
emit Mint(msg.sender, amount0In, amount1In, liquidityOut, to);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external override lock returns (uint256 amount0Out, uint256 amount1Out) {
require(canTrade(msg.sender), 'TP0C');
require(to != address(0), 'TP02');
uint256 _totalSupply = totalSupply; // gas savings
require(_totalSupply > 0, 'TP36');
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
(uint256 balance0, uint256 balance1) = getBalances(token0, token1);
uint256 liquidityIn = balanceOf[address(this)];
if (msg.sender != factory && burnFee > 0) {
uint256 fee = liquidityIn.mul(burnFee).div(PRECISION);
liquidityIn = liquidityIn.sub(fee);
_transfer(address(this), factory, fee);
}
_burn(address(this), liquidityIn);
amount0Out = liquidityIn.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1Out = liquidityIn.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0Out > 0 && amount1Out > 0, 'TP39');
_safeTransfer(_token0, to, amount0Out);
_safeTransfer(_token1, to, amount1Out);
(balance0, balance1) = getBalances(token0, token1);
setReserves(balance0, balance1);
emit Burn(msg.sender, amount0Out, amount1Out, liquidityIn, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external override lock {
require(canTrade(msg.sender), 'TP0C');
require(to != address(0), 'TP02');
require((amount0Out > 0 && amount1Out == 0) || (amount1Out > 0 && amount0Out == 0), 'TP31');
(uint112 _reserve0, uint112 _reserve1) = getReserves();
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'TP07');
{
// scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'TP2D');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
}
(uint256 balance0, uint256 balance1) = getBalances(token0, token1);
if (amount0Out > 0) {
// trading token1 for token0
require(balance1 > _reserve1, 'TP08');
uint256 amount1In = balance1 - _reserve1;
emit Swap(msg.sender, 0, amount1In, amount0Out, 0, to);
uint256 fee1 = amount1In.mul(swapFee).div(PRECISION);
uint256 balance1After = balance1.sub(fee1);
uint256 balance0After = ITwapOracle(oracle).tradeY(balance1After, _reserve0, _reserve1, data);
require(balance0 >= balance0After, 'TP2E');
uint256 fee0 = balance0.sub(balance0After);
addFees(fee0, fee1);
setReserves(balance0After, balance1After);
} else {
// trading token0 for token1
require(balance0 > _reserve0, 'TP08');
uint256 amount0In = balance0 - _reserve0;
emit Swap(msg.sender, amount0In, 0, 0, amount1Out, to);
uint256 fee0 = amount0In.mul(swapFee).div(PRECISION);
uint256 balance0After = balance0.sub(fee0);
uint256 balance1After = ITwapOracle(oracle).tradeX(balance0After, _reserve0, _reserve1, data);
require(balance1 >= balance1After, 'TP2E');
uint256 fee1 = balance1.sub(balance1After);
addFees(fee0, fee1);
setReserves(balance0After, balance1After);
}
}
function sync() external override lock {
require(canTrade(msg.sender), 'TP0C');
_sync();
}
// force reserves to match balances
function _sync() internal {
syncReserves(token0, token1);
uint256 tokens = balanceOf[address(this)];
if (tokens > 0) {
_transfer(address(this), factory, tokens);
}
}
function getSwapAmount0In(uint256 amount1Out, bytes calldata data)
public
view
override
returns (uint256 swapAmount0In)
{
(uint112 reserve0, uint112 reserve1) = getReserves();
uint256 balance1After = uint256(reserve1).sub(amount1Out);
uint256 balance0After = ITwapOracle(oracle).tradeY(balance1After, reserve0, reserve1, data);
return balance0After.sub(uint256(reserve0)).mul(PRECISION).ceil_div(PRECISION.sub(swapFee));
}
function getSwapAmount1In(uint256 amount0Out, bytes calldata data)
public
view
override
returns (uint256 swapAmount1In)
{
(uint112 reserve0, uint112 reserve1) = getReserves();
uint256 balance0After = uint256(reserve0).sub(amount0Out);
uint256 balance1After = ITwapOracle(oracle).tradeX(balance0After, reserve0, reserve1, data);
return balance1After.add(1).sub(uint256(reserve1)).mul(PRECISION).ceil_div(PRECISION.sub(swapFee));
}
function getSwapAmount0Out(uint256 amount1In, bytes calldata data)
public
view
override
returns (uint256 swapAmount0Out)
{
(uint112 reserve0, uint112 reserve1) = getReserves();
uint256 fee = amount1In.mul(swapFee).div(PRECISION);
uint256 balance0After = ITwapOracle(oracle).tradeY(
uint256(reserve1).add(amount1In).sub(fee),
reserve0,
reserve1,
data
);
return uint256(reserve0).sub(balance0After);
}
function getSwapAmount1Out(uint256 amount0In, bytes calldata data)
public
view
override
returns (uint256 swapAmount1Out)
{
(uint112 reserve0, uint112 reserve1) = getReserves();
uint256 fee = amount0In.mul(swapFee).div(PRECISION);
uint256 balance1After = ITwapOracle(oracle).tradeX(
uint256(reserve0).add(amount0In).sub(fee),
reserve0,
reserve1,
data
);
return uint256(reserve1).sub(balance1After);
}
function getDepositAmount0In(uint256 amount0, bytes calldata data) external view override returns (uint256) {
(uint112 reserve0, uint112 reserve1) = getReserves();
return ITwapOracle(oracle).depositTradeXIn(amount0, reserve0, reserve1, data);
}
function getDepositAmount1In(uint256 amount1, bytes calldata data) external view override returns (uint256) {
(uint112 reserve0, uint112 reserve1) = getReserves();
return ITwapOracle(oracle).depositTradeYIn(amount1, reserve0, reserve1, data);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import './ITwapERC20.sol';
import './IReserves.sol';
interface ITwapPair is ITwapERC20, IReserves {
event Mint(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 liquidityOut, address indexed to);
event Burn(address indexed sender, uint256 amount0Out, uint256 amount1Out, uint256 liquidityIn, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event SetMintFee(uint256 fee);
event SetBurnFee(uint256 fee);
event SetSwapFee(uint256 fee);
event SetOracle(address account);
event SetTrader(address trader);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function oracle() external view returns (address);
function trader() external view returns (address);
function mintFee() external view returns (uint256);
function setMintFee(uint256 fee) external;
function mint(address to) external returns (uint256 liquidity);
function burnFee() external view returns (uint256);
function setBurnFee(uint256 fee) external;
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swapFee() external view returns (uint256);
function setSwapFee(uint256 fee) external;
function setOracle(address account) external;
function setTrader(address account) external;
function collect(address to) external;
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function sync() external;
function initialize(
address _token0,
address _token1,
address _oracle,
address _trader
) external;
function getSwapAmount0In(uint256 amount1Out, bytes calldata data) external view returns (uint256 swapAmount0In);
function getSwapAmount1In(uint256 amount0Out, bytes calldata data) external view returns (uint256 swapAmount1In);
function getSwapAmount0Out(uint256 amount1In, bytes calldata data) external view returns (uint256 swapAmount0Out);
function getSwapAmount1Out(uint256 amount0In, bytes calldata data) external view returns (uint256 swapAmount1Out);
function getDepositAmount0In(uint256 amount0, bytes calldata data) external view returns (uint256 depositAmount0In);
function getDepositAmount1In(uint256 amount1, bytes calldata data) external view returns (uint256 depositAmount1In);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import '../interfaces/IReserves.sol';
import '../interfaces/IERC20.sol';
import '../libraries/SafeMath.sol';
contract Reserves is IReserves {
using SafeMath for uint256;
uint112 private reserve0;
uint112 private reserve1;
uint112 private fee0;
uint112 private fee1;
function getReserves() public view override returns (uint112, uint112) {
return (reserve0, reserve1);
}
function setReserves(uint256 balance0MinusFee, uint256 balance1MinusFee) internal {
require(balance0MinusFee != 0 && balance1MinusFee != 0, 'RS09');
reserve0 = balance0MinusFee.toUint112();
reserve1 = balance1MinusFee.toUint112();
}
function syncReserves(address token0, address token1) internal {
uint256 balance0 = IERC20(token0).balanceOf(address(this));
uint256 balance1 = IERC20(token1).balanceOf(address(this));
uint256 oldBalance0 = uint256(reserve0) + fee0;
uint256 oldBalance1 = uint256(reserve1) + fee1;
if (balance0 != oldBalance0 || balance1 != oldBalance1) {
if (oldBalance0 != 0) {
fee0 = (balance0.mul(fee0).div(oldBalance0)).toUint112();
}
if (oldBalance1 != 0) {
fee1 = (balance1.mul(fee1).div(oldBalance1)).toUint112();
}
setReserves(balance0.sub(fee0), balance1.sub(fee1));
}
}
function getFees() public view override returns (uint256, uint256) {
return (fee0, fee1);
}
function addFees(uint256 _fee0, uint256 _fee1) internal {
setFees(_fee0.add(fee0), _fee1.add(fee1));
}
function setFees(uint256 _fee0, uint256 _fee1) internal {
fee0 = _fee0.toUint112();
fee1 = _fee1.toUint112();
}
function getBalances(address token0, address token1) internal returns (uint256, uint256) {
uint256 balance0 = IERC20(token0).balanceOf(address(this));
uint256 balance1 = IERC20(token1).balanceOf(address(this));
if (fee0 > balance0) {
fee0 = uint112(balance0);
}
if (fee1 > balance1) {
fee1 = uint112(balance1);
}
return (balance0.sub(fee0), balance1.sub(fee1));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import './libraries/AbstractERC20.sol';
contract TwapLPToken is AbstractERC20 {
constructor() {
name = 'Twap LP';
symbol = 'TWAP-LP';
decimals = 18;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
// a library for performing various math operations
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x > y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
interface ITwapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
event OwnerSet(address owner);
function owner() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(
address tokenA,
address tokenB,
address oracle,
address trader
) external returns (address pair);
function setOwner(address) external;
function setMintFee(
address tokenA,
address tokenB,
uint256 fee
) external;
function setBurnFee(
address tokenA,
address tokenB,
uint256 fee
) external;
function setSwapFee(
address tokenA,
address tokenB,
uint256 fee
) external;
function setOracle(
address tokenA,
address tokenB,
address oracle
) external;
function setTrader(
address tokenA,
address tokenB,
address trader
) external;
function collect(
address tokenA,
address tokenB,
address to
) external;
function withdraw(
address tokenA,
address tokenB,
uint256 amount,
address to
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
interface ITwapOracle {
event OwnerSet(address owner);
event UniswapPairSet(address uniswapPair);
function decimalsConverter() external view returns (int256);
function xDecimals() external view returns (uint8);
function yDecimals() external view returns (uint8);
function owner() external view returns (address);
function uniswapPair() external view returns (address);
function getPriceInfo() external view returns (uint256 priceAccumulator, uint32 priceTimestamp);
function getSpotPrice() external view returns (uint256);
function getAveragePrice(uint256 priceAccumulator, uint32 priceTimestamp) external view returns (uint256);
function setOwner(address _owner) external;
function setUniswapPair(address _uniswapPair) external;
function tradeX(
uint256 xAfter,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 yAfter);
function tradeY(
uint256 yAfter,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 xAfter);
function depositTradeXIn(
uint256 xLeft,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 xIn);
function depositTradeYIn(
uint256 yLeft,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 yIn);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import './IERC20.sol';
interface ITwapERC20 is IERC20 {
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
interface IReserves {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1);
function getFees() external view returns (uint256 fee0, uint256 fee1);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
int256 private constant _INT256_MIN = -2**255;
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'SM4E');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = sub(x, y, 'SM12');
}
function sub(
uint256 x,
uint256 y,
string memory message
) internal pure returns (uint256 z) {
require((z = x - y) <= x, message);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'SM2A');
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SM43');
uint256 c = a / b;
return c;
}
function ceil_div(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = div(a, b);
if (c == mul(a, b)) {
return c;
} else {
return add(c, 1);
}
}
function toUint32(uint256 n) internal pure returns (uint32) {
require(n <= type(uint32).max, 'SM50');
return uint32(n);
}
function toUint112(uint256 n) internal pure returns (uint112) {
require(n <= type(uint112).max, 'SM51');
return uint112(n);
}
function toInt256(uint256 unsigned) internal pure returns (int256 signed) {
require(unsigned <= uint256(type(int256).max), 'SM34');
signed = int256(unsigned);
}
// int256
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), 'SM4D');
return c;
}
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), 'SM11');
return c;
}
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), 'SM29');
int256 c = a * b;
require(c / a == b, 'SM29');
return c;
}
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, 'SM43');
require(!(b == -1 && a == _INT256_MIN), 'SM42');
int256 c = a / b;
return c;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import '../interfaces/ITwapERC20.sol';
import './SafeMath.sol';
abstract contract AbstractERC20 is ITwapERC20 {
using SafeMath for uint256;
string public override name;
string public override symbol;
uint8 public override decimals;
uint256 public override totalSupply;
mapping(address => uint256) public override balanceOf;
mapping(address => mapping(address => uint256)) public override allowance;
bytes32 public constant DOMAIN_TYPEHASH =
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)');
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant override PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public override nonces;
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(
address owner,
address spender,
uint256 value
) internal {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(
address from,
address to,
uint256 value
) internal {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value) external override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external override returns (bool) {
_approve(msg.sender, spender, allowance[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external override returns (bool) {
uint256 currentAllowance = allowance[msg.sender][spender];
require(currentAllowance >= subtractedValue, 'TA48');
_approve(msg.sender, spender, currentAllowance.sub(subtractedValue));
return true;
}
function transfer(address to, uint256 value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external override returns (bool) {
if (allowance[from][msg.sender] != uint256(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(deadline >= block.timestamp, 'TA04');
bytes32 digest = keccak256(
abi.encodePacked(
'\\x19\\x01',
getDomainSeparator(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'TA2F');
_approve(owner, spender, value);
}
function getDomainSeparator() public view returns (bytes32) {
uint256 chainId;
assembly {
chainId := chainid()
}
return
keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this))
);
}
}
File 3 of 11: WETH9
// Copyright (C) 2015, 2016, 2017 Dapphub
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.4.18;
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
function() public payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return this.balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
Transfer(src, dst, wad);
return true;
}
}
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/File 4 of 11: Proxy
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
pragma abicoder v2;
contract Proxy {
// EIP1967
// bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)
bytes32 private constant adminPosition = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
// EIP1967
// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
bytes32 private constant implementationPosition =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
// EIP1967
event AdminChanged(address previousAdmin, address newAdmin);
event Upgraded(address indexed implementation);
constructor(address _implementation) {
_setAdmin(address(0), msg.sender);
setImplementation(_implementation);
}
function implementation() public view returns (address _implementation) {
assembly {
_implementation := sload(implementationPosition)
}
}
function setImplementation(address _implementation) public {
require(msg.sender == admin(), 'PX00');
require(_implementation != implementation(), 'PX01');
require(_implementation != address(0), 'PX02');
assembly {
sstore(implementationPosition, _implementation)
}
emit Upgraded(_implementation);
}
function admin() public view returns (address _admin) {
assembly {
_admin := sload(adminPosition)
}
}
function setAdmin(address _admin) external {
address currentAdmin = admin();
require(msg.sender == currentAdmin, 'PX00');
require(_admin != currentAdmin, 'PX01');
require(_admin != address(0), 'PX02');
_setAdmin(currentAdmin, _admin);
}
function _setAdmin(address currentAdmin, address newAdmin) internal {
assembly {
sstore(adminPosition, newAdmin)
}
emit AdminChanged(currentAdmin, newAdmin);
}
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal {
address _implementation = implementation();
assembly {
// Copy msg.data.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
let result := delegatecall(gas(), _implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
fallback() external payable {
_fallback();
}
receive() external payable {
_fallback();
}
}
File 5 of 11: WBTC
pragma solidity 0.4.24;
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol
/**
* @title DetailedERC20 token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
hasMintPermission
canMint
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/PausableToken.sol
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// File: openzeppelin-solidity/contracts/ownership/Claimable.sol
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol
/**
* @title Contracts that should be able to recover tokens
* @author SylTi
* @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.
* This will prevent any accidental loss of tokens.
*/
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param _token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic _token) external onlyOwner {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(owner, balance);
}
}
// File: contracts/utils/OwnableContract.sol
// empty block is used as this contract just inherits others.
contract OwnableContract is CanReclaimToken, Claimable { } /* solhint-disable-line no-empty-blocks */
// File: contracts/token/WBTC.sol
contract WBTC is StandardToken, DetailedERC20("Wrapped BTC", "WBTC", 8),
MintableToken, BurnableToken, PausableToken, OwnableContract {
function burn(uint value) public onlyOwner {
super.burn(value);
}
function finishMinting() public onlyOwner returns (bool) {
return false;
}
function renounceOwnership() public onlyOwner {
revert("renouncing ownership is blocked");
}
}File 6 of 11: Orders
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IReserves {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1);
function getFees() external view returns (uint256 fee0, uint256 fee1);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './IERC20.sol';
interface ITwapERC20 is IERC20 {
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface ITwapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
event OwnerSet(address owner);
function owner() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB, address oracle, address trader) external returns (address pair);
function setOwner(address) external;
function setMintFee(address tokenA, address tokenB, uint256 fee) external;
function setBurnFee(address tokenA, address tokenB, uint256 fee) external;
function setSwapFee(address tokenA, address tokenB, uint256 fee) external;
function setOracle(address tokenA, address tokenB, address oracle) external;
function setTrader(address tokenA, address tokenB, address trader) external;
function collect(address tokenA, address tokenB, address to) external;
function withdraw(address tokenA, address tokenB, uint256 amount, address to) external;
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface ITwapOracle {
event OwnerSet(address owner);
event UniswapPairSet(address uniswapPair);
function decimalsConverter() external view returns (int256);
function xDecimals() external view returns (uint8);
function yDecimals() external view returns (uint8);
function owner() external view returns (address);
function uniswapPair() external view returns (address);
function getPriceInfo() external view returns (uint256 priceAccumulator, uint256 priceTimestamp);
function getSpotPrice() external view returns (uint256);
function getAveragePrice(uint256 priceAccumulator, uint256 priceTimestamp) external view returns (uint256);
function setOwner(address _owner) external;
function setUniswapPair(address _uniswapPair) external;
function tradeX(
uint256 xAfter,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 yAfter);
function tradeY(
uint256 yAfter,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 xAfter);
function depositTradeXIn(
uint256 xLeft,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 xIn);
function depositTradeYIn(
uint256 yLeft,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 yIn);
function getSwapAmount0Out(
uint256 swapFee,
uint256 amount1In,
bytes calldata data
) external view returns (uint256 amount0Out);
function getSwapAmount1Out(
uint256 swapFee,
uint256 amount0In,
bytes calldata data
) external view returns (uint256 amount1Out);
function getSwapAmountInMaxOut(
bool inverse,
uint256 swapFee,
uint256 _amountOut,
bytes calldata data
) external view returns (uint256 amountIn, uint256 amountOut);
function getSwapAmountInMinOut(
bool inverse,
uint256 swapFee,
uint256 _amountOut,
bytes calldata data
) external view returns (uint256 amountIn, uint256 amountOut);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './ITwapERC20.sol';
import './IReserves.sol';
interface ITwapPair is ITwapERC20, IReserves {
event Mint(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 liquidityOut, address indexed to);
event Burn(address indexed sender, uint256 amount0Out, uint256 amount1Out, uint256 liquidityIn, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event SetMintFee(uint256 fee);
event SetBurnFee(uint256 fee);
event SetSwapFee(uint256 fee);
event SetOracle(address account);
event SetTrader(address trader);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function oracle() external view returns (address);
function trader() external view returns (address);
function mintFee() external view returns (uint256);
function setMintFee(uint256 fee) external;
function mint(address to) external returns (uint256 liquidity);
function burnFee() external view returns (uint256);
function setBurnFee(uint256 fee) external;
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swapFee() external view returns (uint256);
function setSwapFee(uint256 fee) external;
function setOracle(address account) external;
function setTrader(address account) external;
function collect(address to) external;
function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
function sync() external;
function initialize(address _token0, address _token1, address _oracle, address _trader) external;
function getSwapAmount0In(uint256 amount1Out, bytes calldata data) external view returns (uint256 swapAmount0In);
function getSwapAmount1In(uint256 amount0Out, bytes calldata data) external view returns (uint256 swapAmount1In);
function getSwapAmount0Out(uint256 amount1In, bytes calldata data) external view returns (uint256 swapAmount0Out);
function getSwapAmount1Out(uint256 amount0In, bytes calldata data) external view returns (uint256 swapAmount1Out);
function getDepositAmount0In(uint256 amount0, bytes calldata data) external view returns (uint256 depositAmount0In);
function getDepositAmount1In(uint256 amount1, bytes calldata data) external view returns (uint256 depositAmount1In);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// a library for performing various math operations
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x > y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './SafeMath.sol';
import '../libraries/Math.sol';
import '../interfaces/ITwapFactory.sol';
import '../interfaces/ITwapPair.sol';
import '../interfaces/ITwapOracle.sol';
import '../libraries/TokenShares.sol';
library Orders {
using SafeMath for uint256;
using TokenShares for TokenShares.Data;
using TransferHelper for address;
enum OrderType {
Empty,
Deposit,
Withdraw,
Sell,
Buy
}
enum OrderStatus {
NonExistent,
EnqueuedWaiting,
EnqueuedReady,
ExecutedSucceeded,
ExecutedFailed,
Canceled
}
event DepositEnqueued(uint256 indexed orderId, Order order);
event WithdrawEnqueued(uint256 indexed orderId, Order order);
event SellEnqueued(uint256 indexed orderId, Order order);
event BuyEnqueued(uint256 indexed orderId, Order order);
event OrderTypesDisabled(address pair, Orders.OrderType[] orderTypes, bool disabled);
event RefundFailed(address indexed to, address indexed token, uint256 amount, bytes data);
// Note on gas estimation for the full order execution in the UI:
// Add (*_ORDER_BASE_COST + token transfer costs) to the actual gas usage
// of the TwapDelay._execute* functions when updating gas cost in the UI.
// Remember that ETH unwrap is part of those functions. It is optional,
// but also needs to be included in the estimate.
uint256 public constant ETHER_TRANSFER_COST = ETHER_TRANSFER_CALL_COST + 2600 + 1504; // Std cost + EIP-2929 acct access cost + Gnosis Safe receive ETH cost
uint256 private constant BOT_ETHER_TRANSFER_COST = 10_000;
uint256 private constant BUFFER_COST = 10_000;
uint256 private constant ORDER_EXECUTED_EVENT_COST = 3700;
uint256 private constant EXECUTE_PREPARATION_COST = 30_000; // dequeue + gas calculation before calls to _execute* functions
uint256 public constant ETHER_TRANSFER_CALL_COST = 10_000;
uint256 public constant PAIR_TRANSFER_COST = 55_000;
uint256 public constant REFUND_BASE_COST =
BOT_ETHER_TRANSFER_COST + ETHER_TRANSFER_COST + BUFFER_COST + ORDER_EXECUTED_EVENT_COST;
uint256 private constant ORDER_BASE_COST = EXECUTE_PREPARATION_COST + REFUND_BASE_COST;
uint256 public constant TOKEN_REFUND_BASE_COST = 20_000; // cost of performing token refund logic (excluding token transfer)
uint256 public constant DEPOSIT_ORDER_BASE_COST = ORDER_BASE_COST + 2 * TOKEN_REFUND_BASE_COST;
uint256 public constant WITHDRAW_ORDER_BASE_COST = ORDER_BASE_COST;
uint256 public constant SELL_ORDER_BASE_COST = ORDER_BASE_COST + TOKEN_REFUND_BASE_COST;
uint256 public constant BUY_ORDER_BASE_COST = ORDER_BASE_COST + TOKEN_REFUND_BASE_COST;
// Masks used for setting order disabled
// Different bits represent different order types
uint8 private constant DEPOSIT_MASK = uint8(1 << uint8(OrderType.Deposit)); // 00000010
uint8 private constant WITHDRAW_MASK = uint8(1 << uint8(OrderType.Withdraw)); // 00000100
uint8 private constant SELL_MASK = uint8(1 << uint8(OrderType.Sell)); // 00001000
uint8 private constant BUY_MASK = uint8(1 << uint8(OrderType.Buy)); // 00010000
address public constant FACTORY_ADDRESS = 0xC480b33eE5229DE3FbDFAD1D2DCD3F3BAD0C56c6;
uint256 public constant MAX_GAS_LIMIT = 5000000;
uint256 public constant GAS_PRICE_INERTIA = 20000000;
uint256 public constant MAX_GAS_PRICE_IMPACT = 1000000;
uint256 public constant DELAY = 1800;
address public constant NATIVE_CURRENCY_SENTINEL = address(0); // A sentinel value for the native currency to distinguish it from ERC20 tokens
struct Data {
uint256 newestOrderId;
uint256 lastProcessedOrderId;
mapping(uint256 => bytes32) orderQueue;
uint256 gasPrice;
mapping(uint256 => bool) canceled;
// Bit on specific positions indicates whether order type is disabled (1) or enabled (0) on specific pair
mapping(address => uint8) orderTypesDisabled;
mapping(uint256 => bool) refundFailed;
}
struct Order {
uint256 orderId;
OrderType orderType;
bool inverted;
uint256 validAfterTimestamp;
bool unwrap;
uint256 timestamp;
uint256 gasLimit;
uint256 gasPrice;
uint256 liquidity;
uint256 value0; // Deposit: share0, Withdraw: amount0Min, Sell: shareIn, Buy: shareInMax
uint256 value1; // Deposit: share1, Withdraw: amount1Min, Sell: amountOutMin, Buy: amountOut
address token0; // Sell: tokenIn, Buy: tokenIn
address token1; // Sell: tokenOut, Buy: tokenOut
address to;
uint256 minSwapPrice;
uint256 maxSwapPrice;
bool swap;
uint256 priceAccumulator;
uint256 amountLimit0;
uint256 amountLimit1;
}
function getOrderStatus(
Data storage data,
uint256 orderId,
uint256 validAfterTimestamp
) internal view returns (OrderStatus) {
if (orderId > data.newestOrderId) {
return OrderStatus.NonExistent;
}
if (data.canceled[orderId]) {
return OrderStatus.Canceled;
}
if (data.refundFailed[orderId]) {
return OrderStatus.ExecutedFailed;
}
if (data.orderQueue[orderId] == bytes32(0)) {
return OrderStatus.ExecutedSucceeded;
}
if (validAfterTimestamp >= block.timestamp) {
return OrderStatus.EnqueuedWaiting;
}
return OrderStatus.EnqueuedReady;
}
function getPair(address tokenA, address tokenB) internal view returns (address pair, bool inverted) {
pair = ITwapFactory(FACTORY_ADDRESS).getPair(tokenA, tokenB);
require(pair != address(0), 'OS17');
inverted = tokenA > tokenB;
}
function getDepositDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & DEPOSIT_MASK != 0;
}
function getWithdrawDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & WITHDRAW_MASK != 0;
}
function getSellDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & SELL_MASK != 0;
}
function getBuyDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & BUY_MASK != 0;
}
function setOrderTypesDisabled(
Data storage data,
address pair,
Orders.OrderType[] calldata orderTypes,
bool disabled
) external {
uint256 orderTypesLength = orderTypes.length;
uint8 currentSettings = data.orderTypesDisabled[pair];
uint8 combinedMask;
for (uint256 i; i < orderTypesLength; ++i) {
Orders.OrderType orderType = orderTypes[i];
require(orderType != Orders.OrderType.Empty, 'OS32');
// zeros with 1 bit set at position specified by orderType
// e.g. for SELL order type
// mask for SELL = 00001000
// combinedMask = 00000110 (DEPOSIT and WITHDRAW masks set in previous iterations)
// the result of OR = 00001110 (DEPOSIT, WITHDRAW and SELL combined mask)
combinedMask = combinedMask | uint8(1 << uint8(orderType));
}
// set/unset a bit accordingly to 'disabled' value
if (disabled) {
// OR operation to disable order
// e.g. for disable DEPOSIT
// currentSettings = 00010100 (BUY and WITHDRAW disabled)
// mask for DEPOSIT = 00000010
// the result of OR = 00010110
currentSettings = currentSettings | combinedMask;
} else {
// AND operation with a mask negation to enable order
// e.g. for enable DEPOSIT
// currentSettings = 00010100 (BUY and WITHDRAW disabled)
// 0xff = 11111111
// mask for Deposit = 00000010
// mask negation = 11111101
// the result of AND = 00010100
currentSettings = currentSettings & (combinedMask ^ 0xff);
}
require(currentSettings != data.orderTypesDisabled[pair], 'OS01');
data.orderTypesDisabled[pair] = currentSettings;
emit OrderTypesDisabled(pair, orderTypes, disabled);
}
function markRefundFailed(Data storage data) internal {
data.refundFailed[data.lastProcessedOrderId] = true;
}
/// @dev The passed in order.oderId is ignored and overwritten with the correct value, i.e. an updated data.newestOrderId.
/// This is done to ensure atomicity of these two actions while optimizing gas usage - adding an order to the queue and incrementing
/// data.newestOrderId (which should not be done anywhere else in the contract).
/// Must only be called on verified orders.
function enqueueOrder(Data storage data, Order memory order) internal {
order.orderId = ++data.newestOrderId;
data.orderQueue[order.orderId] = getOrderDigest(order);
}
struct DepositParams {
address token0;
address token1;
uint256 amount0;
uint256 amount1;
uint256 minSwapPrice;
uint256 maxSwapPrice;
bool wrap;
bool swap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function deposit(
Data storage data,
DepositParams calldata depositParams,
TokenShares.Data storage tokenShares
) external {
checkOrderParams(
depositParams.to,
depositParams.gasLimit,
depositParams.submitDeadline,
DEPOSIT_ORDER_BASE_COST +
getTransferGasCost(depositParams.token0) +
getTransferGasCost(depositParams.token1)
);
require(depositParams.amount0 != 0 || depositParams.amount1 != 0, 'OS25');
(address pairAddress, bool inverted) = getPair(depositParams.token0, depositParams.token1);
require(!getDepositDisabled(data, pairAddress), 'OS46');
{
// scope for value, avoids stack too deep errors
uint256 value = msg.value;
// allocate gas refund
if (depositParams.wrap) {
if (depositParams.token0 == TokenShares.WETH_ADDRESS) {
value = msg.value.sub(depositParams.amount0, 'OS1E');
} else if (depositParams.token1 == TokenShares.WETH_ADDRESS) {
value = msg.value.sub(depositParams.amount1, 'OS1E');
}
}
allocateGasRefund(data, value, depositParams.gasLimit);
}
uint256 shares0 = tokenShares.amountToShares(
inverted ? depositParams.token1 : depositParams.token0,
inverted ? depositParams.amount1 : depositParams.amount0,
depositParams.wrap
);
uint256 shares1 = tokenShares.amountToShares(
inverted ? depositParams.token0 : depositParams.token1,
inverted ? depositParams.amount0 : depositParams.amount1,
depositParams.wrap
);
(uint256 priceAccumulator, uint256 timestamp) = ITwapOracle(ITwapPair(pairAddress).oracle()).getPriceInfo();
Order memory order = Order(
0,
OrderType.Deposit,
inverted,
timestamp + DELAY, // validAfterTimestamp
depositParams.wrap,
timestamp,
depositParams.gasLimit,
data.gasPrice,
0, // liquidity
shares0,
shares1,
inverted ? depositParams.token1 : depositParams.token0,
inverted ? depositParams.token0 : depositParams.token1,
depositParams.to,
depositParams.minSwapPrice,
depositParams.maxSwapPrice,
depositParams.swap,
priceAccumulator,
inverted ? depositParams.amount1 : depositParams.amount0,
inverted ? depositParams.amount0 : depositParams.amount1
);
enqueueOrder(data, order);
emit DepositEnqueued(order.orderId, order);
}
struct WithdrawParams {
address token0;
address token1;
uint256 liquidity;
uint256 amount0Min;
uint256 amount1Min;
bool unwrap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function withdraw(Data storage data, WithdrawParams calldata withdrawParams) external {
(address pair, bool inverted) = getPair(withdrawParams.token0, withdrawParams.token1);
require(!getWithdrawDisabled(data, pair), 'OS0A');
checkOrderParams(
withdrawParams.to,
withdrawParams.gasLimit,
withdrawParams.submitDeadline,
WITHDRAW_ORDER_BASE_COST + PAIR_TRANSFER_COST
);
require(withdrawParams.liquidity != 0, 'OS22');
allocateGasRefund(data, msg.value, withdrawParams.gasLimit);
pair.safeTransferFrom(msg.sender, address(this), withdrawParams.liquidity);
Order memory order = Order(
0,
OrderType.Withdraw,
inverted,
block.timestamp + DELAY, // validAfterTimestamp
withdrawParams.unwrap,
0, // timestamp
withdrawParams.gasLimit,
data.gasPrice,
withdrawParams.liquidity,
inverted ? withdrawParams.amount1Min : withdrawParams.amount0Min,
inverted ? withdrawParams.amount0Min : withdrawParams.amount1Min,
inverted ? withdrawParams.token1 : withdrawParams.token0,
inverted ? withdrawParams.token0 : withdrawParams.token1,
withdrawParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
0, // priceAccumulator
0, // amountLimit0
0 // amountLimit1
);
enqueueOrder(data, order);
emit WithdrawEnqueued(order.orderId, order);
}
struct SellParams {
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 amountOutMin;
bool wrapUnwrap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function sell(Data storage data, SellParams calldata sellParams, TokenShares.Data storage tokenShares) external {
checkOrderParams(
sellParams.to,
sellParams.gasLimit,
sellParams.submitDeadline,
SELL_ORDER_BASE_COST + getTransferGasCost(sellParams.tokenIn)
);
(address pairAddress, bool inverted) = sellHelper(data, sellParams);
(uint256 priceAccumulator, uint256 timestamp) = ITwapOracle(ITwapPair(pairAddress).oracle()).getPriceInfo();
uint256 shares = tokenShares.amountToShares(sellParams.tokenIn, sellParams.amountIn, sellParams.wrapUnwrap);
Order memory order = Order(
0,
OrderType.Sell,
inverted,
timestamp + DELAY, // validAfterTimestamp
sellParams.wrapUnwrap,
timestamp,
sellParams.gasLimit,
data.gasPrice,
0, // liquidity
shares,
sellParams.amountOutMin,
sellParams.tokenIn,
sellParams.tokenOut,
sellParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
priceAccumulator,
sellParams.amountIn,
0 // amountLimit1
);
enqueueOrder(data, order);
emit SellEnqueued(order.orderId, order);
}
function relayerSell(
Data storage data,
SellParams calldata sellParams,
TokenShares.Data storage tokenShares
) external {
checkOrderParams(
sellParams.to,
sellParams.gasLimit,
sellParams.submitDeadline,
SELL_ORDER_BASE_COST + getTransferGasCost(sellParams.tokenIn)
);
(, bool inverted) = sellHelper(data, sellParams);
uint256 shares = tokenShares.amountToSharesWithoutTransfer(
sellParams.tokenIn,
sellParams.amountIn,
sellParams.wrapUnwrap
);
Order memory order = Order(
0,
OrderType.Sell,
inverted,
block.timestamp + DELAY, // validAfterTimestamp
false, // Never wrap/unwrap
block.timestamp,
sellParams.gasLimit,
data.gasPrice,
0, // liquidity
shares,
sellParams.amountOutMin,
sellParams.tokenIn,
sellParams.tokenOut,
sellParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
0, // priceAccumulator - oracleV3 pairs don't need priceAccumulator
sellParams.amountIn,
0 // amountLimit1
);
enqueueOrder(data, order);
emit SellEnqueued(order.orderId, order);
}
function sellHelper(
Data storage data,
SellParams calldata sellParams
) internal returns (address pairAddress, bool inverted) {
require(sellParams.amountIn != 0, 'OS24');
(pairAddress, inverted) = getPair(sellParams.tokenIn, sellParams.tokenOut);
require(!getSellDisabled(data, pairAddress), 'OS13');
// allocate gas refund
uint256 value = msg.value;
if (sellParams.wrapUnwrap && sellParams.tokenIn == TokenShares.WETH_ADDRESS) {
value = msg.value.sub(sellParams.amountIn, 'OS1E');
}
allocateGasRefund(data, value, sellParams.gasLimit);
}
struct BuyParams {
address tokenIn;
address tokenOut;
uint256 amountInMax;
uint256 amountOut;
bool wrapUnwrap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function buy(Data storage data, BuyParams calldata buyParams, TokenShares.Data storage tokenShares) external {
checkOrderParams(
buyParams.to,
buyParams.gasLimit,
buyParams.submitDeadline,
BUY_ORDER_BASE_COST + getTransferGasCost(buyParams.tokenIn)
);
require(buyParams.amountOut != 0, 'OS23');
(address pairAddress, bool inverted) = getPair(buyParams.tokenIn, buyParams.tokenOut);
require(!getBuyDisabled(data, pairAddress), 'OS49');
uint256 value = msg.value;
// allocate gas refund
if (buyParams.tokenIn == TokenShares.WETH_ADDRESS && buyParams.wrapUnwrap) {
value = msg.value.sub(buyParams.amountInMax, 'OS1E');
}
allocateGasRefund(data, value, buyParams.gasLimit);
uint256 shares = tokenShares.amountToShares(buyParams.tokenIn, buyParams.amountInMax, buyParams.wrapUnwrap);
(uint256 priceAccumulator, uint256 timestamp) = ITwapOracle(ITwapPair(pairAddress).oracle()).getPriceInfo();
Order memory order = Order(
0,
OrderType.Buy,
inverted,
timestamp + DELAY, // validAfterTimestamp
buyParams.wrapUnwrap,
timestamp,
buyParams.gasLimit,
data.gasPrice,
0, // liquidity
shares,
buyParams.amountOut,
buyParams.tokenIn,
buyParams.tokenOut,
buyParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
priceAccumulator,
buyParams.amountInMax,
0 // amountLimit1
);
enqueueOrder(data, order);
emit BuyEnqueued(order.orderId, order);
}
function checkOrderParams(address to, uint256 gasLimit, uint32 submitDeadline, uint256 minGasLimit) private view {
require(submitDeadline >= block.timestamp, 'OS04');
require(gasLimit <= MAX_GAS_LIMIT, 'OS3E');
require(gasLimit >= minGasLimit, 'OS3D');
require(to != address(0), 'OS26');
}
function allocateGasRefund(Data storage data, uint256 value, uint256 gasLimit) private returns (uint256 futureFee) {
futureFee = data.gasPrice.mul(gasLimit);
require(value >= futureFee, 'OS1E');
if (value > futureFee) {
TransferHelper.safeTransferETH(msg.sender, value - futureFee, getTransferGasCost(NATIVE_CURRENCY_SENTINEL));
}
}
function updateGasPrice(Data storage data, uint256 gasUsed) external {
uint256 scale = Math.min(gasUsed, MAX_GAS_PRICE_IMPACT);
data.gasPrice = data.gasPrice.mul(GAS_PRICE_INERTIA.sub(scale)).add(tx.gasprice.mul(scale)).div(
GAS_PRICE_INERTIA
);
}
function refundLiquidity(address pair, address to, uint256 liquidity, bytes4 selector) internal returns (bool) {
if (liquidity == 0) {
return true;
}
(bool success, bytes memory data) = address(this).call{ gas: PAIR_TRANSFER_COST }(
abi.encodeWithSelector(selector, pair, to, liquidity, false)
);
if (!success) {
emit RefundFailed(to, pair, liquidity, data);
}
return success;
}
function dequeueOrder(Data storage data, uint256 orderId) internal {
++data.lastProcessedOrderId;
require(orderId == data.lastProcessedOrderId, 'OS72');
}
function forgetOrder(Data storage data, uint256 orderId) internal {
delete data.orderQueue[orderId];
}
function forgetLastProcessedOrder(Data storage data) internal {
delete data.orderQueue[data.lastProcessedOrderId];
}
function getOrderDigest(Order memory order) internal pure returns (bytes32) {
// Used to avoid the 'stack too deep' error.
bytes memory partialOrderData = abi.encodePacked(
order.orderId,
order.orderType,
order.inverted,
order.validAfterTimestamp,
order.unwrap,
order.timestamp,
order.gasLimit,
order.gasPrice,
order.liquidity,
order.value0,
order.value1,
order.token0,
order.token1,
order.to
);
return
keccak256(
abi.encodePacked(
partialOrderData,
order.minSwapPrice,
order.maxSwapPrice,
order.swap,
order.priceAccumulator,
order.amountLimit0,
order.amountLimit1
)
);
}
function verifyOrder(Data storage data, Order memory order) external view {
require(getOrderDigest(order) == data.orderQueue[order.orderId], 'OS71');
}
// constant mapping for transferGasCost
/**
* @dev This function should either return a default value != 0 or revert.
*/
function getTransferGasCost(address token) internal pure returns (uint256) {
if (token == NATIVE_CURRENCY_SENTINEL) return ETHER_TRANSFER_CALL_COST;
if (token == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) return 31000;
if (token == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 42000;
if (token == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return 66000;
if (token == 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599) return 34000;
if (token == 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B) return 31000;
if (token == 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2) return 31000;
if (token == 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84) return 68000;
if (token == 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0) return 31000;
if (token == 0xD33526068D116cE69F19A9ee46F0bd304F21A51f) return 31000;
if (token == 0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2) return 40000;
if (token == 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32) return 149000;
if (token == 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2) return 34000;
if (token == 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984) return 37000;
if (token == 0x514910771AF9Ca656af840dff83E8264EcF986CA) return 32000;
if (token == 0x3c3a81e81dc49A522A592e7622A7E711c06bf354) return 34000;
return 60000;
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
int256 private constant _INT256_MIN = -2 ** 255;
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'SM4E');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = sub(x, y, 'SM12');
}
function sub(uint256 x, uint256 y, string memory message) internal pure returns (uint256 z) {
require((z = x - y) <= x, message);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'SM2A');
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SM43');
return a / b;
}
function ceil_div(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = div(a, b);
if (a != mul(b, c)) {
return add(c, 1);
}
}
function toUint32(uint256 n) internal pure returns (uint32) {
require(n <= type(uint32).max, 'SM50');
return uint32(n);
}
function toUint64(uint256 n) internal pure returns (uint64) {
require(n <= type(uint64).max, 'SM54');
return uint64(n);
}
function toUint112(uint256 n) internal pure returns (uint112) {
require(n <= type(uint112).max, 'SM51');
return uint112(n);
}
function toInt256(uint256 unsigned) internal pure returns (int256 signed) {
require(unsigned <= uint256(type(int256).max), 'SM34');
signed = int256(unsigned);
}
// int256
function add(int256 a, int256 b) internal pure returns (int256 c) {
c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), 'SM4D');
}
function sub(int256 a, int256 b) internal pure returns (int256 c) {
c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), 'SM11');
}
function mul(int256 a, int256 b) internal pure returns (int256 c) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), 'SM29');
c = a * b;
require(c / a == b, 'SM29');
}
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, 'SM43');
require(!(b == -1 && a == _INT256_MIN), 'SM42');
return a / b;
}
function neg_floor_div(int256 a, int256 b) internal pure returns (int256 c) {
c = div(a, b);
if ((a < 0 && b > 0) || (a >= 0 && b < 0)) {
if (a != mul(b, c)) {
c = sub(c, 1);
}
}
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import '../interfaces/IERC20.sol';
import '../interfaces/IWETH.sol';
import './SafeMath.sol';
import './TransferHelper.sol';
library TokenShares {
using SafeMath for uint256;
using TransferHelper for address;
uint256 private constant PRECISION = 10 ** 18;
uint256 private constant TOLERANCE = 10 ** 18 + 10 ** 16;
uint256 private constant TOTAL_SHARES_PRECISION = 10 ** 18;
event UnwrapFailed(address to, uint256 amount);
// represents wrapped native currency (WETH or WMATIC)
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
struct Data {
mapping(address => uint256) totalShares;
}
function sharesToAmount(
Data storage data,
address token,
uint256 share,
uint256 amountLimit,
address refundTo
) external returns (uint256) {
if (share == 0) {
return 0;
}
if (token == WETH_ADDRESS || isNonRebasing(token)) {
return share;
}
uint256 totalTokenShares = data.totalShares[token];
require(totalTokenShares >= share, 'TS3A');
uint256 balance = IERC20(token).balanceOf(address(this));
uint256 value = balance.mul(share).div(totalTokenShares);
data.totalShares[token] = totalTokenShares.sub(share);
if (amountLimit > 0) {
uint256 amountLimitWithTolerance = amountLimit.mul(TOLERANCE).div(PRECISION);
if (value > amountLimitWithTolerance) {
TransferHelper.safeTransfer(token, refundTo, value.sub(amountLimitWithTolerance));
return amountLimitWithTolerance;
}
}
return value;
}
function amountToShares(Data storage data, address token, uint256 amount, bool wrap) external returns (uint256) {
if (amount == 0) {
return 0;
}
if (token == WETH_ADDRESS) {
if (wrap) {
require(msg.value >= amount, 'TS03');
IWETH(token).deposit{ value: amount }();
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
return amount;
} else if (isNonRebasing(token)) {
token.safeTransferFrom(msg.sender, address(this), amount);
return amount;
} else {
uint256 balanceBefore = IERC20(token).balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), amount);
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
return amountToSharesHelper(data, token, balanceBefore, balanceAfter);
}
}
function amountToSharesWithoutTransfer(
Data storage data,
address token,
uint256 amount,
bool wrap
) external returns (uint256) {
if (token == WETH_ADDRESS) {
if (wrap) {
// require(msg.value >= amount, 'TS03'); // Duplicate check in TwapRelayer.sell
IWETH(token).deposit{ value: amount }();
}
return amount;
} else if (isNonRebasing(token)) {
return amount;
} else {
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
uint256 balanceBefore = balanceAfter.sub(amount);
return amountToSharesHelper(data, token, balanceBefore, balanceAfter);
}
}
function amountToSharesHelper(
Data storage data,
address token,
uint256 balanceBefore,
uint256 balanceAfter
) internal returns (uint256) {
uint256 totalTokenShares = data.totalShares[token];
require(balanceBefore > 0 || totalTokenShares == 0, 'TS30');
require(balanceAfter > balanceBefore, 'TS2C');
if (balanceBefore > 0) {
if (totalTokenShares == 0) {
totalTokenShares = balanceBefore.mul(TOTAL_SHARES_PRECISION);
}
uint256 newShares = totalTokenShares.mul(balanceAfter).div(balanceBefore);
require(balanceAfter < type(uint256).max.div(newShares), 'TS73'); // to prevent overflow at execution
data.totalShares[token] = newShares;
return newShares - totalTokenShares;
} else {
totalTokenShares = balanceAfter.mul(TOTAL_SHARES_PRECISION);
require(totalTokenShares < type(uint256).max.div(totalTokenShares), 'TS73'); // to prevent overflow at execution
data.totalShares[token] = totalTokenShares;
return totalTokenShares;
}
}
function onUnwrapFailed(address to, uint256 amount) external {
emit UnwrapFailed(to, amount);
IWETH(WETH_ADDRESS).deposit{ value: amount }();
TransferHelper.safeTransfer(WETH_ADDRESS, to, amount);
}
// constant mapping for nonRebasingToken
function isNonRebasing(address token) internal pure returns (bool) {
if (token == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) return true;
if (token == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return true;
if (token == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return true;
if (token == 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599) return true;
if (token == 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B) return true;
if (token == 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2) return true;
if (token == 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0) return true;
if (token == 0xD33526068D116cE69F19A9ee46F0bd304F21A51f) return true;
if (token == 0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2) return true;
if (token == 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32) return true;
if (token == 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2) return true;
if (token == 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984) return true;
if (token == 0x514910771AF9Ca656af840dff83E8264EcF986CA) return true;
if (token == 0x3c3a81e81dc49A522A592e7622A7E711c06bf354) return true;
return false;
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint256 value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH4B');
}
function safeTransfer(address token, address to, uint256 value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH05');
}
function safeTransferFrom(address token, address from, address to, uint256 value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH0E');
}
function safeTransferETH(address to, uint256 value, uint256 gasLimit) internal {
(bool success, ) = to.call{ value: value, gas: gasLimit }('');
require(success, 'TH3F');
}
function transferETH(address to, uint256 value, uint256 gasLimit) internal returns (bool success) {
(success, ) = to.call{ value: value, gas: gasLimit }('');
}
}
File 7 of 11: TwapFactory
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import './interfaces/ITwapFactory.sol';
import './TwapPair.sol';
contract TwapFactory is ITwapFactory {
mapping(address => mapping(address => address)) public override getPair;
address[] public override allPairs;
address public override owner;
constructor() {
owner = msg.sender;
emit OwnerSet(msg.sender);
}
function allPairsLength() external view override returns (uint256) {
return allPairs.length;
}
function createPair(
address tokenA,
address tokenB,
address oracle,
address trader
) external override returns (address pair) {
require(msg.sender == owner, 'TF00');
require(tokenA != tokenB, 'TF3B');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'TF02');
require(getPair[token0][token1] == address(0), 'TF18'); // single check is sufficient
bytes memory bytecode = type(TwapPair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
ITwapPair(pair).initialize(token0, token1, oracle, trader);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setOwner(address _owner) external override {
require(msg.sender == owner, 'TF00');
require(_owner != owner, 'TF01');
require(_owner != address(0), 'TF02');
owner = _owner;
emit OwnerSet(_owner);
}
function setMintFee(
address tokenA,
address tokenB,
uint256 fee
) external override {
require(msg.sender == owner, 'TF00');
_getPair(tokenA, tokenB).setMintFee(fee);
}
function setBurnFee(
address tokenA,
address tokenB,
uint256 fee
) external override {
require(msg.sender == owner, 'TF00');
_getPair(tokenA, tokenB).setBurnFee(fee);
}
function setSwapFee(
address tokenA,
address tokenB,
uint256 fee
) external override {
require(msg.sender == owner, 'TF00');
_getPair(tokenA, tokenB).setSwapFee(fee);
}
function setOracle(
address tokenA,
address tokenB,
address oracle
) external override {
require(msg.sender == owner, 'TF00');
_getPair(tokenA, tokenB).setOracle(oracle);
}
function setTrader(
address tokenA,
address tokenB,
address trader
) external override {
require(msg.sender == owner, 'TF00');
_getPair(tokenA, tokenB).setTrader(trader);
}
function collect(
address tokenA,
address tokenB,
address to
) external override {
require(msg.sender == owner, 'TF00');
_getPair(tokenA, tokenB).collect(to);
}
function withdraw(
address tokenA,
address tokenB,
uint256 amount,
address to
) external override {
require(msg.sender == owner, 'TF00');
ITwapPair pair = _getPair(tokenA, tokenB);
pair.transfer(address(pair), amount);
pair.burn(to);
}
function _getPair(address tokenA, address tokenB) internal view returns (ITwapPair pair) {
pair = ITwapPair(getPair[tokenA][tokenB]);
require(address(pair) != address(0), 'TF19');
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
interface ITwapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
event OwnerSet(address owner);
function owner() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(
address tokenA,
address tokenB,
address oracle,
address trader
) external returns (address pair);
function setOwner(address) external;
function setMintFee(
address tokenA,
address tokenB,
uint256 fee
) external;
function setBurnFee(
address tokenA,
address tokenB,
uint256 fee
) external;
function setSwapFee(
address tokenA,
address tokenB,
uint256 fee
) external;
function setOracle(
address tokenA,
address tokenB,
address oracle
) external;
function setTrader(
address tokenA,
address tokenB,
address trader
) external;
function collect(
address tokenA,
address tokenB,
address to
) external;
function withdraw(
address tokenA,
address tokenB,
uint256 amount,
address to
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import './interfaces/ITwapPair.sol';
import './libraries/Reserves.sol';
import './TwapLPToken.sol';
import './libraries/Math.sol';
import './interfaces/IERC20.sol';
import './interfaces/ITwapFactory.sol';
import './interfaces/ITwapOracle.sol';
contract TwapPair is Reserves, TwapLPToken, ITwapPair {
using SafeMath for uint256;
uint256 private constant PRECISION = 10**18;
uint256 public override mintFee = 0;
uint256 public override burnFee = 0;
uint256 public override swapFee = 0;
uint256 public constant override MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public immutable override factory;
address public override token0;
address public override token1;
address public override oracle;
address public override trader;
uint256 private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'TP06');
unlocked = 0;
_;
unlocked = 1;
}
function isContract(address addr) private view returns (bool) {
uint256 size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
function setMintFee(uint256 fee) external override {
require(msg.sender == factory, 'TP00');
require(fee != mintFee, 'TP01');
mintFee = fee;
emit SetMintFee(fee);
}
function setBurnFee(uint256 fee) external override {
require(msg.sender == factory, 'TP00');
require(fee != burnFee, 'TP01');
burnFee = fee;
emit SetBurnFee(fee);
}
function setSwapFee(uint256 fee) external override {
require(msg.sender == factory, 'TP00');
require(fee != swapFee, 'TP01');
swapFee = fee;
emit SetSwapFee(fee);
}
function setOracle(address _oracle) external override {
require(msg.sender == factory, 'TP00');
require(_oracle != oracle, 'TP01');
require(_oracle != address(0), 'TP02');
require(isContract(_oracle), 'TP1D');
oracle = _oracle;
emit SetOracle(_oracle);
}
function setTrader(address _trader) external override {
require(msg.sender == factory, 'TP00');
require(_trader != trader, 'TP01');
// Allow trader to be set as address(0) to disable interaction
trader = _trader;
emit SetTrader(_trader);
}
function collect(address to) external override lock {
require(msg.sender == factory, 'TP00');
require(to != address(0), 'TP02');
(uint256 fee0, uint256 fee1) = getFees();
if (fee0 > 0) _safeTransfer(token0, to, fee0);
if (fee1 > 0) _safeTransfer(token1, to, fee1);
setFees(0, 0);
_sync();
}
function _safeTransfer(
address token,
address to,
uint256 value
) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TP05');
}
function canTrade(address user) private view returns (bool) {
return user == trader || user == factory;
}
constructor() {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(
address _token0,
address _token1,
address _oracle,
address _trader
) external override {
require(msg.sender == factory, 'TP00');
require(_oracle != address(0), 'TP02');
require(isContract(_oracle), 'TP1D');
require(isContract(_token0) && isContract(_token1), 'TP10');
token0 = _token0;
token1 = _token1;
oracle = _oracle;
trader = _trader;
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external override lock returns (uint256 liquidityOut) {
require(canTrade(msg.sender), 'TP0C');
require(to != address(0), 'TP02');
(uint112 reserve0, uint112 reserve1) = getReserves();
(uint256 balance0, uint256 balance1) = getBalances(token0, token1);
uint256 amount0In = balance0.sub(reserve0);
uint256 amount1In = balance1.sub(reserve1);
uint256 _totalSupply = totalSupply; // gas savings
if (_totalSupply == 0) {
liquidityOut = Math.sqrt(amount0In.mul(amount1In)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidityOut = Math.min(amount0In.mul(_totalSupply) / reserve0, amount1In.mul(_totalSupply) / reserve1);
}
require(liquidityOut > 0, 'TP38');
if (mintFee > 0) {
uint256 fee = liquidityOut.mul(mintFee).div(PRECISION);
liquidityOut = liquidityOut.sub(fee);
_mint(factory, fee);
}
_mint(to, liquidityOut);
setReserves(balance0, balance1);
emit Mint(msg.sender, amount0In, amount1In, liquidityOut, to);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external override lock returns (uint256 amount0Out, uint256 amount1Out) {
require(canTrade(msg.sender), 'TP0C');
require(to != address(0), 'TP02');
uint256 _totalSupply = totalSupply; // gas savings
require(_totalSupply > 0, 'TP36');
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
(uint256 balance0, uint256 balance1) = getBalances(token0, token1);
uint256 liquidityIn = balanceOf[address(this)];
if (msg.sender != factory && burnFee > 0) {
uint256 fee = liquidityIn.mul(burnFee).div(PRECISION);
liquidityIn = liquidityIn.sub(fee);
_transfer(address(this), factory, fee);
}
_burn(address(this), liquidityIn);
amount0Out = liquidityIn.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1Out = liquidityIn.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0Out > 0 && amount1Out > 0, 'TP39');
_safeTransfer(_token0, to, amount0Out);
_safeTransfer(_token1, to, amount1Out);
(balance0, balance1) = getBalances(token0, token1);
setReserves(balance0, balance1);
emit Burn(msg.sender, amount0Out, amount1Out, liquidityIn, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external override lock {
require(canTrade(msg.sender), 'TP0C');
require(to != address(0), 'TP02');
require((amount0Out > 0 && amount1Out == 0) || (amount1Out > 0 && amount0Out == 0), 'TP31');
(uint112 _reserve0, uint112 _reserve1) = getReserves();
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'TP07');
{
// scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'TP2D');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
}
(uint256 balance0, uint256 balance1) = getBalances(token0, token1);
if (amount0Out > 0) {
// trading token1 for token0
require(balance1 > _reserve1, 'TP08');
uint256 amount1In = balance1 - _reserve1;
emit Swap(msg.sender, 0, amount1In, amount0Out, 0, to);
uint256 fee1 = amount1In.mul(swapFee).div(PRECISION);
uint256 balance1After = balance1.sub(fee1);
uint256 balance0After = ITwapOracle(oracle).tradeY(balance1After, _reserve0, _reserve1, data);
require(balance0 >= balance0After, 'TP2E');
uint256 fee0 = balance0.sub(balance0After);
addFees(fee0, fee1);
setReserves(balance0After, balance1After);
} else {
// trading token0 for token1
require(balance0 > _reserve0, 'TP08');
uint256 amount0In = balance0 - _reserve0;
emit Swap(msg.sender, amount0In, 0, 0, amount1Out, to);
uint256 fee0 = amount0In.mul(swapFee).div(PRECISION);
uint256 balance0After = balance0.sub(fee0);
uint256 balance1After = ITwapOracle(oracle).tradeX(balance0After, _reserve0, _reserve1, data);
require(balance1 >= balance1After, 'TP2E');
uint256 fee1 = balance1.sub(balance1After);
addFees(fee0, fee1);
setReserves(balance0After, balance1After);
}
}
function sync() external override lock {
require(canTrade(msg.sender), 'TP0C');
_sync();
}
// force reserves to match balances
function _sync() internal {
syncReserves(token0, token1);
uint256 tokens = balanceOf[address(this)];
if (tokens > 0) {
_transfer(address(this), factory, tokens);
}
}
function getSwapAmount0In(uint256 amount1Out, bytes calldata data)
public
view
override
returns (uint256 swapAmount0In)
{
(uint112 reserve0, uint112 reserve1) = getReserves();
uint256 balance1After = uint256(reserve1).sub(amount1Out);
uint256 balance0After = ITwapOracle(oracle).tradeY(balance1After, reserve0, reserve1, data);
return balance0After.sub(uint256(reserve0)).mul(PRECISION).ceil_div(PRECISION.sub(swapFee));
}
function getSwapAmount1In(uint256 amount0Out, bytes calldata data)
public
view
override
returns (uint256 swapAmount1In)
{
(uint112 reserve0, uint112 reserve1) = getReserves();
uint256 balance0After = uint256(reserve0).sub(amount0Out);
uint256 balance1After = ITwapOracle(oracle).tradeX(balance0After, reserve0, reserve1, data);
return balance1After.add(1).sub(uint256(reserve1)).mul(PRECISION).ceil_div(PRECISION.sub(swapFee));
}
function getSwapAmount0Out(uint256 amount1In, bytes calldata data)
public
view
override
returns (uint256 swapAmount0Out)
{
(uint112 reserve0, uint112 reserve1) = getReserves();
uint256 fee = amount1In.mul(swapFee).div(PRECISION);
uint256 balance0After = ITwapOracle(oracle).tradeY(
uint256(reserve1).add(amount1In).sub(fee),
reserve0,
reserve1,
data
);
return uint256(reserve0).sub(balance0After);
}
function getSwapAmount1Out(uint256 amount0In, bytes calldata data)
public
view
override
returns (uint256 swapAmount1Out)
{
(uint112 reserve0, uint112 reserve1) = getReserves();
uint256 fee = amount0In.mul(swapFee).div(PRECISION);
uint256 balance1After = ITwapOracle(oracle).tradeX(
uint256(reserve0).add(amount0In).sub(fee),
reserve0,
reserve1,
data
);
return uint256(reserve1).sub(balance1After);
}
function getDepositAmount0In(uint256 amount0, bytes calldata data) external view override returns (uint256) {
(uint112 reserve0, uint112 reserve1) = getReserves();
return ITwapOracle(oracle).depositTradeXIn(amount0, reserve0, reserve1, data);
}
function getDepositAmount1In(uint256 amount1, bytes calldata data) external view override returns (uint256) {
(uint112 reserve0, uint112 reserve1) = getReserves();
return ITwapOracle(oracle).depositTradeYIn(amount1, reserve0, reserve1, data);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import './ITwapERC20.sol';
import './IReserves.sol';
interface ITwapPair is ITwapERC20, IReserves {
event Mint(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 liquidityOut, address indexed to);
event Burn(address indexed sender, uint256 amount0Out, uint256 amount1Out, uint256 liquidityIn, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event SetMintFee(uint256 fee);
event SetBurnFee(uint256 fee);
event SetSwapFee(uint256 fee);
event SetOracle(address account);
event SetTrader(address trader);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function oracle() external view returns (address);
function trader() external view returns (address);
function mintFee() external view returns (uint256);
function setMintFee(uint256 fee) external;
function mint(address to) external returns (uint256 liquidity);
function burnFee() external view returns (uint256);
function setBurnFee(uint256 fee) external;
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swapFee() external view returns (uint256);
function setSwapFee(uint256 fee) external;
function setOracle(address account) external;
function setTrader(address account) external;
function collect(address to) external;
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function sync() external;
function initialize(
address _token0,
address _token1,
address _oracle,
address _trader
) external;
function getSwapAmount0In(uint256 amount1Out, bytes calldata data) external view returns (uint256 swapAmount0In);
function getSwapAmount1In(uint256 amount0Out, bytes calldata data) external view returns (uint256 swapAmount1In);
function getSwapAmount0Out(uint256 amount1In, bytes calldata data) external view returns (uint256 swapAmount0Out);
function getSwapAmount1Out(uint256 amount0In, bytes calldata data) external view returns (uint256 swapAmount1Out);
function getDepositAmount0In(uint256 amount0, bytes calldata data) external view returns (uint256 depositAmount0In);
function getDepositAmount1In(uint256 amount1, bytes calldata data) external view returns (uint256 depositAmount1In);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import '../interfaces/IReserves.sol';
import '../interfaces/IERC20.sol';
import '../libraries/SafeMath.sol';
contract Reserves is IReserves {
using SafeMath for uint256;
uint112 private reserve0;
uint112 private reserve1;
uint112 private fee0;
uint112 private fee1;
function getReserves() public view override returns (uint112, uint112) {
return (reserve0, reserve1);
}
function setReserves(uint256 balance0MinusFee, uint256 balance1MinusFee) internal {
require(balance0MinusFee != 0 && balance1MinusFee != 0, 'RS09');
reserve0 = balance0MinusFee.toUint112();
reserve1 = balance1MinusFee.toUint112();
}
function syncReserves(address token0, address token1) internal {
uint256 balance0 = IERC20(token0).balanceOf(address(this));
uint256 balance1 = IERC20(token1).balanceOf(address(this));
uint256 oldBalance0 = uint256(reserve0) + fee0;
uint256 oldBalance1 = uint256(reserve1) + fee1;
if (balance0 != oldBalance0 || balance1 != oldBalance1) {
if (oldBalance0 != 0) {
fee0 = (balance0.mul(fee0).div(oldBalance0)).toUint112();
}
if (oldBalance1 != 0) {
fee1 = (balance1.mul(fee1).div(oldBalance1)).toUint112();
}
setReserves(balance0.sub(fee0), balance1.sub(fee1));
}
}
function getFees() public view override returns (uint256, uint256) {
return (fee0, fee1);
}
function addFees(uint256 _fee0, uint256 _fee1) internal {
setFees(_fee0.add(fee0), _fee1.add(fee1));
}
function setFees(uint256 _fee0, uint256 _fee1) internal {
fee0 = _fee0.toUint112();
fee1 = _fee1.toUint112();
}
function getBalances(address token0, address token1) internal returns (uint256, uint256) {
uint256 balance0 = IERC20(token0).balanceOf(address(this));
uint256 balance1 = IERC20(token1).balanceOf(address(this));
if (fee0 > balance0) {
fee0 = uint112(balance0);
}
if (fee1 > balance1) {
fee1 = uint112(balance1);
}
return (balance0.sub(fee0), balance1.sub(fee1));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import './libraries/AbstractERC20.sol';
contract TwapLPToken is AbstractERC20 {
constructor() {
name = 'Twap LP';
symbol = 'TWAP-LP';
decimals = 18;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
// a library for performing various math operations
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x > y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
interface ITwapOracle {
event OwnerSet(address owner);
event UniswapPairSet(address uniswapPair);
function decimalsConverter() external view returns (int256);
function xDecimals() external view returns (uint8);
function yDecimals() external view returns (uint8);
function owner() external view returns (address);
function uniswapPair() external view returns (address);
function getPriceInfo() external view returns (uint256 priceAccumulator, uint32 priceTimestamp);
function getSpotPrice() external view returns (uint256);
function getAveragePrice(uint256 priceAccumulator, uint32 priceTimestamp) external view returns (uint256);
function setOwner(address _owner) external;
function setUniswapPair(address _uniswapPair) external;
function tradeX(
uint256 xAfter,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 yAfter);
function tradeY(
uint256 yAfter,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 xAfter);
function depositTradeXIn(
uint256 xLeft,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 xIn);
function depositTradeYIn(
uint256 yLeft,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 yIn);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import './IERC20.sol';
interface ITwapERC20 is IERC20 {
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
interface IReserves {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1);
function getFees() external view returns (uint256 fee0, uint256 fee1);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
int256 private constant _INT256_MIN = -2**255;
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'SM4E');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = sub(x, y, 'SM12');
}
function sub(
uint256 x,
uint256 y,
string memory message
) internal pure returns (uint256 z) {
require((z = x - y) <= x, message);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'SM2A');
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SM43');
uint256 c = a / b;
return c;
}
function ceil_div(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = div(a, b);
if (c == mul(a, b)) {
return c;
} else {
return add(c, 1);
}
}
function toUint32(uint256 n) internal pure returns (uint32) {
require(n <= type(uint32).max, 'SM50');
return uint32(n);
}
function toUint112(uint256 n) internal pure returns (uint112) {
require(n <= type(uint112).max, 'SM51');
return uint112(n);
}
function toInt256(uint256 unsigned) internal pure returns (int256 signed) {
require(unsigned <= uint256(type(int256).max), 'SM34');
signed = int256(unsigned);
}
// int256
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), 'SM4D');
return c;
}
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), 'SM11');
return c;
}
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), 'SM29');
int256 c = a * b;
require(c / a == b, 'SM29');
return c;
}
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, 'SM43');
require(!(b == -1 && a == _INT256_MIN), 'SM42');
int256 c = a / b;
return c;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import '../interfaces/ITwapERC20.sol';
import './SafeMath.sol';
abstract contract AbstractERC20 is ITwapERC20 {
using SafeMath for uint256;
string public override name;
string public override symbol;
uint8 public override decimals;
uint256 public override totalSupply;
mapping(address => uint256) public override balanceOf;
mapping(address => mapping(address => uint256)) public override allowance;
bytes32 public constant DOMAIN_TYPEHASH =
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)');
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant override PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public override nonces;
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(
address owner,
address spender,
uint256 value
) internal {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(
address from,
address to,
uint256 value
) internal {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value) external override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external override returns (bool) {
_approve(msg.sender, spender, allowance[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external override returns (bool) {
uint256 currentAllowance = allowance[msg.sender][spender];
require(currentAllowance >= subtractedValue, 'TA48');
_approve(msg.sender, spender, currentAllowance.sub(subtractedValue));
return true;
}
function transfer(address to, uint256 value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external override returns (bool) {
if (allowance[from][msg.sender] != uint256(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(deadline >= block.timestamp, 'TA04');
bytes32 digest = keccak256(
abi.encodePacked(
'\\x19\\x01',
getDomainSeparator(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'TA2F');
_approve(owner, spender, value);
}
function getDomainSeparator() public view returns (bytes32) {
uint256 chainId;
assembly {
chainId := chainid()
}
return
keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this))
);
}
}
File 8 of 11: ExecutionHelper
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IReserves {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1);
function getFees() external view returns (uint256 fee0, uint256 fee1);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './IERC20.sol';
interface ITwapERC20 is IERC20 {
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface ITwapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
event OwnerSet(address owner);
function owner() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB, address oracle, address trader) external returns (address pair);
function setOwner(address) external;
function setMintFee(address tokenA, address tokenB, uint256 fee) external;
function setBurnFee(address tokenA, address tokenB, uint256 fee) external;
function setSwapFee(address tokenA, address tokenB, uint256 fee) external;
function setOracle(address tokenA, address tokenB, address oracle) external;
function setTrader(address tokenA, address tokenB, address trader) external;
function collect(address tokenA, address tokenB, address to) external;
function withdraw(address tokenA, address tokenB, uint256 amount, address to) external;
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface ITwapOracle {
event OwnerSet(address owner);
event UniswapPairSet(address uniswapPair);
function decimalsConverter() external view returns (int256);
function xDecimals() external view returns (uint8);
function yDecimals() external view returns (uint8);
function owner() external view returns (address);
function uniswapPair() external view returns (address);
function getPriceInfo() external view returns (uint256 priceAccumulator, uint256 priceTimestamp);
function getSpotPrice() external view returns (uint256);
function getAveragePrice(uint256 priceAccumulator, uint256 priceTimestamp) external view returns (uint256);
function setOwner(address _owner) external;
function setUniswapPair(address _uniswapPair) external;
function tradeX(
uint256 xAfter,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 yAfter);
function tradeY(
uint256 yAfter,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 xAfter);
function depositTradeXIn(
uint256 xLeft,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 xIn);
function depositTradeYIn(
uint256 yLeft,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 yIn);
function getSwapAmount0Out(
uint256 swapFee,
uint256 amount1In,
bytes calldata data
) external view returns (uint256 amount0Out);
function getSwapAmount1Out(
uint256 swapFee,
uint256 amount0In,
bytes calldata data
) external view returns (uint256 amount1Out);
function getSwapAmountInMaxOut(
bool inverse,
uint256 swapFee,
uint256 _amountOut,
bytes calldata data
) external view returns (uint256 amountIn, uint256 amountOut);
function getSwapAmountInMinOut(
bool inverse,
uint256 swapFee,
uint256 _amountOut,
bytes calldata data
) external view returns (uint256 amountIn, uint256 amountOut);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './ITwapERC20.sol';
import './IReserves.sol';
interface ITwapPair is ITwapERC20, IReserves {
event Mint(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 liquidityOut, address indexed to);
event Burn(address indexed sender, uint256 amount0Out, uint256 amount1Out, uint256 liquidityIn, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event SetMintFee(uint256 fee);
event SetBurnFee(uint256 fee);
event SetSwapFee(uint256 fee);
event SetOracle(address account);
event SetTrader(address trader);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function oracle() external view returns (address);
function trader() external view returns (address);
function mintFee() external view returns (uint256);
function setMintFee(uint256 fee) external;
function mint(address to) external returns (uint256 liquidity);
function burnFee() external view returns (uint256);
function setBurnFee(uint256 fee) external;
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swapFee() external view returns (uint256);
function setSwapFee(uint256 fee) external;
function setOracle(address account) external;
function setTrader(address account) external;
function collect(address to) external;
function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
function sync() external;
function initialize(address _token0, address _token1, address _oracle, address _trader) external;
function getSwapAmount0In(uint256 amount1Out, bytes calldata data) external view returns (uint256 swapAmount0In);
function getSwapAmount1In(uint256 amount0Out, bytes calldata data) external view returns (uint256 swapAmount1In);
function getSwapAmount0Out(uint256 amount1In, bytes calldata data) external view returns (uint256 swapAmount0Out);
function getSwapAmount1Out(uint256 amount0In, bytes calldata data) external view returns (uint256 swapAmount1Out);
function getDepositAmount0In(uint256 amount0, bytes calldata data) external view returns (uint256 depositAmount0In);
function getDepositAmount1In(uint256 amount1, bytes calldata data) external view returns (uint256 depositAmount1In);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './TransferHelper.sol';
import './SafeMath.sol';
import './Math.sol';
import '../interfaces/ITwapPair.sol';
import '../interfaces/ITwapOracle.sol';
library AddLiquidity {
using SafeMath for uint256;
function addLiquidity(
address pair,
uint256 amount0Desired,
uint256 amount1Desired
) internal view returns (uint256 amount0, uint256 amount1, uint256 swapToken) {
if (amount0Desired == 0 || amount1Desired == 0) {
if (amount0Desired > 0) {
swapToken = 1;
} else if (amount1Desired > 0) {
swapToken = 2;
}
return (0, 0, swapToken);
}
(uint256 reserve0, uint256 reserve1) = ITwapPair(pair).getReserves();
if (reserve0 == 0 && reserve1 == 0) {
(amount0, amount1) = (amount0Desired, amount1Desired);
} else {
require(reserve0 > 0 && reserve1 > 0, 'AL07');
uint256 amount1Optimal = amount0Desired.mul(reserve1) / reserve0;
if (amount1Optimal <= amount1Desired) {
swapToken = 2;
(amount0, amount1) = (amount0Desired, amount1Optimal);
} else {
uint256 amount0Optimal = amount1Desired.mul(reserve0) / reserve1;
assert(amount0Optimal <= amount0Desired);
swapToken = 1;
(amount0, amount1) = (amount0Optimal, amount1Desired);
}
uint256 totalSupply = ITwapPair(pair).totalSupply();
uint256 liquidityOut = Math.min(amount0.mul(totalSupply) / reserve0, amount1.mul(totalSupply) / reserve1);
if (liquidityOut == 0) {
amount0 = 0;
amount1 = 0;
}
}
}
function addLiquidityAndMint(
address pair,
address to,
address token0,
address token1,
uint256 amount0Desired,
uint256 amount1Desired
) external returns (uint256 amount0Left, uint256 amount1Left, uint256 swapToken) {
uint256 amount0;
uint256 amount1;
(amount0, amount1, swapToken) = addLiquidity(pair, amount0Desired, amount1Desired);
if (amount0 == 0 || amount1 == 0) {
return (amount0Desired, amount1Desired, swapToken);
}
TransferHelper.safeTransfer(token0, pair, amount0);
TransferHelper.safeTransfer(token1, pair, amount1);
ITwapPair(pair).mint(to);
amount0Left = amount0Desired.sub(amount0);
amount1Left = amount1Desired.sub(amount1);
}
function swapDeposit0(
address pair,
address token0,
uint256 amount0,
uint256 minSwapPrice,
uint16 tolerance,
bytes calldata data
) external returns (uint256 amount0Left, uint256 amount1Left) {
uint256 amount0In = ITwapPair(pair).getDepositAmount0In(amount0, data);
amount1Left = ITwapPair(pair).getSwapAmount1Out(amount0In, data).sub(tolerance);
if (amount1Left == 0) {
return (amount0, amount1Left);
}
uint256 price = getPrice(amount0In, amount1Left, pair);
require(minSwapPrice == 0 || price >= minSwapPrice, 'AL15');
TransferHelper.safeTransfer(token0, pair, amount0In);
ITwapPair(pair).swap(0, amount1Left, address(this), data);
amount0Left = amount0.sub(amount0In);
}
function swapDeposit1(
address pair,
address token1,
uint256 amount1,
uint256 maxSwapPrice,
uint16 tolerance,
bytes calldata data
) external returns (uint256 amount0Left, uint256 amount1Left) {
uint256 amount1In = ITwapPair(pair).getDepositAmount1In(amount1, data);
amount0Left = ITwapPair(pair).getSwapAmount0Out(amount1In, data).sub(tolerance);
if (amount0Left == 0) {
return (amount0Left, amount1);
}
uint256 price = getPrice(amount0Left, amount1In, pair);
require(maxSwapPrice == 0 || price <= maxSwapPrice, 'AL16');
TransferHelper.safeTransfer(token1, pair, amount1In);
ITwapPair(pair).swap(amount0Left, 0, address(this), data);
amount1Left = amount1.sub(amount1In);
}
function getPrice(uint256 amount0, uint256 amount1, address pair) internal view returns (uint256) {
ITwapOracle oracle = ITwapOracle(ITwapPair(pair).oracle());
return amount1.mul(uint256(oracle.decimalsConverter())).div(amount0);
}
function _refundDeposit(address to, address token0, address token1, uint256 amount0, uint256 amount1) internal {
if (amount0 > 0) {
TransferHelper.safeTransfer(token0, to, amount0);
}
if (amount1 > 0) {
TransferHelper.safeTransfer(token1, to, amount1);
}
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import '../interfaces/ITwapOracle.sol';
import '../interfaces/ITwapPair.sol';
import '../interfaces/IWETH.sol';
import '../libraries/SafeMath.sol';
import '../libraries/Orders.sol';
import '../libraries/TokenShares.sol';
import '../libraries/AddLiquidity.sol';
import '../libraries/WithdrawHelper.sol';
library ExecutionHelper {
using SafeMath for uint256;
using TransferHelper for address;
using Orders for Orders.Data;
using TokenShares for TokenShares.Data;
uint256 private constant ORDER_LIFESPAN = 48 hours;
struct ExecuteBuySellParams {
Orders.Order order;
address pairAddress;
uint16 pairTolerance;
}
function executeDeposit(
Orders.Order calldata order,
address pairAddress,
uint16 pairTolerance,
TokenShares.Data storage tokenShares
) external {
require(order.validAfterTimestamp + ORDER_LIFESPAN >= block.timestamp, 'EH04');
(uint256 amount0Left, uint256 amount1Left, uint256 swapToken) = _initialDeposit(
order,
pairAddress,
tokenShares
);
if (order.swap && swapToken != 0) {
bytes memory data = encodePriceInfo(pairAddress, order.priceAccumulator, order.timestamp);
if (amount0Left != 0 && swapToken == 1) {
uint256 extraAmount1;
(amount0Left, extraAmount1) = AddLiquidity.swapDeposit0(
pairAddress,
order.token0,
amount0Left,
order.minSwapPrice,
pairTolerance,
data
);
amount1Left = amount1Left.add(extraAmount1);
} else if (amount1Left != 0 && swapToken == 2) {
uint256 extraAmount0;
(extraAmount0, amount1Left) = AddLiquidity.swapDeposit1(
pairAddress,
order.token1,
amount1Left,
order.maxSwapPrice,
pairTolerance,
data
);
amount0Left = amount0Left.add(extraAmount0);
}
}
if (amount0Left != 0 && amount1Left != 0) {
(amount0Left, amount1Left, ) = AddLiquidity.addLiquidityAndMint(
pairAddress,
order.to,
order.token0,
order.token1,
amount0Left,
amount1Left
);
}
AddLiquidity._refundDeposit(order.to, order.token0, order.token1, amount0Left, amount1Left);
}
function _initialDeposit(
Orders.Order calldata order,
address pairAddress,
TokenShares.Data storage tokenShares
) private returns (uint256 amount0Left, uint256 amount1Left, uint256 swapToken) {
uint256 amount0Desired = tokenShares.sharesToAmount(order.token0, order.value0, order.amountLimit0, order.to);
uint256 amount1Desired = tokenShares.sharesToAmount(order.token1, order.value1, order.amountLimit1, order.to);
(amount0Left, amount1Left, swapToken) = AddLiquidity.addLiquidityAndMint(
pairAddress,
order.to,
order.token0,
order.token1,
amount0Desired,
amount1Desired
);
}
function executeWithdraw(Orders.Order calldata order) external {
require(order.validAfterTimestamp + ORDER_LIFESPAN >= block.timestamp, 'EH04');
(address pairAddress, ) = Orders.getPair(order.token0, order.token1);
TransferHelper.safeTransfer(pairAddress, pairAddress, order.liquidity);
uint256 wethAmount;
uint256 amount0;
uint256 amount1;
if (order.unwrap && (order.token0 == TokenShares.WETH_ADDRESS || order.token1 == TokenShares.WETH_ADDRESS)) {
bool success;
(success, wethAmount, amount0, amount1) = WithdrawHelper.withdrawAndUnwrap(
order.token0,
order.token1,
pairAddress,
TokenShares.WETH_ADDRESS,
order.to,
Orders.getTransferGasCost(Orders.NATIVE_CURRENCY_SENTINEL)
);
if (!success) {
TokenShares.onUnwrapFailed(order.to, wethAmount);
}
} else {
(amount0, amount1) = ITwapPair(pairAddress).burn(order.to);
}
require(amount0 >= order.value0 && amount1 >= order.value1, 'EH03');
}
function executeBuy(ExecuteBuySellParams memory orderParams, TokenShares.Data storage tokenShares) external {
require(orderParams.order.validAfterTimestamp + ORDER_LIFESPAN >= block.timestamp, 'EH04');
uint256 amountInMax = tokenShares.sharesToAmount(
orderParams.order.token0,
orderParams.order.value0,
orderParams.order.amountLimit0,
orderParams.order.to
);
bytes memory priceInfo = encodePriceInfo(
orderParams.pairAddress,
orderParams.order.priceAccumulator,
orderParams.order.timestamp
);
uint256 amountIn;
uint256 amountOut;
uint256 reserveOut;
bool inverted = orderParams.order.inverted;
{
// scope for reserve out logic, avoids stack too deep errors
(uint112 reserve0, uint112 reserve1) = ITwapPair(orderParams.pairAddress).getReserves();
// subtract 1 to prevent reserve going to 0
reserveOut = uint256(inverted ? reserve0 : reserve1).sub(1);
}
{
// scope for partial fill logic, avoids stack too deep errors
address oracle = ITwapPair(orderParams.pairAddress).oracle();
uint256 swapFee = ITwapPair(orderParams.pairAddress).swapFee();
(amountIn, amountOut) = ITwapOracle(oracle).getSwapAmountInMaxOut(
inverted,
swapFee,
orderParams.order.value1,
priceInfo
);
uint256 amountInMaxScaled;
if (amountOut > reserveOut) {
amountInMaxScaled = amountInMax.mul(reserveOut).ceil_div(orderParams.order.value1);
(amountIn, amountOut) = ITwapOracle(oracle).getSwapAmountInMinOut(
inverted,
swapFee,
reserveOut,
priceInfo
);
} else {
amountInMaxScaled = amountInMax;
amountOut = orderParams.order.value1; // Truncate to desired out
}
require(amountInMaxScaled >= amountIn, 'EH08');
if (amountInMax > amountIn) {
if (orderParams.order.token0 == TokenShares.WETH_ADDRESS && orderParams.order.unwrap) {
forceEtherTransfer(orderParams.order.to, amountInMax.sub(amountIn));
} else {
TransferHelper.safeTransfer(
orderParams.order.token0,
orderParams.order.to,
amountInMax.sub(amountIn)
);
}
}
TransferHelper.safeTransfer(orderParams.order.token0, orderParams.pairAddress, amountIn);
}
amountOut = amountOut.sub(orderParams.pairTolerance);
uint256 amount0Out;
uint256 amount1Out;
if (inverted) {
amount0Out = amountOut;
} else {
amount1Out = amountOut;
}
if (orderParams.order.token1 == TokenShares.WETH_ADDRESS && orderParams.order.unwrap) {
ITwapPair(orderParams.pairAddress).swap(amount0Out, amount1Out, address(this), priceInfo);
forceEtherTransfer(orderParams.order.to, amountOut);
} else {
ITwapPair(orderParams.pairAddress).swap(amount0Out, amount1Out, orderParams.order.to, priceInfo);
}
}
function executeSell(ExecuteBuySellParams memory orderParams, TokenShares.Data storage tokenShares) external {
require(orderParams.order.validAfterTimestamp + ORDER_LIFESPAN >= block.timestamp, 'EH04');
bytes memory priceInfo = encodePriceInfo(
orderParams.pairAddress,
orderParams.order.priceAccumulator,
orderParams.order.timestamp
);
uint256 amountOut = _executeSellHelper(orderParams, priceInfo, tokenShares);
(uint256 amount0Out, uint256 amount1Out) = orderParams.order.inverted
? (amountOut, uint256(0))
: (uint256(0), amountOut);
if (orderParams.order.token1 == TokenShares.WETH_ADDRESS && orderParams.order.unwrap) {
ITwapPair(orderParams.pairAddress).swap(amount0Out, amount1Out, address(this), priceInfo);
forceEtherTransfer(orderParams.order.to, amountOut);
} else {
ITwapPair(orderParams.pairAddress).swap(amount0Out, amount1Out, orderParams.order.to, priceInfo);
}
}
function _executeSellHelper(
ExecuteBuySellParams memory orderParams,
bytes memory priceInfo,
TokenShares.Data storage tokenShares
) internal returns (uint256 amountOut) {
uint256 reserveOut;
{
// scope for determining reserve out, avoids stack too deep errors
(uint112 reserve0, uint112 reserve1) = ITwapPair(orderParams.pairAddress).getReserves();
// subtract 1 to prevent reserve going to 0
reserveOut = uint256(orderParams.order.inverted ? reserve0 : reserve1).sub(1);
}
{
// scope for calculations, avoids stack too deep errors
address oracle = ITwapPair(orderParams.pairAddress).oracle();
uint256 swapFee = ITwapPair(orderParams.pairAddress).swapFee();
uint256 amountIn = tokenShares.sharesToAmount(
orderParams.order.token0,
orderParams.order.value0,
orderParams.order.amountLimit0,
orderParams.order.to
);
amountOut = orderParams.order.inverted
? ITwapOracle(oracle).getSwapAmount0Out(swapFee, amountIn, priceInfo)
: ITwapOracle(oracle).getSwapAmount1Out(swapFee, amountIn, priceInfo);
uint256 amountOutMinScaled;
if (amountOut > reserveOut) {
amountOutMinScaled = orderParams.order.value1.mul(reserveOut).div(amountOut);
uint256 _amountIn = amountIn;
(amountIn, amountOut) = ITwapOracle(oracle).getSwapAmountInMinOut(
orderParams.order.inverted,
swapFee,
reserveOut,
priceInfo
);
if (orderParams.order.token0 == TokenShares.WETH_ADDRESS && orderParams.order.unwrap) {
forceEtherTransfer(orderParams.order.to, _amountIn.sub(amountIn));
} else {
TransferHelper.safeTransfer(
orderParams.order.token0,
orderParams.order.to,
_amountIn.sub(amountIn)
);
}
} else {
amountOutMinScaled = orderParams.order.value1;
}
amountOut = amountOut.sub(orderParams.pairTolerance);
require(amountOut >= amountOutMinScaled, 'EH37');
TransferHelper.safeTransfer(orderParams.order.token0, orderParams.pairAddress, amountIn);
}
}
function encodePriceInfo(
address pairAddress,
uint256 priceAccumulator,
uint256 priceTimestamp
) internal view returns (bytes memory data) {
uint256 price = ITwapOracle(ITwapPair(pairAddress).oracle()).getAveragePrice(priceAccumulator, priceTimestamp);
// Pack everything as 32 bytes / uint256 to simplify decoding
data = abi.encode(price);
}
function forceEtherTransfer(address to, uint256 amount) internal {
IWETH(TokenShares.WETH_ADDRESS).withdraw(amount);
(bool success, ) = to.call{ value: amount, gas: Orders.getTransferGasCost(Orders.NATIVE_CURRENCY_SENTINEL) }(
''
);
if (!success) {
TokenShares.onUnwrapFailed(to, amount);
}
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// a library for performing various math operations
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x > y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './SafeMath.sol';
import '../libraries/Math.sol';
import '../interfaces/ITwapFactory.sol';
import '../interfaces/ITwapPair.sol';
import '../interfaces/ITwapOracle.sol';
import '../libraries/TokenShares.sol';
library Orders {
using SafeMath for uint256;
using TokenShares for TokenShares.Data;
using TransferHelper for address;
enum OrderType {
Empty,
Deposit,
Withdraw,
Sell,
Buy
}
enum OrderStatus {
NonExistent,
EnqueuedWaiting,
EnqueuedReady,
ExecutedSucceeded,
ExecutedFailed,
Canceled
}
event DepositEnqueued(uint256 indexed orderId, Order order);
event WithdrawEnqueued(uint256 indexed orderId, Order order);
event SellEnqueued(uint256 indexed orderId, Order order);
event BuyEnqueued(uint256 indexed orderId, Order order);
event OrderTypesDisabled(address pair, Orders.OrderType[] orderTypes, bool disabled);
event RefundFailed(address indexed to, address indexed token, uint256 amount, bytes data);
// Note on gas estimation for the full order execution in the UI:
// Add (*_ORDER_BASE_COST + token transfer costs) to the actual gas usage
// of the TwapDelay._execute* functions when updating gas cost in the UI.
// Remember that ETH unwrap is part of those functions. It is optional,
// but also needs to be included in the estimate.
uint256 public constant ETHER_TRANSFER_COST = ETHER_TRANSFER_CALL_COST + 2600 + 1504; // Std cost + EIP-2929 acct access cost + Gnosis Safe receive ETH cost
uint256 private constant BOT_ETHER_TRANSFER_COST = 10_000;
uint256 private constant BUFFER_COST = 10_000;
uint256 private constant ORDER_EXECUTED_EVENT_COST = 3700;
uint256 private constant EXECUTE_PREPARATION_COST = 30_000; // dequeue + gas calculation before calls to _execute* functions
uint256 public constant ETHER_TRANSFER_CALL_COST = 10_000;
uint256 public constant PAIR_TRANSFER_COST = 55_000;
uint256 public constant REFUND_BASE_COST =
BOT_ETHER_TRANSFER_COST + ETHER_TRANSFER_COST + BUFFER_COST + ORDER_EXECUTED_EVENT_COST;
uint256 private constant ORDER_BASE_COST = EXECUTE_PREPARATION_COST + REFUND_BASE_COST;
uint256 public constant TOKEN_REFUND_BASE_COST = 20_000; // cost of performing token refund logic (excluding token transfer)
uint256 public constant DEPOSIT_ORDER_BASE_COST = ORDER_BASE_COST + 2 * TOKEN_REFUND_BASE_COST;
uint256 public constant WITHDRAW_ORDER_BASE_COST = ORDER_BASE_COST;
uint256 public constant SELL_ORDER_BASE_COST = ORDER_BASE_COST + TOKEN_REFUND_BASE_COST;
uint256 public constant BUY_ORDER_BASE_COST = ORDER_BASE_COST + TOKEN_REFUND_BASE_COST;
// Masks used for setting order disabled
// Different bits represent different order types
uint8 private constant DEPOSIT_MASK = uint8(1 << uint8(OrderType.Deposit)); // 00000010
uint8 private constant WITHDRAW_MASK = uint8(1 << uint8(OrderType.Withdraw)); // 00000100
uint8 private constant SELL_MASK = uint8(1 << uint8(OrderType.Sell)); // 00001000
uint8 private constant BUY_MASK = uint8(1 << uint8(OrderType.Buy)); // 00010000
address public constant FACTORY_ADDRESS = 0xC480b33eE5229DE3FbDFAD1D2DCD3F3BAD0C56c6;
uint256 public constant MAX_GAS_LIMIT = 5000000;
uint256 public constant GAS_PRICE_INERTIA = 20000000;
uint256 public constant MAX_GAS_PRICE_IMPACT = 1000000;
uint256 public constant DELAY = 1800;
address public constant NATIVE_CURRENCY_SENTINEL = address(0); // A sentinel value for the native currency to distinguish it from ERC20 tokens
struct Data {
uint256 newestOrderId;
uint256 lastProcessedOrderId;
mapping(uint256 => bytes32) orderQueue;
uint256 gasPrice;
mapping(uint256 => bool) canceled;
// Bit on specific positions indicates whether order type is disabled (1) or enabled (0) on specific pair
mapping(address => uint8) orderTypesDisabled;
mapping(uint256 => bool) refundFailed;
}
struct Order {
uint256 orderId;
OrderType orderType;
bool inverted;
uint256 validAfterTimestamp;
bool unwrap;
uint256 timestamp;
uint256 gasLimit;
uint256 gasPrice;
uint256 liquidity;
uint256 value0; // Deposit: share0, Withdraw: amount0Min, Sell: shareIn, Buy: shareInMax
uint256 value1; // Deposit: share1, Withdraw: amount1Min, Sell: amountOutMin, Buy: amountOut
address token0; // Sell: tokenIn, Buy: tokenIn
address token1; // Sell: tokenOut, Buy: tokenOut
address to;
uint256 minSwapPrice;
uint256 maxSwapPrice;
bool swap;
uint256 priceAccumulator;
uint256 amountLimit0;
uint256 amountLimit1;
}
function getOrderStatus(
Data storage data,
uint256 orderId,
uint256 validAfterTimestamp
) internal view returns (OrderStatus) {
if (orderId > data.newestOrderId) {
return OrderStatus.NonExistent;
}
if (data.canceled[orderId]) {
return OrderStatus.Canceled;
}
if (data.refundFailed[orderId]) {
return OrderStatus.ExecutedFailed;
}
if (data.orderQueue[orderId] == bytes32(0)) {
return OrderStatus.ExecutedSucceeded;
}
if (validAfterTimestamp >= block.timestamp) {
return OrderStatus.EnqueuedWaiting;
}
return OrderStatus.EnqueuedReady;
}
function getPair(address tokenA, address tokenB) internal view returns (address pair, bool inverted) {
pair = ITwapFactory(FACTORY_ADDRESS).getPair(tokenA, tokenB);
require(pair != address(0), 'OS17');
inverted = tokenA > tokenB;
}
function getDepositDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & DEPOSIT_MASK != 0;
}
function getWithdrawDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & WITHDRAW_MASK != 0;
}
function getSellDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & SELL_MASK != 0;
}
function getBuyDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & BUY_MASK != 0;
}
function setOrderTypesDisabled(
Data storage data,
address pair,
Orders.OrderType[] calldata orderTypes,
bool disabled
) external {
uint256 orderTypesLength = orderTypes.length;
uint8 currentSettings = data.orderTypesDisabled[pair];
uint8 combinedMask;
for (uint256 i; i < orderTypesLength; ++i) {
Orders.OrderType orderType = orderTypes[i];
require(orderType != Orders.OrderType.Empty, 'OS32');
// zeros with 1 bit set at position specified by orderType
// e.g. for SELL order type
// mask for SELL = 00001000
// combinedMask = 00000110 (DEPOSIT and WITHDRAW masks set in previous iterations)
// the result of OR = 00001110 (DEPOSIT, WITHDRAW and SELL combined mask)
combinedMask = combinedMask | uint8(1 << uint8(orderType));
}
// set/unset a bit accordingly to 'disabled' value
if (disabled) {
// OR operation to disable order
// e.g. for disable DEPOSIT
// currentSettings = 00010100 (BUY and WITHDRAW disabled)
// mask for DEPOSIT = 00000010
// the result of OR = 00010110
currentSettings = currentSettings | combinedMask;
} else {
// AND operation with a mask negation to enable order
// e.g. for enable DEPOSIT
// currentSettings = 00010100 (BUY and WITHDRAW disabled)
// 0xff = 11111111
// mask for Deposit = 00000010
// mask negation = 11111101
// the result of AND = 00010100
currentSettings = currentSettings & (combinedMask ^ 0xff);
}
require(currentSettings != data.orderTypesDisabled[pair], 'OS01');
data.orderTypesDisabled[pair] = currentSettings;
emit OrderTypesDisabled(pair, orderTypes, disabled);
}
function markRefundFailed(Data storage data) internal {
data.refundFailed[data.lastProcessedOrderId] = true;
}
/// @dev The passed in order.oderId is ignored and overwritten with the correct value, i.e. an updated data.newestOrderId.
/// This is done to ensure atomicity of these two actions while optimizing gas usage - adding an order to the queue and incrementing
/// data.newestOrderId (which should not be done anywhere else in the contract).
/// Must only be called on verified orders.
function enqueueOrder(Data storage data, Order memory order) internal {
order.orderId = ++data.newestOrderId;
data.orderQueue[order.orderId] = getOrderDigest(order);
}
struct DepositParams {
address token0;
address token1;
uint256 amount0;
uint256 amount1;
uint256 minSwapPrice;
uint256 maxSwapPrice;
bool wrap;
bool swap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function deposit(
Data storage data,
DepositParams calldata depositParams,
TokenShares.Data storage tokenShares
) external {
checkOrderParams(
depositParams.to,
depositParams.gasLimit,
depositParams.submitDeadline,
DEPOSIT_ORDER_BASE_COST +
getTransferGasCost(depositParams.token0) +
getTransferGasCost(depositParams.token1)
);
require(depositParams.amount0 != 0 || depositParams.amount1 != 0, 'OS25');
(address pairAddress, bool inverted) = getPair(depositParams.token0, depositParams.token1);
require(!getDepositDisabled(data, pairAddress), 'OS46');
{
// scope for value, avoids stack too deep errors
uint256 value = msg.value;
// allocate gas refund
if (depositParams.wrap) {
if (depositParams.token0 == TokenShares.WETH_ADDRESS) {
value = msg.value.sub(depositParams.amount0, 'OS1E');
} else if (depositParams.token1 == TokenShares.WETH_ADDRESS) {
value = msg.value.sub(depositParams.amount1, 'OS1E');
}
}
allocateGasRefund(data, value, depositParams.gasLimit);
}
uint256 shares0 = tokenShares.amountToShares(
inverted ? depositParams.token1 : depositParams.token0,
inverted ? depositParams.amount1 : depositParams.amount0,
depositParams.wrap
);
uint256 shares1 = tokenShares.amountToShares(
inverted ? depositParams.token0 : depositParams.token1,
inverted ? depositParams.amount0 : depositParams.amount1,
depositParams.wrap
);
(uint256 priceAccumulator, uint256 timestamp) = ITwapOracle(ITwapPair(pairAddress).oracle()).getPriceInfo();
Order memory order = Order(
0,
OrderType.Deposit,
inverted,
timestamp + DELAY, // validAfterTimestamp
depositParams.wrap,
timestamp,
depositParams.gasLimit,
data.gasPrice,
0, // liquidity
shares0,
shares1,
inverted ? depositParams.token1 : depositParams.token0,
inverted ? depositParams.token0 : depositParams.token1,
depositParams.to,
depositParams.minSwapPrice,
depositParams.maxSwapPrice,
depositParams.swap,
priceAccumulator,
inverted ? depositParams.amount1 : depositParams.amount0,
inverted ? depositParams.amount0 : depositParams.amount1
);
enqueueOrder(data, order);
emit DepositEnqueued(order.orderId, order);
}
struct WithdrawParams {
address token0;
address token1;
uint256 liquidity;
uint256 amount0Min;
uint256 amount1Min;
bool unwrap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function withdraw(Data storage data, WithdrawParams calldata withdrawParams) external {
(address pair, bool inverted) = getPair(withdrawParams.token0, withdrawParams.token1);
require(!getWithdrawDisabled(data, pair), 'OS0A');
checkOrderParams(
withdrawParams.to,
withdrawParams.gasLimit,
withdrawParams.submitDeadline,
WITHDRAW_ORDER_BASE_COST + PAIR_TRANSFER_COST
);
require(withdrawParams.liquidity != 0, 'OS22');
allocateGasRefund(data, msg.value, withdrawParams.gasLimit);
pair.safeTransferFrom(msg.sender, address(this), withdrawParams.liquidity);
Order memory order = Order(
0,
OrderType.Withdraw,
inverted,
block.timestamp + DELAY, // validAfterTimestamp
withdrawParams.unwrap,
0, // timestamp
withdrawParams.gasLimit,
data.gasPrice,
withdrawParams.liquidity,
inverted ? withdrawParams.amount1Min : withdrawParams.amount0Min,
inverted ? withdrawParams.amount0Min : withdrawParams.amount1Min,
inverted ? withdrawParams.token1 : withdrawParams.token0,
inverted ? withdrawParams.token0 : withdrawParams.token1,
withdrawParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
0, // priceAccumulator
0, // amountLimit0
0 // amountLimit1
);
enqueueOrder(data, order);
emit WithdrawEnqueued(order.orderId, order);
}
struct SellParams {
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 amountOutMin;
bool wrapUnwrap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function sell(Data storage data, SellParams calldata sellParams, TokenShares.Data storage tokenShares) external {
checkOrderParams(
sellParams.to,
sellParams.gasLimit,
sellParams.submitDeadline,
SELL_ORDER_BASE_COST + getTransferGasCost(sellParams.tokenIn)
);
(address pairAddress, bool inverted) = sellHelper(data, sellParams);
(uint256 priceAccumulator, uint256 timestamp) = ITwapOracle(ITwapPair(pairAddress).oracle()).getPriceInfo();
uint256 shares = tokenShares.amountToShares(sellParams.tokenIn, sellParams.amountIn, sellParams.wrapUnwrap);
Order memory order = Order(
0,
OrderType.Sell,
inverted,
timestamp + DELAY, // validAfterTimestamp
sellParams.wrapUnwrap,
timestamp,
sellParams.gasLimit,
data.gasPrice,
0, // liquidity
shares,
sellParams.amountOutMin,
sellParams.tokenIn,
sellParams.tokenOut,
sellParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
priceAccumulator,
sellParams.amountIn,
0 // amountLimit1
);
enqueueOrder(data, order);
emit SellEnqueued(order.orderId, order);
}
function relayerSell(
Data storage data,
SellParams calldata sellParams,
TokenShares.Data storage tokenShares
) external {
checkOrderParams(
sellParams.to,
sellParams.gasLimit,
sellParams.submitDeadline,
SELL_ORDER_BASE_COST + getTransferGasCost(sellParams.tokenIn)
);
(, bool inverted) = sellHelper(data, sellParams);
uint256 shares = tokenShares.amountToSharesWithoutTransfer(
sellParams.tokenIn,
sellParams.amountIn,
sellParams.wrapUnwrap
);
Order memory order = Order(
0,
OrderType.Sell,
inverted,
block.timestamp + DELAY, // validAfterTimestamp
false, // Never wrap/unwrap
block.timestamp,
sellParams.gasLimit,
data.gasPrice,
0, // liquidity
shares,
sellParams.amountOutMin,
sellParams.tokenIn,
sellParams.tokenOut,
sellParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
0, // priceAccumulator - oracleV3 pairs don't need priceAccumulator
sellParams.amountIn,
0 // amountLimit1
);
enqueueOrder(data, order);
emit SellEnqueued(order.orderId, order);
}
function sellHelper(
Data storage data,
SellParams calldata sellParams
) internal returns (address pairAddress, bool inverted) {
require(sellParams.amountIn != 0, 'OS24');
(pairAddress, inverted) = getPair(sellParams.tokenIn, sellParams.tokenOut);
require(!getSellDisabled(data, pairAddress), 'OS13');
// allocate gas refund
uint256 value = msg.value;
if (sellParams.wrapUnwrap && sellParams.tokenIn == TokenShares.WETH_ADDRESS) {
value = msg.value.sub(sellParams.amountIn, 'OS1E');
}
allocateGasRefund(data, value, sellParams.gasLimit);
}
struct BuyParams {
address tokenIn;
address tokenOut;
uint256 amountInMax;
uint256 amountOut;
bool wrapUnwrap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function buy(Data storage data, BuyParams calldata buyParams, TokenShares.Data storage tokenShares) external {
checkOrderParams(
buyParams.to,
buyParams.gasLimit,
buyParams.submitDeadline,
BUY_ORDER_BASE_COST + getTransferGasCost(buyParams.tokenIn)
);
require(buyParams.amountOut != 0, 'OS23');
(address pairAddress, bool inverted) = getPair(buyParams.tokenIn, buyParams.tokenOut);
require(!getBuyDisabled(data, pairAddress), 'OS49');
uint256 value = msg.value;
// allocate gas refund
if (buyParams.tokenIn == TokenShares.WETH_ADDRESS && buyParams.wrapUnwrap) {
value = msg.value.sub(buyParams.amountInMax, 'OS1E');
}
allocateGasRefund(data, value, buyParams.gasLimit);
uint256 shares = tokenShares.amountToShares(buyParams.tokenIn, buyParams.amountInMax, buyParams.wrapUnwrap);
(uint256 priceAccumulator, uint256 timestamp) = ITwapOracle(ITwapPair(pairAddress).oracle()).getPriceInfo();
Order memory order = Order(
0,
OrderType.Buy,
inverted,
timestamp + DELAY, // validAfterTimestamp
buyParams.wrapUnwrap,
timestamp,
buyParams.gasLimit,
data.gasPrice,
0, // liquidity
shares,
buyParams.amountOut,
buyParams.tokenIn,
buyParams.tokenOut,
buyParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
priceAccumulator,
buyParams.amountInMax,
0 // amountLimit1
);
enqueueOrder(data, order);
emit BuyEnqueued(order.orderId, order);
}
function checkOrderParams(address to, uint256 gasLimit, uint32 submitDeadline, uint256 minGasLimit) private view {
require(submitDeadline >= block.timestamp, 'OS04');
require(gasLimit <= MAX_GAS_LIMIT, 'OS3E');
require(gasLimit >= minGasLimit, 'OS3D');
require(to != address(0), 'OS26');
}
function allocateGasRefund(Data storage data, uint256 value, uint256 gasLimit) private returns (uint256 futureFee) {
futureFee = data.gasPrice.mul(gasLimit);
require(value >= futureFee, 'OS1E');
if (value > futureFee) {
TransferHelper.safeTransferETH(msg.sender, value - futureFee, getTransferGasCost(NATIVE_CURRENCY_SENTINEL));
}
}
function updateGasPrice(Data storage data, uint256 gasUsed) external {
uint256 scale = Math.min(gasUsed, MAX_GAS_PRICE_IMPACT);
data.gasPrice = data.gasPrice.mul(GAS_PRICE_INERTIA.sub(scale)).add(tx.gasprice.mul(scale)).div(
GAS_PRICE_INERTIA
);
}
function refundLiquidity(address pair, address to, uint256 liquidity, bytes4 selector) internal returns (bool) {
if (liquidity == 0) {
return true;
}
(bool success, bytes memory data) = address(this).call{ gas: PAIR_TRANSFER_COST }(
abi.encodeWithSelector(selector, pair, to, liquidity, false)
);
if (!success) {
emit RefundFailed(to, pair, liquidity, data);
}
return success;
}
function dequeueOrder(Data storage data, uint256 orderId) internal {
++data.lastProcessedOrderId;
require(orderId == data.lastProcessedOrderId, 'OS72');
}
function forgetOrder(Data storage data, uint256 orderId) internal {
delete data.orderQueue[orderId];
}
function forgetLastProcessedOrder(Data storage data) internal {
delete data.orderQueue[data.lastProcessedOrderId];
}
function getOrderDigest(Order memory order) internal pure returns (bytes32) {
// Used to avoid the 'stack too deep' error.
bytes memory partialOrderData = abi.encodePacked(
order.orderId,
order.orderType,
order.inverted,
order.validAfterTimestamp,
order.unwrap,
order.timestamp,
order.gasLimit,
order.gasPrice,
order.liquidity,
order.value0,
order.value1,
order.token0,
order.token1,
order.to
);
return
keccak256(
abi.encodePacked(
partialOrderData,
order.minSwapPrice,
order.maxSwapPrice,
order.swap,
order.priceAccumulator,
order.amountLimit0,
order.amountLimit1
)
);
}
function verifyOrder(Data storage data, Order memory order) external view {
require(getOrderDigest(order) == data.orderQueue[order.orderId], 'OS71');
}
// constant mapping for transferGasCost
/**
* @dev This function should either return a default value != 0 or revert.
*/
function getTransferGasCost(address token) internal pure returns (uint256) {
if (token == NATIVE_CURRENCY_SENTINEL) return ETHER_TRANSFER_CALL_COST;
if (token == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) return 31000;
if (token == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 42000;
if (token == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return 66000;
if (token == 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599) return 34000;
if (token == 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B) return 31000;
if (token == 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2) return 31000;
if (token == 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84) return 68000;
if (token == 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0) return 31000;
if (token == 0xD33526068D116cE69F19A9ee46F0bd304F21A51f) return 31000;
if (token == 0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2) return 40000;
if (token == 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32) return 149000;
if (token == 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2) return 34000;
if (token == 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984) return 37000;
if (token == 0x514910771AF9Ca656af840dff83E8264EcF986CA) return 32000;
if (token == 0x3c3a81e81dc49A522A592e7622A7E711c06bf354) return 34000;
return 60000;
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
int256 private constant _INT256_MIN = -2 ** 255;
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'SM4E');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = sub(x, y, 'SM12');
}
function sub(uint256 x, uint256 y, string memory message) internal pure returns (uint256 z) {
require((z = x - y) <= x, message);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'SM2A');
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SM43');
return a / b;
}
function ceil_div(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = div(a, b);
if (a != mul(b, c)) {
return add(c, 1);
}
}
function toUint32(uint256 n) internal pure returns (uint32) {
require(n <= type(uint32).max, 'SM50');
return uint32(n);
}
function toUint64(uint256 n) internal pure returns (uint64) {
require(n <= type(uint64).max, 'SM54');
return uint64(n);
}
function toUint112(uint256 n) internal pure returns (uint112) {
require(n <= type(uint112).max, 'SM51');
return uint112(n);
}
function toInt256(uint256 unsigned) internal pure returns (int256 signed) {
require(unsigned <= uint256(type(int256).max), 'SM34');
signed = int256(unsigned);
}
// int256
function add(int256 a, int256 b) internal pure returns (int256 c) {
c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), 'SM4D');
}
function sub(int256 a, int256 b) internal pure returns (int256 c) {
c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), 'SM11');
}
function mul(int256 a, int256 b) internal pure returns (int256 c) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), 'SM29');
c = a * b;
require(c / a == b, 'SM29');
}
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, 'SM43');
require(!(b == -1 && a == _INT256_MIN), 'SM42');
return a / b;
}
function neg_floor_div(int256 a, int256 b) internal pure returns (int256 c) {
c = div(a, b);
if ((a < 0 && b > 0) || (a >= 0 && b < 0)) {
if (a != mul(b, c)) {
c = sub(c, 1);
}
}
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import '../interfaces/IERC20.sol';
import '../interfaces/IWETH.sol';
import './SafeMath.sol';
import './TransferHelper.sol';
library TokenShares {
using SafeMath for uint256;
using TransferHelper for address;
uint256 private constant PRECISION = 10 ** 18;
uint256 private constant TOLERANCE = 10 ** 18 + 10 ** 16;
uint256 private constant TOTAL_SHARES_PRECISION = 10 ** 18;
event UnwrapFailed(address to, uint256 amount);
// represents wrapped native currency (WETH or WMATIC)
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
struct Data {
mapping(address => uint256) totalShares;
}
function sharesToAmount(
Data storage data,
address token,
uint256 share,
uint256 amountLimit,
address refundTo
) external returns (uint256) {
if (share == 0) {
return 0;
}
if (token == WETH_ADDRESS || isNonRebasing(token)) {
return share;
}
uint256 totalTokenShares = data.totalShares[token];
require(totalTokenShares >= share, 'TS3A');
uint256 balance = IERC20(token).balanceOf(address(this));
uint256 value = balance.mul(share).div(totalTokenShares);
data.totalShares[token] = totalTokenShares.sub(share);
if (amountLimit > 0) {
uint256 amountLimitWithTolerance = amountLimit.mul(TOLERANCE).div(PRECISION);
if (value > amountLimitWithTolerance) {
TransferHelper.safeTransfer(token, refundTo, value.sub(amountLimitWithTolerance));
return amountLimitWithTolerance;
}
}
return value;
}
function amountToShares(Data storage data, address token, uint256 amount, bool wrap) external returns (uint256) {
if (amount == 0) {
return 0;
}
if (token == WETH_ADDRESS) {
if (wrap) {
require(msg.value >= amount, 'TS03');
IWETH(token).deposit{ value: amount }();
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
return amount;
} else if (isNonRebasing(token)) {
token.safeTransferFrom(msg.sender, address(this), amount);
return amount;
} else {
uint256 balanceBefore = IERC20(token).balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), amount);
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
return amountToSharesHelper(data, token, balanceBefore, balanceAfter);
}
}
function amountToSharesWithoutTransfer(
Data storage data,
address token,
uint256 amount,
bool wrap
) external returns (uint256) {
if (token == WETH_ADDRESS) {
if (wrap) {
// require(msg.value >= amount, 'TS03'); // Duplicate check in TwapRelayer.sell
IWETH(token).deposit{ value: amount }();
}
return amount;
} else if (isNonRebasing(token)) {
return amount;
} else {
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
uint256 balanceBefore = balanceAfter.sub(amount);
return amountToSharesHelper(data, token, balanceBefore, balanceAfter);
}
}
function amountToSharesHelper(
Data storage data,
address token,
uint256 balanceBefore,
uint256 balanceAfter
) internal returns (uint256) {
uint256 totalTokenShares = data.totalShares[token];
require(balanceBefore > 0 || totalTokenShares == 0, 'TS30');
require(balanceAfter > balanceBefore, 'TS2C');
if (balanceBefore > 0) {
if (totalTokenShares == 0) {
totalTokenShares = balanceBefore.mul(TOTAL_SHARES_PRECISION);
}
uint256 newShares = totalTokenShares.mul(balanceAfter).div(balanceBefore);
require(balanceAfter < type(uint256).max.div(newShares), 'TS73'); // to prevent overflow at execution
data.totalShares[token] = newShares;
return newShares - totalTokenShares;
} else {
totalTokenShares = balanceAfter.mul(TOTAL_SHARES_PRECISION);
require(totalTokenShares < type(uint256).max.div(totalTokenShares), 'TS73'); // to prevent overflow at execution
data.totalShares[token] = totalTokenShares;
return totalTokenShares;
}
}
function onUnwrapFailed(address to, uint256 amount) external {
emit UnwrapFailed(to, amount);
IWETH(WETH_ADDRESS).deposit{ value: amount }();
TransferHelper.safeTransfer(WETH_ADDRESS, to, amount);
}
// constant mapping for nonRebasingToken
function isNonRebasing(address token) internal pure returns (bool) {
if (token == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) return true;
if (token == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return true;
if (token == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return true;
if (token == 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599) return true;
if (token == 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B) return true;
if (token == 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2) return true;
if (token == 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0) return true;
if (token == 0xD33526068D116cE69F19A9ee46F0bd304F21A51f) return true;
if (token == 0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2) return true;
if (token == 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32) return true;
if (token == 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2) return true;
if (token == 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984) return true;
if (token == 0x514910771AF9Ca656af840dff83E8264EcF986CA) return true;
if (token == 0x3c3a81e81dc49A522A592e7622A7E711c06bf354) return true;
return false;
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint256 value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH4B');
}
function safeTransfer(address token, address to, uint256 value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH05');
}
function safeTransferFrom(address token, address from, address to, uint256 value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH0E');
}
function safeTransferETH(address to, uint256 value, uint256 gasLimit) internal {
(bool success, ) = to.call{ value: value, gas: gasLimit }('');
require(success, 'TH3F');
}
function transferETH(address to, uint256 value, uint256 gasLimit) internal returns (bool success) {
(success, ) = to.call{ value: value, gas: gasLimit }('');
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import '../interfaces/ITwapPair.sol';
import '../interfaces/IWETH.sol';
import './Orders.sol';
library WithdrawHelper {
using SafeMath for uint256;
function _transferToken(uint256 balanceBefore, address token, address to) internal {
uint256 tokenAmount = IERC20(token).balanceOf(address(this)).sub(balanceBefore);
TransferHelper.safeTransfer(token, to, tokenAmount);
}
// unwraps wrapped native currency
function _unwrapWeth(uint256 ethAmount, address weth, address to, uint256 gasLimit) internal returns (bool) {
IWETH(weth).withdraw(ethAmount);
(bool success, ) = to.call{ value: ethAmount, gas: gasLimit }('');
return success;
}
function withdrawAndUnwrap(
address token0,
address token1,
address pair,
address weth,
address to,
uint256 gasLimit
) external returns (bool, uint256, uint256, uint256) {
bool isToken0Weth = token0 == weth;
address otherToken = isToken0Weth ? token1 : token0;
uint256 balanceBefore = IERC20(otherToken).balanceOf(address(this));
(uint256 amount0, uint256 amount1) = ITwapPair(pair).burn(address(this));
_transferToken(balanceBefore, otherToken, to);
bool success = _unwrapWeth(isToken0Weth ? amount0 : amount1, weth, to, gasLimit);
return (success, isToken0Weth ? amount0 : amount1, amount0, amount1);
}
}
File 9 of 11: TwapOracleV3
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @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
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0 <0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
/// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool
/// @param pool Address of the pool that we want to observe
/// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means
/// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp
/// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp
function consult(address pool, uint32 secondsAgo)
internal
view
returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
{
require(secondsAgo != 0, 'BP');
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
secondsAgos[1] = 0;
(int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =
IUniswapV3Pool(pool).observe(secondsAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
uint160 secondsPerLiquidityCumulativesDelta =
secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];
arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgo);
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgo != 0)) arithmeticMeanTick--;
// We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128
uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));
}
/// @notice Given a tick and a token amount, calculates the amount of token received in exchange
/// @param tick Tick value used to calculate the quote
/// @param baseAmount Amount of token to be converted
/// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
/// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
/// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
) internal pure returns (uint256 quoteAmount) {
uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
// Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
if (sqrtRatioX96 <= type(uint128).max) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
: FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
} else {
uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
: FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
}
}
/// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation
/// @param pool Address of Uniswap V3 pool that we want to observe
/// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool
function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {
(, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
require(observationCardinality > 0, 'NI');
(uint32 observationTimestamp, , , bool initialized) =
IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);
// The next index might not be initialized if the cardinality is in the process of increasing
// In this case the oldest observation is always in index 0
if (!initialized) {
(observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);
}
secondsAgo = uint32(block.timestamp) - observationTimestamp;
}
/// @notice Given a pool, it returns the tick value as of the start of the current block
/// @param pool Address of Uniswap V3 pool
/// @return The tick that the pool was in at the start of the current block
function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {
(, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
// 2 observations are needed to reliably calculate the block starting tick
require(observationCardinality > 1, 'NEO');
// If the latest observation occurred in the past, then no tick-changing trades have happened in this block
// therefore the tick in `slot0` is the same as at the beginning of the current block.
// We don't need to check if this observation is initialized - it is guaranteed to be.
(uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) =
IUniswapV3Pool(pool).observations(observationIndex);
if (observationTimestamp != uint32(block.timestamp)) {
return (tick, IUniswapV3Pool(pool).liquidity());
}
uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;
(
uint32 prevObservationTimestamp,
int56 prevTickCumulative,
uint160 prevSecondsPerLiquidityCumulativeX128,
bool prevInitialized
) = IUniswapV3Pool(pool).observations(prevIndex);
require(prevInitialized, 'ONI');
uint32 delta = observationTimestamp - prevObservationTimestamp;
tick = int24((tickCumulative - prevTickCumulative) / delta);
uint128 liquidity =
uint128(
(uint192(delta) * type(uint160).max) /
(uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)
);
return (tick, liquidity);
}
/// @notice Information for calculating a weighted arithmetic mean tick
struct WeightedTickData {
int24 tick;
uint128 weight;
}
/// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick
/// @param weightedTickData An array of ticks and weights
/// @return weightedArithmeticMeanTick The weighted arithmetic mean tick
/// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,
/// extreme care must be taken to ensure that ticks are comparable (including decimal differences).
/// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.
function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)
internal
pure
returns (int24 weightedArithmeticMeanTick)
{
// Accumulates the sum of products between each tick and its weight
int256 numerator;
// Accumulates the sum of the weights
uint256 denominator;
// Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic
for (uint256 i; i < weightedTickData.length; i++) {
numerator += weightedTickData[i].tick * int256(weightedTickData[i].weight);
denominator += weightedTickData[i].weight;
}
weightedArithmeticMeanTick = int24(numerator / int256(denominator));
// Always round to negative infinity
if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;
}
/// @notice Returns the "synthetic" tick which represents the price of the first entry in `tokens` in terms of the last
/// @dev Useful for calculating relative prices along routes.
/// @dev There must be one tick for each pairwise set of tokens.
/// @param tokens The token contract addresses
/// @param ticks The ticks, representing the price of each token pair in `tokens`
/// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`
function getChainedPrice(address[] memory tokens, int24[] memory ticks)
internal
pure
returns (int256 syntheticTick)
{
require(tokens.length - 1 == ticks.length, 'DL');
for (uint256 i = 1; i <= ticks.length; i++) {
// check the tokens for address sort order, then accumulate the
// ticks into the running synthetic tick, ensuring that intermediate tokens "cancel out"
tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
interface ITwapOracle {
event OwnerSet(address owner);
event UniswapPairSet(address uniswapPair);
function decimalsConverter() external view returns (int256);
function xDecimals() external view returns (uint8);
function yDecimals() external view returns (uint8);
function owner() external view returns (address);
function uniswapPair() external view returns (address);
function getPriceInfo() external view returns (uint256 priceAccumulator, uint256 priceTimestamp);
function getSpotPrice() external view returns (uint256);
function getAveragePrice(uint256 priceAccumulator, uint256 priceTimestamp) external view returns (uint256);
function setOwner(address _owner) external;
function setUniswapPair(address _uniswapPair) external;
function tradeX(
uint256 xAfter,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 yAfter);
function tradeY(
uint256 yAfter,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 xAfter);
function depositTradeXIn(
uint256 xLeft,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 xIn);
function depositTradeYIn(
uint256 yLeft,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 yIn);
function getSwapAmount0Out(
uint256 swapFee,
uint256 amount1In,
bytes calldata data
) external view returns (uint256 amount0Out);
function getSwapAmount1Out(
uint256 swapFee,
uint256 amount0In,
bytes calldata data
) external view returns (uint256 amount1Out);
function getSwapAmountInMaxOut(
bool inverse,
uint256 swapFee,
uint256 _amountOut,
bytes calldata data
) external view returns (uint256 amountIn, uint256 amountOut);
function getSwapAmountInMinOut(
bool inverse,
uint256 swapFee,
uint256 _amountOut,
bytes calldata data
) external view returns (uint256 amountIn, uint256 amountOut);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import './ITwapOracle.sol';
interface ITwapOracleV3 is ITwapOracle {
event TwapIntervalSet(uint32 interval);
function setTwapInterval(uint32 _interval) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
int256 private constant _INT256_MIN = -2**255;
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'SM4E');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = sub(x, y, 'SM12');
}
function sub(
uint256 x,
uint256 y,
string memory message
) internal pure returns (uint256 z) {
require((z = x - y) <= x, message);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'SM2A');
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SM43');
return a / b;
}
function ceil_div(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = div(a, b);
if (a != mul(b, c)) {
return add(c, 1);
}
}
function toUint32(uint256 n) internal pure returns (uint32) {
require(n <= type(uint32).max, 'SM50');
return uint32(n);
}
function toUint64(uint256 n) internal pure returns (uint64) {
require(n <= type(uint64).max, 'SM54');
return uint64(n);
}
function toUint112(uint256 n) internal pure returns (uint112) {
require(n <= type(uint112).max, 'SM51');
return uint112(n);
}
function toInt256(uint256 unsigned) internal pure returns (int256 signed) {
require(unsigned <= uint256(type(int256).max), 'SM34');
signed = int256(unsigned);
}
// int256
function add(int256 a, int256 b) internal pure returns (int256 c) {
c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), 'SM4D');
}
function sub(int256 a, int256 b) internal pure returns (int256 c) {
c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), 'SM11');
}
function mul(int256 a, int256 b) internal pure returns (int256 c) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), 'SM29');
c = a * b;
require(c / a == b, 'SM29');
}
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, 'SM43');
require(!(b == -1 && a == _INT256_MIN), 'SM42');
return a / b;
}
function neg_floor_div(int256 a, int256 b) internal pure returns (int256 c) {
c = div(a, b);
if ((a < 0 && b > 0) || (a >= 0 && b < 0)) {
if (a != mul(b, c)) {
c = sub(c, 1);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.6;
import './interfaces/ITwapOracleV3.sol';
import './interfaces/IERC20.sol';
import './libraries/SafeMath.sol';
import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol';
contract TwapOracleV3 is ITwapOracleV3 {
using SafeMath for uint256;
using SafeMath for int256;
uint256 private constant PRECISION = 10**18;
uint8 public immutable override xDecimals;
uint8 public immutable override yDecimals;
uint32 public twapInterval;
int256 public immutable override decimalsConverter;
address public override owner;
address public override uniswapPair;
constructor(uint8 _xDecimals, uint8 _yDecimals) {
require(_xDecimals <= 75 && _yDecimals <= 75, 'TO4F');
if (_yDecimals > _xDecimals) {
require(_yDecimals - _xDecimals <= 18, 'TO47');
} else {
require(_xDecimals - _yDecimals <= 18, 'TO47');
}
owner = msg.sender;
xDecimals = _xDecimals;
yDecimals = _yDecimals;
decimalsConverter = (10**(18 + _xDecimals - _yDecimals)).toInt256();
emit OwnerSet(msg.sender);
}
function isContract(address addr) private view returns (bool) {
uint256 size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
function setOwner(address _owner) external override {
require(msg.sender == owner, 'TO00');
require(_owner != address(0), 'TO02');
require(_owner != owner, 'TO01');
owner = _owner;
emit OwnerSet(_owner);
}
function setTwapInterval(uint32 _interval) external override {
require(msg.sender == owner, 'TO00');
require(_interval > 0, 'Interval should be larger than 0');
twapInterval = _interval;
emit TwapIntervalSet(_interval);
}
function setUniswapPair(address _uniswapPair) external override {
require(msg.sender == owner, 'TO00');
require(_uniswapPair != uniswapPair, 'TO01');
require(_uniswapPair != address(0), 'TO02');
require(isContract(_uniswapPair), 'TO0B');
uniswapPair = _uniswapPair;
IUniswapV3Pool pool = IUniswapV3Pool(_uniswapPair);
require(IERC20(pool.token0()).decimals() == xDecimals && IERC20(pool.token1()).decimals() == yDecimals, 'TO45');
require(pool.liquidity() != 0, 'TO1F');
emit UniswapPairSet(_uniswapPair);
}
function getPriceInfo() public view override returns (uint256 priceAccumulator, uint256 priceTimestamp) {
return (0, block.timestamp);
}
function decodePriceInfo(bytes memory data) internal pure returns (uint256 price) {
assembly {
price := mload(add(data, 32))
}
}
function getSpotPrice() external view override returns (uint256) {
(uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(uniswapPair).slot0();
if (sqrtPriceX96 <= type(uint128).max) {
uint256 priceX192 = uint256(sqrtPriceX96) * sqrtPriceX96;
return FullMath.mulDiv(priceX192, uint256(decimalsConverter), 2**192);
} else {
uint256 priceX128 = FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, 2**64);
return FullMath.mulDiv(priceX128, uint256(decimalsConverter), 2**128);
}
}
function getAveragePrice(uint256, uint256) public view override returns (uint256) {
uint32 secondsAgo = twapInterval;
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
(int56[] memory tickCumulatives, ) = IUniswapV3Pool(uniswapPair).observe(secondsAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
int24 arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgo);
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgo != 0)) --arithmeticMeanTick;
uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(arithmeticMeanTick);
if (sqrtRatioX96 <= type(uint128).max) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
return FullMath.mulDiv(ratioX192, uint256(decimalsConverter), 2**192);
} else {
uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 2**64);
return FullMath.mulDiv(ratioX128, uint256(decimalsConverter), 2**128);
}
}
function tradeX(
uint256 xAfter,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view override returns (uint256 yAfter) {
int256 xAfterInt = xAfter.toInt256();
int256 xBeforeInt = xBefore.toInt256();
int256 yBeforeInt = yBefore.toInt256();
int256 averagePriceInt = decodePriceInfo(data).toInt256();
int256 yTradedInt = xAfterInt.sub(xBeforeInt).mul(averagePriceInt);
// yAfter = yBefore - yTraded = yBefore - ((xAfter - xBefore) * price)
int256 yAfterInt = yBeforeInt.sub(yTradedInt.neg_floor_div(decimalsConverter));
require(yAfterInt >= 0, 'TO27');
yAfter = uint256(yAfterInt);
}
function tradeY(
uint256 yAfter,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view override returns (uint256 xAfter) {
int256 yAfterInt = yAfter.toInt256();
int256 xBeforeInt = xBefore.toInt256();
int256 yBeforeInt = yBefore.toInt256();
int256 averagePriceInt = decodePriceInfo(data).toInt256();
int256 xTradedInt = yAfterInt.sub(yBeforeInt).mul(decimalsConverter);
// xAfter = xBefore - xTraded = xBefore - ((yAfter - yBefore) * price)
int256 xAfterInt = xBeforeInt.sub(xTradedInt.neg_floor_div(averagePriceInt));
require(xAfterInt >= 0, 'TO28');
xAfter = uint256(xAfterInt);
}
function depositTradeXIn(
uint256 xLeft,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view override returns (uint256) {
if (xBefore == 0 || yBefore == 0) {
return 0;
}
// ratio after swap = ratio after second mint
// (xBefore + xIn) / (yBefore - xIn * price) = (xBefore + xLeft) / yBefore
// xIn = xLeft * yBefore / (price * (xLeft + xBefore) + yBefore)
uint256 price = decodePriceInfo(data);
uint256 numerator = xLeft.mul(yBefore);
uint256 denominator = price.mul(xLeft.add(xBefore)).add(yBefore.mul(uint256(decimalsConverter)));
uint256 xIn = numerator.mul(uint256(decimalsConverter)).div(denominator);
// Don't swap when numbers are too large. This should actually never happen.
if (xIn.mul(price).div(uint256(decimalsConverter)) >= yBefore || xIn >= xLeft) {
return 0;
}
return xIn;
}
function depositTradeYIn(
uint256 yLeft,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view override returns (uint256) {
if (xBefore == 0 || yBefore == 0) {
return 0;
}
// ratio after swap = ratio after second mint
// (xBefore - yIn / price) / (yBefore + yIn) = xBefore / (yBefore + yLeft)
// yIn = price * xBefore * yLeft / (price * xBefore + yLeft + yBefore)
uint256 price = decodePriceInfo(data);
uint256 numerator = price.mul(xBefore).mul(yLeft);
uint256 denominator = price.mul(xBefore).add(yLeft.add(yBefore).mul(uint256(decimalsConverter)));
uint256 yIn = numerator.div(denominator);
// Don't swap when numbers are too large. This should actually never happen.
if (yIn.mul(uint256(decimalsConverter)).div(price) >= xBefore || yIn >= yLeft) {
return 0;
}
return yIn;
}
function getSwapAmount0Out(
uint256 swapFee,
uint256 amount1In,
bytes calldata data
) public view override returns (uint256 amount0Out) {
uint256 fee = amount1In.mul(swapFee).div(PRECISION);
uint256 price = decodePriceInfo(data);
amount0Out = amount1In.sub(fee).mul(uint256(decimalsConverter)).div(price);
}
function getSwapAmount1Out(
uint256 swapFee,
uint256 amount0In,
bytes calldata data
) public view override returns (uint256 amount1Out) {
uint256 fee = amount0In.mul(swapFee).div(PRECISION);
uint256 price = decodePriceInfo(data);
amount1Out = amount0In.sub(fee).mul(price).div(uint256(decimalsConverter));
}
function getSwapAmount0InMax(
uint256 swapFee,
uint256 amount1Out,
bytes calldata data
) internal view returns (uint256 amount0In) {
uint256 price = decodePriceInfo(data);
amount0In = amount1Out.mul(uint256(decimalsConverter)).mul(PRECISION).ceil_div(
price.mul(PRECISION.sub(swapFee))
);
}
function getSwapAmount0InMin(
uint256 swapFee,
uint256 amount1Out,
bytes calldata data
) internal view returns (uint256 amount0In) {
uint256 price = decodePriceInfo(data);
amount0In = amount1Out.mul(uint256(decimalsConverter)).div(price).mul(PRECISION).div(PRECISION.sub(swapFee));
}
function getSwapAmount1InMax(
uint256 swapFee,
uint256 amount0Out,
bytes calldata data
) internal view returns (uint256 amount1In) {
uint256 price = decodePriceInfo(data);
amount1In = amount0Out.mul(price).mul(PRECISION).ceil_div(
uint256(decimalsConverter).mul(PRECISION.sub(swapFee))
);
}
function getSwapAmount1InMin(
uint256 swapFee,
uint256 amount0Out,
bytes calldata data
) internal view returns (uint256 amount1In) {
uint256 price = decodePriceInfo(data);
amount1In = amount0Out.mul(price).div(uint256(decimalsConverter)).mul(PRECISION).div(PRECISION.sub(swapFee));
}
function getSwapAmountInMaxOut(
bool inverse,
uint256 swapFee,
uint256 _amountOut,
bytes calldata data
) external view override returns (uint256 amountIn, uint256 amountOut) {
amountIn = inverse
? getSwapAmount1InMax(swapFee, _amountOut, data)
: getSwapAmount0InMax(swapFee, _amountOut, data);
amountOut = inverse ? getSwapAmount0Out(swapFee, amountIn, data) : getSwapAmount1Out(swapFee, amountIn, data);
}
function getSwapAmountInMinOut(
bool inverse,
uint256 swapFee,
uint256 _amountOut,
bytes calldata data
) external view override returns (uint256 amountIn, uint256 amountOut) {
amountIn = inverse
? getSwapAmount1InMin(swapFee, _amountOut, data)
: getSwapAmount0InMin(swapFee, _amountOut, data);
amountOut = inverse ? getSwapAmount0Out(swapFee, amountIn, data) : getSwapAmount1Out(swapFee, amountIn, data);
}
}
File 10 of 11: TokenShares
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
int256 private constant _INT256_MIN = -2 ** 255;
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'SM4E');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = sub(x, y, 'SM12');
}
function sub(uint256 x, uint256 y, string memory message) internal pure returns (uint256 z) {
require((z = x - y) <= x, message);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'SM2A');
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SM43');
return a / b;
}
function ceil_div(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = div(a, b);
if (a != mul(b, c)) {
return add(c, 1);
}
}
function toUint32(uint256 n) internal pure returns (uint32) {
require(n <= type(uint32).max, 'SM50');
return uint32(n);
}
function toUint64(uint256 n) internal pure returns (uint64) {
require(n <= type(uint64).max, 'SM54');
return uint64(n);
}
function toUint112(uint256 n) internal pure returns (uint112) {
require(n <= type(uint112).max, 'SM51');
return uint112(n);
}
function toInt256(uint256 unsigned) internal pure returns (int256 signed) {
require(unsigned <= uint256(type(int256).max), 'SM34');
signed = int256(unsigned);
}
// int256
function add(int256 a, int256 b) internal pure returns (int256 c) {
c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), 'SM4D');
}
function sub(int256 a, int256 b) internal pure returns (int256 c) {
c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), 'SM11');
}
function mul(int256 a, int256 b) internal pure returns (int256 c) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), 'SM29');
c = a * b;
require(c / a == b, 'SM29');
}
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, 'SM43');
require(!(b == -1 && a == _INT256_MIN), 'SM42');
return a / b;
}
function neg_floor_div(int256 a, int256 b) internal pure returns (int256 c) {
c = div(a, b);
if ((a < 0 && b > 0) || (a >= 0 && b < 0)) {
if (a != mul(b, c)) {
c = sub(c, 1);
}
}
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import '../interfaces/IERC20.sol';
import '../interfaces/IWETH.sol';
import './SafeMath.sol';
import './TransferHelper.sol';
library TokenShares {
using SafeMath for uint256;
using TransferHelper for address;
uint256 private constant PRECISION = 10 ** 18;
uint256 private constant TOLERANCE = 10 ** 18 + 10 ** 16;
uint256 private constant TOTAL_SHARES_PRECISION = 10 ** 18;
event UnwrapFailed(address to, uint256 amount);
// represents wrapped native currency (WETH or WMATIC)
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
struct Data {
mapping(address => uint256) totalShares;
}
function sharesToAmount(
Data storage data,
address token,
uint256 share,
uint256 amountLimit,
address refundTo
) external returns (uint256) {
if (share == 0) {
return 0;
}
if (token == WETH_ADDRESS || isNonRebasing(token)) {
return share;
}
uint256 totalTokenShares = data.totalShares[token];
require(totalTokenShares >= share, 'TS3A');
uint256 balance = IERC20(token).balanceOf(address(this));
uint256 value = balance.mul(share).div(totalTokenShares);
data.totalShares[token] = totalTokenShares.sub(share);
if (amountLimit > 0) {
uint256 amountLimitWithTolerance = amountLimit.mul(TOLERANCE).div(PRECISION);
if (value > amountLimitWithTolerance) {
TransferHelper.safeTransfer(token, refundTo, value.sub(amountLimitWithTolerance));
return amountLimitWithTolerance;
}
}
return value;
}
function amountToShares(Data storage data, address token, uint256 amount, bool wrap) external returns (uint256) {
if (amount == 0) {
return 0;
}
if (token == WETH_ADDRESS) {
if (wrap) {
require(msg.value >= amount, 'TS03');
IWETH(token).deposit{ value: amount }();
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
return amount;
} else if (isNonRebasing(token)) {
token.safeTransferFrom(msg.sender, address(this), amount);
return amount;
} else {
uint256 balanceBefore = IERC20(token).balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), amount);
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
return amountToSharesHelper(data, token, balanceBefore, balanceAfter);
}
}
function amountToSharesWithoutTransfer(
Data storage data,
address token,
uint256 amount,
bool wrap
) external returns (uint256) {
if (token == WETH_ADDRESS) {
if (wrap) {
// require(msg.value >= amount, 'TS03'); // Duplicate check in TwapRelayer.sell
IWETH(token).deposit{ value: amount }();
}
return amount;
} else if (isNonRebasing(token)) {
return amount;
} else {
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
uint256 balanceBefore = balanceAfter.sub(amount);
return amountToSharesHelper(data, token, balanceBefore, balanceAfter);
}
}
function amountToSharesHelper(
Data storage data,
address token,
uint256 balanceBefore,
uint256 balanceAfter
) internal returns (uint256) {
uint256 totalTokenShares = data.totalShares[token];
require(balanceBefore > 0 || totalTokenShares == 0, 'TS30');
require(balanceAfter > balanceBefore, 'TS2C');
if (balanceBefore > 0) {
if (totalTokenShares == 0) {
totalTokenShares = balanceBefore.mul(TOTAL_SHARES_PRECISION);
}
uint256 newShares = totalTokenShares.mul(balanceAfter).div(balanceBefore);
require(balanceAfter < type(uint256).max.div(newShares), 'TS73'); // to prevent overflow at execution
data.totalShares[token] = newShares;
return newShares - totalTokenShares;
} else {
totalTokenShares = balanceAfter.mul(TOTAL_SHARES_PRECISION);
require(totalTokenShares < type(uint256).max.div(totalTokenShares), 'TS73'); // to prevent overflow at execution
data.totalShares[token] = totalTokenShares;
return totalTokenShares;
}
}
function onUnwrapFailed(address to, uint256 amount) external {
emit UnwrapFailed(to, amount);
IWETH(WETH_ADDRESS).deposit{ value: amount }();
TransferHelper.safeTransfer(WETH_ADDRESS, to, amount);
}
// constant mapping for nonRebasingToken
function isNonRebasing(address token) internal pure returns (bool) {
if (token == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) return true;
if (token == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return true;
if (token == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return true;
if (token == 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599) return true;
if (token == 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B) return true;
if (token == 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2) return true;
if (token == 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0) return true;
if (token == 0xD33526068D116cE69F19A9ee46F0bd304F21A51f) return true;
if (token == 0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2) return true;
if (token == 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32) return true;
if (token == 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2) return true;
if (token == 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984) return true;
if (token == 0x514910771AF9Ca656af840dff83E8264EcF986CA) return true;
if (token == 0x3c3a81e81dc49A522A592e7622A7E711c06bf354) return true;
return false;
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint256 value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH4B');
}
function safeTransfer(address token, address to, uint256 value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH05');
}
function safeTransferFrom(address token, address from, address to, uint256 value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH0E');
}
function safeTransferETH(address to, uint256 value, uint256 gasLimit) internal {
(bool success, ) = to.call{ value: value, gas: gasLimit }('');
require(success, 'TH3F');
}
function transferETH(address to, uint256 value, uint256 gasLimit) internal returns (bool success) {
(success, ) = to.call{ value: value, gas: gasLimit }('');
}
}
File 11 of 11: TwapRelayer
pragma solidity >=0.5.0;
// SPDX-License-Identifier: GPL-2.0-or-later
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
pragma solidity >=0.5.0;
// SPDX-License-Identifier: GPL-2.0-or-later
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @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
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
pragma solidity >=0.5.0;
// SPDX-License-Identifier: GPL-2.0-or-later
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
pragma solidity >=0.5.0;
// SPDX-License-Identifier: GPL-2.0-or-later
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
pragma solidity >=0.5.0;
// SPDX-License-Identifier: GPL-2.0-or-later
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
pragma solidity >=0.5.0;
// SPDX-License-Identifier: GPL-2.0-or-later
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
pragma solidity >=0.5.0;
// SPDX-License-Identifier: GPL-2.0-or-later
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
pragma solidity >=0.4.0 <0.8.0;
// SPDX-License-Identifier: MIT
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
pragma solidity >=0.5.0 <0.8.0;
// SPDX-License-Identifier: GPL-2.0-or-later
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
pragma solidity >=0.5.0 <0.8.0;
// SPDX-License-Identifier: GPL-2.0-or-later
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
/// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool
/// @param pool Address of the pool that we want to observe
/// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means
/// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp
/// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp
function consult(address pool, uint32 secondsAgo)
internal
view
returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
{
require(secondsAgo != 0, 'BP');
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
secondsAgos[1] = 0;
(int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =
IUniswapV3Pool(pool).observe(secondsAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
uint160 secondsPerLiquidityCumulativesDelta =
secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];
arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgo);
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgo != 0)) arithmeticMeanTick--;
// We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128
uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));
}
/// @notice Given a tick and a token amount, calculates the amount of token received in exchange
/// @param tick Tick value used to calculate the quote
/// @param baseAmount Amount of token to be converted
/// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
/// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
/// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
) internal pure returns (uint256 quoteAmount) {
uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
// Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
if (sqrtRatioX96 <= type(uint128).max) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
: FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
} else {
uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
: FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
}
}
/// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation
/// @param pool Address of Uniswap V3 pool that we want to observe
/// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool
function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {
(, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
require(observationCardinality > 0, 'NI');
(uint32 observationTimestamp, , , bool initialized) =
IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);
// The next index might not be initialized if the cardinality is in the process of increasing
// In this case the oldest observation is always in index 0
if (!initialized) {
(observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);
}
secondsAgo = uint32(block.timestamp) - observationTimestamp;
}
/// @notice Given a pool, it returns the tick value as of the start of the current block
/// @param pool Address of Uniswap V3 pool
/// @return The tick that the pool was in at the start of the current block
function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {
(, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
// 2 observations are needed to reliably calculate the block starting tick
require(observationCardinality > 1, 'NEO');
// If the latest observation occurred in the past, then no tick-changing trades have happened in this block
// therefore the tick in `slot0` is the same as at the beginning of the current block.
// We don't need to check if this observation is initialized - it is guaranteed to be.
(uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) =
IUniswapV3Pool(pool).observations(observationIndex);
if (observationTimestamp != uint32(block.timestamp)) {
return (tick, IUniswapV3Pool(pool).liquidity());
}
uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;
(
uint32 prevObservationTimestamp,
int56 prevTickCumulative,
uint160 prevSecondsPerLiquidityCumulativeX128,
bool prevInitialized
) = IUniswapV3Pool(pool).observations(prevIndex);
require(prevInitialized, 'ONI');
uint32 delta = observationTimestamp - prevObservationTimestamp;
tick = int24((tickCumulative - prevTickCumulative) / delta);
uint128 liquidity =
uint128(
(uint192(delta) * type(uint160).max) /
(uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)
);
return (tick, liquidity);
}
/// @notice Information for calculating a weighted arithmetic mean tick
struct WeightedTickData {
int24 tick;
uint128 weight;
}
/// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick
/// @param weightedTickData An array of ticks and weights
/// @return weightedArithmeticMeanTick The weighted arithmetic mean tick
/// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,
/// extreme care must be taken to ensure that ticks are comparable (including decimal differences).
/// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.
function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)
internal
pure
returns (int24 weightedArithmeticMeanTick)
{
// Accumulates the sum of products between each tick and its weight
int256 numerator;
// Accumulates the sum of the weights
uint256 denominator;
// Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic
for (uint256 i; i < weightedTickData.length; i++) {
numerator += weightedTickData[i].tick * int256(weightedTickData[i].weight);
denominator += weightedTickData[i].weight;
}
weightedArithmeticMeanTick = int24(numerator / int256(denominator));
// Always round to negative infinity
if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;
}
/// @notice Returns the "synthetic" tick which represents the price of the first entry in `tokens` in terms of the last
/// @dev Useful for calculating relative prices along routes.
/// @dev There must be one tick for each pairwise set of tokens.
/// @param tokens The token contract addresses
/// @param ticks The ticks, representing the price of each token pair in `tokens`
/// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`
function getChainedPrice(address[] memory tokens, int24[] memory ticks)
internal
pure
returns (int256 syntheticTick)
{
require(tokens.length - 1 == ticks.length, 'DL');
for (uint256 i = 1; i <= ticks.length; i++) {
// check the tokens for address sort order, then accumulate the
// ticks into the running synthetic tick, ensuring that intermediate tokens "cancel out"
tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];
}
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IReserves {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1);
function getFees() external view returns (uint256 fee0, uint256 fee1);
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import '../libraries/Orders.sol';
interface ITwapDelay {
event OrderExecuted(uint256 indexed id, bool indexed success, bytes data, uint256 gasSpent, uint256 ethRefunded);
event EthRefund(address indexed to, bool indexed success, uint256 value);
event OwnerSet(address owner);
event FactoryGovernorSet(address factoryGovernor);
event BotSet(address bot, bool isBot);
event DelaySet(uint256 delay);
event RelayerSet(address relayer);
event MaxGasLimitSet(uint256 maxGasLimit);
event GasPriceInertiaSet(uint256 gasPriceInertia);
event MaxGasPriceImpactSet(uint256 maxGasPriceImpact);
event TransferGasCostSet(address token, uint256 gasCost);
event ToleranceSet(address pair, uint16 amount);
event NonRebasingTokenSet(address token, bool isNonRebasing);
function factory() external view returns (address);
function factoryGovernor() external view returns (address);
function relayer() external view returns (address);
function owner() external view returns (address);
function isBot(address bot) external view returns (bool);
function getTolerance(address pair) external view returns (uint16);
function isNonRebasingToken(address token) external view returns (bool);
function gasPriceInertia() external view returns (uint256);
function gasPrice() external view returns (uint256);
function maxGasPriceImpact() external view returns (uint256);
function maxGasLimit() external view returns (uint256);
function delay() external view returns (uint256);
function totalShares(address token) external view returns (uint256);
function weth() external view returns (address);
function getTransferGasCost(address token) external pure returns (uint256);
function getDepositDisabled(address pair) external view returns (bool);
function getWithdrawDisabled(address pair) external view returns (bool);
function getBuyDisabled(address pair) external view returns (bool);
function getSellDisabled(address pair) external view returns (bool);
function getOrderStatus(uint256 orderId, uint256 validAfterTimestamp) external view returns (Orders.OrderStatus);
function setOrderTypesDisabled(address pair, Orders.OrderType[] calldata orderTypes, bool disabled) external;
function setOwner(address _owner) external;
function setFactoryGovernor(address _factoryGovernor) external;
function setBot(address _bot, bool _isBot) external;
function deposit(Orders.DepositParams memory depositParams) external payable returns (uint256 orderId);
function withdraw(Orders.WithdrawParams memory withdrawParams) external payable returns (uint256 orderId);
function sell(Orders.SellParams memory sellParams) external payable returns (uint256 orderId);
function relayerSell(Orders.SellParams memory sellParams) external payable returns (uint256 orderId);
function buy(Orders.BuyParams memory buyParams) external payable returns (uint256 orderId);
function execute(Orders.Order[] calldata orders) external payable;
function retryRefund(Orders.Order calldata order) external;
function cancelOrder(Orders.Order calldata order) external;
function syncPair(address token0, address token1) external returns (address pairAddress);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './IERC20.sol';
interface ITwapERC20 is IERC20 {
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface ITwapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
event OwnerSet(address owner);
function owner() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB, address oracle, address trader) external returns (address pair);
function setOwner(address) external;
function setMintFee(address tokenA, address tokenB, uint256 fee) external;
function setBurnFee(address tokenA, address tokenB, uint256 fee) external;
function setSwapFee(address tokenA, address tokenB, uint256 fee) external;
function setOracle(address tokenA, address tokenB, address oracle) external;
function setTrader(address tokenA, address tokenB, address trader) external;
function collect(address tokenA, address tokenB, address to) external;
function withdraw(address tokenA, address tokenB, uint256 amount, address to) external;
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface ITwapOracle {
event OwnerSet(address owner);
event UniswapPairSet(address uniswapPair);
function decimalsConverter() external view returns (int256);
function xDecimals() external view returns (uint8);
function yDecimals() external view returns (uint8);
function owner() external view returns (address);
function uniswapPair() external view returns (address);
function getPriceInfo() external view returns (uint256 priceAccumulator, uint256 priceTimestamp);
function getSpotPrice() external view returns (uint256);
function getAveragePrice(uint256 priceAccumulator, uint256 priceTimestamp) external view returns (uint256);
function setOwner(address _owner) external;
function setUniswapPair(address _uniswapPair) external;
function tradeX(
uint256 xAfter,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 yAfter);
function tradeY(
uint256 yAfter,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 xAfter);
function depositTradeXIn(
uint256 xLeft,
uint256 xBefore,
uint256 yBefore,
bytes calldata data
) external view returns (uint256 xIn);
function depositTradeYIn(
uint256 yLeft,
uint256 yBefore,
uint256 xBefore,
bytes calldata data
) external view returns (uint256 yIn);
function getSwapAmount0Out(
uint256 swapFee,
uint256 amount1In,
bytes calldata data
) external view returns (uint256 amount0Out);
function getSwapAmount1Out(
uint256 swapFee,
uint256 amount0In,
bytes calldata data
) external view returns (uint256 amount1Out);
function getSwapAmountInMaxOut(
bool inverse,
uint256 swapFee,
uint256 _amountOut,
bytes calldata data
) external view returns (uint256 amountIn, uint256 amountOut);
function getSwapAmountInMinOut(
bool inverse,
uint256 swapFee,
uint256 _amountOut,
bytes calldata data
) external view returns (uint256 amountIn, uint256 amountOut);
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './ITwapOracle.sol';
interface ITwapOracleV3 is ITwapOracle {
event TwapIntervalSet(uint32 interval);
function setTwapInterval(uint32 _interval) external;
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './ITwapERC20.sol';
import './IReserves.sol';
interface ITwapPair is ITwapERC20, IReserves {
event Mint(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 liquidityOut, address indexed to);
event Burn(address indexed sender, uint256 amount0Out, uint256 amount1Out, uint256 liquidityIn, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event SetMintFee(uint256 fee);
event SetBurnFee(uint256 fee);
event SetSwapFee(uint256 fee);
event SetOracle(address account);
event SetTrader(address trader);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function oracle() external view returns (address);
function trader() external view returns (address);
function mintFee() external view returns (uint256);
function setMintFee(uint256 fee) external;
function mint(address to) external returns (uint256 liquidity);
function burnFee() external view returns (uint256);
function setBurnFee(uint256 fee) external;
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swapFee() external view returns (uint256);
function setSwapFee(uint256 fee) external;
function setOracle(address account) external;
function setTrader(address account) external;
function collect(address to) external;
function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
function sync() external;
function initialize(address _token0, address _token1, address _oracle, address _trader) external;
function getSwapAmount0In(uint256 amount1Out, bytes calldata data) external view returns (uint256 swapAmount0In);
function getSwapAmount1In(uint256 amount0Out, bytes calldata data) external view returns (uint256 swapAmount1In);
function getSwapAmount0Out(uint256 amount1In, bytes calldata data) external view returns (uint256 swapAmount0Out);
function getSwapAmount1Out(uint256 amount0In, bytes calldata data) external view returns (uint256 swapAmount1Out);
function getDepositAmount0In(uint256 amount0, bytes calldata data) external view returns (uint256 depositAmount0In);
function getDepositAmount1In(uint256 amount1, bytes calldata data) external view returns (uint256 depositAmount1In);
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import '../libraries/Orders.sol';
interface ITwapRelayer {
event OwnerSet(address owner);
event RebalancerSet(address rebalancer);
event DelaySet(address delay);
event PairEnabledSet(address pair, bool enabled);
event SwapFeeSet(address pair, uint256 fee);
event TwapIntervalSet(address pair, uint32 interval);
event EthTransferGasCostSet(uint256 gasCost);
event ExecutionGasLimitSet(uint256 limit);
event TokenLimitMinSet(address token, uint256 limit);
event TokenLimitMaxMultiplierSet(address token, uint256 limit);
event ToleranceSet(address pair, uint16 tolerance);
event Approve(address token, address to, uint256 amount);
event Withdraw(address token, address to, uint256 amount);
event Sell(
address indexed sender,
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOut,
uint256 amountOutMin,
bool wrapUnwrap,
uint256 fee,
address indexed to,
address orderContract,
uint256 indexed orderId
);
event Buy(
address indexed sender,
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountInMax,
uint256 amountOut,
bool wrapUnwrap,
uint256 fee,
address indexed to,
address orderContract,
uint256 indexed orderId
);
event RebalanceSellWithDelay(
address indexed sender,
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 indexed delayOrderId
);
event RebalanceSellWithOneInch(address indexed oneInchRouter, uint256 gas, bytes data);
event OneInchRouterWhitelisted(address indexed oneInchRouter, bool whitelisted);
event WrapEth(uint256 amount);
event UnwrapWeth(uint256 amount);
function factory() external pure returns (address);
function delay() external pure returns (address);
function weth() external pure returns (address);
function owner() external view returns (address);
function rebalancer() external view returns (address);
function isOneInchRouterWhitelisted(address oneInchRouter) external view returns (bool);
function setOwner(address _owner) external;
function swapFee(address pair) external view returns (uint256);
function setSwapFee(address pair, uint256 fee) external;
function twapInterval(address pair) external pure returns (uint32);
function isPairEnabled(address pair) external view returns (bool);
function setPairEnabled(address pair, bool enabled) external;
function ethTransferGasCost() external pure returns (uint256);
function executionGasLimit() external pure returns (uint256);
function tokenLimitMin(address token) external pure returns (uint256);
function tokenLimitMaxMultiplier(address token) external pure returns (uint256);
function tolerance(address pair) external pure returns (uint16);
function setRebalancer(address _rebalancer) external;
function whitelistOneInchRouter(address oneInchRouter, bool whitelisted) external;
function getTolerance(address pair) external pure returns (uint16);
function getTokenLimitMin(address token) external pure returns (uint256);
function getTokenLimitMaxMultiplier(address token) external pure returns (uint256);
function getTwapInterval(address pair) external pure returns (uint32);
struct SellParams {
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 amountOutMin;
bool wrapUnwrap;
address to;
uint32 submitDeadline;
}
function sell(SellParams memory sellParams) external payable returns (uint256 orderId);
struct BuyParams {
address tokenIn;
address tokenOut;
uint256 amountInMax;
uint256 amountOut;
bool wrapUnwrap;
address to;
uint32 submitDeadline;
}
function buy(BuyParams memory buyParams) external payable returns (uint256 orderId);
function getPriceByPairAddress(
address pair,
bool inverted
) external view returns (uint8 xDecimals, uint8 yDecimals, uint256 price);
function getPriceByTokenAddresses(address tokenIn, address tokenOut) external view returns (uint256 price);
function getPoolState(
address token0,
address token1
)
external
view
returns (
uint256 price,
uint256 fee,
uint256 limitMin0,
uint256 limitMax0,
uint256 limitMin1,
uint256 limitMax1
);
function quoteSell(address tokenIn, address tokenOut, uint256 amountIn) external view returns (uint256 amountOut);
function quoteBuy(address tokenIn, address tokenOut, uint256 amountOut) external view returns (uint256 amountIn);
function approve(address token, uint256 amount, address to) external;
function withdraw(address token, uint256 amount, address to) external;
function rebalanceSellWithDelay(address tokenIn, address tokenOut, uint256 amountIn) external;
function rebalanceSellWithOneInch(
address tokenIn,
uint256 amountIn,
address oneInchRouter,
uint256 _gas,
bytes calldata data
) external;
function wrapEth(uint256 amount) external;
function unwrapWeth(uint256 amount) external;
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface ITwapRelayerInitializable {
event Initialized(address _factory, address _delay, address _weth);
function initialize() external;
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// a library for performing various math operations
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x > y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './SafeMath.sol';
import '../libraries/Math.sol';
import '../interfaces/ITwapFactory.sol';
import '../interfaces/ITwapPair.sol';
import '../interfaces/ITwapOracle.sol';
import '../libraries/TokenShares.sol';
library Orders {
using SafeMath for uint256;
using TokenShares for TokenShares.Data;
using TransferHelper for address;
enum OrderType {
Empty,
Deposit,
Withdraw,
Sell,
Buy
}
enum OrderStatus {
NonExistent,
EnqueuedWaiting,
EnqueuedReady,
ExecutedSucceeded,
ExecutedFailed,
Canceled
}
event DepositEnqueued(uint256 indexed orderId, Order order);
event WithdrawEnqueued(uint256 indexed orderId, Order order);
event SellEnqueued(uint256 indexed orderId, Order order);
event BuyEnqueued(uint256 indexed orderId, Order order);
event OrderTypesDisabled(address pair, Orders.OrderType[] orderTypes, bool disabled);
event RefundFailed(address indexed to, address indexed token, uint256 amount, bytes data);
// Note on gas estimation for the full order execution in the UI:
// Add (*_ORDER_BASE_COST + token transfer costs) to the actual gas usage
// of the TwapDelay._execute* functions when updating gas cost in the UI.
// Remember that ETH unwrap is part of those functions. It is optional,
// but also needs to be included in the estimate.
uint256 public constant ETHER_TRANSFER_COST = ETHER_TRANSFER_CALL_COST + 2600 + 1504; // Std cost + EIP-2929 acct access cost + Gnosis Safe receive ETH cost
uint256 private constant BOT_ETHER_TRANSFER_COST = 10_000;
uint256 private constant BUFFER_COST = 10_000;
uint256 private constant ORDER_EXECUTED_EVENT_COST = 3700;
uint256 private constant EXECUTE_PREPARATION_COST = 30_000; // dequeue + gas calculation before calls to _execute* functions
uint256 public constant ETHER_TRANSFER_CALL_COST = 10_000;
uint256 public constant PAIR_TRANSFER_COST = 55_000;
uint256 public constant REFUND_BASE_COST =
BOT_ETHER_TRANSFER_COST + ETHER_TRANSFER_COST + BUFFER_COST + ORDER_EXECUTED_EVENT_COST;
uint256 private constant ORDER_BASE_COST = EXECUTE_PREPARATION_COST + REFUND_BASE_COST;
uint256 public constant TOKEN_REFUND_BASE_COST = 20_000; // cost of performing token refund logic (excluding token transfer)
uint256 public constant DEPOSIT_ORDER_BASE_COST = ORDER_BASE_COST + 2 * TOKEN_REFUND_BASE_COST;
uint256 public constant WITHDRAW_ORDER_BASE_COST = ORDER_BASE_COST;
uint256 public constant SELL_ORDER_BASE_COST = ORDER_BASE_COST + TOKEN_REFUND_BASE_COST;
uint256 public constant BUY_ORDER_BASE_COST = ORDER_BASE_COST + TOKEN_REFUND_BASE_COST;
// Masks used for setting order disabled
// Different bits represent different order types
uint8 private constant DEPOSIT_MASK = uint8(1 << uint8(OrderType.Deposit)); // 00000010
uint8 private constant WITHDRAW_MASK = uint8(1 << uint8(OrderType.Withdraw)); // 00000100
uint8 private constant SELL_MASK = uint8(1 << uint8(OrderType.Sell)); // 00001000
uint8 private constant BUY_MASK = uint8(1 << uint8(OrderType.Buy)); // 00010000
address public constant FACTORY_ADDRESS = 0xC480b33eE5229DE3FbDFAD1D2DCD3F3BAD0C56c6;
uint256 public constant MAX_GAS_LIMIT = 5000000;
uint256 public constant GAS_PRICE_INERTIA = 20000000;
uint256 public constant MAX_GAS_PRICE_IMPACT = 1000000;
uint256 public constant DELAY = 1800;
address public constant NATIVE_CURRENCY_SENTINEL = address(0); // A sentinel value for the native currency to distinguish it from ERC20 tokens
struct Data {
uint256 newestOrderId;
uint256 lastProcessedOrderId;
mapping(uint256 => bytes32) orderQueue;
uint256 gasPrice;
mapping(uint256 => bool) canceled;
// Bit on specific positions indicates whether order type is disabled (1) or enabled (0) on specific pair
mapping(address => uint8) orderTypesDisabled;
mapping(uint256 => bool) refundFailed;
}
struct Order {
uint256 orderId;
OrderType orderType;
bool inverted;
uint256 validAfterTimestamp;
bool unwrap;
uint256 timestamp;
uint256 gasLimit;
uint256 gasPrice;
uint256 liquidity;
uint256 value0; // Deposit: share0, Withdraw: amount0Min, Sell: shareIn, Buy: shareInMax
uint256 value1; // Deposit: share1, Withdraw: amount1Min, Sell: amountOutMin, Buy: amountOut
address token0; // Sell: tokenIn, Buy: tokenIn
address token1; // Sell: tokenOut, Buy: tokenOut
address to;
uint256 minSwapPrice;
uint256 maxSwapPrice;
bool swap;
uint256 priceAccumulator;
uint256 amountLimit0;
uint256 amountLimit1;
}
function getOrderStatus(
Data storage data,
uint256 orderId,
uint256 validAfterTimestamp
) internal view returns (OrderStatus) {
if (orderId > data.newestOrderId) {
return OrderStatus.NonExistent;
}
if (data.canceled[orderId]) {
return OrderStatus.Canceled;
}
if (data.refundFailed[orderId]) {
return OrderStatus.ExecutedFailed;
}
if (data.orderQueue[orderId] == bytes32(0)) {
return OrderStatus.ExecutedSucceeded;
}
if (validAfterTimestamp >= block.timestamp) {
return OrderStatus.EnqueuedWaiting;
}
return OrderStatus.EnqueuedReady;
}
function getPair(address tokenA, address tokenB) internal view returns (address pair, bool inverted) {
pair = ITwapFactory(FACTORY_ADDRESS).getPair(tokenA, tokenB);
require(pair != address(0), 'OS17');
inverted = tokenA > tokenB;
}
function getDepositDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & DEPOSIT_MASK != 0;
}
function getWithdrawDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & WITHDRAW_MASK != 0;
}
function getSellDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & SELL_MASK != 0;
}
function getBuyDisabled(Data storage data, address pair) internal view returns (bool) {
return data.orderTypesDisabled[pair] & BUY_MASK != 0;
}
function setOrderTypesDisabled(
Data storage data,
address pair,
Orders.OrderType[] calldata orderTypes,
bool disabled
) external {
uint256 orderTypesLength = orderTypes.length;
uint8 currentSettings = data.orderTypesDisabled[pair];
uint8 combinedMask;
for (uint256 i; i < orderTypesLength; ++i) {
Orders.OrderType orderType = orderTypes[i];
require(orderType != Orders.OrderType.Empty, 'OS32');
// zeros with 1 bit set at position specified by orderType
// e.g. for SELL order type
// mask for SELL = 00001000
// combinedMask = 00000110 (DEPOSIT and WITHDRAW masks set in previous iterations)
// the result of OR = 00001110 (DEPOSIT, WITHDRAW and SELL combined mask)
combinedMask = combinedMask | uint8(1 << uint8(orderType));
}
// set/unset a bit accordingly to 'disabled' value
if (disabled) {
// OR operation to disable order
// e.g. for disable DEPOSIT
// currentSettings = 00010100 (BUY and WITHDRAW disabled)
// mask for DEPOSIT = 00000010
// the result of OR = 00010110
currentSettings = currentSettings | combinedMask;
} else {
// AND operation with a mask negation to enable order
// e.g. for enable DEPOSIT
// currentSettings = 00010100 (BUY and WITHDRAW disabled)
// 0xff = 11111111
// mask for Deposit = 00000010
// mask negation = 11111101
// the result of AND = 00010100
currentSettings = currentSettings & (combinedMask ^ 0xff);
}
require(currentSettings != data.orderTypesDisabled[pair], 'OS01');
data.orderTypesDisabled[pair] = currentSettings;
emit OrderTypesDisabled(pair, orderTypes, disabled);
}
function markRefundFailed(Data storage data) internal {
data.refundFailed[data.lastProcessedOrderId] = true;
}
/// @dev The passed in order.oderId is ignored and overwritten with the correct value, i.e. an updated data.newestOrderId.
/// This is done to ensure atomicity of these two actions while optimizing gas usage - adding an order to the queue and incrementing
/// data.newestOrderId (which should not be done anywhere else in the contract).
/// Must only be called on verified orders.
function enqueueOrder(Data storage data, Order memory order) internal {
order.orderId = ++data.newestOrderId;
data.orderQueue[order.orderId] = getOrderDigest(order);
}
struct DepositParams {
address token0;
address token1;
uint256 amount0;
uint256 amount1;
uint256 minSwapPrice;
uint256 maxSwapPrice;
bool wrap;
bool swap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function deposit(
Data storage data,
DepositParams calldata depositParams,
TokenShares.Data storage tokenShares
) external {
checkOrderParams(
depositParams.to,
depositParams.gasLimit,
depositParams.submitDeadline,
DEPOSIT_ORDER_BASE_COST +
getTransferGasCost(depositParams.token0) +
getTransferGasCost(depositParams.token1)
);
require(depositParams.amount0 != 0 || depositParams.amount1 != 0, 'OS25');
(address pairAddress, bool inverted) = getPair(depositParams.token0, depositParams.token1);
require(!getDepositDisabled(data, pairAddress), 'OS46');
{
// scope for value, avoids stack too deep errors
uint256 value = msg.value;
// allocate gas refund
if (depositParams.wrap) {
if (depositParams.token0 == TokenShares.WETH_ADDRESS) {
value = msg.value.sub(depositParams.amount0, 'OS1E');
} else if (depositParams.token1 == TokenShares.WETH_ADDRESS) {
value = msg.value.sub(depositParams.amount1, 'OS1E');
}
}
allocateGasRefund(data, value, depositParams.gasLimit);
}
uint256 shares0 = tokenShares.amountToShares(
inverted ? depositParams.token1 : depositParams.token0,
inverted ? depositParams.amount1 : depositParams.amount0,
depositParams.wrap
);
uint256 shares1 = tokenShares.amountToShares(
inverted ? depositParams.token0 : depositParams.token1,
inverted ? depositParams.amount0 : depositParams.amount1,
depositParams.wrap
);
(uint256 priceAccumulator, uint256 timestamp) = ITwapOracle(ITwapPair(pairAddress).oracle()).getPriceInfo();
Order memory order = Order(
0,
OrderType.Deposit,
inverted,
timestamp + DELAY, // validAfterTimestamp
depositParams.wrap,
timestamp,
depositParams.gasLimit,
data.gasPrice,
0, // liquidity
shares0,
shares1,
inverted ? depositParams.token1 : depositParams.token0,
inverted ? depositParams.token0 : depositParams.token1,
depositParams.to,
depositParams.minSwapPrice,
depositParams.maxSwapPrice,
depositParams.swap,
priceAccumulator,
inverted ? depositParams.amount1 : depositParams.amount0,
inverted ? depositParams.amount0 : depositParams.amount1
);
enqueueOrder(data, order);
emit DepositEnqueued(order.orderId, order);
}
struct WithdrawParams {
address token0;
address token1;
uint256 liquidity;
uint256 amount0Min;
uint256 amount1Min;
bool unwrap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function withdraw(Data storage data, WithdrawParams calldata withdrawParams) external {
(address pair, bool inverted) = getPair(withdrawParams.token0, withdrawParams.token1);
require(!getWithdrawDisabled(data, pair), 'OS0A');
checkOrderParams(
withdrawParams.to,
withdrawParams.gasLimit,
withdrawParams.submitDeadline,
WITHDRAW_ORDER_BASE_COST + PAIR_TRANSFER_COST
);
require(withdrawParams.liquidity != 0, 'OS22');
allocateGasRefund(data, msg.value, withdrawParams.gasLimit);
pair.safeTransferFrom(msg.sender, address(this), withdrawParams.liquidity);
Order memory order = Order(
0,
OrderType.Withdraw,
inverted,
block.timestamp + DELAY, // validAfterTimestamp
withdrawParams.unwrap,
0, // timestamp
withdrawParams.gasLimit,
data.gasPrice,
withdrawParams.liquidity,
inverted ? withdrawParams.amount1Min : withdrawParams.amount0Min,
inverted ? withdrawParams.amount0Min : withdrawParams.amount1Min,
inverted ? withdrawParams.token1 : withdrawParams.token0,
inverted ? withdrawParams.token0 : withdrawParams.token1,
withdrawParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
0, // priceAccumulator
0, // amountLimit0
0 // amountLimit1
);
enqueueOrder(data, order);
emit WithdrawEnqueued(order.orderId, order);
}
struct SellParams {
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 amountOutMin;
bool wrapUnwrap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function sell(Data storage data, SellParams calldata sellParams, TokenShares.Data storage tokenShares) external {
checkOrderParams(
sellParams.to,
sellParams.gasLimit,
sellParams.submitDeadline,
SELL_ORDER_BASE_COST + getTransferGasCost(sellParams.tokenIn)
);
(address pairAddress, bool inverted) = sellHelper(data, sellParams);
(uint256 priceAccumulator, uint256 timestamp) = ITwapOracle(ITwapPair(pairAddress).oracle()).getPriceInfo();
uint256 shares = tokenShares.amountToShares(sellParams.tokenIn, sellParams.amountIn, sellParams.wrapUnwrap);
Order memory order = Order(
0,
OrderType.Sell,
inverted,
timestamp + DELAY, // validAfterTimestamp
sellParams.wrapUnwrap,
timestamp,
sellParams.gasLimit,
data.gasPrice,
0, // liquidity
shares,
sellParams.amountOutMin,
sellParams.tokenIn,
sellParams.tokenOut,
sellParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
priceAccumulator,
sellParams.amountIn,
0 // amountLimit1
);
enqueueOrder(data, order);
emit SellEnqueued(order.orderId, order);
}
function relayerSell(
Data storage data,
SellParams calldata sellParams,
TokenShares.Data storage tokenShares
) external {
checkOrderParams(
sellParams.to,
sellParams.gasLimit,
sellParams.submitDeadline,
SELL_ORDER_BASE_COST + getTransferGasCost(sellParams.tokenIn)
);
(, bool inverted) = sellHelper(data, sellParams);
uint256 shares = tokenShares.amountToSharesWithoutTransfer(
sellParams.tokenIn,
sellParams.amountIn,
sellParams.wrapUnwrap
);
Order memory order = Order(
0,
OrderType.Sell,
inverted,
block.timestamp + DELAY, // validAfterTimestamp
false, // Never wrap/unwrap
block.timestamp,
sellParams.gasLimit,
data.gasPrice,
0, // liquidity
shares,
sellParams.amountOutMin,
sellParams.tokenIn,
sellParams.tokenOut,
sellParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
0, // priceAccumulator - oracleV3 pairs don't need priceAccumulator
sellParams.amountIn,
0 // amountLimit1
);
enqueueOrder(data, order);
emit SellEnqueued(order.orderId, order);
}
function sellHelper(
Data storage data,
SellParams calldata sellParams
) internal returns (address pairAddress, bool inverted) {
require(sellParams.amountIn != 0, 'OS24');
(pairAddress, inverted) = getPair(sellParams.tokenIn, sellParams.tokenOut);
require(!getSellDisabled(data, pairAddress), 'OS13');
// allocate gas refund
uint256 value = msg.value;
if (sellParams.wrapUnwrap && sellParams.tokenIn == TokenShares.WETH_ADDRESS) {
value = msg.value.sub(sellParams.amountIn, 'OS1E');
}
allocateGasRefund(data, value, sellParams.gasLimit);
}
struct BuyParams {
address tokenIn;
address tokenOut;
uint256 amountInMax;
uint256 amountOut;
bool wrapUnwrap;
address to;
uint256 gasLimit;
uint32 submitDeadline;
}
function buy(Data storage data, BuyParams calldata buyParams, TokenShares.Data storage tokenShares) external {
checkOrderParams(
buyParams.to,
buyParams.gasLimit,
buyParams.submitDeadline,
BUY_ORDER_BASE_COST + getTransferGasCost(buyParams.tokenIn)
);
require(buyParams.amountOut != 0, 'OS23');
(address pairAddress, bool inverted) = getPair(buyParams.tokenIn, buyParams.tokenOut);
require(!getBuyDisabled(data, pairAddress), 'OS49');
uint256 value = msg.value;
// allocate gas refund
if (buyParams.tokenIn == TokenShares.WETH_ADDRESS && buyParams.wrapUnwrap) {
value = msg.value.sub(buyParams.amountInMax, 'OS1E');
}
allocateGasRefund(data, value, buyParams.gasLimit);
uint256 shares = tokenShares.amountToShares(buyParams.tokenIn, buyParams.amountInMax, buyParams.wrapUnwrap);
(uint256 priceAccumulator, uint256 timestamp) = ITwapOracle(ITwapPair(pairAddress).oracle()).getPriceInfo();
Order memory order = Order(
0,
OrderType.Buy,
inverted,
timestamp + DELAY, // validAfterTimestamp
buyParams.wrapUnwrap,
timestamp,
buyParams.gasLimit,
data.gasPrice,
0, // liquidity
shares,
buyParams.amountOut,
buyParams.tokenIn,
buyParams.tokenOut,
buyParams.to,
0, // minSwapPrice
0, // maxSwapPrice
false, // swap
priceAccumulator,
buyParams.amountInMax,
0 // amountLimit1
);
enqueueOrder(data, order);
emit BuyEnqueued(order.orderId, order);
}
function checkOrderParams(address to, uint256 gasLimit, uint32 submitDeadline, uint256 minGasLimit) private view {
require(submitDeadline >= block.timestamp, 'OS04');
require(gasLimit <= MAX_GAS_LIMIT, 'OS3E');
require(gasLimit >= minGasLimit, 'OS3D');
require(to != address(0), 'OS26');
}
function allocateGasRefund(Data storage data, uint256 value, uint256 gasLimit) private returns (uint256 futureFee) {
futureFee = data.gasPrice.mul(gasLimit);
require(value >= futureFee, 'OS1E');
if (value > futureFee) {
TransferHelper.safeTransferETH(msg.sender, value - futureFee, getTransferGasCost(NATIVE_CURRENCY_SENTINEL));
}
}
function updateGasPrice(Data storage data, uint256 gasUsed) external {
uint256 scale = Math.min(gasUsed, MAX_GAS_PRICE_IMPACT);
data.gasPrice = data.gasPrice.mul(GAS_PRICE_INERTIA.sub(scale)).add(tx.gasprice.mul(scale)).div(
GAS_PRICE_INERTIA
);
}
function refundLiquidity(address pair, address to, uint256 liquidity, bytes4 selector) internal returns (bool) {
if (liquidity == 0) {
return true;
}
(bool success, bytes memory data) = address(this).call{ gas: PAIR_TRANSFER_COST }(
abi.encodeWithSelector(selector, pair, to, liquidity, false)
);
if (!success) {
emit RefundFailed(to, pair, liquidity, data);
}
return success;
}
function dequeueOrder(Data storage data, uint256 orderId) internal {
++data.lastProcessedOrderId;
require(orderId == data.lastProcessedOrderId, 'OS72');
}
function forgetOrder(Data storage data, uint256 orderId) internal {
delete data.orderQueue[orderId];
}
function forgetLastProcessedOrder(Data storage data) internal {
delete data.orderQueue[data.lastProcessedOrderId];
}
function getOrderDigest(Order memory order) internal pure returns (bytes32) {
// Used to avoid the 'stack too deep' error.
bytes memory partialOrderData = abi.encodePacked(
order.orderId,
order.orderType,
order.inverted,
order.validAfterTimestamp,
order.unwrap,
order.timestamp,
order.gasLimit,
order.gasPrice,
order.liquidity,
order.value0,
order.value1,
order.token0,
order.token1,
order.to
);
return
keccak256(
abi.encodePacked(
partialOrderData,
order.minSwapPrice,
order.maxSwapPrice,
order.swap,
order.priceAccumulator,
order.amountLimit0,
order.amountLimit1
)
);
}
function verifyOrder(Data storage data, Order memory order) external view {
require(getOrderDigest(order) == data.orderQueue[order.orderId], 'OS71');
}
// constant mapping for transferGasCost
/**
* @dev This function should either return a default value != 0 or revert.
*/
function getTransferGasCost(address token) internal pure returns (uint256) {
if (token == NATIVE_CURRENCY_SENTINEL) return ETHER_TRANSFER_CALL_COST;
if (token == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) return 31000;
if (token == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 42000;
if (token == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return 66000;
if (token == 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599) return 34000;
if (token == 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B) return 31000;
if (token == 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2) return 31000;
if (token == 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84) return 68000;
if (token == 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0) return 31000;
if (token == 0xD33526068D116cE69F19A9ee46F0bd304F21A51f) return 31000;
if (token == 0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2) return 40000;
if (token == 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32) return 149000;
if (token == 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2) return 34000;
if (token == 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984) return 37000;
if (token == 0x514910771AF9Ca656af840dff83E8264EcF986CA) return 32000;
if (token == 0x3c3a81e81dc49A522A592e7622A7E711c06bf354) return 34000;
return 60000;
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
int256 private constant _INT256_MIN = -2 ** 255;
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'SM4E');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = sub(x, y, 'SM12');
}
function sub(uint256 x, uint256 y, string memory message) internal pure returns (uint256 z) {
require((z = x - y) <= x, message);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'SM2A');
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SM43');
return a / b;
}
function ceil_div(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = div(a, b);
if (a != mul(b, c)) {
return add(c, 1);
}
}
function toUint32(uint256 n) internal pure returns (uint32) {
require(n <= type(uint32).max, 'SM50');
return uint32(n);
}
function toUint64(uint256 n) internal pure returns (uint64) {
require(n <= type(uint64).max, 'SM54');
return uint64(n);
}
function toUint112(uint256 n) internal pure returns (uint112) {
require(n <= type(uint112).max, 'SM51');
return uint112(n);
}
function toInt256(uint256 unsigned) internal pure returns (int256 signed) {
require(unsigned <= uint256(type(int256).max), 'SM34');
signed = int256(unsigned);
}
// int256
function add(int256 a, int256 b) internal pure returns (int256 c) {
c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), 'SM4D');
}
function sub(int256 a, int256 b) internal pure returns (int256 c) {
c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), 'SM11');
}
function mul(int256 a, int256 b) internal pure returns (int256 c) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), 'SM29');
c = a * b;
require(c / a == b, 'SM29');
}
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, 'SM43');
require(!(b == -1 && a == _INT256_MIN), 'SM42');
return a / b;
}
function neg_floor_div(int256 a, int256 b) internal pure returns (int256 c) {
c = div(a, b);
if ((a < 0 && b > 0) || (a >= 0 && b < 0)) {
if (a != mul(b, c)) {
c = sub(c, 1);
}
}
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import '../interfaces/IERC20.sol';
import '../interfaces/IWETH.sol';
import './SafeMath.sol';
import './TransferHelper.sol';
library TokenShares {
using SafeMath for uint256;
using TransferHelper for address;
uint256 private constant PRECISION = 10 ** 18;
uint256 private constant TOLERANCE = 10 ** 18 + 10 ** 16;
uint256 private constant TOTAL_SHARES_PRECISION = 10 ** 18;
event UnwrapFailed(address to, uint256 amount);
// represents wrapped native currency (WETH or WMATIC)
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
struct Data {
mapping(address => uint256) totalShares;
}
function sharesToAmount(
Data storage data,
address token,
uint256 share,
uint256 amountLimit,
address refundTo
) external returns (uint256) {
if (share == 0) {
return 0;
}
if (token == WETH_ADDRESS || isNonRebasing(token)) {
return share;
}
uint256 totalTokenShares = data.totalShares[token];
require(totalTokenShares >= share, 'TS3A');
uint256 balance = IERC20(token).balanceOf(address(this));
uint256 value = balance.mul(share).div(totalTokenShares);
data.totalShares[token] = totalTokenShares.sub(share);
if (amountLimit > 0) {
uint256 amountLimitWithTolerance = amountLimit.mul(TOLERANCE).div(PRECISION);
if (value > amountLimitWithTolerance) {
TransferHelper.safeTransfer(token, refundTo, value.sub(amountLimitWithTolerance));
return amountLimitWithTolerance;
}
}
return value;
}
function amountToShares(Data storage data, address token, uint256 amount, bool wrap) external returns (uint256) {
if (amount == 0) {
return 0;
}
if (token == WETH_ADDRESS) {
if (wrap) {
require(msg.value >= amount, 'TS03');
IWETH(token).deposit{ value: amount }();
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
return amount;
} else if (isNonRebasing(token)) {
token.safeTransferFrom(msg.sender, address(this), amount);
return amount;
} else {
uint256 balanceBefore = IERC20(token).balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), amount);
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
return amountToSharesHelper(data, token, balanceBefore, balanceAfter);
}
}
function amountToSharesWithoutTransfer(
Data storage data,
address token,
uint256 amount,
bool wrap
) external returns (uint256) {
if (token == WETH_ADDRESS) {
if (wrap) {
// require(msg.value >= amount, 'TS03'); // Duplicate check in TwapRelayer.sell
IWETH(token).deposit{ value: amount }();
}
return amount;
} else if (isNonRebasing(token)) {
return amount;
} else {
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
uint256 balanceBefore = balanceAfter.sub(amount);
return amountToSharesHelper(data, token, balanceBefore, balanceAfter);
}
}
function amountToSharesHelper(
Data storage data,
address token,
uint256 balanceBefore,
uint256 balanceAfter
) internal returns (uint256) {
uint256 totalTokenShares = data.totalShares[token];
require(balanceBefore > 0 || totalTokenShares == 0, 'TS30');
require(balanceAfter > balanceBefore, 'TS2C');
if (balanceBefore > 0) {
if (totalTokenShares == 0) {
totalTokenShares = balanceBefore.mul(TOTAL_SHARES_PRECISION);
}
uint256 newShares = totalTokenShares.mul(balanceAfter).div(balanceBefore);
require(balanceAfter < type(uint256).max.div(newShares), 'TS73'); // to prevent overflow at execution
data.totalShares[token] = newShares;
return newShares - totalTokenShares;
} else {
totalTokenShares = balanceAfter.mul(TOTAL_SHARES_PRECISION);
require(totalTokenShares < type(uint256).max.div(totalTokenShares), 'TS73'); // to prevent overflow at execution
data.totalShares[token] = totalTokenShares;
return totalTokenShares;
}
}
function onUnwrapFailed(address to, uint256 amount) external {
emit UnwrapFailed(to, amount);
IWETH(WETH_ADDRESS).deposit{ value: amount }();
TransferHelper.safeTransfer(WETH_ADDRESS, to, amount);
}
// constant mapping for nonRebasingToken
function isNonRebasing(address token) internal pure returns (bool) {
if (token == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) return true;
if (token == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return true;
if (token == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return true;
if (token == 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599) return true;
if (token == 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B) return true;
if (token == 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2) return true;
if (token == 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0) return true;
if (token == 0xD33526068D116cE69F19A9ee46F0bd304F21A51f) return true;
if (token == 0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2) return true;
if (token == 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32) return true;
if (token == 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2) return true;
if (token == 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984) return true;
if (token == 0x514910771AF9Ca656af840dff83E8264EcF986CA) return true;
if (token == 0x3c3a81e81dc49A522A592e7622A7E711c06bf354) return true;
return false;
}
}
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint256 value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH4B');
}
function safeTransfer(address token, address to, uint256 value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH05');
}
function safeTransferFrom(address token, address from, address to, uint256 value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH0E');
}
function safeTransferETH(address to, uint256 value, uint256 gasLimit) internal {
(bool success, ) = to.call{ value: value, gas: gasLimit }('');
require(success, 'TH3F');
}
function transferETH(address to, uint256 value, uint256 gasLimit) internal returns (bool success) {
(success, ) = to.call{ value: value, gas: gasLimit }('');
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
import './interfaces/ITwapFactory.sol';
import './interfaces/ITwapDelay.sol';
import './interfaces/ITwapPair.sol';
import './interfaces/ITwapOracleV3.sol';
import './interfaces/ITwapRelayer.sol';
import './interfaces/ITwapRelayerInitializable.sol';
import './interfaces/IWETH.sol';
import './libraries/SafeMath.sol';
import './libraries/Orders.sol';
import './libraries/TransferHelper.sol';
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol';
contract TwapRelayer is ITwapRelayer, ITwapRelayerInitializable {
using SafeMath for uint256;
uint256 private constant PRECISION = 10 ** 18;
address public constant FACTORY_ADDRESS = 0xC480b33eE5229DE3FbDFAD1D2DCD3F3BAD0C56c6;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DELAY_ADDRESS = 0xc3a99a855D060D727367c599Ecb2423e0bEbEe24;
uint256 public constant EXECUTION_GAS_LIMIT = 710000;
/*
* DO NOT CHANGE THE BELOW STATE VARIABLES.
* REMOVING, REORDERING OR INSERTING STATE VARIABLES WILL CAUSE STORAGE COLLISION.
* NEW VARIABLES SHOULD BE ADDED BELOW THESE VARIABLES TO AVOID STORAGE COLLISION.
*/
uint8 public initialized;
uint8 private __RESERVED__OLD_LOCKED;
address public override owner;
address public __RESERVED__OLD_FACTORY;
address public __RESERVED__OLD_WETH;
address public __RESERVED__OLD_DELAY;
uint256 public __RESERVED__OLD_ETH_TRANSFER_GAS_COST;
uint256 public __RESERVED__OLD_EXECUTION_GAS_LIMIT;
uint256 public __RESERVED__SLOT_6_USED_IN_PREVIOUS_VERSIONS;
mapping(address => uint256) public override swapFee;
mapping(address => uint32) public __RESERVED__OLD_TWAP_INTERVAL;
mapping(address => bool) public override isPairEnabled;
mapping(address => uint256) public __RESERVED__OLD_TOKEN_LIMIT_MIN;
mapping(address => uint256) public __RESERVED__OLD_TOKEN_LIMIT_MAX_MULTIPLIER;
mapping(address => uint16) public __RESERVED__OLD_TOLERANCE;
address public override rebalancer;
mapping(address => bool) public override isOneInchRouterWhitelisted;
uint256 private locked = 1;
/*
* DO NOT CHANGE THE ABOVE STATE VARIABLES.
* REMOVING, REORDERING OR INSERTING STATE VARIABLES WILL CAUSE STORAGE COLLISION.
* NEW VARIABLES SHOULD BE ADDED BELOW THESE VARIABLES TO AVOID STORAGE COLLISION.
*/
modifier lock() {
require(locked == 1, 'TR06');
locked = 2;
_;
locked = 1;
}
// This contract implements a proxy pattern.
// The constructor is to set to prevent abuse of this implementation contract.
// Setting locked = 2 forces core features, e.g. buy(), to always revert.
constructor() {
owner = msg.sender;
initialized = 1;
locked = 2;
}
// This function should be called through the proxy contract to initialize the proxy contract's storage.
function initialize() external override {
require(initialized == 0, 'TR5B');
initialized = 1;
owner = msg.sender;
locked = 1;
emit Initialized(FACTORY_ADDRESS, DELAY_ADDRESS, WETH_ADDRESS);
emit OwnerSet(msg.sender);
_emitEventWithDefaults();
}
// This function should be called through the proxy contract to update lock
function initializeLock() external {
require(msg.sender == owner, 'TR00');
require(locked == 0, 'TR5B');
locked = 1;
}
function setOwner(address _owner) external override {
require(msg.sender == owner, 'TR00');
require(_owner != owner, 'TR01');
require(_owner != address(0), 'TR02');
owner = _owner;
emit OwnerSet(_owner);
}
function setSwapFee(address pair, uint256 fee) external override {
require(msg.sender == owner, 'TR00');
require(fee != swapFee[pair], 'TR01');
swapFee[pair] = fee;
emit SwapFeeSet(pair, fee);
}
function setPairEnabled(address pair, bool enabled) external override {
require(msg.sender == owner, 'TR00');
require(enabled != isPairEnabled[pair], 'TR01');
isPairEnabled[pair] = enabled;
emit PairEnabledSet(pair, enabled);
}
function setRebalancer(address _rebalancer) external override {
require(msg.sender == owner, 'TR00');
require(_rebalancer != rebalancer, 'TR01');
require(_rebalancer != msg.sender, 'TR5D');
rebalancer = _rebalancer;
emit RebalancerSet(_rebalancer);
}
function whitelistOneInchRouter(address oneInchRouter, bool whitelisted) external override {
require(msg.sender == owner, 'TR00');
require(oneInchRouter != address(0), 'TR02');
require(whitelisted != isOneInchRouterWhitelisted[oneInchRouter], 'TR01');
isOneInchRouterWhitelisted[oneInchRouter] = whitelisted;
emit OneInchRouterWhitelisted(oneInchRouter, whitelisted);
}
function sell(SellParams calldata sellParams) external payable override lock returns (uint256 orderId) {
require(
sellParams.to != sellParams.tokenIn && sellParams.to != sellParams.tokenOut && sellParams.to != address(0),
'TR26'
);
// Duplicate checks in Orders.sell
// require(sellParams.amountIn != 0, 'TR24');
uint256 ethValue = calculatePrepay();
if (sellParams.wrapUnwrap && sellParams.tokenIn == WETH_ADDRESS) {
require(msg.value == sellParams.amountIn, 'TR59');
ethValue = ethValue.add(msg.value);
} else {
require(msg.value == 0, 'TR58');
}
(uint256 amountIn, uint256 amountOut, uint256 fee) = swapExactIn(
sellParams.tokenIn,
sellParams.tokenOut,
sellParams.amountIn,
sellParams.wrapUnwrap,
sellParams.to
);
require(amountOut >= sellParams.amountOutMin, 'TR37');
orderId = ITwapDelay(DELAY_ADDRESS).relayerSell{ value: ethValue }(
Orders.SellParams(
sellParams.tokenIn,
sellParams.tokenOut,
amountIn,
0, // Relax slippage constraints
sellParams.wrapUnwrap,
address(this),
EXECUTION_GAS_LIMIT,
sellParams.submitDeadline
)
);
emit Sell(
msg.sender,
sellParams.tokenIn,
sellParams.tokenOut,
amountIn,
amountOut,
sellParams.amountOutMin,
sellParams.wrapUnwrap,
fee,
sellParams.to,
DELAY_ADDRESS,
orderId
);
}
function buy(BuyParams calldata buyParams) external payable override lock returns (uint256 orderId) {
require(
buyParams.to != buyParams.tokenIn && buyParams.to != buyParams.tokenOut && buyParams.to != address(0),
'TR26'
);
// Duplicate checks in Orders.sell
// require(buyParams.amountOut != 0, 'TR23');
uint256 balanceBefore = address(this).balance.sub(msg.value);
(uint256 amountIn, uint256 amountOut, uint256 fee) = swapExactOut(
buyParams.tokenIn,
buyParams.tokenOut,
buyParams.amountOut,
buyParams.wrapUnwrap,
buyParams.to
);
require(amountIn <= buyParams.amountInMax, 'TR08');
// Used to avoid the 'stack too deep' error.
{
bool wrapUnwrapWeth = buyParams.wrapUnwrap && buyParams.tokenIn == WETH_ADDRESS;
uint256 prepay = calculatePrepay();
uint256 ethValue = prepay;
if (wrapUnwrapWeth) {
require(msg.value >= amountIn, 'TR59');
ethValue = ethValue.add(amountIn);
} else {
require(msg.value == 0, 'TR58');
}
orderId = ITwapDelay(DELAY_ADDRESS).relayerSell{ value: ethValue }(
Orders.SellParams(
buyParams.tokenIn,
buyParams.tokenOut,
amountIn,
0, // Relax slippage constraints
buyParams.wrapUnwrap,
address(this),
EXECUTION_GAS_LIMIT,
buyParams.submitDeadline
)
);
// refund remaining ETH
if (wrapUnwrapWeth) {
uint256 balanceAfter = address(this).balance + prepay;
if (balanceAfter > balanceBefore) {
TransferHelper.safeTransferETH(
msg.sender,
balanceAfter - balanceBefore,
Orders.ETHER_TRANSFER_COST
);
}
}
}
emit Buy(
msg.sender,
buyParams.tokenIn,
buyParams.tokenOut,
amountIn,
buyParams.amountInMax,
amountOut,
buyParams.wrapUnwrap,
fee,
buyParams.to,
DELAY_ADDRESS,
orderId
);
}
function getPair(address tokenA, address tokenB) internal view returns (address pair, bool inverted) {
inverted = tokenA > tokenB;
pair = ITwapFactory(FACTORY_ADDRESS).getPair(tokenA, tokenB);
require(pair != address(0), 'TR17');
}
function calculatePrepay() internal view returns (uint256) {
return ITwapDelay(DELAY_ADDRESS).gasPrice().mul(EXECUTION_GAS_LIMIT);
}
function swapExactIn(
address tokenIn,
address tokenOut,
uint256 amountIn,
bool wrapUnwrap,
address to
) internal returns (uint256 _amountIn, uint256 _amountOut, uint256 fee) {
(address pair, bool inverted) = getPair(tokenIn, tokenOut);
require(isPairEnabled[pair], 'TR5A');
_amountIn = transferIn(tokenIn, amountIn, wrapUnwrap);
fee = _amountIn.mul(swapFee[pair]).div(PRECISION);
uint256 calculatedAmountOut = calculateAmountOut(pair, inverted, _amountIn.sub(fee));
_amountOut = transferOut(to, tokenOut, calculatedAmountOut, wrapUnwrap);
require(_amountOut <= calculatedAmountOut.add(getTolerance(pair)), 'TR2E');
}
function swapExactOut(
address tokenIn,
address tokenOut,
uint256 amountOut,
bool wrapUnwrap,
address to
) internal returns (uint256 _amountIn, uint256 _amountOut, uint256 fee) {
(address pair, bool inverted) = getPair(tokenIn, tokenOut);
require(isPairEnabled[pair], 'TR5A');
_amountOut = transferOut(to, tokenOut, amountOut, wrapUnwrap);
uint256 calculatedAmountIn = calculateAmountIn(pair, inverted, _amountOut);
uint256 amountInPlusFee = calculatedAmountIn.mul(PRECISION).ceil_div(PRECISION.sub(swapFee[pair]));
fee = amountInPlusFee.sub(calculatedAmountIn);
_amountIn = transferIn(tokenIn, amountInPlusFee, wrapUnwrap);
require(_amountIn >= amountInPlusFee.sub(getTolerance(pair)), 'TR2E');
}
function calculateAmountIn(
address pair,
bool inverted,
uint256 amountOut
) internal view returns (uint256 amountIn) {
(uint8 xDecimals, uint8 yDecimals, uint256 price) = _getPriceByPairAddress(pair, inverted);
uint256 decimalsConverter = getDecimalsConverter(xDecimals, yDecimals, inverted);
amountIn = amountOut.mul(decimalsConverter).ceil_div(price);
}
function calculateAmountOut(
address pair,
bool inverted,
uint256 amountIn
) internal view returns (uint256 amountOut) {
(uint8 xDecimals, uint8 yDecimals, uint256 price) = _getPriceByPairAddress(pair, inverted);
uint256 decimalsConverter = getDecimalsConverter(xDecimals, yDecimals, inverted);
amountOut = amountIn.mul(price).div(decimalsConverter);
}
function getDecimalsConverter(
uint8 xDecimals,
uint8 yDecimals,
bool inverted
) internal pure returns (uint256 decimalsConverter) {
decimalsConverter = 10 ** (18 + (inverted ? yDecimals - xDecimals : xDecimals - yDecimals));
}
function getPriceByPairAddress(
address pair,
bool inverted
) external view override returns (uint8 xDecimals, uint8 yDecimals, uint256 price) {
require(isPairEnabled[pair], 'TR5A');
(xDecimals, yDecimals, price) = _getPriceByPairAddress(pair, inverted);
}
/**
* @dev Ensure that the `pair` is enabled before invoking this function.
*/
function _getPriceByPairAddress(
address pair,
bool inverted
) internal view returns (uint8 xDecimals, uint8 yDecimals, uint256 price) {
uint256 spotPrice;
uint256 averagePrice;
(spotPrice, averagePrice, xDecimals, yDecimals) = getPricesFromOracle(pair);
if (inverted) {
price = uint256(10 ** 36).div(spotPrice > averagePrice ? spotPrice : averagePrice);
} else {
price = spotPrice < averagePrice ? spotPrice : averagePrice;
}
}
function getPriceByTokenAddresses(
address tokenIn,
address tokenOut
) external view override returns (uint256 price) {
(address pair, bool inverted) = getPair(tokenIn, tokenOut);
require(isPairEnabled[pair], 'TR5A');
(, , price) = _getPriceByPairAddress(pair, inverted);
}
/**
* @dev Ensure that the pair for 'tokenIn' and 'tokenOut' is enabled before invoking this function.
*/
function _getPriceByTokenAddresses(address tokenIn, address tokenOut) internal view returns (uint256 price) {
(address pair, bool inverted) = getPair(tokenIn, tokenOut);
(, , price) = _getPriceByPairAddress(pair, inverted);
}
function getPoolState(
address token0,
address token1
)
external
view
override
returns (uint256 price, uint256 fee, uint256 limitMin0, uint256 limitMax0, uint256 limitMin1, uint256 limitMax1)
{
(address pair, ) = getPair(token0, token1);
require(isPairEnabled[pair], 'TR5A');
fee = swapFee[pair];
price = _getPriceByTokenAddresses(token0, token1);
limitMin0 = getTokenLimitMin(token0);
limitMax0 = IERC20(token0).balanceOf(address(this)).mul(getTokenLimitMaxMultiplier(token0)).div(PRECISION);
limitMin1 = getTokenLimitMin(token1);
limitMax1 = IERC20(token1).balanceOf(address(this)).mul(getTokenLimitMaxMultiplier(token1)).div(PRECISION);
}
function quoteSell(
address tokenIn,
address tokenOut,
uint256 amountIn
) external view override returns (uint256 amountOut) {
require(amountIn > 0, 'TR24');
(address pair, bool inverted) = getPair(tokenIn, tokenOut);
require(isPairEnabled[pair], 'TR5A');
uint256 fee = amountIn.mul(swapFee[pair]).div(PRECISION);
uint256 amountInMinusFee = amountIn.sub(fee);
amountOut = calculateAmountOut(pair, inverted, amountInMinusFee);
checkLimits(tokenOut, amountOut);
}
function quoteBuy(
address tokenIn,
address tokenOut,
uint256 amountOut
) external view override returns (uint256 amountIn) {
require(amountOut > 0, 'TR23');
(address pair, bool inverted) = getPair(tokenIn, tokenOut);
require(isPairEnabled[pair], 'TR5A');
checkLimits(tokenOut, amountOut);
uint256 calculatedAmountIn = calculateAmountIn(pair, inverted, amountOut);
amountIn = calculatedAmountIn.mul(PRECISION).ceil_div(PRECISION.sub(swapFee[pair]));
}
function getPricesFromOracle(
address pair
) internal view returns (uint256 spotPrice, uint256 averagePrice, uint8 xDecimals, uint8 yDecimals) {
ITwapOracleV3 oracle = ITwapOracleV3(ITwapPair(pair).oracle());
xDecimals = oracle.xDecimals();
yDecimals = oracle.yDecimals();
spotPrice = oracle.getSpotPrice();
address uniswapPair = oracle.uniswapPair();
averagePrice = getAveragePrice(pair, uniswapPair, getDecimalsConverter(xDecimals, yDecimals, false));
}
function getAveragePrice(
address pair,
address uniswapPair,
uint256 decimalsConverter
) internal view returns (uint256) {
uint32 secondsAgo = getTwapInterval(pair);
require(secondsAgo > 0, 'TR55');
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
(int56[] memory tickCumulatives, ) = IUniswapV3Pool(uniswapPair).observe(secondsAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
int24 arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgo);
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgo != 0)) --arithmeticMeanTick;
uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(arithmeticMeanTick);
if (sqrtRatioX96 <= type(uint128).max) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
return FullMath.mulDiv(ratioX192, decimalsConverter, 2 ** 192);
} else {
uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 2 ** 64);
return FullMath.mulDiv(ratioX128, decimalsConverter, 2 ** 128);
}
}
function transferIn(address token, uint256 amount, bool wrap) internal returns (uint256) {
if (amount == 0) {
return 0;
}
if (token == WETH_ADDRESS) {
// eth is transferred directly to the delay in sell / buy function
if (!wrap) {
TransferHelper.safeTransferFrom(token, msg.sender, DELAY_ADDRESS, amount);
}
return amount;
} else {
uint256 balanceBefore = IERC20(token).balanceOf(DELAY_ADDRESS);
TransferHelper.safeTransferFrom(token, msg.sender, DELAY_ADDRESS, amount);
uint256 balanceAfter = IERC20(token).balanceOf(DELAY_ADDRESS);
require(balanceAfter > balanceBefore, 'TR2C');
return balanceAfter - balanceBefore;
}
}
function transferOut(address to, address token, uint256 amount, bool unwrap) internal returns (uint256) {
if (amount == 0) {
return 0;
}
checkLimits(token, amount);
if (token == WETH_ADDRESS) {
if (unwrap) {
IWETH(token).withdraw(amount);
TransferHelper.safeTransferETH(to, amount, Orders.ETHER_TRANSFER_COST);
} else {
TransferHelper.safeTransfer(token, to, amount);
}
return amount;
} else {
uint256 balanceBefore = IERC20(token).balanceOf(address(this));
TransferHelper.safeTransfer(token, to, amount);
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
require(balanceBefore > balanceAfter, 'TR2C');
return balanceBefore - balanceAfter;
}
}
function checkLimits(address token, uint256 amount) internal view {
require(amount >= getTokenLimitMin(token), 'TR03');
require(
amount <= IERC20(token).balanceOf(address(this)).mul(getTokenLimitMaxMultiplier(token)).div(PRECISION),
'TR3A'
);
}
function approve(address token, uint256 amount, address to) external override lock {
require(msg.sender == owner, 'TR00');
require(to != address(0), 'TR02');
TransferHelper.safeApprove(token, to, amount);
emit Approve(token, to, amount);
}
function withdraw(address token, uint256 amount, address to) external override lock {
require(msg.sender == owner, 'TR00');
require(to != address(0), 'TR02');
if (token == Orders.NATIVE_CURRENCY_SENTINEL) {
TransferHelper.safeTransferETH(to, amount, Orders.ETHER_TRANSFER_COST);
} else {
TransferHelper.safeTransfer(token, to, amount);
}
emit Withdraw(token, to, amount);
}
function rebalanceSellWithDelay(address tokenIn, address tokenOut, uint256 amountIn) external override lock {
require(msg.sender == rebalancer, 'TR00');
uint256 delayOrderId = ITwapDelay(DELAY_ADDRESS).sell{ value: calculatePrepay() }(
Orders.SellParams(
tokenIn,
tokenOut,
amountIn,
0, // Relax slippage constraints
false, // Never wrap/unwrap
address(this),
EXECUTION_GAS_LIMIT,
uint32(block.timestamp)
)
);
emit RebalanceSellWithDelay(msg.sender, tokenIn, tokenOut, amountIn, delayOrderId);
}
function rebalanceSellWithOneInch(
address tokenIn,
uint256 amountIn,
address oneInchRouter,
uint256 _gas,
bytes calldata data
) external override lock {
require(msg.sender == rebalancer, 'TR00');
require(isOneInchRouterWhitelisted[oneInchRouter], 'TR5F');
TransferHelper.safeApprove(tokenIn, oneInchRouter, amountIn);
(bool success, ) = oneInchRouter.call{ gas: _gas }(data);
require(success, 'TR5E');
emit Approve(tokenIn, oneInchRouter, amountIn);
emit RebalanceSellWithOneInch(oneInchRouter, _gas, data);
}
function wrapEth(uint256 amount) external override lock {
require(msg.sender == owner, 'TR00');
IWETH(WETH_ADDRESS).deposit{ value: amount }();
emit WrapEth(amount);
}
function unwrapWeth(uint256 amount) external override lock {
require(msg.sender == owner, 'TR00');
IWETH(WETH_ADDRESS).withdraw(amount);
emit UnwrapWeth(amount);
}
function _emitEventWithDefaults() internal {
emit DelaySet(DELAY_ADDRESS);
emit EthTransferGasCostSet(Orders.ETHER_TRANSFER_COST);
emit ExecutionGasLimitSet(EXECUTION_GAS_LIMIT);
emit ToleranceSet(0x2fe16Dd18bba26e457B7dD2080d5674312b026a2, 0);
emit ToleranceSet(0x048f0e7ea2CFD522a4a058D1b1bDd574A0486c46, 0);
emit ToleranceSet(0x37F6dF71b40c50b2038329CaBf5FDa3682Df1ebF, 0);
emit ToleranceSet(0x6ec472b613012a492693697FA551420E60567eA7, 0);
emit ToleranceSet(0x29b57D56a114aE5BE3c129240898B3321A70A300, 0);
emit ToleranceSet(0x61fA1CEe13CEEAF20C30611c5e6dA48c595F7dB2, 0);
emit ToleranceSet(0x045950A37c59d75496BB4Af68c05f9066A4C7e27, 0);
emit ToleranceSet(0xbEE7Ef1adfaa628536Ebc0C1EBF082DbDC27265F, 0);
emit ToleranceSet(0x51baDc1622C63d1E448A4F1aC1DC008b8a27Fe67, 0);
emit ToleranceSet(0x0e52DB138Df9CE54Bc9D9330f418015eD512830A, 0);
emit ToleranceSet(0xDDE7684D88E0B482B2b455936fe0D22dd48CDcb3, 0);
emit ToleranceSet(0x43102f07414D95eF71EC9aEbA011b8595BA010D0, 0);
emit TokenLimitMinSet(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 1200000000000000000);
emit TokenLimitMinSet(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 5000000000);
emit TokenLimitMinSet(0xdAC17F958D2ee523a2206206994597C13D831ec7, 5000000000);
emit TokenLimitMinSet(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, 7000000);
emit TokenLimitMinSet(0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0, 1100000000000000000);
emit TokenLimitMinSet(0xD33526068D116cE69F19A9ee46F0bd304F21A51f, 170000000000000000000);
emit TokenLimitMinSet(0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2, 10000000000000000000000);
emit TokenLimitMinSet(0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32, 1800000000000000000000);
emit TokenLimitMinSet(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2, 1800000000000000000);
emit TokenLimitMinSet(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984, 400000000000000000000);
emit TokenLimitMinSet(0x514910771AF9Ca656af840dff83E8264EcF986CA, 250000000000000000000);
emit TokenLimitMinSet(0x3c3a81e81dc49A522A592e7622A7E711c06bf354, 5000000000000000000000);
emit TokenLimitMaxMultiplierSet(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 950000000000000000);
emit TokenLimitMaxMultiplierSet(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 950000000000000000);
emit TokenLimitMaxMultiplierSet(0xdAC17F958D2ee523a2206206994597C13D831ec7, 950000000000000000);
emit TokenLimitMaxMultiplierSet(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, 950000000000000000);
emit TokenLimitMaxMultiplierSet(0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0, 950000000000000000);
emit TokenLimitMaxMultiplierSet(0xD33526068D116cE69F19A9ee46F0bd304F21A51f, 950000000000000000);
emit TokenLimitMaxMultiplierSet(0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2, 950000000000000000);
emit TokenLimitMaxMultiplierSet(0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32, 950000000000000000);
emit TokenLimitMaxMultiplierSet(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2, 950000000000000000);
emit TokenLimitMaxMultiplierSet(0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984, 950000000000000000);
emit TokenLimitMaxMultiplierSet(0x514910771AF9Ca656af840dff83E8264EcF986CA, 950000000000000000);
emit TokenLimitMaxMultiplierSet(0x3c3a81e81dc49A522A592e7622A7E711c06bf354, 950000000000000000);
emit TwapIntervalSet(0x2fe16Dd18bba26e457B7dD2080d5674312b026a2, 300);
emit TwapIntervalSet(0x048f0e7ea2CFD522a4a058D1b1bDd574A0486c46, 300);
emit TwapIntervalSet(0x37F6dF71b40c50b2038329CaBf5FDa3682Df1ebF, 300);
emit TwapIntervalSet(0x6ec472b613012a492693697FA551420E60567eA7, 300);
emit TwapIntervalSet(0x29b57D56a114aE5BE3c129240898B3321A70A300, 300);
emit TwapIntervalSet(0x61fA1CEe13CEEAF20C30611c5e6dA48c595F7dB2, 300);
emit TwapIntervalSet(0x045950A37c59d75496BB4Af68c05f9066A4C7e27, 300);
emit TwapIntervalSet(0xbEE7Ef1adfaa628536Ebc0C1EBF082DbDC27265F, 300);
emit TwapIntervalSet(0x51baDc1622C63d1E448A4F1aC1DC008b8a27Fe67, 300);
emit TwapIntervalSet(0x0e52DB138Df9CE54Bc9D9330f418015eD512830A, 300);
emit TwapIntervalSet(0xDDE7684D88E0B482B2b455936fe0D22dd48CDcb3, 300);
emit TwapIntervalSet(0x43102f07414D95eF71EC9aEbA011b8595BA010D0, 300);
}
// constant mapping for tolerance
function getTolerance(address) public pure override returns (uint16) {
return 0;
}
// constant mapping for tokenLimitMin
function getTokenLimitMin(address token) public pure override returns (uint256) {
if (token == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) return 1200000000000000000;
if (token == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 5000000000;
if (token == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return 5000000000;
if (token == 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599) return 7000000;
if (token == 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0) return 1100000000000000000;
if (token == 0xD33526068D116cE69F19A9ee46F0bd304F21A51f) return 170000000000000000000;
if (token == 0x48C3399719B582dD63eB5AADf12A40B4C3f52FA2) return 10000000000000000000000;
if (token == 0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32) return 1800000000000000000000;
if (token == 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2) return 1800000000000000000;
if (token == 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984) return 400000000000000000000;
if (token == 0x514910771AF9Ca656af840dff83E8264EcF986CA) return 250000000000000000000;
if (token == 0x3c3a81e81dc49A522A592e7622A7E711c06bf354) return 5000000000000000000000;
return 0;
}
// constant mapping for tokenLimitMaxMultiplier
function getTokenLimitMaxMultiplier(address) public pure override returns (uint256) {
return 950000000000000000;
}
// constant mapping for twapInterval
function getTwapInterval(address) public pure override returns (uint32) {
return 300;
}
/*
* Methods for backward compatibility
*/
function factory() external pure override returns (address) {
return FACTORY_ADDRESS;
}
function delay() external pure override returns (address) {
return DELAY_ADDRESS;
}
function weth() external pure override returns (address) {
return WETH_ADDRESS;
}
function twapInterval(address pair) external pure override returns (uint32) {
return getTwapInterval(pair);
}
function ethTransferGasCost() external pure override returns (uint256) {
return Orders.ETHER_TRANSFER_COST;
}
function executionGasLimit() external pure override returns (uint256) {
return EXECUTION_GAS_LIMIT;
}
function tokenLimitMin(address token) external pure override returns (uint256) {
return getTokenLimitMin(token);
}
function tokenLimitMaxMultiplier(address token) external pure override returns (uint256) {
return getTokenLimitMaxMultiplier(token);
}
function tolerance(address pair) external pure override returns (uint16) {
return getTolerance(pair);
}
receive() external payable {}
}