Transaction Hash:
Block:
11847447 at Feb-13-2021 09:23:26 AM +UTC
Transaction Fee:
0.0986276529 ETH
$248.11
Gas Used:
525,930 Gas / 187.53 Gwei
Emitted Events:
66 |
SoloMargin.0x91b01baeee3a24b590d112613814d86801005c7ef9353e7fc1eaeaf33ccf83b0( 0x91b01baeee3a24b590d112613814d86801005c7ef9353e7fc1eaeaf33ccf83b0, 000000000000000000000000c9e15f678824caf680d282d762133c72103ace8a )
|
67 |
SoloMargin.0xf4626fd1187f91e6761ffb8a6ac3e8d9235a4a92da54e43feb0c57c4a4a322ab( 0xf4626fd1187f91e6761ffb8a6ac3e8d9235a4a92da54e43feb0c57c4a4a322ab, 0x0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000e1a4cd514012a3f, 0000000000000000000000000000000000000000000000000de8035409d7c3e7, 0000000000000000000000000000000000000000000000000000000060279a8e )
|
68 |
WETH9.Transfer( src=SoloMargin, dst=[Receiver] 0xc9e15f678824caf680d282d762133c72103ace8a, wad=29160000000000004000 )
|
69 |
SoloMargin.0xbc83c08f0b269b1726990c8348ffdf1ae1696244a14868d766e542a2f18cd7d4( 0xbc83c08f0b269b1726990c8348ffdf1ae1696244a14868d766e542a2f18cd7d4, 0x000000000000000000000000c9e15f678824caf680d282d762133c72103ace8a, 0000000000000000000000000000000000000000000000000000000000000001, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 00000000000000000000000000000000000000000000000194ad2180f2640fa0, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000018e38b1d40014ecc5, 000000000000000000000000c9e15f678824caf680d282d762133c72103ace8a )
|
70 |
WETH9.Transfer( src=[Receiver] 0xc9e15f678824caf680d282d762133c72103ace8a, dst=UniswapV2Pair, wad=29160000000000004000 )
|
71 |
AlphaToken.Transfer( from=UniswapV2Pair, to=[Receiver] 0xc9e15f678824caf680d282d762133c72103ace8a, value=26121371288131203193378 )
|
72 |
UniswapV2Pair.Sync( reserve0=1766612790156882022773167, reserve1=1995361739853841893270 )
|
73 |
UniswapV2Pair.Swap( sender=UniswapV2Router02, amount0In=0, amount1In=29160000000000004000, amount0Out=26121371288131203193378, amount1Out=0, to=[Receiver] 0xc9e15f678824caf680d282d762133c72103ace8a )
|
74 |
AlphaToken.Transfer( from=[Receiver] 0xc9e15f678824caf680d282d762133c72103ace8a, to=IbETHRouter, value=26121371288131203193378 )
|
75 |
AlphaToken.Approval( owner=[Receiver] 0xc9e15f678824caf680d282d762133c72103ace8a, spender=IbETHRouter, value=115792089237316195423570985008687907853269984665640563969619259991935159931504 )
|
76 |
AlphaToken.Transfer( from=IbETHRouter, to=UniswapV2Pair, value=26121371288131203193378 )
|
77 |
AlphaToken.Approval( owner=IbETHRouter, spender=UniswapV2Router02, value=115792089237316195423570985008687907853269984665640248594227110874487926866580 )
|
78 |
Bank.Transfer( from=UniswapV2Pair, to=IbETHRouter, value=28177085892464840015 )
|
79 |
UniswapV2Pair.Sync( reserve0=8370261985991092853818, reserve1=7762435686529408544250041 )
|
80 |
UniswapV2Pair.Swap( sender=UniswapV2Router02, amount0In=0, amount1In=26121371288131203193378, amount0Out=28177085892464840015, amount1Out=0, to=IbETHRouter )
|
81 |
Bank.Transfer( from=IbETHRouter, to=0x0000000000000000000000000000000000000000, value=28177085892464840015 )
|
82 |
WETH9.Deposit( dst=[Receiver] 0xc9e15f678824caf680d282d762133c72103ace8a, wad=29226775653085899447 )
|
83 |
SoloMargin.0xab38cdc4a831ebe6542bf277d36b65dbc5c66a4d03ec6cf56ac38de05dc30098( 0xab38cdc4a831ebe6542bf277d36b65dbc5c66a4d03ec6cf56ac38de05dc30098, 0x000000000000000000000000c9e15f678824caf680d282d762133c72103ace8a, 0000000000000000000000000000000000000000000000000000000000000001, 000000000000000000000000c9e15f678824caf680d282d762133c72103ace8a )
|
84 |
WETH9.Transfer( src=[Receiver] 0xc9e15f678824caf680d282d762133c72103ace8a, dst=SoloMargin, wad=29160000000000004002 )
|
85 |
SoloMargin.0x2bad8bc95088af2c247b30fa2b2e6a0886f88625e0945cd3051008e0e270198f( 0x2bad8bc95088af2c247b30fa2b2e6a0886f88625e0945cd3051008e0e270198f, 0x000000000000000000000000c9e15f678824caf680d282d762133c72103ace8a, 0000000000000000000000000000000000000000000000000000000000000001, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000001, 00000000000000000000000000000000000000000000000194ad2180f2640fa2, 0000000000000000000000000000000000000000000000000000000000000001, 0000000000000000000000000000000000000000000000000000000000000000, 000000000000000000000000c9e15f678824caf680d282d762133c72103ace8a )
|
86 |
WETH9.Withdrawal( src=[Receiver] 0xc9e15f678824caf680d282d762133c72103ace8a, wad=66775653085895445 )
|
87 |
ChiToken.Transfer( from=[Sender] 0x30f0d59bf7659cadfa89b6d54e1dbd8acef83aa3, to=0x0000000000000000000000000000000000000000, value=0 )
|
88 |
ChiToken.Approval( owner=[Sender] 0x30f0d59bf7659cadfa89b6d54e1dbd8acef83aa3, spender=[Receiver] 0xc9e15f678824caf680d282d762133c72103ace8a, value=115792089237316195423570985008687907853269984665640564039457584007913129638434 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x1aD91ee0...dA6B45836
Miner
| (Hiveon Pool) | 1,666.827351464648288283 Eth | 1,666.925979117548288283 Eth | 0.0986276529 | |
0x1E0447b1...659614e4e | (dYdX: Solo Margin) | ||||
0x30f0d59B...AceF83AA3 |
0.200365869323083792 Eth
Nonce: 518
|
0.168513869508979237 Eth
Nonce: 519
| 0.031851999814104555 | ||
0x411A9B90...566a42875 | |||||
0x67B66C99...39F0b9c7A | 19,684.047762281917332227 Eth | 19,654.82098662883143278 Eth | 29.226775653085899447 | ||
0xa1faa113...c13B40975 | |||||
0xC02aaA39...83C756Cc2 | 5,898,304.862105749275501433 Eth | 5,898,334.022105749275505435 Eth | 29.160000000000004002 | ||
0xf55C33D9...388b14964 |
Execution Trace
0xc9e15f678824caf680d282d762133c72103ace8a.3d511538( )
-
SoloMargin.STATICCALL( )
-
SoloMargin.getMarketTokenAddress( marketId=0 ) => ( 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 )
-
WETH9.allowance( 0xC9e15F678824caf680D282D762133C72103aCE8A, 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e ) => ( 115792089237316195423570985008687907853269984665640564039457584007913129639935 )
SoloMargin.operate( accounts=, actions= )
OperationImpl.bd76ecfd( )
WethPriceOracle.getPrice( 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ) => ( [{name:value, type:uint256, order:1, indexed:false, value:1818000000000000000000, valueString:1818000000000000000000}] )
-
P1MirrorOracleETHUSD.STATICCALL( )
-
-
DoubleExponentInterestSetter.getInterestRate( 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, borrowWei=2480166587992639622522, supplyWei=116543603032404703047362 ) => ( [{name:value, type:uint256, order:1, indexed:false, value:67481667, valueString:67481667}] )
-
WETH9.transfer( dst=0xC9e15F678824caf680D282D762133C72103aCE8A, wad=29160000000000004000 ) => ( True )
0xc9e15f678824caf680d282d762133c72103ace8a.8b418713( )
-
WETH9.balanceOf( 0xC9e15F678824caf680D282D762133C72103aCE8A ) => ( 29160000000000004000 )
-
WETH9.allowance( 0xC9e15F678824caf680D282D762133C72103aCE8A, 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F ) => ( 115792089237316195423570985008687907853269984665640564039457584007913129639935 )
UniswapV2Router02.swapExactTokensForTokensSupportingFeeOnTransferTokens( amountIn=29160000000000004000, amountOutMin=1, path=[0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 0xa1faa113cbE53436Df28FF0aEe54275c13B40975], to=0xC9e15F678824caf680D282D762133C72103aCE8A, deadline=1613208206 )
-
WETH9.transferFrom( src=0xC9e15F678824caf680D282D762133C72103aCE8A, dst=0xf55C33D94150d93c2cfb833bcCA30bE388b14964, wad=29160000000000004000 ) => ( True )
-
AlphaToken.balanceOf( account=0xC9e15F678824caf680D282D762133C72103aCE8A ) => ( 0 )
-
UniswapV2Pair.STATICCALL( )
-
WETH9.balanceOf( 0xf55C33D94150d93c2cfb833bcCA30bE388b14964 ) => ( 1995361739853841893270 )
UniswapV2Pair.swap( amount0Out=26121371288131203193378, amount1Out=0, to=0xC9e15F678824caf680D282D762133C72103aCE8A, data=0x )
-
AlphaToken.transfer( recipient=0xC9e15F678824caf680D282D762133C72103aCE8A, amount=26121371288131203193378 ) => ( True )
-
AlphaToken.balanceOf( account=0xf55C33D94150d93c2cfb833bcCA30bE388b14964 ) => ( 1766612790156882022773167 )
-
WETH9.balanceOf( 0xf55C33D94150d93c2cfb833bcCA30bE388b14964 ) => ( 1995361739853841893270 )
-
-
AlphaToken.balanceOf( account=0xC9e15F678824caf680D282D762133C72103aCE8A ) => ( 26121371288131203193378 )
-
-
AlphaToken.balanceOf( account=0xC9e15F678824caf680D282D762133C72103aCE8A ) => ( 26121371288131203193378 )
-
AlphaToken.allowance( owner=0xC9e15F678824caf680D282D762133C72103aCE8A, spender=0xbEBBFF645d666445F39900F33201405E1CdAF130 ) => ( 115792089237316195423570985008687907853269984665640563995740631280066363124882 )
IbETHRouter.swapExactAlphaForETH( amountAlphaIn=26121371288131203193378, amountETHOutMin=1, to=0xC9e15F678824caf680D282D762133C72103aCE8A, deadline=1613208206 ) => ( amounts=[26121371288131203193378, 29226775653085899447] )
-
AlphaToken.transferFrom( sender=0xC9e15F678824caf680D282D762133C72103aCE8A, recipient=0xbEBBFF645d666445F39900F33201405E1CdAF130, amount=26121371288131203193378 ) => ( True )
UniswapV2Router02.swapExactTokensForTokens( amountIn=26121371288131203193378, amountOutMin=0, path=[0xa1faa113cbE53436Df28FF0aEe54275c13B40975, 0x67B66C99D3Eb37Fa76Aa3Ed1ff33E8e39F0b9c7A], to=0xbEBBFF645d666445F39900F33201405E1CdAF130, deadline=1613208206 ) => ( amounts=[26121371288131203193378, 28177085892464840015] )
-
UniswapV2Pair.STATICCALL( )
-
AlphaToken.transferFrom( sender=0xbEBBFF645d666445F39900F33201405E1CdAF130, recipient=0x411A9B902F364817a0f9C4261Ce28b5566a42875, amount=26121371288131203193378 ) => ( True )
-
UniswapV2Pair.swap( amount0Out=28177085892464840015, amount1Out=0, to=0xbEBBFF645d666445F39900F33201405E1CdAF130, data=0x )
-
Bank.withdraw( share=28177085892464840015 )
-
ConfigurableInterestBankConfig.getInterestRate( debt=287088063871374426880116, floating=19684047762281917332227 ) => ( 7716254488 )
-
ConfigurableInterestBankConfig.STATICCALL( )
- ETH 29.226775653085899447
IbETHRouter.CALL( )
-
- ETH 29.226775653085899447
0xc9e15f678824caf680d282d762133c72103ace8a.CALL( )
-
- ETH 29.226775653085899447
WETH9.CALL( )
-
-
WETH9.transferFrom( src=0xC9e15F678824caf680D282D762133C72103aCE8A, dst=0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e, wad=29160000000000004002 ) => ( True )
-
WETH9.balanceOf( 0xC9e15F678824caf680D282D762133C72103aCE8A ) => ( 66775653085895445 )
WETH9.withdraw( wad=66775653085895445 )
- ETH 0.066775653085895445
0xc9e15f678824caf680d282d762133c72103ace8a.CALL( )
- ETH 0.066775653085895445
- ETH 0.066775653085895445
0x30f0d59bf7659cadfa89b6d54e1dbd8acef83aa3.CALL( )
-
ChiToken.freeFromUpTo( from=0x30f0d59BF7659cAdfA89B6D54E1DBd8AceF83AA3, value=15 ) => ( 0 )
File 1 of 15: SoloMargin
File 2 of 15: WETH9
File 3 of 15: UniswapV2Pair
File 4 of 15: AlphaToken
File 5 of 15: IbETHRouter
File 6 of 15: UniswapV2Pair
File 7 of 15: Bank
File 8 of 15: ChiToken
File 9 of 15: OperationImpl
File 10 of 15: WethPriceOracle
File 11 of 15: P1MirrorOracleETHUSD
File 12 of 15: DoubleExponentInterestSetter
File 13 of 15: UniswapV2Router02
File 14 of 15: UniswapV2Router02
File 15 of 15: ConfigurableInterestBankConfig
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental ABIEncoderV2; // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/protocol/lib/Require.sol /** * @title Require * @author dYdX * * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require() */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringify( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } // File: contracts/protocol/lib/Math.sol /** * @title Math * @author dYdX * * Library for non-standard Math functions */ library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // File: contracts/protocol/lib/Types.sol /** * @title Types * @author dYdX * * Library for interacting with the basic structs used in Solo */ library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } // File: contracts/protocol/lib/Account.sol /** * @title Account * @author dYdX * * Library of structs and functions that represent an account */ library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } // File: contracts/protocol/lib/Monetary.sol /** * @title Monetary * @author dYdX * * Library for types involving money */ library Monetary { /* * The price of a base-unit of an asset. */ struct Price { uint256 value; } /* * Total value of an some amount of an asset. Equal to (price * amount). */ struct Value { uint256 value; } } // File: contracts/protocol/lib/Cache.sol /** * @title Cache * @author dYdX * * Library for caching information about markets */ library Cache { using Cache for MarketCache; using Storage for Storage.State; // ============ Structs ============ struct MarketInfo { bool isClosing; uint128 borrowPar; Monetary.Price price; } struct MarketCache { MarketInfo[] markets; } // ============ Setter Functions ============ /** * Initialize an empty cache for some given number of total markets. */ function create( uint256 numMarkets ) internal pure returns (MarketCache memory) { return MarketCache({ markets: new MarketInfo[](numMarkets) }); } /** * Add market information (price and total borrowed par if the market is closing) to the cache. * Return true if the market information did not previously exist in the cache. */ function addMarket( MarketCache memory cache, Storage.State storage state, uint256 marketId ) internal view returns (bool) { if (cache.hasMarket(marketId)) { return false; } cache.markets[marketId].price = state.fetchPrice(marketId); if (state.markets[marketId].isClosing) { cache.markets[marketId].isClosing = true; cache.markets[marketId].borrowPar = state.getTotalPar(marketId).borrow; } return true; } // ============ Getter Functions ============ function getNumMarkets( MarketCache memory cache ) internal pure returns (uint256) { return cache.markets.length; } function hasMarket( MarketCache memory cache, uint256 marketId ) internal pure returns (bool) { return cache.markets[marketId].price.value != 0; } function getIsClosing( MarketCache memory cache, uint256 marketId ) internal pure returns (bool) { return cache.markets[marketId].isClosing; } function getPrice( MarketCache memory cache, uint256 marketId ) internal pure returns (Monetary.Price memory) { return cache.markets[marketId].price; } function getBorrowPar( MarketCache memory cache, uint256 marketId ) internal pure returns (uint128) { return cache.markets[marketId].borrowPar; } } // File: contracts/protocol/lib/Decimal.sol /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Functions ============ function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function onePlus( D256 memory d ) internal pure returns (D256 memory) { return D256({ value: d.value.add(BASE) }); } function mul( uint256 target, D256 memory d ) internal pure returns (uint256) { return Math.getPartial(target, d.value, BASE); } function div( uint256 target, D256 memory d ) internal pure returns (uint256) { return Math.getPartial(target, BASE, d.value); } } // File: contracts/protocol/lib/Time.sol /** * @title Time * @author dYdX * * Library for dealing with time, assuming timestamps fit within 32 bits (valid until year 2106) */ library Time { // ============ Library Functions ============ function currentTime() internal view returns (uint32) { return Math.to32(block.timestamp); } } // File: contracts/protocol/lib/Interest.sol /** * @title Interest * @author dYdX * * Library for managing the interest rate and interest indexes of Solo */ library Interest { using Math for uint256; using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Interest"; uint64 constant BASE = 10**18; // ============ Structs ============ struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } // ============ Library Functions ============ /** * Get a new market Index based on the old index and market interest rate. * Calculate interest for borrowers by using the formula rate * time. Approximates * continuously-compounded interest when called frequently, but is much more * gas-efficient to calculate. For suppliers, the interest rate is adjusted by the earningsRate, * then prorated the across all suppliers. * * @param index The old index for a market * @param rate The current interest rate of the market * @param totalPar The total supply and borrow par values of the market * @param earningsRate The portion of the interest that is forwarded to the suppliers * @return The updated index for a market */ function calculateNewIndex( Index memory index, Rate memory rate, Types.TotalPar memory totalPar, Decimal.D256 memory earningsRate ) internal view returns (Index memory) { ( Types.Wei memory supplyWei, Types.Wei memory borrowWei ) = totalParToWei(totalPar, index); // get interest increase for borrowers uint32 currentTime = Time.currentTime(); uint256 borrowInterest = rate.value.mul(uint256(currentTime).sub(index.lastUpdate)); // get interest increase for suppliers uint256 supplyInterest; if (Types.isZero(supplyWei)) { supplyInterest = 0; } else { supplyInterest = Decimal.mul(borrowInterest, earningsRate); if (borrowWei.value < supplyWei.value) { supplyInterest = Math.getPartial(supplyInterest, borrowWei.value, supplyWei.value); } } assert(supplyInterest <= borrowInterest); return Index({ borrow: Math.getPartial(index.borrow, borrowInterest, BASE).add(index.borrow).to96(), supply: Math.getPartial(index.supply, supplyInterest, BASE).add(index.supply).to96(), lastUpdate: currentTime }); } function newIndex() internal view returns (Index memory) { return Index({ borrow: BASE, supply: BASE, lastUpdate: Time.currentTime() }); } /* * Convert a principal amount to a token amount given an index. */ function parToWei( Types.Par memory input, Index memory index ) internal pure returns (Types.Wei memory) { uint256 inputValue = uint256(input.value); if (input.sign) { return Types.Wei({ sign: true, value: inputValue.getPartial(index.supply, BASE) }); } else { return Types.Wei({ sign: false, value: inputValue.getPartialRoundUp(index.borrow, BASE) }); } } /* * Convert a token amount to a principal amount given an index. */ function weiToPar( Types.Wei memory input, Index memory index ) internal pure returns (Types.Par memory) { if (input.sign) { return Types.Par({ sign: true, value: input.value.getPartial(BASE, index.supply).to128() }); } else { return Types.Par({ sign: false, value: input.value.getPartialRoundUp(BASE, index.borrow).to128() }); } } /* * Convert the total supply and borrow principal amounts of a market to total supply and borrow * token amounts. */ function totalParToWei( Types.TotalPar memory totalPar, Index memory index ) internal pure returns (Types.Wei memory, Types.Wei memory) { Types.Par memory supplyPar = Types.Par({ sign: true, value: totalPar.supply }); Types.Par memory borrowPar = Types.Par({ sign: false, value: totalPar.borrow }); Types.Wei memory supplyWei = parToWei(supplyPar, index); Types.Wei memory borrowWei = parToWei(borrowPar, index); return (supplyWei, borrowWei); } } // File: contracts/protocol/interfaces/IErc20.sol /** * @title IErc20 * @author dYdX * * Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so * that we don't automatically revert when calling non-compliant tokens that have no return value for * transfer(), transferFrom(), or approve(). */ interface IErc20 { event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); function totalSupply( ) external view returns (uint256); function balanceOf( address who ) external view returns (uint256); function allowance( address owner, address spender ) external view returns (uint256); function transfer( address to, uint256 value ) external; function transferFrom( address from, address to, uint256 value ) external; function approve( address spender, uint256 value ) external; function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // File: contracts/protocol/lib/Token.sol /** * @title Token * @author dYdX * * This library contains basic functions for interacting with ERC20 tokens. Modified to work with * tokens that don't adhere strictly to the ERC20 standard (for example tokens that don't return a * boolean value on success). */ library Token { // ============ Constants ============ bytes32 constant FILE = "Token"; // ============ Library Functions ============ function balanceOf( address token, address owner ) internal view returns (uint256) { return IErc20(token).balanceOf(owner); } function allowance( address token, address owner, address spender ) internal view returns (uint256) { return IErc20(token).allowance(owner, spender); } function approve( address token, address spender, uint256 amount ) internal { IErc20(token).approve(spender, amount); Require.that( checkSuccess(), FILE, "Approve failed" ); } function approveMax( address token, address spender ) internal { approve( token, spender, uint256(-1) ); } function transfer( address token, address to, uint256 amount ) internal { if (amount == 0 || to == address(this)) { return; } IErc20(token).transfer(to, amount); Require.that( checkSuccess(), FILE, "Transfer failed" ); } function transferFrom( address token, address from, address to, uint256 amount ) internal { if (amount == 0 || to == from) { return; } IErc20(token).transferFrom(from, to, amount); Require.that( checkSuccess(), FILE, "TransferFrom failed" ); } // ============ Private Functions ============ /** * Check the return value of the previous function up to 32 bytes. Return true if the previous * function returned 0 bytes or 32 bytes that are not all-zero. */ function checkSuccess( ) private pure returns (bool) { uint256 returnValue = 0; /* solium-disable-next-line security/no-inline-assembly */ assembly { // check number of bytes returned from last function call switch returndatasize // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned: check if non-zero case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: don't mark as success default { } } return returnValue != 0; } } // File: contracts/protocol/interfaces/IInterestSetter.sol /** * @title IInterestSetter * @author dYdX * * Interface that Interest Setters for Solo must implement in order to report interest rates. */ interface IInterestSetter { // ============ Public Functions ============ /** * Get the interest rate of a token given some borrowed and supplied amounts * * @param token The address of the ERC20 token for the market * @param borrowWei The total borrowed token amount for the market * @param supplyWei The total supplied token amount for the market * @return The interest rate per second */ function getInterestRate( address token, uint256 borrowWei, uint256 supplyWei ) external view returns (Interest.Rate memory); } // File: contracts/protocol/interfaces/IPriceOracle.sol /** * @title IPriceOracle * @author dYdX * * Interface that Price Oracles for Solo must implement in order to report prices. */ contract IPriceOracle { // ============ Constants ============ uint256 public constant ONE_DOLLAR = 10 ** 36; // ============ Public Functions ============ /** * Get the price of a token * * @param token The ERC20 token address of the market * @return The USD price of a base unit of the token, then multiplied by 10^36. * So a USD-stable coin with 18 decimal places would return 10^18. * This is the price of the base unit rather than the price of a "human-readable" * token amount. Every ERC20 may have a different number of decimals. */ function getPrice( address token ) public view returns (Monetary.Price memory); } // File: contracts/protocol/lib/Storage.sol /** * @title Storage * @author dYdX * * Functions for reading, writing, and verifying state in Solo */ library Storage { using Cache for Cache.MarketCache; using Storage for Storage.State; using Math for uint256; using Types for Types.Par; using Types for Types.Wei; using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Storage"; // ============ Structs ============ // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market IPriceOracle priceOracle; // Contract address of the interest setter for this market IInterestSetter interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping (uint256 => Market) markets; // owner => account number => Account mapping (address => mapping (uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping (address => mapping (address => bool)) operators; // Addresses that can control all users accounts mapping (address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } // ============ Functions ============ function getToken( Storage.State storage state, uint256 marketId ) internal view returns (address) { return state.markets[marketId].token; } function getTotalPar( Storage.State storage state, uint256 marketId ) internal view returns (Types.TotalPar memory) { return state.markets[marketId].totalPar; } function getIndex( Storage.State storage state, uint256 marketId ) internal view returns (Interest.Index memory) { return state.markets[marketId].index; } function getNumExcessTokens( Storage.State storage state, uint256 marketId ) internal view returns (Types.Wei memory) { Interest.Index memory index = state.getIndex(marketId); Types.TotalPar memory totalPar = state.getTotalPar(marketId); address token = state.getToken(marketId); Types.Wei memory balanceWei = Types.Wei({ sign: true, value: Token.balanceOf(token, address(this)) }); ( Types.Wei memory supplyWei, Types.Wei memory borrowWei ) = Interest.totalParToWei(totalPar, index); // borrowWei is negative, so subtracting it makes the value more positive return balanceWei.sub(borrowWei).sub(supplyWei); } function getStatus( Storage.State storage state, Account.Info memory account ) internal view returns (Account.Status) { return state.accounts[account.owner][account.number].status; } function getPar( Storage.State storage state, Account.Info memory account, uint256 marketId ) internal view returns (Types.Par memory) { return state.accounts[account.owner][account.number].balances[marketId]; } function getWei( Storage.State storage state, Account.Info memory account, uint256 marketId ) internal view returns (Types.Wei memory) { Types.Par memory par = state.getPar(account, marketId); if (par.isZero()) { return Types.zeroWei(); } Interest.Index memory index = state.getIndex(marketId); return Interest.parToWei(par, index); } function getLiquidationSpreadForPair( Storage.State storage state, uint256 heldMarketId, uint256 owedMarketId ) internal view returns (Decimal.D256 memory) { uint256 result = state.riskParams.liquidationSpread.value; result = Decimal.mul(result, Decimal.onePlus(state.markets[heldMarketId].spreadPremium)); result = Decimal.mul(result, Decimal.onePlus(state.markets[owedMarketId].spreadPremium)); return Decimal.D256({ value: result }); } function fetchNewIndex( Storage.State storage state, uint256 marketId, Interest.Index memory index ) internal view returns (Interest.Index memory) { Interest.Rate memory rate = state.fetchInterestRate(marketId, index); return Interest.calculateNewIndex( index, rate, state.getTotalPar(marketId), state.riskParams.earningsRate ); } function fetchInterestRate( Storage.State storage state, uint256 marketId, Interest.Index memory index ) internal view returns (Interest.Rate memory) { Types.TotalPar memory totalPar = state.getTotalPar(marketId); ( Types.Wei memory supplyWei, Types.Wei memory borrowWei ) = Interest.totalParToWei(totalPar, index); Interest.Rate memory rate = state.markets[marketId].interestSetter.getInterestRate( state.getToken(marketId), borrowWei.value, supplyWei.value ); return rate; } function fetchPrice( Storage.State storage state, uint256 marketId ) internal view returns (Monetary.Price memory) { IPriceOracle oracle = IPriceOracle(state.markets[marketId].priceOracle); Monetary.Price memory price = oracle.getPrice(state.getToken(marketId)); Require.that( price.value != 0, FILE, "Price cannot be zero", marketId ); return price; } function getAccountValues( Storage.State storage state, Account.Info memory account, Cache.MarketCache memory cache, bool adjustForLiquidity ) internal view returns (Monetary.Value memory, Monetary.Value memory) { Monetary.Value memory supplyValue; Monetary.Value memory borrowValue; uint256 numMarkets = cache.getNumMarkets(); for (uint256 m = 0; m < numMarkets; m++) { if (!cache.hasMarket(m)) { continue; } Types.Wei memory userWei = state.getWei(account, m); if (userWei.isZero()) { continue; } uint256 assetValue = userWei.value.mul(cache.getPrice(m).value); Decimal.D256 memory adjust = Decimal.one(); if (adjustForLiquidity) { adjust = Decimal.onePlus(state.markets[m].marginPremium); } if (userWei.sign) { supplyValue.value = supplyValue.value.add(Decimal.div(assetValue, adjust)); } else { borrowValue.value = borrowValue.value.add(Decimal.mul(assetValue, adjust)); } } return (supplyValue, borrowValue); } function isCollateralized( Storage.State storage state, Account.Info memory account, Cache.MarketCache memory cache, bool requireMinBorrow ) internal view returns (bool) { // get account values (adjusted for liquidity) ( Monetary.Value memory supplyValue, Monetary.Value memory borrowValue ) = state.getAccountValues(account, cache, /* adjustForLiquidity = */ true); if (borrowValue.value == 0) { return true; } if (requireMinBorrow) { Require.that( borrowValue.value >= state.riskParams.minBorrowedValue.value, FILE, "Borrow value too low", account.owner, account.number, borrowValue.value ); } uint256 requiredMargin = Decimal.mul(borrowValue.value, state.riskParams.marginRatio); return supplyValue.value >= borrowValue.value.add(requiredMargin); } function isGlobalOperator( Storage.State storage state, address operator ) internal view returns (bool) { return state.globalOperators[operator]; } function isLocalOperator( Storage.State storage state, address owner, address operator ) internal view returns (bool) { return state.operators[owner][operator]; } function requireIsOperator( Storage.State storage state, Account.Info memory account, address operator ) internal view { bool isValidOperator = operator == account.owner || state.isGlobalOperator(operator) || state.isLocalOperator(account.owner, operator); Require.that( isValidOperator, FILE, "Unpermissioned operator", operator ); } /** * Determine and set an account's balance based on the intended balance change. Return the * equivalent amount in wei */ function getNewParAndDeltaWei( Storage.State storage state, Account.Info memory account, uint256 marketId, Types.AssetAmount memory amount ) internal view returns (Types.Par memory, Types.Wei memory) { Types.Par memory oldPar = state.getPar(account, marketId); if (amount.value == 0 && amount.ref == Types.AssetReference.Delta) { return (oldPar, Types.zeroWei()); } Interest.Index memory index = state.getIndex(marketId); Types.Wei memory oldWei = Interest.parToWei(oldPar, index); Types.Par memory newPar; Types.Wei memory deltaWei; if (amount.denomination == Types.AssetDenomination.Wei) { deltaWei = Types.Wei({ sign: amount.sign, value: amount.value }); if (amount.ref == Types.AssetReference.Target) { deltaWei = deltaWei.sub(oldWei); } newPar = Interest.weiToPar(oldWei.add(deltaWei), index); } else { // AssetDenomination.Par newPar = Types.Par({ sign: amount.sign, value: amount.value.to128() }); if (amount.ref == Types.AssetReference.Delta) { newPar = oldPar.add(newPar); } deltaWei = Interest.parToWei(newPar, index).sub(oldWei); } return (newPar, deltaWei); } function getNewParAndDeltaWeiForLiquidation( Storage.State storage state, Account.Info memory account, uint256 marketId, Types.AssetAmount memory amount ) internal view returns (Types.Par memory, Types.Wei memory) { Types.Par memory oldPar = state.getPar(account, marketId); Require.that( !oldPar.isPositive(), FILE, "Owed balance cannot be positive", account.owner, account.number, marketId ); ( Types.Par memory newPar, Types.Wei memory deltaWei ) = state.getNewParAndDeltaWei( account, marketId, amount ); // if attempting to over-repay the owed asset, bound it by the maximum if (newPar.isPositive()) { newPar = Types.zeroPar(); deltaWei = state.getWei(account, marketId).negative(); } Require.that( !deltaWei.isNegative() && oldPar.value >= newPar.value, FILE, "Owed balance cannot increase", account.owner, account.number, marketId ); // if not paying back enough wei to repay any par, then bound wei to zero if (oldPar.equals(newPar)) { deltaWei = Types.zeroWei(); } return (newPar, deltaWei); } function isVaporizable( Storage.State storage state, Account.Info memory account, Cache.MarketCache memory cache ) internal view returns (bool) { bool hasNegative = false; uint256 numMarkets = cache.getNumMarkets(); for (uint256 m = 0; m < numMarkets; m++) { if (!cache.hasMarket(m)) { continue; } Types.Par memory par = state.getPar(account, m); if (par.isZero()) { continue; } else if (par.sign) { return false; } else { hasNegative = true; } } return hasNegative; } // =============== Setter Functions =============== function updateIndex( Storage.State storage state, uint256 marketId ) internal returns (Interest.Index memory) { Interest.Index memory index = state.getIndex(marketId); if (index.lastUpdate == Time.currentTime()) { return index; } return state.markets[marketId].index = state.fetchNewIndex(marketId, index); } function setStatus( Storage.State storage state, Account.Info memory account, Account.Status status ) internal { state.accounts[account.owner][account.number].status = status; } function setPar( Storage.State storage state, Account.Info memory account, uint256 marketId, Types.Par memory newPar ) internal { Types.Par memory oldPar = state.getPar(account, marketId); if (Types.equals(oldPar, newPar)) { return; } // updateTotalPar Types.TotalPar memory totalPar = state.getTotalPar(marketId); // roll-back oldPar if (oldPar.sign) { totalPar.supply = uint256(totalPar.supply).sub(oldPar.value).to128(); } else { totalPar.borrow = uint256(totalPar.borrow).sub(oldPar.value).to128(); } // roll-forward newPar if (newPar.sign) { totalPar.supply = uint256(totalPar.supply).add(newPar.value).to128(); } else { totalPar.borrow = uint256(totalPar.borrow).add(newPar.value).to128(); } state.markets[marketId].totalPar = totalPar; state.accounts[account.owner][account.number].balances[marketId] = newPar; } /** * Determine and set an account's balance based on a change in wei */ function setParFromDeltaWei( Storage.State storage state, Account.Info memory account, uint256 marketId, Types.Wei memory deltaWei ) internal { if (deltaWei.isZero()) { return; } Interest.Index memory index = state.getIndex(marketId); Types.Wei memory oldWei = state.getWei(account, marketId); Types.Wei memory newWei = oldWei.add(deltaWei); Types.Par memory newPar = Interest.weiToPar(newWei, index); state.setPar( account, marketId, newPar ); } } // File: contracts/protocol/State.sol /** * @title State * @author dYdX * * Base-level contract that holds the state of Solo */ contract State { Storage.State g_state; } // File: contracts/protocol/impl/AdminImpl.sol /** * @title AdminImpl * @author dYdX * * Administrative functions to keep the protocol updated */ library AdminImpl { using Storage for Storage.State; using Token for address; using Types for Types.Wei; // ============ Constants ============ bytes32 constant FILE = "AdminImpl"; // ============ Events ============ event LogWithdrawExcessTokens( address token, uint256 amount ); event LogAddMarket( uint256 marketId, address token ); event LogSetIsClosing( uint256 marketId, bool isClosing ); event LogSetPriceOracle( uint256 marketId, address priceOracle ); event LogSetInterestSetter( uint256 marketId, address interestSetter ); event LogSetMarginPremium( uint256 marketId, Decimal.D256 marginPremium ); event LogSetSpreadPremium( uint256 marketId, Decimal.D256 spreadPremium ); event LogSetMarginRatio( Decimal.D256 marginRatio ); event LogSetLiquidationSpread( Decimal.D256 liquidationSpread ); event LogSetEarningsRate( Decimal.D256 earningsRate ); event LogSetMinBorrowedValue( Monetary.Value minBorrowedValue ); event LogSetGlobalOperator( address operator, bool approved ); // ============ Token Functions ============ function ownerWithdrawExcessTokens( Storage.State storage state, uint256 marketId, address recipient ) public returns (uint256) { _validateMarketId(state, marketId); Types.Wei memory excessWei = state.getNumExcessTokens(marketId); Require.that( !excessWei.isNegative(), FILE, "Negative excess" ); address token = state.getToken(marketId); uint256 actualBalance = token.balanceOf(address(this)); if (excessWei.value > actualBalance) { excessWei.value = actualBalance; } token.transfer(recipient, excessWei.value); emit LogWithdrawExcessTokens(token, excessWei.value); return excessWei.value; } function ownerWithdrawUnsupportedTokens( Storage.State storage state, address token, address recipient ) public returns (uint256) { _requireNoMarket(state, token); uint256 balance = token.balanceOf(address(this)); token.transfer(recipient, balance); emit LogWithdrawExcessTokens(token, balance); return balance; } // ============ Market Functions ============ function ownerAddMarket( Storage.State storage state, address token, IPriceOracle priceOracle, IInterestSetter interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) public { _requireNoMarket(state, token); uint256 marketId = state.numMarkets; state.numMarkets++; state.markets[marketId].token = token; state.markets[marketId].index = Interest.newIndex(); emit LogAddMarket(marketId, token); _setPriceOracle(state, marketId, priceOracle); _setInterestSetter(state, marketId, interestSetter); _setMarginPremium(state, marketId, marginPremium); _setSpreadPremium(state, marketId, spreadPremium); } function ownerSetIsClosing( Storage.State storage state, uint256 marketId, bool isClosing ) public { _validateMarketId(state, marketId); state.markets[marketId].isClosing = isClosing; emit LogSetIsClosing(marketId, isClosing); } function ownerSetPriceOracle( Storage.State storage state, uint256 marketId, IPriceOracle priceOracle ) public { _validateMarketId(state, marketId); _setPriceOracle(state, marketId, priceOracle); } function ownerSetInterestSetter( Storage.State storage state, uint256 marketId, IInterestSetter interestSetter ) public { _validateMarketId(state, marketId); _setInterestSetter(state, marketId, interestSetter); } function ownerSetMarginPremium( Storage.State storage state, uint256 marketId, Decimal.D256 memory marginPremium ) public { _validateMarketId(state, marketId); _setMarginPremium(state, marketId, marginPremium); } function ownerSetSpreadPremium( Storage.State storage state, uint256 marketId, Decimal.D256 memory spreadPremium ) public { _validateMarketId(state, marketId); _setSpreadPremium(state, marketId, spreadPremium); } // ============ Risk Functions ============ function ownerSetMarginRatio( Storage.State storage state, Decimal.D256 memory ratio ) public { Require.that( ratio.value <= state.riskLimits.marginRatioMax, FILE, "Ratio too high" ); Require.that( ratio.value > state.riskParams.liquidationSpread.value, FILE, "Ratio cannot be <= spread" ); state.riskParams.marginRatio = ratio; emit LogSetMarginRatio(ratio); } function ownerSetLiquidationSpread( Storage.State storage state, Decimal.D256 memory spread ) public { Require.that( spread.value <= state.riskLimits.liquidationSpreadMax, FILE, "Spread too high" ); Require.that( spread.value < state.riskParams.marginRatio.value, FILE, "Spread cannot be >= ratio" ); state.riskParams.liquidationSpread = spread; emit LogSetLiquidationSpread(spread); } function ownerSetEarningsRate( Storage.State storage state, Decimal.D256 memory earningsRate ) public { Require.that( earningsRate.value <= state.riskLimits.earningsRateMax, FILE, "Rate too high" ); state.riskParams.earningsRate = earningsRate; emit LogSetEarningsRate(earningsRate); } function ownerSetMinBorrowedValue( Storage.State storage state, Monetary.Value memory minBorrowedValue ) public { Require.that( minBorrowedValue.value <= state.riskLimits.minBorrowedValueMax, FILE, "Value too high" ); state.riskParams.minBorrowedValue = minBorrowedValue; emit LogSetMinBorrowedValue(minBorrowedValue); } // ============ Global Operator Functions ============ function ownerSetGlobalOperator( Storage.State storage state, address operator, bool approved ) public { state.globalOperators[operator] = approved; emit LogSetGlobalOperator(operator, approved); } // ============ Private Functions ============ function _setPriceOracle( Storage.State storage state, uint256 marketId, IPriceOracle priceOracle ) private { // require oracle can return non-zero price address token = state.markets[marketId].token; Require.that( priceOracle.getPrice(token).value != 0, FILE, "Invalid oracle price" ); state.markets[marketId].priceOracle = priceOracle; emit LogSetPriceOracle(marketId, address(priceOracle)); } function _setInterestSetter( Storage.State storage state, uint256 marketId, IInterestSetter interestSetter ) private { // ensure interestSetter can return a value without reverting address token = state.markets[marketId].token; interestSetter.getInterestRate(token, 0, 0); state.markets[marketId].interestSetter = interestSetter; emit LogSetInterestSetter(marketId, address(interestSetter)); } function _setMarginPremium( Storage.State storage state, uint256 marketId, Decimal.D256 memory marginPremium ) private { Require.that( marginPremium.value <= state.riskLimits.marginPremiumMax, FILE, "Margin premium too high" ); state.markets[marketId].marginPremium = marginPremium; emit LogSetMarginPremium(marketId, marginPremium); } function _setSpreadPremium( Storage.State storage state, uint256 marketId, Decimal.D256 memory spreadPremium ) private { Require.that( spreadPremium.value <= state.riskLimits.spreadPremiumMax, FILE, "Spread premium too high" ); state.markets[marketId].spreadPremium = spreadPremium; emit LogSetSpreadPremium(marketId, spreadPremium); } function _requireNoMarket( Storage.State storage state, address token ) private view { uint256 numMarkets = state.numMarkets; bool marketExists = false; for (uint256 m = 0; m < numMarkets; m++) { if (state.markets[m].token == token) { marketExists = true; break; } } Require.that( !marketExists, FILE, "Market exists" ); } function _validateMarketId( Storage.State storage state, uint256 marketId ) private view { Require.that( marketId < state.numMarkets, FILE, "Market OOB", marketId ); } } // File: contracts/protocol/Admin.sol /** * @title Admin * @author dYdX * * Public functions that allow the privileged owner address to manage Solo */ contract Admin is State, Ownable, ReentrancyGuard { // ============ Token Functions ============ /** * Withdraw an ERC20 token for which there is an associated market. Only excess tokens can be * withdrawn. The number of excess tokens is calculated by taking the current number of tokens * held in Solo, adding the number of tokens owed to Solo by borrowers, and subtracting the * number of tokens owed to suppliers by Solo. */ function ownerWithdrawExcessTokens( uint256 marketId, address recipient ) public onlyOwner nonReentrant returns (uint256) { return AdminImpl.ownerWithdrawExcessTokens( g_state, marketId, recipient ); } /** * Withdraw an ERC20 token for which there is no associated market. */ function ownerWithdrawUnsupportedTokens( address token, address recipient ) public onlyOwner nonReentrant returns (uint256) { return AdminImpl.ownerWithdrawUnsupportedTokens( g_state, token, recipient ); } // ============ Market Functions ============ /** * Add a new market to Solo. Must be for a previously-unsupported ERC20 token. */ function ownerAddMarket( address token, IPriceOracle priceOracle, IInterestSetter interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) public onlyOwner nonReentrant { AdminImpl.ownerAddMarket( g_state, token, priceOracle, interestSetter, marginPremium, spreadPremium ); } /** * Set (or unset) the status of a market to "closing". The borrowedValue of a market cannot * increase while its status is "closing". */ function ownerSetIsClosing( uint256 marketId, bool isClosing ) public onlyOwner nonReentrant { AdminImpl.ownerSetIsClosing( g_state, marketId, isClosing ); } /** * Set the price oracle for a market. */ function ownerSetPriceOracle( uint256 marketId, IPriceOracle priceOracle ) public onlyOwner nonReentrant { AdminImpl.ownerSetPriceOracle( g_state, marketId, priceOracle ); } /** * Set the interest-setter for a market. */ function ownerSetInterestSetter( uint256 marketId, IInterestSetter interestSetter ) public onlyOwner nonReentrant { AdminImpl.ownerSetInterestSetter( g_state, marketId, interestSetter ); } /** * Set a premium on the minimum margin-ratio for a market. This makes it so that any positions * that include this market require a higher collateralization to avoid being liquidated. */ function ownerSetMarginPremium( uint256 marketId, Decimal.D256 memory marginPremium ) public onlyOwner nonReentrant { AdminImpl.ownerSetMarginPremium( g_state, marketId, marginPremium ); } /** * Set a premium on the liquidation spread for a market. This makes it so that any liquidations * that include this market have a higher spread than the global default. */ function ownerSetSpreadPremium( uint256 marketId, Decimal.D256 memory spreadPremium ) public onlyOwner nonReentrant { AdminImpl.ownerSetSpreadPremium( g_state, marketId, spreadPremium ); } // ============ Risk Functions ============ /** * Set the global minimum margin-ratio that every position must maintain to prevent being * liquidated. */ function ownerSetMarginRatio( Decimal.D256 memory ratio ) public onlyOwner nonReentrant { AdminImpl.ownerSetMarginRatio( g_state, ratio ); } /** * Set the global liquidation spread. This is the spread between oracle prices that incentivizes * the liquidation of risky positions. */ function ownerSetLiquidationSpread( Decimal.D256 memory spread ) public onlyOwner nonReentrant { AdminImpl.ownerSetLiquidationSpread( g_state, spread ); } /** * Set the global earnings-rate variable that determines what percentage of the interest paid * by borrowers gets passed-on to suppliers. */ function ownerSetEarningsRate( Decimal.D256 memory earningsRate ) public onlyOwner nonReentrant { AdminImpl.ownerSetEarningsRate( g_state, earningsRate ); } /** * Set the global minimum-borrow value which is the minimum value of any new borrow on Solo. */ function ownerSetMinBorrowedValue( Monetary.Value memory minBorrowedValue ) public onlyOwner nonReentrant { AdminImpl.ownerSetMinBorrowedValue( g_state, minBorrowedValue ); } // ============ Global Operator Functions ============ /** * Approve (or disapprove) an address that is permissioned to be an operator for all accounts in * Solo. Intended only to approve smart-contracts. */ function ownerSetGlobalOperator( address operator, bool approved ) public onlyOwner nonReentrant { AdminImpl.ownerSetGlobalOperator( g_state, operator, approved ); } } // File: contracts/protocol/Getters.sol /** * @title Getters * @author dYdX * * Public read-only functions that allow transparency into the state of Solo */ contract Getters is State { using Cache for Cache.MarketCache; using Storage for Storage.State; using Types for Types.Par; // ============ Constants ============ bytes32 FILE = "Getters"; // ============ Getters for Risk ============ /** * Get the global minimum margin-ratio that every position must maintain to prevent being * liquidated. * * @return The global margin-ratio */ function getMarginRatio() public view returns (Decimal.D256 memory) { return g_state.riskParams.marginRatio; } /** * Get the global liquidation spread. This is the spread between oracle prices that incentivizes * the liquidation of risky positions. * * @return The global liquidation spread */ function getLiquidationSpread() public view returns (Decimal.D256 memory) { return g_state.riskParams.liquidationSpread; } /** * Get the global earnings-rate variable that determines what percentage of the interest paid * by borrowers gets passed-on to suppliers. * * @return The global earnings rate */ function getEarningsRate() public view returns (Decimal.D256 memory) { return g_state.riskParams.earningsRate; } /** * Get the global minimum-borrow value which is the minimum value of any new borrow on Solo. * * @return The global minimum borrow value */ function getMinBorrowedValue() public view returns (Monetary.Value memory) { return g_state.riskParams.minBorrowedValue; } /** * Get all risk parameters in a single struct. * * @return All global risk parameters */ function getRiskParams() public view returns (Storage.RiskParams memory) { return g_state.riskParams; } /** * Get all risk parameter limits in a single struct. These are the maximum limits at which the * risk parameters can be set by the admin of Solo. * * @return All global risk parameter limnits */ function getRiskLimits() public view returns (Storage.RiskLimits memory) { return g_state.riskLimits; } // ============ Getters for Markets ============ /** * Get the total number of markets. * * @return The number of markets */ function getNumMarkets() public view returns (uint256) { return g_state.numMarkets; } /** * Get the ERC20 token address for a market. * * @param marketId The market to query * @return The token address */ function getMarketTokenAddress( uint256 marketId ) public view returns (address) { _requireValidMarket(marketId); return g_state.getToken(marketId); } /** * Get the total principal amounts (borrowed and supplied) for a market. * * @param marketId The market to query * @return The total principal amounts */ function getMarketTotalPar( uint256 marketId ) public view returns (Types.TotalPar memory) { _requireValidMarket(marketId); return g_state.getTotalPar(marketId); } /** * Get the most recently cached interest index for a market. * * @param marketId The market to query * @return The most recent index */ function getMarketCachedIndex( uint256 marketId ) public view returns (Interest.Index memory) { _requireValidMarket(marketId); return g_state.getIndex(marketId); } /** * Get the interest index for a market if it were to be updated right now. * * @param marketId The market to query * @return The estimated current index */ function getMarketCurrentIndex( uint256 marketId ) public view returns (Interest.Index memory) { _requireValidMarket(marketId); return g_state.fetchNewIndex(marketId, g_state.getIndex(marketId)); } /** * Get the price oracle address for a market. * * @param marketId The market to query * @return The price oracle address */ function getMarketPriceOracle( uint256 marketId ) public view returns (IPriceOracle) { _requireValidMarket(marketId); return g_state.markets[marketId].priceOracle; } /** * Get the interest-setter address for a market. * * @param marketId The market to query * @return The interest-setter address */ function getMarketInterestSetter( uint256 marketId ) public view returns (IInterestSetter) { _requireValidMarket(marketId); return g_state.markets[marketId].interestSetter; } /** * Get the margin premium for a market. A margin premium makes it so that any positions that * include the market require a higher collateralization to avoid being liquidated. * * @param marketId The market to query * @return The market's margin premium */ function getMarketMarginPremium( uint256 marketId ) public view returns (Decimal.D256 memory) { _requireValidMarket(marketId); return g_state.markets[marketId].marginPremium; } /** * Get the spread premium for a market. A spread premium makes it so that any liquidations * that include the market have a higher spread than the global default. * * @param marketId The market to query * @return The market's spread premium */ function getMarketSpreadPremium( uint256 marketId ) public view returns (Decimal.D256 memory) { _requireValidMarket(marketId); return g_state.markets[marketId].spreadPremium; } /** * Return true if a particular market is in closing mode. Additional borrows cannot be taken * from a market that is closing. * * @param marketId The market to query * @return True if the market is closing */ function getMarketIsClosing( uint256 marketId ) public view returns (bool) { _requireValidMarket(marketId); return g_state.markets[marketId].isClosing; } /** * Get the price of the token for a market. * * @param marketId The market to query * @return The price of each atomic unit of the token */ function getMarketPrice( uint256 marketId ) public view returns (Monetary.Price memory) { _requireValidMarket(marketId); return g_state.fetchPrice(marketId); } /** * Get the current borrower interest rate for a market. * * @param marketId The market to query * @return The current interest rate */ function getMarketInterestRate( uint256 marketId ) public view returns (Interest.Rate memory) { _requireValidMarket(marketId); return g_state.fetchInterestRate( marketId, g_state.getIndex(marketId) ); } /** * Get the adjusted liquidation spread for some market pair. This is equal to the global * liquidation spread multiplied by (1 + spreadPremium) for each of the two markets. * * @param heldMarketId The market for which the account has collateral * @param owedMarketId The market for which the account has borrowed tokens * @return The adjusted liquidation spread */ function getLiquidationSpreadForPair( uint256 heldMarketId, uint256 owedMarketId ) public view returns (Decimal.D256 memory) { _requireValidMarket(heldMarketId); _requireValidMarket(owedMarketId); return g_state.getLiquidationSpreadForPair(heldMarketId, owedMarketId); } /** * Get basic information about a particular market. * * @param marketId The market to query * @return A Storage.Market struct with the current state of the market */ function getMarket( uint256 marketId ) public view returns (Storage.Market memory) { _requireValidMarket(marketId); return g_state.markets[marketId]; } /** * Get comprehensive information about a particular market. * * @param marketId The market to query * @return A tuple containing the values: * - A Storage.Market struct with the current state of the market * - The current estimated interest index * - The current token price * - The current market interest rate */ function getMarketWithInfo( uint256 marketId ) public view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ) { _requireValidMarket(marketId); return ( getMarket(marketId), getMarketCurrentIndex(marketId), getMarketPrice(marketId), getMarketInterestRate(marketId) ); } /** * Get the number of excess tokens for a market. The number of excess tokens is calculated * by taking the current number of tokens held in Solo, adding the number of tokens owed to Solo * by borrowers, and subtracting the number of tokens owed to suppliers by Solo. * * @param marketId The market to query * @return The number of excess tokens */ function getNumExcessTokens( uint256 marketId ) public view returns (Types.Wei memory) { _requireValidMarket(marketId); return g_state.getNumExcessTokens(marketId); } // ============ Getters for Accounts ============ /** * Get the principal value for a particular account and market. * * @param account The account to query * @param marketId The market to query * @return The principal value */ function getAccountPar( Account.Info memory account, uint256 marketId ) public view returns (Types.Par memory) { _requireValidMarket(marketId); return g_state.getPar(account, marketId); } /** * Get the token balance for a particular account and market. * * @param account The account to query * @param marketId The market to query * @return The token amount */ function getAccountWei( Account.Info memory account, uint256 marketId ) public view returns (Types.Wei memory) { _requireValidMarket(marketId); return Interest.parToWei( g_state.getPar(account, marketId), g_state.fetchNewIndex(marketId, g_state.getIndex(marketId)) ); } /** * Get the status of an account (Normal, Liquidating, or Vaporizing). * * @param account The account to query * @return The account's status */ function getAccountStatus( Account.Info memory account ) public view returns (Account.Status) { return g_state.getStatus(account); } /** * Get the total supplied and total borrowed value of an account. * * @param account The account to query * @return The following values: * - The supplied value of the account * - The borrowed value of the account */ function getAccountValues( Account.Info memory account ) public view returns (Monetary.Value memory, Monetary.Value memory) { return getAccountValuesInternal(account, /* adjustForLiquidity = */ false); } /** * Get the total supplied and total borrowed values of an account adjusted by the marginPremium * of each market. Supplied values are divided by (1 + marginPremium) for each market and * borrowed values are multiplied by (1 + marginPremium) for each market. Comparing these * adjusted values gives the margin-ratio of the account which will be compared to the global * margin-ratio when determining if the account can be liquidated. * * @param account The account to query * @return The following values: * - The supplied value of the account (adjusted for marginPremium) * - The borrowed value of the account (adjusted for marginPremium) */ function getAdjustedAccountValues( Account.Info memory account ) public view returns (Monetary.Value memory, Monetary.Value memory) { return getAccountValuesInternal(account, /* adjustForLiquidity = */ true); } /** * Get an account's summary for each market. * * @param account The account to query * @return The following values: * - The ERC20 token address for each market * - The account's principal value for each market * - The account's (supplied or borrowed) number of tokens for each market */ function getAccountBalances( Account.Info memory account ) public view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ) { uint256 numMarkets = g_state.numMarkets; address[] memory tokens = new address[](numMarkets); Types.Par[] memory pars = new Types.Par[](numMarkets); Types.Wei[] memory weis = new Types.Wei[](numMarkets); for (uint256 m = 0; m < numMarkets; m++) { tokens[m] = getMarketTokenAddress(m); pars[m] = getAccountPar(account, m); weis[m] = getAccountWei(account, m); } return ( tokens, pars, weis ); } // ============ Getters for Permissions ============ /** * Return true if a particular address is approved as an operator for an owner's accounts. * Approved operators can act on the accounts of the owner as if it were the operator's own. * * @param owner The owner of the accounts * @param operator The possible operator * @return True if operator is approved for owner's accounts */ function getIsLocalOperator( address owner, address operator ) public view returns (bool) { return g_state.isLocalOperator(owner, operator); } /** * Return true if a particular address is approved as a global operator. Such an address can * act on any account as if it were the operator's own. * * @param operator The address to query * @return True if operator is a global operator */ function getIsGlobalOperator( address operator ) public view returns (bool) { return g_state.isGlobalOperator(operator); } // ============ Private Helper Functions ============ /** * Revert if marketId is invalid. */ function _requireValidMarket( uint256 marketId ) private view { Require.that( marketId < g_state.numMarkets, FILE, "Market OOB" ); } /** * Private helper for getting the monetary values of an account. */ function getAccountValuesInternal( Account.Info memory account, bool adjustForLiquidity ) private view returns (Monetary.Value memory, Monetary.Value memory) { uint256 numMarkets = g_state.numMarkets; // populate cache Cache.MarketCache memory cache = Cache.create(numMarkets); for (uint256 m = 0; m < numMarkets; m++) { if (!g_state.getPar(account, m).isZero()) { cache.addMarket(g_state, m); } } return g_state.getAccountValues(account, cache, adjustForLiquidity); } } // File: contracts/protocol/interfaces/IAutoTrader.sol /** * @title IAutoTrader * @author dYdX * * Interface that Auto-Traders for Solo must implement in order to approve trades. */ contract IAutoTrader { // ============ Public Functions ============ /** * Allows traders to make trades approved by this smart contract. The active trader's account is * the takerAccount and the passive account (for which this contract approves trades * on-behalf-of) is the makerAccount. * * @param inputMarketId The market for which the trader specified the original amount * @param outputMarketId The market for which the trader wants the resulting amount specified * @param makerAccount The account for which this contract is making trades * @param takerAccount The account requesting the trade * @param oldInputPar The old principal amount for the makerAccount for the inputMarketId * @param newInputPar The new principal amount for the makerAccount for the inputMarketId * @param inputWei The change in token amount for the makerAccount for the inputMarketId * @param data Arbitrary data passed in by the trader * @return The AssetAmount for the makerAccount for the outputMarketId */ function getTradeCost( uint256 inputMarketId, uint256 outputMarketId, Account.Info memory makerAccount, Account.Info memory takerAccount, Types.Par memory oldInputPar, Types.Par memory newInputPar, Types.Wei memory inputWei, bytes memory data ) public returns (Types.AssetAmount memory); } // File: contracts/protocol/interfaces/ICallee.sol /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ contract ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) public; } // File: contracts/protocol/lib/Actions.sol /** * @title Actions * @author dYdX * * Library that defines and parses valid Actions */ library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } // File: contracts/protocol/lib/Events.sol /** * @title Events * @author dYdX * * Library to parse and emit logs from which the state of all accounts and indexes can be followed */ library Events { using Types for Types.Wei; using Storage for Storage.State; // ============ Events ============ event LogIndexUpdate( uint256 indexed market, Interest.Index index ); event LogOperation( address sender ); event LogDeposit( address indexed accountOwner, uint256 accountNumber, uint256 market, BalanceUpdate update, address from ); event LogWithdraw( address indexed accountOwner, uint256 accountNumber, uint256 market, BalanceUpdate update, address to ); event LogTransfer( address indexed accountOneOwner, uint256 accountOneNumber, address indexed accountTwoOwner, uint256 accountTwoNumber, uint256 market, BalanceUpdate updateOne, BalanceUpdate updateTwo ); event LogBuy( address indexed accountOwner, uint256 accountNumber, uint256 takerMarket, uint256 makerMarket, BalanceUpdate takerUpdate, BalanceUpdate makerUpdate, address exchangeWrapper ); event LogSell( address indexed accountOwner, uint256 accountNumber, uint256 takerMarket, uint256 makerMarket, BalanceUpdate takerUpdate, BalanceUpdate makerUpdate, address exchangeWrapper ); event LogTrade( address indexed takerAccountOwner, uint256 takerAccountNumber, address indexed makerAccountOwner, uint256 makerAccountNumber, uint256 inputMarket, uint256 outputMarket, BalanceUpdate takerInputUpdate, BalanceUpdate takerOutputUpdate, BalanceUpdate makerInputUpdate, BalanceUpdate makerOutputUpdate, address autoTrader ); event LogCall( address indexed accountOwner, uint256 accountNumber, address callee ); event LogLiquidate( address indexed solidAccountOwner, uint256 solidAccountNumber, address indexed liquidAccountOwner, uint256 liquidAccountNumber, uint256 heldMarket, uint256 owedMarket, BalanceUpdate solidHeldUpdate, BalanceUpdate solidOwedUpdate, BalanceUpdate liquidHeldUpdate, BalanceUpdate liquidOwedUpdate ); event LogVaporize( address indexed solidAccountOwner, uint256 solidAccountNumber, address indexed vaporAccountOwner, uint256 vaporAccountNumber, uint256 heldMarket, uint256 owedMarket, BalanceUpdate solidHeldUpdate, BalanceUpdate solidOwedUpdate, BalanceUpdate vaporOwedUpdate ); // ============ Structs ============ struct BalanceUpdate { Types.Wei deltaWei; Types.Par newPar; } // ============ Internal Functions ============ function logIndexUpdate( uint256 marketId, Interest.Index memory index ) internal { emit LogIndexUpdate( marketId, index ); } function logOperation() internal { emit LogOperation(msg.sender); } function logDeposit( Storage.State storage state, Actions.DepositArgs memory args, Types.Wei memory deltaWei ) internal { emit LogDeposit( args.account.owner, args.account.number, args.market, getBalanceUpdate( state, args.account, args.market, deltaWei ), args.from ); } function logWithdraw( Storage.State storage state, Actions.WithdrawArgs memory args, Types.Wei memory deltaWei ) internal { emit LogWithdraw( args.account.owner, args.account.number, args.market, getBalanceUpdate( state, args.account, args.market, deltaWei ), args.to ); } function logTransfer( Storage.State storage state, Actions.TransferArgs memory args, Types.Wei memory deltaWei ) internal { emit LogTransfer( args.accountOne.owner, args.accountOne.number, args.accountTwo.owner, args.accountTwo.number, args.market, getBalanceUpdate( state, args.accountOne, args.market, deltaWei ), getBalanceUpdate( state, args.accountTwo, args.market, deltaWei.negative() ) ); } function logBuy( Storage.State storage state, Actions.BuyArgs memory args, Types.Wei memory takerWei, Types.Wei memory makerWei ) internal { emit LogBuy( args.account.owner, args.account.number, args.takerMarket, args.makerMarket, getBalanceUpdate( state, args.account, args.takerMarket, takerWei ), getBalanceUpdate( state, args.account, args.makerMarket, makerWei ), args.exchangeWrapper ); } function logSell( Storage.State storage state, Actions.SellArgs memory args, Types.Wei memory takerWei, Types.Wei memory makerWei ) internal { emit LogSell( args.account.owner, args.account.number, args.takerMarket, args.makerMarket, getBalanceUpdate( state, args.account, args.takerMarket, takerWei ), getBalanceUpdate( state, args.account, args.makerMarket, makerWei ), args.exchangeWrapper ); } function logTrade( Storage.State storage state, Actions.TradeArgs memory args, Types.Wei memory inputWei, Types.Wei memory outputWei ) internal { BalanceUpdate[4] memory updates = [ getBalanceUpdate( state, args.takerAccount, args.inputMarket, inputWei.negative() ), getBalanceUpdate( state, args.takerAccount, args.outputMarket, outputWei.negative() ), getBalanceUpdate( state, args.makerAccount, args.inputMarket, inputWei ), getBalanceUpdate( state, args.makerAccount, args.outputMarket, outputWei ) ]; emit LogTrade( args.takerAccount.owner, args.takerAccount.number, args.makerAccount.owner, args.makerAccount.number, args.inputMarket, args.outputMarket, updates[0], updates[1], updates[2], updates[3], args.autoTrader ); } function logCall( Actions.CallArgs memory args ) internal { emit LogCall( args.account.owner, args.account.number, args.callee ); } function logLiquidate( Storage.State storage state, Actions.LiquidateArgs memory args, Types.Wei memory heldWei, Types.Wei memory owedWei ) internal { BalanceUpdate memory solidHeldUpdate = getBalanceUpdate( state, args.solidAccount, args.heldMarket, heldWei.negative() ); BalanceUpdate memory solidOwedUpdate = getBalanceUpdate( state, args.solidAccount, args.owedMarket, owedWei.negative() ); BalanceUpdate memory liquidHeldUpdate = getBalanceUpdate( state, args.liquidAccount, args.heldMarket, heldWei ); BalanceUpdate memory liquidOwedUpdate = getBalanceUpdate( state, args.liquidAccount, args.owedMarket, owedWei ); emit LogLiquidate( args.solidAccount.owner, args.solidAccount.number, args.liquidAccount.owner, args.liquidAccount.number, args.heldMarket, args.owedMarket, solidHeldUpdate, solidOwedUpdate, liquidHeldUpdate, liquidOwedUpdate ); } function logVaporize( Storage.State storage state, Actions.VaporizeArgs memory args, Types.Wei memory heldWei, Types.Wei memory owedWei, Types.Wei memory excessWei ) internal { BalanceUpdate memory solidHeldUpdate = getBalanceUpdate( state, args.solidAccount, args.heldMarket, heldWei.negative() ); BalanceUpdate memory solidOwedUpdate = getBalanceUpdate( state, args.solidAccount, args.owedMarket, owedWei.negative() ); BalanceUpdate memory vaporOwedUpdate = getBalanceUpdate( state, args.vaporAccount, args.owedMarket, owedWei.add(excessWei) ); emit LogVaporize( args.solidAccount.owner, args.solidAccount.number, args.vaporAccount.owner, args.vaporAccount.number, args.heldMarket, args.owedMarket, solidHeldUpdate, solidOwedUpdate, vaporOwedUpdate ); } // ============ Private Functions ============ function getBalanceUpdate( Storage.State storage state, Account.Info memory account, uint256 market, Types.Wei memory deltaWei ) private view returns (BalanceUpdate memory) { return BalanceUpdate({ deltaWei: deltaWei, newPar: state.getPar(account, market) }); } } // File: contracts/protocol/interfaces/IExchangeWrapper.sol /** * @title IExchangeWrapper * @author dYdX * * Interface that Exchange Wrappers for Solo must implement in order to trade ERC20 tokens. */ interface IExchangeWrapper { // ============ Public Functions ============ /** * Exchange some amount of takerToken for makerToken. * * @param tradeOriginator Address of the initiator of the trade (however, this value * cannot always be trusted as it is set at the discretion of the * msg.sender) * @param receiver Address to set allowance on once the trade has completed * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param requestedFillAmount Amount of takerToken being paid * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return The amount of makerToken received */ function exchange( address tradeOriginator, address receiver, address makerToken, address takerToken, uint256 requestedFillAmount, bytes calldata orderData ) external returns (uint256); /** * Get amount of takerToken required to buy a certain amount of makerToken for a given trade. * Should match the takerToken amount used in exchangeForAmount. If the order cannot provide * exactly desiredMakerToken, then it must return the price to buy the minimum amount greater * than desiredMakerToken * * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param desiredMakerToken Amount of makerToken requested * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return Amount of takerToken the needed to complete the exchange */ function getExchangeCost( address makerToken, address takerToken, uint256 desiredMakerToken, bytes calldata orderData ) external view returns (uint256); } // File: contracts/protocol/lib/Exchange.sol /** * @title Exchange * @author dYdX * * Library for transferring tokens and interacting with ExchangeWrappers by using the Wei struct */ library Exchange { using Types for Types.Wei; // ============ Constants ============ bytes32 constant FILE = "Exchange"; // ============ Library Functions ============ function transferOut( address token, address to, Types.Wei memory deltaWei ) internal { Require.that( !deltaWei.isPositive(), FILE, "Cannot transferOut positive", deltaWei.value ); Token.transfer( token, to, deltaWei.value ); } function transferIn( address token, address from, Types.Wei memory deltaWei ) internal { Require.that( !deltaWei.isNegative(), FILE, "Cannot transferIn negative", deltaWei.value ); Token.transferFrom( token, from, address(this), deltaWei.value ); } function getCost( address exchangeWrapper, address supplyToken, address borrowToken, Types.Wei memory desiredAmount, bytes memory orderData ) internal view returns (Types.Wei memory) { Require.that( !desiredAmount.isNegative(), FILE, "Cannot getCost negative", desiredAmount.value ); Types.Wei memory result; result.sign = false; result.value = IExchangeWrapper(exchangeWrapper).getExchangeCost( supplyToken, borrowToken, desiredAmount.value, orderData ); return result; } function exchange( address exchangeWrapper, address accountOwner, address supplyToken, address borrowToken, Types.Wei memory requestedFillAmount, bytes memory orderData ) internal returns (Types.Wei memory) { Require.that( !requestedFillAmount.isPositive(), FILE, "Cannot exchange positive", requestedFillAmount.value ); transferOut(borrowToken, exchangeWrapper, requestedFillAmount); Types.Wei memory result; result.sign = true; result.value = IExchangeWrapper(exchangeWrapper).exchange( accountOwner, address(this), supplyToken, borrowToken, requestedFillAmount.value, orderData ); transferIn(supplyToken, exchangeWrapper, result); return result; } } // File: contracts/protocol/impl/OperationImpl.sol /** * @title OperationImpl * @author dYdX * * Logic for processing actions */ library OperationImpl { using Cache for Cache.MarketCache; using SafeMath for uint256; using Storage for Storage.State; using Types for Types.Par; using Types for Types.Wei; // ============ Constants ============ bytes32 constant FILE = "OperationImpl"; // ============ Public Functions ============ function operate( Storage.State storage state, Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public { Events.logOperation(); _verifyInputs(accounts, actions); ( bool[] memory primaryAccounts, Cache.MarketCache memory cache ) = _runPreprocessing( state, accounts, actions ); _runActions( state, accounts, actions, cache ); _verifyFinalState( state, accounts, primaryAccounts, cache ); } // ============ Helper Functions ============ function _verifyInputs( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) private pure { Require.that( actions.length != 0, FILE, "Cannot have zero actions" ); Require.that( accounts.length != 0, FILE, "Cannot have zero accounts" ); for (uint256 a = 0; a < accounts.length; a++) { for (uint256 b = a + 1; b < accounts.length; b++) { Require.that( !Account.equals(accounts[a], accounts[b]), FILE, "Cannot duplicate accounts", a, b ); } } } function _runPreprocessing( Storage.State storage state, Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) private returns ( bool[] memory, Cache.MarketCache memory ) { uint256 numMarkets = state.numMarkets; bool[] memory primaryAccounts = new bool[](accounts.length); Cache.MarketCache memory cache = Cache.create(numMarkets); // keep track of primary accounts and indexes that need updating for (uint256 i = 0; i < actions.length; i++) { Actions.ActionArgs memory arg = actions[i]; Actions.ActionType actionType = arg.actionType; Actions.MarketLayout marketLayout = Actions.getMarketLayout(actionType); Actions.AccountLayout accountLayout = Actions.getAccountLayout(actionType); // parse out primary accounts if (accountLayout != Actions.AccountLayout.OnePrimary) { Require.that( arg.accountId != arg.otherAccountId, FILE, "Duplicate accounts in action", i ); if (accountLayout == Actions.AccountLayout.TwoPrimary) { primaryAccounts[arg.otherAccountId] = true; } else { assert(accountLayout == Actions.AccountLayout.PrimaryAndSecondary); Require.that( !primaryAccounts[arg.otherAccountId], FILE, "Requires non-primary account", arg.otherAccountId ); } } primaryAccounts[arg.accountId] = true; // keep track of indexes to update if (marketLayout == Actions.MarketLayout.OneMarket) { _updateMarket(state, cache, arg.primaryMarketId); } else if (marketLayout == Actions.MarketLayout.TwoMarkets) { Require.that( arg.primaryMarketId != arg.secondaryMarketId, FILE, "Duplicate markets in action", i ); _updateMarket(state, cache, arg.primaryMarketId); _updateMarket(state, cache, arg.secondaryMarketId); } else { assert(marketLayout == Actions.MarketLayout.ZeroMarkets); } } // get any other markets for which an account has a balance for (uint256 m = 0; m < numMarkets; m++) { if (cache.hasMarket(m)) { continue; } for (uint256 a = 0; a < accounts.length; a++) { if (!state.getPar(accounts[a], m).isZero()) { _updateMarket(state, cache, m); break; } } } return (primaryAccounts, cache); } function _updateMarket( Storage.State storage state, Cache.MarketCache memory cache, uint256 marketId ) private { bool updated = cache.addMarket(state, marketId); if (updated) { Events.logIndexUpdate(marketId, state.updateIndex(marketId)); } } function _runActions( Storage.State storage state, Account.Info[] memory accounts, Actions.ActionArgs[] memory actions, Cache.MarketCache memory cache ) private { for (uint256 i = 0; i < actions.length; i++) { Actions.ActionArgs memory action = actions[i]; Actions.ActionType actionType = action.actionType; if (actionType == Actions.ActionType.Deposit) { _deposit(state, Actions.parseDepositArgs(accounts, action)); } else if (actionType == Actions.ActionType.Withdraw) { _withdraw(state, Actions.parseWithdrawArgs(accounts, action)); } else if (actionType == Actions.ActionType.Transfer) { _transfer(state, Actions.parseTransferArgs(accounts, action)); } else if (actionType == Actions.ActionType.Buy) { _buy(state, Actions.parseBuyArgs(accounts, action)); } else if (actionType == Actions.ActionType.Sell) { _sell(state, Actions.parseSellArgs(accounts, action)); } else if (actionType == Actions.ActionType.Trade) { _trade(state, Actions.parseTradeArgs(accounts, action)); } else if (actionType == Actions.ActionType.Liquidate) { _liquidate(state, Actions.parseLiquidateArgs(accounts, action), cache); } else if (actionType == Actions.ActionType.Vaporize) { _vaporize(state, Actions.parseVaporizeArgs(accounts, action), cache); } else { assert(actionType == Actions.ActionType.Call); _call(state, Actions.parseCallArgs(accounts, action)); } } } function _verifyFinalState( Storage.State storage state, Account.Info[] memory accounts, bool[] memory primaryAccounts, Cache.MarketCache memory cache ) private { // verify no increase in borrowPar for closing markets uint256 numMarkets = cache.getNumMarkets(); for (uint256 m = 0; m < numMarkets; m++) { if (cache.getIsClosing(m)) { Require.that( state.getTotalPar(m).borrow <= cache.getBorrowPar(m), FILE, "Market is closing", m ); } } // verify account collateralization for (uint256 a = 0; a < accounts.length; a++) { Account.Info memory account = accounts[a]; // validate minBorrowedValue bool collateralized = state.isCollateralized(account, cache, true); // don't check collateralization for non-primary accounts if (!primaryAccounts[a]) { continue; } // check collateralization for primary accounts Require.that( collateralized, FILE, "Undercollateralized account", account.owner, account.number ); // ensure status is normal for primary accounts if (state.getStatus(account) != Account.Status.Normal) { state.setStatus(account, Account.Status.Normal); } } } // ============ Action Functions ============ function _deposit( Storage.State storage state, Actions.DepositArgs memory args ) private { state.requireIsOperator(args.account, msg.sender); Require.that( args.from == msg.sender || args.from == args.account.owner, FILE, "Invalid deposit source", args.from ); ( Types.Par memory newPar, Types.Wei memory deltaWei ) = state.getNewParAndDeltaWei( args.account, args.market, args.amount ); state.setPar( args.account, args.market, newPar ); // requires a positive deltaWei Exchange.transferIn( state.getToken(args.market), args.from, deltaWei ); Events.logDeposit( state, args, deltaWei ); } function _withdraw( Storage.State storage state, Actions.WithdrawArgs memory args ) private { state.requireIsOperator(args.account, msg.sender); ( Types.Par memory newPar, Types.Wei memory deltaWei ) = state.getNewParAndDeltaWei( args.account, args.market, args.amount ); state.setPar( args.account, args.market, newPar ); // requires a negative deltaWei Exchange.transferOut( state.getToken(args.market), args.to, deltaWei ); Events.logWithdraw( state, args, deltaWei ); } function _transfer( Storage.State storage state, Actions.TransferArgs memory args ) private { state.requireIsOperator(args.accountOne, msg.sender); state.requireIsOperator(args.accountTwo, msg.sender); ( Types.Par memory newPar, Types.Wei memory deltaWei ) = state.getNewParAndDeltaWei( args.accountOne, args.market, args.amount ); state.setPar( args.accountOne, args.market, newPar ); state.setParFromDeltaWei( args.accountTwo, args.market, deltaWei.negative() ); Events.logTransfer( state, args, deltaWei ); } function _buy( Storage.State storage state, Actions.BuyArgs memory args ) private { state.requireIsOperator(args.account, msg.sender); address takerToken = state.getToken(args.takerMarket); address makerToken = state.getToken(args.makerMarket); ( Types.Par memory makerPar, Types.Wei memory makerWei ) = state.getNewParAndDeltaWei( args.account, args.makerMarket, args.amount ); Types.Wei memory takerWei = Exchange.getCost( args.exchangeWrapper, makerToken, takerToken, makerWei, args.orderData ); Types.Wei memory tokensReceived = Exchange.exchange( args.exchangeWrapper, args.account.owner, makerToken, takerToken, takerWei, args.orderData ); Require.that( tokensReceived.value >= makerWei.value, FILE, "Buy amount less than promised", tokensReceived.value, makerWei.value ); state.setPar( args.account, args.makerMarket, makerPar ); state.setParFromDeltaWei( args.account, args.takerMarket, takerWei ); Events.logBuy( state, args, takerWei, makerWei ); } function _sell( Storage.State storage state, Actions.SellArgs memory args ) private { state.requireIsOperator(args.account, msg.sender); address takerToken = state.getToken(args.takerMarket); address makerToken = state.getToken(args.makerMarket); ( Types.Par memory takerPar, Types.Wei memory takerWei ) = state.getNewParAndDeltaWei( args.account, args.takerMarket, args.amount ); Types.Wei memory makerWei = Exchange.exchange( args.exchangeWrapper, args.account.owner, makerToken, takerToken, takerWei, args.orderData ); state.setPar( args.account, args.takerMarket, takerPar ); state.setParFromDeltaWei( args.account, args.makerMarket, makerWei ); Events.logSell( state, args, takerWei, makerWei ); } function _trade( Storage.State storage state, Actions.TradeArgs memory args ) private { state.requireIsOperator(args.takerAccount, msg.sender); state.requireIsOperator(args.makerAccount, args.autoTrader); Types.Par memory oldInputPar = state.getPar( args.makerAccount, args.inputMarket ); ( Types.Par memory newInputPar, Types.Wei memory inputWei ) = state.getNewParAndDeltaWei( args.makerAccount, args.inputMarket, args.amount ); Types.AssetAmount memory outputAmount = IAutoTrader(args.autoTrader).getTradeCost( args.inputMarket, args.outputMarket, args.makerAccount, args.takerAccount, oldInputPar, newInputPar, inputWei, args.tradeData ); ( Types.Par memory newOutputPar, Types.Wei memory outputWei ) = state.getNewParAndDeltaWei( args.makerAccount, args.outputMarket, outputAmount ); Require.that( outputWei.isZero() || inputWei.isZero() || outputWei.sign != inputWei.sign, FILE, "Trades cannot be one-sided" ); // set the balance for the maker state.setPar( args.makerAccount, args.inputMarket, newInputPar ); state.setPar( args.makerAccount, args.outputMarket, newOutputPar ); // set the balance for the taker state.setParFromDeltaWei( args.takerAccount, args.inputMarket, inputWei.negative() ); state.setParFromDeltaWei( args.takerAccount, args.outputMarket, outputWei.negative() ); Events.logTrade( state, args, inputWei, outputWei ); } function _liquidate( Storage.State storage state, Actions.LiquidateArgs memory args, Cache.MarketCache memory cache ) private { state.requireIsOperator(args.solidAccount, msg.sender); // verify liquidatable if (Account.Status.Liquid != state.getStatus(args.liquidAccount)) { Require.that( !state.isCollateralized(args.liquidAccount, cache, /* requireMinBorrow = */ false), FILE, "Unliquidatable account", args.liquidAccount.owner, args.liquidAccount.number ); state.setStatus(args.liquidAccount, Account.Status.Liquid); } Types.Wei memory maxHeldWei = state.getWei( args.liquidAccount, args.heldMarket ); Require.that( !maxHeldWei.isNegative(), FILE, "Collateral cannot be negative", args.liquidAccount.owner, args.liquidAccount.number, args.heldMarket ); ( Types.Par memory owedPar, Types.Wei memory owedWei ) = state.getNewParAndDeltaWeiForLiquidation( args.liquidAccount, args.owedMarket, args.amount ); ( Monetary.Price memory heldPrice, Monetary.Price memory owedPrice ) = _getLiquidationPrices( state, cache, args.heldMarket, args.owedMarket ); Types.Wei memory heldWei = _owedWeiToHeldWei(owedWei, heldPrice, owedPrice); // if attempting to over-borrow the held asset, bound it by the maximum if (heldWei.value > maxHeldWei.value) { heldWei = maxHeldWei.negative(); owedWei = _heldWeiToOwedWei(heldWei, heldPrice, owedPrice); state.setPar( args.liquidAccount, args.heldMarket, Types.zeroPar() ); state.setParFromDeltaWei( args.liquidAccount, args.owedMarket, owedWei ); } else { state.setPar( args.liquidAccount, args.owedMarket, owedPar ); state.setParFromDeltaWei( args.liquidAccount, args.heldMarket, heldWei ); } // set the balances for the solid account state.setParFromDeltaWei( args.solidAccount, args.owedMarket, owedWei.negative() ); state.setParFromDeltaWei( args.solidAccount, args.heldMarket, heldWei.negative() ); Events.logLiquidate( state, args, heldWei, owedWei ); } function _vaporize( Storage.State storage state, Actions.VaporizeArgs memory args, Cache.MarketCache memory cache ) private { state.requireIsOperator(args.solidAccount, msg.sender); // verify vaporizable if (Account.Status.Vapor != state.getStatus(args.vaporAccount)) { Require.that( state.isVaporizable(args.vaporAccount, cache), FILE, "Unvaporizable account", args.vaporAccount.owner, args.vaporAccount.number ); state.setStatus(args.vaporAccount, Account.Status.Vapor); } // First, attempt to refund using the same token ( bool fullyRepaid, Types.Wei memory excessWei ) = _vaporizeUsingExcess(state, args); if (fullyRepaid) { Events.logVaporize( state, args, Types.zeroWei(), Types.zeroWei(), excessWei ); return; } Types.Wei memory maxHeldWei = state.getNumExcessTokens(args.heldMarket); Require.that( !maxHeldWei.isNegative(), FILE, "Excess cannot be negative", args.heldMarket ); ( Types.Par memory owedPar, Types.Wei memory owedWei ) = state.getNewParAndDeltaWeiForLiquidation( args.vaporAccount, args.owedMarket, args.amount ); ( Monetary.Price memory heldPrice, Monetary.Price memory owedPrice ) = _getLiquidationPrices( state, cache, args.heldMarket, args.owedMarket ); Types.Wei memory heldWei = _owedWeiToHeldWei(owedWei, heldPrice, owedPrice); // if attempting to over-borrow the held asset, bound it by the maximum if (heldWei.value > maxHeldWei.value) { heldWei = maxHeldWei.negative(); owedWei = _heldWeiToOwedWei(heldWei, heldPrice, owedPrice); state.setParFromDeltaWei( args.vaporAccount, args.owedMarket, owedWei ); } else { state.setPar( args.vaporAccount, args.owedMarket, owedPar ); } // set the balances for the solid account state.setParFromDeltaWei( args.solidAccount, args.owedMarket, owedWei.negative() ); state.setParFromDeltaWei( args.solidAccount, args.heldMarket, heldWei.negative() ); Events.logVaporize( state, args, heldWei, owedWei, excessWei ); } function _call( Storage.State storage state, Actions.CallArgs memory args ) private { state.requireIsOperator(args.account, msg.sender); ICallee(args.callee).callFunction( msg.sender, args.account, args.data ); Events.logCall(args); } // ============ Private Functions ============ /** * For the purposes of liquidation or vaporization, get the value-equivalent amount of heldWei * given owedWei and the (spread-adjusted) prices of each asset. */ function _owedWeiToHeldWei( Types.Wei memory owedWei, Monetary.Price memory heldPrice, Monetary.Price memory owedPrice ) private pure returns (Types.Wei memory) { return Types.Wei({ sign: false, value: Math.getPartial(owedWei.value, owedPrice.value, heldPrice.value) }); } /** * For the purposes of liquidation or vaporization, get the value-equivalent amount of owedWei * given heldWei and the (spread-adjusted) prices of each asset. */ function _heldWeiToOwedWei( Types.Wei memory heldWei, Monetary.Price memory heldPrice, Monetary.Price memory owedPrice ) private pure returns (Types.Wei memory) { return Types.Wei({ sign: true, value: Math.getPartialRoundUp(heldWei.value, heldPrice.value, owedPrice.value) }); } /** * Attempt to vaporize an account's balance using the excess tokens in the protocol. Return a * bool and a wei value. The boolean is true if and only if the balance was fully vaporized. The * Wei value is how many excess tokens were used to partially or fully vaporize the account's * negative balance. */ function _vaporizeUsingExcess( Storage.State storage state, Actions.VaporizeArgs memory args ) internal returns (bool, Types.Wei memory) { Types.Wei memory excessWei = state.getNumExcessTokens(args.owedMarket); // There are no excess funds, return zero if (!excessWei.isPositive()) { return (false, Types.zeroWei()); } Types.Wei memory maxRefundWei = state.getWei(args.vaporAccount, args.owedMarket); maxRefundWei.sign = true; // The account is fully vaporizable using excess funds if (excessWei.value >= maxRefundWei.value) { state.setPar( args.vaporAccount, args.owedMarket, Types.zeroPar() ); return (true, maxRefundWei); } // The account is only partially vaporizable using excess funds else { state.setParFromDeltaWei( args.vaporAccount, args.owedMarket, excessWei ); return (false, excessWei); } } /** * Return the (spread-adjusted) prices of two assets for the purposes of liquidation or * vaporization. */ function _getLiquidationPrices( Storage.State storage state, Cache.MarketCache memory cache, uint256 heldMarketId, uint256 owedMarketId ) internal view returns ( Monetary.Price memory, Monetary.Price memory ) { uint256 originalPrice = cache.getPrice(owedMarketId).value; Decimal.D256 memory spread = state.getLiquidationSpreadForPair( heldMarketId, owedMarketId ); Monetary.Price memory owedPrice = Monetary.Price({ value: originalPrice.add(Decimal.mul(originalPrice, spread)) }); return (cache.getPrice(heldMarketId), owedPrice); } } // File: contracts/protocol/Operation.sol /** * @title Operation * @author dYdX * * Primary public function for allowing users and contracts to manage accounts within Solo */ contract Operation is State, ReentrancyGuard { // ============ Public Functions ============ /** * The main entry-point to Solo that allows users and contracts to manage accounts. * Take one or more actions on one or more accounts. The msg.sender must be the owner or * operator of all accounts except for those being liquidated, vaporized, or traded with. * One call to operate() is considered a singular "operation". Account collateralization is * ensured only after the completion of the entire operation. * * @param accounts A list of all accounts that will be used in this operation. Cannot contain * duplicates. In each action, the relevant account will be referred-to by its * index in the list. * @param actions An ordered list of all actions that will be taken in this operation. The * actions will be processed in order. */ function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public nonReentrant { OperationImpl.operate( g_state, accounts, actions ); } } // File: contracts/protocol/Permission.sol /** * @title Permission * @author dYdX * * Public function that allows other addresses to manage accounts */ contract Permission is State { // ============ Events ============ event LogOperatorSet( address indexed owner, address operator, bool trusted ); // ============ Structs ============ struct OperatorArg { address operator; bool trusted; } // ============ Public Functions ============ /** * Approves/disapproves any number of operators. An operator is an external address that has the * same permissions to manipulate an account as the owner of the account. Operators are simply * addresses and therefore may either be externally-owned Ethereum accounts OR smart contracts. * * Operators are also able to act as AutoTrader contracts on behalf of the account owner if the * operator is a smart contract and implements the IAutoTrader interface. * * @param args A list of OperatorArgs which have an address and a boolean. The boolean value * denotes whether to approve (true) or revoke approval (false) for that address. */ function setOperators( OperatorArg[] memory args ) public { for (uint256 i = 0; i < args.length; i++) { address operator = args[i].operator; bool trusted = args[i].trusted; g_state.operators[msg.sender][operator] = trusted; emit LogOperatorSet(msg.sender, operator, trusted); } } } // File: contracts/protocol/SoloMargin.sol /** * @title SoloMargin * @author dYdX * * Main contract that inherits from other contracts */ contract SoloMargin is State, Admin, Getters, Operation, Permission { // ============ Constructor ============ constructor( Storage.RiskParams memory riskParams, Storage.RiskLimits memory riskLimits ) public { g_state.riskParams = riskParams; g_state.riskLimits = riskLimits; } }
File 2 of 15: 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 3 of 15: UniswapV2Pair
// File: contracts/uniswapv2/interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } // File: contracts/uniswapv2/libraries/SafeMath.sol pragma solidity =0.6.12; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathUniswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File: contracts/uniswapv2/UniswapV2ERC20.sol pragma solidity =0.6.12; contract UniswapV2ERC20 { using SafeMathUniswap for uint; string public constant name = 'SushiSwap LP Token'; string public constant symbol = 'SLP'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'UniswapV2: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE'); _approve(owner, spender, value); } } // File: contracts/uniswapv2/libraries/Math.sol pragma solidity =0.6.12; // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: contracts/uniswapv2/libraries/UQ112x112.sol pragma solidity =0.6.12; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } // File: contracts/uniswapv2/interfaces/IERC20.sol pragma solidity >=0.5.0; interface IERC20Uniswap { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint 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 (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // File: contracts/uniswapv2/interfaces/IUniswapV2Callee.sol pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } // File: contracts/uniswapv2/UniswapV2Pair.sol pragma solidity =0.6.12; interface IMigrator { // Return the desired amount of liquidity token that the migrator wants. function desiredLiquidity() external view returns (uint256); } contract UniswapV2Pair is UniswapV2ERC20 { using SafeMathUniswap for uint; using UQ112x112 for uint224; uint public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public token0; address public token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint public price0CumulativeLast; uint public price1CumulativeLast; uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'UniswapV2: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED'); } event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } // update reserves and, on the first call per block, price accumulators function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IUniswapV2Factory(factory).feeTo(); feeOn = feeTo != address(0); uint _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)); uint denominator = rootK.mul(5).add(rootKLast); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } // this low-level function should be called from a contract which performs important safety checks function mint(address to) external lock returns (uint liquidity) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings uint balance0 = IERC20Uniswap(token0).balanceOf(address(this)); uint balance1 = IERC20Uniswap(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { address migrator = IUniswapV2Factory(factory).migrator(); if (msg.sender == migrator) { liquidity = IMigrator(migrator).desiredLiquidity(); require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity"); } else { require(migrator == address(0), "Must not have migrator"); liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } } else { liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Mint(msg.sender, amount0, amount1); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock returns (uint amount0, uint amount1) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; // gas savings uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K'); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external lock { _update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1); } }
File 4 of 15: AlphaToken
// File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // 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: @openzeppelin/contracts/math/SafeMath.sol 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/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/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/distribution/AlphaToken.sol pragma solidity 0.6.11; /** * @title Alpha token contract * @notice Implements Alpha token contract * @author Alpha Finance Lab */ contract AlphaToken is ERC20("AlphaToken", "ALPHA"), Ownable { function getOwner() public view returns (address) { return owner(); } function mint(uint256 _value) public onlyOwner { _mint(msg.sender, _value); } function burn(uint256 _value) public onlyOwner { _burn(msg.sender, _value); } }
File 5 of 15: IbETHRouter
// File: openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity-2.3.0/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ 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. * * > 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: @uniswap/v2-core/contracts/libraries/Math.sol pragma solidity =0.5.16; // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol pragma solidity ^0.5.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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts/5/uniswap/IUniswapV2Router02.sol pragma solidity >=0.5.0; interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // File: contracts/5/interfaces/IBank.sol pragma solidity 0.5.16; interface IBank { /** * @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. * * > 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 Return the total ETH entitled to the token holders. Be careful of unaccrued interests. function totalETH() external view returns (uint256); /// @dev Add more ETH to the bank. Hope to get some good returns. function deposit() external payable; /// @dev Withdraw ETH from the bank by burning the share tokens. function withdraw(uint256 share) external; } // File: contracts/5/IbETHRouter.sol pragma solidity =0.5.16; // 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))), "TransferHelper: APPROVE_FAILED" ); } 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))), "TransferHelper: TRANSFER_FAILED" ); } 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))), "TransferHelper: TRANSFER_FROM_FAILED" ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call.value(value)(new bytes(0)); require(success, "TransferHelper: ETH_TRANSFER_FAILED"); } } contract IbETHRouter is Ownable { using SafeMath for uint256; address public router; address public ibETH; address public alpha; address public lpToken; constructor(address _router, address _ibETH, address _alpha) public { router = _router; ibETH = _ibETH; alpha = _alpha; address factory = IUniswapV2Router02(router).factory(); lpToken = IUniswapV2Factory(factory).getPair(ibETH, alpha); IUniswapV2Pair(lpToken).approve(router, uint256(-1)); // 100% trust in the router IBank(ibETH).approve(router, uint256(-1)); // 100% trust in the router IERC20(alpha).approve(router, uint256(-1)); // 100% trust in the router } function() external payable { assert(msg.sender == ibETH); // only accept ETH via fallback from the Bank contract } // **** ETH-ibETH FUNCTIONS **** // Get number of ibETH needed to withdraw to get exact amountETH from the Bank function ibETHForExactETH(uint256 amountETH) public view returns (uint256) { uint256 totalETH = IBank(ibETH).totalETH(); return totalETH == 0 ? amountETH : amountETH.mul(IBank(ibETH).totalSupply()).add(totalETH).sub(1).div(totalETH); } // Add ETH and Alpha from ibETH-Alpha Pool. // 1. Receive ETH and Alpha from caller. // 2. Wrap ETH to ibETH. // 3. Provide liquidity to the pool. function addLiquidityETH( uint256 amountAlphaDesired, uint256 amountAlphaMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountAlpha, uint256 amountETH, uint256 liquidity ) { TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaDesired); IBank(ibETH).deposit.value(msg.value)(); uint256 amountIbETHDesired = IBank(ibETH).balanceOf(address(this)); uint256 amountIbETH; (amountAlpha, amountIbETH, liquidity) = IUniswapV2Router02(router).addLiquidity( alpha, ibETH, amountAlphaDesired, amountIbETHDesired, amountAlphaMin, 0, to, deadline ); if (amountAlphaDesired > amountAlpha) { TransferHelper.safeTransfer(alpha, msg.sender, amountAlphaDesired.sub(amountAlpha)); } IBank(ibETH).withdraw(amountIbETHDesired.sub(amountIbETH)); amountETH = msg.value - address(this).balance; if (amountETH > 0) { TransferHelper.safeTransferETH(msg.sender, address(this).balance); } require(amountETH >= amountETHMin, "IbETHRouter: require more ETH than amountETHmin"); } /// @dev Compute optimal deposit amount /// @param amtA amount of token A desired to deposit /// @param amtB amonut of token B desired to deposit /// @param resA amount of token A in reserve /// @param resB amount of token B in reserve /// (forked from ./StrategyAddTwoSidesOptimal.sol) function optimalDeposit( uint256 amtA, uint256 amtB, uint256 resA, uint256 resB ) internal pure returns (uint256 swapAmt, bool isReversed) { if (amtA.mul(resB) >= amtB.mul(resA)) { swapAmt = _optimalDepositA(amtA, amtB, resA, resB); isReversed = false; } else { swapAmt = _optimalDepositA(amtB, amtA, resB, resA); isReversed = true; } } /// @dev Compute optimal deposit amount helper /// @param amtA amount of token A desired to deposit /// @param amtB amonut of token B desired to deposit /// @param resA amount of token A in reserve /// @param resB amount of token B in reserve /// (forked from ./StrategyAddTwoSidesOptimal.sol) function _optimalDepositA( uint256 amtA, uint256 amtB, uint256 resA, uint256 resB ) internal pure returns (uint256) { require(amtA.mul(resB) >= amtB.mul(resA), "Reversed"); uint256 a = 997; uint256 b = uint256(1997).mul(resA); uint256 _c = (amtA.mul(resB)).sub(amtB.mul(resA)); uint256 c = _c.mul(1000).div(amtB.add(resB)).mul(resA); uint256 d = a.mul(c).mul(4); uint256 e = Math.sqrt(b.mul(b).add(d)); uint256 numerator = e.sub(b); uint256 denominator = a.mul(2); return numerator.div(denominator); } // Add ibETH and Alpha to ibETH-Alpha Pool. // All ibETH and Alpha supplied are optimally swap and add too ibETH-Alpha Pool. function addLiquidityTwoSidesOptimal( uint256 amountIbETHDesired, uint256 amountAlphaDesired, uint256 amountLPMin, address to, uint256 deadline ) external returns ( uint256 liquidity ) { if (amountIbETHDesired > 0) { TransferHelper.safeTransferFrom(ibETH, msg.sender, address(this), amountIbETHDesired); } if (amountAlphaDesired > 0) { TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaDesired); } uint256 swapAmt; bool isReversed; { (uint256 r0, uint256 r1, ) = IUniswapV2Pair(lpToken).getReserves(); (uint256 ibETHReserve, uint256 alphaReserve) = IUniswapV2Pair(lpToken).token0() == ibETH ? (r0, r1) : (r1, r0); (swapAmt, isReversed) = optimalDeposit(amountIbETHDesired, amountAlphaDesired, ibETHReserve, alphaReserve); } address[] memory path = new address[](2); (path[0], path[1]) = isReversed ? (alpha, ibETH) : (ibETH, alpha); IUniswapV2Router02(router).swapExactTokensForTokens(swapAmt, 0, path, address(this), now); (,, liquidity) = IUniswapV2Router02(router).addLiquidity( alpha, ibETH, IERC20(alpha).balanceOf(address(this)), IBank(ibETH).balanceOf(address(this)), 0, 0, to, deadline ); uint256 dustAlpha = IERC20(alpha).balanceOf(address(this)); uint256 dustIbETH = IBank(ibETH).balanceOf(address(this)); if (dustAlpha > 0) { TransferHelper.safeTransfer(alpha, msg.sender, dustAlpha); } if (dustIbETH > 0) { TransferHelper.safeTransfer(ibETH, msg.sender, dustIbETH); } require(liquidity >= amountLPMin, "IbETHRouter: receive less lpToken than amountLPMin"); } // Add ETH and Alpha to ibETH-Alpha Pool. // All ETH and Alpha supplied are optimally swap and add too ibETH-Alpha Pool. function addLiquidityTwoSidesOptimalETH( uint256 amountAlphaDesired, uint256 amountLPMin, address to, uint256 deadline ) external payable returns ( uint256 liquidity ) { if (amountAlphaDesired > 0) { TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaDesired); } IBank(ibETH).deposit.value(msg.value)(); uint256 amountIbETHDesired = IBank(ibETH).balanceOf(address(this)); uint256 swapAmt; bool isReversed; { (uint256 r0, uint256 r1, ) = IUniswapV2Pair(lpToken).getReserves(); (uint256 ibETHReserve, uint256 alphaReserve) = IUniswapV2Pair(lpToken).token0() == ibETH ? (r0, r1) : (r1, r0); (swapAmt, isReversed) = optimalDeposit(amountIbETHDesired, amountAlphaDesired, ibETHReserve, alphaReserve); } address[] memory path = new address[](2); (path[0], path[1]) = isReversed ? (alpha, ibETH) : (ibETH, alpha); IUniswapV2Router02(router).swapExactTokensForTokens(swapAmt, 0, path, address(this), now); (,, liquidity) = IUniswapV2Router02(router).addLiquidity( alpha, ibETH, IERC20(alpha).balanceOf(address(this)), IBank(ibETH).balanceOf(address(this)), 0, 0, to, deadline ); uint256 dustAlpha = IERC20(alpha).balanceOf(address(this)); uint256 dustIbETH = IBank(ibETH).balanceOf(address(this)); if (dustAlpha > 0) { TransferHelper.safeTransfer(alpha, msg.sender, dustAlpha); } if (dustIbETH > 0) { TransferHelper.safeTransfer(ibETH, msg.sender, dustIbETH); } require(liquidity >= amountLPMin, "IbETHRouter: receive less lpToken than amountLPMin"); } // Remove ETH and Alpha from ibETH-Alpha Pool. // 1. Remove ibETH and Alpha from the pool. // 2. Unwrap ibETH to ETH. // 3. Return ETH and Alpha to caller. function removeLiquidityETH( uint256 liquidity, uint256 amountAlphaMin, uint256 amountETHMin, address to, uint256 deadline ) public returns (uint256 amountAlpha, uint256 amountETH) { TransferHelper.safeTransferFrom(lpToken, msg.sender, address(this), liquidity); uint256 amountIbETH; (amountAlpha, amountIbETH) = IUniswapV2Router02(router).removeLiquidity( alpha, ibETH, liquidity, amountAlphaMin, 0, address(this), deadline ); TransferHelper.safeTransfer(alpha, to, amountAlpha); IBank(ibETH).withdraw(amountIbETH); amountETH = address(this).balance; if (amountETH > 0) { TransferHelper.safeTransferETH(msg.sender, address(this).balance); } require(amountETH >= amountETHMin, "IbETHRouter: receive less ETH than amountETHmin"); } // Remove liquidity from ibETH-Alpha Pool and convert all ibETH to Alpha // 1. Remove ibETH and Alpha from the pool. // 2. Swap ibETH for Alpha. // 3. Return Alpha to caller. function removeLiquidityAllAlpha( uint256 liquidity, uint256 amountAlphaMin, address to, uint256 deadline ) public returns (uint256 amountAlpha) { TransferHelper.safeTransferFrom(lpToken, msg.sender, address(this), liquidity); (uint256 removeAmountAlpha, uint256 removeAmountIbETH) = IUniswapV2Router02(router).removeLiquidity( alpha, ibETH, liquidity, 0, 0, address(this), deadline ); address[] memory path = new address[](2); path[0] = ibETH; path[1] = alpha; uint256[] memory amounts = IUniswapV2Router02(router).swapExactTokensForTokens(removeAmountIbETH, 0, path, to, deadline); TransferHelper.safeTransfer(alpha, to, removeAmountAlpha); amountAlpha = removeAmountAlpha.add(amounts[1]); require(amountAlpha >= amountAlphaMin, "IbETHRouter: receive less Alpha than amountAlphaMin"); } // Swap exact amount of ETH for Token // 1. Receive ETH from caller // 2. Wrap ETH to ibETH. // 3. Swap ibETH for Token function swapExactETHForAlpha( uint256 amountAlphaOutMin, address to, uint256 deadline ) external payable returns (uint256[] memory amounts) { IBank(ibETH).deposit.value(msg.value)(); address[] memory path = new address[](2); path[0] = ibETH; path[1] = alpha; uint256[] memory swapAmounts = IUniswapV2Router02(router).swapExactTokensForTokens(IBank(ibETH).balanceOf(address(this)), amountAlphaOutMin, path, to, deadline); amounts = new uint256[](2); amounts[0] = msg.value; amounts[1] = swapAmounts[1]; } // Swap Token for exact amount of ETH // 1. Receive Token from caller // 2. Swap Token for ibETH. // 3. Unwrap ibETH to ETH. function swapAlphaForExactETH( uint256 amountETHOut, uint256 amountAlphaInMax, address to, uint256 deadline ) external returns (uint256[] memory amounts) { TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaInMax); address[] memory path = new address[](2); path[0] = alpha; path[1] = ibETH; IBank(ibETH).withdraw(0); uint256[] memory swapAmounts = IUniswapV2Router02(router).swapTokensForExactTokens(ibETHForExactETH(amountETHOut), amountAlphaInMax, path, address(this), deadline); IBank(ibETH).withdraw(swapAmounts[1]); amounts = new uint256[](2); amounts[0] = swapAmounts[0]; amounts[1] = address(this).balance; TransferHelper.safeTransferETH(to, address(this).balance); if (amountAlphaInMax > amounts[0]) { TransferHelper.safeTransfer(alpha, msg.sender, amountAlphaInMax.sub(amounts[0])); } } // Swap exact amount of Token for ETH // 1. Receive Token from caller // 2. Swap Token for ibETH. // 3. Unwrap ibETH to ETH. function swapExactAlphaForETH( uint256 amountAlphaIn, uint256 amountETHOutMin, address to, uint256 deadline ) external returns (uint256[] memory amounts) { TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaIn); address[] memory path = new address[](2); path[0] = alpha; path[1] = ibETH; uint256[] memory swapAmounts = IUniswapV2Router02(router).swapExactTokensForTokens(amountAlphaIn, 0, path, address(this), deadline); IBank(ibETH).withdraw(swapAmounts[1]); amounts = new uint256[](2); amounts[0] = swapAmounts[0]; amounts[1] = address(this).balance; TransferHelper.safeTransferETH(to, amounts[1]); require(amounts[1] >= amountETHOutMin, "IbETHRouter: receive less ETH than amountETHmin"); } // Swap ETH for exact amount of Token // 1. Receive ETH from caller // 2. Wrap ETH to ibETH. // 3. Swap ibETH for Token function swapETHForExactAlpha( uint256 amountAlphaOut, address to, uint256 deadline ) external payable returns (uint256[] memory amounts) { IBank(ibETH).deposit.value(msg.value)(); uint256 amountIbETHInMax = IBank(ibETH).balanceOf(address(this)); address[] memory path = new address[](2); path[0] = ibETH; path[1] = alpha; uint256[] memory swapAmounts = IUniswapV2Router02(router).swapTokensForExactTokens(amountAlphaOut, amountIbETHInMax, path, to, deadline); amounts = new uint256[](2); amounts[0] = msg.value; amounts[1] = swapAmounts[1]; // Transfer left over ETH back if (amountIbETHInMax > swapAmounts[0]) { IBank(ibETH).withdraw(amountIbETHInMax.sub(swapAmounts[0])); amounts[0] = msg.value - address(this).balance; TransferHelper.safeTransferETH(to, address(this).balance); } } /// @dev Recover ERC20 tokens that were accidentally sent to this smart contract. /// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens. /// @param to The address to send the tokens to. /// @param value The number of tokens to transfer to `to`. function recover(address token, address to, uint256 value) external onlyOwner { TransferHelper.safeTransfer(token, to, value); } /// @dev Recover ETH that were accidentally sent to this smart contract. /// @param to The address to send the ETH to. /// @param value The number of ETH to transfer to `to`. function recoverETH(address to, uint256 value) external onlyOwner { TransferHelper.safeTransferETH(to, value); } }
File 6 of 15: UniswapV2Pair
// File: contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/interfaces/IUniswapV2ERC20.sol pragma solidity >=0.5.0; interface IUniswapV2ERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } // File: contracts/libraries/SafeMath.sol pragma solidity =0.5.16; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File: contracts/UniswapV2ERC20.sol pragma solidity =0.5.16; contract UniswapV2ERC20 is IUniswapV2ERC20 { using SafeMath for uint; string public constant name = 'Uniswap V2'; string public constant symbol = 'UNI-V2'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := chainid } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'UniswapV2: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE'); _approve(owner, spender, value); } } // File: contracts/libraries/Math.sol pragma solidity =0.5.16; // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: contracts/libraries/UQ112x112.sol pragma solidity =0.5.16; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } // File: contracts/interfaces/IERC20.sol pragma solidity >=0.5.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint 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 (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // File: contracts/interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: contracts/interfaces/IUniswapV2Callee.sol pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } // File: contracts/UniswapV2Pair.sol pragma solidity =0.5.16; contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 { using SafeMath for uint; using UQ112x112 for uint224; uint public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public token0; address public token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint public price0CumulativeLast; uint public price1CumulativeLast; uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'UniswapV2: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED'); } event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } // update reserves and, on the first call per block, price accumulators function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IUniswapV2Factory(factory).feeTo(); feeOn = feeTo != address(0); uint _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)); uint denominator = rootK.mul(5).add(rootKLast); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } // this low-level function should be called from a contract which performs important safety checks function mint(address to) external lock returns (uint liquidity) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings uint balance0 = IERC20(token0).balanceOf(address(this)); uint balance1 = IERC20(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Mint(msg.sender, amount0, amount1); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock returns (uint amount0, uint amount1) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; // gas savings uint balance0 = IERC20(_token0).balanceOf(address(this)); uint balance1 = IERC20(_token1).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K'); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external lock { _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1); } }
File 7 of 15: Bank
// File: openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity-2.3.0/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ 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. * * > 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: openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol pragma solidity ^0.5.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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: openzeppelin-solidity-2.3.0/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } // File: openzeppelin-solidity-2.3.0/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: openzeppelin-solidity-2.3.0/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier * available, which can be aplied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } // File: contracts/BankConfig.sol pragma solidity 0.5.16; interface BankConfig { /// @dev Return minimum ETH debt size per position. function minDebtSize() external view returns (uint256); /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint256 debt, uint256 floating) external view returns (uint256); /// @dev Return the bps rate for reserve pool. function getReservePoolBps() external view returns (uint256); /// @dev Return the bps rate for Avada Kill caster. function getKillBps() external view returns (uint256); /// @dev Return whether the given address is a goblin. function isGoblin(address goblin) external view returns (bool); /// @dev Return whether the given goblin accepts more debt. Revert on non-goblin. function acceptDebt(address goblin) external view returns (bool); /// @dev Return the work factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin. function workFactor(address goblin, uint256 debt) external view returns (uint256); /// @dev Return the kill factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin. function killFactor(address goblin, uint256 debt) external view returns (uint256); } // File: contracts/Goblin.sol pragma solidity 0.5.16; interface Goblin { /// @dev Work on a (potentially new) position. Optionally send ETH back to Bank. function work(uint256 id, address user, uint256 debt, bytes calldata data) external payable; /// @dev Re-invest whatever the goblin is working on. function reinvest() external; /// @dev Return the amount of ETH wei to get back if we are to liquidate the position. function health(uint256 id) external view returns (uint256); /// @dev Liquidate the given position to ETH. Send all ETH back to Bank. function liquidate(uint256 id) external; } // File: contracts/SafeToken.sol pragma solidity 0.5.16; interface ERC20Interface { function balanceOf(address user) external view returns (uint256); } library SafeToken { function myBalance(address token) internal view returns (uint256) { return ERC20Interface(token).balanceOf(address(this)); } function balanceOf(address token, address user) internal view returns (uint256) { return ERC20Interface(token).balanceOf(user); } 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))), "!safeApprove"); } 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))), "!safeTransfer"); } 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))), "!safeTransferFrom"); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call.value(value)(new bytes(0)); require(success, "!safeTransferETH"); } } // File: contracts/Bank.sol pragma solidity 0.5.16; contract Bank is ERC20, ReentrancyGuard, Ownable { /// @notice Libraries using SafeToken for address; using SafeMath for uint256; /// @notice Events event AddDebt(uint256 indexed id, uint256 debtShare); event RemoveDebt(uint256 indexed id, uint256 debtShare); event Work(uint256 indexed id, uint256 loan); event Kill(uint256 indexed id, address indexed killer, uint256 prize, uint256 left); string public name = "Interest Bearing ETH"; string public symbol = "ibETH"; uint8 public decimals = 18; struct Position { address goblin; address owner; uint256 debtShare; } BankConfig public config; mapping (uint256 => Position) public positions; uint256 public nextPositionID = 1; uint256 public glbDebtShare; uint256 public glbDebtVal; uint256 public lastAccrueTime; uint256 public reservePool; /// @dev Require that the caller must be an EOA account to avoid flash loans. modifier onlyEOA() { require(msg.sender == tx.origin, "not eoa"); _; } /// @dev Add more debt to the global debt pool. modifier accrue(uint256 msgValue) { if (now > lastAccrueTime) { uint256 interest = pendingInterest(msgValue); uint256 toReserve = interest.mul(config.getReservePoolBps()).div(10000); reservePool = reservePool.add(toReserve); glbDebtVal = glbDebtVal.add(interest); lastAccrueTime = now; } _; } constructor(BankConfig _config) public { config = _config; lastAccrueTime = now; } /// @dev Return the pending interest that will be accrued in the next call. /// @param msgValue Balance value to subtract off address(this).balance when called from payable functions. function pendingInterest(uint256 msgValue) public view returns (uint256) { if (now > lastAccrueTime) { uint256 timePast = now.sub(lastAccrueTime); uint256 balance = address(this).balance.sub(msgValue); uint256 ratePerSec = config.getInterestRate(glbDebtVal, balance); return ratePerSec.mul(glbDebtVal).mul(timePast).div(1e18); } else { return 0; } } /// @dev Return the ETH debt value given the debt share. Be careful of unaccrued interests. /// @param debtShare The debt share to be converted. function debtShareToVal(uint256 debtShare) public view returns (uint256) { if (glbDebtShare == 0) return debtShare; // When there's no share, 1 share = 1 val. return debtShare.mul(glbDebtVal).div(glbDebtShare); } /// @dev Return the debt share for the given debt value. Be careful of unaccrued interests. /// @param debtVal The debt value to be converted. function debtValToShare(uint256 debtVal) public view returns (uint256) { if (glbDebtShare == 0) return debtVal; // When there's no share, 1 share = 1 val. return debtVal.mul(glbDebtShare).div(glbDebtVal); } /// @dev Return ETH value and debt of the given position. Be careful of unaccrued interests. /// @param id The position ID to query. function positionInfo(uint256 id) public view returns (uint256, uint256) { Position storage pos = positions[id]; return (Goblin(pos.goblin).health(id), debtShareToVal(pos.debtShare)); } /// @dev Return the total ETH entitled to the token holders. Be careful of unaccrued interests. function totalETH() public view returns (uint256) { return address(this).balance.add(glbDebtVal).sub(reservePool); } /// @dev Add more ETH to the bank. Hope to get some good returns. function deposit() external payable accrue(msg.value) nonReentrant { uint256 total = totalETH().sub(msg.value); uint256 share = total == 0 ? msg.value : msg.value.mul(totalSupply()).div(total); _mint(msg.sender, share); } /// @dev Withdraw ETH from the bank by burning the share tokens. function withdraw(uint256 share) external accrue(0) nonReentrant { uint256 amount = share.mul(totalETH()).div(totalSupply()); _burn(msg.sender, share); SafeToken.safeTransferETH(msg.sender, amount); } /// @dev Create a new farming position to unlock your yield farming potential. /// @param id The ID of the position to unlock the earning. Use ZERO for new position. /// @param goblin The address of the authorized goblin to work for this position. /// @param loan The amount of ETH to borrow from the pool. /// @param maxReturn The max amount of ETH to return to the pool. /// @param data The calldata to pass along to the goblin for more working context. function work(uint256 id, address goblin, uint256 loan, uint256 maxReturn, bytes calldata data) external payable onlyEOA accrue(msg.value) nonReentrant { // 1. Sanity check the input position, or add a new position of ID is 0. if (id == 0) { id = nextPositionID++; positions[id].goblin = goblin; positions[id].owner = msg.sender; } else { require(id < nextPositionID, "bad position id"); require(positions[id].goblin == goblin, "bad position goblin"); require(positions[id].owner == msg.sender, "not position owner"); } emit Work(id, loan); // 2. Make sure the goblin can accept more debt and remove the existing debt. require(config.isGoblin(goblin), "not a goblin"); require(loan == 0 || config.acceptDebt(goblin), "goblin not accept more debt"); uint256 debt = _removeDebt(id).add(loan); // 3. Perform the actual work, using a new scope to avoid stack-too-deep errors. uint256 back; { uint256 sendETH = msg.value.add(loan); require(sendETH <= address(this).balance, "insufficient ETH in the bank"); uint256 beforeETH = address(this).balance.sub(sendETH); Goblin(goblin).work.value(sendETH)(id, msg.sender, debt, data); back = address(this).balance.sub(beforeETH); } // 4. Check and update position debt. uint256 lessDebt = Math.min(debt, Math.min(back, maxReturn)); debt = debt.sub(lessDebt); if (debt > 0) { require(debt >= config.minDebtSize(), "too small debt size"); uint256 health = Goblin(goblin).health(id); uint256 workFactor = config.workFactor(goblin, debt); require(health.mul(workFactor) >= debt.mul(10000), "bad work factor"); _addDebt(id, debt); } // 5. Return excess ETH back. if (back > lessDebt) SafeToken.safeTransferETH(msg.sender, back - lessDebt); } /// @dev Kill the given to the position. Liquidate it immediately if killFactor condition is met. /// @param id The position ID to be killed. function kill(uint256 id) external onlyEOA accrue(0) nonReentrant { // 1. Verify that the position is eligible for liquidation. Position storage pos = positions[id]; require(pos.debtShare > 0, "no debt"); uint256 debt = _removeDebt(id); uint256 health = Goblin(pos.goblin).health(id); uint256 killFactor = config.killFactor(pos.goblin, debt); require(health.mul(killFactor) < debt.mul(10000), "can't liquidate"); // 2. Perform liquidation and compute the amount of ETH received. uint256 beforeETH = address(this).balance; Goblin(pos.goblin).liquidate(id); uint256 back = address(this).balance.sub(beforeETH); uint256 prize = back.mul(config.getKillBps()).div(10000); uint256 rest = back.sub(prize); // 3. Clear position debt and return funds to liquidator and position owner. if (prize > 0) SafeToken.safeTransferETH(msg.sender, prize); uint256 left = rest > debt ? rest - debt : 0; if (left > 0) SafeToken.safeTransferETH(pos.owner, left); emit Kill(id, msg.sender, prize, left); } /// @dev Internal function to add the given debt value to the given position. function _addDebt(uint256 id, uint256 debtVal) internal { Position storage pos = positions[id]; uint256 debtShare = debtValToShare(debtVal); pos.debtShare = pos.debtShare.add(debtShare); glbDebtShare = glbDebtShare.add(debtShare); glbDebtVal = glbDebtVal.add(debtVal); emit AddDebt(id, debtShare); } /// @dev Internal function to clear the debt of the given position. Return the debt value. function _removeDebt(uint256 id) internal returns (uint256) { Position storage pos = positions[id]; uint256 debtShare = pos.debtShare; if (debtShare > 0) { uint256 debtVal = debtShareToVal(debtShare); pos.debtShare = 0; glbDebtShare = glbDebtShare.sub(debtShare); glbDebtVal = glbDebtVal.sub(debtVal); emit RemoveDebt(id, debtShare); return debtVal; } else { return 0; } } /// @dev Update bank configuration to a new address. Must only be called by owner. /// @param _config The new configurator address. function updateConfig(BankConfig _config) external onlyOwner { config = _config; } /// @dev Withdraw ETH reserve for underwater positions to the given address. /// @param to The address to transfer ETH to. /// @param value The number of ETH tokens to withdraw. Must not exceed `reservePool`. function withdrawReserve(address to, uint256 value) external onlyOwner nonReentrant { reservePool = reservePool.sub(value); SafeToken.safeTransferETH(to, value); } /// @dev Reduce ETH reserve, effectively giving them to the depositors. /// @param value The number of ETH reserve to reduce. function reduceReserve(uint256 value) external onlyOwner { reservePool = reservePool.sub(value); } /// @dev Recover ERC20 tokens that were accidentally sent to this smart contract. /// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens. /// @param to The address to send the tokens to. /// @param value The number of tokens to transfer to `to`. function recover(address token, address to, uint256 value) external onlyOwner nonReentrant { token.safeTransfer(to, value); } /// @dev Fallback function to accept ETH. Goblins will send ETH back the pool. function() external payable {} }
File 8 of 15: ChiToken
/* ,╖╗#▒▓▓▓▓▓╣╬╣▓▓▓▓▒#╗╗╓, ,╗@▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓╗╖ ╓#▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝▀╠╠▄╣╝╜"""╙╙▀╝╝╣╬╬╬╬▓▌╖ ╓▓╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▀`╓å▓▓▓╙ ,▄▓▓██▓▓▓▄▄▄▄▄╠╠╙╠▄▄ ╓@╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▌ ê`' *▀▀▀▀▀▀▀▓██████████████▄ ╔▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ╙▀████████████▌ ╓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ╙████████████▌ ,▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▀ ╗▄█████████████▄ é╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▌ #╙ ╙▀█████████████▓ ╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▀ ╙▓╬╣▓▄ ╙▀▀███████████µ ▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▀╣╝╙ ╒▓╬╬╬╬╬╬▓ ╙████████████████µ ▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▌ ╖╖╖▄▓╬╬╬╬╬╬╬▓ █████████████████µ ╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ,#▓╣╬╬▓╬╬╬╬╬╬╬╬╬╬╬╬▌ ▓█████████████████ ]╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╓╖ ]╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣╨ ██████████████████▌ ▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▌╖, ╙╠╠▓╬╬╬╬╬╬╬╬╬▓╝╙ ╫███████████████████ ]╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝▀╙ ▓████████████████████▌ ║╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝▀╙` ▄███████████████████████ ╟╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓╝▀╙ ,▄█████████████████████████ ╟╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝╜` ▄▓████████████████████████████ ║╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣▀` ,▄▄▓████████████████████████████████ ▐╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓╙ ,,,▄╠▓██████████████████████████████▌ ╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓╙╔▒` ╓▄▓████████████████████████████████████████⌐ ╚╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓╣▓ ▄▓████████████████████████████████████████████ ▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ▄██████████████████████████████████████████████⌐ ╣╬╬╬╬╬╬╬╬╬╬╬╬╬╛ ▄███████████████████████████████████████████████▌ └╣╬╬╬╬╬╬╬╬╬╬╬▓ ▄███████████████████████████████████████████████▌ └▓╬╬╬╬╬╬╬╬╬╬Γ ]███████████████████████████████████████████████▀ ╣╬╬╬╬╬╬╬╬╬⌐ ╫████████████████████████████████▀▀▀▀▀▓████████╜ ╙╬╬╬╬╬╬╬╬⌐ ╟███████████████████████████▀╙ ,▄▓▓▓▓▓████▓ ╫╬╬╬╬╬╬b ████████████████████████▀` ,Φ▀▀█████████╙ ╫╬╬╬╬▌╟ ██████████████████▀╓▀─ ▄▓█████████▀ ╚╣╬▓╣▓ └▀████████████▀` ╓▓█████████▓╙ ╙╝╬╬▓ .▄▄▓█▀▀▀` ▄▓█████████▀ ╙▀▓▄ ƒ,▓███████▀▀ " ╓▓█▓█████▀▀└ ╓▄▓████▀▀╙└ ██████╗██╗ ██╗██╗ ██████╗ █████╗ ███████╗████████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗ ██████╗ ██╗ ██╗ ██╗██╗███╗ ██╗ ██████╗██╗ ██╗ ██╔════╝██║ ██║██║ ██╔════╝ ██╔══██╗██╔════╝╚══██╔══╝██╔═══██╗██║ ██╔╝██╔════╝████╗ ██║ ██╔══██╗╚██╗ ██╔╝ ███║██║████╗ ██║██╔════╝██║ ██║ ██║ ███████║██║ ██║ ███╗███████║███████╗ ██║ ██║ ██║█████╔╝ █████╗ ██╔██╗ ██║ ██████╔╝ ╚████╔╝ ╚██║██║██╔██╗ ██║██║ ███████║ ██║ ██╔══██║██║ ██║ ██║██╔══██║╚════██║ ██║ ██║ ██║██╔═██╗ ██╔══╝ ██║╚██╗██║ ██╔══██╗ ╚██╔╝ ██║██║██║╚██╗██║██║ ██╔══██║ ╚██████╗██║ ██║██║ ╚██████╔╝██║ ██║███████║ ██║ ╚██████╔╝██║ ██╗███████╗██║ ╚████║ ██████╔╝ ██║ ██║██║██║ ╚████║╚██████╗██║ ██║ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═════╝╚═╝ ╚═╝ Copyright by 1inch Corporation https://1inch.exchange --- Deployer wallet address: 0x7E1E3334130355799F833ffec2D731BCa3E68aF6 Signed raw transaction for chainId 1: 0xf90d7f808506fc23ac00830bd0fa8080b90d2c608060405234801561001057600080fd5b50610d0c806100206000396000f3fe608060405234801561001057600080fd5b506004361061010b5760003560e01c806370a08231116100a2578063a9059cbb11610071578063a9059cbb14610305578063b0ac19a014610331578063d89135cd1461036a578063d8ccd0f314610372578063dd62ed3e1461038f5761010b565b806370a08231146102b057806395d89b41146102d6578063a0712d68146102de578063a2309ff8146102fd5761010b565b806323b872dd116100de57806323b872dd14610213578063313ce567146102495780635f2e2b45146102675780636366b936146102935761010b565b806306fdde0314610110578063079d229f1461018d578063095ea7b3146101cb57806318160ddd1461020b575b600080fd5b6101186103bd565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561015257818101518382015260200161013a565b50505050905090810190601f16801561017f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101b9600480360360408110156101a357600080fd5b506001600160a01b0381351690602001356103ee565b60408051918252519081900360200190f35b6101f7600480360360408110156101e157600080fd5b506001600160a01b03813516906020013561041f565b604080519115158252519081900360200190f35b6101b9610435565b6101f76004803603606081101561022957600080fd5b506001600160a01b03813581169160208101359091169060400135610453565b6102516104c2565b6040805160ff9092168252519081900360200190f35b6101b96004803603604081101561027d57600080fd5b506001600160a01b0381351690602001356104c7565b6101b9600480360360208110156102a957600080fd5b50356104e2565b6101b9600480360360208110156102c657600080fd5b50356001600160a01b03166104ff565b61011861051a565b6102fb600480360360208110156102f457600080fd5b5035610539565b005b6101b961070d565b6101f76004803603604081101561031b57600080fd5b506001600160a01b038135169060200135610713565b61034e6004803603602081101561034757600080fd5b5035610720565b604080516001600160a01b039092168252519081900360200190f35b6101b961078b565b6101b96004803603602081101561038857600080fd5b5035610791565b6101b9600480360360408110156103a557600080fd5b506001600160a01b03813581169160200135166107aa565b60405180604001604052806015815260200174086d0d2408ec2e6e8ded6cadc40c4f24062d2dcc6d605b1b81525081565b60006104188361041361040985610404886104ff565b6107d5565b61040487336107aa565b6104c7565b9392505050565b600061042c3384846107eb565b50600192915050565b600061044e60035460025461084d90919063ffffffff16565b905090565b600061046084848461088f565b6104b884336104b385604051806060016040528060288152602001610c8b602891396001600160a01b038a166000908152600160209081526040808320338452909152902054919063ffffffff61096116565b6107eb565b5060019392505050565b600081565b60006104d383836109f8565b6104dc82610a59565b50919050565b60006104f96104f483610404336104ff565b610791565b92915050565b6001600160a01b031660009081526020819052604090205490565b6040518060400160405280600381526020016243484960e81b81525081565b6002547f746d4946c0e9f43f4dee607b0ef1fa1c3318585733ff6000526015600bf30000600052602082045b80156106d85781601e600080f55060018201601e600080f55060028201601e600080f55060038201601e600080f55060048201601e600080f55060058201601e600080f55060068201601e600080f55060078201601e600080f55060088201601e600080f55060098201601e600080f550600a8201601e600080f550600b8201601e600080f550600c8201601e600080f550600d8201601e600080f550600e8201601e600080f550600f8201601e600080f55060108201601e600080f55060118201601e600080f55060128201601e600080f55060138201601e600080f55060148201601e600080f55060158201601e600080f55060168201601e600080f55060178201601e600080f55060188201601e600080f55060198201601e600080f550601a8201601e600080f550601b8201601e600080f550601c8201601e600080f550601d8201601e600080f550601e8201601e600080f550601f8201601e600080f5506020919091019060001901610565565b50601f82165b80156106fc5781601e600080f55060019190910190600019016106de565b506107073383610ad1565b60025550565b60025481565b600061042c33848461088f565b604080516001600160f81b03196020808301919091523060601b602183015260358201939093527f3c1644c68e5d6cb380c36d1bf847fdbc0c7ac28030025a2fc5e63cce23c16348605580830191909152825180830390910181526075909101909152805191012090565b60035481565b600061079d3383610b50565b6107a682610a59565b5090565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b60008183106107e45781610418565b5090919050565b6001600160a01b03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b600061041883836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610961565b6108d281604051806060016040528060268152602001610c65602691396001600160a01b038616600090815260208190526040902054919063ffffffff61096116565b6001600160a01b038085166000908152602081905260408082209390935590841681522054610907908263ffffffff610be816565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600081848411156109f05760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156109b557818101518382015260200161099d565b50505050905090810190601f1680156109e25780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b610a028282610b50565b610a5582336104b384604051806060016040528060248152602001610cb3602491396001600160a01b0388166000908152600160209081526040808320338452909152902054919063ffffffff61096116565b5050565b60035460005b82811015610aca57610a72818301610720565b6040516001600160a01b039190911690600081818181865af19150503d8060008114610aba576040519150601f19603f3d011682016040523d82523d6000602084013e610abf565b606091505b505050600101610a5f565b5001600355565b6001600160a01b038216600090815260208190526040902054610afa908263ffffffff610be816565b6001600160a01b0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b610b9381604051806060016040528060228152602001610c43602291396001600160a01b038516600090815260208190526040902054919063ffffffff61096116565b6001600160a01b038316600081815260208181526040808320949094558351858152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35050565b600082820183811015610418576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fdfe45524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e20616d6f756e74206578636565647320616c6c6f77616e6365a2646970667358221220687f814fb4c0b3c6abd66ebdb1f1eabcf69becf92a382c3af453e0b21c3d15b564736f6c6343000608003325a00ed87a047b4e415bd7f8cf7a7ce5a1c204125df1cedc35c7bdcb71bd2a29a35ea02db2490337fa6c425f1b3d74b7b217de8b394adb3f571827629c06dc16364b66 --- */ // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol 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) { // Solidity only automatically asserts when dividing by 0 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/ChiToken.sol pragma solidity ^0.6.0; abstract contract ERC20WithoutTotalSupply is IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _approve(address owner, address spender, uint256 amount) internal { _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _mint(address account, uint256 amount) internal { _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); emit Transfer(account, address(0), amount); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract ChiToken is IERC20, ERC20WithoutTotalSupply { string constant public name = "Chi Gastoken by 1inch"; string constant public symbol = "CHI"; uint8 constant public decimals = 0; uint256 public totalMinted; uint256 public totalBurned; function totalSupply() public view override returns(uint256) { return totalMinted.sub(totalBurned); } function mint(uint256 value) public { uint256 offset = totalMinted; assembly { mstore(0, 0x746d4946c0e9F43F4Dee607b0eF1fA1c3318585733ff6000526015600bf30000) for {let i := div(value, 32)} i {i := sub(i, 1)} { pop(create2(0, 0, 30, add(offset, 0))) pop(create2(0, 0, 30, add(offset, 1))) pop(create2(0, 0, 30, add(offset, 2))) pop(create2(0, 0, 30, add(offset, 3))) pop(create2(0, 0, 30, add(offset, 4))) pop(create2(0, 0, 30, add(offset, 5))) pop(create2(0, 0, 30, add(offset, 6))) pop(create2(0, 0, 30, add(offset, 7))) pop(create2(0, 0, 30, add(offset, 8))) pop(create2(0, 0, 30, add(offset, 9))) pop(create2(0, 0, 30, add(offset, 10))) pop(create2(0, 0, 30, add(offset, 11))) pop(create2(0, 0, 30, add(offset, 12))) pop(create2(0, 0, 30, add(offset, 13))) pop(create2(0, 0, 30, add(offset, 14))) pop(create2(0, 0, 30, add(offset, 15))) pop(create2(0, 0, 30, add(offset, 16))) pop(create2(0, 0, 30, add(offset, 17))) pop(create2(0, 0, 30, add(offset, 18))) pop(create2(0, 0, 30, add(offset, 19))) pop(create2(0, 0, 30, add(offset, 20))) pop(create2(0, 0, 30, add(offset, 21))) pop(create2(0, 0, 30, add(offset, 22))) pop(create2(0, 0, 30, add(offset, 23))) pop(create2(0, 0, 30, add(offset, 24))) pop(create2(0, 0, 30, add(offset, 25))) pop(create2(0, 0, 30, add(offset, 26))) pop(create2(0, 0, 30, add(offset, 27))) pop(create2(0, 0, 30, add(offset, 28))) pop(create2(0, 0, 30, add(offset, 29))) pop(create2(0, 0, 30, add(offset, 30))) pop(create2(0, 0, 30, add(offset, 31))) offset := add(offset, 32) } for {let i := and(value, 0x1F)} i {i := sub(i, 1)} { pop(create2(0, 0, 30, offset)) offset := add(offset, 1) } } _mint(msg.sender, value); totalMinted = offset; } function computeAddress2(uint256 salt) public view returns (address) { bytes32 _data = keccak256( abi.encodePacked(bytes1(0xff), address(this), salt, bytes32(0x3c1644c68e5d6cb380c36d1bf847fdbc0c7ac28030025a2fc5e63cce23c16348)) ); return address(uint256(_data)); } function _destroyChildren(uint256 value) internal { uint256 _totalBurned = totalBurned; for (uint256 i = 0; i < value; i++) { computeAddress2(_totalBurned + i).call(""); } totalBurned = _totalBurned + value; } function free(uint256 value) public returns (uint256) { _burn(msg.sender, value); _destroyChildren(value); return value; } function freeUpTo(uint256 value) public returns (uint256) { return free(Math.min(value, balanceOf(msg.sender))); } function freeFrom(address from, uint256 value) public returns (uint256) { _burnFrom(from, value); _destroyChildren(value); return value; } function freeFromUpTo(address from, uint256 value) public returns (uint256) { return freeFrom(from, Math.min(Math.min(value, balanceOf(from)), allowance(from, msg.sender))); } }
File 9 of 15: OperationImpl
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental ABIEncoderV2; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/protocol/lib/Require.sol /** * @title Require * @author dYdX * * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require() */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringify( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } // File: contracts/protocol/lib/Math.sol /** * @title Math * @author dYdX * * Library for non-standard Math functions */ library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // File: contracts/protocol/lib/Types.sol /** * @title Types * @author dYdX * * Library for interacting with the basic structs used in Solo */ library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } // File: contracts/protocol/lib/Account.sol /** * @title Account * @author dYdX * * Library of structs and functions that represent an account */ library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } // File: contracts/protocol/interfaces/IAutoTrader.sol /** * @title IAutoTrader * @author dYdX * * Interface that Auto-Traders for Solo must implement in order to approve trades. */ contract IAutoTrader { // ============ Public Functions ============ /** * Allows traders to make trades approved by this smart contract. The active trader's account is * the takerAccount and the passive account (for which this contract approves trades * on-behalf-of) is the makerAccount. * * @param inputMarketId The market for which the trader specified the original amount * @param outputMarketId The market for which the trader wants the resulting amount specified * @param makerAccount The account for which this contract is making trades * @param takerAccount The account requesting the trade * @param oldInputPar The old principal amount for the makerAccount for the inputMarketId * @param newInputPar The new principal amount for the makerAccount for the inputMarketId * @param inputWei The change in token amount for the makerAccount for the inputMarketId * @param data Arbitrary data passed in by the trader * @return The AssetAmount for the makerAccount for the outputMarketId */ function getTradeCost( uint256 inputMarketId, uint256 outputMarketId, Account.Info memory makerAccount, Account.Info memory takerAccount, Types.Par memory oldInputPar, Types.Par memory newInputPar, Types.Wei memory inputWei, bytes memory data ) public returns (Types.AssetAmount memory); } // File: contracts/protocol/interfaces/ICallee.sol /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ contract ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) public; } // File: contracts/protocol/lib/Actions.sol /** * @title Actions * @author dYdX * * Library that defines and parses valid Actions */ library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } // File: contracts/protocol/lib/Monetary.sol /** * @title Monetary * @author dYdX * * Library for types involving money */ library Monetary { /* * The price of a base-unit of an asset. */ struct Price { uint256 value; } /* * Total value of an some amount of an asset. Equal to (price * amount). */ struct Value { uint256 value; } } // File: contracts/protocol/lib/Cache.sol /** * @title Cache * @author dYdX * * Library for caching information about markets */ library Cache { using Cache for MarketCache; using Storage for Storage.State; // ============ Structs ============ struct MarketInfo { bool isClosing; uint128 borrowPar; Monetary.Price price; } struct MarketCache { MarketInfo[] markets; } // ============ Setter Functions ============ /** * Initialize an empty cache for some given number of total markets. */ function create( uint256 numMarkets ) internal pure returns (MarketCache memory) { return MarketCache({ markets: new MarketInfo[](numMarkets) }); } /** * Add market information (price and total borrowed par if the market is closing) to the cache. * Return true if the market information did not previously exist in the cache. */ function addMarket( MarketCache memory cache, Storage.State storage state, uint256 marketId ) internal view returns (bool) { if (cache.hasMarket(marketId)) { return false; } cache.markets[marketId].price = state.fetchPrice(marketId); if (state.markets[marketId].isClosing) { cache.markets[marketId].isClosing = true; cache.markets[marketId].borrowPar = state.getTotalPar(marketId).borrow; } return true; } // ============ Getter Functions ============ function getNumMarkets( MarketCache memory cache ) internal pure returns (uint256) { return cache.markets.length; } function hasMarket( MarketCache memory cache, uint256 marketId ) internal pure returns (bool) { return cache.markets[marketId].price.value != 0; } function getIsClosing( MarketCache memory cache, uint256 marketId ) internal pure returns (bool) { return cache.markets[marketId].isClosing; } function getPrice( MarketCache memory cache, uint256 marketId ) internal pure returns (Monetary.Price memory) { return cache.markets[marketId].price; } function getBorrowPar( MarketCache memory cache, uint256 marketId ) internal pure returns (uint128) { return cache.markets[marketId].borrowPar; } } // File: contracts/protocol/lib/Decimal.sol /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Functions ============ function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function onePlus( D256 memory d ) internal pure returns (D256 memory) { return D256({ value: d.value.add(BASE) }); } function mul( uint256 target, D256 memory d ) internal pure returns (uint256) { return Math.getPartial(target, d.value, BASE); } function div( uint256 target, D256 memory d ) internal pure returns (uint256) { return Math.getPartial(target, BASE, d.value); } } // File: contracts/protocol/lib/Time.sol /** * @title Time * @author dYdX * * Library for dealing with time, assuming timestamps fit within 32 bits (valid until year 2106) */ library Time { // ============ Library Functions ============ function currentTime() internal view returns (uint32) { return Math.to32(block.timestamp); } } // File: contracts/protocol/lib/Interest.sol /** * @title Interest * @author dYdX * * Library for managing the interest rate and interest indexes of Solo */ library Interest { using Math for uint256; using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Interest"; uint64 constant BASE = 10**18; // ============ Structs ============ struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } // ============ Library Functions ============ /** * Get a new market Index based on the old index and market interest rate. * Calculate interest for borrowers by using the formula rate * time. Approximates * continuously-compounded interest when called frequently, but is much more * gas-efficient to calculate. For suppliers, the interest rate is adjusted by the earningsRate, * then prorated the across all suppliers. * * @param index The old index for a market * @param rate The current interest rate of the market * @param totalPar The total supply and borrow par values of the market * @param earningsRate The portion of the interest that is forwarded to the suppliers * @return The updated index for a market */ function calculateNewIndex( Index memory index, Rate memory rate, Types.TotalPar memory totalPar, Decimal.D256 memory earningsRate ) internal view returns (Index memory) { ( Types.Wei memory supplyWei, Types.Wei memory borrowWei ) = totalParToWei(totalPar, index); // get interest increase for borrowers uint32 currentTime = Time.currentTime(); uint256 borrowInterest = rate.value.mul(uint256(currentTime).sub(index.lastUpdate)); // get interest increase for suppliers uint256 supplyInterest; if (Types.isZero(supplyWei)) { supplyInterest = 0; } else { supplyInterest = Decimal.mul(borrowInterest, earningsRate); if (borrowWei.value < supplyWei.value) { supplyInterest = Math.getPartial(supplyInterest, borrowWei.value, supplyWei.value); } } assert(supplyInterest <= borrowInterest); return Index({ borrow: Math.getPartial(index.borrow, borrowInterest, BASE).add(index.borrow).to96(), supply: Math.getPartial(index.supply, supplyInterest, BASE).add(index.supply).to96(), lastUpdate: currentTime }); } function newIndex() internal view returns (Index memory) { return Index({ borrow: BASE, supply: BASE, lastUpdate: Time.currentTime() }); } /* * Convert a principal amount to a token amount given an index. */ function parToWei( Types.Par memory input, Index memory index ) internal pure returns (Types.Wei memory) { uint256 inputValue = uint256(input.value); if (input.sign) { return Types.Wei({ sign: true, value: inputValue.getPartial(index.supply, BASE) }); } else { return Types.Wei({ sign: false, value: inputValue.getPartialRoundUp(index.borrow, BASE) }); } } /* * Convert a token amount to a principal amount given an index. */ function weiToPar( Types.Wei memory input, Index memory index ) internal pure returns (Types.Par memory) { if (input.sign) { return Types.Par({ sign: true, value: input.value.getPartial(BASE, index.supply).to128() }); } else { return Types.Par({ sign: false, value: input.value.getPartialRoundUp(BASE, index.borrow).to128() }); } } /* * Convert the total supply and borrow principal amounts of a market to total supply and borrow * token amounts. */ function totalParToWei( Types.TotalPar memory totalPar, Index memory index ) internal pure returns (Types.Wei memory, Types.Wei memory) { Types.Par memory supplyPar = Types.Par({ sign: true, value: totalPar.supply }); Types.Par memory borrowPar = Types.Par({ sign: false, value: totalPar.borrow }); Types.Wei memory supplyWei = parToWei(supplyPar, index); Types.Wei memory borrowWei = parToWei(borrowPar, index); return (supplyWei, borrowWei); } } // File: contracts/protocol/interfaces/IErc20.sol /** * @title IErc20 * @author dYdX * * Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so * that we don't automatically revert when calling non-compliant tokens that have no return value for * transfer(), transferFrom(), or approve(). */ interface IErc20 { event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); function totalSupply( ) external view returns (uint256); function balanceOf( address who ) external view returns (uint256); function allowance( address owner, address spender ) external view returns (uint256); function transfer( address to, uint256 value ) external; function transferFrom( address from, address to, uint256 value ) external; function approve( address spender, uint256 value ) external; function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // File: contracts/protocol/lib/Token.sol /** * @title Token * @author dYdX * * This library contains basic functions for interacting with ERC20 tokens. Modified to work with * tokens that don't adhere strictly to the ERC20 standard (for example tokens that don't return a * boolean value on success). */ library Token { // ============ Constants ============ bytes32 constant FILE = "Token"; // ============ Library Functions ============ function balanceOf( address token, address owner ) internal view returns (uint256) { return IErc20(token).balanceOf(owner); } function allowance( address token, address owner, address spender ) internal view returns (uint256) { return IErc20(token).allowance(owner, spender); } function approve( address token, address spender, uint256 amount ) internal { IErc20(token).approve(spender, amount); Require.that( checkSuccess(), FILE, "Approve failed" ); } function approveMax( address token, address spender ) internal { approve( token, spender, uint256(-1) ); } function transfer( address token, address to, uint256 amount ) internal { if (amount == 0 || to == address(this)) { return; } IErc20(token).transfer(to, amount); Require.that( checkSuccess(), FILE, "Transfer failed" ); } function transferFrom( address token, address from, address to, uint256 amount ) internal { if (amount == 0 || to == from) { return; } IErc20(token).transferFrom(from, to, amount); Require.that( checkSuccess(), FILE, "TransferFrom failed" ); } // ============ Private Functions ============ /** * Check the return value of the previous function up to 32 bytes. Return true if the previous * function returned 0 bytes or 32 bytes that are not all-zero. */ function checkSuccess( ) private pure returns (bool) { uint256 returnValue = 0; /* solium-disable-next-line security/no-inline-assembly */ assembly { // check number of bytes returned from last function call switch returndatasize // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned: check if non-zero case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: don't mark as success default { } } return returnValue != 0; } } // File: contracts/protocol/interfaces/IInterestSetter.sol /** * @title IInterestSetter * @author dYdX * * Interface that Interest Setters for Solo must implement in order to report interest rates. */ interface IInterestSetter { // ============ Public Functions ============ /** * Get the interest rate of a token given some borrowed and supplied amounts * * @param token The address of the ERC20 token for the market * @param borrowWei The total borrowed token amount for the market * @param supplyWei The total supplied token amount for the market * @return The interest rate per second */ function getInterestRate( address token, uint256 borrowWei, uint256 supplyWei ) external view returns (Interest.Rate memory); } // File: contracts/protocol/interfaces/IPriceOracle.sol /** * @title IPriceOracle * @author dYdX * * Interface that Price Oracles for Solo must implement in order to report prices. */ contract IPriceOracle { // ============ Constants ============ uint256 public constant ONE_DOLLAR = 10 ** 36; // ============ Public Functions ============ /** * Get the price of a token * * @param token The ERC20 token address of the market * @return The USD price of a base unit of the token, then multiplied by 10^36. * So a USD-stable coin with 18 decimal places would return 10^18. * This is the price of the base unit rather than the price of a "human-readable" * token amount. Every ERC20 may have a different number of decimals. */ function getPrice( address token ) public view returns (Monetary.Price memory); } // File: contracts/protocol/lib/Storage.sol /** * @title Storage * @author dYdX * * Functions for reading, writing, and verifying state in Solo */ library Storage { using Cache for Cache.MarketCache; using Storage for Storage.State; using Math for uint256; using Types for Types.Par; using Types for Types.Wei; using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Storage"; // ============ Structs ============ // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market IPriceOracle priceOracle; // Contract address of the interest setter for this market IInterestSetter interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping (uint256 => Market) markets; // owner => account number => Account mapping (address => mapping (uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping (address => mapping (address => bool)) operators; // Addresses that can control all users accounts mapping (address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } // ============ Functions ============ function getToken( Storage.State storage state, uint256 marketId ) internal view returns (address) { return state.markets[marketId].token; } function getTotalPar( Storage.State storage state, uint256 marketId ) internal view returns (Types.TotalPar memory) { return state.markets[marketId].totalPar; } function getIndex( Storage.State storage state, uint256 marketId ) internal view returns (Interest.Index memory) { return state.markets[marketId].index; } function getNumExcessTokens( Storage.State storage state, uint256 marketId ) internal view returns (Types.Wei memory) { Interest.Index memory index = state.getIndex(marketId); Types.TotalPar memory totalPar = state.getTotalPar(marketId); address token = state.getToken(marketId); Types.Wei memory balanceWei = Types.Wei({ sign: true, value: Token.balanceOf(token, address(this)) }); ( Types.Wei memory supplyWei, Types.Wei memory borrowWei ) = Interest.totalParToWei(totalPar, index); // borrowWei is negative, so subtracting it makes the value more positive return balanceWei.sub(borrowWei).sub(supplyWei); } function getStatus( Storage.State storage state, Account.Info memory account ) internal view returns (Account.Status) { return state.accounts[account.owner][account.number].status; } function getPar( Storage.State storage state, Account.Info memory account, uint256 marketId ) internal view returns (Types.Par memory) { return state.accounts[account.owner][account.number].balances[marketId]; } function getWei( Storage.State storage state, Account.Info memory account, uint256 marketId ) internal view returns (Types.Wei memory) { Types.Par memory par = state.getPar(account, marketId); if (par.isZero()) { return Types.zeroWei(); } Interest.Index memory index = state.getIndex(marketId); return Interest.parToWei(par, index); } function getLiquidationSpreadForPair( Storage.State storage state, uint256 heldMarketId, uint256 owedMarketId ) internal view returns (Decimal.D256 memory) { uint256 result = state.riskParams.liquidationSpread.value; result = Decimal.mul(result, Decimal.onePlus(state.markets[heldMarketId].spreadPremium)); result = Decimal.mul(result, Decimal.onePlus(state.markets[owedMarketId].spreadPremium)); return Decimal.D256({ value: result }); } function fetchNewIndex( Storage.State storage state, uint256 marketId, Interest.Index memory index ) internal view returns (Interest.Index memory) { Interest.Rate memory rate = state.fetchInterestRate(marketId, index); return Interest.calculateNewIndex( index, rate, state.getTotalPar(marketId), state.riskParams.earningsRate ); } function fetchInterestRate( Storage.State storage state, uint256 marketId, Interest.Index memory index ) internal view returns (Interest.Rate memory) { Types.TotalPar memory totalPar = state.getTotalPar(marketId); ( Types.Wei memory supplyWei, Types.Wei memory borrowWei ) = Interest.totalParToWei(totalPar, index); Interest.Rate memory rate = state.markets[marketId].interestSetter.getInterestRate( state.getToken(marketId), borrowWei.value, supplyWei.value ); return rate; } function fetchPrice( Storage.State storage state, uint256 marketId ) internal view returns (Monetary.Price memory) { IPriceOracle oracle = IPriceOracle(state.markets[marketId].priceOracle); Monetary.Price memory price = oracle.getPrice(state.getToken(marketId)); Require.that( price.value != 0, FILE, "Price cannot be zero", marketId ); return price; } function getAccountValues( Storage.State storage state, Account.Info memory account, Cache.MarketCache memory cache, bool adjustForLiquidity ) internal view returns (Monetary.Value memory, Monetary.Value memory) { Monetary.Value memory supplyValue; Monetary.Value memory borrowValue; uint256 numMarkets = cache.getNumMarkets(); for (uint256 m = 0; m < numMarkets; m++) { if (!cache.hasMarket(m)) { continue; } Types.Wei memory userWei = state.getWei(account, m); if (userWei.isZero()) { continue; } uint256 assetValue = userWei.value.mul(cache.getPrice(m).value); Decimal.D256 memory adjust = Decimal.one(); if (adjustForLiquidity) { adjust = Decimal.onePlus(state.markets[m].marginPremium); } if (userWei.sign) { supplyValue.value = supplyValue.value.add(Decimal.div(assetValue, adjust)); } else { borrowValue.value = borrowValue.value.add(Decimal.mul(assetValue, adjust)); } } return (supplyValue, borrowValue); } function isCollateralized( Storage.State storage state, Account.Info memory account, Cache.MarketCache memory cache, bool requireMinBorrow ) internal view returns (bool) { // get account values (adjusted for liquidity) ( Monetary.Value memory supplyValue, Monetary.Value memory borrowValue ) = state.getAccountValues(account, cache, /* adjustForLiquidity = */ true); if (borrowValue.value == 0) { return true; } if (requireMinBorrow) { Require.that( borrowValue.value >= state.riskParams.minBorrowedValue.value, FILE, "Borrow value too low", account.owner, account.number, borrowValue.value ); } uint256 requiredMargin = Decimal.mul(borrowValue.value, state.riskParams.marginRatio); return supplyValue.value >= borrowValue.value.add(requiredMargin); } function isGlobalOperator( Storage.State storage state, address operator ) internal view returns (bool) { return state.globalOperators[operator]; } function isLocalOperator( Storage.State storage state, address owner, address operator ) internal view returns (bool) { return state.operators[owner][operator]; } function requireIsOperator( Storage.State storage state, Account.Info memory account, address operator ) internal view { bool isValidOperator = operator == account.owner || state.isGlobalOperator(operator) || state.isLocalOperator(account.owner, operator); Require.that( isValidOperator, FILE, "Unpermissioned operator", operator ); } /** * Determine and set an account's balance based on the intended balance change. Return the * equivalent amount in wei */ function getNewParAndDeltaWei( Storage.State storage state, Account.Info memory account, uint256 marketId, Types.AssetAmount memory amount ) internal view returns (Types.Par memory, Types.Wei memory) { Types.Par memory oldPar = state.getPar(account, marketId); if (amount.value == 0 && amount.ref == Types.AssetReference.Delta) { return (oldPar, Types.zeroWei()); } Interest.Index memory index = state.getIndex(marketId); Types.Wei memory oldWei = Interest.parToWei(oldPar, index); Types.Par memory newPar; Types.Wei memory deltaWei; if (amount.denomination == Types.AssetDenomination.Wei) { deltaWei = Types.Wei({ sign: amount.sign, value: amount.value }); if (amount.ref == Types.AssetReference.Target) { deltaWei = deltaWei.sub(oldWei); } newPar = Interest.weiToPar(oldWei.add(deltaWei), index); } else { // AssetDenomination.Par newPar = Types.Par({ sign: amount.sign, value: amount.value.to128() }); if (amount.ref == Types.AssetReference.Delta) { newPar = oldPar.add(newPar); } deltaWei = Interest.parToWei(newPar, index).sub(oldWei); } return (newPar, deltaWei); } function getNewParAndDeltaWeiForLiquidation( Storage.State storage state, Account.Info memory account, uint256 marketId, Types.AssetAmount memory amount ) internal view returns (Types.Par memory, Types.Wei memory) { Types.Par memory oldPar = state.getPar(account, marketId); Require.that( !oldPar.isPositive(), FILE, "Owed balance cannot be positive", account.owner, account.number, marketId ); ( Types.Par memory newPar, Types.Wei memory deltaWei ) = state.getNewParAndDeltaWei( account, marketId, amount ); // if attempting to over-repay the owed asset, bound it by the maximum if (newPar.isPositive()) { newPar = Types.zeroPar(); deltaWei = state.getWei(account, marketId).negative(); } Require.that( !deltaWei.isNegative() && oldPar.value >= newPar.value, FILE, "Owed balance cannot increase", account.owner, account.number, marketId ); // if not paying back enough wei to repay any par, then bound wei to zero if (oldPar.equals(newPar)) { deltaWei = Types.zeroWei(); } return (newPar, deltaWei); } function isVaporizable( Storage.State storage state, Account.Info memory account, Cache.MarketCache memory cache ) internal view returns (bool) { bool hasNegative = false; uint256 numMarkets = cache.getNumMarkets(); for (uint256 m = 0; m < numMarkets; m++) { if (!cache.hasMarket(m)) { continue; } Types.Par memory par = state.getPar(account, m); if (par.isZero()) { continue; } else if (par.sign) { return false; } else { hasNegative = true; } } return hasNegative; } // =============== Setter Functions =============== function updateIndex( Storage.State storage state, uint256 marketId ) internal returns (Interest.Index memory) { Interest.Index memory index = state.getIndex(marketId); if (index.lastUpdate == Time.currentTime()) { return index; } return state.markets[marketId].index = state.fetchNewIndex(marketId, index); } function setStatus( Storage.State storage state, Account.Info memory account, Account.Status status ) internal { state.accounts[account.owner][account.number].status = status; } function setPar( Storage.State storage state, Account.Info memory account, uint256 marketId, Types.Par memory newPar ) internal { Types.Par memory oldPar = state.getPar(account, marketId); if (Types.equals(oldPar, newPar)) { return; } // updateTotalPar Types.TotalPar memory totalPar = state.getTotalPar(marketId); // roll-back oldPar if (oldPar.sign) { totalPar.supply = uint256(totalPar.supply).sub(oldPar.value).to128(); } else { totalPar.borrow = uint256(totalPar.borrow).sub(oldPar.value).to128(); } // roll-forward newPar if (newPar.sign) { totalPar.supply = uint256(totalPar.supply).add(newPar.value).to128(); } else { totalPar.borrow = uint256(totalPar.borrow).add(newPar.value).to128(); } state.markets[marketId].totalPar = totalPar; state.accounts[account.owner][account.number].balances[marketId] = newPar; } /** * Determine and set an account's balance based on a change in wei */ function setParFromDeltaWei( Storage.State storage state, Account.Info memory account, uint256 marketId, Types.Wei memory deltaWei ) internal { if (deltaWei.isZero()) { return; } Interest.Index memory index = state.getIndex(marketId); Types.Wei memory oldWei = state.getWei(account, marketId); Types.Wei memory newWei = oldWei.add(deltaWei); Types.Par memory newPar = Interest.weiToPar(newWei, index); state.setPar( account, marketId, newPar ); } } // File: contracts/protocol/lib/Events.sol /** * @title Events * @author dYdX * * Library to parse and emit logs from which the state of all accounts and indexes can be followed */ library Events { using Types for Types.Wei; using Storage for Storage.State; // ============ Events ============ event LogIndexUpdate( uint256 indexed market, Interest.Index index ); event LogOperation( address sender ); event LogDeposit( address indexed accountOwner, uint256 accountNumber, uint256 market, BalanceUpdate update, address from ); event LogWithdraw( address indexed accountOwner, uint256 accountNumber, uint256 market, BalanceUpdate update, address to ); event LogTransfer( address indexed accountOneOwner, uint256 accountOneNumber, address indexed accountTwoOwner, uint256 accountTwoNumber, uint256 market, BalanceUpdate updateOne, BalanceUpdate updateTwo ); event LogBuy( address indexed accountOwner, uint256 accountNumber, uint256 takerMarket, uint256 makerMarket, BalanceUpdate takerUpdate, BalanceUpdate makerUpdate, address exchangeWrapper ); event LogSell( address indexed accountOwner, uint256 accountNumber, uint256 takerMarket, uint256 makerMarket, BalanceUpdate takerUpdate, BalanceUpdate makerUpdate, address exchangeWrapper ); event LogTrade( address indexed takerAccountOwner, uint256 takerAccountNumber, address indexed makerAccountOwner, uint256 makerAccountNumber, uint256 inputMarket, uint256 outputMarket, BalanceUpdate takerInputUpdate, BalanceUpdate takerOutputUpdate, BalanceUpdate makerInputUpdate, BalanceUpdate makerOutputUpdate, address autoTrader ); event LogCall( address indexed accountOwner, uint256 accountNumber, address callee ); event LogLiquidate( address indexed solidAccountOwner, uint256 solidAccountNumber, address indexed liquidAccountOwner, uint256 liquidAccountNumber, uint256 heldMarket, uint256 owedMarket, BalanceUpdate solidHeldUpdate, BalanceUpdate solidOwedUpdate, BalanceUpdate liquidHeldUpdate, BalanceUpdate liquidOwedUpdate ); event LogVaporize( address indexed solidAccountOwner, uint256 solidAccountNumber, address indexed vaporAccountOwner, uint256 vaporAccountNumber, uint256 heldMarket, uint256 owedMarket, BalanceUpdate solidHeldUpdate, BalanceUpdate solidOwedUpdate, BalanceUpdate vaporOwedUpdate ); // ============ Structs ============ struct BalanceUpdate { Types.Wei deltaWei; Types.Par newPar; } // ============ Internal Functions ============ function logIndexUpdate( uint256 marketId, Interest.Index memory index ) internal { emit LogIndexUpdate( marketId, index ); } function logOperation() internal { emit LogOperation(msg.sender); } function logDeposit( Storage.State storage state, Actions.DepositArgs memory args, Types.Wei memory deltaWei ) internal { emit LogDeposit( args.account.owner, args.account.number, args.market, getBalanceUpdate( state, args.account, args.market, deltaWei ), args.from ); } function logWithdraw( Storage.State storage state, Actions.WithdrawArgs memory args, Types.Wei memory deltaWei ) internal { emit LogWithdraw( args.account.owner, args.account.number, args.market, getBalanceUpdate( state, args.account, args.market, deltaWei ), args.to ); } function logTransfer( Storage.State storage state, Actions.TransferArgs memory args, Types.Wei memory deltaWei ) internal { emit LogTransfer( args.accountOne.owner, args.accountOne.number, args.accountTwo.owner, args.accountTwo.number, args.market, getBalanceUpdate( state, args.accountOne, args.market, deltaWei ), getBalanceUpdate( state, args.accountTwo, args.market, deltaWei.negative() ) ); } function logBuy( Storage.State storage state, Actions.BuyArgs memory args, Types.Wei memory takerWei, Types.Wei memory makerWei ) internal { emit LogBuy( args.account.owner, args.account.number, args.takerMarket, args.makerMarket, getBalanceUpdate( state, args.account, args.takerMarket, takerWei ), getBalanceUpdate( state, args.account, args.makerMarket, makerWei ), args.exchangeWrapper ); } function logSell( Storage.State storage state, Actions.SellArgs memory args, Types.Wei memory takerWei, Types.Wei memory makerWei ) internal { emit LogSell( args.account.owner, args.account.number, args.takerMarket, args.makerMarket, getBalanceUpdate( state, args.account, args.takerMarket, takerWei ), getBalanceUpdate( state, args.account, args.makerMarket, makerWei ), args.exchangeWrapper ); } function logTrade( Storage.State storage state, Actions.TradeArgs memory args, Types.Wei memory inputWei, Types.Wei memory outputWei ) internal { BalanceUpdate[4] memory updates = [ getBalanceUpdate( state, args.takerAccount, args.inputMarket, inputWei.negative() ), getBalanceUpdate( state, args.takerAccount, args.outputMarket, outputWei.negative() ), getBalanceUpdate( state, args.makerAccount, args.inputMarket, inputWei ), getBalanceUpdate( state, args.makerAccount, args.outputMarket, outputWei ) ]; emit LogTrade( args.takerAccount.owner, args.takerAccount.number, args.makerAccount.owner, args.makerAccount.number, args.inputMarket, args.outputMarket, updates[0], updates[1], updates[2], updates[3], args.autoTrader ); } function logCall( Actions.CallArgs memory args ) internal { emit LogCall( args.account.owner, args.account.number, args.callee ); } function logLiquidate( Storage.State storage state, Actions.LiquidateArgs memory args, Types.Wei memory heldWei, Types.Wei memory owedWei ) internal { BalanceUpdate memory solidHeldUpdate = getBalanceUpdate( state, args.solidAccount, args.heldMarket, heldWei.negative() ); BalanceUpdate memory solidOwedUpdate = getBalanceUpdate( state, args.solidAccount, args.owedMarket, owedWei.negative() ); BalanceUpdate memory liquidHeldUpdate = getBalanceUpdate( state, args.liquidAccount, args.heldMarket, heldWei ); BalanceUpdate memory liquidOwedUpdate = getBalanceUpdate( state, args.liquidAccount, args.owedMarket, owedWei ); emit LogLiquidate( args.solidAccount.owner, args.solidAccount.number, args.liquidAccount.owner, args.liquidAccount.number, args.heldMarket, args.owedMarket, solidHeldUpdate, solidOwedUpdate, liquidHeldUpdate, liquidOwedUpdate ); } function logVaporize( Storage.State storage state, Actions.VaporizeArgs memory args, Types.Wei memory heldWei, Types.Wei memory owedWei, Types.Wei memory excessWei ) internal { BalanceUpdate memory solidHeldUpdate = getBalanceUpdate( state, args.solidAccount, args.heldMarket, heldWei.negative() ); BalanceUpdate memory solidOwedUpdate = getBalanceUpdate( state, args.solidAccount, args.owedMarket, owedWei.negative() ); BalanceUpdate memory vaporOwedUpdate = getBalanceUpdate( state, args.vaporAccount, args.owedMarket, owedWei.add(excessWei) ); emit LogVaporize( args.solidAccount.owner, args.solidAccount.number, args.vaporAccount.owner, args.vaporAccount.number, args.heldMarket, args.owedMarket, solidHeldUpdate, solidOwedUpdate, vaporOwedUpdate ); } // ============ Private Functions ============ function getBalanceUpdate( Storage.State storage state, Account.Info memory account, uint256 market, Types.Wei memory deltaWei ) private view returns (BalanceUpdate memory) { return BalanceUpdate({ deltaWei: deltaWei, newPar: state.getPar(account, market) }); } } // File: contracts/protocol/interfaces/IExchangeWrapper.sol /** * @title IExchangeWrapper * @author dYdX * * Interface that Exchange Wrappers for Solo must implement in order to trade ERC20 tokens. */ interface IExchangeWrapper { // ============ Public Functions ============ /** * Exchange some amount of takerToken for makerToken. * * @param tradeOriginator Address of the initiator of the trade (however, this value * cannot always be trusted as it is set at the discretion of the * msg.sender) * @param receiver Address to set allowance on once the trade has completed * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param requestedFillAmount Amount of takerToken being paid * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return The amount of makerToken received */ function exchange( address tradeOriginator, address receiver, address makerToken, address takerToken, uint256 requestedFillAmount, bytes calldata orderData ) external returns (uint256); /** * Get amount of takerToken required to buy a certain amount of makerToken for a given trade. * Should match the takerToken amount used in exchangeForAmount. If the order cannot provide * exactly desiredMakerToken, then it must return the price to buy the minimum amount greater * than desiredMakerToken * * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param desiredMakerToken Amount of makerToken requested * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return Amount of takerToken the needed to complete the exchange */ function getExchangeCost( address makerToken, address takerToken, uint256 desiredMakerToken, bytes calldata orderData ) external view returns (uint256); } // File: contracts/protocol/lib/Exchange.sol /** * @title Exchange * @author dYdX * * Library for transferring tokens and interacting with ExchangeWrappers by using the Wei struct */ library Exchange { using Types for Types.Wei; // ============ Constants ============ bytes32 constant FILE = "Exchange"; // ============ Library Functions ============ function transferOut( address token, address to, Types.Wei memory deltaWei ) internal { Require.that( !deltaWei.isPositive(), FILE, "Cannot transferOut positive", deltaWei.value ); Token.transfer( token, to, deltaWei.value ); } function transferIn( address token, address from, Types.Wei memory deltaWei ) internal { Require.that( !deltaWei.isNegative(), FILE, "Cannot transferIn negative", deltaWei.value ); Token.transferFrom( token, from, address(this), deltaWei.value ); } function getCost( address exchangeWrapper, address supplyToken, address borrowToken, Types.Wei memory desiredAmount, bytes memory orderData ) internal view returns (Types.Wei memory) { Require.that( !desiredAmount.isNegative(), FILE, "Cannot getCost negative", desiredAmount.value ); Types.Wei memory result; result.sign = false; result.value = IExchangeWrapper(exchangeWrapper).getExchangeCost( supplyToken, borrowToken, desiredAmount.value, orderData ); return result; } function exchange( address exchangeWrapper, address accountOwner, address supplyToken, address borrowToken, Types.Wei memory requestedFillAmount, bytes memory orderData ) internal returns (Types.Wei memory) { Require.that( !requestedFillAmount.isPositive(), FILE, "Cannot exchange positive", requestedFillAmount.value ); transferOut(borrowToken, exchangeWrapper, requestedFillAmount); Types.Wei memory result; result.sign = true; result.value = IExchangeWrapper(exchangeWrapper).exchange( accountOwner, address(this), supplyToken, borrowToken, requestedFillAmount.value, orderData ); transferIn(supplyToken, exchangeWrapper, result); return result; } } // File: contracts/protocol/impl/OperationImpl.sol /** * @title OperationImpl * @author dYdX * * Logic for processing actions */ library OperationImpl { using Cache for Cache.MarketCache; using SafeMath for uint256; using Storage for Storage.State; using Types for Types.Par; using Types for Types.Wei; // ============ Constants ============ bytes32 constant FILE = "OperationImpl"; // ============ Public Functions ============ function operate( Storage.State storage state, Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public { Events.logOperation(); _verifyInputs(accounts, actions); ( bool[] memory primaryAccounts, Cache.MarketCache memory cache ) = _runPreprocessing( state, accounts, actions ); _runActions( state, accounts, actions, cache ); _verifyFinalState( state, accounts, primaryAccounts, cache ); } // ============ Helper Functions ============ function _verifyInputs( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) private pure { Require.that( actions.length != 0, FILE, "Cannot have zero actions" ); Require.that( accounts.length != 0, FILE, "Cannot have zero accounts" ); for (uint256 a = 0; a < accounts.length; a++) { for (uint256 b = a + 1; b < accounts.length; b++) { Require.that( !Account.equals(accounts[a], accounts[b]), FILE, "Cannot duplicate accounts", a, b ); } } } function _runPreprocessing( Storage.State storage state, Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) private returns ( bool[] memory, Cache.MarketCache memory ) { uint256 numMarkets = state.numMarkets; bool[] memory primaryAccounts = new bool[](accounts.length); Cache.MarketCache memory cache = Cache.create(numMarkets); // keep track of primary accounts and indexes that need updating for (uint256 i = 0; i < actions.length; i++) { Actions.ActionArgs memory arg = actions[i]; Actions.ActionType actionType = arg.actionType; Actions.MarketLayout marketLayout = Actions.getMarketLayout(actionType); Actions.AccountLayout accountLayout = Actions.getAccountLayout(actionType); // parse out primary accounts if (accountLayout != Actions.AccountLayout.OnePrimary) { Require.that( arg.accountId != arg.otherAccountId, FILE, "Duplicate accounts in action", i ); if (accountLayout == Actions.AccountLayout.TwoPrimary) { primaryAccounts[arg.otherAccountId] = true; } else { assert(accountLayout == Actions.AccountLayout.PrimaryAndSecondary); Require.that( !primaryAccounts[arg.otherAccountId], FILE, "Requires non-primary account", arg.otherAccountId ); } } primaryAccounts[arg.accountId] = true; // keep track of indexes to update if (marketLayout == Actions.MarketLayout.OneMarket) { _updateMarket(state, cache, arg.primaryMarketId); } else if (marketLayout == Actions.MarketLayout.TwoMarkets) { Require.that( arg.primaryMarketId != arg.secondaryMarketId, FILE, "Duplicate markets in action", i ); _updateMarket(state, cache, arg.primaryMarketId); _updateMarket(state, cache, arg.secondaryMarketId); } else { assert(marketLayout == Actions.MarketLayout.ZeroMarkets); } } // get any other markets for which an account has a balance for (uint256 m = 0; m < numMarkets; m++) { if (cache.hasMarket(m)) { continue; } for (uint256 a = 0; a < accounts.length; a++) { if (!state.getPar(accounts[a], m).isZero()) { _updateMarket(state, cache, m); break; } } } return (primaryAccounts, cache); } function _updateMarket( Storage.State storage state, Cache.MarketCache memory cache, uint256 marketId ) private { bool updated = cache.addMarket(state, marketId); if (updated) { Events.logIndexUpdate(marketId, state.updateIndex(marketId)); } } function _runActions( Storage.State storage state, Account.Info[] memory accounts, Actions.ActionArgs[] memory actions, Cache.MarketCache memory cache ) private { for (uint256 i = 0; i < actions.length; i++) { Actions.ActionArgs memory action = actions[i]; Actions.ActionType actionType = action.actionType; if (actionType == Actions.ActionType.Deposit) { _deposit(state, Actions.parseDepositArgs(accounts, action)); } else if (actionType == Actions.ActionType.Withdraw) { _withdraw(state, Actions.parseWithdrawArgs(accounts, action)); } else if (actionType == Actions.ActionType.Transfer) { _transfer(state, Actions.parseTransferArgs(accounts, action)); } else if (actionType == Actions.ActionType.Buy) { _buy(state, Actions.parseBuyArgs(accounts, action)); } else if (actionType == Actions.ActionType.Sell) { _sell(state, Actions.parseSellArgs(accounts, action)); } else if (actionType == Actions.ActionType.Trade) { _trade(state, Actions.parseTradeArgs(accounts, action)); } else if (actionType == Actions.ActionType.Liquidate) { _liquidate(state, Actions.parseLiquidateArgs(accounts, action), cache); } else if (actionType == Actions.ActionType.Vaporize) { _vaporize(state, Actions.parseVaporizeArgs(accounts, action), cache); } else { assert(actionType == Actions.ActionType.Call); _call(state, Actions.parseCallArgs(accounts, action)); } } } function _verifyFinalState( Storage.State storage state, Account.Info[] memory accounts, bool[] memory primaryAccounts, Cache.MarketCache memory cache ) private { // verify no increase in borrowPar for closing markets uint256 numMarkets = cache.getNumMarkets(); for (uint256 m = 0; m < numMarkets; m++) { if (cache.getIsClosing(m)) { Require.that( state.getTotalPar(m).borrow <= cache.getBorrowPar(m), FILE, "Market is closing", m ); } } // verify account collateralization for (uint256 a = 0; a < accounts.length; a++) { Account.Info memory account = accounts[a]; // validate minBorrowedValue bool collateralized = state.isCollateralized(account, cache, true); // don't check collateralization for non-primary accounts if (!primaryAccounts[a]) { continue; } // check collateralization for primary accounts Require.that( collateralized, FILE, "Undercollateralized account", account.owner, account.number ); // ensure status is normal for primary accounts if (state.getStatus(account) != Account.Status.Normal) { state.setStatus(account, Account.Status.Normal); } } } // ============ Action Functions ============ function _deposit( Storage.State storage state, Actions.DepositArgs memory args ) private { state.requireIsOperator(args.account, msg.sender); Require.that( args.from == msg.sender || args.from == args.account.owner, FILE, "Invalid deposit source", args.from ); ( Types.Par memory newPar, Types.Wei memory deltaWei ) = state.getNewParAndDeltaWei( args.account, args.market, args.amount ); state.setPar( args.account, args.market, newPar ); // requires a positive deltaWei Exchange.transferIn( state.getToken(args.market), args.from, deltaWei ); Events.logDeposit( state, args, deltaWei ); } function _withdraw( Storage.State storage state, Actions.WithdrawArgs memory args ) private { state.requireIsOperator(args.account, msg.sender); ( Types.Par memory newPar, Types.Wei memory deltaWei ) = state.getNewParAndDeltaWei( args.account, args.market, args.amount ); state.setPar( args.account, args.market, newPar ); // requires a negative deltaWei Exchange.transferOut( state.getToken(args.market), args.to, deltaWei ); Events.logWithdraw( state, args, deltaWei ); } function _transfer( Storage.State storage state, Actions.TransferArgs memory args ) private { state.requireIsOperator(args.accountOne, msg.sender); state.requireIsOperator(args.accountTwo, msg.sender); ( Types.Par memory newPar, Types.Wei memory deltaWei ) = state.getNewParAndDeltaWei( args.accountOne, args.market, args.amount ); state.setPar( args.accountOne, args.market, newPar ); state.setParFromDeltaWei( args.accountTwo, args.market, deltaWei.negative() ); Events.logTransfer( state, args, deltaWei ); } function _buy( Storage.State storage state, Actions.BuyArgs memory args ) private { state.requireIsOperator(args.account, msg.sender); address takerToken = state.getToken(args.takerMarket); address makerToken = state.getToken(args.makerMarket); ( Types.Par memory makerPar, Types.Wei memory makerWei ) = state.getNewParAndDeltaWei( args.account, args.makerMarket, args.amount ); Types.Wei memory takerWei = Exchange.getCost( args.exchangeWrapper, makerToken, takerToken, makerWei, args.orderData ); Types.Wei memory tokensReceived = Exchange.exchange( args.exchangeWrapper, args.account.owner, makerToken, takerToken, takerWei, args.orderData ); Require.that( tokensReceived.value >= makerWei.value, FILE, "Buy amount less than promised", tokensReceived.value, makerWei.value ); state.setPar( args.account, args.makerMarket, makerPar ); state.setParFromDeltaWei( args.account, args.takerMarket, takerWei ); Events.logBuy( state, args, takerWei, makerWei ); } function _sell( Storage.State storage state, Actions.SellArgs memory args ) private { state.requireIsOperator(args.account, msg.sender); address takerToken = state.getToken(args.takerMarket); address makerToken = state.getToken(args.makerMarket); ( Types.Par memory takerPar, Types.Wei memory takerWei ) = state.getNewParAndDeltaWei( args.account, args.takerMarket, args.amount ); Types.Wei memory makerWei = Exchange.exchange( args.exchangeWrapper, args.account.owner, makerToken, takerToken, takerWei, args.orderData ); state.setPar( args.account, args.takerMarket, takerPar ); state.setParFromDeltaWei( args.account, args.makerMarket, makerWei ); Events.logSell( state, args, takerWei, makerWei ); } function _trade( Storage.State storage state, Actions.TradeArgs memory args ) private { state.requireIsOperator(args.takerAccount, msg.sender); state.requireIsOperator(args.makerAccount, args.autoTrader); Types.Par memory oldInputPar = state.getPar( args.makerAccount, args.inputMarket ); ( Types.Par memory newInputPar, Types.Wei memory inputWei ) = state.getNewParAndDeltaWei( args.makerAccount, args.inputMarket, args.amount ); Types.AssetAmount memory outputAmount = IAutoTrader(args.autoTrader).getTradeCost( args.inputMarket, args.outputMarket, args.makerAccount, args.takerAccount, oldInputPar, newInputPar, inputWei, args.tradeData ); ( Types.Par memory newOutputPar, Types.Wei memory outputWei ) = state.getNewParAndDeltaWei( args.makerAccount, args.outputMarket, outputAmount ); Require.that( outputWei.isZero() || inputWei.isZero() || outputWei.sign != inputWei.sign, FILE, "Trades cannot be one-sided" ); // set the balance for the maker state.setPar( args.makerAccount, args.inputMarket, newInputPar ); state.setPar( args.makerAccount, args.outputMarket, newOutputPar ); // set the balance for the taker state.setParFromDeltaWei( args.takerAccount, args.inputMarket, inputWei.negative() ); state.setParFromDeltaWei( args.takerAccount, args.outputMarket, outputWei.negative() ); Events.logTrade( state, args, inputWei, outputWei ); } function _liquidate( Storage.State storage state, Actions.LiquidateArgs memory args, Cache.MarketCache memory cache ) private { state.requireIsOperator(args.solidAccount, msg.sender); // verify liquidatable if (Account.Status.Liquid != state.getStatus(args.liquidAccount)) { Require.that( !state.isCollateralized(args.liquidAccount, cache, /* requireMinBorrow = */ false), FILE, "Unliquidatable account", args.liquidAccount.owner, args.liquidAccount.number ); state.setStatus(args.liquidAccount, Account.Status.Liquid); } Types.Wei memory maxHeldWei = state.getWei( args.liquidAccount, args.heldMarket ); Require.that( !maxHeldWei.isNegative(), FILE, "Collateral cannot be negative", args.liquidAccount.owner, args.liquidAccount.number, args.heldMarket ); ( Types.Par memory owedPar, Types.Wei memory owedWei ) = state.getNewParAndDeltaWeiForLiquidation( args.liquidAccount, args.owedMarket, args.amount ); ( Monetary.Price memory heldPrice, Monetary.Price memory owedPrice ) = _getLiquidationPrices( state, cache, args.heldMarket, args.owedMarket ); Types.Wei memory heldWei = _owedWeiToHeldWei(owedWei, heldPrice, owedPrice); // if attempting to over-borrow the held asset, bound it by the maximum if (heldWei.value > maxHeldWei.value) { heldWei = maxHeldWei.negative(); owedWei = _heldWeiToOwedWei(heldWei, heldPrice, owedPrice); state.setPar( args.liquidAccount, args.heldMarket, Types.zeroPar() ); state.setParFromDeltaWei( args.liquidAccount, args.owedMarket, owedWei ); } else { state.setPar( args.liquidAccount, args.owedMarket, owedPar ); state.setParFromDeltaWei( args.liquidAccount, args.heldMarket, heldWei ); } // set the balances for the solid account state.setParFromDeltaWei( args.solidAccount, args.owedMarket, owedWei.negative() ); state.setParFromDeltaWei( args.solidAccount, args.heldMarket, heldWei.negative() ); Events.logLiquidate( state, args, heldWei, owedWei ); } function _vaporize( Storage.State storage state, Actions.VaporizeArgs memory args, Cache.MarketCache memory cache ) private { state.requireIsOperator(args.solidAccount, msg.sender); // verify vaporizable if (Account.Status.Vapor != state.getStatus(args.vaporAccount)) { Require.that( state.isVaporizable(args.vaporAccount, cache), FILE, "Unvaporizable account", args.vaporAccount.owner, args.vaporAccount.number ); state.setStatus(args.vaporAccount, Account.Status.Vapor); } // First, attempt to refund using the same token ( bool fullyRepaid, Types.Wei memory excessWei ) = _vaporizeUsingExcess(state, args); if (fullyRepaid) { Events.logVaporize( state, args, Types.zeroWei(), Types.zeroWei(), excessWei ); return; } Types.Wei memory maxHeldWei = state.getNumExcessTokens(args.heldMarket); Require.that( !maxHeldWei.isNegative(), FILE, "Excess cannot be negative", args.heldMarket ); ( Types.Par memory owedPar, Types.Wei memory owedWei ) = state.getNewParAndDeltaWeiForLiquidation( args.vaporAccount, args.owedMarket, args.amount ); ( Monetary.Price memory heldPrice, Monetary.Price memory owedPrice ) = _getLiquidationPrices( state, cache, args.heldMarket, args.owedMarket ); Types.Wei memory heldWei = _owedWeiToHeldWei(owedWei, heldPrice, owedPrice); // if attempting to over-borrow the held asset, bound it by the maximum if (heldWei.value > maxHeldWei.value) { heldWei = maxHeldWei.negative(); owedWei = _heldWeiToOwedWei(heldWei, heldPrice, owedPrice); state.setParFromDeltaWei( args.vaporAccount, args.owedMarket, owedWei ); } else { state.setPar( args.vaporAccount, args.owedMarket, owedPar ); } // set the balances for the solid account state.setParFromDeltaWei( args.solidAccount, args.owedMarket, owedWei.negative() ); state.setParFromDeltaWei( args.solidAccount, args.heldMarket, heldWei.negative() ); Events.logVaporize( state, args, heldWei, owedWei, excessWei ); } function _call( Storage.State storage state, Actions.CallArgs memory args ) private { state.requireIsOperator(args.account, msg.sender); ICallee(args.callee).callFunction( msg.sender, args.account, args.data ); Events.logCall(args); } // ============ Private Functions ============ /** * For the purposes of liquidation or vaporization, get the value-equivalent amount of heldWei * given owedWei and the (spread-adjusted) prices of each asset. */ function _owedWeiToHeldWei( Types.Wei memory owedWei, Monetary.Price memory heldPrice, Monetary.Price memory owedPrice ) private pure returns (Types.Wei memory) { return Types.Wei({ sign: false, value: Math.getPartial(owedWei.value, owedPrice.value, heldPrice.value) }); } /** * For the purposes of liquidation or vaporization, get the value-equivalent amount of owedWei * given heldWei and the (spread-adjusted) prices of each asset. */ function _heldWeiToOwedWei( Types.Wei memory heldWei, Monetary.Price memory heldPrice, Monetary.Price memory owedPrice ) private pure returns (Types.Wei memory) { return Types.Wei({ sign: true, value: Math.getPartialRoundUp(heldWei.value, heldPrice.value, owedPrice.value) }); } /** * Attempt to vaporize an account's balance using the excess tokens in the protocol. Return a * bool and a wei value. The boolean is true if and only if the balance was fully vaporized. The * Wei value is how many excess tokens were used to partially or fully vaporize the account's * negative balance. */ function _vaporizeUsingExcess( Storage.State storage state, Actions.VaporizeArgs memory args ) internal returns (bool, Types.Wei memory) { Types.Wei memory excessWei = state.getNumExcessTokens(args.owedMarket); // There are no excess funds, return zero if (!excessWei.isPositive()) { return (false, Types.zeroWei()); } Types.Wei memory maxRefundWei = state.getWei(args.vaporAccount, args.owedMarket); maxRefundWei.sign = true; // The account is fully vaporizable using excess funds if (excessWei.value >= maxRefundWei.value) { state.setPar( args.vaporAccount, args.owedMarket, Types.zeroPar() ); return (true, maxRefundWei); } // The account is only partially vaporizable using excess funds else { state.setParFromDeltaWei( args.vaporAccount, args.owedMarket, excessWei ); return (false, excessWei); } } /** * Return the (spread-adjusted) prices of two assets for the purposes of liquidation or * vaporization. */ function _getLiquidationPrices( Storage.State storage state, Cache.MarketCache memory cache, uint256 heldMarketId, uint256 owedMarketId ) internal view returns ( Monetary.Price memory, Monetary.Price memory ) { uint256 originalPrice = cache.getPrice(owedMarketId).value; Decimal.D256 memory spread = state.getLiquidationSpreadForPair( heldMarketId, owedMarketId ); Monetary.Price memory owedPrice = Monetary.Price({ value: originalPrice.add(Decimal.mul(originalPrice, spread)) }); return (cache.getPrice(heldMarketId), owedPrice); } }
File 10 of 15: WethPriceOracle
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental ABIEncoderV2; // File: contracts/protocol/lib/Monetary.sol /** * @title Monetary * @author dYdX * * Library for types involving money */ library Monetary { /* * The price of a base-unit of an asset. */ struct Price { uint256 value; } /* * Total value of an some amount of an asset. Equal to (price * amount). */ struct Value { uint256 value; } } // File: contracts/protocol/interfaces/IPriceOracle.sol /** * @title IPriceOracle * @author dYdX * * Interface that Price Oracles for Solo must implement in order to report prices. */ contract IPriceOracle { // ============ Constants ============ uint256 public constant ONE_DOLLAR = 10 ** 36; // ============ Public Functions ============ /** * Get the price of a token * * @param token The ERC20 token address of the market * @return The USD price of a base unit of the token, then multiplied by 10^36. * So a USD-stable coin with 18 decimal places would return 10^18. * This is the price of the base unit rather than the price of a "human-readable" * token amount. Every ERC20 may have a different number of decimals. */ function getPrice( address token ) public view returns (Monetary.Price memory); } // File: contracts/external/interfaces/IMakerOracle.sol /** * @title IMakerOracle * @author dYdX * * Interface for the price oracles run by MakerDao */ interface IMakerOracle { // Event that is logged when the `note` modifier is used event LogNote( bytes4 indexed msgSig, address indexed msgSender, bytes32 indexed arg1, bytes32 indexed arg2, uint256 msgValue, bytes msgData ) anonymous; // returns the current value (ETH/USD * 10**18) as a bytes32 function peek() external view returns (bytes32, bool); // requires a fresh price and then returns the current value function read() external view returns (bytes32); } // File: contracts/external/oracles/WethPriceOracle.sol /** * @title WethPriceOracle * @author dYdX * * PriceOracle that returns the price of Wei in USD */ contract WethPriceOracle is IPriceOracle { // ============ Storage ============ IMakerOracle public MEDIANIZER; // ============ Constructor ============= constructor( address medianizer ) public { MEDIANIZER = IMakerOracle(medianizer); } // ============ IPriceOracle Functions ============= function getPrice( address /* token */ ) public view returns (Monetary.Price memory) { (bytes32 value, /* bool fresh */) = MEDIANIZER.peek(); return Monetary.Price({ value: uint256(value) }); } }
File 11 of 15: P1MirrorOracleETHUSD
/* Copyright 2020 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.16; pragma experimental ABIEncoderV2; // File: @openzeppelin/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/external/maker/I_MakerOracle.sol /** * @title I_MakerOracle * @author dYdX * * Interface for the MakerDAO Oracles V2 smart contrats. */ interface I_MakerOracle { // ============ Getter Functions ============ /** * @notice Returns the current value as a bytes32. */ function peek() external view returns (bytes32, bool); /** * @notice Requires a fresh price and then returns the current value. */ function read() external view returns (bytes32); /** * @notice Returns the number of signers per poke. */ function bar() external view returns (uint256); /** * @notice Returns the timetamp of the last update. */ function age() external view returns (uint32); /** * @notice Returns 1 if the signer is authorized, and 0 otherwise. */ function orcl( address signer ) external view returns (uint256); /** * @notice Returns 1 if the address is authorized to read the oracle price, and 0 otherwise. */ function bud( address reader ) external view returns (uint256); /** * @notice A mapping from the first byte of an authorized signer's address to the signer. */ function slot( uint8 signerId ) external view returns (address); // ============ State-Changing Functions ============ /** * @notice Updates the value of the oracle */ function poke( uint256[] calldata val_, uint256[] calldata age_, uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s ) external; /** * @notice Authorize an address to read the oracle price. */ function kiss( address reader ) external; /** * @notice Unauthorize an address so it can no longer read the oracle price. */ function diss( address reader ) external; /** * @notice Authorize addresses to read the oracle price. */ function kiss( address[] calldata readers ) external; /** * @notice Unauthorize addresses so they can no longer read the oracle price. */ function diss( address[] calldata readers ) external; } // File: contracts/protocol/v1/oracles/P1MirrorOracle.sol /** * @title P1MirrorOracle * @author dYdX * * Oracle which mirrors an underlying oracle. */ contract P1MirrorOracle is Ownable, I_MakerOracle { // ============ Events ============ event LogMedianPrice( uint256 val, uint256 age ); event LogSetSigner( address signer, bool authorized ); event LogSetBar( uint256 bar ); event LogSetReader( address reader, bool authorized ); // ============ Mutable Storage ============ // The oracle price. uint128 internal _VAL_; // The timestamp of the last oracle update. uint32 public _AGE_; // The number of signers required to update the oracle price. uint256 public _BAR_; // Authorized signers. Value is equal to 0 or 1. mapping (address => uint256) public _ORCL_; // Addresses with permission to get the oracle price. Value is equal to 0 or 1. mapping (address => uint256) _READERS_; // Mapping for at most 256 signers. // Each signer is identified by the first byte of their address. mapping (uint8 => address) public _SLOT_; // ============ Immutable Storage ============ // The underlying oracle. address public _ORACLE_; // ============ Constructor ============ constructor( address oracle ) public { _ORACLE_ = oracle; } // ============ Getter Functions ============ /** * @notice Returns the current price, and a boolean indicating whether the price is nonzero. */ function peek() external view returns (bytes32, bool) { require( _READERS_[msg.sender] == 1, "P1MirrorOracle#peek: Sender not authorized to get price" ); uint256 val = _VAL_; return (bytes32(val), val > 0); } /** * @notice Requires the price to be nonzero, and returns the current price. */ function read() external view returns (bytes32) { require( _READERS_[msg.sender] == 1, "P1MirrorOracle#read: Sender not authorized to get price" ); uint256 val = _VAL_; require( val > 0, "P1MirrorOracle#read: Price is zero" ); return bytes32(val); } /** * @notice Returns the number of signers per poke. */ function bar() external view returns (uint256) { return _BAR_; } /** * @notice Returns the timetamp of the last update. */ function age() external view returns (uint32) { return _AGE_; } /** * @notice Returns 1 if the signer is authorized, and 0 otherwise. */ function orcl( address signer ) external view returns (uint256) { return _ORCL_[signer]; } /** * @notice Returns 1 if the address is authorized to read the oracle price, and 0 otherwise. */ function bud( address reader ) external view returns (uint256) { return _READERS_[reader]; } /** * @notice A mapping from the first byte of an authorized signer's address to the signer. */ function slot( uint8 signerId ) external view returns (address) { return _SLOT_[signerId]; } /** * @notice Check whether the list of signers and required number of signers match the underlying * oracle. * * @return A bitmap of the IDs of signers that need to be added to the mirror. * @return A bitmap of the IDs of signers that need to be removed from the mirror. * @return False if the required number of signers (“bar”) matches, and true otherwise. */ function checkSynced() external view returns (uint256, uint256, bool) { uint256 signersToAdd = 0; uint256 signersToRemove = 0; bool barNeedsUpdate = _BAR_ != I_MakerOracle(_ORACLE_).bar(); // Note that `i` cannot be a uint8 since it is incremented to 256 at the end of the loop. for (uint256 i = 0; i < 256; i++) { uint8 signerId = uint8(i); uint256 signerBit = uint256(1) << signerId; address ours = _SLOT_[signerId]; address theirs = I_MakerOracle(_ORACLE_).slot(signerId); if (ours == address(0)) { if (theirs != address(0)) { signersToAdd = signersToAdd | signerBit; } } else { if (theirs == address(0)) { signersToRemove = signersToRemove | signerBit; } else if (ours != theirs) { signersToAdd = signersToAdd | signerBit; signersToRemove = signersToRemove | signerBit; } } } return (signersToAdd, signersToRemove, barNeedsUpdate); } // ============ State-Changing Functions ============ /** * @notice Send an array of signed messages to update the oracle value. * Must have exactly `_BAR_` number of messages. */ function poke( uint256[] calldata val_, uint256[] calldata age_, uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s ) external { require(val_.length == _BAR_, "P1MirrorOracle#poke: Wrong number of messages"); // Bitmap of signers, used to ensure that each message has a different signer. uint256 bloom = 0; // Last message value, used to ensure messages are ordered by value. uint256 last = 0; // Require that all messages are newer than the last oracle update. uint256 zzz = _AGE_; for (uint256 i = 0; i < val_.length; i++) { uint256 val_i = val_[i]; uint256 age_i = age_[i]; // Verify that the message comes from an authorized signer. address signer = recover( val_i, age_i, v[i], r[i], s[i] ); require(_ORCL_[signer] == 1, "P1MirrorOracle#poke: Invalid signer"); // Verify that the message is newer than the last oracle update. require(age_i > zzz, "P1MirrorOracle#poke: Stale message"); // Verify that the messages are ordered by value. require(val_i >= last, "P1MirrorOracle#poke: Message out of order"); last = val_i; // Verify that each message has a different signer. // Each signer is identified by the first byte of their address. uint8 signerId = getSignerId(signer); uint256 signerBit = uint256(1) << signerId; require(bloom & signerBit == 0, "P1MirrorOracle#poke: Duplicate signer"); bloom = bloom | signerBit; } // Set the oracle value to the median (note that val_.length is always odd). _VAL_ = uint128(val_[val_.length >> 1]); // Set the timestamp of the oracle update. _AGE_ = uint32(block.timestamp); emit LogMedianPrice(_VAL_, _AGE_); } /** * @notice Authorize new signers. The signers must be authorized on the underlying oracle. */ function lift( address[] calldata signers ) external { for (uint256 i = 0; i < signers.length; i++) { address signer = signers[i]; require( I_MakerOracle(_ORACLE_).orcl(signer) == 1, "P1MirrorOracle#lift: Signer not authorized on underlying oracle" ); // orcl and slot must both be empty. // orcl is filled implies slot is filled, therefore slot is empty implies orcl is empty. // Assume that the underlying oracle ensures that the signer cannot be the zero address. uint8 signerId = getSignerId(signer); require( _SLOT_[signerId] == address(0), "P1MirrorOracle#lift: Signer already authorized" ); _ORCL_[signer] = 1; _SLOT_[signerId] = signer; emit LogSetSigner(signer, true); } } /** * @notice Unauthorize signers. The signers must NOT be authorized on the underlying oracle. */ function drop( address[] calldata signers ) external { for (uint256 i = 0; i < signers.length; i++) { address signer = signers[i]; require( I_MakerOracle(_ORACLE_).orcl(signer) == 0, "P1MirrorOracle#drop: Signer is authorized on underlying oracle" ); // orcl and slot must both be filled. // orcl is filled implies slot is filled. require( _ORCL_[signer] != 0, "P1MirrorOracle#drop: Signer is already not authorized" ); uint8 signerId = getSignerId(signer); _ORCL_[signer] = 0; _SLOT_[signerId] = address(0); emit LogSetSigner(signer, false); } } /** * @notice Sync `_BAR_` (the number of required signers) with the underyling oracle contract. */ function setBar() external { uint256 newBar = I_MakerOracle(_ORACLE_).bar(); _BAR_ = newBar; emit LogSetBar(newBar); } /** * @notice Authorize an address to read the oracle price. */ function kiss( address reader ) external onlyOwner { _kiss(reader); } /** * @notice Unauthorize an address so it can no longer read the oracle price. */ function diss( address reader ) external onlyOwner { _diss(reader); } /** * @notice Authorize addresses to read the oracle price. */ function kiss( address[] calldata readers ) external onlyOwner { for (uint256 i = 0; i < readers.length; i++) { _kiss(readers[i]); } } /** * @notice Unauthorize addresses so they can no longer read the oracle price. */ function diss( address[] calldata readers ) external onlyOwner { for (uint256 i = 0; i < readers.length; i++) { _diss(readers[i]); } } // ============ Internal Functions ============ function wat() internal pure returns (bytes32); function recover( uint256 val_, uint256 age_, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { return ecrecover( keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(val_, age_, wat()))) ), v, r, s ); } function getSignerId( address signer ) internal pure returns (uint8) { return uint8(uint256(signer) >> 152); } function _kiss( address reader ) private { _READERS_[reader] = 1; emit LogSetReader(reader, true); } function _diss( address reader ) private { _READERS_[reader] = 0; emit LogSetReader(reader, false); } } // File: contracts/protocol/v1/oracles/P1MirrorOracleETHUSD.sol /** * @title P1MirrorOracleETHUSD * @author dYdX * * Oracle which mirrors the ETHUSD oracle. */ contract P1MirrorOracleETHUSD is P1MirrorOracle { bytes32 public constant WAT = "ETHUSD"; constructor( address oracle ) P1MirrorOracle(oracle) public { } function wat() internal pure returns (bytes32) { return WAT; } }
File 12 of 15: DoubleExponentInterestSetter
/** *Submitted for verification at Etherscan.io on 2019-08-28 */ /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental ABIEncoderV2; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/protocol/lib/Require.sol /** * @title Require * @author dYdX * * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require() */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringify(file), COLON, stringify(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringify( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } // File: contracts/protocol/lib/Math.sol /** * @title Math * @author dYdX * * Library for non-standard Math functions */ library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // File: contracts/protocol/lib/Decimal.sol /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Functions ============ function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function onePlus( D256 memory d ) internal pure returns (D256 memory) { return D256({ value: d.value.add(BASE) }); } function mul( uint256 target, D256 memory d ) internal pure returns (uint256) { return Math.getPartial(target, d.value, BASE); } function div( uint256 target, D256 memory d ) internal pure returns (uint256) { return Math.getPartial(target, BASE, d.value); } } // File: contracts/protocol/lib/Time.sol /** * @title Time * @author dYdX * * Library for dealing with time, assuming timestamps fit within 32 bits (valid until year 2106) */ library Time { // ============ Library Functions ============ function currentTime() internal view returns (uint32) { return Math.to32(block.timestamp); } } // File: contracts/protocol/lib/Types.sol /** * @title Types * @author dYdX * * Library for interacting with the basic structs used in Solo */ library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } // File: contracts/protocol/lib/Interest.sol /** * @title Interest * @author dYdX * * Library for managing the interest rate and interest indexes of Solo */ library Interest { using Math for uint256; using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Interest"; uint64 constant BASE = 10**18; // ============ Structs ============ struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } // ============ Library Functions ============ /** * Get a new market Index based on the old index and market interest rate. * Calculate interest for borrowers by using the formula rate * time. Approximates * continuously-compounded interest when called frequently, but is much more * gas-efficient to calculate. For suppliers, the interest rate is adjusted by the earningsRate, * then prorated the across all suppliers. * * @param index The old index for a market * @param rate The current interest rate of the market * @param totalPar The total supply and borrow par values of the market * @param earningsRate The portion of the interest that is forwarded to the suppliers * @return The updated index for a market */ function calculateNewIndex( Index memory index, Rate memory rate, Types.TotalPar memory totalPar, Decimal.D256 memory earningsRate ) internal view returns (Index memory) { ( Types.Wei memory supplyWei, Types.Wei memory borrowWei ) = totalParToWei(totalPar, index); // get interest increase for borrowers uint32 currentTime = Time.currentTime(); uint256 borrowInterest = rate.value.mul(uint256(currentTime).sub(index.lastUpdate)); // get interest increase for suppliers uint256 supplyInterest; if (Types.isZero(supplyWei)) { supplyInterest = 0; } else { supplyInterest = Decimal.mul(borrowInterest, earningsRate); if (borrowWei.value < supplyWei.value) { supplyInterest = Math.getPartial(supplyInterest, borrowWei.value, supplyWei.value); } } assert(supplyInterest <= borrowInterest); return Index({ borrow: Math.getPartial(index.borrow, borrowInterest, BASE).add(index.borrow).to96(), supply: Math.getPartial(index.supply, supplyInterest, BASE).add(index.supply).to96(), lastUpdate: currentTime }); } function newIndex() internal view returns (Index memory) { return Index({ borrow: BASE, supply: BASE, lastUpdate: Time.currentTime() }); } /* * Convert a principal amount to a token amount given an index. */ function parToWei( Types.Par memory input, Index memory index ) internal pure returns (Types.Wei memory) { uint256 inputValue = uint256(input.value); if (input.sign) { return Types.Wei({ sign: true, value: inputValue.getPartial(index.supply, BASE) }); } else { return Types.Wei({ sign: false, value: inputValue.getPartialRoundUp(index.borrow, BASE) }); } } /* * Convert a token amount to a principal amount given an index. */ function weiToPar( Types.Wei memory input, Index memory index ) internal pure returns (Types.Par memory) { if (input.sign) { return Types.Par({ sign: true, value: input.value.getPartial(BASE, index.supply).to128() }); } else { return Types.Par({ sign: false, value: input.value.getPartialRoundUp(BASE, index.borrow).to128() }); } } /* * Convert the total supply and borrow principal amounts of a market to total supply and borrow * token amounts. */ function totalParToWei( Types.TotalPar memory totalPar, Index memory index ) internal pure returns (Types.Wei memory, Types.Wei memory) { Types.Par memory supplyPar = Types.Par({ sign: true, value: totalPar.supply }); Types.Par memory borrowPar = Types.Par({ sign: false, value: totalPar.borrow }); Types.Wei memory supplyWei = parToWei(supplyPar, index); Types.Wei memory borrowWei = parToWei(borrowPar, index); return (supplyWei, borrowWei); } } // File: contracts/protocol/interfaces/IInterestSetter.sol /** * @title IInterestSetter * @author dYdX * * Interface that Interest Setters for Solo must implement in order to report interest rates. */ interface IInterestSetter { // ============ Public Functions ============ /** * Get the interest rate of a token given some borrowed and supplied amounts * * @param token The address of the ERC20 token for the market * @param borrowWei The total borrowed token amount for the market * @param supplyWei The total supplied token amount for the market * @return The interest rate per second */ function getInterestRate( address token, uint256 borrowWei, uint256 supplyWei ) external view returns (Interest.Rate memory); } // File: contracts/external/interestsetters/DoubleExponentInterestSetter.sol /** * @title DoubleExponentInterestSetter * @author dYdX * * Interest setter that sets interest based on a polynomial of the usage percentage of the market. * Interest = C_0 + C_1 * U^(2^0) + C_2 * U^(2^1) + C_3 * U^(2^2) ... */ contract DoubleExponentInterestSetter is IInterestSetter { using Math for uint256; using SafeMath for uint256; // ============ Constants ============ uint256 constant PERCENT = 100; uint256 constant BASE = 10 ** 18; uint256 constant SECONDS_IN_A_YEAR = 60 * 60 * 24 * 365; uint256 constant BYTE = 8; // ============ Structs ============ struct PolyStorage { uint128 maxAPR; uint128 coefficients; } // ============ Storage ============ PolyStorage g_storage; // ============ Constructor ============ constructor( PolyStorage memory params ) public { // verify that all coefficients add up to 100% uint256 sumOfCoefficients = 0; for ( uint256 coefficients = params.coefficients; coefficients != 0; coefficients >>= BYTE ) { sumOfCoefficients += coefficients % 256; } require( sumOfCoefficients == PERCENT, "Coefficients must sum to 100" ); // store the params g_storage = params; } // ============ Public Functions ============ /** * Get the interest rate given some borrowed and supplied amounts. The interest function is a * polynomial function of the utilization (borrowWei / supplyWei) of the market. * * - If borrowWei > supplyWei then the utilization is considered to be equal to 1. * - If both are zero, then the utilization is considered to be equal to 0. * * @return The interest rate per second (times 10 ** 18) */ function getInterestRate( address /* token */, uint256 borrowWei, uint256 supplyWei ) external view returns (Interest.Rate memory) { if (borrowWei == 0) { return Interest.Rate({ value: 0 }); } PolyStorage memory s = g_storage; uint256 maxAPR = s.maxAPR; if (borrowWei >= supplyWei) { return Interest.Rate({ value: maxAPR / SECONDS_IN_A_YEAR }); } // process the first coefficient uint256 coefficients = s.coefficients; uint256 result = uint8(coefficients) * BASE; coefficients >>= BYTE; // initialize polynomial as the utilization // no safeDiv since supplyWei must be non-zero at this point uint256 polynomial = BASE.mul(borrowWei) / supplyWei; // for each non-zero coefficient... while (true) { // gets the lowest-order byte uint256 coefficient = uint256(uint8(coefficients)); // if non-zero, add to result if (coefficient != 0) { // no safeAdd since there are at most 16 coefficients // no safeMul since (coefficient < 256 && polynomial <= 10**18) result += coefficient * polynomial; // break if this is the last non-zero coefficient if (coefficient == coefficients) { break; } } // double the order of the polynomial term // no safeMul since polynomial <= 10^18 // no safeDiv since the divisor is a non-zero constant polynomial = polynomial * polynomial / BASE; // move to next coefficient coefficients >>= BYTE; } // normalize the result // no safeMul since result fits within 72 bits and maxAPR fits within 128 bits // no safeDiv since the divisor is a non-zero constant return Interest.Rate({ value: result * maxAPR / (SECONDS_IN_A_YEAR * BASE * PERCENT) }); } /** * Get the maximum APR that this interestSetter will return. The actual APY may be higher * depending on how often the interest is compounded. * * @return The maximum APR */ function getMaxAPR() external view returns (uint256) { return g_storage.maxAPR; } /** * Get all of the coefficients of the interest calculation, starting from the coefficient for * the first-order utilization variable. * * @return The coefficients */ function getCoefficients() external view returns (uint256[] memory) { // allocate new array with maximum of 16 coefficients uint256[] memory result = new uint256[](16); // add the coefficients to the array uint256 numCoefficients = 0; for ( uint256 coefficients = g_storage.coefficients; coefficients != 0; coefficients >>= BYTE ) { result[numCoefficients] = coefficients % 256; numCoefficients++; } // modify result.length to match numCoefficients /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, numCoefficients) } return result; } }
File 13 of 15: UniswapV2Router02
// File: contracts/uniswapv2/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/uniswapv2/libraries/SafeMath.sol pragma solidity =0.6.12; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathUniswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File: contracts/uniswapv2/libraries/UniswapV2Library.sol pragma solidity >=0.5.0; library UniswapV2Library { using SafeMathUniswap for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File: contracts/uniswapv2/libraries/TransferHelper.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // 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, uint 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))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint 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))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint 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))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: contracts/uniswapv2/interfaces/IUniswapV2Router01.sol pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: contracts/uniswapv2/interfaces/IUniswapV2Router02.sol pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File: contracts/uniswapv2/interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } // File: contracts/uniswapv2/interfaces/IERC20.sol pragma solidity >=0.5.0; interface IERC20Uniswap { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint 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 (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // File: contracts/uniswapv2/interfaces/IWETH.sol pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File: contracts/uniswapv2/UniswapV2Router02.sol pragma solidity =0.6.12; contract UniswapV2Router02 is IUniswapV2Router02 { using SafeMathUniswap for uint; address public immutable override factory; address public immutable override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IUniswapV2Pair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = UniswapV2Library.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IUniswapV2Pair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to); (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20Uniswap(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20Uniswap(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20Uniswap(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return UniswapV2Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsIn(factory, amountOut, path); } }
File 14 of 15: UniswapV2Router02
pragma solidity =0.6.6; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint 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 (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } contract UniswapV2Router02 is IUniswapV2Router02 { using SafeMath for uint; address public immutable override factory; address public immutable override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IUniswapV2Pair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = UniswapV2Library.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IUniswapV2Pair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to); (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return UniswapV2Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsIn(factory, amountOut, path); } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // 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, uint 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))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint 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))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint 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))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } }
File 15 of 15: ConfigurableInterestBankConfig
// File: openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol pragma solidity ^0.5.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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts/BankConfig.sol pragma solidity 0.5.16; interface BankConfig { /// @dev Return minimum ETH debt size per position. function minDebtSize() external view returns (uint256); /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint256 debt, uint256 floating) external view returns (uint256); /// @dev Return the bps rate for reserve pool. function getReservePoolBps() external view returns (uint256); /// @dev Return the bps rate for Avada Kill caster. function getKillBps() external view returns (uint256); /// @dev Return whether the given address is a goblin. function isGoblin(address goblin) external view returns (bool); /// @dev Return whether the given goblin accepts more debt. Revert on non-goblin. function acceptDebt(address goblin) external view returns (bool); /// @dev Return the work factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin. function workFactor(address goblin, uint256 debt) external view returns (uint256); /// @dev Return the kill factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin. function killFactor(address goblin, uint256 debt) external view returns (uint256); } // File: contracts/GoblinConfig.sol pragma solidity 0.5.16; interface GoblinConfig { /// @dev Return whether the given goblin accepts more debt. function acceptDebt(address goblin) external view returns (bool); /// @dev Return the work factor for the goblin + ETH debt, using 1e4 as denom. function workFactor(address goblin, uint256 debt) external view returns (uint256); /// @dev Return the kill factor for the goblin + ETH debt, using 1e4 as denom. function killFactor(address goblin, uint256 debt) external view returns (uint256); } // File: contracts/ConfigurableInterestBankConfig.sol pragma solidity 0.5.16; interface InterestModel { /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint256 debt, uint256 floating) external view returns (uint256); } contract ConfigurableInterestBankConfig is BankConfig, Ownable { /// The minimum ETH debt size per position. uint256 public minDebtSize; /// The portion of interests allocated to the reserve pool. uint256 public getReservePoolBps; /// The reward for successfully killing a position. uint256 public getKillBps; /// Mapping for goblin address to its configuration. mapping (address => GoblinConfig) public goblins; /// Interest rate model InterestModel public interestModel; constructor( uint256 _minDebtSize, uint256 _reservePoolBps, uint256 _killBps, InterestModel _interestModel ) public { setParams(_minDebtSize, _reservePoolBps, _killBps, _interestModel); } /// @dev Set all the basic parameters. Must only be called by the owner. /// @param _minDebtSize The new minimum debt size value. /// @param _reservePoolBps The new interests allocated to the reserve pool value. /// @param _killBps The new reward for killing a position value. /// @param _interestModel The new interest rate model contract. function setParams( uint256 _minDebtSize, uint256 _reservePoolBps, uint256 _killBps, InterestModel _interestModel ) public onlyOwner { minDebtSize = _minDebtSize; getReservePoolBps = _reservePoolBps; getKillBps = _killBps; interestModel = _interestModel; } /// @dev Set the configuration for the given goblins. Must only be called by the owner. function setGoblins(address[] calldata addrs, GoblinConfig[] calldata configs) external onlyOwner { require(addrs.length == configs.length, "bad length"); for (uint256 idx = 0; idx < addrs.length; idx++) { goblins[addrs[idx]] = configs[idx]; } } /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint256 debt, uint256 floating) external view returns (uint256) { return interestModel.getInterestRate(debt, floating); } /// @dev Return whether the given address is a goblin. function isGoblin(address goblin) external view returns (bool) { return address(goblins[goblin]) != address(0); } /// @dev Return whether the given goblin accepts more debt. Revert on non-goblin. function acceptDebt(address goblin) external view returns (bool) { return goblins[goblin].acceptDebt(goblin); } /// @dev Return the work factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin. function workFactor(address goblin, uint256 debt) external view returns (uint256) { return goblins[goblin].workFactor(goblin, debt); } /// @dev Return the kill factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin. function killFactor(address goblin, uint256 debt) external view returns (uint256) { return goblins[goblin].killFactor(goblin, debt); } }