Transaction Hash:
Block:
18630763 at Nov-23-2023 12:09:35 AM +UTC
Transaction Fee:
0.008755436538702086 ETH
$22.64
Gas Used:
273,694 Gas / 31.989873869 Gwei
Emitted Events:
228 |
FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x00000000000000000000000035cb375799b28c8d6b7c5c8d494ed180ae2e60cb, 0x0000000000000000000000002fe16dd18bba26e457b7dd2080d5674312b026a2, 0000000000000000000000000000000000000000000000000000001a13b86000 )
|
229 |
WETH9.Transfer( src=TwapPair, dst=Proxy, wad=54219094909615096876 )
|
230 |
TwapPair.Swap( sender=[Receiver] TwapDelay, amount0In=112000000000, amount1In=0, amount0Out=0, amount1Out=54219094909615096876, to=Proxy )
|
231 |
TwapDelay.EthRefund( to=[Sender] 0x3a1d749fa4a9e650fce844ff1c58c5faf7e2a9d1, success=True, value=9079522959063510 )
|
232 |
TwapDelay.EthRefund( to=Proxy, success=True, value=9513196800936490 )
|
233 |
TwapDelay.OrderExecuted( id=1412, success=True, data=0x, gasSpent=244858, ethRefunded=9513196800936490 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x2fe16Dd1...312b026a2 | |||||
0x35Cb3757...0AE2E60cB | 0.0371331043075 Eth | 0.0185403845475 Eth | 0.01859271976 | ||
0x3a1D749f...af7e2a9D1 |
0.801960595817059665 Eth
Nonce: 11029
|
0.802284682237421089 Eth
Nonce: 11030
| 0.000324086420361424 | ||
0x95222290...5CC4BAfe5
Miner
| (beaverbuild) | 7.801531341452574807 Eth | 7.801563748112915711 Eth | 0.000032406660340904 | |
0xA0b86991...E3606eB48 | |||||
0xC02aaA39...83C756Cc2 | |||||
0xd17b3c97...3BcD81e2E | (Integral: TWAP Relayer) | 0.813013007691465493 Eth | 0.822526204492401983 Eth | 0.00951319680093649 |
Execution Trace
TwapDelay.execute( _orders= )
-
Orders.2e548b5b( )
TwapDelay._executeSell( order=[{name:orderId, type:uint256, order:1, indexed:false, value:1412, valueString:1412}, {name:orderType, type:uint8, order:2, indexed:false, value:3, valueString:3}, {name:inverted, type:bool, order:3, indexed:false, value:false, valueString:False}, {name:validAfterTimestamp, type:uint256, order:4, indexed:false, value:1700698139, valueString:1700698139}, {name:unwrap, type:bool, order:5, indexed:false, value:false, valueString:False}, {name:timestamp, type:uint256, order:6, indexed:false, value:1700696339, valueString:1700696339}, {name:gasLimit, type:uint256, order:7, indexed:false, value:500000, valueString:500000}, {name:gasPrice, type:uint256, order:8, indexed:false, value:37185439520, valueString:37185439520}, {name:liquidity, type:uint256, order:9, indexed:false, value:0, valueString:0}, {name:value0, type:uint256, order:10, indexed:false, value:112000000000, valueString:112000000000}, {name:value1, type:uint256, order:11, indexed:false, value:0, valueString:0}, {name:token0, type:address, order:12, indexed:false, value:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, valueString:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48}, {name:token1, type:address, order:13, indexed:false, value:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, valueString:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2}, {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:112000000000, valueString:112000000000}, {name:amountLimit1, type:uint256, order:20, indexed:false, value:0, valueString:0}] )
-
TwapFactory.getPair( 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ) => ( 0x2fe16Dd18bba26e457B7dD2080d5674312b026a2 )
TwapPair.CALL( )
FiatTokenProxy.70a08231( )
-
FiatTokenV2_1.balanceOf( account=0x2fe16Dd18bba26e457B7dD2080d5674312b026a2 ) => ( 32910192383 )
-
-
WETH9.balanceOf( 0x2fe16Dd18bba26e457B7dD2080d5674312b026a2 ) => ( 259856818046157547700 )
ExecutionHelper.143d9d38( )
-
TwapPair.STATICCALL( )
TwapOracleV3.getAveragePrice( 0, 1700696339 ) => ( 484147476440636 )
-
Uniswap V3: USDC 3.883bdbfd( )
-
-
TwapPair.STATICCALL( )
-
TwapPair.STATICCALL( )
-
TwapPair.STATICCALL( )
-
TokenShares.a8d669b4( )
-
TwapOracleV3.getSwapAmount1Out( swapFee=100000000000000, amount0In=112000000000, data=0x0000000000000000000000000000000000000000000000000001B8545E5A263C ) => ( amount1Out=54219094909615096876 )
FiatTokenProxy.a9059cbb( )
-
FiatTokenV2_1.transfer( to=0x2fe16Dd18bba26e457B7dD2080d5674312b026a2, value=112000000000 ) => ( True )
-
TwapPair.swap( amount0Out=0, amount1Out=54219094909615096876, to=0xd17b3c9784510E33cD5B87b490E79253BcD81e2E, data=0x0000000000000000000000000000000000000000000000000001B8545E5A263C )
-
WETH9.transfer( dst=0xd17b3c9784510E33cD5B87b490E79253BcD81e2E, wad=54219094909615096876 ) => ( True )
FiatTokenProxy.70a08231( )
-
FiatTokenV2_1.balanceOf( account=0x2fe16Dd18bba26e457B7dD2080d5674312b026a2 ) => ( 144910192383 )
-
-
WETH9.balanceOf( 0x2fe16Dd18bba26e457B7dD2080d5674312b026a2 ) => ( 205637723136542450824 )
-
TwapOracleV3.tradeX( xAfter=141805269978, xBefore=29816469978, yBefore=258260488992688327071, data=0x0000000000000000000000000000000000000000000000000001B8545E5A263C ) => ( yAfter=204041394083073230195 )
-
-
-
- ETH 0.00907952295906351
0x3a1d749fa4a9e650fce844ff1c58c5faf7e2a9d1.CALL( )
ETH 0.00951319680093649
Proxy.CALL( )
- ETH 0.00951319680093649
TwapRelayer.DELEGATECALL( )
- ETH 0.00951319680093649
-
Orders.9db74df1( )
execute[TwapDelay (ln:1897)]
gasleft[TwapDelay (ln:1899)]
dequeueOrder[TwapDelay (ln:1907)]
verifyOrder[TwapDelay (ln:1910)]
executeDeposit[TwapDelay (ln:1918)]
gasleft[TwapDelay (ln:1933)]
dequeueOrder[TwapDelay (ln:1934)]
call[TwapDelay (ln:1935)]
sub[TwapDelay (ln:1936)]
add[TwapDelay (ln:1937)]
add[TwapDelay (ln:1937)]
getTransferGasCost[TwapDelay (ln:1937)]
getTransferGasCost[TwapDelay (ln:1938)]
encodeWithSelector[TwapDelay (ln:1941)]
refundTokens[TwapDelay (ln:1944)]
call[TwapDelay (ln:2055)]
add[TwapDelay (ln:2056)]
getTransferGasCost[TwapDelay (ln:2056)]
getTransferGasCost[TwapDelay (ln:2056)]
encodeWithSelector[TwapDelay (ln:2057)]
RefundFailed[TwapDelay (ln:2059)]
RefundFailed[TwapDelay (ln:2060)]
finalizeOrder[TwapDelay (ln:1953)]
markRefundFailed[TwapDelay (ln:2005)]
forgetLastProcessedOrder[TwapDelay (ln:2007)]
refund[TwapDelay (ln:1954)]
mul[TwapDelay (ln:2016)]
add[TwapDelay (ln:2017)]
sub[TwapDelay (ln:2017)]
gasleft[TwapDelay (ln:2017)]
min[TwapDelay (ln:2018)]
mul[TwapDelay (ln:2018)]
sub[TwapDelay (ln:2019)]
refundEth[TwapDelay (ln:2020)]
transferETH[TwapDelay (ln:2027)]
getTransferGasCost[TwapDelay (ln:2027)]
EthRefund[TwapDelay (ln:2028)]
refundEth[TwapDelay (ln:2021)]
transferETH[TwapDelay (ln:2027)]
getTransferGasCost[TwapDelay (ln:2027)]
EthRefund[TwapDelay (ln:2028)]
payable[TwapDelay (ln:2021)]
OrderExecuted[TwapDelay (ln:1955)]
executeWithdraw[TwapDelay (ln:1920)]
gasleft[TwapDelay (ln:1959)]
dequeueOrder[TwapDelay (ln:1960)]
call[TwapDelay (ln:1961)]
sub[TwapDelay (ln:1962)]
add[TwapDelay (ln:1962)]
encodeWithSelector[TwapDelay (ln:1963)]
getPair[TwapDelay (ln:1966)]
getPair[Orders (ln:939)]
refundLiquidity[TwapDelay (ln:1967)]
call[Orders (ln:1336)]
encodeWithSelector[Orders (ln:1337)]
RefundFailed[Orders (ln:1340)]
finalizeOrder[TwapDelay (ln:1969)]
markRefundFailed[TwapDelay (ln:2005)]
forgetLastProcessedOrder[TwapDelay (ln:2007)]
refund[TwapDelay (ln:1970)]
mul[TwapDelay (ln:2016)]
add[TwapDelay (ln:2017)]
sub[TwapDelay (ln:2017)]
gasleft[TwapDelay (ln:2017)]
min[TwapDelay (ln:2018)]
mul[TwapDelay (ln:2018)]
sub[TwapDelay (ln:2019)]
refundEth[TwapDelay (ln:2020)]
transferETH[TwapDelay (ln:2027)]
getTransferGasCost[TwapDelay (ln:2027)]
EthRefund[TwapDelay (ln:2028)]
refundEth[TwapDelay (ln:2021)]
transferETH[TwapDelay (ln:2027)]
getTransferGasCost[TwapDelay (ln:2027)]
EthRefund[TwapDelay (ln:2028)]
payable[TwapDelay (ln:2021)]
OrderExecuted[TwapDelay (ln:1971)]
executeSell[TwapDelay (ln:1922)]
gasleft[TwapDelay (ln:1975)]
dequeueOrder[TwapDelay (ln:1976)]
call[TwapDelay (ln:1977)]
sub[TwapDelay (ln:1978)]
add[TwapDelay (ln:1978)]
getTransferGasCost[TwapDelay (ln:1978)]
encodeWithSelector[TwapDelay (ln:1979)]
refundToken[TwapDelay (ln:1982)]
call[TwapDelay (ln:2039)]
getTransferGasCost[TwapDelay (ln:2039)]
encodeWithSelector[TwapDelay (ln:2040)]
RefundFailed[TwapDelay (ln:2043)]
finalizeOrder[TwapDelay (ln:1984)]
markRefundFailed[TwapDelay (ln:2005)]
forgetLastProcessedOrder[TwapDelay (ln:2007)]
refund[TwapDelay (ln:1985)]
mul[TwapDelay (ln:2016)]
add[TwapDelay (ln:2017)]
sub[TwapDelay (ln:2017)]
gasleft[TwapDelay (ln:2017)]
min[TwapDelay (ln:2018)]
mul[TwapDelay (ln:2018)]
sub[TwapDelay (ln:2019)]
refundEth[TwapDelay (ln:2020)]
transferETH[TwapDelay (ln:2027)]
getTransferGasCost[TwapDelay (ln:2027)]
EthRefund[TwapDelay (ln:2028)]
refundEth[TwapDelay (ln:2021)]
transferETH[TwapDelay (ln:2027)]
getTransferGasCost[TwapDelay (ln:2027)]
EthRefund[TwapDelay (ln:2028)]
payable[TwapDelay (ln:2021)]
OrderExecuted[TwapDelay (ln:1986)]
executeBuy[TwapDelay (ln:1924)]
gasleft[TwapDelay (ln:1990)]
dequeueOrder[TwapDelay (ln:1991)]
call[TwapDelay (ln:1992)]
sub[TwapDelay (ln:1993)]
add[TwapDelay (ln:1993)]
getTransferGasCost[TwapDelay (ln:1993)]
encodeWithSelector[TwapDelay (ln:1994)]
refundToken[TwapDelay (ln:1997)]
call[TwapDelay (ln:2039)]
getTransferGasCost[TwapDelay (ln:2039)]
encodeWithSelector[TwapDelay (ln:2040)]
RefundFailed[TwapDelay (ln:2043)]
finalizeOrder[TwapDelay (ln:1999)]
markRefundFailed[TwapDelay (ln:2005)]
forgetLastProcessedOrder[TwapDelay (ln:2007)]
refund[TwapDelay (ln:2000)]
mul[TwapDelay (ln:2016)]
add[TwapDelay (ln:2017)]
sub[TwapDelay (ln:2017)]
gasleft[TwapDelay (ln:2017)]
min[TwapDelay (ln:2018)]
mul[TwapDelay (ln:2018)]
sub[TwapDelay (ln:2019)]
refundEth[TwapDelay (ln:2020)]
transferETH[TwapDelay (ln:2027)]
getTransferGasCost[TwapDelay (ln:2027)]
EthRefund[TwapDelay (ln:2028)]
refundEth[TwapDelay (ln:2021)]
transferETH[TwapDelay (ln:2027)]
getTransferGasCost[TwapDelay (ln:2027)]
EthRefund[TwapDelay (ln:2028)]
payable[TwapDelay (ln:2021)]
OrderExecuted[TwapDelay (ln:2001)]
updateGasPrice[TwapDelay (ln:1928)]
sub[TwapDelay (ln:1928)]
gasleft[TwapDelay (ln:1928)]
File 1 of 12: TwapDelay
File 2 of 12: FiatTokenProxy
File 3 of 12: TwapPair
File 4 of 12: Proxy
File 5 of 12: WETH9
File 6 of 12: Orders
File 7 of 12: TwapFactory
File 8 of 12: FiatTokenV2_1
File 9 of 12: ExecutionHelper
File 10 of 12: TwapOracleV3
File 11 of 12: TokenShares
File 12 of 12: 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 public constant ORDER_BASE_COST = EXECUTE_PREPARATION_COST + 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 { { // scope for checks, avoids stack too deep errors uint256 token0TransferCost = getTransferGasCost(depositParams.token0); uint256 token1TransferCost = getTransferGasCost(depositParams.token1); checkOrderParams( depositParams.to, depositParams.gasLimit, depositParams.submitDeadline, ORDER_BASE_COST.add(token0TransferCost).add(token1TransferCost) ); } 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, ORDER_BASE_COST.add(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 { uint256 tokenTransferCost = getTransferGasCost(sellParams.tokenIn); checkOrderParams( sellParams.to, sellParams.gasLimit, sellParams.submitDeadline, ORDER_BASE_COST.add(tokenTransferCost) ); (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, ORDER_BASE_COST); (, 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 { uint256 tokenTransferCost = getTransferGasCost(buyParams.tokenIn); checkOrderParams( buyParams.to, buyParams.gasLimit, buyParams.submitDeadline, ORDER_BASE_COST.add(tokenTransferCost) ); 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.sub(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 == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 70000; 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; 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; modifier lock() { require(locked == 0, 'TD06'); locked = 1; _; locked = 0; } 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.ORDER_BASE_COST.add(Orders.getTransferGasCost(order.token0)).add( 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 ); } 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.ORDER_BASE_COST.add(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.ORDER_BASE_COST.add(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); } 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.ORDER_BASE_COST.add(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); } 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 ) private returns (bool) { if (share == 0) { return true; } (bool success, bytes memory data) = address(this).call{ gas: 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 ) private returns (bool) { (bool success, bytes memory data) = address(this).call{ gas: Orders.getTransferGasCost(token0).add(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), '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), '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), '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 TransferGasCostSet(Orders.NATIVE_CURRENCY_SENTINEL, Orders.ETHER_TRANSFER_CALL_COST); emit TransferGasCostSet(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 60000); emit TransferGasCostSet(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 70000); emit TransferGasCostSet(0xdAC17F958D2ee523a2206206994597C13D831ec7, 60000); emit TransferGasCostSet(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, 60000); emit TransferGasCostSet(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B, 60000); emit TransferGasCostSet(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2, 60000); emit NonRebasingTokenSet(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, true); emit NonRebasingTokenSet(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, true); emit NonRebasingTokenSet(0xdAC17F958D2ee523a2206206994597C13D831ec7, true); emit NonRebasingTokenSet(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, true); emit NonRebasingTokenSet(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B, false); emit NonRebasingTokenSet(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2, false); } // 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 12: FiatTokenProxy
pragma solidity ^0.4.24; // File: zos-lib/contracts/upgradeability/Proxy.sol /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. 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) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // File: openzeppelin-solidity/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } // File: zos-lib/contracts/upgradeability/UpgradeabilityProxy.sol /** * @title UpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Contract constructor. * @param _implementation Address of the initial implementation. */ constructor(address _implementation) public { assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation")); _setImplementation(_implementation); } /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } // File: zos-lib/contracts/upgradeability/AdminUpgradeabilityProxy.sol /** * @title AdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * Contract constructor. * It sets the `msg.sender` as the proxy administrator. * @param _implementation address of the initial implementation. */ constructor(address _implementation) UpgradeabilityProxy(_implementation) public { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(msg.sender); } /** * @return The address of the proxy admin. */ function admin() external view ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external view ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin { _upgradeTo(newImplementation); require(address(this).call.value(msg.value)(data)); } /** * @return The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } // File: contracts/FiatTokenProxy.sol /** * Copyright CENTRE SECZ 2018 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished to * do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.4.24; /** * @title FiatTokenProxy * @dev This contract proxies FiatToken calls and enables FiatToken upgrades */ contract FiatTokenProxy is AdminUpgradeabilityProxy { constructor(address _implementation) public AdminUpgradeabilityProxy(_implementation) { } }
File 3 of 12: 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 4 of 12: 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 12: 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 6 of 12: 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 public constant ORDER_BASE_COST = EXECUTE_PREPARATION_COST + 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 { { // scope for checks, avoids stack too deep errors uint256 token0TransferCost = getTransferGasCost(depositParams.token0); uint256 token1TransferCost = getTransferGasCost(depositParams.token1); checkOrderParams( depositParams.to, depositParams.gasLimit, depositParams.submitDeadline, ORDER_BASE_COST.add(token0TransferCost).add(token1TransferCost) ); } 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, ORDER_BASE_COST.add(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 { uint256 tokenTransferCost = getTransferGasCost(sellParams.tokenIn); checkOrderParams( sellParams.to, sellParams.gasLimit, sellParams.submitDeadline, ORDER_BASE_COST.add(tokenTransferCost) ); (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, ORDER_BASE_COST); (, 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 { uint256 tokenTransferCost = getTransferGasCost(buyParams.tokenIn); checkOrderParams( buyParams.to, buyParams.gasLimit, buyParams.submitDeadline, ORDER_BASE_COST.add(tokenTransferCost) ); 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.sub(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 == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 70000; 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; 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 12: 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 12: FiatTokenV2_1
// File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: 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 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/v1/AbstractFiatTokenV1.sol /** * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; abstract contract AbstractFiatTokenV1 is IERC20 { function _approve( address owner, address spender, uint256 value ) internal virtual; function _transfer( address from, address to, uint256 value ) internal virtual; } // File: contracts/v1/Ownable.sol /** * Copyright (c) 2018 zOS Global Limited. * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @notice The Ownable contract has an owner address, and provides basic * authorization control functions * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol * Modifications: * 1. Consolidate OwnableStorage into this contract (7/13/18) * 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 3. Make public functions external (5/27/20) */ contract Ownable { // Owner of the contract address private _owner; /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev The constructor sets the original owner of the contract to the sender account. */ constructor() public { setOwner(msg.sender); } /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() external view returns (address) { return _owner; } /** * @dev Sets a new owner address */ function setOwner(address newOwner) internal { _owner = newOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == _owner, "Ownable: caller is not the owner"); _; } /** * @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) external onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); setOwner(newOwner); } } // File: contracts/v1/Pausable.sol /** * Copyright (c) 2016 Smart Contract Solutions, Inc. * Copyright (c) 2018-2020 CENTRE SECZ0 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @notice Base contract which allows children to implement an emergency stop * mechanism * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol * Modifications: * 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018) * 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018) * 3. Removed whenPaused (6/14/2018) * 4. Switches ownable library to use ZeppelinOS (7/12/18) * 5. Remove constructor (7/13/18) * 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20) * 7. Make public functions external (5/27/20) */ contract Pausable is Ownable { event Pause(); event Unpause(); event PauserChanged(address indexed newAddress); address public pauser; bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "Pausable: paused"); _; } /** * @dev throws if called by any account other than the pauser */ modifier onlyPauser() { require(msg.sender == pauser, "Pausable: caller is not the pauser"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() external onlyPauser { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() external onlyPauser { paused = false; emit Unpause(); } /** * @dev update the pauser role */ function updatePauser(address _newPauser) external onlyOwner { require( _newPauser != address(0), "Pausable: new pauser is the zero address" ); pauser = _newPauser; emit PauserChanged(pauser); } } // File: contracts/v1/Blacklistable.sol /** * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title Blacklistable Token * @dev Allows accounts to be blacklisted by a "blacklister" role */ contract Blacklistable is Ownable { address public blacklister; mapping(address => bool) internal blacklisted; event Blacklisted(address indexed _account); event UnBlacklisted(address indexed _account); event BlacklisterChanged(address indexed newBlacklister); /** * @dev Throws if called by any account other than the blacklister */ modifier onlyBlacklister() { require( msg.sender == blacklister, "Blacklistable: caller is not the blacklister" ); _; } /** * @dev Throws if argument account is blacklisted * @param _account The address to check */ modifier notBlacklisted(address _account) { require( !blacklisted[_account], "Blacklistable: account is blacklisted" ); _; } /** * @dev Checks if account is blacklisted * @param _account The address to check */ function isBlacklisted(address _account) external view returns (bool) { return blacklisted[_account]; } /** * @dev Adds account to blacklist * @param _account The address to blacklist */ function blacklist(address _account) external onlyBlacklister { blacklisted[_account] = true; emit Blacklisted(_account); } /** * @dev Removes account from blacklist * @param _account The address to remove from the blacklist */ function unBlacklist(address _account) external onlyBlacklister { blacklisted[_account] = false; emit UnBlacklisted(_account); } function updateBlacklister(address _newBlacklister) external onlyOwner { require( _newBlacklister != address(0), "Blacklistable: new blacklister is the zero address" ); blacklister = _newBlacklister; emit BlacklisterChanged(blacklister); } } // File: contracts/v1/FiatTokenV1.sol /** * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */ contract FiatTokenV1 is AbstractFiatTokenV1, Ownable, Pausable, Blacklistable { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string memory tokenName, string memory tokenSymbol, string memory tokenCurrency, uint8 tokenDecimals, address newMasterMinter, address newPauser, address newBlacklister, address newOwner ) public { require(!initialized, "FiatToken: contract is already initialized"); require( newMasterMinter != address(0), "FiatToken: new masterMinter is the zero address" ); require( newPauser != address(0), "FiatToken: new pauser is the zero address" ); require( newBlacklister != address(0), "FiatToken: new blacklister is the zero address" ); require( newOwner != address(0), "FiatToken: new owner is the zero address" ); name = tokenName; symbol = tokenSymbol; currency = tokenCurrency; decimals = tokenDecimals; masterMinter = newMasterMinter; pauser = newPauser; blacklister = newBlacklister; setOwner(newOwner); initialized = true; } /** * @dev Throws if called by any account other than a minter */ modifier onlyMinters() { require(minters[msg.sender], "FiatToken: caller is not a minter"); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. Must be less than or equal * to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) external whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) returns (bool) { require(_to != address(0), "FiatToken: mint to the zero address"); require(_amount > 0, "FiatToken: mint amount not greater than 0"); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require( _amount <= mintingAllowedAmount, "FiatToken: mint amount exceeds minterAllowance" ); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Throws if called by any account other than the masterMinter */ modifier onlyMasterMinter() { require( msg.sender == masterMinter, "FiatToken: caller is not the masterMinter" ); _; } /** * @dev Get minter allowance for an account * @param minter The address of the minter */ function minterAllowance(address minter) external view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks if account is a minter * @param account The address to check */ function isMinter(address account) external view returns (bool) { return minters[account]; } /** * @notice Amount of remaining tokens spender is allowed to transfer on * behalf of the token owner * @param owner Token owner's address * @param spender Spender's address * @return Allowance amount */ function allowance(address owner, address spender) external override view returns (uint256) { return allowed[owner][spender]; } /** * @dev Get totalSupply of token */ function totalSupply() external override view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * @param account address The account */ function balanceOf(address account) external override view returns (uint256) { return balances[account]; } /** * @notice Set spender's allowance over the caller's tokens to be a given * value. * @param spender Spender's address * @param value Allowance amount * @return True if successful */ function approve(address spender, uint256 value) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Internal function to set allowance * @param owner Token owner's address * @param spender Spender's address * @param value Allowance amount */ function _approve( address owner, address spender, uint256 value ) internal override { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @notice Transfer tokens by spending allowance * @param from Payer's address * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transferFrom( address from, address to, uint256 value ) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(from) notBlacklisted(to) returns (bool) { require( value <= allowed[from][msg.sender], "ERC20: transfer amount exceeds allowance" ); _transfer(from, to, value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); return true; } /** * @notice Transfer tokens from the caller * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transfer(address to, uint256 value) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(to) returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @notice Internal function to process transfers * @param from Payer's address * @param to Payee's address * @param value Transfer amount */ function _transfer( address from, address to, uint256 value ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require( value <= balances[from], "ERC20: transfer amount exceeds balance" ); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Function to add/update a new minter * @param minter The address of the minter * @param minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) external whenNotPaused onlyMasterMinter returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * @param minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) external onlyMasterMinter returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter's account balance * @param _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) external whenNotPaused onlyMinters notBlacklisted(msg.sender) { uint256 balance = balances[msg.sender]; require(_amount > 0, "FiatToken: burn amount not greater than 0"); require(balance >= _amount, "FiatToken: burn amount exceeds balance"); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) external onlyOwner { require( _newMasterMinter != address(0), "FiatToken: new masterMinter is the zero address" ); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/v1.1/Rescuable.sol /** * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; contract Rescuable is Ownable { using SafeERC20 for IERC20; address private _rescuer; event RescuerChanged(address indexed newRescuer); /** * @notice Returns current rescuer * @return Rescuer's address */ function rescuer() external view returns (address) { return _rescuer; } /** * @notice Revert if called by any account other than the rescuer. */ modifier onlyRescuer() { require(msg.sender == _rescuer, "Rescuable: caller is not the rescuer"); _; } /** * @notice Rescue ERC20 tokens locked up in this contract. * @param tokenContract ERC20 token contract address * @param to Recipient address * @param amount Amount to withdraw */ function rescueERC20( IERC20 tokenContract, address to, uint256 amount ) external onlyRescuer { tokenContract.safeTransfer(to, amount); } /** * @notice Assign the rescuer role to a given address. * @param newRescuer New rescuer's address */ function updateRescuer(address newRescuer) external onlyOwner { require( newRescuer != address(0), "Rescuable: new rescuer is the zero address" ); _rescuer = newRescuer; emit RescuerChanged(newRescuer); } } // File: contracts/v1.1/FiatTokenV1_1.sol /** * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title FiatTokenV1_1 * @dev ERC20 Token backed by fiat reserves */ contract FiatTokenV1_1 is FiatTokenV1, Rescuable { } // File: contracts/v2/AbstractFiatTokenV2.sol /** * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; abstract contract AbstractFiatTokenV2 is AbstractFiatTokenV1 { function _increaseAllowance( address owner, address spender, uint256 increment ) internal virtual; function _decreaseAllowance( address owner, address spender, uint256 decrement ) internal virtual; } // File: contracts/util/ECRecover.sol /** * Copyright (c) 2016-2019 zOS Global Limited * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title ECRecover * @notice A library that provides a safe ECDSA recovery function */ library ECRecover { /** * @notice Recover signer's address from a signed message * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol * Modifications: Accept v, r, and s as separate arguments * @param digest Keccak-256 hash digest of the signed message * @param v v of the signature * @param r r of the signature * @param s s of the signature * @return Signer address */ function recover( bytes32 digest, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if ( uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 ) { revert("ECRecover: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECRecover: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(digest, v, r, s); require(signer != address(0), "ECRecover: invalid signature"); return signer; } } // File: contracts/util/EIP712.sol /** * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title EIP712 * @notice A library that provides EIP712 helper functions */ library EIP712 { /** * @notice Make EIP712 domain separator * @param name Contract name * @param version Contract version * @return Domain separator */ function makeDomainSeparator(string memory name, string memory version) internal view returns (bytes32) { uint256 chainId; assembly { chainId := chainid() } return keccak256( abi.encode( // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } /** * @notice Recover signer's address from a EIP712 signature * @param domainSeparator Domain separator * @param v v of the signature * @param r r of the signature * @param s s of the signature * @param typeHashAndData Type hash concatenated with data * @return Signer's address */ function recover( bytes32 domainSeparator, uint8 v, bytes32 r, bytes32 s, bytes memory typeHashAndData ) internal pure returns (address) { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, keccak256(typeHashAndData) ) ); return ECRecover.recover(digest, v, r, s); } } // File: contracts/v2/EIP712Domain.sol /** * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title EIP712 Domain */ contract EIP712Domain { /** * @dev EIP712 Domain Separator */ bytes32 public DOMAIN_SEPARATOR; } // File: contracts/v2/EIP3009.sol /** * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title EIP-3009 * @notice Provide internal implementation for gas-abstracted transfers * @dev Contracts that inherit from this must wrap these with publicly * accessible functions, optionally adding modifiers where necessary */ abstract contract EIP3009 is AbstractFiatTokenV2, EIP712Domain { // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; /** * @dev authorizer address => nonce => bool (true if nonce is used) */ mapping(address => mapping(bytes32 => bool)) private _authorizationStates; event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event AuthorizationCanceled( address indexed authorizer, bytes32 indexed nonce ); /** * @notice Returns the state of an authorization * @dev Nonces are randomly generated 32-byte data unique to the * authorizer's address * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @return True if the nonce is used */ function authorizationState(address authorizer, bytes32 nonce) external view returns (bool) { return _authorizationStates[authorizer][nonce]; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Receive a transfer with a signed authorization from the payer * @dev This has an additional check to ensure that the payee's address * matches the caller of this function to prevent front-running attacks. * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { require(to == msg.sender, "FiatTokenV2: caller must be the payee"); _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( RECEIVE_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Attempt to cancel an authorization * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireUnusedAuthorization(authorizer, nonce); bytes memory data = abi.encode( CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == authorizer, "FiatTokenV2: invalid signature" ); _authorizationStates[authorizer][nonce] = true; emit AuthorizationCanceled(authorizer, nonce); } /** * @notice Check that an authorization is unused * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _requireUnusedAuthorization(address authorizer, bytes32 nonce) private view { require( !_authorizationStates[authorizer][nonce], "FiatTokenV2: authorization is used or canceled" ); } /** * @notice Check that authorization is valid * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) */ function _requireValidAuthorization( address authorizer, bytes32 nonce, uint256 validAfter, uint256 validBefore ) private view { require( now > validAfter, "FiatTokenV2: authorization is not yet valid" ); require(now < validBefore, "FiatTokenV2: authorization is expired"); _requireUnusedAuthorization(authorizer, nonce); } /** * @notice Mark an authorization as used * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _markAuthorizationAsUsed(address authorizer, bytes32 nonce) private { _authorizationStates[authorizer][nonce] = true; emit AuthorizationUsed(authorizer, nonce); } } // File: contracts/v2/EIP2612.sol /** * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title EIP-2612 * @notice Provide internal implementation for gas-abstracted approvals */ abstract contract EIP2612 is AbstractFiatTokenV2, EIP712Domain { // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) private _permitNonces; /** * @notice Nonces for permit * @param owner Token owner's address (Authorizer) * @return Next nonce */ function nonces(address owner) external view returns (uint256) { return _permitNonces[owner]; } /** * @notice Verify a signed approval permit and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline The time at which this expires (unix time) * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { require(deadline >= now, "FiatTokenV2: permit is expired"); bytes memory data = abi.encode( PERMIT_TYPEHASH, owner, spender, value, _permitNonces[owner]++, deadline ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner, "EIP2612: invalid signature" ); _approve(owner, spender, value); } } // File: contracts/v2/FiatTokenV2.sol /** * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title FiatToken V2 * @notice ERC20 Token backed by fiat reserves, version 2 */ contract FiatTokenV2 is FiatTokenV1_1, EIP3009, EIP2612 { uint8 internal _initializedVersion; /** * @notice Initialize v2 * @param newName New token name */ function initializeV2(string calldata newName) external { // solhint-disable-next-line reason-string require(initialized && _initializedVersion == 0); name = newName; DOMAIN_SEPARATOR = EIP712.makeDomainSeparator(newName, "2"); _initializedVersion = 1; } /** * @notice Increase the allowance by a given increment * @param spender Spender's address * @param increment Amount of increase in allowance * @return True if successful */ function increaseAllowance(address spender, uint256 increment) external whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _increaseAllowance(msg.sender, spender, increment); return true; } /** * @notice Decrease the allowance by a given decrement * @param spender Spender's address * @param decrement Amount of decrease in allowance * @return True if successful */ function decreaseAllowance(address spender, uint256 decrement) external whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _decreaseAllowance(msg.sender, spender, decrement); return true; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) { _transferWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Receive a transfer with a signed authorization from the payer * @dev This has an additional check to ensure that the payee's address * matches the caller of this function to prevent front-running attacks. * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) { _receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Attempt to cancel an authorization * @dev Works only if the authorization is not yet used. * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused { _cancelAuthorization(authorizer, nonce, v, r, s); } /** * @notice Update allowance with a signed permit * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline Expiration time, seconds since the epoch * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) { _permit(owner, spender, value, deadline, v, r, s); } /** * @notice Internal function to increase the allowance by a given increment * @param owner Token owner's address * @param spender Spender's address * @param increment Amount of increase */ function _increaseAllowance( address owner, address spender, uint256 increment ) internal override { _approve(owner, spender, allowed[owner][spender].add(increment)); } /** * @notice Internal function to decrease the allowance by a given decrement * @param owner Token owner's address * @param spender Spender's address * @param decrement Amount of decrease */ function _decreaseAllowance( address owner, address spender, uint256 decrement ) internal override { _approve( owner, spender, allowed[owner][spender].sub( decrement, "ERC20: decreased allowance below zero" ) ); } } // File: contracts/v2/FiatTokenV2_1.sol /** * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; // solhint-disable func-name-mixedcase /** * @title FiatToken V2.1 * @notice ERC20 Token backed by fiat reserves, version 2.1 */ contract FiatTokenV2_1 is FiatTokenV2 { /** * @notice Initialize v2.1 * @param lostAndFound The address to which the locked funds are sent */ function initializeV2_1(address lostAndFound) external { // solhint-disable-next-line reason-string require(_initializedVersion == 1); uint256 lockedAmount = balances[address(this)]; if (lockedAmount > 0) { _transfer(address(this), lostAndFound, lockedAmount); } blacklisted[address(this)] = true; _initializedVersion = 2; } /** * @notice Version string for the EIP712 domain separator * @return Version string */ function version() external view returns (string memory) { return "2"; } }
File 9 of 12: 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 public constant ORDER_BASE_COST = EXECUTE_PREPARATION_COST + 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 { { // scope for checks, avoids stack too deep errors uint256 token0TransferCost = getTransferGasCost(depositParams.token0); uint256 token1TransferCost = getTransferGasCost(depositParams.token1); checkOrderParams( depositParams.to, depositParams.gasLimit, depositParams.submitDeadline, ORDER_BASE_COST.add(token0TransferCost).add(token1TransferCost) ); } 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, ORDER_BASE_COST.add(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 { uint256 tokenTransferCost = getTransferGasCost(sellParams.tokenIn); checkOrderParams( sellParams.to, sellParams.gasLimit, sellParams.submitDeadline, ORDER_BASE_COST.add(tokenTransferCost) ); (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, ORDER_BASE_COST); (, 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 { uint256 tokenTransferCost = getTransferGasCost(buyParams.tokenIn); checkOrderParams( buyParams.to, buyParams.gasLimit, buyParams.submitDeadline, ORDER_BASE_COST.add(tokenTransferCost) ); 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.sub(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 == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 70000; 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; 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 10 of 12: 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 11 of 12: 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; 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 12 of 12: 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); 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; } 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 public constant ORDER_BASE_COST = EXECUTE_PREPARATION_COST + 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 { { // scope for checks, avoids stack too deep errors uint256 token0TransferCost = getTransferGasCost(depositParams.token0); uint256 token1TransferCost = getTransferGasCost(depositParams.token1); checkOrderParams( depositParams.to, depositParams.gasLimit, depositParams.submitDeadline, ORDER_BASE_COST.add(token0TransferCost).add(token1TransferCost) ); } 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, ORDER_BASE_COST.add(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 { uint256 tokenTransferCost = getTransferGasCost(sellParams.tokenIn); checkOrderParams( sellParams.to, sellParams.gasLimit, sellParams.submitDeadline, ORDER_BASE_COST.add(tokenTransferCost) ); (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, ORDER_BASE_COST); (, 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 { uint256 tokenTransferCost = getTransferGasCost(buyParams.tokenIn); checkOrderParams( buyParams.to, buyParams.gasLimit, buyParams.submitDeadline, ORDER_BASE_COST.add(tokenTransferCost) ); 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.sub(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 == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 70000; 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; 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 = 0x35Cb375799B28C8D6b7C5C8d494ed180AE2E60cB; uint256 public constant EXECUTION_GAS_LIMIT = 500000; /* * 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; /* * 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 == 0, 'TR06'); locked = 1; _; locked = 0; } // This contract implements a proxy pattern. // The constructor is to set to prevent abuse of this implementation contract. // Setting locked = 1 forces core features, e.g. buy(), to always revert. constructor() { owner = msg.sender; initialized = 1; locked = 1; } // 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; emit Initialized(FACTORY_ADDRESS, DELAY_ADDRESS, WETH_ADDRESS); emit OwnerSet(msg.sender); _emitEventWithDefaults(); } 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) public view override 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) public view override 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); 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); 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 _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 TokenLimitMinSet(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 10000000000000000); emit TokenLimitMinSet(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 20000000); emit TokenLimitMinSet(0xdAC17F958D2ee523a2206206994597C13D831ec7, 20000000); emit TokenLimitMinSet(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, 64500); emit TokenLimitMaxMultiplierSet(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 950000000000000000); emit TokenLimitMaxMultiplierSet(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 950000000000000000); emit TokenLimitMaxMultiplierSet(0xdAC17F958D2ee523a2206206994597C13D831ec7, 950000000000000000); emit TokenLimitMaxMultiplierSet(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, 950000000000000000); emit TwapIntervalSet(0x2fe16Dd18bba26e457B7dD2080d5674312b026a2, 300); emit TwapIntervalSet(0x048f0e7ea2CFD522a4a058D1b1bDd574A0486c46, 300); emit TwapIntervalSet(0x37F6dF71b40c50b2038329CaBf5FDa3682Df1ebF, 300); emit TwapIntervalSet(0x6ec472b613012a492693697FA551420E60567eA7, 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 10000000000000000; if (token == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 20000000; if (token == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return 20000000; if (token == 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599) return 64500; 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 {} }