From b04455c36f052ccd678af07f46353d39f24070a7 Mon Sep 17 00:00:00 2001 From: Elyas <35933488+eobbad@users.noreply.github.com> Date: Thu, 6 Oct 2022 11:44:57 -0400 Subject: [PATCH] chore: Configure `prettier-solidity` and run `prettier-solidity` [TKR-532] (#592) * add prettier-solidity + config * run prettier * update lockfile * run prettier again * Prettier missed one /: * keep bridge adapter the same * yarn prettier --- .prettierignore | 1 - .prettierrc | 14 +- contracts/erc20/contracts/src/ERC20Token.sol | 85 +--- .../erc20/contracts/src/LibERC20Token.sol | 78 +--- .../contracts/src/MintableERC20Token.sol | 25 +- .../src/UnlimitedAllowanceERC20Token.sol | 33 +- contracts/erc20/contracts/src/WETH9.sol | 41 +- contracts/erc20/contracts/src/ZRXToken.sol | 93 ++--- .../contracts/src/interfaces/IERC20Token.sol | 41 +- .../contracts/src/interfaces/IEtherToken.sol | 12 +- .../contracts/src/v06/IERC20TokenV06.sol | 46 +-- .../contracts/src/v06/IEtherTokenV06.sol | 5 +- .../contracts/src/v06/LibERC20TokenV06.sol | 82 +--- .../erc20/contracts/test/DummyERC20Token.sol | 26 +- .../test/DummyMultipleReturnERC20Token.sol | 29 +- .../test/DummyNoReturnERC20Token.sol | 67 +--- .../contracts/test/TestLibERC20Token.sol | 19 +- .../test/TestLibERC20TokenTarget.sol | 57 +-- .../test/UntransferrableDummyERC20Token.sol | 28 +- contracts/erc20/src/artifacts.ts | 2 +- contracts/erc20/test/artifacts.ts | 2 +- .../treasury/contracts/external/ISablier.sol | 12 +- .../contracts/src/DefaultPoolOperator.sol | 14 +- contracts/treasury/contracts/src/IStaking.sol | 40 +- .../treasury/contracts/src/IZrxTreasury.sol | 65 +-- .../treasury/contracts/src/ZrxTreasury.sol | 188 +++------ .../utils/contracts/src/Authorizable.sol | 65 +-- contracts/utils/contracts/src/D18.sol | 139 ++----- .../contracts/src/DeploymentConstants.sol | 140 ++----- contracts/utils/contracts/src/LibAddress.sol | 7 +- .../utils/contracts/src/LibAddressArray.sol | 35 +- .../src/LibAddressArrayRichErrors.sol | 16 +- .../src/LibAuthorizableRichErrors.sol | 89 +---- contracts/utils/contracts/src/LibBytes.sol | 240 +++++------ .../contracts/src/LibBytesRichErrors.sol | 18 +- contracts/utils/contracts/src/LibEIP1271.sol | 4 +- contracts/utils/contracts/src/LibEIP712.sol | 23 +- .../utils/contracts/src/LibFractions.sol | 54 +-- contracts/utils/contracts/src/LibMath.sol | 82 +--- .../utils/contracts/src/LibMathRichErrors.sol | 27 +- .../contracts/src/LibOwnableRichErrors.sol | 29 +- .../src/LibReentrancyGuardRichErrors.sol | 11 +- .../utils/contracts/src/LibRichErrors.sol | 24 +- contracts/utils/contracts/src/LibSafeMath.sol | 78 ++-- .../contracts/src/LibSafeMathRichErrors.sol | 36 +- contracts/utils/contracts/src/Ownable.sol | 24 +- .../utils/contracts/src/ReentrancyGuard.sol | 14 +- contracts/utils/contracts/src/Refundable.sol | 34 +- .../src/interfaces/IAuthorizable.sol | 32 +- .../contracts/src/interfaces/IOwnable.sol | 5 +- .../contracts/src/v06/AuthorizableV06.sol | 71 +--- .../utils/contracts/src/v06/LibBytesV06.sol | 240 +++++------ .../utils/contracts/src/v06/LibMathV06.sol | 82 +--- .../contracts/src/v06/LibSafeMathV06.sol | 186 ++++----- .../utils/contracts/src/v06/OwnableV06.sol | 21 +- .../contracts/src/v06/ReentrancyGuardV06.sol | 14 +- .../errors/LibAuthorizableRichErrorsV06.sol | 89 +---- .../src/v06/errors/LibBytesRichErrorsV06.sol | 18 +- .../src/v06/errors/LibMathRichErrorsV06.sol | 27 +- .../v06/errors/LibOwnableRichErrorsV06.sol | 29 +- .../LibReentrancyGuardRichErrorsV06.sol | 11 +- .../src/v06/errors/LibRichErrorsV06.sol | 19 +- .../v06/errors/LibSafeMathRichErrorsV06.sol | 36 +- .../src/v06/interfaces/IAuthorizableV06.sol | 33 +- .../src/v06/interfaces/IOwnableV06.sol | 2 - .../utils/contracts/test/TestAuthorizable.sol | 11 +- .../utils/contracts/test/TestLibAddress.sol | 8 +- .../contracts/test/TestLibAddressArray.sol | 9 +- .../utils/contracts/test/TestLibBytes.sol | 108 +---- .../utils/contracts/test/TestLibEIP712.sol | 21 +- .../utils/contracts/test/TestLibMath.sol | 38 +- .../contracts/test/TestLibRichErrors.sol | 7 +- .../utils/contracts/test/TestLibSafeMath.sol | 38 +- .../utils/contracts/test/TestLogDecoding.sol | 24 +- .../test/TestLogDecodingDownstream.sol | 19 +- .../utils/contracts/test/TestOwnable.sol | 12 +- .../contracts/test/TestReentrancyGuard.sol | 22 +- .../utils/contracts/test/TestRefundable.sol | 46 +-- .../contracts/test/TestRefundableReceiver.sol | 51 +-- contracts/zero-ex/contracts/src/IZeroEx.sol | 1 - contracts/zero-ex/contracts/src/ZeroEx.sol | 18 +- .../zero-ex/contracts/src/ZeroExOptimized.sol | 14 +- .../src/errors/LibCommonRichErrors.sol | 30 +- .../errors/LibLiquidityProviderRichErrors.sol | 29 +- .../errors/LibMetaTransactionsRichErrors.sol | 166 ++++---- .../src/errors/LibNFTOrdersRichErrors.sol | 222 +++-------- .../src/errors/LibNativeOrdersRichErrors.sol | 206 ++++------ .../src/errors/LibOwnableRichErrors.sol | 39 +- .../src/errors/LibProxyRichErrors.sol | 50 +-- .../src/errors/LibSignatureRichErrors.sol | 34 +- .../LibSimpleFunctionRegistryRichErrors.sol | 19 +- .../errors/LibTransformERC20RichErrors.sol | 224 ++++------- .../src/errors/LibWalletRichErrors.sol | 46 +-- .../contracts/src/external/FeeCollector.sol | 14 +- .../src/external/FeeCollectorController.sol | 27 +- .../contracts/src/external/FlashWallet.sol | 74 +--- .../contracts/src/external/IFlashWallet.sol | 12 +- .../external/ILiquidityProviderSandbox.sol | 11 +- .../src/external/LibFeeCollector.sol | 31 +- .../src/external/LiquidityProviderSandbox.sol | 54 +-- .../PermissionlessTransformerDeployer.sol | 36 +- .../src/external/TransformerDeployer.sol | 21 +- .../features/BatchFillNativeOrdersFeature.sol | 125 +++--- .../src/features/BootstrapFeature.sol | 16 +- .../contracts/src/features/ERC165Feature.sol | 19 +- .../src/features/FundRecoveryFeature.sol | 23 +- .../src/features/LiquidityProviderFeature.sol | 84 +--- .../src/features/MetaTransactionsFeature.sol | 321 ++++++--------- .../src/features/NativeOrdersFeature.sol | 22 +- .../src/features/OtcOrdersFeature.sol | 281 ++++--------- .../contracts/src/features/OwnableFeature.sol | 26 +- .../src/features/PancakeSwapFeature.sol | 339 ++++++++-------- .../SimpleFunctionRegistryFeature.sol | 62 +-- .../src/features/TransformERC20Feature.sol | 203 +++------- .../contracts/src/features/UniswapFeature.sol | 234 ++++++----- .../src/features/UniswapV3Feature.sol | 151 ++----- .../IBatchFillNativeOrdersFeature.sol | 17 +- .../features/interfaces/IBootstrapFeature.sol | 2 - .../interfaces/IERC1155OrdersFeature.sol | 46 +-- .../features/interfaces/IERC165Feature.sol | 7 +- .../interfaces/IERC721OrdersFeature.sol | 61 +-- .../src/features/interfaces/IFeature.sol | 2 - .../interfaces/IFundRecoveryFeature.sol | 9 +- .../interfaces/ILiquidityProviderFeature.sol | 7 +- .../interfaces/IMetaTransactionsFeature.sol | 27 +- .../features/interfaces/IMultiplexFeature.sol | 27 +- .../interfaces/INativeOrdersEvents.sol | 33 +- .../interfaces/INativeOrdersFeature.sol | 109 ++--- .../features/interfaces/IOtcOrdersFeature.sol | 47 +-- .../features/interfaces/IOwnableFeature.sol | 11 +- .../interfaces/IPancakeSwapFeature.sol | 7 +- .../ISimpleFunctionRegistryFeature.sol | 12 +- .../interfaces/ITokenSpenderFeature.sol | 10 +- .../interfaces/ITransformERC20Feature.sol | 37 +- .../features/interfaces/IUniswapFeature.sol | 7 +- .../features/interfaces/IUniswapV3Feature.sol | 22 +- .../src/features/libs/LibNFTOrder.sol | 102 ++--- .../src/features/libs/LibNativeOrder.sol | 41 +- .../src/features/libs/LibSignature.sol | 76 ++-- .../features/multiplex/MultiplexFeature.sol | 373 +++++------------- .../multiplex/MultiplexLiquidityProvider.sol | 61 +-- .../src/features/multiplex/MultiplexOtc.sol | 53 +-- .../src/features/multiplex/MultiplexRfq.sol | 53 +-- .../multiplex/MultiplexTransformERC20.sol | 16 +- .../features/multiplex/MultiplexUniswapV2.sol | 169 +++----- .../features/multiplex/MultiplexUniswapV3.sol | 14 +- .../NativeOrdersCancellation.sol | 205 +++------- .../native_orders/NativeOrdersInfo.sol | 171 +++----- .../NativeOrdersProtocolFees.sol | 20 +- .../native_orders/NativeOrdersSettlement.sol | 262 ++++-------- .../nft_orders/ERC1155OrdersFeature.sol | 217 +++------- .../nft_orders/ERC721OrdersFeature.sol | 325 +++++---------- .../src/features/nft_orders/NFTOrders.sol | 308 ++++----------- .../contracts/src/fixins/FixinCommon.sol | 21 +- .../contracts/src/fixins/FixinEIP712.sol | 26 +- .../src/fixins/FixinERC1155Spender.sol | 18 +- .../src/fixins/FixinERC721Spender.sol | 18 +- .../src/fixins/FixinProtocolFees.sol | 53 +-- .../src/fixins/FixinReentrancyGuard.sol | 12 +- .../src/fixins/FixinTokenSpender.sol | 69 +--- .../CurveLiquidityProvider.sol | 84 ++-- .../MooniswapLiquidityProvider.sol | 71 +--- .../src/migrations/FullMigration.sol | 48 +-- .../src/migrations/InitialMigration.sol | 22 +- .../contracts/src/migrations/LibBootstrap.sol | 14 +- .../contracts/src/migrations/LibMigrate.sol | 14 +- .../src/storage/LibERC1155OrdersStorage.sol | 10 +- .../src/storage/LibERC721OrdersStorage.sol | 10 +- .../storage/LibMetaTransactionsStorage.sol | 12 +- .../src/storage/LibNativeOrdersStorage.sol | 16 +- .../src/storage/LibOtcOrdersStorage.sol | 10 +- .../src/storage/LibOwnableStorage.sol | 10 +- .../contracts/src/storage/LibProxyStorage.sol | 10 +- .../src/storage/LibReentrancyGuardStorage.sol | 10 +- .../LibSimpleFunctionRegistryStorage.sol | 10 +- .../contracts/src/storage/LibStorage.sol | 8 +- .../src/storage/LibTransformERC20Storage.sol | 10 +- .../transformers/AffiliateFeeTransformer.sol | 11 +- .../src/transformers/FillQuoteTransformer.sol | 212 ++++------ .../src/transformers/IERC20Transformer.sol | 6 +- .../src/transformers/LibERC20Transformer.sol | 73 ++-- .../transformers/LogMetadataTransformer.sol | 11 +- .../src/transformers/PayTakerTransformer.sol | 16 +- .../PositiveSlippageFeeTransformer.sol | 11 +- .../src/transformers/Transformer.sol | 18 +- .../src/transformers/WethTransformer.sol | 26 +- .../bridges/AbstractBridgeAdapter.sol | 47 +-- .../bridges/ArbitrumBridgeAdapter.sol | 132 +++---- .../bridges/AvalancheBridgeAdapter.sol | 124 ++---- .../transformers/bridges/BSCBridgeAdapter.sol | 114 ++---- .../transformers/bridges/BridgeProtocols.sol | 63 ++- .../bridges/CeloBridgeAdapter.sol | 57 +-- .../bridges/EthereumBridgeAdapter.sol | 254 +++++------- .../bridges/FantomBridgeAdapter.sol | 105 ++--- .../transformers/bridges/IBridgeAdapter.sol | 10 +- .../bridges/OptimismBridgeAdapter.sol | 123 ++---- .../bridges/PolygonBridgeAdapter.sol | 165 +++----- .../bridges/mixins/MixinAaveV2.sol | 74 ++-- .../bridges/mixins/MixinBalancer.sol | 32 +- .../bridges/mixins/MixinBalancerV2.sol | 12 +- .../bridges/mixins/MixinBalancerV2Batch.sol | 19 +- .../bridges/mixins/MixinBancor.sol | 38 +- .../bridges/mixins/MixinBancorV3.sol | 37 +- .../bridges/mixins/MixinCompound.sol | 24 +- .../bridges/mixins/MixinCryptoCom.sol | 25 +- .../bridges/mixins/MixinCurve.sol | 20 +- .../bridges/mixins/MixinCurveV2.sol | 13 +- .../transformers/bridges/mixins/MixinDodo.sol | 33 +- .../bridges/mixins/MixinDodoV2.sol | 23 +- .../transformers/bridges/mixins/MixinGMX.sol | 27 +- .../bridges/mixins/MixinKyberDmm.sol | 31 +- .../transformers/bridges/mixins/MixinLido.sol | 26 +- .../bridges/mixins/MixinMStable.sol | 14 +- .../bridges/mixins/MixinMakerPSM.sol | 39 +- .../bridges/mixins/MixinMooniswap.sol | 26 +- .../bridges/mixins/MixinNerve.sol | 14 +- .../bridges/mixins/MixinPlatypus.sol | 24 +- .../bridges/mixins/MixinShell.sol | 20 +- .../bridges/mixins/MixinSynthetix.sol | 30 +- .../bridges/mixins/MixinUniswap.sol | 71 +--- .../bridges/mixins/MixinUniswapV2.sol | 32 +- .../bridges/mixins/MixinUniswapV3.sol | 31 +- .../bridges/mixins/MixinVelodrome.sol | 10 +- .../bridges/mixins/MixinWOOFi.sol | 68 +--- .../bridges/mixins/MixinZeroExBridge.sol | 15 +- .../contracts/src/vendor/IERC1155Token.sol | 32 +- .../contracts/src/vendor/IERC721Token.sol | 55 +-- .../contracts/src/vendor/IFeeRecipient.sol | 6 +- .../src/vendor/ILiquidityProvider.sol | 20 +- .../contracts/src/vendor/IMooniswapPool.sol | 6 +- .../src/vendor/IPropertyValidator.sol | 6 +- .../contracts/src/vendor/ITakerCallback.sol | 9 +- .../contracts/src/vendor/IUniswapV2Pair.sol | 5 +- .../contracts/src/vendor/IUniswapV3Pool.sol | 6 +- .../contracts/src/vendor/v3/IERC20Bridge.sol | 5 +- .../contracts/src/vendor/v3/IStaking.sol | 7 +- .../ITestSimpleFunctionRegistryFeature.sol | 1 - .../zero-ex/contracts/test/TestBridge.sol | 24 +- .../zero-ex/contracts/test/TestCallTarget.sol | 16 +- .../contracts/test/TestDelegateCaller.sol | 16 +- .../test/TestFeeCollectorController.sol | 2 - .../contracts/test/TestFeeRecipient.sol | 19 +- .../test/TestFillQuoteTransformerBridge.sol | 16 +- .../test/TestFillQuoteTransformerExchange.sol | 63 +-- .../test/TestFillQuoteTransformerHost.sol | 16 +- .../contracts/test/TestFixinProtocolFees.sol | 32 +- .../contracts/test/TestFixinTokenSpender.sol | 31 +- .../contracts/test/TestFullMigration.sol | 5 +- .../contracts/test/TestInitialMigration.sol | 17 +- .../contracts/test/TestLibNativeOrder.sol | 8 +- .../contracts/test/TestLibSignature.sol | 2 - ...estMetaTransactionsNativeOrdersFeature.sol | 20 +- ...tMetaTransactionsTransformERC20Feature.sol | 18 +- .../zero-ex/contracts/test/TestMigrator.sol | 16 +- .../test/TestMintTokenERC20Transformer.sol | 26 +- .../contracts/test/TestNFTOrderPresigner.sol | 38 +- .../test/TestNativeOrdersFeature.sol | 4 +- ...tOrderSignerRegistryWithContractWallet.sol | 14 +- ...missionlessTransformerDeployerSuicidal.sol | 1 - ...sionlessTransformerDeployerTransformer.sol | 6 +- .../contracts/test/TestPropertyValidator.sol | 12 +- .../test/TestRfqOriginRegistration.sol | 4 +- ...TestSimpleFunctionRegistryFeatureImpl1.sol | 11 +- ...TestSimpleFunctionRegistryFeatureImpl2.sol | 11 +- .../zero-ex/contracts/test/TestStaking.sol | 5 +- .../contracts/test/TestTransformERC20.sol | 5 +- .../contracts/test/TestTransformerBase.sol | 14 +- .../TestTransformerDeployerTransformer.sol | 18 +- .../contracts/test/TestTransformerHost.sol | 15 +- .../contracts/test/TestUniswapV3Feature.sol | 5 +- .../test/TestWethTransformerHost.sol | 17 +- .../contracts/test/TestZeroExFeature.sol | 23 +- .../contracts/test/foundry/ContractTest.sol | 2 +- .../contracts/test/integration/TestCurve.sol | 32 +- .../integration/TestLiquidityProvider.sol | 44 +-- .../test/integration/TestMooniswap.sol | 16 +- .../test/integration/TestUniswapV2Factory.sol | 24 +- .../test/integration/TestUniswapV2Pool.sol | 21 +- .../test/integration/TestUniswapV3Factory.sol | 29 +- .../test/integration/TestUniswapV3Pool.sol | 30 +- .../test/tokens/TestMintableERC1155Token.sol | 112 ++---- .../test/tokens/TestMintableERC20Token.sol | 64 +-- .../test/tokens/TestMintableERC721Token.sol | 203 ++-------- .../tokens/TestTokenSpenderERC20Token.sol | 46 +-- .../contracts/test/tokens/TestWeth.sol | 19 +- contracts/zero-ex/test/artifacts.ts | 3 +- package.json | 5 +- yarn.lock | 34 ++ 288 files changed, 4198 insertions(+), 10059 deletions(-) diff --git a/.prettierignore b/.prettierignore index d9aa5a46df..5e3a4f1a7a 100644 --- a/.prettierignore +++ b/.prettierignore @@ -85,4 +85,3 @@ lib package.json packages/*/docs docs/ -*.sol diff --git a/.prettierrc b/.prettierrc index d1d79da835..c6ae6178cb 100644 --- a/.prettierrc +++ b/.prettierrc @@ -4,5 +4,17 @@ "singleQuote": true, "trailingComma": "all", "bracketSpacing": true, - "arrowParens": "avoid" + "arrowParens": "avoid", + "overrides": [ + { + "files": "**/*.sol", + "options": { + "printWidth": 120, + "tabWidth": 4, + "useTabs": false, + "singleQuote": false, + "bracketSpacing": false + } + } + ] } diff --git a/contracts/erc20/contracts/src/ERC20Token.sol b/contracts/erc20/contracts/src/ERC20Token.sol index 313bf1784d..32eb815454 100644 --- a/contracts/erc20/contracts/src/ERC20Token.sol +++ b/contracts/erc20/contracts/src/ERC20Token.sol @@ -20,12 +20,9 @@ pragma solidity ^0.5.9; import "./interfaces/IERC20Token.sol"; - -contract ERC20Token is - IERC20Token -{ - mapping (address => uint256) internal balances; - mapping (address => mapping (address => uint256)) internal allowed; +contract ERC20Token is IERC20Token { + mapping(address => uint256) internal balances; + mapping(address => mapping(address => uint256)) internal allowed; uint256 internal _totalSupply; @@ -33,27 +30,14 @@ contract ERC20Token is /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return True if transfer was successful - function transfer(address _to, uint256 _value) - external - returns (bool) - { - require( - balances[msg.sender] >= _value, - "ERC20_INSUFFICIENT_BALANCE" - ); - require( - balances[_to] + _value >= balances[_to], - "UINT256_OVERFLOW" - ); + function transfer(address _to, uint256 _value) external returns (bool) { + require(balances[msg.sender] >= _value, "ERC20_INSUFFICIENT_BALANCE"); + require(balances[_to] + _value >= balances[_to], "UINT256_OVERFLOW"); balances[msg.sender] -= _value; balances[_to] += _value; - emit Transfer( - msg.sender, - _to, - _value - ); + emit Transfer(msg.sender, _to, _value); return true; } @@ -67,32 +51,16 @@ contract ERC20Token is address _from, address _to, uint256 _value - ) - external - returns (bool) - { - require( - balances[_from] >= _value, - "ERC20_INSUFFICIENT_BALANCE" - ); - require( - allowed[_from][msg.sender] >= _value, - "ERC20_INSUFFICIENT_ALLOWANCE" - ); - require( - balances[_to] + _value >= balances[_to], - "UINT256_OVERFLOW" - ); + ) external returns (bool) { + require(balances[_from] >= _value, "ERC20_INSUFFICIENT_BALANCE"); + require(allowed[_from][msg.sender] >= _value, "ERC20_INSUFFICIENT_ALLOWANCE"); + require(balances[_to] + _value >= balances[_to], "UINT256_OVERFLOW"); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; - emit Transfer( - _from, - _to, - _value - ); + emit Transfer(_from, _to, _value); return true; } @@ -101,48 +69,29 @@ contract ERC20Token is /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution - function approve(address _spender, uint256 _value) - external - returns (bool) - { + function approve(address _spender, uint256 _value) external returns (bool) { allowed[msg.sender][_spender] = _value; - emit Approval( - msg.sender, - _spender, - _value - ); + emit Approval(msg.sender, _spender, _value); return true; } /// @dev Query total supply of token /// @return Total supply of token - function totalSupply() - external - view - returns (uint256) - { + function totalSupply() external view returns (uint256) { return _totalSupply; } /// @dev Query the balance of owner /// @param _owner The address from which the balance will be retrieved /// @return Balance of owner - function balanceOf(address _owner) - external - view - returns (uint256) - { + function balanceOf(address _owner) external view returns (uint256) { return balances[_owner]; } /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent - function allowance(address _owner, address _spender) - external - view - returns (uint256) - { + function allowance(address _owner, address _spender) external view returns (uint256) { return allowed[_owner][_spender]; } } diff --git a/contracts/erc20/contracts/src/LibERC20Token.sol b/contracts/erc20/contracts/src/LibERC20Token.sol index 651375c62b..6a04d92140 100644 --- a/contracts/erc20/contracts/src/LibERC20Token.sol +++ b/contracts/erc20/contracts/src/LibERC20Token.sol @@ -22,9 +22,8 @@ import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "@0x/contracts-utils/contracts/src/LibBytes.sol"; import "../src/interfaces/IERC20Token.sol"; - library LibERC20Token { - bytes constant private DECIMALS_CALL_DATA = hex"313ce567"; + bytes private constant DECIMALS_CALL_DATA = hex"313ce567"; /// @dev Calls `IERC20Token(token).approve()`. /// Reverts if `false` is returned or if the return @@ -36,14 +35,8 @@ library LibERC20Token { address token, address spender, uint256 allowance - ) - internal - { - bytes memory callData = abi.encodeWithSelector( - IERC20Token(0).approve.selector, - spender, - allowance - ); + ) internal { + bytes memory callData = abi.encodeWithSelector(IERC20Token(0).approve.selector, spender, allowance); _callWithOptionalBooleanResult(token, callData); } @@ -58,9 +51,7 @@ library LibERC20Token { address token, address spender, uint256 amount - ) - internal - { + ) internal { if (IERC20Token(token).allowance(address(this), spender) < amount) { approve(token, spender, uint256(-1)); } @@ -76,14 +67,8 @@ library LibERC20Token { address token, address to, uint256 amount - ) - internal - { - bytes memory callData = abi.encodeWithSelector( - IERC20Token(0).transfer.selector, - to, - amount - ); + ) internal { + bytes memory callData = abi.encodeWithSelector(IERC20Token(0).transfer.selector, to, amount); _callWithOptionalBooleanResult(token, callData); } @@ -99,15 +84,8 @@ library LibERC20Token { address from, address to, uint256 amount - ) - internal - { - bytes memory callData = abi.encodeWithSelector( - IERC20Token(0).transferFrom.selector, - from, - to, - amount - ); + ) internal { + bytes memory callData = abi.encodeWithSelector(IERC20Token(0).transferFrom.selector, from, to, amount); _callWithOptionalBooleanResult(token, callData); } @@ -115,11 +93,7 @@ library LibERC20Token { /// Returns `18` if the call reverts. /// @param token The address of the token contract. /// @return tokenDecimals The number of decimals places for the token. - function decimals(address token) - internal - view - returns (uint8 tokenDecimals) - { + function decimals(address token) internal view returns (uint8 tokenDecimals) { tokenDecimals = 18; (bool didSucceed, bytes memory resultData) = token.staticcall(DECIMALS_CALL_DATA); if (didSucceed && resultData.length == 32) { @@ -133,17 +107,13 @@ library LibERC20Token { /// @param owner The owner of the tokens. /// @param spender The address the spender. /// @return allowance The allowance for a token, owner, and spender. - function allowance(address token, address owner, address spender) - internal - view - returns (uint256 allowance_) - { + function allowance( + address token, + address owner, + address spender + ) internal view returns (uint256 allowance_) { (bool didSucceed, bytes memory resultData) = token.staticcall( - abi.encodeWithSelector( - IERC20Token(0).allowance.selector, - owner, - spender - ) + abi.encodeWithSelector(IERC20Token(0).allowance.selector, owner, spender) ); if (didSucceed && resultData.length == 32) { allowance_ = LibBytes.readUint256(resultData, 0); @@ -155,16 +125,9 @@ library LibERC20Token { /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @return balance The token balance of an owner. - function balanceOf(address token, address owner) - internal - view - returns (uint256 balance) - { + function balanceOf(address token, address owner) internal view returns (uint256 balance) { (bool didSucceed, bytes memory resultData) = token.staticcall( - abi.encodeWithSelector( - IERC20Token(0).balanceOf.selector, - owner - ) + abi.encodeWithSelector(IERC20Token(0).balanceOf.selector, owner) ); if (didSucceed && resultData.length == 32) { balance = LibBytes.readUint256(resultData, 0); @@ -176,12 +139,7 @@ library LibERC20Token { /// was returned equal to `true`. /// @param target The call target. /// @param callData The abi-encoded call data. - function _callWithOptionalBooleanResult( - address target, - bytes memory callData - ) - private - { + function _callWithOptionalBooleanResult(address target, bytes memory callData) private { (bool didSucceed, bytes memory resultData) = target.call(callData); if (didSucceed) { if (resultData.length == 0) { diff --git a/contracts/erc20/contracts/src/MintableERC20Token.sol b/contracts/erc20/contracts/src/MintableERC20Token.sol index fab2aac164..0a5c317652 100644 --- a/contracts/erc20/contracts/src/MintableERC20Token.sol +++ b/contracts/erc20/contracts/src/MintableERC20Token.sol @@ -21,41 +21,26 @@ pragma solidity ^0.5.9; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "./UnlimitedAllowanceERC20Token.sol"; - -contract MintableERC20Token is - UnlimitedAllowanceERC20Token -{ +contract MintableERC20Token is UnlimitedAllowanceERC20Token { using LibSafeMath for uint256; /// @dev Mints new tokens /// @param _to Address of the beneficiary that will own the minted token /// @param _value Amount of tokens to mint - function _mint(address _to, uint256 _value) - internal - { + function _mint(address _to, uint256 _value) internal { balances[_to] = _value.safeAdd(balances[_to]); _totalSupply = _totalSupply.safeAdd(_value); - emit Transfer( - address(0), - _to, - _value - ); + emit Transfer(address(0), _to, _value); } /// @dev Mints new tokens /// @param _owner Owner of tokens that will be burned /// @param _value Amount of tokens to burn - function _burn(address _owner, uint256 _value) - internal - { + function _burn(address _owner, uint256 _value) internal { balances[_owner] = balances[_owner].safeSub(_value); _totalSupply = _totalSupply.safeSub(_value); - emit Transfer( - _owner, - address(0), - _value - ); + emit Transfer(_owner, address(0), _value); } } diff --git a/contracts/erc20/contracts/src/UnlimitedAllowanceERC20Token.sol b/contracts/erc20/contracts/src/UnlimitedAllowanceERC20Token.sol index beb2d59c89..2f0a5037f1 100644 --- a/contracts/erc20/contracts/src/UnlimitedAllowanceERC20Token.sol +++ b/contracts/erc20/contracts/src/UnlimitedAllowanceERC20Token.sol @@ -20,11 +20,8 @@ pragma solidity ^0.5.9; import "./ERC20Token.sol"; - -contract UnlimitedAllowanceERC20Token is - ERC20Token -{ - uint256 constant internal MAX_UINT = 2**256 - 1; +contract UnlimitedAllowanceERC20Token is ERC20Token { + uint256 internal constant MAX_UINT = 2**256 - 1; /// @dev ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited allowance. See https://github.com/ethereum/EIPs/issues/717 /// @param _from Address to transfer from. @@ -35,23 +32,11 @@ contract UnlimitedAllowanceERC20Token is address _from, address _to, uint256 _value - ) - external - returns (bool) - { + ) external returns (bool) { uint256 allowance = allowed[_from][msg.sender]; - require( - balances[_from] >= _value, - "ERC20_INSUFFICIENT_BALANCE" - ); - require( - allowance >= _value, - "ERC20_INSUFFICIENT_ALLOWANCE" - ); - require( - balances[_to] + _value >= balances[_to], - "UINT256_OVERFLOW" - ); + require(balances[_from] >= _value, "ERC20_INSUFFICIENT_BALANCE"); + require(allowance >= _value, "ERC20_INSUFFICIENT_ALLOWANCE"); + require(balances[_to] + _value >= balances[_to], "UINT256_OVERFLOW"); balances[_to] += _value; balances[_from] -= _value; @@ -59,11 +44,7 @@ contract UnlimitedAllowanceERC20Token is allowed[_from][msg.sender] -= _value; } - emit Transfer( - _from, - _to, - _value - ); + emit Transfer(_from, _to, _value); return true; } diff --git a/contracts/erc20/contracts/src/WETH9.sol b/contracts/erc20/contracts/src/WETH9.sol index 4881ef6547..9b07bc5c5c 100644 --- a/contracts/erc20/contracts/src/WETH9.sol +++ b/contracts/erc20/contracts/src/WETH9.sol @@ -16,55 +16,57 @@ // solhint-disable pragma solidity ^0.5.9; - contract WETH9 { - string public name = "Wrapped Ether"; - string public symbol = "WETH"; - uint8 public decimals = 18; + string public name = "Wrapped Ether"; + string public symbol = "WETH"; + uint8 public decimals = 18; - event Approval(address indexed _owner, address indexed _spender, uint _value); - event Transfer(address indexed _from, address indexed _to, uint _value); - event Deposit(address indexed _owner, uint _value); - event Withdrawal(address indexed _owner, uint _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Deposit(address indexed _owner, uint256 _value); + event Withdrawal(address indexed _owner, uint256 _value); - mapping (address => uint) public balanceOf; - mapping (address => mapping (address => uint)) public allowance; + mapping(address => uint256) public balanceOf; + mapping(address => mapping(address => uint256)) public allowance; function() external payable { deposit(); } + function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } - function withdraw(uint wad) public { + + function withdraw(uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); emit Withdrawal(msg.sender, wad); } - function totalSupply() public view returns (uint) { + function totalSupply() public view returns (uint256) { return address(this).balance; } - function approve(address guy, uint wad) public returns (bool) { + function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } - function transfer(address dst, uint wad) public returns (bool) { + function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } - function transferFrom(address src, address dst, uint wad) - public - returns (bool) - { + function transferFrom( + address src, + address dst, + uint256 wad + ) public returns (bool) { require(balanceOf[src] >= wad); - if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { + if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } @@ -78,7 +80,6 @@ contract WETH9 { } } - /* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 diff --git a/contracts/erc20/contracts/src/ZRXToken.sol b/contracts/erc20/contracts/src/ZRXToken.sol index a5d5e21120..dc2f29191b 100644 --- a/contracts/erc20/contracts/src/ZRXToken.sol +++ b/contracts/erc20/contracts/src/ZRXToken.sol @@ -18,105 +18,111 @@ pragma solidity 0.4.11; - contract Token { - /// @return total amount of tokens - function totalSupply() constant returns (uint supply) {} + function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance - function balanceOf(address _owner) constant returns (uint balance) {} + function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not - function transfer(address _to, uint _value) returns (bool success) {} + function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not - function transferFrom(address _from, address _to, uint _value) returns (bool success) {} + function transferFrom( + address _from, + address _to, + uint256 _value + ) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not - function approve(address _spender, uint _value) returns (bool success) {} + function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent - function allowance(address _owner, address _spender) constant returns (uint remaining) {} + function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} - event Transfer(address indexed _from, address indexed _to, uint _value); - event Approval(address indexed _owner, address indexed _spender, uint _value); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); } - contract ERC20Token is Token { - - function transfer(address _to, uint _value) returns (bool) { + function transfer(address _to, uint256 _value) returns (bool) { //Default assumes totalSupply can't be over max (2^256 - 1). if (balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; - } else { return false; } + } else { + return false; + } } - function transferFrom(address _from, address _to, uint _value) returns (bool) { - if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value >= balances[_to]) { + function transferFrom( + address _from, + address _to, + uint256 _value + ) returns (bool) { + if ( + balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value >= balances[_to] + ) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; - } else { return false; } + } else { + return false; + } } - function balanceOf(address _owner) constant returns (uint) { + function balanceOf(address _owner) constant returns (uint256) { return balances[_owner]; } - function approve(address _spender, uint _value) returns (bool) { + function approve(address _spender, uint256 _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } - function allowance(address _owner, address _spender) constant returns (uint) { + function allowance(address _owner, address _spender) constant returns (uint256) { return allowed[_owner][_spender]; } - mapping (address => uint) balances; - mapping (address => mapping (address => uint)) allowed; - uint public totalSupply; + mapping(address => uint256) balances; + mapping(address => mapping(address => uint256)) allowed; + uint256 public totalSupply; } - contract UnlimitedAllowanceToken is ERC20Token { - - uint constant MAX_UINT = 2**256 - 1; + uint256 constant MAX_UINT = 2**256 - 1; /// @dev ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited allowance. /// @param _from Address to transfer from. /// @param _to Address to transfer to. /// @param _value Amount to transfer. /// @return Success of transfer. - function transferFrom(address _from, address _to, uint _value) - public - returns (bool) - { - uint allowance = allowed[_from][msg.sender]; - if (balances[_from] >= _value - && allowance >= _value - && balances[_to] + _value >= balances[_to] - ) { + function transferFrom( + address _from, + address _to, + uint256 _value + ) public returns (bool) { + uint256 allowance = allowed[_from][msg.sender]; + if (balances[_from] >= _value && allowance >= _value && balances[_to] + _value >= balances[_to]) { balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT) { @@ -130,21 +136,16 @@ contract UnlimitedAllowanceToken is ERC20Token { } } - -contract ZRXToken is - UnlimitedAllowanceToken -{ - +contract ZRXToken is UnlimitedAllowanceToken { // solhint-disable const-name-snakecase - uint8 constant public decimals = 18; + uint8 public constant decimals = 18; uint256 public totalSupply = 10**27; // 1 billion tokens, 18 decimal places - string constant public name = "0x Protocol Token"; - string constant public symbol = "ZRX"; + string public constant name = "0x Protocol Token"; + string public constant symbol = "ZRX"; + // solhint-enableconst-name-snakecase - function ZRXToken() - public - { + function ZRXToken() public { balances[msg.sender] = totalSupply; } } diff --git a/contracts/erc20/contracts/src/interfaces/IERC20Token.sol b/contracts/erc20/contracts/src/interfaces/IERC20Token.sol index e3ce453e29..56e7b12758 100644 --- a/contracts/erc20/contracts/src/interfaces/IERC20Token.sol +++ b/contracts/erc20/contracts/src/interfaces/IERC20Token.sol @@ -18,29 +18,17 @@ pragma solidity ^0.5.9; - contract IERC20Token { - // solhint-disable no-simple-event-func-name - event Transfer( - address indexed _from, - address indexed _to, - uint256 _value - ); + event Transfer(address indexed _from, address indexed _to, uint256 _value); - event Approval( - address indexed _owner, - address indexed _spender, - uint256 _value - ); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); /// @dev send `value` token to `to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return True if transfer was successful - function transfer(address _to, uint256 _value) - external - returns (bool); + function transfer(address _to, uint256 _value) external returns (bool); /// @dev send `value` token to `to` from `from` on the condition it is approved by `from` /// @param _from The address of the sender @@ -51,37 +39,24 @@ contract IERC20Token { address _from, address _to, uint256 _value - ) - external - returns (bool); + ) external returns (bool); /// @dev `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution - function approve(address _spender, uint256 _value) - external - returns (bool); + function approve(address _spender, uint256 _value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token - function totalSupply() - external - view - returns (uint256); + function totalSupply() external view returns (uint256); /// @param _owner The address from which the balance will be retrieved /// @return Balance of owner - function balanceOf(address _owner) - external - view - returns (uint256); + function balanceOf(address _owner) external view returns (uint256); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent - function allowance(address _owner, address _spender) - external - view - returns (uint256); + function allowance(address _owner, address _spender) external view returns (uint256); } diff --git a/contracts/erc20/contracts/src/interfaces/IEtherToken.sol b/contracts/erc20/contracts/src/interfaces/IEtherToken.sol index 12e39edb7d..e14b58e89b 100644 --- a/contracts/erc20/contracts/src/interfaces/IEtherToken.sol +++ b/contracts/erc20/contracts/src/interfaces/IEtherToken.sol @@ -20,14 +20,8 @@ pragma solidity ^0.5.9; import "./IERC20Token.sol"; +contract IEtherToken is IERC20Token { + function deposit() public payable; -contract IEtherToken is - IERC20Token -{ - function deposit() - public - payable; - - function withdraw(uint256 amount) - public; + function withdraw(uint256 amount) public; } diff --git a/contracts/erc20/contracts/src/v06/IERC20TokenV06.sol b/contracts/erc20/contracts/src/v06/IERC20TokenV06.sol index 09179e4745..d602e22f84 100644 --- a/contracts/erc20/contracts/src/v06/IERC20TokenV06.sol +++ b/contracts/erc20/contracts/src/v06/IERC20TokenV06.sol @@ -19,29 +19,17 @@ pragma solidity ^0.6.5; - interface IERC20TokenV06 { - // solhint-disable no-simple-event-func-name - event Transfer( - address indexed from, - address indexed to, - uint256 value - ); + event Transfer(address indexed from, address indexed to, uint256 value); - event Approval( - address indexed owner, - address indexed spender, - uint256 value - ); + event Approval(address indexed owner, address indexed spender, uint256 value); /// @dev send `value` token to `to` from `msg.sender` /// @param to The address of the recipient /// @param value The amount of token to be transferred /// @return True if transfer was successful - function transfer(address to, uint256 value) - external - returns (bool); + function transfer(address to, uint256 value) external returns (bool); /// @dev send `value` token to `to` from `from` on the condition it is approved by `from` /// @param from The address of the sender @@ -52,45 +40,29 @@ interface IERC20TokenV06 { address from, address to, uint256 value - ) - external - returns (bool); + ) external returns (bool); /// @dev `msg.sender` approves `spender` to spend `value` tokens /// @param spender The address of the account able to transfer the tokens /// @param value The amount of wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution - function approve(address spender, uint256 value) - external - returns (bool); + function approve(address spender, uint256 value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token - function totalSupply() - external - view - returns (uint256); + function totalSupply() external view returns (uint256); /// @dev Get the balance of `owner`. /// @param owner The address from which the balance will be retrieved /// @return Balance of owner - function balanceOf(address owner) - external - view - returns (uint256); + function balanceOf(address owner) external view returns (uint256); /// @dev Get the allowance for `spender` to spend from `owner`. /// @param owner The address of the account owning tokens /// @param spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent - function allowance(address owner, address spender) - external - view - returns (uint256); + function allowance(address owner, address spender) external view returns (uint256); /// @dev Get the number of decimals this token has. - function decimals() - external - view - returns (uint8); + function decimals() external view returns (uint8); } diff --git a/contracts/erc20/contracts/src/v06/IEtherTokenV06.sol b/contracts/erc20/contracts/src/v06/IEtherTokenV06.sol index a3d7dc9bbb..1ccc051541 100644 --- a/contracts/erc20/contracts/src/v06/IEtherTokenV06.sol +++ b/contracts/erc20/contracts/src/v06/IEtherTokenV06.sol @@ -21,10 +21,7 @@ pragma solidity ^0.6.5; import "./IERC20TokenV06.sol"; - -interface IEtherTokenV06 is - IERC20TokenV06 -{ +interface IEtherTokenV06 is IERC20TokenV06 { /// @dev Wrap ether. function deposit() external payable; diff --git a/contracts/erc20/contracts/src/v06/LibERC20TokenV06.sol b/contracts/erc20/contracts/src/v06/LibERC20TokenV06.sol index 13f0a1c7c1..de035d269a 100644 --- a/contracts/erc20/contracts/src/v06/LibERC20TokenV06.sol +++ b/contracts/erc20/contracts/src/v06/LibERC20TokenV06.sol @@ -23,9 +23,8 @@ import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol"; import "./IERC20TokenV06.sol"; - library LibERC20TokenV06 { - bytes constant private DECIMALS_CALL_DATA = hex"313ce567"; + bytes private constant DECIMALS_CALL_DATA = hex"313ce567"; /// @dev Calls `IERC20TokenV06(token).approve()`. /// Reverts if the return data is invalid or the call reverts. @@ -36,14 +35,8 @@ library LibERC20TokenV06 { IERC20TokenV06 token, address spender, uint256 allowance - ) - internal - { - bytes memory callData = abi.encodeWithSelector( - token.approve.selector, - spender, - allowance - ); + ) internal { + bytes memory callData = abi.encodeWithSelector(token.approve.selector, spender, allowance); _callWithOptionalBooleanResult(address(token), callData); } @@ -57,9 +50,7 @@ library LibERC20TokenV06 { IERC20TokenV06 token, address spender, uint256 amount - ) - internal - { + ) internal { if (token.allowance(address(this), spender) < amount) { compatApprove(token, spender, uint256(-1)); } @@ -74,14 +65,8 @@ library LibERC20TokenV06 { IERC20TokenV06 token, address to, uint256 amount - ) - internal - { - bytes memory callData = abi.encodeWithSelector( - token.transfer.selector, - to, - amount - ); + ) internal { + bytes memory callData = abi.encodeWithSelector(token.transfer.selector, to, amount); _callWithOptionalBooleanResult(address(token), callData); } @@ -96,15 +81,8 @@ library LibERC20TokenV06 { address from, address to, uint256 amount - ) - internal - { - bytes memory callData = abi.encodeWithSelector( - token.transferFrom.selector, - from, - to, - amount - ); + ) internal { + bytes memory callData = abi.encodeWithSelector(token.transferFrom.selector, from, to, amount); _callWithOptionalBooleanResult(address(token), callData); } @@ -112,11 +90,7 @@ library LibERC20TokenV06 { /// Returns `18` if the call reverts. /// @param token The address of the token contract. /// @return tokenDecimals The number of decimals places for the token. - function compatDecimals(IERC20TokenV06 token) - internal - view - returns (uint8 tokenDecimals) - { + function compatDecimals(IERC20TokenV06 token) internal view returns (uint8 tokenDecimals) { tokenDecimals = 18; (bool didSucceed, bytes memory resultData) = address(token).staticcall(DECIMALS_CALL_DATA); if (didSucceed && resultData.length >= 32) { @@ -130,17 +104,13 @@ library LibERC20TokenV06 { /// @param owner The owner of the tokens. /// @param spender The address the spender. /// @return allowance_ The allowance for a token, owner, and spender. - function compatAllowance(IERC20TokenV06 token, address owner, address spender) - internal - view - returns (uint256 allowance_) - { + function compatAllowance( + IERC20TokenV06 token, + address owner, + address spender + ) internal view returns (uint256 allowance_) { (bool didSucceed, bytes memory resultData) = address(token).staticcall( - abi.encodeWithSelector( - token.allowance.selector, - owner, - spender - ) + abi.encodeWithSelector(token.allowance.selector, owner, spender) ); if (didSucceed && resultData.length >= 32) { allowance_ = LibBytesV06.readUint256(resultData, 0); @@ -152,16 +122,9 @@ library LibERC20TokenV06 { /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @return balance The token balance of an owner. - function compatBalanceOf(IERC20TokenV06 token, address owner) - internal - view - returns (uint256 balance) - { + function compatBalanceOf(IERC20TokenV06 token, address owner) internal view returns (uint256 balance) { (bool didSucceed, bytes memory resultData) = address(token).staticcall( - abi.encodeWithSelector( - token.balanceOf.selector, - owner - ) + abi.encodeWithSelector(token.balanceOf.selector, owner) ); if (didSucceed && resultData.length >= 32) { balance = LibBytesV06.readUint256(resultData, 0); @@ -173,12 +136,7 @@ library LibERC20TokenV06 { /// was returned equal to `true`. /// @param target The call target. /// @param callData The abi-encoded call data. - function _callWithOptionalBooleanResult( - address target, - bytes memory callData - ) - private - { + function _callWithOptionalBooleanResult(address target, bytes memory callData) private { (bool didSucceed, bytes memory resultData) = target.call(callData); // Revert if the call reverted. if (!didSucceed) { @@ -188,7 +146,9 @@ library LibERC20TokenV06 { // does not return a boolean. Check that it at least contains code. if (resultData.length == 0) { uint256 size; - assembly { size := extcodesize(target) } + assembly { + size := extcodesize(target) + } require(size > 0, "invalid token address, contains no code"); return; } diff --git a/contracts/erc20/contracts/test/DummyERC20Token.sol b/contracts/erc20/contracts/test/DummyERC20Token.sol index be39ac3048..4f8287cce4 100644 --- a/contracts/erc20/contracts/test/DummyERC20Token.sol +++ b/contracts/erc20/contracts/test/DummyERC20Token.sol @@ -22,11 +22,7 @@ import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "@0x/contracts-utils/contracts/src/Ownable.sol"; import "../src/MintableERC20Token.sol"; - -contract DummyERC20Token is - Ownable, - MintableERC20Token -{ +contract DummyERC20Token is Ownable, MintableERC20Token { using LibSafeMath for uint256; string public name; @@ -34,14 +30,12 @@ contract DummyERC20Token is uint256 public decimals; uint256 public constant MAX_MINT_AMOUNT = 10000000000000000000000; - constructor ( + constructor( string memory _name, string memory _symbol, uint256 _decimals, uint256 _totalSupply - ) - public - { + ) public { name = _name; symbol = _symbol; decimals = _decimals; @@ -52,10 +46,7 @@ contract DummyERC20Token is /// @dev Sets the balance of target address /// @param _target Address or which balance will be updated /// @param _value New balance of target address - function setBalance(address _target, uint256 _value) - external - onlyOwner - { + function setBalance(address _target, uint256 _value) external onlyOwner { uint256 currBalance = balances[_target]; if (_value < currBalance) { _totalSupply = _totalSupply.safeSub(currBalance.safeSub(_value)); @@ -67,13 +58,8 @@ contract DummyERC20Token is /// @dev Mints new tokens for sender /// @param _value Amount of tokens to mint - function mint(uint256 _value) - external - { - require( - _value <= MAX_MINT_AMOUNT, - "VALUE_TOO_LARGE" - ); + function mint(uint256 _value) external { + require(_value <= MAX_MINT_AMOUNT, "VALUE_TOO_LARGE"); _mint(msg.sender, _value); } diff --git a/contracts/erc20/contracts/test/DummyMultipleReturnERC20Token.sol b/contracts/erc20/contracts/test/DummyMultipleReturnERC20Token.sol index 2b60837c57..f478f37bb2 100644 --- a/contracts/erc20/contracts/test/DummyMultipleReturnERC20Token.sol +++ b/contracts/erc20/contracts/test/DummyMultipleReturnERC20Token.sol @@ -20,25 +20,14 @@ pragma solidity ^0.5.5; import "./DummyERC20Token.sol"; - // solhint-disable no-empty-blocks -contract DummyMultipleReturnERC20Token is - DummyERC20Token -{ - constructor ( +contract DummyMultipleReturnERC20Token is DummyERC20Token { + constructor( string memory _name, string memory _symbol, uint256 _decimals, uint256 _totalSupply - ) - public - DummyERC20Token( - _name, - _symbol, - _decimals, - _totalSupply - ) - {} + ) public DummyERC20Token(_name, _symbol, _decimals, _totalSupply) {} /// @dev send `value` token to `to` from `from` on the condition it is approved by `from` /// @param _from The address of the sender @@ -48,15 +37,8 @@ contract DummyMultipleReturnERC20Token is address _from, address _to, uint256 _value - ) - external - returns (bool) - { - emit Transfer( - _from, - _to, - _value - ); + ) external returns (bool) { + emit Transfer(_from, _to, _value); // HACK: This contract will not compile if we remove `returns (bool)`, so we manually return 64 bytes (equiavalent to true, true) assembly { @@ -66,4 +48,3 @@ contract DummyMultipleReturnERC20Token is } } } - diff --git a/contracts/erc20/contracts/test/DummyNoReturnERC20Token.sol b/contracts/erc20/contracts/test/DummyNoReturnERC20Token.sol index 39ae64ac33..47dedefbb2 100644 --- a/contracts/erc20/contracts/test/DummyNoReturnERC20Token.sol +++ b/contracts/erc20/contracts/test/DummyNoReturnERC20Token.sol @@ -20,50 +20,26 @@ pragma solidity ^0.5.5; import "./DummyERC20Token.sol"; - // solhint-disable no-empty-blocks -contract DummyNoReturnERC20Token is - DummyERC20Token -{ - constructor ( +contract DummyNoReturnERC20Token is DummyERC20Token { + constructor( string memory _name, string memory _symbol, uint256 _decimals, uint256 _totalSupply - ) - public - DummyERC20Token( - _name, - _symbol, - _decimals, - _totalSupply - ) - {} + ) public DummyERC20Token(_name, _symbol, _decimals, _totalSupply) {} /// @dev send `value` token to `to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred - function transfer(address _to, uint256 _value) - external - returns (bool) - { - require( - balances[msg.sender] >= _value, - "ERC20_INSUFFICIENT_BALANCE" - ); - require( - balances[_to] + _value >= balances[_to], - "UINT256_OVERFLOW" - ); + function transfer(address _to, uint256 _value) external returns (bool) { + require(balances[msg.sender] >= _value, "ERC20_INSUFFICIENT_BALANCE"); + require(balances[_to] + _value >= balances[_to], "UINT256_OVERFLOW"); balances[msg.sender] -= _value; balances[_to] += _value; - emit Transfer( - msg.sender, - _to, - _value - ); + emit Transfer(msg.sender, _to, _value); // HACK: This contract will not compile if we remove `returns (bool)`, so we manually return no data assembly { @@ -79,32 +55,16 @@ contract DummyNoReturnERC20Token is address _from, address _to, uint256 _value - ) - external - returns (bool) - { - require( - balances[_from] >= _value, - "ERC20_INSUFFICIENT_BALANCE" - ); - require( - allowed[_from][msg.sender] >= _value, - "ERC20_INSUFFICIENT_ALLOWANCE" - ); - require( - balances[_to] + _value >= balances[_to], - "UINT256_OVERFLOW" - ); + ) external returns (bool) { + require(balances[_from] >= _value, "ERC20_INSUFFICIENT_BALANCE"); + require(allowed[_from][msg.sender] >= _value, "ERC20_INSUFFICIENT_ALLOWANCE"); + require(balances[_to] + _value >= balances[_to], "UINT256_OVERFLOW"); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; - - emit Transfer( - _from, - _to, - _value - ); + + emit Transfer(_from, _to, _value); // HACK: This contract will not compile if we remove `returns (bool)`, so we manually return no data assembly { @@ -112,4 +72,3 @@ contract DummyNoReturnERC20Token is } } } - diff --git a/contracts/erc20/contracts/test/TestLibERC20Token.sol b/contracts/erc20/contracts/test/TestLibERC20Token.sol index bf64255209..edb02dea02 100644 --- a/contracts/erc20/contracts/test/TestLibERC20Token.sol +++ b/contracts/erc20/contracts/test/TestLibERC20Token.sol @@ -21,9 +21,7 @@ pragma solidity ^0.5.9; import "../src/LibERC20Token.sol"; import "./TestLibERC20TokenTarget.sol"; - contract TestLibERC20Token { - TestLibERC20TokenTarget public target; constructor() public { @@ -36,9 +34,7 @@ contract TestLibERC20Token { bytes calldata returnData, address spender, uint256 allowance - ) - external - { + ) external { target.setBehavior(shouldRevert, revertData, returnData); LibERC20Token.approve(address(target), spender, allowance); } @@ -49,9 +45,7 @@ contract TestLibERC20Token { bytes calldata returnData, address to, uint256 amount - ) - external - { + ) external { target.setBehavior(shouldRevert, revertData, returnData); LibERC20Token.transfer(address(target), to, amount); } @@ -63,9 +57,7 @@ contract TestLibERC20Token { address from, address to, uint256 amount - ) - external - { + ) external { target.setBehavior(shouldRevert, revertData, returnData); LibERC20Token.transferFrom(address(target), from, to, amount); } @@ -74,10 +66,7 @@ contract TestLibERC20Token { bool shouldRevert, bytes calldata revertData, bytes calldata returnData - ) - external - returns (uint8) - { + ) external returns (uint8) { target.setBehavior(shouldRevert, revertData, returnData); return LibERC20Token.decimals(address(target)); } diff --git a/contracts/erc20/contracts/test/TestLibERC20TokenTarget.sol b/contracts/erc20/contracts/test/TestLibERC20TokenTarget.sol index b8a14f1001..5d8cd2645b 100644 --- a/contracts/erc20/contracts/test/TestLibERC20TokenTarget.sol +++ b/contracts/erc20/contracts/test/TestLibERC20TokenTarget.sol @@ -18,24 +18,12 @@ pragma solidity ^0.5.9; - contract TestLibERC20TokenTarget { + event ApproveCalled(address spender, uint256 allowance); - event ApproveCalled( - address spender, - uint256 allowance - ); + event TransferCalled(address to, uint256 amount); - event TransferCalled( - address to, - uint256 amount - ); - - event TransferFromCalled( - address from, - address to, - uint256 amount - ); + event TransferFromCalled(address from, address to, uint256 amount); bool private _shouldRevert; bytes private _revertData; @@ -45,32 +33,18 @@ contract TestLibERC20TokenTarget { bool shouldRevert, bytes calldata revertData, bytes calldata returnData - ) - external - { + ) external { _shouldRevert = shouldRevert; _revertData = revertData; _returnData = returnData; } - function approve( - address spender, - uint256 allowance - ) - external - returns (bool) - { + function approve(address spender, uint256 allowance) external returns (bool) { emit ApproveCalled(spender, allowance); _execute(); } - function transfer( - address to, - uint256 amount - ) - external - returns (bool) - { + function transfer(address to, uint256 amount) external returns (bool) { emit TransferCalled(to, amount); _execute(); } @@ -79,28 +53,25 @@ contract TestLibERC20TokenTarget { address from, address to, uint256 amount - ) - external - returns (bool) - { + ) external returns (bool) { emit TransferFromCalled(from, to, amount); _execute(); } - function decimals() - external - view - returns (uint8) - { + function decimals() external view returns (uint8) { _execute(); } function _execute() private view { if (_shouldRevert) { bytes memory revertData = _revertData; - assembly { revert(add(revertData, 0x20), mload(revertData)) } + assembly { + revert(add(revertData, 0x20), mload(revertData)) + } } bytes memory returnData = _returnData; - assembly { return(add(returnData, 0x20), mload(returnData)) } + assembly { + return(add(returnData, 0x20), mload(returnData)) + } } } diff --git a/contracts/erc20/contracts/test/UntransferrableDummyERC20Token.sol b/contracts/erc20/contracts/test/UntransferrableDummyERC20Token.sol index 250034a8f0..0fb5d3cf3c 100644 --- a/contracts/erc20/contracts/test/UntransferrableDummyERC20Token.sol +++ b/contracts/erc20/contracts/test/UntransferrableDummyERC20Token.sol @@ -20,26 +20,15 @@ pragma solidity ^0.5.5; import "./DummyERC20Token.sol"; - // solhint-disable no-empty-blocks // solhint-disable no-unused-vars -contract UntransferrableDummyERC20Token is - DummyERC20Token -{ - constructor ( +contract UntransferrableDummyERC20Token is DummyERC20Token { + constructor( string memory _name, string memory _symbol, uint256 _decimals, uint256 _totalSupply - ) - public - DummyERC20Token( - _name, - _symbol, - _decimals, - _totalSupply - ) - {} + ) public DummyERC20Token(_name, _symbol, _decimals, _totalSupply) {} /// @dev send `value` token to `to` from `from` on the condition it is approved by `from` /// @param _from The address of the sender @@ -49,14 +38,7 @@ contract UntransferrableDummyERC20Token is address _from, address _to, uint256 _value - ) - external - returns (bool) - { - require( - false, - "TRANSFER_DISABLED" - ); + ) external returns (bool) { + require(false, "TRANSFER_DISABLED"); } } - diff --git a/contracts/erc20/src/artifacts.ts b/contracts/erc20/src/artifacts.ts index 58950e0e05..d8339aaafb 100644 --- a/contracts/erc20/src/artifacts.ts +++ b/contracts/erc20/src/artifacts.ts @@ -15,7 +15,7 @@ export const artifacts = { DummyERC20Token: DummyERC20Token as ContractArtifact, ERC20Token: ERC20Token as ContractArtifact, WETH9: WETH9 as ContractArtifact, - ZRXToken: (ZRXToken as any) as ContractArtifact, + ZRXToken: ZRXToken as any as ContractArtifact, DummyNoReturnERC20Token: DummyNoReturnERC20Token as ContractArtifact, DummyMultipleReturnERC20Token: DummyMultipleReturnERC20Token as ContractArtifact, }; diff --git a/contracts/erc20/test/artifacts.ts b/contracts/erc20/test/artifacts.ts index a7249ae38a..54624be41f 100644 --- a/contracts/erc20/test/artifacts.ts +++ b/contracts/erc20/test/artifacts.ts @@ -28,7 +28,7 @@ export const artifacts = { MintableERC20Token: MintableERC20Token as ContractArtifact, UnlimitedAllowanceERC20Token: UnlimitedAllowanceERC20Token as ContractArtifact, WETH9: WETH9 as ContractArtifact, - ZRXToken: (ZRXToken as any) as ContractArtifact, + ZRXToken: ZRXToken as any as ContractArtifact, IERC20Token: IERC20Token as ContractArtifact, IEtherToken: IEtherToken as ContractArtifact, IERC20TokenV06: IERC20TokenV06 as ContractArtifact, diff --git a/contracts/treasury/contracts/external/ISablier.sol b/contracts/treasury/contracts/external/ISablier.sol index 632db17576..181850c5d0 100644 --- a/contracts/treasury/contracts/external/ISablier.sol +++ b/contracts/treasury/contracts/external/ISablier.sol @@ -50,11 +50,15 @@ interface ISablier { uint256 ratePerSecond ); - function createStream(address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime) - external - returns (uint256 streamId); + function createStream( + address recipient, + uint256 deposit, + address tokenAddress, + uint256 startTime, + uint256 stopTime + ) external returns (uint256 streamId); function withdrawFromStream(uint256 streamId, uint256 funds) external returns (bool); function cancelStream(uint256 streamId) external returns (bool); -} \ No newline at end of file +} diff --git a/contracts/treasury/contracts/src/DefaultPoolOperator.sol b/contracts/treasury/contracts/src/DefaultPoolOperator.sol index c97f856800..5e98d600e7 100644 --- a/contracts/treasury/contracts/src/DefaultPoolOperator.sol +++ b/contracts/treasury/contracts/src/DefaultPoolOperator.sol @@ -23,7 +23,6 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "./IStaking.sol"; - contract DefaultPoolOperator { // Immutables IStaking public immutable stakingProxy; @@ -33,16 +32,11 @@ contract DefaultPoolOperator { /// @dev Initializes this contract and creates a staking pool. /// @param stakingProxy_ The 0x staking proxy contract. /// @param weth_ The WETH token contract. - constructor( - IStaking stakingProxy_, - IERC20TokenV06 weth_ - ) - public - { + constructor(IStaking stakingProxy_, IERC20TokenV06 weth_) public { stakingProxy = stakingProxy_; weth = weth_; // operator share = 100% - poolId = stakingProxy_.createStakingPool(10 ** 6, false); + poolId = stakingProxy_.createStakingPool(10**6, false); } /// @dev Sends this contract's entire WETH balance to the @@ -51,9 +45,7 @@ contract DefaultPoolOperator { /// market making for some reason, thus earning this contract /// some staking rewards. Note that anyone can call this /// function at any time. - function returnStakingRewards() - external - { + function returnStakingRewards() external { uint256 wethBalance = weth.balanceOf(address(this)); weth.transfer(address(stakingProxy), wethBalance); } diff --git a/contracts/treasury/contracts/src/IStaking.sol b/contracts/treasury/contracts/src/IStaking.sol index 37ed738fd9..ad003f6852 100644 --- a/contracts/treasury/contracts/src/IStaking.sol +++ b/contracts/treasury/contracts/src/IStaking.sol @@ -20,7 +20,6 @@ pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; - interface IStaking { /// @dev Statuses that stake can exist in. /// Any stake can be (re)delegated effective at the next epoch @@ -55,54 +54,34 @@ interface IStaking { /// @param operatorShare Portion of rewards owned by the operator, in ppm. /// @param addOperatorAsMaker Adds operator to the created pool as a maker for convenience iff true. /// @return poolId The unique pool id generated for this pool. - function createStakingPool(uint32 operatorShare, bool addOperatorAsMaker) - external - returns (bytes32 poolId); + function createStakingPool(uint32 operatorShare, bool addOperatorAsMaker) external returns (bytes32 poolId); /// @dev Returns the current staking epoch number. /// @return epoch The current epoch. - function currentEpoch() - external - view - returns (uint256 epoch); + function currentEpoch() external view returns (uint256 epoch); /// @dev Returns the time (in seconds) at which the current staking epoch started. /// @return startTime The start time of the current epoch, in seconds. - function currentEpochStartTimeInSeconds() - external - view - returns (uint256 startTime); + function currentEpochStartTimeInSeconds() external view returns (uint256 startTime); /// @dev Returns the duration of an epoch in seconds. This value can be updated. /// @return duration The duration of an epoch, in seconds. - function epochDurationInSeconds() - external - view - returns (uint256 duration); + function epochDurationInSeconds() external view returns (uint256 duration); /// @dev Returns a staking pool /// @param poolId Unique id of pool. - function getStakingPool(bytes32 poolId) - external - view - returns (Pool memory); + function getStakingPool(bytes32 poolId) external view returns (Pool memory); /// @dev Gets global stake for a given status. /// @param stakeStatus UNDELEGATED or DELEGATED /// @return balance Global stake for given status. - function getGlobalStakeByStatus(StakeStatus stakeStatus) - external - view - returns (StoredBalance memory balance); + function getGlobalStakeByStatus(StakeStatus stakeStatus) external view returns (StoredBalance memory balance); /// @dev Gets an owner's stake balances by status. /// @param staker Owner of stake. /// @param stakeStatus UNDELEGATED or DELEGATED /// @return balance Owner's stake balances for given status. - function getOwnerStakeByStatus( - address staker, - StakeStatus stakeStatus - ) + function getOwnerStakeByStatus(address staker, StakeStatus stakeStatus) external view returns (StoredBalance memory balance); @@ -111,10 +90,7 @@ interface IStaking { /// across all members. /// @param poolId Unique Id of pool. /// @return balance Total stake delegated to pool. - function getTotalStakeDelegatedToPool(bytes32 poolId) - external - view - returns (StoredBalance memory balance); + function getTotalStakeDelegatedToPool(bytes32 poolId) external view returns (StoredBalance memory balance); /// @dev Returns the stake delegated to a specific staking pool, by a given staker. /// @param staker of stake. diff --git a/contracts/treasury/contracts/src/IZrxTreasury.sol b/contracts/treasury/contracts/src/IZrxTreasury.sol index f0590a16a2..8321ece159 100644 --- a/contracts/treasury/contracts/src/IZrxTreasury.sol +++ b/contracts/treasury/contracts/src/IZrxTreasury.sol @@ -23,9 +23,7 @@ pragma experimental ABIEncoderV2; import "./DefaultPoolOperator.sol"; import "./IStaking.sol"; - interface IZrxTreasury { - struct TreasuryParameters { uint256 votingPeriod; uint256 proposalThreshold; @@ -57,45 +55,21 @@ interface IZrxTreasury { string description ); - event VoteCast( - address voter, - bytes32[] operatedPoolIds, - uint256 proposalId, - bool support, - uint256 votingPower - ); + event VoteCast(address voter, bytes32[] operatedPoolIds, uint256 proposalId, bool support, uint256 votingPower); event ProposalExecuted(uint256 proposalId); - function stakingProxy() - external - view - returns (IStaking); + function stakingProxy() external view returns (IStaking); - function defaultPoolOperator() - external - view - returns (DefaultPoolOperator); + function defaultPoolOperator() external view returns (DefaultPoolOperator); - function defaultPoolId() - external - view - returns (bytes32); + function defaultPoolId() external view returns (bytes32); - function votingPeriod() - external - view - returns (uint256); + function votingPeriod() external view returns (uint256); - function proposalThreshold() - external - view - returns (uint256); + function proposalThreshold() external view returns (uint256); - function quorumThreshold() - external - view - returns (uint256); + function quorumThreshold() external view returns (uint256); /// @dev Updates the proposal and quorum thresholds to the given /// values. Note that this function is only callable by the @@ -103,11 +77,7 @@ interface IZrxTreasury { /// updated via a successful treasury proposal. /// @param newProposalThreshold The new value for the proposal threshold. /// @param newQuorumThreshold The new value for the quorum threshold. - function updateThresholds( - uint256 newProposalThreshold, - uint256 newQuorumThreshold - ) - external; + function updateThresholds(uint256 newProposalThreshold, uint256 newQuorumThreshold) external; /// @dev Creates a proposal to send ZRX from this treasury on the /// the given actions. Must have at least `proposalThreshold` @@ -131,9 +101,7 @@ interface IZrxTreasury { uint256 executionEpoch, string calldata description, bytes32[] calldata operatedPoolIds - ) - external - returns (uint256 proposalId); + ) external returns (uint256 proposalId); /// @dev Casts a vote for the given proposal. Only callable /// during the voting period for that proposal. @@ -148,8 +116,7 @@ interface IZrxTreasury { uint256 proposalId, bool support, bytes32[] calldata operatedPoolIds - ) - external; + ) external; /// @dev Casts a vote for the given proposal, by signature. /// Only callable during the voting period for that proposal. @@ -170,23 +137,17 @@ interface IZrxTreasury { uint8 v, bytes32 r, bytes32 s - ) - external; + ) external; /// @dev Executes a proposal that has passed and is /// currently executable. /// @param proposalId The ID of the proposal to execute. /// @param actions Actions associated with the proposal to execute. - function execute(uint256 proposalId, ProposedAction[] memory actions) - external - payable; + function execute(uint256 proposalId, ProposedAction[] memory actions) external payable; /// @dev Returns the total number of proposals. /// @return count The number of proposals. - function proposalCount() - external - view - returns (uint256 count); + function proposalCount() external view returns (uint256 count); /// @dev Computes the current voting power of the given account. /// Voting power is equal to: diff --git a/contracts/treasury/contracts/src/ZrxTreasury.sol b/contracts/treasury/contracts/src/ZrxTreasury.sol index b969639127..10cdc72641 100644 --- a/contracts/treasury/contracts/src/ZrxTreasury.sol +++ b/contracts/treasury/contracts/src/ZrxTreasury.sol @@ -26,10 +26,7 @@ import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-zero-ex/contracts/src/features/libs/LibSignature.sol"; import "./IZrxTreasury.sol"; - -contract ZrxTreasury is - IZrxTreasury -{ +contract ZrxTreasury is IZrxTreasury { using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; using LibBytesV06 for bytes; @@ -41,10 +38,12 @@ contract ZrxTreasury is string private constant CONTRACT_VERSION = "1.0.0"; /// The EIP-712 typehash for the contract's domain - bytes32 private constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); + bytes32 private constant DOMAIN_TYPEHASH = + keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /// The EIP-712 typehash for the vote struct - bytes32 private constant VOTE_TYPEHASH = keccak256("TreasuryVote(uint256 proposalId,bool support,bytes32[] operatedPoolIds)"); + bytes32 private constant VOTE_TYPEHASH = + keccak256("TreasuryVote(uint256 proposalId,bool support,bytes32[] operatedPoolIds)"); // Immutables IStaking public immutable override stakingProxy; @@ -58,22 +57,14 @@ contract ZrxTreasury is // Storage Proposal[] public proposals; - mapping (uint256 => mapping (address => bool)) public hasVoted; + mapping(uint256 => mapping(address => bool)) public hasVoted; /// @dev Initializes the ZRX treasury and creates the default /// staking pool. /// @param stakingProxy_ The 0x staking proxy contract. /// @param params Immutable treasury parameters. - constructor( - IStaking stakingProxy_, - TreasuryParameters memory params - ) - public - { - require( - params.votingPeriod < stakingProxy_.epochDurationInSeconds(), - "VOTING_PERIOD_TOO_LONG" - ); + constructor(IStaking stakingProxy_, TreasuryParameters memory params) public { + require(params.votingPeriod < stakingProxy_.epochDurationInSeconds(), "VOTING_PERIOD_TOO_LONG"); stakingProxy = stakingProxy_; votingPeriod = params.votingPeriod; proposalThreshold = params.proposalThreshold; @@ -95,6 +86,7 @@ contract ZrxTreasury is // solhint-disable /// @dev Allows this contract to receive ether. receive() external payable {} + // solhint-enable /// @dev Updates the proposal and quorum thresholds to the given @@ -103,13 +95,7 @@ contract ZrxTreasury is /// updated via a successful treasury proposal. /// @param newProposalThreshold The new value for the proposal threshold. /// @param newQuorumThreshold The new value for the quorum threshold. - function updateThresholds( - uint256 newProposalThreshold, - uint256 newQuorumThreshold - ) - external - override - { + function updateThresholds(uint256 newProposalThreshold, uint256 newQuorumThreshold) external override { require(msg.sender == address(this), "updateThresholds/ONLY_SELF"); proposalThreshold = newProposalThreshold; quorumThreshold = newQuorumThreshold; @@ -137,24 +123,11 @@ contract ZrxTreasury is uint256 executionEpoch, string memory description, bytes32[] memory operatedPoolIds - ) - public - override - returns (uint256 proposalId) - { - require( - getVotingPower(msg.sender, operatedPoolIds) >= proposalThreshold, - "propose/INSUFFICIENT_VOTING_POWER" - ); - require( - actions.length > 0, - "propose/NO_ACTIONS_PROPOSED" - ); + ) public override returns (uint256 proposalId) { + require(getVotingPower(msg.sender, operatedPoolIds) >= proposalThreshold, "propose/INSUFFICIENT_VOTING_POWER"); + require(actions.length > 0, "propose/NO_ACTIONS_PROPOSED"); uint256 currentEpoch = stakingProxy.currentEpoch(); - require( - executionEpoch >= currentEpoch + 2, - "propose/INVALID_EXECUTION_EPOCH" - ); + require(executionEpoch >= currentEpoch + 2, "propose/INVALID_EXECUTION_EPOCH"); proposalId = proposalCount(); Proposal storage newProposal = proposals.push(); @@ -162,14 +135,7 @@ contract ZrxTreasury is newProposal.executionEpoch = executionEpoch; newProposal.voteEpoch = currentEpoch + 2; - emit ProposalCreated( - msg.sender, - operatedPoolIds, - proposalId, - actions, - executionEpoch, - description - ); + emit ProposalCreated(msg.sender, operatedPoolIds, proposalId, actions, executionEpoch, description); } /// @dev Casts a vote for the given proposal. Only callable @@ -185,10 +151,7 @@ contract ZrxTreasury is uint256 proposalId, bool support, bytes32[] memory operatedPoolIds - ) - public - override - { + ) public override { return _castVote(msg.sender, proposalId, support, operatedPoolIds); } @@ -211,10 +174,7 @@ contract ZrxTreasury is uint8 v, bytes32 r, bytes32 s - ) - public - override - { + ) public override { bytes32 structHash = keccak256( abi.encode(VOTE_TYPEHASH, proposalId, support, keccak256(abi.encodePacked(operatedPoolIds))) ); @@ -228,11 +188,7 @@ contract ZrxTreasury is /// currently executable. /// @param proposalId The ID of the proposal to execute. /// @param actions Actions associated with the proposal to execute. - function execute(uint256 proposalId, ProposedAction[] memory actions) - public - payable - override - { + function execute(uint256 proposalId, ProposedAction[] memory actions) public payable override { if (proposalId >= proposalCount()) { revert("execute/INVALID_PROPOSAL_ID"); } @@ -244,10 +200,7 @@ contract ZrxTreasury is for (uint256 i = 0; i != actions.length; i++) { ProposedAction memory action = actions[i]; (bool didSucceed, ) = action.target.call{value: action.value}(action.data); - require( - didSucceed, - "execute/ACTION_EXECUTION_FAILED" - ); + require(didSucceed, "execute/ACTION_EXECUTION_FAILED"); } emit ProposalExecuted(proposalId); @@ -255,12 +208,7 @@ contract ZrxTreasury is /// @dev Returns the total number of proposals. /// @return count The number of proposals. - function proposalCount() - public - override - view - returns (uint256 count) - { + function proposalCount() public view override returns (uint256 count) { return proposals.length; } @@ -276,39 +224,29 @@ contract ZrxTreasury is /// @return votingPower The current voting power of the given account. function getVotingPower(address account, bytes32[] memory operatedPoolIds) public - override view + override returns (uint256 votingPower) { - uint256 delegatedBalance = stakingProxy.getOwnerStakeByStatus( - account, - IStaking.StakeStatus.DELEGATED - ).currentEpochBalance; - uint256 balanceDelegatedToDefaultPool = stakingProxy.getStakeDelegatedToPoolByOwner( - account, - defaultPoolId - ).currentEpochBalance; + uint256 delegatedBalance = stakingProxy + .getOwnerStakeByStatus(account, IStaking.StakeStatus.DELEGATED) + .currentEpochBalance; + uint256 balanceDelegatedToDefaultPool = stakingProxy + .getStakeDelegatedToPoolByOwner(account, defaultPoolId) + .currentEpochBalance; // Voting power for ZRX delegated to the default pool is not diluted, // so we double-count the balance delegated to the default pool before // dividing by 2. - votingPower = delegatedBalance - .safeAdd(balanceDelegatedToDefaultPool) - .safeDiv(2); + votingPower = delegatedBalance.safeAdd(balanceDelegatedToDefaultPool).safeDiv(2); // Add voting power for operated staking pools. for (uint256 i = 0; i != operatedPoolIds.length; i++) { for (uint256 j = 0; j != i; j++) { - require( - operatedPoolIds[i] != operatedPoolIds[j], - "getVotingPower/DUPLICATE_POOL_ID" - ); + require(operatedPoolIds[i] != operatedPoolIds[j], "getVotingPower/DUPLICATE_POOL_ID"); } IStaking.Pool memory pool = stakingProxy.getStakingPool(operatedPoolIds[i]); - require( - pool.operator == account, - "getVotingPower/POOL_NOT_OPERATED_BY_ACCOUNT" - ); + require(pool.operator == account, "getVotingPower/POOL_NOT_OPERATED_BY_ACCOUNT"); uint96 stakeDelegatedToPool = stakingProxy .getTotalStakeDelegatedToPool(operatedPoolIds[i]) .currentEpochBalance; @@ -322,25 +260,10 @@ contract ZrxTreasury is /// @dev Checks whether the given proposal is executable. /// Reverts if not. /// @param proposal The proposal to check. - function _assertProposalExecutable( - Proposal memory proposal, - ProposedAction[] memory actions - ) - private - view - { - require( - keccak256(abi.encode(actions)) == proposal.actionsHash, - "_assertProposalExecutable/INVALID_ACTIONS" - ); - require( - _hasProposalPassed(proposal), - "_assertProposalExecutable/PROPOSAL_HAS_NOT_PASSED" - ); - require( - !proposal.executed, - "_assertProposalExecutable/PROPOSAL_ALREADY_EXECUTED" - ); + function _assertProposalExecutable(Proposal memory proposal, ProposedAction[] memory actions) private view { + require(keccak256(abi.encode(actions)) == proposal.actionsHash, "_assertProposalExecutable/INVALID_ACTIONS"); + require(_hasProposalPassed(proposal), "_assertProposalExecutable/PROPOSAL_HAS_NOT_PASSED"); + require(!proposal.executed, "_assertProposalExecutable/PROPOSAL_ALREADY_EXECUTED"); require( stakingProxy.currentEpoch() == proposal.executionEpoch, "_assertProposalExecutable/CANNOT_EXECUTE_THIS_EPOCH" @@ -350,11 +273,7 @@ contract ZrxTreasury is /// @dev Checks whether the given proposal has passed or not. /// @param proposal The proposal to check. /// @return hasPassed Whether the proposal has passed. - function _hasProposalPassed(Proposal memory proposal) - private - view - returns (bool hasPassed) - { + function _hasProposalPassed(Proposal memory proposal) private view returns (bool hasPassed) { // Proposal is not passed until the vote is over. if (!_hasVoteEnded(proposal.voteEpoch)) { return false; @@ -374,11 +293,7 @@ contract ZrxTreasury is /// epoch has ended or not. /// @param voteEpoch The epoch at which the vote started. /// @return hasEnded Whether the vote has ended. - function _hasVoteEnded(uint256 voteEpoch) - private - view - returns (bool hasEnded) - { + function _hasVoteEnded(uint256 voteEpoch) private view returns (bool hasEnded) { uint256 currentEpoch = stakingProxy.currentEpoch(); if (currentEpoch < voteEpoch) { return false; @@ -388,9 +303,7 @@ contract ZrxTreasury is } // voteEpoch == currentEpoch // Vote ends at currentEpochStartTime + votingPeriod - uint256 voteEndTime = stakingProxy - .currentEpochStartTimeInSeconds() - .safeAdd(votingPeriod); + uint256 voteEndTime = stakingProxy.currentEpochStartTimeInSeconds().safeAdd(votingPeriod); return block.timestamp > voteEndTime; } @@ -402,9 +315,7 @@ contract ZrxTreasury is uint256 proposalId, bool support, bytes32[] memory operatedPoolIds - ) - private - { + ) private { if (proposalId >= proposalCount()) { revert("_castVote/INVALID_PROPOSAL_ID"); } @@ -413,10 +324,7 @@ contract ZrxTreasury is } Proposal memory proposal = proposals[proposalId]; - if ( - proposal.voteEpoch != stakingProxy.currentEpoch() || - _hasVoteEnded(proposal.voteEpoch) - ) { + if (proposal.voteEpoch != stakingProxy.currentEpoch() || _hasVoteEnded(proposal.voteEpoch)) { revert("_castVote/VOTING_IS_CLOSED"); } @@ -426,27 +334,21 @@ contract ZrxTreasury is } if (support) { - proposals[proposalId].votesFor = proposals[proposalId].votesFor - .safeAdd(votingPower); + proposals[proposalId].votesFor = proposals[proposalId].votesFor.safeAdd(votingPower); } else { - proposals[proposalId].votesAgainst = proposals[proposalId].votesAgainst - .safeAdd(votingPower); + proposals[proposalId].votesAgainst = proposals[proposalId].votesAgainst.safeAdd(votingPower); } hasVoted[proposalId][voter] = true; - emit VoteCast( - voter, - operatedPoolIds, - proposalId, - support, - votingPower - ); + emit VoteCast(voter, operatedPoolIds, proposalId, support, votingPower); } /// @dev Gets the Ethereum chain id function _getChainId() private pure returns (uint256) { uint256 chainId; - assembly { chainId := chainid() } + assembly { + chainId := chainid() + } return chainId; } } diff --git a/contracts/utils/contracts/src/Authorizable.sol b/contracts/utils/contracts/src/Authorizable.sol index 2161bdb35b..cb3d62ad66 100644 --- a/contracts/utils/contracts/src/Authorizable.sol +++ b/contracts/utils/contracts/src/Authorizable.sol @@ -23,14 +23,10 @@ import "./LibAuthorizableRichErrors.sol"; import "./LibRichErrors.sol"; import "./Ownable.sol"; - // solhint-disable no-empty-blocks -contract Authorizable is - Ownable, - IAuthorizable -{ +contract Authorizable is Ownable, IAuthorizable { /// @dev Only authorized addresses can invoke functions with this modifier. - modifier onlyAuthorized { + modifier onlyAuthorized() { _assertSenderIsAuthorized(); _; } @@ -38,33 +34,24 @@ contract Authorizable is /// @dev Whether an adderss is authorized to call privileged functions. /// @param 0 Address to query. /// @return 0 Whether the address is authorized. - mapping (address => bool) public authorized; + mapping(address => bool) public authorized; /// @dev Whether an adderss is authorized to call privileged functions. /// @param 0 Index of authorized address. /// @return 0 Authorized address. address[] public authorities; /// @dev Initializes the `owner` address. - constructor() - public - Ownable() - {} + constructor() public Ownable() {} /// @dev Authorizes an address. /// @param target Address to authorize. - function addAuthorizedAddress(address target) - external - onlyOwner - { + function addAuthorizedAddress(address target) external onlyOwner { _addAuthorizedAddress(target); } /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. - function removeAuthorizedAddress(address target) - external - onlyOwner - { + function removeAuthorizedAddress(address target) external onlyOwner { if (!authorized[target]) { LibRichErrors.rrevert(LibAuthorizableRichErrors.TargetNotAuthorizedError(target)); } @@ -79,31 +66,18 @@ contract Authorizable is /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. /// @param index Index of target in authorities array. - function removeAuthorizedAddressAtIndex( - address target, - uint256 index - ) - external - onlyOwner - { + function removeAuthorizedAddressAtIndex(address target, uint256 index) external onlyOwner { _removeAuthorizedAddressAtIndex(target, index); } /// @dev Gets all authorized addresses. /// @return Array of authorized addresses. - function getAuthorizedAddresses() - external - view - returns (address[] memory) - { + function getAuthorizedAddresses() external view returns (address[] memory) { return authorities; } /// @dev Reverts if msg.sender is not authorized. - function _assertSenderIsAuthorized() - internal - view - { + function _assertSenderIsAuthorized() internal view { if (!authorized[msg.sender]) { LibRichErrors.rrevert(LibAuthorizableRichErrors.SenderNotAuthorizedError(msg.sender)); } @@ -111,9 +85,7 @@ contract Authorizable is /// @dev Authorizes an address. /// @param target Address to authorize. - function _addAuthorizedAddress(address target) - internal - { + function _addAuthorizedAddress(address target) internal { // Ensure that the target is not the zero address. if (target == address(0)) { LibRichErrors.rrevert(LibAuthorizableRichErrors.ZeroCantBeAuthorizedError()); @@ -132,26 +104,15 @@ contract Authorizable is /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. /// @param index Index of target in authorities array. - function _removeAuthorizedAddressAtIndex( - address target, - uint256 index - ) - internal - { + function _removeAuthorizedAddressAtIndex(address target, uint256 index) internal { if (!authorized[target]) { LibRichErrors.rrevert(LibAuthorizableRichErrors.TargetNotAuthorizedError(target)); } if (index >= authorities.length) { - LibRichErrors.rrevert(LibAuthorizableRichErrors.IndexOutOfBoundsError( - index, - authorities.length - )); + LibRichErrors.rrevert(LibAuthorizableRichErrors.IndexOutOfBoundsError(index, authorities.length)); } if (authorities[index] != target) { - LibRichErrors.rrevert(LibAuthorizableRichErrors.AuthorizedAddressMismatchError( - authorities[index], - target - )); + LibRichErrors.rrevert(LibAuthorizableRichErrors.AuthorizedAddressMismatchError(authorities[index], target)); } delete authorized[target]; diff --git a/contracts/utils/contracts/src/D18.sol b/contracts/utils/contracts/src/D18.sol index d6fde12b0f..1c09e754e0 100644 --- a/contracts/utils/contracts/src/D18.sol +++ b/contracts/utils/contracts/src/D18.sol @@ -18,201 +18,124 @@ pragma solidity ^0.5.16; - /// @dev A library for working with 18 digit, base 10 decimals. library D18 { - /// @dev Decimal places for dydx value quantities. uint256 private constant PRECISION = 18; /// @dev 1.0 in base-18 decimal. - int256 private constant DECIMAL_ONE = int256(10 ** PRECISION); + int256 private constant DECIMAL_ONE = int256(10**PRECISION); /// @dev Minimum signed integer value. - int256 private constant MIN_INT256_VALUE = int256(0x8000000000000000000000000000000000000000000000000000000000000000); + int256 private constant MIN_INT256_VALUE = + int256(0x8000000000000000000000000000000000000000000000000000000000000000); /// @dev Return `1.0` - function one() - internal - pure - returns (int256 r) - { + function one() internal pure returns (int256 r) { r = DECIMAL_ONE; } /// @dev Add two decimals. - function add(int256 a, int256 b) - internal - pure - returns (int256 r) - { + function add(int256 a, int256 b) internal pure returns (int256 r) { r = _add(a, b); } /// @dev Add two decimals. - function add(uint256 a, int256 b) - internal - pure - returns (int256 r) - { + function add(uint256 a, int256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _add(int256(a), b); } /// @dev Add two decimals. - function add(int256 a, uint256 b) - internal - pure - returns (int256 r) - { + function add(int256 a, uint256 b) internal pure returns (int256 r) { require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _add(a, int256(b)); } /// @dev Add two decimals. - function add(uint256 a, uint256 b) - internal - pure - returns (int256 r) - { + function add(uint256 a, uint256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _add(int256(a), int256(b)); } /// @dev Subract two decimals. - function sub(int256 a, int256 b) - internal - pure - returns (int256 r) - { + function sub(int256 a, int256 b) internal pure returns (int256 r) { r = _add(a, -b); } /// @dev Subract two decimals. - function sub(uint256 a, int256 b) - internal - pure - returns (int256 r) - { + function sub(uint256 a, int256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _add(int256(a), -b); } /// @dev Subract two decimals. - function sub(uint256 a, uint256 b) - internal - pure - returns (int256 r) - { + function sub(uint256 a, uint256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _add(int256(a), -int256(b)); } /// @dev Multiply two decimals. - function mul(int256 a, int256 b) - internal - pure - returns (int256 r) - { + function mul(int256 a, int256 b) internal pure returns (int256 r) { r = _div(_mul(a, b), DECIMAL_ONE); } /// @dev Multiply two decimals. - function mul(uint256 a, int256 b) - internal - pure - returns (int256 r) - { + function mul(uint256 a, int256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _div(_mul(int256(a), b), DECIMAL_ONE); } /// @dev Multiply two decimals. - function mul(int256 a, uint256 b) - internal - pure - returns (int256 r) - { + function mul(int256 a, uint256 b) internal pure returns (int256 r) { require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _div(_mul(a, int256(b)), DECIMAL_ONE); } /// @dev Multiply two decimals. - function mul(uint256 a, uint256 b) - internal - pure - returns (int256 r) - { + function mul(uint256 a, uint256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _div(_mul(int256(a), int256(b)), DECIMAL_ONE); } /// @dev Divide two decimals. - function div(int256 a, int256 b) - internal - pure - returns (int256 r) - { + function div(int256 a, int256 b) internal pure returns (int256 r) { r = _div(_mul(a, DECIMAL_ONE), b); } /// @dev Divide two decimals. - function div(uint256 a, int256 b) - internal - pure - returns (int256 r) - { + function div(uint256 a, int256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _div(_mul(int256(a), DECIMAL_ONE), b); } /// @dev Divide two decimals. - function div(int256 a, uint256 b) - internal - pure - returns (int256 r) - { + function div(int256 a, uint256 b) internal pure returns (int256 r) { require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _div(_mul(a, DECIMAL_ONE), int256(b)); } /// @dev Divide two decimals. - function div(uint256 a, uint256 b) - internal - pure - returns (int256 r) - { + function div(uint256 a, uint256 b) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); require(int256(b) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = _div(_mul(int256(a), DECIMAL_ONE), int256(b)); } /// @dev Safely convert an unsigned integer into a signed integer. - function toSigned(uint256 a) - internal - pure - returns (int256 r) - { + function toSigned(uint256 a) internal pure returns (int256 r) { require(int256(a) >= 0, "D18/DECIMAL_VALUE_TOO_BIG"); r = int256(a); } /// @dev Clip a signed value to be positive. - function clip(int256 a) - internal - pure - returns (int256 r) - { + function clip(int256 a) internal pure returns (int256 r) { r = a < 0 ? 0 : a; } /// @dev Safely multiply two signed integers. - function _mul(int256 a, int256 b) - private - pure - returns (int256 r) - { + function _mul(int256 a, int256 b) private pure returns (int256 r) { if (a == 0 || b == 0) { return 0; } @@ -222,27 +145,15 @@ library D18 { } /// @dev Safely divide two signed integers. - function _div(int256 a, int256 b) - private - pure - returns (int256 r) - { + function _div(int256 a, int256 b) private pure returns (int256 r) { require(b != 0, "D18/DECIMAL_DIV_BY_ZERO"); require(a != MIN_INT256_VALUE || b != -1, "D18/DECIMAL_DIV_OVERFLOW"); r = a / b; } /// @dev Safely add two signed integers. - function _add(int256 a, int256 b) - private - pure - returns (int256 r) - { + function _add(int256 a, int256 b) private pure returns (int256 r) { r = a + b; - require( - !((a < 0 && b < 0 && r > a) || (a > 0 && b > 0 && r < a)), - "D18/DECIMAL_ADD_OVERFLOW" - ); + require(!((a < 0 && b < 0 && r > a) || (a > 0 && b > 0 && r < a)), "D18/DECIMAL_ADD_OVERFLOW"); } - } diff --git a/contracts/utils/contracts/src/DeploymentConstants.sol b/contracts/utils/contracts/src/DeploymentConstants.sol index 2aefe53cbe..6e363fbcc3 100644 --- a/contracts/utils/contracts/src/DeploymentConstants.sol +++ b/contracts/utils/contracts/src/DeploymentConstants.sol @@ -18,48 +18,46 @@ pragma solidity ^0.5.9; - contract DeploymentConstants { - // solhint-disable separate-by-one-line-in-contract // Mainnet addresses /////////////////////////////////////////////////////// /// @dev Mainnet address of the WETH contract. - address constant private WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; + address private constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /// @dev Mainnet address of the KyberNetworkProxy contract. - address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; + address private constant KYBER_NETWORK_PROXY_ADDRESS = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; /// @dev Mainnet address of the KyberHintHandler contract. - address constant private KYBER_HINT_HANDLER_ADDRESS = 0xa1C0Fa73c39CFBcC11ec9Eb1Afc665aba9996E2C; + address private constant KYBER_HINT_HANDLER_ADDRESS = 0xa1C0Fa73c39CFBcC11ec9Eb1Afc665aba9996E2C; /// @dev Mainnet address of the `UniswapExchangeFactory` contract. - address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; + address private constant UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; /// @dev Mainnet address of the `UniswapV2Router01` contract. - address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; + address private constant UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; /// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract. - address constant private ETH2DAI_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; + address private constant ETH2DAI_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; /// @dev Mainnet address of the `ERC20BridgeProxy` contract - address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0x8ED95d1746bf1E4dAb58d8ED4724f1Ef95B20Db0; + address private constant ERC20_BRIDGE_PROXY_ADDRESS = 0x8ED95d1746bf1E4dAb58d8ED4724f1Ef95B20Db0; ///@dev Mainnet address of the `Dai` (multi-collateral) contract - address constant private DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; + address private constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; /// @dev Mainnet address of the `Chai` contract - address constant private CHAI_ADDRESS = 0x06AF07097C9Eeb7fD685c692751D5C66dB49c215; + address private constant CHAI_ADDRESS = 0x06AF07097C9Eeb7fD685c692751D5C66dB49c215; /// @dev Mainnet address of the 0x DevUtils contract. - address constant private DEV_UTILS_ADDRESS = 0x74134CF88b21383713E096a5ecF59e297dc7f547; + address private constant DEV_UTILS_ADDRESS = 0x74134CF88b21383713E096a5ecF59e297dc7f547; /// @dev Kyber ETH pseudo-address. - address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; + address internal constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Mainnet address of the dYdX contract. - address constant private DYDX_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; + address private constant DYDX_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; /// @dev Mainnet address of the GST2 contract - address constant private GST_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; + address private constant GST_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; /// @dev Mainnet address of the GST Collector - address constant private GST_COLLECTOR_ADDRESS = 0x000000D3b08566BE75A6DB803C03C85C0c1c5B96; + address private constant GST_COLLECTOR_ADDRESS = 0x000000D3b08566BE75A6DB803C03C85C0c1c5B96; /// @dev Mainnet address of the mStable mUSD contract. - address constant private MUSD_ADDRESS = 0xe2f2a5C287993345a840Db3B0845fbC70f5935a5; + address private constant MUSD_ADDRESS = 0xe2f2a5C287993345a840Db3B0845fbC70f5935a5; /// @dev Mainnet address of the Mooniswap Registry contract - address constant private MOONISWAP_REGISTRY = 0x71CD6666064C3A1354a3B4dca5fA1E2D3ee7D303; + address private constant MOONISWAP_REGISTRY = 0x71CD6666064C3A1354a3B4dca5fA1E2D3ee7D303; /// @dev Mainnet address of the DODO Registry (ZOO) contract - address constant private DODO_REGISTRY = 0x3A97247DF274a17C59A3bd12735ea3FcDFb49950; + address private constant DODO_REGISTRY = 0x3A97247DF274a17C59A3bd12735ea3FcDFb49950; /// @dev Mainnet address of the DODO Helper contract - address constant private DODO_HELPER = 0x533dA777aeDCE766CEAe696bf90f8541A4bA80Eb; + address private constant DODO_HELPER = 0x533dA777aeDCE766CEAe696bf90f8541A4bA80Eb; // // Ropsten addresses /////////////////////////////////////////////////////// // /// @dev Mainnet address of the WETH contract. @@ -153,171 +151,103 @@ contract DeploymentConstants { /// @dev Overridable way to get the `KyberNetworkProxy` address. /// @return kyberAddress The `IKyberNetworkProxy` address. - function _getKyberNetworkProxyAddress() - internal - view - returns (address kyberAddress) - { + function _getKyberNetworkProxyAddress() internal view returns (address kyberAddress) { return KYBER_NETWORK_PROXY_ADDRESS; } /// @dev Overridable way to get the `KyberHintHandler` address. /// @return kyberAddress The `IKyberHintHandler` address. - function _getKyberHintHandlerAddress() - internal - view - returns (address hintHandlerAddress) - { + function _getKyberHintHandlerAddress() internal view returns (address hintHandlerAddress) { return KYBER_HINT_HANDLER_ADDRESS; } /// @dev Overridable way to get the WETH address. /// @return wethAddress The WETH address. - function _getWethAddress() - internal - view - returns (address wethAddress) - { + function _getWethAddress() internal view returns (address wethAddress) { return WETH_ADDRESS; } /// @dev Overridable way to get the `UniswapExchangeFactory` address. /// @return uniswapAddress The `UniswapExchangeFactory` address. - function _getUniswapExchangeFactoryAddress() - internal - view - returns (address uniswapAddress) - { + function _getUniswapExchangeFactoryAddress() internal view returns (address uniswapAddress) { return UNISWAP_EXCHANGE_FACTORY_ADDRESS; } /// @dev Overridable way to get the `UniswapV2Router01` address. /// @return uniswapRouterAddress The `UniswapV2Router01` address. - function _getUniswapV2Router01Address() - internal - view - returns (address uniswapRouterAddress) - { + function _getUniswapV2Router01Address() internal view returns (address uniswapRouterAddress) { return UNISWAP_V2_ROUTER_01_ADDRESS; } /// @dev An overridable way to retrieve the Eth2Dai `MatchingMarket` contract. /// @return eth2daiAddress The Eth2Dai `MatchingMarket` contract. - function _getEth2DaiAddress() - internal - view - returns (address eth2daiAddress) - { + function _getEth2DaiAddress() internal view returns (address eth2daiAddress) { return ETH2DAI_ADDRESS; } /// @dev An overridable way to retrieve the `ERC20BridgeProxy` contract. /// @return erc20BridgeProxyAddress The `ERC20BridgeProxy` contract. - function _getERC20BridgeProxyAddress() - internal - view - returns (address erc20BridgeProxyAddress) - { + function _getERC20BridgeProxyAddress() internal view returns (address erc20BridgeProxyAddress) { return ERC20_BRIDGE_PROXY_ADDRESS; } /// @dev An overridable way to retrieve the `Dai` contract. /// @return daiAddress The `Dai` contract. - function _getDaiAddress() - internal - view - returns (address daiAddress) - { + function _getDaiAddress() internal view returns (address daiAddress) { return DAI_ADDRESS; } /// @dev An overridable way to retrieve the `Chai` contract. /// @return chaiAddress The `Chai` contract. - function _getChaiAddress() - internal - view - returns (address chaiAddress) - { + function _getChaiAddress() internal view returns (address chaiAddress) { return CHAI_ADDRESS; } /// @dev An overridable way to retrieve the 0x `DevUtils` contract address. /// @return devUtils The 0x `DevUtils` contract address. - function _getDevUtilsAddress() - internal - view - returns (address devUtils) - { + function _getDevUtilsAddress() internal view returns (address devUtils) { return DEV_UTILS_ADDRESS; } /// @dev Overridable way to get the DyDx contract. /// @return exchange The DyDx exchange contract. - function _getDydxAddress() - internal - view - returns (address dydxAddress) - { + function _getDydxAddress() internal view returns (address dydxAddress) { return DYDX_ADDRESS; } /// @dev An overridable way to retrieve the GST2 contract address. /// @return gst The GST contract. - function _getGstAddress() - internal - view - returns (address gst) - { + function _getGstAddress() internal view returns (address gst) { return GST_ADDRESS; } /// @dev An overridable way to retrieve the GST Collector address. /// @return collector The GST collector address. - function _getGstCollectorAddress() - internal - view - returns (address collector) - { + function _getGstCollectorAddress() internal view returns (address collector) { return GST_COLLECTOR_ADDRESS; } /// @dev An overridable way to retrieve the mStable mUSD address. /// @return musd The mStable mUSD address. - function _getMUsdAddress() - internal - view - returns (address musd) - { + function _getMUsdAddress() internal view returns (address musd) { return MUSD_ADDRESS; } /// @dev An overridable way to retrieve the Mooniswap registry address. /// @return registry The Mooniswap registry address. - function _getMooniswapAddress() - internal - view - returns (address) - { + function _getMooniswapAddress() internal view returns (address) { return MOONISWAP_REGISTRY; } /// @dev An overridable way to retrieve the DODO Registry contract address. /// @return registry The DODO Registry contract address. - function _getDODORegistryAddress() - internal - view - returns (address) - { + function _getDODORegistryAddress() internal view returns (address) { return DODO_REGISTRY; } /// @dev An overridable way to retrieve the DODO Helper contract address. /// @return registry The DODO Helper contract address. - function _getDODOHelperAddress() - internal - view - returns (address) - { + function _getDODOHelperAddress() internal view returns (address) { return DODO_HELPER; } } diff --git a/contracts/utils/contracts/src/LibAddress.sol b/contracts/utils/contracts/src/LibAddress.sol index cd0d41792e..cacaaed1e2 100644 --- a/contracts/utils/contracts/src/LibAddress.sol +++ b/contracts/utils/contracts/src/LibAddress.sol @@ -18,12 +18,10 @@ pragma solidity ^0.5.9; - /** * Utility library of inline functions on addresses */ library LibAddress { - /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, @@ -40,8 +38,9 @@ library LibAddress { // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly - assembly { size := extcodesize(account) } + assembly { + size := extcodesize(account) + } return size > 0; } - } diff --git a/contracts/utils/contracts/src/LibAddressArray.sol b/contracts/utils/contracts/src/LibAddressArray.sol index bbb8278221..937093a9ca 100644 --- a/contracts/utils/contracts/src/LibAddressArray.sol +++ b/contracts/utils/contracts/src/LibAddressArray.sol @@ -22,9 +22,7 @@ import "./LibAddressArrayRichErrors.sol"; import "./LibBytes.sol"; import "./LibRichErrors.sol"; - library LibAddressArray { - /// @dev Append a new address to an array of addresses. /// The `addressArray` may need to be reallocated to make space /// for the new address. Because of this we return the resulting @@ -32,11 +30,7 @@ library LibAddressArray { /// @param addressArray Array of addresses. /// @param addressToAppend Address to append. /// @return Array of addresses: [... addressArray, addressToAppend] - function append(address[] memory addressArray, address addressToAppend) - internal - pure - returns (address[] memory) - { + function append(address[] memory addressArray, address addressToAppend) internal pure returns (address[] memory) { // Get stats on address array and free memory uint256 freeMemPtr = 0; uint256 addressArrayBeginPtr = 0; @@ -54,10 +48,7 @@ library LibAddressArray { // `freeMemPtr` > `addressArrayEndPtr`: Some value occupies memory after `addressArray` // `freeMemPtr` < `addressArrayEndPtr`: Memory has not been managed properly. if (freeMemPtr < addressArrayEndPtr) { - LibRichErrors.rrevert(LibAddressArrayRichErrors.MismanagedMemoryError( - freeMemPtr, - addressArrayEndPtr - )); + LibRichErrors.rrevert(LibAddressArrayRichErrors.MismanagedMemoryError(freeMemPtr, addressArrayEndPtr)); } // If free memory begins at the end of `addressArray` @@ -92,13 +83,8 @@ library LibAddressArray { /// @param addressArray Array of addresses. /// @param target Address to search for in array. /// @return True if the addressArray contains the target. - function contains(address[] memory addressArray, address target) - internal - pure - returns (bool success) - { + function contains(address[] memory addressArray, address target) internal pure returns (bool success) { assembly { - // Calculate byte length of array let arrayByteLen := mul(mload(addressArray), 32) // Calculate beginning of array contents @@ -107,8 +93,11 @@ library LibAddressArray { let arrayContentsEnd := add(arrayContentsStart, arrayByteLen) // Loop through array - for {let i:= arrayContentsStart} lt(i, arrayContentsEnd) {i := add(i, 32)} { - + for { + let i := arrayContentsStart + } lt(i, arrayContentsEnd) { + i := add(i, 32) + } { // Load array element let arrayElement := mload(i) @@ -134,7 +123,6 @@ library LibAddressArray { returns (bool success, uint256 index) { assembly { - // Calculate byte length of array let arrayByteLen := mul(mload(addressArray), 32) // Calculate beginning of array contents @@ -143,8 +131,11 @@ library LibAddressArray { let arrayContentsEnd := add(arrayContentsStart, arrayByteLen) // Loop through array - for {let i:= arrayContentsStart} lt(i, arrayContentsEnd) {i := add(i, 32)} { - + for { + let i := arrayContentsStart + } lt(i, arrayContentsEnd) { + i := add(i, 32) + } { // Load array element let arrayElement := mload(i) diff --git a/contracts/utils/contracts/src/LibAddressArrayRichErrors.sol b/contracts/utils/contracts/src/LibAddressArrayRichErrors.sol index 82b99c6a2c..d4517bf5b6 100644 --- a/contracts/utils/contracts/src/LibAddressArrayRichErrors.sol +++ b/contracts/utils/contracts/src/LibAddressArrayRichErrors.sol @@ -18,26 +18,16 @@ pragma solidity ^0.5.9; - library LibAddressArrayRichErrors { - // bytes4(keccak256("MismanagedMemoryError(uint256,uint256)")) - bytes4 internal constant MISMANAGED_MEMORY_ERROR_SELECTOR = - 0x5fc83722; + bytes4 internal constant MISMANAGED_MEMORY_ERROR_SELECTOR = 0x5fc83722; // solhint-disable func-name-mixedcase - function MismanagedMemoryError( - uint256 freeMemPtr, - uint256 addressArrayEndPtr - ) + function MismanagedMemoryError(uint256 freeMemPtr, uint256 addressArrayEndPtr) internal pure returns (bytes memory) { - return abi.encodeWithSelector( - MISMANAGED_MEMORY_ERROR_SELECTOR, - freeMemPtr, - addressArrayEndPtr - ); + return abi.encodeWithSelector(MISMANAGED_MEMORY_ERROR_SELECTOR, freeMemPtr, addressArrayEndPtr); } } diff --git a/contracts/utils/contracts/src/LibAuthorizableRichErrors.sol b/contracts/utils/contracts/src/LibAuthorizableRichErrors.sol index 5cec572a4e..3cba0910bf 100644 --- a/contracts/utils/contracts/src/LibAuthorizableRichErrors.sol +++ b/contracts/utils/contracts/src/LibAuthorizableRichErrors.sol @@ -18,102 +18,47 @@ pragma solidity ^0.5.9; - library LibAuthorizableRichErrors { - // bytes4(keccak256("AuthorizedAddressMismatchError(address,address)")) - bytes4 internal constant AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR = - 0x140a84db; + bytes4 internal constant AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR = 0x140a84db; // bytes4(keccak256("IndexOutOfBoundsError(uint256,uint256)")) - bytes4 internal constant INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR = - 0xe9f83771; + bytes4 internal constant INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR = 0xe9f83771; // bytes4(keccak256("SenderNotAuthorizedError(address)")) - bytes4 internal constant SENDER_NOT_AUTHORIZED_ERROR_SELECTOR = - 0xb65a25b9; + bytes4 internal constant SENDER_NOT_AUTHORIZED_ERROR_SELECTOR = 0xb65a25b9; // bytes4(keccak256("TargetAlreadyAuthorizedError(address)")) - bytes4 internal constant TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR = - 0xde16f1a0; + bytes4 internal constant TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR = 0xde16f1a0; // bytes4(keccak256("TargetNotAuthorizedError(address)")) - bytes4 internal constant TARGET_NOT_AUTHORIZED_ERROR_SELECTOR = - 0xeb5108a2; + bytes4 internal constant TARGET_NOT_AUTHORIZED_ERROR_SELECTOR = 0xeb5108a2; // bytes4(keccak256("ZeroCantBeAuthorizedError()")) - bytes internal constant ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES = - hex"57654fe4"; + bytes internal constant ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES = hex"57654fe4"; // solhint-disable func-name-mixedcase - function AuthorizedAddressMismatchError( - address authorized, - address target - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR, - authorized, - target - ); + function AuthorizedAddressMismatchError(address authorized, address target) internal pure returns (bytes memory) { + return abi.encodeWithSelector(AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR, authorized, target); } - function IndexOutOfBoundsError( - uint256 index, - uint256 length - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR, - index, - length - ); + function IndexOutOfBoundsError(uint256 index, uint256 length) internal pure returns (bytes memory) { + return abi.encodeWithSelector(INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR, index, length); } - function SenderNotAuthorizedError(address sender) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - SENDER_NOT_AUTHORIZED_ERROR_SELECTOR, - sender - ); + function SenderNotAuthorizedError(address sender) internal pure returns (bytes memory) { + return abi.encodeWithSelector(SENDER_NOT_AUTHORIZED_ERROR_SELECTOR, sender); } - function TargetAlreadyAuthorizedError(address target) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR, - target - ); + function TargetAlreadyAuthorizedError(address target) internal pure returns (bytes memory) { + return abi.encodeWithSelector(TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR, target); } - function TargetNotAuthorizedError(address target) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - TARGET_NOT_AUTHORIZED_ERROR_SELECTOR, - target - ); + function TargetNotAuthorizedError(address target) internal pure returns (bytes memory) { + return abi.encodeWithSelector(TARGET_NOT_AUTHORIZED_ERROR_SELECTOR, target); } - function ZeroCantBeAuthorizedError() - internal - pure - returns (bytes memory) - { + function ZeroCantBeAuthorizedError() internal pure returns (bytes memory) { return ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES; } } diff --git a/contracts/utils/contracts/src/LibBytes.sol b/contracts/utils/contracts/src/LibBytes.sol index 4646d3b622..9be62d4dd1 100644 --- a/contracts/utils/contracts/src/LibBytes.sol +++ b/contracts/utils/contracts/src/LibBytes.sol @@ -21,9 +21,7 @@ pragma solidity ^0.5.9; import "./LibBytesRichErrors.sol"; import "./LibRichErrors.sol"; - library LibBytes { - using LibBytes for bytes; /// @dev Gets the memory address for a byte array. @@ -31,11 +29,7 @@ library LibBytes { /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. - function rawAddress(bytes memory input) - internal - pure - returns (uint256 memoryAddress) - { + function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } @@ -45,11 +39,7 @@ library LibBytes { /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. - function contentAddress(bytes memory input) - internal - pure - returns (uint256 memoryAddress) - { + function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } @@ -64,10 +54,7 @@ library LibBytes { uint256 dest, uint256 source, uint256 length - ) - internal - pure - { + ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. @@ -119,7 +106,11 @@ library LibBytes { // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks - for {} lt(source, sEnd) {} { + for { + + } lt(source, sEnd) { + + } { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) @@ -150,7 +141,11 @@ library LibBytes { // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks - for {} slt(dest, dEnd) {} { + for { + + } slt(dest, dEnd) { + + } { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) @@ -172,35 +167,31 @@ library LibBytes { bytes memory b, uint256 from, uint256 to - ) - internal - pure - returns (bytes memory result) - { + ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { - LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( - LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, - from, - to - )); + LibRichErrors.rrevert( + LibBytesRichErrors.InvalidByteOperationError( + LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, + from, + to + ) + ); } if (to > b.length) { - LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( - LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, - to, - b.length - )); + LibRichErrors.rrevert( + LibBytesRichErrors.InvalidByteOperationError( + LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, + to, + b.length + ) + ); } // Create a new bytes structure and copy contents result = new bytes(to - from); - memCopy( - result.contentAddress(), - b.contentAddress() + from, - result.length - ); + memCopy(result.contentAddress(), b.contentAddress() + from, result.length); return result; } @@ -214,26 +205,26 @@ library LibBytes { bytes memory b, uint256 from, uint256 to - ) - internal - pure - returns (bytes memory result) - { + ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { - LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( - LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, - from, - to - )); + LibRichErrors.rrevert( + LibBytesRichErrors.InvalidByteOperationError( + LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, + from, + to + ) + ); } if (to > b.length) { - LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( - LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, - to, - b.length - )); + LibRichErrors.rrevert( + LibBytesRichErrors.InvalidByteOperationError( + LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, + to, + b.length + ) + ); } // Create a new bytes structure around [from, to) in-place. @@ -247,17 +238,15 @@ library LibBytes { /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. - function popLastByte(bytes memory b) - internal - pure - returns (bytes1 result) - { + function popLastByte(bytes memory b) internal pure returns (bytes1 result) { if (b.length == 0) { - LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( - LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, - b.length, - 0 - )); + LibRichErrors.rrevert( + LibBytesRichErrors.InvalidByteOperationError( + LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, + b.length, + 0 + ) + ); } // Store last byte. @@ -275,14 +264,7 @@ library LibBytes { /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return True if arrays are the same. False otherwise. - function equals( - bytes memory lhs, - bytes memory rhs - ) - internal - pure - returns (bool equal) - { + function equals(bytes memory lhs, bytes memory rhs) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. @@ -293,20 +275,15 @@ library LibBytes { /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return address from byte array. - function readAddress( - bytes memory b, - uint256 index - ) - internal - pure - returns (address result) - { + function readAddress(bytes memory b, uint256 index) internal pure returns (address result) { if (b.length < index + 20) { - LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( - LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, - b.length, - index + 20 // 20 is length of address - )); + LibRichErrors.rrevert( + LibBytesRichErrors.InvalidByteOperationError( + LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, + b.length, + index + 20 // 20 is length of address + ) + ); } // Add offset to index: @@ -332,16 +309,15 @@ library LibBytes { bytes memory b, uint256 index, address input - ) - internal - pure - { + ) internal pure { if (b.length < index + 20) { - LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( - LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, - b.length, - index + 20 // 20 is length of address - )); + LibRichErrors.rrevert( + LibBytesRichErrors.InvalidByteOperationError( + LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, + b.length, + index + 20 // 20 is length of address + ) + ); } // Add offset to index: @@ -377,20 +353,15 @@ library LibBytes { /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. - function readBytes32( - bytes memory b, - uint256 index - ) - internal - pure - returns (bytes32 result) - { + function readBytes32(bytes memory b, uint256 index) internal pure returns (bytes32 result) { if (b.length < index + 32) { - LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( - LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, - b.length, - index + 32 - )); + LibRichErrors.rrevert( + LibBytesRichErrors.InvalidByteOperationError( + LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, + b.length, + index + 32 + ) + ); } // Arrays are prefixed by a 256 bit length parameter @@ -411,16 +382,15 @@ library LibBytes { bytes memory b, uint256 index, bytes32 input - ) - internal - pure - { + ) internal pure { if (b.length < index + 32) { - LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( - LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, - b.length, - index + 32 - )); + LibRichErrors.rrevert( + LibBytesRichErrors.InvalidByteOperationError( + LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, + b.length, + index + 32 + ) + ); } // Arrays are prefixed by a 256 bit length parameter @@ -436,14 +406,7 @@ library LibBytes { /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return uint256 value from byte array. - function readUint256( - bytes memory b, - uint256 index - ) - internal - pure - returns (uint256 result) - { + function readUint256(bytes memory b, uint256 index) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } @@ -456,10 +419,7 @@ library LibBytes { bytes memory b, uint256 index, uint256 input - ) - internal - pure - { + ) internal pure { writeBytes32(b, index, bytes32(input)); } @@ -467,20 +427,15 @@ library LibBytes { /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. - function readBytes4( - bytes memory b, - uint256 index - ) - internal - pure - returns (bytes4 result) - { + function readBytes4(bytes memory b, uint256 index) internal pure returns (bytes4 result) { if (b.length < index + 4) { - LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( - LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, - b.length, - index + 4 - )); + LibRichErrors.rrevert( + LibBytesRichErrors.InvalidByteOperationError( + LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, + b.length, + index + 4 + ) + ); } // Arrays are prefixed by a 32 byte length field @@ -501,10 +456,7 @@ library LibBytes { /// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array. /// @param b Bytes array to write new length to. /// @param length New length of byte array. - function writeLength(bytes memory b, uint256 length) - internal - pure - { + function writeLength(bytes memory b, uint256 length) internal pure { assembly { mstore(b, length) } diff --git a/contracts/utils/contracts/src/LibBytesRichErrors.sol b/contracts/utils/contracts/src/LibBytesRichErrors.sol index b90bd868c9..ab09048497 100644 --- a/contracts/utils/contracts/src/LibBytesRichErrors.sol +++ b/contracts/utils/contracts/src/LibBytesRichErrors.sol @@ -18,9 +18,7 @@ pragma solidity ^0.5.9; - library LibBytesRichErrors { - enum InvalidByteOperationErrorCodes { FromLessThanOrEqualsToRequired, ToLessThanOrEqualsLengthRequired, @@ -33,24 +31,14 @@ library LibBytesRichErrors { } // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)")) - bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = - 0x28006595; + bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = 0x28006595; // solhint-disable func-name-mixedcase function InvalidByteOperationError( InvalidByteOperationErrorCodes errorCode, uint256 offset, uint256 required - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - INVALID_BYTE_OPERATION_ERROR_SELECTOR, - errorCode, - offset, - required - ); + ) internal pure returns (bytes memory) { + return abi.encodeWithSelector(INVALID_BYTE_OPERATION_ERROR_SELECTOR, errorCode, offset, required); } } diff --git a/contracts/utils/contracts/src/LibEIP1271.sol b/contracts/utils/contracts/src/LibEIP1271.sol index 6dfe8b7787..c4da2cf26f 100644 --- a/contracts/utils/contracts/src/LibEIP1271.sol +++ b/contracts/utils/contracts/src/LibEIP1271.sol @@ -18,10 +18,8 @@ pragma solidity ^0.5.9; - contract LibEIP1271 { - /// @dev Magic bytes returned by EIP1271 wallets on success. /// @return 0 Magic bytes. - bytes4 constant public EIP1271_MAGIC_VALUE = 0x20c13b0b; + bytes4 public constant EIP1271_MAGIC_VALUE = 0x20c13b0b; } diff --git a/contracts/utils/contracts/src/LibEIP712.sol b/contracts/utils/contracts/src/LibEIP712.sol index 38d08fbf12..656eb90ec1 100644 --- a/contracts/utils/contracts/src/LibEIP712.sol +++ b/contracts/utils/contracts/src/LibEIP712.sol @@ -18,9 +18,7 @@ pragma solidity ^0.5.9; - library LibEIP712 { - // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", @@ -30,7 +28,8 @@ library LibEIP712 { // "address verifyingContract", // ")" // )) - bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; + bytes32 internal constant _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = + 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. @@ -42,11 +41,7 @@ library LibEIP712 { string memory version, uint256 chainId, address verifyingContract - ) - internal - pure - returns (bytes32 result) - { + ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: @@ -84,11 +79,7 @@ library LibEIP712 { /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return EIP712 hash applied to the given EIP712 Domain. - function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) - internal - pure - returns (bytes32 result) - { + function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, @@ -100,9 +91,9 @@ library LibEIP712 { // Load free memory pointer let memPtr := mload(64) - mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header - mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash - mstore(add(memPtr, 34), hashStruct) // Hash of struct + mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header + mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash + mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) diff --git a/contracts/utils/contracts/src/LibFractions.sol b/contracts/utils/contracts/src/LibFractions.sol index f5a05706c6..051fa466ba 100644 --- a/contracts/utils/contracts/src/LibFractions.sol +++ b/contracts/utils/contracts/src/LibFractions.sol @@ -2,9 +2,7 @@ pragma solidity ^0.5.9; import "./LibSafeMath.sol"; - library LibFractions { - using LibSafeMath for uint256; /// @dev Safely adds two fractions `n1/d1 + n2/d2` @@ -19,23 +17,14 @@ library LibFractions { uint256 d1, uint256 n2, uint256 d2 - ) - internal - pure - returns ( - uint256 numerator, - uint256 denominator - ) - { + ) internal pure returns (uint256 numerator, uint256 denominator) { if (n1 == 0) { return (numerator = n2, denominator = d2); } if (n2 == 0) { return (numerator = n1, denominator = d1); } - numerator = n1 - .safeMul(d2) - .safeAdd(n2.safeMul(d1)); + numerator = n1.safeMul(d2).safeAdd(n2.safeMul(d1)); denominator = d1.safeMul(d2); return (numerator, denominator); } @@ -52,14 +41,7 @@ library LibFractions { uint256 numerator, uint256 denominator, uint256 maxValue - ) - internal - pure - returns ( - uint256 scaledNumerator, - uint256 scaledDenominator - ) - { + ) internal pure returns (uint256 scaledNumerator, uint256 scaledDenominator) { // If either the numerator or the denominator are > `maxValue`, // re-scale them by `maxValue` to prevent overflows in future operations. if (numerator > maxValue || denominator > maxValue) { @@ -80,18 +62,12 @@ library LibFractions { /// @param denominator The denominator. /// @return scaledNumerator The rescaled numerator. /// @return scaledDenominator The rescaled denominator. - function normalize( - uint256 numerator, - uint256 denominator - ) + function normalize(uint256 numerator, uint256 denominator) internal pure - returns ( - uint256 scaledNumerator, - uint256 scaledDenominator - ) + returns (uint256 scaledNumerator, uint256 scaledDenominator) { - return normalize(numerator, denominator, 2 ** 127); + return normalize(numerator, denominator, 2**127); } /// @dev Safely scales the difference between two fractions. @@ -107,25 +83,15 @@ library LibFractions { uint256 n2, uint256 d2, uint256 s - ) - internal - pure - returns (uint256 result) - { + ) internal pure returns (uint256 result) { if (s == 0) { return 0; } if (n2 == 0) { - return result = s - .safeMul(n1) - .safeDiv(d1); + return result = s.safeMul(n1).safeDiv(d1); } - uint256 numerator = n1 - .safeMul(d2) - .safeSub(n2.safeMul(d1)); + uint256 numerator = n1.safeMul(d2).safeSub(n2.safeMul(d1)); uint256 tmp = numerator.safeDiv(d2); - return s - .safeMul(tmp) - .safeDiv(d1); + return s.safeMul(tmp).safeDiv(d1); } } diff --git a/contracts/utils/contracts/src/LibMath.sol b/contracts/utils/contracts/src/LibMath.sol index 1df06f436e..797508be35 100644 --- a/contracts/utils/contracts/src/LibMath.sol +++ b/contracts/utils/contracts/src/LibMath.sol @@ -22,9 +22,7 @@ import "./LibSafeMath.sol"; import "./LibRichErrors.sol"; import "./LibMathRichErrors.sol"; - library LibMath { - using LibSafeMath for uint256; /// @dev Calculates partial value given a numerator and denominator rounded down. @@ -37,21 +35,9 @@ library LibMath { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (uint256 partialAmount) - { - if (isRoundingErrorFloor( - numerator, - denominator, - target - )) { - LibRichErrors.rrevert(LibMathRichErrors.RoundingError( - numerator, - denominator, - target - )); + ) internal pure returns (uint256 partialAmount) { + if (isRoundingErrorFloor(numerator, denominator, target)) { + LibRichErrors.rrevert(LibMathRichErrors.RoundingError(numerator, denominator, target)); } partialAmount = numerator.safeMul(target).safeDiv(denominator); @@ -68,29 +54,15 @@ library LibMath { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (uint256 partialAmount) - { - if (isRoundingErrorCeil( - numerator, - denominator, - target - )) { - LibRichErrors.rrevert(LibMathRichErrors.RoundingError( - numerator, - denominator, - target - )); + ) internal pure returns (uint256 partialAmount) { + if (isRoundingErrorCeil(numerator, denominator, target)) { + LibRichErrors.rrevert(LibMathRichErrors.RoundingError(numerator, denominator, target)); } // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. - partialAmount = numerator.safeMul(target) - .safeAdd(denominator.safeSub(1)) - .safeDiv(denominator); + partialAmount = numerator.safeMul(target).safeAdd(denominator.safeSub(1)).safeDiv(denominator); return partialAmount; } @@ -104,11 +76,7 @@ library LibMath { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (uint256 partialAmount) - { + ) internal pure returns (uint256 partialAmount) { partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } @@ -122,17 +90,11 @@ library LibMath { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (uint256 partialAmount) - { + ) internal pure returns (uint256 partialAmount) { // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. - partialAmount = numerator.safeMul(target) - .safeAdd(denominator.safeSub(1)) - .safeDiv(denominator); + partialAmount = numerator.safeMul(target).safeAdd(denominator.safeSub(1)).safeDiv(denominator); return partialAmount; } @@ -146,11 +108,7 @@ library LibMath { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (bool isError) - { + ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError()); } @@ -181,11 +139,7 @@ library LibMath { // 1000 * remainder < numerator * target // so we have a rounding error iff: // 1000 * remainder >= numerator * target - uint256 remainder = mulmod( - target, - numerator, - denominator - ); + uint256 remainder = mulmod(target, numerator, denominator); isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } @@ -199,11 +153,7 @@ library LibMath { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (bool isError) - { + ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError()); } @@ -216,11 +166,7 @@ library LibMath { return false; } // Compute remainder as before - uint256 remainder = mulmod( - target, - numerator, - denominator - ); + uint256 remainder = mulmod(target, numerator, denominator); remainder = denominator.safeSub(remainder) % denominator; isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; diff --git a/contracts/utils/contracts/src/LibMathRichErrors.sol b/contracts/utils/contracts/src/LibMathRichErrors.sol index 16afae26ef..982993af16 100644 --- a/contracts/utils/contracts/src/LibMathRichErrors.sol +++ b/contracts/utils/contracts/src/LibMathRichErrors.sol @@ -1,22 +1,14 @@ pragma solidity ^0.5.9; - library LibMathRichErrors { - // bytes4(keccak256("DivisionByZeroError()")) - bytes internal constant DIVISION_BY_ZERO_ERROR = - hex"a791837c"; + bytes internal constant DIVISION_BY_ZERO_ERROR = hex"a791837c"; // bytes4(keccak256("RoundingError(uint256,uint256,uint256)")) - bytes4 internal constant ROUNDING_ERROR_SELECTOR = - 0x339f3de2; + bytes4 internal constant ROUNDING_ERROR_SELECTOR = 0x339f3de2; // solhint-disable func-name-mixedcase - function DivisionByZeroError() - internal - pure - returns (bytes memory) - { + function DivisionByZeroError() internal pure returns (bytes memory) { return DIVISION_BY_ZERO_ERROR; } @@ -24,16 +16,7 @@ library LibMathRichErrors { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - ROUNDING_ERROR_SELECTOR, - numerator, - denominator, - target - ); + ) internal pure returns (bytes memory) { + return abi.encodeWithSelector(ROUNDING_ERROR_SELECTOR, numerator, denominator, target); } } diff --git a/contracts/utils/contracts/src/LibOwnableRichErrors.sol b/contracts/utils/contracts/src/LibOwnableRichErrors.sol index 0ea83e2007..d8b82c62b8 100644 --- a/contracts/utils/contracts/src/LibOwnableRichErrors.sol +++ b/contracts/utils/contracts/src/LibOwnableRichErrors.sol @@ -1,37 +1,18 @@ pragma solidity ^0.5.9; - library LibOwnableRichErrors { - // bytes4(keccak256("OnlyOwnerError(address,address)")) - bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR = - 0x1de45ad1; + bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR = 0x1de45ad1; // bytes4(keccak256("TransferOwnerToZeroError()")) - bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES = - hex"e69edc3e"; + bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES = hex"e69edc3e"; // solhint-disable func-name-mixedcase - function OnlyOwnerError( - address sender, - address owner - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - ONLY_OWNER_ERROR_SELECTOR, - sender, - owner - ); + function OnlyOwnerError(address sender, address owner) internal pure returns (bytes memory) { + return abi.encodeWithSelector(ONLY_OWNER_ERROR_SELECTOR, sender, owner); } - function TransferOwnerToZeroError() - internal - pure - returns (bytes memory) - { + function TransferOwnerToZeroError() internal pure returns (bytes memory) { return TRANSFER_OWNER_TO_ZERO_ERROR_BYTES; } } diff --git a/contracts/utils/contracts/src/LibReentrancyGuardRichErrors.sol b/contracts/utils/contracts/src/LibReentrancyGuardRichErrors.sol index dd42c7d249..372d964ef2 100644 --- a/contracts/utils/contracts/src/LibReentrancyGuardRichErrors.sol +++ b/contracts/utils/contracts/src/LibReentrancyGuardRichErrors.sol @@ -18,19 +18,12 @@ pragma solidity ^0.5.9; - library LibReentrancyGuardRichErrors { - // bytes4(keccak256("IllegalReentrancyError()")) - bytes internal constant ILLEGAL_REENTRANCY_ERROR_SELECTOR_BYTES = - hex"0c3b823f"; + bytes internal constant ILLEGAL_REENTRANCY_ERROR_SELECTOR_BYTES = hex"0c3b823f"; // solhint-disable func-name-mixedcase - function IllegalReentrancyError() - internal - pure - returns (bytes memory) - { + function IllegalReentrancyError() internal pure returns (bytes memory) { return ILLEGAL_REENTRANCY_ERROR_SELECTOR_BYTES; } } diff --git a/contracts/utils/contracts/src/LibRichErrors.sol b/contracts/utils/contracts/src/LibRichErrors.sol index 8c4837c5d0..be14775fc7 100644 --- a/contracts/utils/contracts/src/LibRichErrors.sol +++ b/contracts/utils/contracts/src/LibRichErrors.sol @@ -18,12 +18,9 @@ pragma solidity ^0.5.9; - library LibRichErrors { - // bytes4(keccak256("Error(string)")) - bytes4 internal constant STANDARD_ERROR_SELECTOR = - 0x08c379a0; + bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. @@ -31,26 +28,15 @@ library LibRichErrors { /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. - function StandardError( - string memory message - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - STANDARD_ERROR_SELECTOR, - bytes(message) - ); + function StandardError(string memory message) internal pure returns (bytes memory) { + return abi.encodeWithSelector(STANDARD_ERROR_SELECTOR, bytes(message)); } + // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. - function rrevert(bytes memory errorData) - internal - pure - { + function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } diff --git a/contracts/utils/contracts/src/LibSafeMath.sol b/contracts/utils/contracts/src/LibSafeMath.sol index 407e02eb45..9903ac3f03 100644 --- a/contracts/utils/contracts/src/LibSafeMath.sol +++ b/contracts/utils/contracts/src/LibSafeMath.sol @@ -3,88 +3,62 @@ pragma solidity ^0.5.9; import "./LibRichErrors.sol"; import "./LibSafeMathRichErrors.sol"; - library LibSafeMath { - - function safeMul(uint256 a, uint256 b) - internal - pure - returns (uint256) - { + function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; if (c / a != b) { - LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( - LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, - a, - b - )); + LibRichErrors.rrevert( + LibSafeMathRichErrors.Uint256BinOpError( + LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, + a, + b + ) + ); } return c; } - function safeDiv(uint256 a, uint256 b) - internal - pure - returns (uint256) - { + function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { - LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( - LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO, - a, - b - )); + LibRichErrors.rrevert( + LibSafeMathRichErrors.Uint256BinOpError(LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO, a, b) + ); } uint256 c = a / b; return c; } - function safeSub(uint256 a, uint256 b) - internal - pure - returns (uint256) - { + function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { if (b > a) { - LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( - LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, - a, - b - )); + LibRichErrors.rrevert( + LibSafeMathRichErrors.Uint256BinOpError( + LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, + a, + b + ) + ); } return a - b; } - function safeAdd(uint256 a, uint256 b) - internal - pure - returns (uint256) - { + function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; if (c < a) { - LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( - LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW, - a, - b - )); + LibRichErrors.rrevert( + LibSafeMathRichErrors.Uint256BinOpError(LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW, a, b) + ); } return c; } - function max256(uint256 a, uint256 b) - internal - pure - returns (uint256) - { + function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } - function min256(uint256 a, uint256 b) - internal - pure - returns (uint256) - { + function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } diff --git a/contracts/utils/contracts/src/LibSafeMathRichErrors.sol b/contracts/utils/contracts/src/LibSafeMathRichErrors.sol index b20e5ab949..a5026ed409 100644 --- a/contracts/utils/contracts/src/LibSafeMathRichErrors.sol +++ b/contracts/utils/contracts/src/LibSafeMathRichErrors.sol @@ -1,15 +1,11 @@ pragma solidity ^0.5.9; - library LibSafeMathRichErrors { - // bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)")) - bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR = - 0xe946c1bb; + bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR = 0xe946c1bb; // bytes4(keccak256("Uint256DowncastError(uint8,uint256)")) - bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR = - 0xc996af7b; + bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR = 0xc996af7b; enum BinOpErrorCodes { ADDITION_OVERFLOW, @@ -29,31 +25,11 @@ library LibSafeMathRichErrors { BinOpErrorCodes errorCode, uint256 a, uint256 b - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - UINT256_BINOP_ERROR_SELECTOR, - errorCode, - a, - b - ); + ) internal pure returns (bytes memory) { + return abi.encodeWithSelector(UINT256_BINOP_ERROR_SELECTOR, errorCode, a, b); } - function Uint256DowncastError( - DowncastErrorCodes errorCode, - uint256 a - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - UINT256_DOWNCAST_ERROR_SELECTOR, - errorCode, - a - ); + function Uint256DowncastError(DowncastErrorCodes errorCode, uint256 a) internal pure returns (bytes memory) { + return abi.encodeWithSelector(UINT256_DOWNCAST_ERROR_SELECTOR, errorCode, a); } } diff --git a/contracts/utils/contracts/src/Ownable.sol b/contracts/utils/contracts/src/Ownable.sol index eff9897552..ed1763d10d 100644 --- a/contracts/utils/contracts/src/Ownable.sol +++ b/contracts/utils/contracts/src/Ownable.sol @@ -22,17 +22,12 @@ import "./interfaces/IOwnable.sol"; import "./LibOwnableRichErrors.sol"; import "./LibRichErrors.sol"; - -contract Ownable is - IOwnable -{ +contract Ownable is IOwnable { /// @dev The owner of this contract. /// @return 0 The owner address. address public owner; - constructor () - public - { + constructor() public { owner = msg.sender; } @@ -43,10 +38,7 @@ contract Ownable is /// @dev Change the owner of this contract. /// @param newOwner New owner address. - function transferOwnership(address newOwner) - public - onlyOwner - { + function transferOwnership(address newOwner) public onlyOwner { if (newOwner == address(0)) { LibRichErrors.rrevert(LibOwnableRichErrors.TransferOwnerToZeroError()); } else { @@ -55,15 +47,9 @@ contract Ownable is } } - function _assertSenderIsOwner() - internal - view - { + function _assertSenderIsOwner() internal view { if (msg.sender != owner) { - LibRichErrors.rrevert(LibOwnableRichErrors.OnlyOwnerError( - msg.sender, - owner - )); + LibRichErrors.rrevert(LibOwnableRichErrors.OnlyOwnerError(msg.sender, owner)); } } } diff --git a/contracts/utils/contracts/src/ReentrancyGuard.sol b/contracts/utils/contracts/src/ReentrancyGuard.sol index 273483e3c5..cfafc01c74 100644 --- a/contracts/utils/contracts/src/ReentrancyGuard.sol +++ b/contracts/utils/contracts/src/ReentrancyGuard.sol @@ -21,9 +21,7 @@ pragma solidity ^0.5.9; import "./LibReentrancyGuardRichErrors.sol"; import "./LibRichErrors.sol"; - contract ReentrancyGuard { - // Locked state of mutex. bool private _locked = false; @@ -35,22 +33,16 @@ contract ReentrancyGuard { _unlockMutex(); } - function _lockMutexOrThrowIfAlreadyLocked() - internal - { + function _lockMutexOrThrowIfAlreadyLocked() internal { // Ensure mutex is unlocked. if (_locked) { - LibRichErrors.rrevert( - LibReentrancyGuardRichErrors.IllegalReentrancyError() - ); + LibRichErrors.rrevert(LibReentrancyGuardRichErrors.IllegalReentrancyError()); } // Lock mutex. _locked = true; } - function _unlockMutex() - internal - { + function _unlockMutex() internal { // Unlock mutex. _locked = false; } diff --git a/contracts/utils/contracts/src/Refundable.sol b/contracts/utils/contracts/src/Refundable.sol index 55d32b492b..77f47c4d0a 100644 --- a/contracts/utils/contracts/src/Refundable.sol +++ b/contracts/utils/contracts/src/Refundable.sol @@ -20,27 +20,23 @@ pragma solidity ^0.5.9; import "./ReentrancyGuard.sol"; - -contract Refundable is - ReentrancyGuard -{ - +contract Refundable is ReentrancyGuard { // This bool is used by the refund modifier to allow for lazily evaluated refunds. bool internal _shouldNotRefund; - modifier refundFinalBalance { + modifier refundFinalBalance() { _; _refundNonZeroBalanceIfEnabled(); } - modifier refundFinalBalanceNoReentry { + modifier refundFinalBalanceNoReentry() { _lockMutexOrThrowIfAlreadyLocked(); _; _refundNonZeroBalanceIfEnabled(); _unlockMutex(); } - modifier disableRefundUntilEnd { + modifier disableRefundUntilEnd() { if (_areRefundsDisabled()) { _; } else { @@ -50,41 +46,29 @@ contract Refundable is } } - function _refundNonZeroBalanceIfEnabled() - internal - { + function _refundNonZeroBalanceIfEnabled() internal { if (!_areRefundsDisabled()) { _refundNonZeroBalance(); } } - function _refundNonZeroBalance() - internal - { + function _refundNonZeroBalance() internal { uint256 balance = address(this).balance; if (balance > 0) { msg.sender.transfer(balance); } } - function _disableRefund() - internal - { + function _disableRefund() internal { _shouldNotRefund = true; } - function _enableAndRefundNonZeroBalance() - internal - { + function _enableAndRefundNonZeroBalance() internal { _shouldNotRefund = false; _refundNonZeroBalance(); } - function _areRefundsDisabled() - internal - view - returns (bool) - { + function _areRefundsDisabled() internal view returns (bool) { return _shouldNotRefund; } } diff --git a/contracts/utils/contracts/src/interfaces/IAuthorizable.sol b/contracts/utils/contracts/src/interfaces/IAuthorizable.sol index cfdaea1439..2e817f5c38 100644 --- a/contracts/utils/contracts/src/interfaces/IAuthorizable.sol +++ b/contracts/utils/contracts/src/interfaces/IAuthorizable.sol @@ -20,45 +20,27 @@ pragma solidity ^0.5.9; import "./IOwnable.sol"; - -contract IAuthorizable is - IOwnable -{ +contract IAuthorizable is IOwnable { // Event logged when a new address is authorized. - event AuthorizedAddressAdded( - address indexed target, - address indexed caller - ); + event AuthorizedAddressAdded(address indexed target, address indexed caller); // Event logged when a currently authorized address is unauthorized. - event AuthorizedAddressRemoved( - address indexed target, - address indexed caller - ); + event AuthorizedAddressRemoved(address indexed target, address indexed caller); /// @dev Authorizes an address. /// @param target Address to authorize. - function addAuthorizedAddress(address target) - external; + function addAuthorizedAddress(address target) external; /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. - function removeAuthorizedAddress(address target) - external; + function removeAuthorizedAddress(address target) external; /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. /// @param index Index of target in authorities array. - function removeAuthorizedAddressAtIndex( - address target, - uint256 index - ) - external; + function removeAuthorizedAddressAtIndex(address target, uint256 index) external; /// @dev Gets all authorized addresses. /// @return Array of authorized addresses. - function getAuthorizedAddresses() - external - view - returns (address[] memory); + function getAuthorizedAddresses() external view returns (address[] memory); } diff --git a/contracts/utils/contracts/src/interfaces/IOwnable.sol b/contracts/utils/contracts/src/interfaces/IOwnable.sol index 2b15d32877..c2b6b2ed43 100644 --- a/contracts/utils/contracts/src/interfaces/IOwnable.sol +++ b/contracts/utils/contracts/src/interfaces/IOwnable.sol @@ -18,9 +18,7 @@ pragma solidity ^0.5.9; - contract IOwnable { - /// @dev Emitted by Ownable when ownership is transferred. /// @param previousOwner The previous owner of the contract. /// @param newOwner The new owner of the contract. @@ -28,6 +26,5 @@ contract IOwnable { /// @dev Transfers ownership of the contract to a new address. /// @param newOwner The address that will become the owner. - function transferOwnership(address newOwner) - public; + function transferOwnership(address newOwner) public; } diff --git a/contracts/utils/contracts/src/v06/AuthorizableV06.sol b/contracts/utils/contracts/src/v06/AuthorizableV06.sol index 2e0601efec..1a1f575491 100644 --- a/contracts/utils/contracts/src/v06/AuthorizableV06.sol +++ b/contracts/utils/contracts/src/v06/AuthorizableV06.sol @@ -24,14 +24,10 @@ import "./errors/LibRichErrorsV06.sol"; import "./errors/LibAuthorizableRichErrorsV06.sol"; import "./OwnableV06.sol"; - // solhint-disable no-empty-blocks -contract AuthorizableV06 is - OwnableV06, - IAuthorizableV06 -{ +contract AuthorizableV06 is OwnableV06, IAuthorizableV06 { /// @dev Only authorized addresses can invoke functions with this modifier. - modifier onlyAuthorized { + modifier onlyAuthorized() { _assertSenderIsAuthorized(); _; } @@ -39,35 +35,24 @@ contract AuthorizableV06 is // @dev Whether an address is authorized to call privileged functions. // @param 0 Address to query. // @return 0 Whether the address is authorized. - mapping (address => bool) public override authorized; + mapping(address => bool) public override authorized; // @dev Whether an address is authorized to call privileged functions. // @param 0 Index of authorized address. // @return 0 Authorized address. address[] public override authorities; /// @dev Initializes the `owner` address. - constructor() - public - OwnableV06() - {} + constructor() public OwnableV06() {} /// @dev Authorizes an address. /// @param target Address to authorize. - function addAuthorizedAddress(address target) - external - override - onlyOwner - { + function addAuthorizedAddress(address target) external override onlyOwner { _addAuthorizedAddress(target); } /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. - function removeAuthorizedAddress(address target) - external - override - onlyOwner - { + function removeAuthorizedAddress(address target) external override onlyOwner { if (!authorized[target]) { LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.TargetNotAuthorizedError(target)); } @@ -82,33 +67,18 @@ contract AuthorizableV06 is /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. /// @param index Index of target in authorities array. - function removeAuthorizedAddressAtIndex( - address target, - uint256 index - ) - external - override - onlyOwner - { + function removeAuthorizedAddressAtIndex(address target, uint256 index) external override onlyOwner { _removeAuthorizedAddressAtIndex(target, index); } /// @dev Gets all authorized addresses. /// @return Array of authorized addresses. - function getAuthorizedAddresses() - external - override - view - returns (address[] memory) - { + function getAuthorizedAddresses() external view override returns (address[] memory) { return authorities; } /// @dev Reverts if msg.sender is not authorized. - function _assertSenderIsAuthorized() - internal - view - { + function _assertSenderIsAuthorized() internal view { if (!authorized[msg.sender]) { LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.SenderNotAuthorizedError(msg.sender)); } @@ -116,9 +86,7 @@ contract AuthorizableV06 is /// @dev Authorizes an address. /// @param target Address to authorize. - function _addAuthorizedAddress(address target) - internal - { + function _addAuthorizedAddress(address target) internal { // Ensure that the target is not the zero address. if (target == address(0)) { LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.ZeroCantBeAuthorizedError()); @@ -137,26 +105,17 @@ contract AuthorizableV06 is /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. /// @param index Index of target in authorities array. - function _removeAuthorizedAddressAtIndex( - address target, - uint256 index - ) - internal - { + function _removeAuthorizedAddressAtIndex(address target, uint256 index) internal { if (!authorized[target]) { LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.TargetNotAuthorizedError(target)); } if (index >= authorities.length) { - LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.IndexOutOfBoundsError( - index, - authorities.length - )); + LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.IndexOutOfBoundsError(index, authorities.length)); } if (authorities[index] != target) { - LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.AuthorizedAddressMismatchError( - authorities[index], - target - )); + LibRichErrorsV06.rrevert( + LibAuthorizableRichErrorsV06.AuthorizedAddressMismatchError(authorities[index], target) + ); } delete authorized[target]; diff --git a/contracts/utils/contracts/src/v06/LibBytesV06.sol b/contracts/utils/contracts/src/v06/LibBytesV06.sol index 2819a405ce..1254d4c77e 100644 --- a/contracts/utils/contracts/src/v06/LibBytesV06.sol +++ b/contracts/utils/contracts/src/v06/LibBytesV06.sol @@ -22,9 +22,7 @@ pragma solidity ^0.6.5; import "./errors/LibBytesRichErrorsV06.sol"; import "./errors/LibRichErrorsV06.sol"; - library LibBytesV06 { - using LibBytesV06 for bytes; /// @dev Gets the memory address for a byte array. @@ -32,11 +30,7 @@ library LibBytesV06 { /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. - function rawAddress(bytes memory input) - internal - pure - returns (uint256 memoryAddress) - { + function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } @@ -46,11 +40,7 @@ library LibBytesV06 { /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. - function contentAddress(bytes memory input) - internal - pure - returns (uint256 memoryAddress) - { + function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } @@ -65,10 +55,7 @@ library LibBytesV06 { uint256 dest, uint256 source, uint256 length - ) - internal - pure - { + ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. @@ -120,7 +107,11 @@ library LibBytesV06 { // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks - for {} lt(source, sEnd) {} { + for { + + } lt(source, sEnd) { + + } { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) @@ -151,7 +142,11 @@ library LibBytesV06 { // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks - for {} slt(dest, dEnd) {} { + for { + + } slt(dest, dEnd) { + + } { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) @@ -173,35 +168,31 @@ library LibBytesV06 { bytes memory b, uint256 from, uint256 to - ) - internal - pure - returns (bytes memory result) - { + ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { - LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( - LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, - from, - to - )); + LibRichErrorsV06.rrevert( + LibBytesRichErrorsV06.InvalidByteOperationError( + LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, + from, + to + ) + ); } if (to > b.length) { - LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( - LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, - to, - b.length - )); + LibRichErrorsV06.rrevert( + LibBytesRichErrorsV06.InvalidByteOperationError( + LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, + to, + b.length + ) + ); } // Create a new bytes structure and copy contents result = new bytes(to - from); - memCopy( - result.contentAddress(), - b.contentAddress() + from, - result.length - ); + memCopy(result.contentAddress(), b.contentAddress() + from, result.length); return result; } @@ -216,26 +207,26 @@ library LibBytesV06 { bytes memory b, uint256 from, uint256 to - ) - internal - pure - returns (bytes memory result) - { + ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { - LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( - LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, - from, - to - )); + LibRichErrorsV06.rrevert( + LibBytesRichErrorsV06.InvalidByteOperationError( + LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, + from, + to + ) + ); } if (to > b.length) { - LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( - LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, - to, - b.length - )); + LibRichErrorsV06.rrevert( + LibBytesRichErrorsV06.InvalidByteOperationError( + LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, + to, + b.length + ) + ); } // Create a new bytes structure around [from, to) in-place. @@ -249,17 +240,15 @@ library LibBytesV06 { /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The byte that was popped off. - function popLastByte(bytes memory b) - internal - pure - returns (bytes1 result) - { + function popLastByte(bytes memory b) internal pure returns (bytes1 result) { if (b.length == 0) { - LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( - LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, - b.length, - 0 - )); + LibRichErrorsV06.rrevert( + LibBytesRichErrorsV06.InvalidByteOperationError( + LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, + b.length, + 0 + ) + ); } // Store last byte. @@ -277,14 +266,7 @@ library LibBytesV06 { /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return equal True if arrays are the same. False otherwise. - function equals( - bytes memory lhs, - bytes memory rhs - ) - internal - pure - returns (bool equal) - { + function equals(bytes memory lhs, bytes memory rhs) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. @@ -295,20 +277,15 @@ library LibBytesV06 { /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return result address from byte array. - function readAddress( - bytes memory b, - uint256 index - ) - internal - pure - returns (address result) - { + function readAddress(bytes memory b, uint256 index) internal pure returns (address result) { if (b.length < index + 20) { - LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( - LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, - b.length, - index + 20 // 20 is length of address - )); + LibRichErrorsV06.rrevert( + LibBytesRichErrorsV06.InvalidByteOperationError( + LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, + b.length, + index + 20 // 20 is length of address + ) + ); } // Add offset to index: @@ -334,16 +311,15 @@ library LibBytesV06 { bytes memory b, uint256 index, address input - ) - internal - pure - { + ) internal pure { if (b.length < index + 20) { - LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( - LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, - b.length, - index + 20 // 20 is length of address - )); + LibRichErrorsV06.rrevert( + LibBytesRichErrorsV06.InvalidByteOperationError( + LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, + b.length, + index + 20 // 20 is length of address + ) + ); } // Add offset to index: @@ -379,20 +355,15 @@ library LibBytesV06 { /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return result bytes32 value from byte array. - function readBytes32( - bytes memory b, - uint256 index - ) - internal - pure - returns (bytes32 result) - { + function readBytes32(bytes memory b, uint256 index) internal pure returns (bytes32 result) { if (b.length < index + 32) { - LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( - LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, - b.length, - index + 32 - )); + LibRichErrorsV06.rrevert( + LibBytesRichErrorsV06.InvalidByteOperationError( + LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, + b.length, + index + 32 + ) + ); } // Arrays are prefixed by a 256 bit length parameter @@ -413,16 +384,15 @@ library LibBytesV06 { bytes memory b, uint256 index, bytes32 input - ) - internal - pure - { + ) internal pure { if (b.length < index + 32) { - LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( - LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, - b.length, - index + 32 - )); + LibRichErrorsV06.rrevert( + LibBytesRichErrorsV06.InvalidByteOperationError( + LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, + b.length, + index + 32 + ) + ); } // Arrays are prefixed by a 256 bit length parameter @@ -438,14 +408,7 @@ library LibBytesV06 { /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return result uint256 value from byte array. - function readUint256( - bytes memory b, - uint256 index - ) - internal - pure - returns (uint256 result) - { + function readUint256(bytes memory b, uint256 index) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } @@ -458,10 +421,7 @@ library LibBytesV06 { bytes memory b, uint256 index, uint256 input - ) - internal - pure - { + ) internal pure { writeBytes32(b, index, bytes32(input)); } @@ -469,20 +429,15 @@ library LibBytesV06 { /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return result bytes4 value from byte array. - function readBytes4( - bytes memory b, - uint256 index - ) - internal - pure - returns (bytes4 result) - { + function readBytes4(bytes memory b, uint256 index) internal pure returns (bytes4 result) { if (b.length < index + 4) { - LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( - LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, - b.length, - index + 4 - )); + LibRichErrorsV06.rrevert( + LibBytesRichErrorsV06.InvalidByteOperationError( + LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, + b.length, + index + 4 + ) + ); } // Arrays are prefixed by a 32 byte length field @@ -503,10 +458,7 @@ library LibBytesV06 { /// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array. /// @param b Bytes array to write new length to. /// @param length New length of byte array. - function writeLength(bytes memory b, uint256 length) - internal - pure - { + function writeLength(bytes memory b, uint256 length) internal pure { assembly { mstore(b, length) } diff --git a/contracts/utils/contracts/src/v06/LibMathV06.sol b/contracts/utils/contracts/src/v06/LibMathV06.sol index 59a60b6dc7..4864792874 100644 --- a/contracts/utils/contracts/src/v06/LibMathV06.sol +++ b/contracts/utils/contracts/src/v06/LibMathV06.sol @@ -23,9 +23,7 @@ import "./LibSafeMathV06.sol"; import "./errors/LibRichErrorsV06.sol"; import "./errors/LibMathRichErrorsV06.sol"; - library LibMathV06 { - using LibSafeMathV06 for uint256; /// @dev Calculates partial value given a numerator and denominator rounded down. @@ -38,21 +36,9 @@ library LibMathV06 { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (uint256 partialAmount) - { - if (isRoundingErrorFloor( - numerator, - denominator, - target - )) { - LibRichErrorsV06.rrevert(LibMathRichErrorsV06.RoundingError( - numerator, - denominator, - target - )); + ) internal pure returns (uint256 partialAmount) { + if (isRoundingErrorFloor(numerator, denominator, target)) { + LibRichErrorsV06.rrevert(LibMathRichErrorsV06.RoundingError(numerator, denominator, target)); } partialAmount = numerator.safeMul(target).safeDiv(denominator); @@ -69,29 +55,15 @@ library LibMathV06 { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (uint256 partialAmount) - { - if (isRoundingErrorCeil( - numerator, - denominator, - target - )) { - LibRichErrorsV06.rrevert(LibMathRichErrorsV06.RoundingError( - numerator, - denominator, - target - )); + ) internal pure returns (uint256 partialAmount) { + if (isRoundingErrorCeil(numerator, denominator, target)) { + LibRichErrorsV06.rrevert(LibMathRichErrorsV06.RoundingError(numerator, denominator, target)); } // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. - partialAmount = numerator.safeMul(target) - .safeAdd(denominator.safeSub(1)) - .safeDiv(denominator); + partialAmount = numerator.safeMul(target).safeAdd(denominator.safeSub(1)).safeDiv(denominator); return partialAmount; } @@ -105,11 +77,7 @@ library LibMathV06 { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (uint256 partialAmount) - { + ) internal pure returns (uint256 partialAmount) { partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } @@ -123,17 +91,11 @@ library LibMathV06 { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (uint256 partialAmount) - { + ) internal pure returns (uint256 partialAmount) { // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. - partialAmount = numerator.safeMul(target) - .safeAdd(denominator.safeSub(1)) - .safeDiv(denominator); + partialAmount = numerator.safeMul(target).safeAdd(denominator.safeSub(1)).safeDiv(denominator); return partialAmount; } @@ -147,11 +109,7 @@ library LibMathV06 { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (bool isError) - { + ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrorsV06.rrevert(LibMathRichErrorsV06.DivisionByZeroError()); } @@ -182,11 +140,7 @@ library LibMathV06 { // 1000 * remainder < numerator * target // so we have a rounding error iff: // 1000 * remainder >= numerator * target - uint256 remainder = mulmod( - target, - numerator, - denominator - ); + uint256 remainder = mulmod(target, numerator, denominator); isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } @@ -200,11 +154,7 @@ library LibMathV06 { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (bool isError) - { + ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrorsV06.rrevert(LibMathRichErrorsV06.DivisionByZeroError()); } @@ -217,11 +167,7 @@ library LibMathV06 { return false; } // Compute remainder as before - uint256 remainder = mulmod( - target, - numerator, - denominator - ); + uint256 remainder = mulmod(target, numerator, denominator); remainder = denominator.safeSub(remainder) % denominator; isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; diff --git a/contracts/utils/contracts/src/v06/LibSafeMathV06.sol b/contracts/utils/contracts/src/v06/LibSafeMathV06.sol index 781f902936..33cc9f2c24 100644 --- a/contracts/utils/contracts/src/v06/LibSafeMathV06.sol +++ b/contracts/utils/contracts/src/v06/LibSafeMathV06.sol @@ -22,183 +22,147 @@ pragma solidity ^0.6.5; import "./errors/LibRichErrorsV06.sol"; import "./errors/LibSafeMathRichErrorsV06.sol"; - library LibSafeMathV06 { - - function safeMul(uint256 a, uint256 b) - internal - pure - returns (uint256) - { + function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; if (c / a != b) { - LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( - LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, - a, - b - )); + LibRichErrorsV06.rrevert( + LibSafeMathRichErrorsV06.Uint256BinOpError( + LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, + a, + b + ) + ); } return c; } - function safeDiv(uint256 a, uint256 b) - internal - pure - returns (uint256) - { + function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { - LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( - LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO, - a, - b - )); + LibRichErrorsV06.rrevert( + LibSafeMathRichErrorsV06.Uint256BinOpError( + LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO, + a, + b + ) + ); } uint256 c = a / b; return c; } - function safeSub(uint256 a, uint256 b) - internal - pure - returns (uint256) - { + function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { if (b > a) { - LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( - LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, - a, - b - )); + LibRichErrorsV06.rrevert( + LibSafeMathRichErrorsV06.Uint256BinOpError( + LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, + a, + b + ) + ); } return a - b; } - function safeAdd(uint256 a, uint256 b) - internal - pure - returns (uint256) - { + function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; if (c < a) { - LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( - LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW, - a, - b - )); + LibRichErrorsV06.rrevert( + LibSafeMathRichErrorsV06.Uint256BinOpError( + LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW, + a, + b + ) + ); } return c; } - function max256(uint256 a, uint256 b) - internal - pure - returns (uint256) - { + function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } - function min256(uint256 a, uint256 b) - internal - pure - returns (uint256) - { + function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } - function safeMul128(uint128 a, uint128 b) - internal - pure - returns (uint128) - { + function safeMul128(uint128 a, uint128 b) internal pure returns (uint128) { if (a == 0) { return 0; } uint128 c = a * b; if (c / a != b) { - LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( - LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, - a, - b - )); + LibRichErrorsV06.rrevert( + LibSafeMathRichErrorsV06.Uint256BinOpError( + LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, + a, + b + ) + ); } return c; } - function safeDiv128(uint128 a, uint128 b) - internal - pure - returns (uint128) - { + function safeDiv128(uint128 a, uint128 b) internal pure returns (uint128) { if (b == 0) { - LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( - LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO, - a, - b - )); + LibRichErrorsV06.rrevert( + LibSafeMathRichErrorsV06.Uint256BinOpError( + LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO, + a, + b + ) + ); } uint128 c = a / b; return c; } - function safeSub128(uint128 a, uint128 b) - internal - pure - returns (uint128) - { + function safeSub128(uint128 a, uint128 b) internal pure returns (uint128) { if (b > a) { - LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( - LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, - a, - b - )); + LibRichErrorsV06.rrevert( + LibSafeMathRichErrorsV06.Uint256BinOpError( + LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, + a, + b + ) + ); } return a - b; } - function safeAdd128(uint128 a, uint128 b) - internal - pure - returns (uint128) - { + function safeAdd128(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; if (c < a) { - LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( - LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW, - a, - b - )); + LibRichErrorsV06.rrevert( + LibSafeMathRichErrorsV06.Uint256BinOpError( + LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW, + a, + b + ) + ); } return c; } - function max128(uint128 a, uint128 b) - internal - pure - returns (uint128) - { + function max128(uint128 a, uint128 b) internal pure returns (uint128) { return a >= b ? a : b; } - function min128(uint128 a, uint128 b) - internal - pure - returns (uint128) - { + function min128(uint128 a, uint128 b) internal pure returns (uint128) { return a < b ? a : b; } - function safeDowncastToUint128(uint256 a) - internal - pure - returns (uint128) - { + function safeDowncastToUint128(uint256 a) internal pure returns (uint128) { if (a > type(uint128).max) { - LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256DowncastError( - LibSafeMathRichErrorsV06.DowncastErrorCodes.VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT128, - a - )); + LibRichErrorsV06.rrevert( + LibSafeMathRichErrorsV06.Uint256DowncastError( + LibSafeMathRichErrorsV06.DowncastErrorCodes.VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT128, + a + ) + ); } return uint128(a); } diff --git a/contracts/utils/contracts/src/v06/OwnableV06.sol b/contracts/utils/contracts/src/v06/OwnableV06.sol index f907b59418..59f70cfa7a 100644 --- a/contracts/utils/contracts/src/v06/OwnableV06.sol +++ b/contracts/utils/contracts/src/v06/OwnableV06.sol @@ -23,10 +23,7 @@ import "./interfaces/IOwnableV06.sol"; import "./errors/LibRichErrorsV06.sol"; import "./errors/LibOwnableRichErrorsV06.sol"; - -contract OwnableV06 is - IOwnableV06 -{ +contract OwnableV06 is IOwnableV06 { /// @dev The owner of this contract. /// @return 0 The owner address. address public override owner; @@ -42,11 +39,7 @@ contract OwnableV06 is /// @dev Change the owner of this contract. /// @param newOwner New owner address. - function transferOwnership(address newOwner) - public - override - onlyOwner - { + function transferOwnership(address newOwner) public override onlyOwner { if (newOwner == address(0)) { LibRichErrorsV06.rrevert(LibOwnableRichErrorsV06.TransferOwnerToZeroError()); } else { @@ -55,15 +48,9 @@ contract OwnableV06 is } } - function _assertSenderIsOwner() - internal - view - { + function _assertSenderIsOwner() internal view { if (msg.sender != owner) { - LibRichErrorsV06.rrevert(LibOwnableRichErrorsV06.OnlyOwnerError( - msg.sender, - owner - )); + LibRichErrorsV06.rrevert(LibOwnableRichErrorsV06.OnlyOwnerError(msg.sender, owner)); } } } diff --git a/contracts/utils/contracts/src/v06/ReentrancyGuardV06.sol b/contracts/utils/contracts/src/v06/ReentrancyGuardV06.sol index 2e21752cfd..33dd4782a8 100644 --- a/contracts/utils/contracts/src/v06/ReentrancyGuardV06.sol +++ b/contracts/utils/contracts/src/v06/ReentrancyGuardV06.sol @@ -22,9 +22,7 @@ pragma solidity ^0.6.5; import "./errors/LibReentrancyGuardRichErrorsV06.sol"; import "./errors/LibRichErrorsV06.sol"; - contract ReentrancyGuardV06 { - // Locked state of mutex. bool private _locked = false; @@ -36,22 +34,16 @@ contract ReentrancyGuardV06 { _unlockMutex(); } - function _lockMutexOrThrowIfAlreadyLocked() - internal - { + function _lockMutexOrThrowIfAlreadyLocked() internal { // Ensure mutex is unlocked. if (_locked) { - LibRichErrorsV06.rrevert( - LibReentrancyGuardRichErrorsV06.IllegalReentrancyError() - ); + LibRichErrorsV06.rrevert(LibReentrancyGuardRichErrorsV06.IllegalReentrancyError()); } // Lock mutex. _locked = true; } - function _unlockMutex() - internal - { + function _unlockMutex() internal { // Unlock mutex. _locked = false; } diff --git a/contracts/utils/contracts/src/v06/errors/LibAuthorizableRichErrorsV06.sol b/contracts/utils/contracts/src/v06/errors/LibAuthorizableRichErrorsV06.sol index b294577838..6bb318a692 100644 --- a/contracts/utils/contracts/src/v06/errors/LibAuthorizableRichErrorsV06.sol +++ b/contracts/utils/contracts/src/v06/errors/LibAuthorizableRichErrorsV06.sol @@ -19,102 +19,47 @@ pragma solidity ^0.6.5; - library LibAuthorizableRichErrorsV06 { - // bytes4(keccak256("AuthorizedAddressMismatchError(address,address)")) - bytes4 internal constant AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR = - 0x140a84db; + bytes4 internal constant AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR = 0x140a84db; // bytes4(keccak256("IndexOutOfBoundsError(uint256,uint256)")) - bytes4 internal constant INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR = - 0xe9f83771; + bytes4 internal constant INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR = 0xe9f83771; // bytes4(keccak256("SenderNotAuthorizedError(address)")) - bytes4 internal constant SENDER_NOT_AUTHORIZED_ERROR_SELECTOR = - 0xb65a25b9; + bytes4 internal constant SENDER_NOT_AUTHORIZED_ERROR_SELECTOR = 0xb65a25b9; // bytes4(keccak256("TargetAlreadyAuthorizedError(address)")) - bytes4 internal constant TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR = - 0xde16f1a0; + bytes4 internal constant TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR = 0xde16f1a0; // bytes4(keccak256("TargetNotAuthorizedError(address)")) - bytes4 internal constant TARGET_NOT_AUTHORIZED_ERROR_SELECTOR = - 0xeb5108a2; + bytes4 internal constant TARGET_NOT_AUTHORIZED_ERROR_SELECTOR = 0xeb5108a2; // bytes4(keccak256("ZeroCantBeAuthorizedError()")) - bytes internal constant ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES = - hex"57654fe4"; + bytes internal constant ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES = hex"57654fe4"; // solhint-disable func-name-mixedcase - function AuthorizedAddressMismatchError( - address authorized, - address target - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR, - authorized, - target - ); + function AuthorizedAddressMismatchError(address authorized, address target) internal pure returns (bytes memory) { + return abi.encodeWithSelector(AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR, authorized, target); } - function IndexOutOfBoundsError( - uint256 index, - uint256 length - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR, - index, - length - ); + function IndexOutOfBoundsError(uint256 index, uint256 length) internal pure returns (bytes memory) { + return abi.encodeWithSelector(INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR, index, length); } - function SenderNotAuthorizedError(address sender) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - SENDER_NOT_AUTHORIZED_ERROR_SELECTOR, - sender - ); + function SenderNotAuthorizedError(address sender) internal pure returns (bytes memory) { + return abi.encodeWithSelector(SENDER_NOT_AUTHORIZED_ERROR_SELECTOR, sender); } - function TargetAlreadyAuthorizedError(address target) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR, - target - ); + function TargetAlreadyAuthorizedError(address target) internal pure returns (bytes memory) { + return abi.encodeWithSelector(TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR, target); } - function TargetNotAuthorizedError(address target) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - TARGET_NOT_AUTHORIZED_ERROR_SELECTOR, - target - ); + function TargetNotAuthorizedError(address target) internal pure returns (bytes memory) { + return abi.encodeWithSelector(TARGET_NOT_AUTHORIZED_ERROR_SELECTOR, target); } - function ZeroCantBeAuthorizedError() - internal - pure - returns (bytes memory) - { + function ZeroCantBeAuthorizedError() internal pure returns (bytes memory) { return ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES; } } diff --git a/contracts/utils/contracts/src/v06/errors/LibBytesRichErrorsV06.sol b/contracts/utils/contracts/src/v06/errors/LibBytesRichErrorsV06.sol index adab0b7a83..510cad651d 100644 --- a/contracts/utils/contracts/src/v06/errors/LibBytesRichErrorsV06.sol +++ b/contracts/utils/contracts/src/v06/errors/LibBytesRichErrorsV06.sol @@ -19,9 +19,7 @@ pragma solidity ^0.6.5; - library LibBytesRichErrorsV06 { - enum InvalidByteOperationErrorCodes { FromLessThanOrEqualsToRequired, ToLessThanOrEqualsLengthRequired, @@ -34,24 +32,14 @@ library LibBytesRichErrorsV06 { } // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)")) - bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = - 0x28006595; + bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = 0x28006595; // solhint-disable func-name-mixedcase function InvalidByteOperationError( InvalidByteOperationErrorCodes errorCode, uint256 offset, uint256 required - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - INVALID_BYTE_OPERATION_ERROR_SELECTOR, - errorCode, - offset, - required - ); + ) internal pure returns (bytes memory) { + return abi.encodeWithSelector(INVALID_BYTE_OPERATION_ERROR_SELECTOR, errorCode, offset, required); } } diff --git a/contracts/utils/contracts/src/v06/errors/LibMathRichErrorsV06.sol b/contracts/utils/contracts/src/v06/errors/LibMathRichErrorsV06.sol index 5fdf42092c..c702ccbeaa 100644 --- a/contracts/utils/contracts/src/v06/errors/LibMathRichErrorsV06.sol +++ b/contracts/utils/contracts/src/v06/errors/LibMathRichErrorsV06.sol @@ -19,23 +19,15 @@ pragma solidity ^0.6.5; - library LibMathRichErrorsV06 { - // bytes4(keccak256("DivisionByZeroError()")) - bytes internal constant DIVISION_BY_ZERO_ERROR = - hex"a791837c"; + bytes internal constant DIVISION_BY_ZERO_ERROR = hex"a791837c"; // bytes4(keccak256("RoundingError(uint256,uint256,uint256)")) - bytes4 internal constant ROUNDING_ERROR_SELECTOR = - 0x339f3de2; + bytes4 internal constant ROUNDING_ERROR_SELECTOR = 0x339f3de2; // solhint-disable func-name-mixedcase - function DivisionByZeroError() - internal - pure - returns (bytes memory) - { + function DivisionByZeroError() internal pure returns (bytes memory) { return DIVISION_BY_ZERO_ERROR; } @@ -43,16 +35,7 @@ library LibMathRichErrorsV06 { uint256 numerator, uint256 denominator, uint256 target - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - ROUNDING_ERROR_SELECTOR, - numerator, - denominator, - target - ); + ) internal pure returns (bytes memory) { + return abi.encodeWithSelector(ROUNDING_ERROR_SELECTOR, numerator, denominator, target); } } diff --git a/contracts/utils/contracts/src/v06/errors/LibOwnableRichErrorsV06.sol b/contracts/utils/contracts/src/v06/errors/LibOwnableRichErrorsV06.sol index e1430d63ef..f0768ce3c6 100644 --- a/contracts/utils/contracts/src/v06/errors/LibOwnableRichErrorsV06.sol +++ b/contracts/utils/contracts/src/v06/errors/LibOwnableRichErrorsV06.sol @@ -18,38 +18,19 @@ */ pragma solidity ^0.6.5; - library LibOwnableRichErrorsV06 { - // bytes4(keccak256("OnlyOwnerError(address,address)")) - bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR = - 0x1de45ad1; + bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR = 0x1de45ad1; // bytes4(keccak256("TransferOwnerToZeroError()")) - bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES = - hex"e69edc3e"; + bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES = hex"e69edc3e"; // solhint-disable func-name-mixedcase - function OnlyOwnerError( - address sender, - address owner - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - ONLY_OWNER_ERROR_SELECTOR, - sender, - owner - ); + function OnlyOwnerError(address sender, address owner) internal pure returns (bytes memory) { + return abi.encodeWithSelector(ONLY_OWNER_ERROR_SELECTOR, sender, owner); } - function TransferOwnerToZeroError() - internal - pure - returns (bytes memory) - { + function TransferOwnerToZeroError() internal pure returns (bytes memory) { return TRANSFER_OWNER_TO_ZERO_ERROR_BYTES; } } diff --git a/contracts/utils/contracts/src/v06/errors/LibReentrancyGuardRichErrorsV06.sol b/contracts/utils/contracts/src/v06/errors/LibReentrancyGuardRichErrorsV06.sol index eb77ce974a..75eb6d619f 100644 --- a/contracts/utils/contracts/src/v06/errors/LibReentrancyGuardRichErrorsV06.sol +++ b/contracts/utils/contracts/src/v06/errors/LibReentrancyGuardRichErrorsV06.sol @@ -19,19 +19,12 @@ pragma solidity ^0.6.5; - library LibReentrancyGuardRichErrorsV06 { - // bytes4(keccak256("IllegalReentrancyError()")) - bytes internal constant ILLEGAL_REENTRANCY_ERROR_SELECTOR_BYTES = - hex"0c3b823f"; + bytes internal constant ILLEGAL_REENTRANCY_ERROR_SELECTOR_BYTES = hex"0c3b823f"; // solhint-disable func-name-mixedcase - function IllegalReentrancyError() - internal - pure - returns (bytes memory) - { + function IllegalReentrancyError() internal pure returns (bytes memory) { return ILLEGAL_REENTRANCY_ERROR_SELECTOR_BYTES; } } diff --git a/contracts/utils/contracts/src/v06/errors/LibRichErrorsV06.sol b/contracts/utils/contracts/src/v06/errors/LibRichErrorsV06.sol index 9e406a24cd..d4d5b0517f 100644 --- a/contracts/utils/contracts/src/v06/errors/LibRichErrorsV06.sol +++ b/contracts/utils/contracts/src/v06/errors/LibRichErrorsV06.sol @@ -19,9 +19,7 @@ pragma solidity ^0.6.5; - library LibRichErrorsV06 { - // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; @@ -31,24 +29,15 @@ library LibRichErrorsV06 { /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. - function StandardError(string memory message) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - STANDARD_ERROR_SELECTOR, - bytes(message) - ); + function StandardError(string memory message) internal pure returns (bytes memory) { + return abi.encodeWithSelector(STANDARD_ERROR_SELECTOR, bytes(message)); } + // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. - function rrevert(bytes memory errorData) - internal - pure - { + function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } diff --git a/contracts/utils/contracts/src/v06/errors/LibSafeMathRichErrorsV06.sol b/contracts/utils/contracts/src/v06/errors/LibSafeMathRichErrorsV06.sol index af278c2fd1..8d792cbe48 100644 --- a/contracts/utils/contracts/src/v06/errors/LibSafeMathRichErrorsV06.sol +++ b/contracts/utils/contracts/src/v06/errors/LibSafeMathRichErrorsV06.sol @@ -19,16 +19,12 @@ pragma solidity ^0.6.5; - library LibSafeMathRichErrorsV06 { - // bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)")) - bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR = - 0xe946c1bb; + bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR = 0xe946c1bb; // bytes4(keccak256("Uint256DowncastError(uint8,uint256)")) - bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR = - 0xc996af7b; + bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR = 0xc996af7b; enum BinOpErrorCodes { ADDITION_OVERFLOW, @@ -49,31 +45,11 @@ library LibSafeMathRichErrorsV06 { BinOpErrorCodes errorCode, uint256 a, uint256 b - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - UINT256_BINOP_ERROR_SELECTOR, - errorCode, - a, - b - ); + ) internal pure returns (bytes memory) { + return abi.encodeWithSelector(UINT256_BINOP_ERROR_SELECTOR, errorCode, a, b); } - function Uint256DowncastError( - DowncastErrorCodes errorCode, - uint256 a - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - UINT256_DOWNCAST_ERROR_SELECTOR, - errorCode, - a - ); + function Uint256DowncastError(DowncastErrorCodes errorCode, uint256 a) internal pure returns (bytes memory) { + return abi.encodeWithSelector(UINT256_DOWNCAST_ERROR_SELECTOR, errorCode, a); } } diff --git a/contracts/utils/contracts/src/v06/interfaces/IAuthorizableV06.sol b/contracts/utils/contracts/src/v06/interfaces/IAuthorizableV06.sol index ac2ac66e38..2e587e830d 100644 --- a/contracts/utils/contracts/src/v06/interfaces/IAuthorizableV06.sol +++ b/contracts/utils/contracts/src/v06/interfaces/IAuthorizableV06.sol @@ -21,47 +21,29 @@ pragma solidity ^0.6.5; import "./IOwnableV06.sol"; - -interface IAuthorizableV06 is - IOwnableV06 -{ +interface IAuthorizableV06 is IOwnableV06 { // Event logged when a new address is authorized. - event AuthorizedAddressAdded( - address indexed target, - address indexed caller - ); + event AuthorizedAddressAdded(address indexed target, address indexed caller); // Event logged when a currently authorized address is unauthorized. - event AuthorizedAddressRemoved( - address indexed target, - address indexed caller - ); + event AuthorizedAddressRemoved(address indexed target, address indexed caller); /// @dev Authorizes an address. /// @param target Address to authorize. - function addAuthorizedAddress(address target) - external; + function addAuthorizedAddress(address target) external; /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. - function removeAuthorizedAddress(address target) - external; + function removeAuthorizedAddress(address target) external; /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. /// @param index Index of target in authorities array. - function removeAuthorizedAddressAtIndex( - address target, - uint256 index - ) - external; + function removeAuthorizedAddressAtIndex(address target, uint256 index) external; /// @dev Gets all authorized addresses. /// @return authorizedAddresses Array of authorized addresses. - function getAuthorizedAddresses() - external - view - returns (address[] memory authorizedAddresses); + function getAuthorizedAddresses() external view returns (address[] memory authorizedAddresses); /// @dev Whether an adderss is authorized to call privileged functions. /// @param addr Address to query. @@ -72,5 +54,4 @@ interface IAuthorizableV06 is /// @param idx Index of authorized address. /// @return addr Authorized address. function authorities(uint256 idx) external view returns (address addr); - } diff --git a/contracts/utils/contracts/src/v06/interfaces/IOwnableV06.sol b/contracts/utils/contracts/src/v06/interfaces/IOwnableV06.sol index fa77e8ac0d..2943ca0e3a 100644 --- a/contracts/utils/contracts/src/v06/interfaces/IOwnableV06.sol +++ b/contracts/utils/contracts/src/v06/interfaces/IOwnableV06.sol @@ -19,9 +19,7 @@ pragma solidity ^0.6.5; - interface IOwnableV06 { - /// @dev Emitted by Ownable when ownership is transferred. /// @param previousOwner The previous owner of the contract. /// @param newOwner The new owner of the contract. diff --git a/contracts/utils/contracts/test/TestAuthorizable.sol b/contracts/utils/contracts/test/TestAuthorizable.sol index 366a4b4274..4cff854960 100644 --- a/contracts/utils/contracts/test/TestAuthorizable.sol +++ b/contracts/utils/contracts/test/TestAuthorizable.sol @@ -20,14 +20,7 @@ pragma solidity ^0.5.9; import "../src/Authorizable.sol"; - // solhint-disable no-empty-blocks -contract TestAuthorizable is - Authorizable -{ - function onlyAuthorizedFn() - external - view - onlyAuthorized - {} +contract TestAuthorizable is Authorizable { + function onlyAuthorizedFn() external view onlyAuthorized {} } diff --git a/contracts/utils/contracts/test/TestLibAddress.sol b/contracts/utils/contracts/test/TestLibAddress.sol index 642ae2b99e..b3c1f60a13 100644 --- a/contracts/utils/contracts/test/TestLibAddress.sol +++ b/contracts/utils/contracts/test/TestLibAddress.sol @@ -20,16 +20,10 @@ pragma solidity ^0.5.9; import "../src/LibAddress.sol"; - contract TestLibAddress { - using LibAddress for address; - function externalIsContract(address account) - external - view - returns (bool) - { + function externalIsContract(address account) external view returns (bool) { return account.isContract(); } } diff --git a/contracts/utils/contracts/test/TestLibAddressArray.sol b/contracts/utils/contracts/test/TestLibAddressArray.sol index dc44dfbb92..5b1930382c 100644 --- a/contracts/utils/contracts/test/TestLibAddressArray.sol +++ b/contracts/utils/contracts/test/TestLibAddressArray.sol @@ -20,9 +20,7 @@ pragma solidity ^0.5.5; import "../src/LibAddressArray.sol"; - contract TestLibAddressArray { - using LibAddressArray for address[]; /// @dev Append a new address to an array of addresses. @@ -83,11 +81,7 @@ contract TestLibAddressArray { /// @param addressArray Array of addresses. /// @param target Address to search for in array. /// @return True if the addressArray contains the target. - function publicContains(address[] memory addressArray, address target) - public - pure - returns (bool success) - { + function publicContains(address[] memory addressArray, address target) public pure returns (bool success) { return addressArray.contains(target); } @@ -102,5 +96,4 @@ contract TestLibAddressArray { { (success, index) = addressArray.indexOf(target); } - } diff --git a/contracts/utils/contracts/test/TestLibBytes.sol b/contracts/utils/contracts/test/TestLibBytes.sol index 361b71164a..2fbc372db7 100644 --- a/contracts/utils/contracts/test/TestLibBytes.sol +++ b/contracts/utils/contracts/test/TestLibBytes.sol @@ -20,19 +20,13 @@ pragma solidity ^0.5.9; import "../src/LibBytes.sol"; - contract TestLibBytes { - using LibBytes for bytes; /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. - function publicPopLastByte(bytes memory b) - public - pure - returns (bytes memory, bytes1 result) - { + function publicPopLastByte(bytes memory b) public pure returns (bytes memory, bytes1 result) { result = b.popLastByte(); return (b, result); } @@ -41,20 +35,12 @@ contract TestLibBytes { /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return True if arrays are the same. False otherwise. - function publicEquals(bytes memory lhs, bytes memory rhs) - public - pure - returns (bool equal) - { + function publicEquals(bytes memory lhs, bytes memory rhs) public pure returns (bool equal) { equal = lhs.equals(rhs); return equal; } - function publicEqualsPop1(bytes memory lhs, bytes memory rhs) - public - pure - returns (bool equal) - { + function publicEqualsPop1(bytes memory lhs, bytes memory rhs) public pure returns (bool equal) { lhs.popLastByte(); rhs.popLastByte(); equal = lhs.equals(rhs); @@ -65,14 +51,7 @@ contract TestLibBytes { /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return address from byte array. - function publicReadAddress( - bytes memory b, - uint256 index - ) - public - pure - returns (address result) - { + function publicReadAddress(bytes memory b, uint256 index) public pure returns (address result) { result = b.readAddress(index); return result; } @@ -85,11 +64,7 @@ contract TestLibBytes { bytes memory b, uint256 index, address input - ) - public - pure - returns (bytes memory) - { + ) public pure returns (bytes memory) { b.writeAddress(index, input); return b; } @@ -98,14 +73,7 @@ contract TestLibBytes { /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. - function publicReadBytes32( - bytes memory b, - uint256 index - ) - public - pure - returns (bytes32 result) - { + function publicReadBytes32(bytes memory b, uint256 index) public pure returns (bytes32 result) { result = b.readBytes32(index); return result; } @@ -118,11 +86,7 @@ contract TestLibBytes { bytes memory b, uint256 index, bytes32 input - ) - public - pure - returns (bytes memory) - { + ) public pure returns (bytes memory) { b.writeBytes32(index, input); return b; } @@ -131,14 +95,7 @@ contract TestLibBytes { /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return uint256 value from byte array. - function publicReadUint256( - bytes memory b, - uint256 index - ) - public - pure - returns (uint256 result) - { + function publicReadUint256(bytes memory b, uint256 index) public pure returns (uint256 result) { result = b.readUint256(index); return result; } @@ -151,11 +108,7 @@ contract TestLibBytes { bytes memory b, uint256 index, uint256 input - ) - public - pure - returns (bytes memory) - { + ) public pure returns (bytes memory) { b.writeUint256(index, input); return b; } @@ -164,14 +117,7 @@ contract TestLibBytes { /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. - function publicReadBytes4( - bytes memory b, - uint256 index - ) - public - pure - returns (bytes4 result) - { + function publicReadBytes4(bytes memory b, uint256 index) public pure returns (bytes4 result) { result = b.readBytes4(index); return result; } @@ -186,12 +132,8 @@ contract TestLibBytes { bytes memory mem, uint256 dest, uint256 source, - uint256 length - ) - public // not external, we need input in memory - pure - returns (bytes memory) - { + uint256 length // not external, we need input in memory + ) public pure returns (bytes memory) { // Sanity check. Overflows are not checked. require(source + length <= mem.length); require(dest + length <= mem.length); @@ -215,11 +157,7 @@ contract TestLibBytes { bytes memory b, uint256 from, uint256 to - ) - public - pure - returns (bytes memory result, bytes memory original) - { + ) public pure returns (bytes memory result, bytes memory original) { result = LibBytes.slice(b, from, to); return (result, b); } @@ -234,11 +172,7 @@ contract TestLibBytes { bytes memory b, uint256 from, uint256 to - ) - public - pure - returns (bytes memory result, bytes memory original) - { + ) public pure returns (bytes memory result, bytes memory original) { result = LibBytes.sliceDestructive(b, from, to); return (result, b); } @@ -254,24 +188,14 @@ contract TestLibBytes { bytes memory b, uint256 length, bytes memory extraBytes - ) - public - pure - returns (bytes memory) - { + ) public pure returns (bytes memory) { uint256 bEnd = b.contentAddress() + b.length; LibBytes.memCopy(bEnd, extraBytes.contentAddress(), extraBytes.length); b.writeLength(length); return b; } - function assertBytesUnchangedAfterLengthReset( - bytes memory b, - uint256 tempLength - ) - public - pure - { + function assertBytesUnchangedAfterLengthReset(bytes memory b, uint256 tempLength) public pure { uint256 length = b.length; bytes memory bCopy = b.slice(0, length); b.writeLength(tempLength); diff --git a/contracts/utils/contracts/test/TestLibEIP712.sol b/contracts/utils/contracts/test/TestLibEIP712.sol index adf3da412d..77077c6892 100644 --- a/contracts/utils/contracts/test/TestLibEIP712.sol +++ b/contracts/utils/contracts/test/TestLibEIP712.sol @@ -20,32 +20,17 @@ pragma solidity ^0.5.9; import "../src/LibEIP712.sol"; - contract TestLibEIP712 { - function externalHashEIP712DomainSeperator( string calldata name, string calldata version, uint256 chainid, address verifyingcontractaddress - ) - external - pure - returns (bytes32) - { - return LibEIP712.hashEIP712Domain( - name, - version, - chainid, - verifyingcontractaddress - ); + ) external pure returns (bytes32) { + return LibEIP712.hashEIP712Domain(name, version, chainid, verifyingcontractaddress); } - function externalHashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) - external - pure - returns (bytes32) - { + function externalHashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) external pure returns (bytes32) { return LibEIP712.hashEIP712Message(eip712DomainHash, hashStruct); } } diff --git a/contracts/utils/contracts/test/TestLibMath.sol b/contracts/utils/contracts/test/TestLibMath.sol index 210db05965..9af557dcea 100644 --- a/contracts/utils/contracts/test/TestLibMath.sol +++ b/contracts/utils/contracts/test/TestLibMath.sol @@ -21,9 +21,7 @@ pragma experimental ABIEncoderV2; import "../src/LibMath.sol"; - contract TestLibMath { - /// @dev Calculates partial value given a numerator and denominator. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. @@ -34,11 +32,7 @@ contract TestLibMath { uint256 numerator, uint256 denominator, uint256 target - ) - public - pure - returns (uint256 partialAmount) - { + ) public pure returns (uint256 partialAmount) { return LibMath.safeGetPartialAmountFloor(numerator, denominator, target); } @@ -52,11 +46,7 @@ contract TestLibMath { uint256 numerator, uint256 denominator, uint256 target - ) - public - pure - returns (uint256 partialAmount) - { + ) public pure returns (uint256 partialAmount) { return LibMath.safeGetPartialAmountCeil(numerator, denominator, target); } @@ -69,11 +59,7 @@ contract TestLibMath { uint256 numerator, uint256 denominator, uint256 target - ) - public - pure - returns (uint256 partialAmount) - { + ) public pure returns (uint256 partialAmount) { return LibMath.getPartialAmountFloor(numerator, denominator, target); } @@ -86,11 +72,7 @@ contract TestLibMath { uint256 numerator, uint256 denominator, uint256 target - ) - public - pure - returns (uint256 partialAmount) - { + ) public pure returns (uint256 partialAmount) { return LibMath.getPartialAmountCeil(numerator, denominator, target); } @@ -103,11 +85,7 @@ contract TestLibMath { uint256 numerator, uint256 denominator, uint256 target - ) - public - pure - returns (bool isError) - { + ) public pure returns (bool isError) { return LibMath.isRoundingErrorFloor(numerator, denominator, target); } @@ -120,11 +98,7 @@ contract TestLibMath { uint256 numerator, uint256 denominator, uint256 target - ) - public - pure - returns (bool isError) - { + ) public pure returns (bool isError) { return LibMath.isRoundingErrorCeil(numerator, denominator, target); } } diff --git a/contracts/utils/contracts/test/TestLibRichErrors.sol b/contracts/utils/contracts/test/TestLibRichErrors.sol index 53b1ae04d0..3bd0472e73 100644 --- a/contracts/utils/contracts/test/TestLibRichErrors.sol +++ b/contracts/utils/contracts/test/TestLibRichErrors.sol @@ -20,13 +20,8 @@ pragma solidity ^0.5.9; import "../src/LibRichErrors.sol"; - contract TestLibRichErrors { - - function externalRRevert(bytes calldata errorData) - external - pure - { + function externalRRevert(bytes calldata errorData) external pure { LibRichErrors.rrevert(errorData); } } diff --git a/contracts/utils/contracts/test/TestLibSafeMath.sol b/contracts/utils/contracts/test/TestLibSafeMath.sol index a3ee8555c0..ba60ac76fe 100644 --- a/contracts/utils/contracts/test/TestLibSafeMath.sol +++ b/contracts/utils/contracts/test/TestLibSafeMath.sol @@ -20,56 +20,30 @@ pragma solidity ^0.5.9; import "../src/LibSafeMath.sol"; - contract TestLibSafeMath { - using LibSafeMath for uint256; - function externalSafeMul(uint256 a, uint256 b) - external - pure - returns (uint256) - { + function externalSafeMul(uint256 a, uint256 b) external pure returns (uint256) { return a.safeMul(b); } - function externalSafeDiv(uint256 a, uint256 b) - external - pure - returns (uint256) - { + function externalSafeDiv(uint256 a, uint256 b) external pure returns (uint256) { return a.safeDiv(b); } - function externalSafeSub(uint256 a, uint256 b) - external - pure - returns (uint256) - { + function externalSafeSub(uint256 a, uint256 b) external pure returns (uint256) { return a.safeSub(b); } - function externalSafeAdd(uint256 a, uint256 b) - external - pure - returns (uint256) - { + function externalSafeAdd(uint256 a, uint256 b) external pure returns (uint256) { return a.safeAdd(b); } - function externalMaxUint256(uint256 a, uint256 b) - external - pure - returns (uint256) - { + function externalMaxUint256(uint256 a, uint256 b) external pure returns (uint256) { return a.max256(b); } - function externalMinUint256(uint256 a, uint256 b) - external - pure - returns (uint256) - { + function externalMinUint256(uint256 a, uint256 b) external pure returns (uint256) { return a.min256(b); } } diff --git a/contracts/utils/contracts/test/TestLogDecoding.sol b/contracts/utils/contracts/test/TestLogDecoding.sol index e692d8b75f..624e71e637 100644 --- a/contracts/utils/contracts/test/TestLogDecoding.sol +++ b/contracts/utils/contracts/test/TestLogDecoding.sol @@ -20,36 +20,24 @@ pragma solidity ^0.5.5; import "./TestLogDecodingDownstream.sol"; - contract TestLogDecoding { - /// @dev arbitrary event; fields to not matter. - event TestEvent( - uint256 foo, - bytes bar, - string car - ); + event TestEvent(uint256 foo, bytes bar, string car); /// @dev Emits a local event - function emitEvent() - public - { - emit TestEvent(256, hex'1234', "4321"); + function emitEvent() public { + emit TestEvent(256, hex"1234", "4321"); } /// @dev Emits an event in a downstream contract - function emitEventDownstream() - public - { + function emitEventDownstream() public { TestLogDecodingDownstream testLogDecodingDownstream = new TestLogDecodingDownstream(); ITestLogDecodingDownstream(testLogDecodingDownstream).emitEvent(); } /// @dev Emits a local event and a downstream event - function emitEventsLocalAndDownstream() - public - { + function emitEventsLocalAndDownstream() public { emitEvent(); emitEventDownstream(); } -} \ No newline at end of file +} diff --git a/contracts/utils/contracts/test/TestLogDecodingDownstream.sol b/contracts/utils/contracts/test/TestLogDecodingDownstream.sol index adb2ffe453..9424fab385 100644 --- a/contracts/utils/contracts/test/TestLogDecodingDownstream.sol +++ b/contracts/utils/contracts/test/TestLogDecodingDownstream.sol @@ -18,31 +18,20 @@ pragma solidity ^0.5.5; - contract ITestLogDecodingDownstream { - /// @dev Emits a local event function emitEvent() external; } - -contract TestLogDecodingDownstream is - ITestLogDecodingDownstream -{ - +contract TestLogDecodingDownstream is ITestLogDecodingDownstream { /// @dev event with fields different than those in `TestLogDecoding.TestEvent` /// Note: do not include this in the interface /// For testing, we want to emit an event that is /// not known by the calling contract. - event TestEvent2( - uint256 lorem, - string ipsum - ); + event TestEvent2(uint256 lorem, string ipsum); /// @dev Emits a local event - function emitEvent() - external - { + function emitEvent() external { emit TestEvent2(256, "4321"); } -} \ No newline at end of file +} diff --git a/contracts/utils/contracts/test/TestOwnable.sol b/contracts/utils/contracts/test/TestOwnable.sol index d7f4bc58b7..0d03bb2867 100644 --- a/contracts/utils/contracts/test/TestOwnable.sol +++ b/contracts/utils/contracts/test/TestOwnable.sol @@ -2,16 +2,8 @@ pragma solidity ^0.5.9; import "../src/Ownable.sol"; - -contract TestOwnable is - Ownable -{ - function externalOnlyOwner() - external - onlyOwner - view - returns (bool) - { +contract TestOwnable is Ownable { + function externalOnlyOwner() external view onlyOwner returns (bool) { return true; } } diff --git a/contracts/utils/contracts/test/TestReentrancyGuard.sol b/contracts/utils/contracts/test/TestReentrancyGuard.sol index 3bf6d3d274..21be0c4735 100644 --- a/contracts/utils/contracts/test/TestReentrancyGuard.sol +++ b/contracts/utils/contracts/test/TestReentrancyGuard.sol @@ -20,18 +20,11 @@ pragma solidity ^0.5.9; import "../src/ReentrancyGuard.sol"; - -contract TestReentrancyGuard is - ReentrancyGuard -{ +contract TestReentrancyGuard is ReentrancyGuard { /// @dev Exposes the nonReentrant modifier publicly. /// @param shouldBeAttacked True if the contract should be attacked. /// @return True if successful. - function guarded(bool shouldBeAttacked) - external - nonReentrant - returns (bool) - { + function guarded(bool shouldBeAttacked) external nonReentrant returns (bool) { if (shouldBeAttacked) { return this.exploitive(); } else { @@ -41,20 +34,13 @@ contract TestReentrancyGuard is /// @dev This is a function that will reenter the current contract. /// @return True if successful. - function exploitive() - external - returns (bool) - { + function exploitive() external returns (bool) { return this.guarded(true); } /// @dev This is a function that will not reenter the current contract. /// @return True if successful. - function nonExploitive() - external - pure - returns (bool) - { + function nonExploitive() external pure returns (bool) { return true; } } diff --git a/contracts/utils/contracts/test/TestRefundable.sol b/contracts/utils/contracts/test/TestRefundable.sol index 86df80185f..f456b3d745 100644 --- a/contracts/utils/contracts/test/TestRefundable.sol +++ b/contracts/utils/contracts/test/TestRefundable.sol @@ -20,59 +20,29 @@ pragma solidity ^0.5.9; import "../src/Refundable.sol"; - -contract TestRefundable is - Refundable -{ - function refundNonZeroBalanceExternal() - external - payable - { +contract TestRefundable is Refundable { + function refundNonZeroBalanceExternal() external payable { _refundNonZeroBalance(); } - function setShouldNotRefund(bool shouldNotRefundNew) - external - { + function setShouldNotRefund(bool shouldNotRefundNew) external { _shouldNotRefund = shouldNotRefundNew; } - function getShouldNotRefund() - external - view - returns (bool) - { + function getShouldNotRefund() external view returns (bool) { return _shouldNotRefund; } - function refundFinalBalanceFunction() - public - payable - refundFinalBalance - {} // solhint-disable-line no-empty-blocks + function refundFinalBalanceFunction() public payable refundFinalBalance {} // solhint-disable-line no-empty-blocks - function disableRefundUntilEndFunction() - public - payable - disableRefundUntilEnd - {} // solhint-disable-line no-empty-blocks + function disableRefundUntilEndFunction() public payable disableRefundUntilEnd {} // solhint-disable-line no-empty-blocks - function nestedDisableRefundUntilEndFunction() - public - payable - disableRefundUntilEnd - returns (uint256) - { + function nestedDisableRefundUntilEndFunction() public payable disableRefundUntilEnd returns (uint256) { disableRefundUntilEndFunction(); return address(this).balance; } - function mixedRefundModifierFunction() - public - payable - disableRefundUntilEnd - returns (uint256) - { + function mixedRefundModifierFunction() public payable disableRefundUntilEnd returns (uint256) { refundFinalBalanceFunction(); return address(this).balance; } diff --git a/contracts/utils/contracts/test/TestRefundableReceiver.sol b/contracts/utils/contracts/test/TestRefundableReceiver.sol index 37cc4d7ae5..f66b0ccff2 100644 --- a/contracts/utils/contracts/test/TestRefundableReceiver.sol +++ b/contracts/utils/contracts/test/TestRefundableReceiver.sol @@ -20,16 +20,11 @@ pragma solidity ^0.5.9; import "./TestRefundable.sol"; - contract TestRefundableReceiver { - /// @dev A payable fallback function is necessary to receive refunds from the `TestRefundable` contract. /// This function ensures that zero value is not sent to the contract, which tests the feature of /// of the `refundNonzeroBalance` that doesn't transfer if the balance is zero. - function () - external - payable - { + function() external payable { // Ensure that a value of zero was not transferred to the contract. require(msg.value != 0, "Zero value should not be sent to this contract."); } @@ -37,10 +32,7 @@ contract TestRefundableReceiver { /// @dev This function tests the behavior of the `refundNonzeroBalance` function by checking whether or /// not the `callCounter` state variable changes after the `refundNonzeroBalance` is called. /// @param testRefundable The TestRefundable that should be tested against. - function testRefundNonZeroBalance(TestRefundable testRefundable) - external - payable - { + function testRefundNonZeroBalance(TestRefundable testRefundable) external payable { // Call `refundNonzeroBalance()` and forward all of the eth sent to the contract. testRefundable.refundNonZeroBalanceExternal.value(msg.value)(); @@ -58,13 +50,7 @@ contract TestRefundableReceiver { /// remains unaltered after the function call. /// @param testRefundable The TestRefundable that should be tested against. /// @param shouldNotRefund The value that shouldNotRefund should be set to before the call to TestRefundable. - function testRefundFinalBalance( - TestRefundable testRefundable, - bool shouldNotRefund - ) - external - payable - { + function testRefundFinalBalance(TestRefundable testRefundable, bool shouldNotRefund) external payable { // Set `shouldNotRefund` to the specified bool. testRefundable.setShouldNotRefund(shouldNotRefund); @@ -82,13 +68,7 @@ contract TestRefundableReceiver { /// remains unaltered after the function call. /// @param testRefundable The TestRefundable that should be tested against. /// @param shouldNotRefund The value that shouldNotRefund should be set to before the call to TestRefundable. - function testDisableRefundUntilEnd( - TestRefundable testRefundable, - bool shouldNotRefund - ) - external - payable - { + function testDisableRefundUntilEnd(TestRefundable testRefundable, bool shouldNotRefund) external payable { // Set `shouldNotRefund` to the specified bool. testRefundable.setShouldNotRefund(shouldNotRefund); @@ -105,13 +85,7 @@ contract TestRefundableReceiver { /// to verify that both the inner and outer modifiers worked correctly. /// @param testRefundable The TestRefundable that should be tested against. /// @param shouldNotRefund The value that shouldNotRefund should be set to before the call to TestRefundable. - function testNestedDisableRefundUntilEnd( - TestRefundable testRefundable, - bool shouldNotRefund - ) - external - payable - { + function testNestedDisableRefundUntilEnd(TestRefundable testRefundable, bool shouldNotRefund) external payable { // Set `shouldNotRefund` to the specified bool. testRefundable.setShouldNotRefund(shouldNotRefund); @@ -132,13 +106,7 @@ contract TestRefundableReceiver { /// to verify that both the inner and outer modifiers worked correctly. /// @param testRefundable The TestRefundable that should be tested against. /// @param shouldNotRefund The value that shouldNotRefund should be set to before the call to TestRefundable. - function testMixedRefunds( - TestRefundable testRefundable, - bool shouldNotRefund - ) - external - payable - { + function testMixedRefunds(TestRefundable testRefundable, bool shouldNotRefund) external payable { // Set `shouldNotRefund` to the specified bool. testRefundable.setShouldNotRefund(shouldNotRefund); @@ -158,12 +126,7 @@ contract TestRefundableReceiver { /// refundable contract and verifies that the `shouldNotRefund` value remains unaltered. /// @param testRefundable The TestRefundable that should be tested against. /// @param shouldNotRefund The value that shouldNotRefund was set to before the call to TestRefundable. - function requireCorrectFinalBalancesAndState( - TestRefundable testRefundable, - bool shouldNotRefund - ) - internal - { + function requireCorrectFinalBalancesAndState(TestRefundable testRefundable, bool shouldNotRefund) internal { // If `shouldNotRefund` was true, then this contract should have a balance of zero, // and `testRefundable` should have a balance of `msg.value`. Otherwise, the opposite // should be true. diff --git a/contracts/zero-ex/contracts/src/IZeroEx.sol b/contracts/zero-ex/contracts/src/IZeroEx.sol index ce021e3c7a..9fbddf536d 100644 --- a/contracts/zero-ex/contracts/src/IZeroEx.sol +++ b/contracts/zero-ex/contracts/src/IZeroEx.sol @@ -38,7 +38,6 @@ import "./features/interfaces/IERC721OrdersFeature.sol"; import "./features/interfaces/IERC1155OrdersFeature.sol"; import "./features/interfaces/IERC165Feature.sol"; - /// @dev Interface for a fully featured Exchange Proxy. interface IZeroEx is IOwnableFeature, diff --git a/contracts/zero-ex/contracts/src/ZeroEx.sol b/contracts/zero-ex/contracts/src/ZeroEx.sol index a7394f2011..2b7a2365a0 100644 --- a/contracts/zero-ex/contracts/src/ZeroEx.sol +++ b/contracts/zero-ex/contracts/src/ZeroEx.sol @@ -26,7 +26,6 @@ import "./features/BootstrapFeature.sol"; import "./storage/LibProxyStorage.sol"; import "./errors/LibProxyRichErrors.sol"; - /// @dev An extensible proxy contract that serves as a universal entry point for /// interacting with the 0x protocol. contract ZeroEx { @@ -41,8 +40,7 @@ contract ZeroEx { // Temporarily create and register the bootstrap feature. // It will deregister itself after `bootstrap()` has been called. BootstrapFeature bootstrap = new BootstrapFeature(bootstrapper); - LibProxyStorage.getStorage().impls[bootstrap.bootstrap.selector] = - address(bootstrap); + LibProxyStorage.getStorage().impls[bootstrap.bootstrap.selector] = address(bootstrap); } // solhint-disable state-visibility @@ -70,23 +68,23 @@ contract ZeroEx { /// @dev Get the implementation contract of a registered function. /// @param selector The function selector. /// @return impl The implementation contract address. - function getFunctionImplementation(bytes4 selector) - public - view - returns (address impl) - { + function getFunctionImplementation(bytes4 selector) public view returns (address impl) { return LibProxyStorage.getStorage().impls[selector]; } /// @dev Revert with arbitrary bytes. /// @param data Revert data. function _revertWithData(bytes memory data) private pure { - assembly { revert(add(data, 32), mload(data)) } + assembly { + revert(add(data, 32), mload(data)) + } } /// @dev Return with arbitrary bytes. /// @param data Return data. function _returnWithData(bytes memory data) private pure { - assembly { return(add(data, 32), mload(data)) } + assembly { + return(add(data, 32), mload(data)) + } } } diff --git a/contracts/zero-ex/contracts/src/ZeroExOptimized.sol b/contracts/zero-ex/contracts/src/ZeroExOptimized.sol index f6e5aab47b..90628fd231 100644 --- a/contracts/zero-ex/contracts/src/ZeroExOptimized.sol +++ b/contracts/zero-ex/contracts/src/ZeroExOptimized.sol @@ -34,18 +34,15 @@ contract ZeroExOptimized { // Temporarily create and register the bootstrap feature. // It will deregister itself after `bootstrap()` has been called. BootstrapFeature bootstrap = new BootstrapFeature(bootstrapper); - LibProxyStorage.getStorage().impls[bootstrap.bootstrap.selector] = - address(bootstrap); + LibProxyStorage.getStorage().impls[bootstrap.bootstrap.selector] = address(bootstrap); } - // solhint-disable state-visibility /// @dev Forwards calls to the appropriate implementation contract. fallback() external payable { // This is used in assembly below as impls_slot. - mapping(bytes4 => address) storage impls = - LibProxyStorage.getStorage().impls; + mapping(bytes4 => address) storage impls = LibProxyStorage.getStorage().impls; assembly { let cdlen := calldatasize() @@ -75,12 +72,7 @@ contract ZeroExOptimized { revert(0, 0x24) } - let success := delegatecall( - gas(), - delegate, - 0x40, cdlen, - 0, 0 - ) + let success := delegatecall(gas(), delegate, 0x40, cdlen, 0, 0) let rdlen := returndatasize() returndatacopy(0, 0, rdlen) if success { diff --git a/contracts/zero-ex/contracts/src/errors/LibCommonRichErrors.sol b/contracts/zero-ex/contracts/src/errors/LibCommonRichErrors.sol index 3b0597dab7..a1bfc6437f 100644 --- a/contracts/zero-ex/contracts/src/errors/LibCommonRichErrors.sol +++ b/contracts/zero-ex/contracts/src/errors/LibCommonRichErrors.sol @@ -19,31 +19,19 @@ pragma solidity ^0.6.5; - library LibCommonRichErrors { - // solhint-disable func-name-mixedcase - function OnlyCallableBySelfError(address sender) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("OnlyCallableBySelfError(address)")), - sender - ); + function OnlyCallableBySelfError(address sender) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("OnlyCallableBySelfError(address)")), sender); } - function IllegalReentrancyError(bytes4 selector, uint256 reentrancyFlags) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("IllegalReentrancyError(bytes4,uint256)")), - selector, - reentrancyFlags - ); + function IllegalReentrancyError(bytes4 selector, uint256 reentrancyFlags) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("IllegalReentrancyError(bytes4,uint256)")), + selector, + reentrancyFlags + ); } } diff --git a/contracts/zero-ex/contracts/src/errors/LibLiquidityProviderRichErrors.sol b/contracts/zero-ex/contracts/src/errors/LibLiquidityProviderRichErrors.sol index 71100bbf80..fb28835e16 100644 --- a/contracts/zero-ex/contracts/src/errors/LibLiquidityProviderRichErrors.sol +++ b/contracts/zero-ex/contracts/src/errors/LibLiquidityProviderRichErrors.sol @@ -19,9 +19,7 @@ pragma solidity ^0.6.5; - library LibLiquidityProviderRichErrors { - // solhint-disable func-name-mixedcase function LiquidityProviderIncompleteSellError( @@ -31,19 +29,18 @@ library LibLiquidityProviderRichErrors { uint256 sellAmount, uint256 boughtAmount, uint256 minBuyAmount - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("LiquidityProviderIncompleteSellError(address,address,address,uint256,uint256,uint256)")), - providerAddress, - makerToken, - takerToken, - sellAmount, - boughtAmount, - minBuyAmount - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4( + keccak256("LiquidityProviderIncompleteSellError(address,address,address,uint256,uint256,uint256)") + ), + providerAddress, + makerToken, + takerToken, + sellAmount, + boughtAmount, + minBuyAmount + ); } } diff --git a/contracts/zero-ex/contracts/src/errors/LibMetaTransactionsRichErrors.sol b/contracts/zero-ex/contracts/src/errors/LibMetaTransactionsRichErrors.sol index 47d15c9ec6..ebb1782d1f 100644 --- a/contracts/zero-ex/contracts/src/errors/LibMetaTransactionsRichErrors.sol +++ b/contracts/zero-ex/contracts/src/errors/LibMetaTransactionsRichErrors.sol @@ -19,73 +19,61 @@ pragma solidity ^0.6.5; - library LibMetaTransactionsRichErrors { - // solhint-disable func-name-mixedcase - function InvalidMetaTransactionsArrayLengthsError( - uint256 mtxCount, - uint256 signatureCount - ) + function InvalidMetaTransactionsArrayLengthsError(uint256 mtxCount, uint256 signatureCount) internal pure returns (bytes memory) { - return abi.encodeWithSelector( - bytes4(keccak256("InvalidMetaTransactionsArrayLengthsError(uint256,uint256)")), - mtxCount, - signatureCount - ); + return + abi.encodeWithSelector( + bytes4(keccak256("InvalidMetaTransactionsArrayLengthsError(uint256,uint256)")), + mtxCount, + signatureCount + ); } - function MetaTransactionUnsupportedFunctionError( - bytes32 mtxHash, - bytes4 selector - ) + function MetaTransactionUnsupportedFunctionError(bytes32 mtxHash, bytes4 selector) internal pure returns (bytes memory) { - return abi.encodeWithSelector( - bytes4(keccak256("MetaTransactionUnsupportedFunctionError(bytes32,bytes4)")), - mtxHash, - selector - ); + return + abi.encodeWithSelector( + bytes4(keccak256("MetaTransactionUnsupportedFunctionError(bytes32,bytes4)")), + mtxHash, + selector + ); } function MetaTransactionWrongSenderError( bytes32 mtxHash, address sender, address expectedSender - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("MetaTransactionWrongSenderError(bytes32,address,address)")), - mtxHash, - sender, - expectedSender - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("MetaTransactionWrongSenderError(bytes32,address,address)")), + mtxHash, + sender, + expectedSender + ); } function MetaTransactionExpiredError( bytes32 mtxHash, uint256 time, uint256 expirationTime - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("MetaTransactionExpiredError(bytes32,uint256,uint256)")), - mtxHash, - time, - expirationTime - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("MetaTransactionExpiredError(bytes32,uint256,uint256)")), + mtxHash, + time, + expirationTime + ); } function MetaTransactionGasPriceError( @@ -93,83 +81,69 @@ library LibMetaTransactionsRichErrors { uint256 gasPrice, uint256 minGasPrice, uint256 maxGasPrice - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("MetaTransactionGasPriceError(bytes32,uint256,uint256,uint256)")), - mtxHash, - gasPrice, - minGasPrice, - maxGasPrice - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("MetaTransactionGasPriceError(bytes32,uint256,uint256,uint256)")), + mtxHash, + gasPrice, + minGasPrice, + maxGasPrice + ); } function MetaTransactionInsufficientEthError( bytes32 mtxHash, uint256 ethBalance, uint256 ethRequired - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("MetaTransactionInsufficientEthError(bytes32,uint256,uint256)")), - mtxHash, - ethBalance, - ethRequired - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("MetaTransactionInsufficientEthError(bytes32,uint256,uint256)")), + mtxHash, + ethBalance, + ethRequired + ); } function MetaTransactionInvalidSignatureError( bytes32 mtxHash, bytes memory signature, bytes memory errData - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("MetaTransactionInvalidSignatureError(bytes32,bytes,bytes)")), - mtxHash, - signature, - errData - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("MetaTransactionInvalidSignatureError(bytes32,bytes,bytes)")), + mtxHash, + signature, + errData + ); } - function MetaTransactionAlreadyExecutedError( - bytes32 mtxHash, - uint256 executedBlockNumber - ) + function MetaTransactionAlreadyExecutedError(bytes32 mtxHash, uint256 executedBlockNumber) internal pure returns (bytes memory) { - return abi.encodeWithSelector( - bytes4(keccak256("MetaTransactionAlreadyExecutedError(bytes32,uint256)")), - mtxHash, - executedBlockNumber - ); + return + abi.encodeWithSelector( + bytes4(keccak256("MetaTransactionAlreadyExecutedError(bytes32,uint256)")), + mtxHash, + executedBlockNumber + ); } function MetaTransactionCallFailedError( bytes32 mtxHash, bytes memory callData, bytes memory returnData - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("MetaTransactionCallFailedError(bytes32,bytes,bytes)")), - mtxHash, - callData, - returnData - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("MetaTransactionCallFailedError(bytes32,bytes,bytes)")), + mtxHash, + callData, + returnData + ); } } diff --git a/contracts/zero-ex/contracts/src/errors/LibNFTOrdersRichErrors.sol b/contracts/zero-ex/contracts/src/errors/LibNFTOrdersRichErrors.sol index 6c354066a3..20e2d2cbbb 100644 --- a/contracts/zero-ex/contracts/src/errors/LibNFTOrdersRichErrors.sol +++ b/contracts/zero-ex/contracts/src/errors/LibNFTOrdersRichErrors.sol @@ -19,176 +19,81 @@ pragma solidity ^0.6.5; - library LibNFTOrdersRichErrors { - // solhint-disable func-name-mixedcase - function OverspentEthError( - uint256 ethSpent, - uint256 ethAvailable - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("OverspentEthError(uint256,uint256)")), - ethSpent, - ethAvailable - ); + function OverspentEthError(uint256 ethSpent, uint256 ethAvailable) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("OverspentEthError(uint256,uint256)")), ethSpent, ethAvailable); } - function InsufficientEthError( - uint256 ethAvailable, - uint256 orderAmount - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("InsufficientEthError(uint256,uint256)")), - ethAvailable, - orderAmount - ); + function InsufficientEthError(uint256 ethAvailable, uint256 orderAmount) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("InsufficientEthError(uint256,uint256)")), + ethAvailable, + orderAmount + ); } - function ERC721TokenMismatchError( - address token1, - address token2 - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("ERC721TokenMismatchError(address,address)")), - token1, - token2 - ); + function ERC721TokenMismatchError(address token1, address token2) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("ERC721TokenMismatchError(address,address)")), token1, token2); } - function ERC1155TokenMismatchError( - address token1, - address token2 - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("ERC1155TokenMismatchError(address,address)")), - token1, - token2 - ); + function ERC1155TokenMismatchError(address token1, address token2) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("ERC1155TokenMismatchError(address,address)")), token1, token2); } - function ERC20TokenMismatchError( - address token1, - address token2 - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("ERC20TokenMismatchError(address,address)")), - token1, - token2 - ); + function ERC20TokenMismatchError(address token1, address token2) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("ERC20TokenMismatchError(address,address)")), token1, token2); } - function NegativeSpreadError( - uint256 sellOrderAmount, - uint256 buyOrderAmount - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("NegativeSpreadError(uint256,uint256)")), - sellOrderAmount, - buyOrderAmount - ); + function NegativeSpreadError(uint256 sellOrderAmount, uint256 buyOrderAmount) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("NegativeSpreadError(uint256,uint256)")), + sellOrderAmount, + buyOrderAmount + ); } - function SellOrderFeesExceedSpreadError( - uint256 sellOrderFees, - uint256 spread - ) + function SellOrderFeesExceedSpreadError(uint256 sellOrderFees, uint256 spread) internal pure returns (bytes memory) { - return abi.encodeWithSelector( - bytes4(keccak256("SellOrderFeesExceedSpreadError(uint256,uint256)")), - sellOrderFees, - spread - ); + return + abi.encodeWithSelector( + bytes4(keccak256("SellOrderFeesExceedSpreadError(uint256,uint256)")), + sellOrderFees, + spread + ); } - function OnlyTakerError( - address sender, - address taker - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("OnlyTakerError(address,address)")), - sender, - taker - ); + function OnlyTakerError(address sender, address taker) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("OnlyTakerError(address,address)")), sender, taker); } - function InvalidSignerError( - address maker, - address signer - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("InvalidSignerError(address,address)")), - maker, - signer - ); + function InvalidSignerError(address maker, address signer) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("InvalidSignerError(address,address)")), maker, signer); } function OrderNotFillableError( address maker, uint256 nonce, uint8 orderStatus - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("OrderNotFillableError(address,uint256,uint8)")), - maker, - nonce, - orderStatus - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("OrderNotFillableError(address,uint256,uint8)")), + maker, + nonce, + orderStatus + ); } - function TokenIdMismatchError( - uint256 tokenId, - uint256 orderTokenId - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("TokenIdMismatchError(uint256,uint256)")), - tokenId, - orderTokenId - ); + function TokenIdMismatchError(uint256 tokenId, uint256 orderTokenId) internal pure returns (bytes memory) { + return + abi.encodeWithSelector(bytes4(keccak256("TokenIdMismatchError(uint256,uint256)")), tokenId, orderTokenId); } function PropertyValidationFailedError( @@ -197,33 +102,28 @@ library LibNFTOrdersRichErrors { uint256 tokenId, bytes memory propertyData, bytes memory errorData - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("PropertyValidationFailedError(address,address,uint256,bytes,bytes)")), - propertyValidator, - token, - tokenId, - propertyData, - errorData - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("PropertyValidationFailedError(address,address,uint256,bytes,bytes)")), + propertyValidator, + token, + tokenId, + propertyData, + errorData + ); } - function ExceedsRemainingOrderAmount( - uint128 remainingOrderAmount, - uint128 fillAmount - ) + function ExceedsRemainingOrderAmount(uint128 remainingOrderAmount, uint128 fillAmount) internal pure returns (bytes memory) { - return abi.encodeWithSelector( - bytes4(keccak256("ExceedsRemainingOrderAmount(uint128,uint128)")), - remainingOrderAmount, - fillAmount - ); + return + abi.encodeWithSelector( + bytes4(keccak256("ExceedsRemainingOrderAmount(uint128,uint128)")), + remainingOrderAmount, + fillAmount + ); } } diff --git a/contracts/zero-ex/contracts/src/errors/LibNativeOrdersRichErrors.sol b/contracts/zero-ex/contracts/src/errors/LibNativeOrdersRichErrors.sol index a12ab14281..5ef6b4444c 100644 --- a/contracts/zero-ex/contracts/src/errors/LibNativeOrdersRichErrors.sol +++ b/contracts/zero-ex/contracts/src/errors/LibNativeOrdersRichErrors.sol @@ -19,187 +19,131 @@ pragma solidity ^0.6.5; - library LibNativeOrdersRichErrors { - // solhint-disable func-name-mixedcase - function ProtocolFeeRefundFailed( - address receiver, - uint256 refundAmount - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("ProtocolFeeRefundFailed(address,uint256)")), - receiver, - refundAmount - ); + function ProtocolFeeRefundFailed(address receiver, uint256 refundAmount) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("ProtocolFeeRefundFailed(address,uint256)")), + receiver, + refundAmount + ); } function OrderNotFillableByOriginError( bytes32 orderHash, address txOrigin, address orderTxOrigin - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("OrderNotFillableByOriginError(bytes32,address,address)")), - orderHash, - txOrigin, - orderTxOrigin - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("OrderNotFillableByOriginError(bytes32,address,address)")), + orderHash, + txOrigin, + orderTxOrigin + ); } - function OrderNotFillableError( - bytes32 orderHash, - uint8 orderStatus - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("OrderNotFillableError(bytes32,uint8)")), - orderHash, - orderStatus - ); + function OrderNotFillableError(bytes32 orderHash, uint8 orderStatus) internal pure returns (bytes memory) { + return + abi.encodeWithSelector(bytes4(keccak256("OrderNotFillableError(bytes32,uint8)")), orderHash, orderStatus); } function OrderNotSignedByMakerError( bytes32 orderHash, address signer, address maker - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("OrderNotSignedByMakerError(bytes32,address,address)")), - orderHash, - signer, - maker - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("OrderNotSignedByMakerError(bytes32,address,address)")), + orderHash, + signer, + maker + ); } - function InvalidSignerError( - address maker, - address signer - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("InvalidSignerError(address,address)")), - maker, - signer - ); + function InvalidSignerError(address maker, address signer) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("InvalidSignerError(address,address)")), maker, signer); } function OrderNotFillableBySenderError( bytes32 orderHash, address sender, address orderSender - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("OrderNotFillableBySenderError(bytes32,address,address)")), - orderHash, - sender, - orderSender - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("OrderNotFillableBySenderError(bytes32,address,address)")), + orderHash, + sender, + orderSender + ); } function OrderNotFillableByTakerError( bytes32 orderHash, address taker, address orderTaker - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("OrderNotFillableByTakerError(bytes32,address,address)")), - orderHash, - taker, - orderTaker - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("OrderNotFillableByTakerError(bytes32,address,address)")), + orderHash, + taker, + orderTaker + ); } - function CancelSaltTooLowError( - uint256 minValidSalt, - uint256 oldMinValidSalt - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("CancelSaltTooLowError(uint256,uint256)")), - minValidSalt, - oldMinValidSalt - ); + function CancelSaltTooLowError(uint256 minValidSalt, uint256 oldMinValidSalt) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("CancelSaltTooLowError(uint256,uint256)")), + minValidSalt, + oldMinValidSalt + ); } function FillOrKillFailedError( bytes32 orderHash, uint256 takerTokenFilledAmount, uint256 takerTokenFillAmount - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("FillOrKillFailedError(bytes32,uint256,uint256)")), - orderHash, - takerTokenFilledAmount, - takerTokenFillAmount - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("FillOrKillFailedError(bytes32,uint256,uint256)")), + orderHash, + takerTokenFilledAmount, + takerTokenFillAmount + ); } function OnlyOrderMakerAllowed( bytes32 orderHash, address sender, address maker - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("OnlyOrderMakerAllowed(bytes32,address,address)")), - orderHash, - sender, - maker - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("OnlyOrderMakerAllowed(bytes32,address,address)")), + orderHash, + sender, + maker + ); } function BatchFillIncompleteError( bytes32 orderHash, uint256 takerTokenFilledAmount, uint256 takerTokenFillAmount - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("BatchFillIncompleteError(bytes32,uint256,uint256)")), - orderHash, - takerTokenFilledAmount, - takerTokenFillAmount - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("BatchFillIncompleteError(bytes32,uint256,uint256)")), + orderHash, + takerTokenFilledAmount, + takerTokenFillAmount + ); } } diff --git a/contracts/zero-ex/contracts/src/errors/LibOwnableRichErrors.sol b/contracts/zero-ex/contracts/src/errors/LibOwnableRichErrors.sol index 73e6b9450a..aca97d63d2 100644 --- a/contracts/zero-ex/contracts/src/errors/LibOwnableRichErrors.sol +++ b/contracts/zero-ex/contracts/src/errors/LibOwnableRichErrors.sol @@ -19,45 +19,18 @@ pragma solidity ^0.6.5; - library LibOwnableRichErrors { - // solhint-disable func-name-mixedcase - function OnlyOwnerError( - address sender, - address owner - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("OnlyOwnerError(address,address)")), - sender, - owner - ); + function OnlyOwnerError(address sender, address owner) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("OnlyOwnerError(address,address)")), sender, owner); } - function TransferOwnerToZeroError() - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("TransferOwnerToZeroError()")) - ); + function TransferOwnerToZeroError() internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("TransferOwnerToZeroError()"))); } - function MigrateCallFailedError(address target, bytes memory resultData) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("MigrateCallFailedError(address,bytes)")), - target, - resultData - ); + function MigrateCallFailedError(address target, bytes memory resultData) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("MigrateCallFailedError(address,bytes)")), target, resultData); } } diff --git a/contracts/zero-ex/contracts/src/errors/LibProxyRichErrors.sol b/contracts/zero-ex/contracts/src/errors/LibProxyRichErrors.sol index 1d5a8f09e9..c609ac1fec 100644 --- a/contracts/zero-ex/contracts/src/errors/LibProxyRichErrors.sol +++ b/contracts/zero-ex/contracts/src/errors/LibProxyRichErrors.sol @@ -19,55 +19,23 @@ pragma solidity ^0.6.5; - library LibProxyRichErrors { - // solhint-disable func-name-mixedcase - function NotImplementedError(bytes4 selector) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("NotImplementedError(bytes4)")), - selector - ); + function NotImplementedError(bytes4 selector) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("NotImplementedError(bytes4)")), selector); } - function InvalidBootstrapCallerError(address actual, address expected) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("InvalidBootstrapCallerError(address,address)")), - actual, - expected - ); + function InvalidBootstrapCallerError(address actual, address expected) internal pure returns (bytes memory) { + return + abi.encodeWithSelector(bytes4(keccak256("InvalidBootstrapCallerError(address,address)")), actual, expected); } - function InvalidDieCallerError(address actual, address expected) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("InvalidDieCallerError(address,address)")), - actual, - expected - ); + function InvalidDieCallerError(address actual, address expected) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("InvalidDieCallerError(address,address)")), actual, expected); } - function BootstrapCallFailedError(address target, bytes memory resultData) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("BootstrapCallFailedError(address,bytes)")), - target, - resultData - ); + function BootstrapCallFailedError(address target, bytes memory resultData) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("BootstrapCallFailedError(address,bytes)")), target, resultData); } } diff --git a/contracts/zero-ex/contracts/src/errors/LibSignatureRichErrors.sol b/contracts/zero-ex/contracts/src/errors/LibSignatureRichErrors.sol index 60623e0026..63862543d4 100644 --- a/contracts/zero-ex/contracts/src/errors/LibSignatureRichErrors.sol +++ b/contracts/zero-ex/contracts/src/errors/LibSignatureRichErrors.sol @@ -19,9 +19,7 @@ pragma solidity ^0.6.5; - library LibSignatureRichErrors { - enum SignatureValidationErrorCodes { ALWAYS_INVALID, INVALID_LENGTH, @@ -38,32 +36,22 @@ library LibSignatureRichErrors { bytes32 hash, address signerAddress, bytes memory signature - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("SignatureValidationError(uint8,bytes32,address,bytes)")), - code, - hash, - signerAddress, - signature - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("SignatureValidationError(uint8,bytes32,address,bytes)")), + code, + hash, + signerAddress, + signature + ); } - function SignatureValidationError( - SignatureValidationErrorCodes code, - bytes32 hash - ) + function SignatureValidationError(SignatureValidationErrorCodes code, bytes32 hash) internal pure returns (bytes memory) { - return abi.encodeWithSelector( - bytes4(keccak256("SignatureValidationError(uint8,bytes32)")), - code, - hash - ); + return abi.encodeWithSelector(bytes4(keccak256("SignatureValidationError(uint8,bytes32)")), code, hash); } } diff --git a/contracts/zero-ex/contracts/src/errors/LibSimpleFunctionRegistryRichErrors.sol b/contracts/zero-ex/contracts/src/errors/LibSimpleFunctionRegistryRichErrors.sol index 84f456124a..335e4c86e0 100644 --- a/contracts/zero-ex/contracts/src/errors/LibSimpleFunctionRegistryRichErrors.sol +++ b/contracts/zero-ex/contracts/src/errors/LibSimpleFunctionRegistryRichErrors.sol @@ -19,20 +19,15 @@ pragma solidity ^0.6.5; - library LibSimpleFunctionRegistryRichErrors { - // solhint-disable func-name-mixedcase - function NotInRollbackHistoryError(bytes4 selector, address targetImpl) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("NotInRollbackHistoryError(bytes4,address)")), - selector, - targetImpl - ); + function NotInRollbackHistoryError(bytes4 selector, address targetImpl) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("NotInRollbackHistoryError(bytes4,address)")), + selector, + targetImpl + ); } } diff --git a/contracts/zero-ex/contracts/src/errors/LibTransformERC20RichErrors.sol b/contracts/zero-ex/contracts/src/errors/LibTransformERC20RichErrors.sol index 6582399b7e..683e56691c 100644 --- a/contracts/zero-ex/contracts/src/errors/LibTransformERC20RichErrors.sol +++ b/contracts/zero-ex/contracts/src/errors/LibTransformERC20RichErrors.sol @@ -19,105 +19,77 @@ pragma solidity ^0.6.5; - library LibTransformERC20RichErrors { - // solhint-disable func-name-mixedcase,separate-by-one-line-in-contract - function InsufficientEthAttachedError( - uint256 ethAttached, - uint256 ethNeeded - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("InsufficientEthAttachedError(uint256,uint256)")), - ethAttached, - ethNeeded - ); + function InsufficientEthAttachedError(uint256 ethAttached, uint256 ethNeeded) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("InsufficientEthAttachedError(uint256,uint256)")), + ethAttached, + ethNeeded + ); } function IncompleteTransformERC20Error( address outputToken, uint256 outputTokenAmount, uint256 minOutputTokenAmount - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("IncompleteTransformERC20Error(address,uint256,uint256)")), - outputToken, - outputTokenAmount, - minOutputTokenAmount - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("IncompleteTransformERC20Error(address,uint256,uint256)")), + outputToken, + outputTokenAmount, + minOutputTokenAmount + ); } - function NegativeTransformERC20OutputError( - address outputToken, - uint256 outputTokenLostAmount - ) + function NegativeTransformERC20OutputError(address outputToken, uint256 outputTokenLostAmount) internal pure returns (bytes memory) { - return abi.encodeWithSelector( - bytes4(keccak256("NegativeTransformERC20OutputError(address,uint256)")), - outputToken, - outputTokenLostAmount - ); + return + abi.encodeWithSelector( + bytes4(keccak256("NegativeTransformERC20OutputError(address,uint256)")), + outputToken, + outputTokenLostAmount + ); } function TransformerFailedError( address transformer, bytes memory transformerData, bytes memory resultData - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("TransformerFailedError(address,bytes,bytes)")), - transformer, - transformerData, - resultData - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("TransformerFailedError(address,bytes,bytes)")), + transformer, + transformerData, + resultData + ); } // Common Transformer errors /////////////////////////////////////////////// - function OnlyCallableByDeployerError( - address caller, - address deployer - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("OnlyCallableByDeployerError(address,address)")), - caller, - deployer - ); + function OnlyCallableByDeployerError(address caller, address deployer) internal pure returns (bytes memory) { + return + abi.encodeWithSelector(bytes4(keccak256("OnlyCallableByDeployerError(address,address)")), caller, deployer); } - function InvalidExecutionContextError( - address actualContext, - address expectedContext - ) + function InvalidExecutionContextError(address actualContext, address expectedContext) internal pure returns (bytes memory) { - return abi.encodeWithSelector( - bytes4(keccak256("InvalidExecutionContextError(address,address)")), - actualContext, - expectedContext - ); + return + abi.encodeWithSelector( + bytes4(keccak256("InvalidExecutionContextError(address,address)")), + actualContext, + expectedContext + ); } enum InvalidTransformDataErrorCode { @@ -125,19 +97,17 @@ library LibTransformERC20RichErrors { INVALID_ARRAY_LENGTH } - function InvalidTransformDataError( - InvalidTransformDataErrorCode errorCode, - bytes memory transformData - ) + function InvalidTransformDataError(InvalidTransformDataErrorCode errorCode, bytes memory transformData) internal pure returns (bytes memory) { - return abi.encodeWithSelector( - bytes4(keccak256("InvalidTransformDataError(uint8,bytes)")), - errorCode, - transformData - ); + return + abi.encodeWithSelector( + bytes4(keccak256("InvalidTransformDataError(uint8,bytes)")), + errorCode, + transformData + ); } // FillQuoteTransformer errors ///////////////////////////////////////////// @@ -146,89 +116,57 @@ library LibTransformERC20RichErrors { address sellToken, uint256 soldAmount, uint256 sellAmount - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("IncompleteFillSellQuoteError(address,uint256,uint256)")), - sellToken, - soldAmount, - sellAmount - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("IncompleteFillSellQuoteError(address,uint256,uint256)")), + sellToken, + soldAmount, + sellAmount + ); } function IncompleteFillBuyQuoteError( address buyToken, uint256 boughtAmount, uint256 buyAmount - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("IncompleteFillBuyQuoteError(address,uint256,uint256)")), - buyToken, - boughtAmount, - buyAmount - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("IncompleteFillBuyQuoteError(address,uint256,uint256)")), + buyToken, + boughtAmount, + buyAmount + ); } - function InsufficientTakerTokenError( - uint256 tokenBalance, - uint256 tokensNeeded - ) + function InsufficientTakerTokenError(uint256 tokenBalance, uint256 tokensNeeded) internal pure returns (bytes memory) { - return abi.encodeWithSelector( - bytes4(keccak256("InsufficientTakerTokenError(uint256,uint256)")), - tokenBalance, - tokensNeeded - ); + return + abi.encodeWithSelector( + bytes4(keccak256("InsufficientTakerTokenError(uint256,uint256)")), + tokenBalance, + tokensNeeded + ); } - function InsufficientProtocolFeeError( - uint256 ethBalance, - uint256 ethNeeded - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("InsufficientProtocolFeeError(uint256,uint256)")), - ethBalance, - ethNeeded - ); + function InsufficientProtocolFeeError(uint256 ethBalance, uint256 ethNeeded) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("InsufficientProtocolFeeError(uint256,uint256)")), + ethBalance, + ethNeeded + ); } - function InvalidERC20AssetDataError( - bytes memory assetData - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("InvalidERC20AssetDataError(bytes)")), - assetData - ); + function InvalidERC20AssetDataError(bytes memory assetData) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("InvalidERC20AssetDataError(bytes)")), assetData); } - function InvalidTakerFeeTokenError( - address token - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("InvalidTakerFeeTokenError(address)")), - token - ); + function InvalidTakerFeeTokenError(address token) internal pure returns (bytes memory) { + return abi.encodeWithSelector(bytes4(keccak256("InvalidTakerFeeTokenError(address)")), token); } } diff --git a/contracts/zero-ex/contracts/src/errors/LibWalletRichErrors.sol b/contracts/zero-ex/contracts/src/errors/LibWalletRichErrors.sol index 00bde1a23e..602c896c15 100644 --- a/contracts/zero-ex/contracts/src/errors/LibWalletRichErrors.sol +++ b/contracts/zero-ex/contracts/src/errors/LibWalletRichErrors.sol @@ -19,9 +19,7 @@ pragma solidity ^0.6.5; - library LibWalletRichErrors { - // solhint-disable func-name-mixedcase function WalletExecuteCallFailedError( @@ -30,19 +28,16 @@ library LibWalletRichErrors { bytes memory callData, uint256 callValue, bytes memory errorData - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("WalletExecuteCallFailedError(address,address,bytes,uint256,bytes)")), - wallet, - callTarget, - callData, - callValue, - errorData - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("WalletExecuteCallFailedError(address,address,bytes,uint256,bytes)")), + wallet, + callTarget, + callData, + callValue, + errorData + ); } function WalletExecuteDelegateCallFailedError( @@ -50,17 +45,14 @@ library LibWalletRichErrors { address callTarget, bytes memory callData, bytes memory errorData - ) - internal - pure - returns (bytes memory) - { - return abi.encodeWithSelector( - bytes4(keccak256("WalletExecuteDelegateCallFailedError(address,address,bytes,bytes)")), - wallet, - callTarget, - callData, - errorData - ); + ) internal pure returns (bytes memory) { + return + abi.encodeWithSelector( + bytes4(keccak256("WalletExecuteDelegateCallFailedError(address,address,bytes,bytes)")), + wallet, + callTarget, + callData, + errorData + ); } } diff --git a/contracts/zero-ex/contracts/src/external/FeeCollector.sol b/contracts/zero-ex/contracts/src/external/FeeCollector.sol index 1adaa898d9..c7f3c608fe 100644 --- a/contracts/zero-ex/contracts/src/external/FeeCollector.sol +++ b/contracts/zero-ex/contracts/src/external/FeeCollector.sol @@ -27,7 +27,7 @@ import "../vendor/v3/IStaking.sol"; /// @dev The collector contract for protocol fees contract FeeCollector is AuthorizableV06 { /// @dev Allow ether transfers to the collector. - receive() external payable { } + receive() external payable {} constructor() public { _addAuthorizedAddress(msg.sender); @@ -42,22 +42,14 @@ contract FeeCollector is AuthorizableV06 { IEtherTokenV06 weth, IStaking staking, bytes32 poolId - ) - external - onlyAuthorized - { + ) external onlyAuthorized { weth.approve(address(staking), type(uint256).max); staking.joinStakingPoolAsMaker(poolId); } /// @dev Convert all held ether to WETH. Only an authority can call this. /// @param weth The WETH contract. - function convertToWeth( - IEtherTokenV06 weth - ) - external - onlyAuthorized - { + function convertToWeth(IEtherTokenV06 weth) external onlyAuthorized { if (address(this).balance > 0) { weth.deposit{value: address(this).balance}(); } diff --git a/contracts/zero-ex/contracts/src/external/FeeCollectorController.sol b/contracts/zero-ex/contracts/src/external/FeeCollectorController.sol index edcd785cbe..9e823f994d 100644 --- a/contracts/zero-ex/contracts/src/external/FeeCollectorController.sol +++ b/contracts/zero-ex/contracts/src/external/FeeCollectorController.sol @@ -25,10 +25,8 @@ import "../vendor/v3/IStaking.sol"; import "./FeeCollector.sol"; import "./LibFeeCollector.sol"; - /// @dev A contract that manages `FeeCollector` contracts. contract FeeCollectorController { - /// @dev Hash of the fee collector init code. bytes32 public immutable FEE_COLLECTOR_INIT_CODE_HASH; /// @dev The WETH contract. @@ -36,12 +34,7 @@ contract FeeCollectorController { /// @dev The staking contract. IStaking private immutable STAKING; - constructor( - IEtherTokenV06 weth, - IStaking staking - ) - public - { + constructor(IEtherTokenV06 weth, IStaking staking) public { FEE_COLLECTOR_INIT_CODE_HASH = keccak256(type(FeeCollector).creationCode); WETH = weth; STAKING = staking; @@ -51,10 +44,7 @@ contract FeeCollectorController { /// and wrap its ETH into WETH. Anyone may call this. /// @param poolId The pool ID associated with the staking pool. /// @return feeCollector The `FeeCollector` contract instance. - function prepareFeeCollectorToPayFees(bytes32 poolId) - external - returns (FeeCollector feeCollector) - { + function prepareFeeCollectorToPayFees(bytes32 poolId) external returns (FeeCollector feeCollector) { feeCollector = getFeeCollector(poolId); uint256 codeSize; assembly { @@ -79,15 +69,8 @@ contract FeeCollectorController { /// has been called once. /// @param poolId The pool ID associated with the staking pool. /// @return feeCollector The `FeeCollector` contract instance. - function getFeeCollector(bytes32 poolId) - public - view - returns (FeeCollector feeCollector) - { - return FeeCollector(LibFeeCollector.getFeeCollectorAddress( - address(this), - FEE_COLLECTOR_INIT_CODE_HASH, - poolId - )); + function getFeeCollector(bytes32 poolId) public view returns (FeeCollector feeCollector) { + return + FeeCollector(LibFeeCollector.getFeeCollectorAddress(address(this), FEE_COLLECTOR_INIT_CODE_HASH, poolId)); } } diff --git a/contracts/zero-ex/contracts/src/external/FlashWallet.sol b/contracts/zero-ex/contracts/src/external/FlashWallet.sol index 2e15f95994..4210a89583 100644 --- a/contracts/zero-ex/contracts/src/external/FlashWallet.sol +++ b/contracts/zero-ex/contracts/src/external/FlashWallet.sol @@ -25,17 +25,15 @@ import "@0x/contracts-utils/contracts/src/v06/errors/LibOwnableRichErrorsV06.sol import "../errors/LibWalletRichErrors.sol"; import "./IFlashWallet.sol"; - /// @dev A contract that can execute arbitrary calls from its owner. -contract FlashWallet is - IFlashWallet -{ +contract FlashWallet is IFlashWallet { // solhint-disable no-unused-vars,indent,no-empty-blocks using LibRichErrorsV06 for bytes; // solhint-disable /// @dev Store the owner/deployer as an immutable to make this contract stateless. - address public override immutable owner; + address public immutable override owner; + // solhint-enable constructor() public { @@ -46,10 +44,7 @@ contract FlashWallet is /// @dev Allows only the (immutable) owner to call a function. modifier onlyOwner() virtual { if (msg.sender != owner) { - LibOwnableRichErrorsV06.OnlyOwnerError( - msg.sender, - owner - ).rrevert(); + LibOwnableRichErrorsV06.OnlyOwnerError(msg.sender, owner).rrevert(); } _; } @@ -63,24 +58,12 @@ contract FlashWallet is address payable target, bytes calldata callData, uint256 value - ) - external - payable - override - onlyOwner - returns (bytes memory resultData) - { + ) external payable override onlyOwner returns (bytes memory resultData) { bool success; (success, resultData) = target.call{value: value}(callData); if (!success) { LibWalletRichErrors - .WalletExecuteCallFailedError( - address(this), - target, - callData, - value, - resultData - ) + .WalletExecuteCallFailedError(address(this), target, callData, value, resultData) .rrevert(); } } @@ -90,10 +73,7 @@ contract FlashWallet is /// @param target The call target. /// @param callData The call data. /// @return resultData The data returned by the call. - function executeDelegateCall( - address payable target, - bytes calldata callData - ) + function executeDelegateCall(address payable target, bytes calldata callData) external payable override @@ -104,32 +84,25 @@ contract FlashWallet is (success, resultData) = target.delegatecall(callData); if (!success) { LibWalletRichErrors - .WalletExecuteDelegateCallFailedError( - address(this), - target, - callData, - resultData - ) + .WalletExecuteDelegateCallFailedError(address(this), target, callData, resultData) .rrevert(); } } // solhint-disable /// @dev Allows this contract to receive ether. - receive() external override payable {} + receive() external payable override {} + // solhint-enable /// @dev Signal support for receiving ERC1155 tokens. /// @param interfaceID The interface ID, as per ERC-165 rules. /// @return hasSupport `true` if this contract supports an ERC-165 interface. - function supportsInterface(bytes4 interfaceID) - external - pure - returns (bool hasSupport) - { - return interfaceID == this.supportsInterface.selector || - interfaceID == this.onERC1155Received.selector ^ this.onERC1155BatchReceived.selector || - interfaceID == this.tokenFallback.selector; + function supportsInterface(bytes4 interfaceID) external pure returns (bool hasSupport) { + return + interfaceID == this.supportsInterface.selector || + interfaceID == this.onERC1155Received.selector ^ this.onERC1155BatchReceived.selector || + interfaceID == this.tokenFallback.selector; } /// @dev Allow this contract to receive ERC1155 tokens. @@ -140,11 +113,7 @@ contract FlashWallet is uint256, // id, uint256, // value, bytes calldata //data - ) - external - pure - returns (bytes4 success) - { + ) external pure returns (bytes4 success) { return this.onERC1155Received.selector; } @@ -156,11 +125,7 @@ contract FlashWallet is uint256[] calldata, // ids, uint256[] calldata, // values, bytes calldata // data - ) - external - pure - returns (bytes4 success) - { + ) external pure returns (bytes4 success) { return this.onERC1155BatchReceived.selector; } @@ -169,8 +134,5 @@ contract FlashWallet is address, // from, uint256, // value, bytes calldata // value - ) - external - pure - {} + ) external pure {} } diff --git a/contracts/zero-ex/contracts/src/external/IFlashWallet.sol b/contracts/zero-ex/contracts/src/external/IFlashWallet.sol index 5cec7f6813..460745e665 100644 --- a/contracts/zero-ex/contracts/src/external/IFlashWallet.sol +++ b/contracts/zero-ex/contracts/src/external/IFlashWallet.sol @@ -22,10 +22,8 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/interfaces/IOwnableV06.sol"; - /// @dev A contract that can execute arbitrary calls from its owner. interface IFlashWallet { - /// @dev Execute an arbitrary call. Only an authority can call this. /// @param target The call target. /// @param callData The call data. @@ -35,20 +33,14 @@ interface IFlashWallet { address payable target, bytes calldata callData, uint256 value - ) - external - payable - returns (bytes memory resultData); + ) external payable returns (bytes memory resultData); /// @dev Execute an arbitrary delegatecall, in the context of this puppet. /// Only an authority can call this. /// @param target The call target. /// @param callData The call data. /// @return resultData The data returned by the call. - function executeDelegateCall( - address payable target, - bytes calldata callData - ) + function executeDelegateCall(address payable target, bytes calldata callData) external payable returns (bytes memory resultData); diff --git a/contracts/zero-ex/contracts/src/external/ILiquidityProviderSandbox.sol b/contracts/zero-ex/contracts/src/external/ILiquidityProviderSandbox.sol index 879d909300..428c8b474c 100644 --- a/contracts/zero-ex/contracts/src/external/ILiquidityProviderSandbox.sol +++ b/contracts/zero-ex/contracts/src/external/ILiquidityProviderSandbox.sol @@ -23,9 +23,7 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../vendor/ILiquidityProvider.sol"; - interface ILiquidityProviderSandbox { - /// @dev Calls `sellTokenForToken` on the given `provider` contract to /// trigger a trade. /// @param provider The address of the on-chain liquidity provider. @@ -41,8 +39,7 @@ interface ILiquidityProviderSandbox { address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external; + ) external; /// @dev Calls `sellEthForToken` on the given `provider` contract to /// trigger a trade. @@ -57,8 +54,7 @@ interface ILiquidityProviderSandbox { address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external; + ) external; /// @dev Calls `sellTokenForEth` on the given `provider` contract to /// trigger a trade. @@ -73,6 +69,5 @@ interface ILiquidityProviderSandbox { address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external; + ) external; } diff --git a/contracts/zero-ex/contracts/src/external/LibFeeCollector.sol b/contracts/zero-ex/contracts/src/external/LibFeeCollector.sol index e44212bfb3..f05b9f7db9 100644 --- a/contracts/zero-ex/contracts/src/external/LibFeeCollector.sol +++ b/contracts/zero-ex/contracts/src/external/LibFeeCollector.sol @@ -20,25 +20,30 @@ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; - /// @dev Helpers for computing `FeeCollector` contract addresses. library LibFeeCollector { - /// @dev Compute the CREATE2 address for a fee collector. /// @param controller The address of the `FeeCollectorController` contract. /// @param initCodeHash The init code hash of the `FeeCollector` contract. /// @param poolId The fee collector's pool ID. - function getFeeCollectorAddress(address controller, bytes32 initCodeHash, bytes32 poolId) - internal - pure - returns (address payable feeCollectorAddress) - { + function getFeeCollectorAddress( + address controller, + bytes32 initCodeHash, + bytes32 poolId + ) internal pure returns (address payable feeCollectorAddress) { // Compute the CREATE2 address for the fee collector. - return address(uint256(keccak256(abi.encodePacked( - byte(0xff), - controller, - poolId, // pool ID is salt - initCodeHash - )))); + return + address( + uint256( + keccak256( + abi.encodePacked( + bytes1(0xff), + controller, + poolId, // pool ID is salt + initCodeHash + ) + ) + ) + ); } } diff --git a/contracts/zero-ex/contracts/src/external/LiquidityProviderSandbox.sol b/contracts/zero-ex/contracts/src/external/LiquidityProviderSandbox.sol index 867e38afd1..853aec423a 100644 --- a/contracts/zero-ex/contracts/src/external/LiquidityProviderSandbox.sol +++ b/contracts/zero-ex/contracts/src/external/LiquidityProviderSandbox.sol @@ -22,30 +22,22 @@ import "../vendor/ILiquidityProvider.sol"; import "../vendor/v3/IERC20Bridge.sol"; import "./ILiquidityProviderSandbox.sol"; - /// @dev A permissionless contract through which the ZeroEx contract can /// safely trigger a trade on an external `ILiquidityProvider` contract. -contract LiquidityProviderSandbox is - ILiquidityProviderSandbox -{ +contract LiquidityProviderSandbox is ILiquidityProviderSandbox { using LibRichErrorsV06 for bytes; /// @dev Store the owner as an immutable. address public immutable owner; - constructor(address owner_) - public - { + constructor(address owner_) public { owner = owner_; } /// @dev Allows only the (immutable) owner to call a function. modifier onlyOwner() virtual { if (msg.sender != owner) { - LibOwnableRichErrorsV06.OnlyOwnerError( - msg.sender, - owner - ).rrevert(); + LibOwnableRichErrorsV06.OnlyOwnerError(msg.sender, owner).rrevert(); } _; } @@ -65,18 +57,8 @@ contract LiquidityProviderSandbox is address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - onlyOwner - override - { - provider.sellTokenForToken( - inputToken, - outputToken, - recipient, - minBuyAmount, - auxiliaryData - ); + ) external override onlyOwner { + provider.sellTokenForToken(inputToken, outputToken, recipient, minBuyAmount, auxiliaryData); } /// @dev Calls `sellEthForToken` on the given `provider` contract to @@ -92,17 +74,8 @@ contract LiquidityProviderSandbox is address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - onlyOwner - override - { - provider.sellEthForToken( - outputToken, - recipient, - minBuyAmount, - auxiliaryData - ); + ) external override onlyOwner { + provider.sellEthForToken(outputToken, recipient, minBuyAmount, auxiliaryData); } /// @dev Calls `sellTokenForEth` on the given `provider` contract to @@ -118,16 +91,7 @@ contract LiquidityProviderSandbox is address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - onlyOwner - override - { - provider.sellTokenForEth( - inputToken, - payable(recipient), - minBuyAmount, - auxiliaryData - ); + ) external override onlyOwner { + provider.sellTokenForEth(inputToken, payable(recipient), minBuyAmount, auxiliaryData); } } diff --git a/contracts/zero-ex/contracts/src/external/PermissionlessTransformerDeployer.sol b/contracts/zero-ex/contracts/src/external/PermissionlessTransformerDeployer.sol index bb66b33942..6430449a7d 100644 --- a/contracts/zero-ex/contracts/src/external/PermissionlessTransformerDeployer.sol +++ b/contracts/zero-ex/contracts/src/external/PermissionlessTransformerDeployer.sol @@ -20,7 +20,6 @@ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; - /// @dev Deployer contract for ERC20 transformers. contract PermissionlessTransformerDeployer { /// @dev Emitted when a contract is deployed via `deploy()`. @@ -30,21 +29,17 @@ contract PermissionlessTransformerDeployer { event Deployed(address deployedAddress, bytes32 salt, address sender); // @dev Mapping of deployed contract address to the deployment salt. - mapping (address => bytes32) public toDeploymentSalt; + mapping(address => bytes32) public toDeploymentSalt; // @dev Mapping of deployed contract address to the init code hash. - mapping (address => bytes32) public toInitCodeHash; + mapping(address => bytes32) public toInitCodeHash; /// @dev Deploy a new contract. Any attached ETH will be forwarded. - function deploy(bytes memory bytecode, bytes32 salt) - public - payable - returns (address deployedAddress) - { + function deploy(bytes memory bytecode, bytes32 salt) public payable returns (address deployedAddress) { assembly { deployedAddress := create2(callvalue(), add(bytecode, 32), mload(bytecode), salt) } - require(deployedAddress != address(0), 'PermissionlessTransformerDeployer/DEPLOY_FAILED'); - require(isDelegateCallSafe(deployedAddress), 'PermissionlessTransformerDeployer/UNSAFE_CODE'); + require(deployedAddress != address(0), "PermissionlessTransformerDeployer/DEPLOY_FAILED"); + require(isDelegateCallSafe(deployedAddress), "PermissionlessTransformerDeployer/UNSAFE_CODE"); toDeploymentSalt[deployedAddress] = salt; toInitCodeHash[deployedAddress] = keccak256(bytecode); emit Deployed(deployedAddress, salt, msg.sender); @@ -59,8 +54,10 @@ contract PermissionlessTransformerDeployer { /// @return True if the contract is considered safe for delegatecall. function isDelegateCallSafe(address target) public view returns (bool) { uint256 size; - assembly { size := extcodesize(target) } - require(size > 0, 'PermissionlessTransformerDeployer/NO_CODE'); + assembly { + size := extcodesize(target) + } + require(size > 0, "PermissionlessTransformerDeployer/NO_CODE"); bytes memory extcode = new bytes(size); assembly { @@ -73,7 +70,8 @@ contract PermissionlessTransformerDeployer { uint8 op = uint8(extcode[i]); // If the opcode is a PUSH, skip over the push data. - if (op > 95 && op < 128) { // pushN + if (op > 95 && op < 128) { + // pushN i += (op - 95); continue; } @@ -84,8 +82,8 @@ contract PermissionlessTransformerDeployer { op == 254 || // invalid op == 243 || // return op == 253 || // revert - op == 86 || // jump - op == 0 // stop + op == 86 || // jump + op == 0 // stop ) { reachable = false; continue; @@ -98,12 +96,13 @@ contract PermissionlessTransformerDeployer { op == 255 || // selfdestruct op == 240 || // create op == 245 || // create2 - op == 84 || // sload - op == 85 // sstore + op == 84 || // sload + op == 85 // sstore ) { return false; } - } else if (op == 91) { // jumpdest + } else if (op == 91) { + // jumpdest // After a JUMPDEST, opcodes are reachable again. reachable = true; } @@ -112,4 +111,3 @@ contract PermissionlessTransformerDeployer { return true; // No impermissible opcodes found. } } - diff --git a/contracts/zero-ex/contracts/src/external/TransformerDeployer.sol b/contracts/zero-ex/contracts/src/external/TransformerDeployer.sol index c6b180ce00..2d344bc5f6 100644 --- a/contracts/zero-ex/contracts/src/external/TransformerDeployer.sol +++ b/contracts/zero-ex/contracts/src/external/TransformerDeployer.sol @@ -22,7 +22,6 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/AuthorizableV06.sol"; - /// @dev A contract with a `die()` function. interface IKillable { function die(address payable ethRecipient) external; @@ -30,9 +29,7 @@ interface IKillable { /// @dev Deployer contract for ERC20 transformers. /// Only authorities may call `deploy()` and `kill()`. -contract TransformerDeployer is - AuthorizableV06 -{ +contract TransformerDeployer is AuthorizableV06 { /// @dev Emitted when a contract is deployed via `deploy()`. /// @param deployedAddress The address of the deployed contract. /// @param nonce The deployment nonce. @@ -46,7 +43,7 @@ contract TransformerDeployer is // @dev The current nonce of this contract. uint256 public nonce = 1; // @dev Mapping of deployed contract address to deployment nonce. - mapping (address => uint256) public toDeploymentNonce; + mapping(address => uint256) public toDeploymentNonce; /// @dev Create this contract and register authorities. constructor(address[] memory initialAuthorities) public { @@ -57,18 +54,13 @@ contract TransformerDeployer is /// @dev Deploy a new contract. Only callable by an authority. /// Any attached ETH will also be forwarded. - function deploy(bytes memory bytecode) - public - payable - onlyAuthorized - returns (address deployedAddress) - { + function deploy(bytes memory bytecode) public payable onlyAuthorized returns (address deployedAddress) { uint256 deploymentNonce = nonce; nonce += 1; assembly { deployedAddress := create(callvalue(), add(bytecode, 32), mload(bytecode)) } - require(deployedAddress != address(0), 'TransformerDeployer/DEPLOY_FAILED'); + require(deployedAddress != address(0), "TransformerDeployer/DEPLOY_FAILED"); toDeploymentNonce[deployedAddress] = deploymentNonce; emit Deployed(deployedAddress, deploymentNonce, msg.sender); } @@ -76,10 +68,7 @@ contract TransformerDeployer is /// @dev Call `die()` on a contract. Only callable by an authority. /// @param target The target contract to call `die()` on. /// @param ethRecipient The Recipient of any ETH locked in `target`. - function kill(IKillable target, address payable ethRecipient) - public - onlyAuthorized - { + function kill(IKillable target, address payable ethRecipient) public onlyAuthorized { target.die(ethRecipient); emit Killed(address(target), msg.sender); } diff --git a/contracts/zero-ex/contracts/src/features/BatchFillNativeOrdersFeature.sol b/contracts/zero-ex/contracts/src/features/BatchFillNativeOrdersFeature.sol index 61f0bd818f..984eb15aa2 100644 --- a/contracts/zero-ex/contracts/src/features/BatchFillNativeOrdersFeature.sol +++ b/contracts/zero-ex/contracts/src/features/BatchFillNativeOrdersFeature.sol @@ -33,14 +33,8 @@ import "./interfaces/INativeOrdersFeature.sol"; import "./libs/LibNativeOrder.sol"; import "./libs/LibSignature.sol"; - /// @dev Feature for batch/market filling limit and RFQ orders. -contract BatchFillNativeOrdersFeature is - IFeature, - IBatchFillNativeOrdersFeature, - FixinCommon, - FixinEIP712 -{ +contract BatchFillNativeOrdersFeature is IFeature, IBatchFillNativeOrdersFeature, FixinCommon, FixinEIP712 { using LibSafeMathV06 for uint128; using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; @@ -50,20 +44,14 @@ contract BatchFillNativeOrdersFeature is /// @dev Version of this feature. uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 1, 0); - constructor(address zeroExAddress) - public - FixinEIP712(zeroExAddress) - { + constructor(address zeroExAddress) public FixinEIP712(zeroExAddress) { // solhint-disable no-empty-blocks } /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. - function migrate() - external - returns (bytes4 success) - { + function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.batchFillLimitOrders.selector); _registerFeatureFunction(this.batchFillRfqOrders.selector); return LibMigrate.MIGRATE_SUCCESS; @@ -86,51 +74,42 @@ contract BatchFillNativeOrdersFeature is external payable override - returns ( - uint128[] memory takerTokenFilledAmounts, - uint128[] memory makerTokenFilledAmounts - ) + returns (uint128[] memory takerTokenFilledAmounts, uint128[] memory makerTokenFilledAmounts) { require( orders.length == signatures.length && orders.length == takerTokenFillAmounts.length, - 'BatchFillNativeOrdersFeature::batchFillLimitOrders/MISMATCHED_ARRAY_LENGTHS' + "BatchFillNativeOrdersFeature::batchFillLimitOrders/MISMATCHED_ARRAY_LENGTHS" ); takerTokenFilledAmounts = new uint128[](orders.length); makerTokenFilledAmounts = new uint128[](orders.length); - uint256 protocolFee = uint256(INativeOrdersFeature(address(this)).getProtocolFeeMultiplier()) - .safeMul(tx.gasprice); + uint256 protocolFee = uint256(INativeOrdersFeature(address(this)).getProtocolFeeMultiplier()).safeMul( + tx.gasprice + ); uint256 ethProtocolFeePaid; for (uint256 i = 0; i != orders.length; i++) { try - INativeOrdersFeature(address(this))._fillLimitOrder - ( - orders[i], - signatures[i], - takerTokenFillAmounts[i], - msg.sender, - msg.sender - ) - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + INativeOrdersFeature(address(this))._fillLimitOrder( + orders[i], + signatures[i], + takerTokenFillAmounts[i], + msg.sender, + msg.sender + ) + returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { // Update amounts filled. - (takerTokenFilledAmounts[i], makerTokenFilledAmounts[i]) = - (takerTokenFilledAmount, makerTokenFilledAmount); + (takerTokenFilledAmounts[i], makerTokenFilledAmounts[i]) = ( + takerTokenFilledAmount, + makerTokenFilledAmount + ); ethProtocolFeePaid = ethProtocolFeePaid.safeAdd(protocolFee); } catch {} - if ( - revertIfIncomplete && - takerTokenFilledAmounts[i] < takerTokenFillAmounts[i] - ) { - bytes32 orderHash = _getEIP712Hash( - LibNativeOrder.getLimitOrderStructHash(orders[i]) - ); + if (revertIfIncomplete && takerTokenFilledAmounts[i] < takerTokenFillAmounts[i]) { + bytes32 orderHash = _getEIP712Hash(LibNativeOrder.getLimitOrderStructHash(orders[i])); // Did not fill the amount requested. - LibNativeOrdersRichErrors.BatchFillIncompleteError( - orderHash, - takerTokenFilledAmounts[i], - takerTokenFillAmounts[i] - ).rrevert(); + LibNativeOrdersRichErrors + .BatchFillIncompleteError(orderHash, takerTokenFilledAmounts[i], takerTokenFillAmounts[i]) + .rrevert(); } } LibNativeOrder.refundExcessProtocolFeeToSender(ethProtocolFeePaid); @@ -149,51 +128,37 @@ contract BatchFillNativeOrdersFeature is LibSignature.Signature[] calldata signatures, uint128[] calldata takerTokenFillAmounts, bool revertIfIncomplete - ) - external - override - returns ( - uint128[] memory takerTokenFilledAmounts, - uint128[] memory makerTokenFilledAmounts - ) - { + ) external override returns (uint128[] memory takerTokenFilledAmounts, uint128[] memory makerTokenFilledAmounts) { require( orders.length == signatures.length && orders.length == takerTokenFillAmounts.length, - 'BatchFillNativeOrdersFeature::batchFillRfqOrders/MISMATCHED_ARRAY_LENGTHS' + "BatchFillNativeOrdersFeature::batchFillRfqOrders/MISMATCHED_ARRAY_LENGTHS" ); takerTokenFilledAmounts = new uint128[](orders.length); makerTokenFilledAmounts = new uint128[](orders.length); for (uint256 i = 0; i != orders.length; i++) { try - INativeOrdersFeature(address(this))._fillRfqOrder - ( - orders[i], - signatures[i], - takerTokenFillAmounts[i], - msg.sender, - false, - msg.sender - ) - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + INativeOrdersFeature(address(this))._fillRfqOrder( + orders[i], + signatures[i], + takerTokenFillAmounts[i], + msg.sender, + false, + msg.sender + ) + returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { // Update amounts filled. - (takerTokenFilledAmounts[i], makerTokenFilledAmounts[i]) = - (takerTokenFilledAmount, makerTokenFilledAmount); + (takerTokenFilledAmounts[i], makerTokenFilledAmounts[i]) = ( + takerTokenFilledAmount, + makerTokenFilledAmount + ); } catch {} - if ( - revertIfIncomplete && - takerTokenFilledAmounts[i] < takerTokenFillAmounts[i] - ) { + if (revertIfIncomplete && takerTokenFilledAmounts[i] < takerTokenFillAmounts[i]) { // Did not fill the amount requested. - bytes32 orderHash = _getEIP712Hash( - LibNativeOrder.getRfqOrderStructHash(orders[i]) - ); - LibNativeOrdersRichErrors.BatchFillIncompleteError( - orderHash, - takerTokenFilledAmounts[i], - takerTokenFillAmounts[i] - ).rrevert(); + bytes32 orderHash = _getEIP712Hash(LibNativeOrder.getRfqOrderStructHash(orders[i])); + LibNativeOrdersRichErrors + .BatchFillIncompleteError(orderHash, takerTokenFilledAmounts[i], takerTokenFillAmounts[i]) + .rrevert(); } } } diff --git a/contracts/zero-ex/contracts/src/features/BootstrapFeature.sol b/contracts/zero-ex/contracts/src/features/BootstrapFeature.sol index b697ead362..b2a6201c92 100644 --- a/contracts/zero-ex/contracts/src/features/BootstrapFeature.sol +++ b/contracts/zero-ex/contracts/src/features/BootstrapFeature.sol @@ -25,21 +25,18 @@ import "../migrations/LibBootstrap.sol"; import "../storage/LibProxyStorage.sol"; import "./interfaces/IBootstrapFeature.sol"; - /// @dev Detachable `bootstrap()` feature. -contract BootstrapFeature is - IBootstrapFeature -{ +contract BootstrapFeature is IBootstrapFeature { // solhint-disable state-visibility,indent /// @dev The ZeroEx contract. /// This has to be immutable to persist across delegatecalls. - address immutable private _deployer; + address private immutable _deployer; /// @dev The implementation address of this contract. /// This has to be immutable to persist across delegatecalls. - address immutable private _implementation; + address private immutable _implementation; /// @dev The deployer. /// This has to be immutable to persist across delegatecalls. - address immutable private _bootstrapCaller; + address private immutable _bootstrapCaller; // solhint-enable state-visibility,indent using LibRichErrorsV06 for bytes; @@ -62,10 +59,7 @@ contract BootstrapFeature is function bootstrap(address target, bytes calldata callData) external override { // Only the bootstrap caller can call this function. if (msg.sender != _bootstrapCaller) { - LibProxyRichErrors.InvalidBootstrapCallerError( - msg.sender, - _bootstrapCaller - ).rrevert(); + LibProxyRichErrors.InvalidBootstrapCallerError(msg.sender, _bootstrapCaller).rrevert(); } // Deregister. LibProxyStorage.getStorage().impls[this.bootstrap.selector] = address(0); diff --git a/contracts/zero-ex/contracts/src/features/ERC165Feature.sol b/contracts/zero-ex/contracts/src/features/ERC165Feature.sol index 52f6dc3783..604ab99d03 100644 --- a/contracts/zero-ex/contracts/src/features/ERC165Feature.sol +++ b/contracts/zero-ex/contracts/src/features/ERC165Feature.sol @@ -23,12 +23,8 @@ pragma experimental ABIEncoderV2; import "../fixins/FixinCommon.sol"; import "./interfaces/IFeature.sol"; - /// @dev Implements the ERC165 `supportsInterface` function -contract ERC165Feature is - IFeature, - FixinCommon -{ +contract ERC165Feature is IFeature, FixinCommon { /// @dev Name of this feature. string public constant override FEATURE_NAME = "ERC165"; /// @dev Version of this feature. @@ -39,13 +35,10 @@ contract ERC165Feature is /// @param interfaceId The interface identifier, as specified in ERC165. /// @return isSupported Whether the given interface is supported by the /// 0x Exchange Proxy. - function supportInterface(bytes4 interfaceId) - external - pure - returns (bool isSupported) - { - return interfaceId == 0x01ffc9a7 || // ERC-165 support - interfaceId == 0x150b7a02 || // ERC-721 `ERC721TokenReceiver` support - interfaceId == 0x4e2312e0; // ERC-1155 `ERC1155TokenReceiver` support + function supportInterface(bytes4 interfaceId) external pure returns (bool isSupported) { + return + interfaceId == 0x01ffc9a7 || // ERC-165 support + interfaceId == 0x150b7a02 || // ERC-721 `ERC721TokenReceiver` support + interfaceId == 0x4e2312e0; // ERC-1155 `ERC1155TokenReceiver` support } } diff --git a/contracts/zero-ex/contracts/src/features/FundRecoveryFeature.sol b/contracts/zero-ex/contracts/src/features/FundRecoveryFeature.sol index c92e979121..33a31168f2 100644 --- a/contracts/zero-ex/contracts/src/features/FundRecoveryFeature.sol +++ b/contracts/zero-ex/contracts/src/features/FundRecoveryFeature.sol @@ -22,11 +22,7 @@ import "./interfaces/IFeature.sol"; import "./interfaces/IFundRecoveryFeature.sol"; import "../transformers/LibERC20Transformer.sol"; -contract FundRecoveryFeature is - IFeature, - IFundRecoveryFeature, - FixinCommon -{ +contract FundRecoveryFeature is IFeature, IFundRecoveryFeature, FixinCommon { /// @dev Name of this feature. string public constant override FEATURE_NAME = "FundRecoveryFeature"; /// @dev Version of this feature. @@ -35,10 +31,7 @@ contract FundRecoveryFeature is /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. - function migrate() - external - returns (bytes4 success) - { + function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.transferTrappedTokensTo.selector); return LibMigrate.MIGRATE_SUCCESS; } @@ -51,16 +44,10 @@ contract FundRecoveryFeature is IERC20TokenV06 erc20, uint256 amountOut, address payable recipientWallet - ) - external - override - onlyOwner - { - if(amountOut == uint256(-1)) { + ) external override onlyOwner { + if (amountOut == uint256(-1)) { amountOut = LibERC20Transformer.getTokenBalanceOf(erc20, address(this)); } LibERC20Transformer.transformerTransfer(erc20, recipientWallet, amountOut); } - - -} \ No newline at end of file +} diff --git a/contracts/zero-ex/contracts/src/features/LiquidityProviderFeature.sol b/contracts/zero-ex/contracts/src/features/LiquidityProviderFeature.sol index 1e2f170ea5..5e91cc5de5 100644 --- a/contracts/zero-ex/contracts/src/features/LiquidityProviderFeature.sol +++ b/contracts/zero-ex/contracts/src/features/LiquidityProviderFeature.sol @@ -34,13 +34,7 @@ import "../transformers/LibERC20Transformer.sol"; import "./interfaces/IFeature.sol"; import "./interfaces/ILiquidityProviderFeature.sol"; - -contract LiquidityProviderFeature is - IFeature, - ILiquidityProviderFeature, - FixinCommon, - FixinTokenSpender -{ +contract LiquidityProviderFeature is IFeature, ILiquidityProviderFeature, FixinCommon, FixinTokenSpender { using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; @@ -52,20 +46,14 @@ contract LiquidityProviderFeature is /// @dev The sandbox contract address. ILiquidityProviderSandbox public immutable sandbox; - constructor(LiquidityProviderSandbox sandbox_) - public - FixinCommon() - { + constructor(LiquidityProviderSandbox sandbox_) public FixinCommon() { sandbox = sandbox_; } /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. - function migrate() - external - returns (bytes4 success) - { + function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.sellToLiquidityProvider.selector); return LibMigrate.MIGRATE_SUCCESS; } @@ -91,12 +79,7 @@ contract LiquidityProviderFeature is uint256 sellAmount, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - override - payable - returns (uint256 boughtAmount) - { + ) external payable override returns (uint256 boughtAmount) { if (recipient == address(0)) { recipient = msg.sender; } @@ -108,65 +91,36 @@ contract LiquidityProviderFeature is if (!LibERC20Transformer.isTokenETH(inputToken)) { // Transfer input ERC20 tokens to the provider. - _transferERC20TokensFrom( - inputToken, - msg.sender, - address(provider), - sellAmount - ); + _transferERC20TokensFrom(inputToken, msg.sender, address(provider), sellAmount); } if (LibERC20Transformer.isTokenETH(inputToken)) { uint256 balanceBefore = outputToken.balanceOf(recipient); - sandbox.executeSellEthForToken( - provider, - outputToken, - recipient, - minBuyAmount, - auxiliaryData - ); + sandbox.executeSellEthForToken(provider, outputToken, recipient, minBuyAmount, auxiliaryData); boughtAmount = IERC20TokenV06(outputToken).balanceOf(recipient).safeSub(balanceBefore); } else if (LibERC20Transformer.isTokenETH(outputToken)) { uint256 balanceBefore = recipient.balance; - sandbox.executeSellTokenForEth( - provider, - inputToken, - recipient, - minBuyAmount, - auxiliaryData - ); + sandbox.executeSellTokenForEth(provider, inputToken, recipient, minBuyAmount, auxiliaryData); boughtAmount = recipient.balance.safeSub(balanceBefore); } else { uint256 balanceBefore = outputToken.balanceOf(recipient); - sandbox.executeSellTokenForToken( - provider, - inputToken, - outputToken, - recipient, - minBuyAmount, - auxiliaryData - ); + sandbox.executeSellTokenForToken(provider, inputToken, outputToken, recipient, minBuyAmount, auxiliaryData); boughtAmount = outputToken.balanceOf(recipient).safeSub(balanceBefore); } if (boughtAmount < minBuyAmount) { - LibLiquidityProviderRichErrors.LiquidityProviderIncompleteSellError( - address(provider), - address(outputToken), - address(inputToken), - sellAmount, - boughtAmount, - minBuyAmount - ).rrevert(); + LibLiquidityProviderRichErrors + .LiquidityProviderIncompleteSellError( + address(provider), + address(outputToken), + address(inputToken), + sellAmount, + boughtAmount, + minBuyAmount + ) + .rrevert(); } - emit LiquidityProviderSwap( - inputToken, - outputToken, - sellAmount, - boughtAmount, - provider, - recipient - ); + emit LiquidityProviderSwap(inputToken, outputToken, sellAmount, boughtAmount, provider, recipient); } } diff --git a/contracts/zero-ex/contracts/src/features/MetaTransactionsFeature.sol b/contracts/zero-ex/contracts/src/features/MetaTransactionsFeature.sol index 6121564462..2701d1db1f 100644 --- a/contracts/zero-ex/contracts/src/features/MetaTransactionsFeature.sol +++ b/contracts/zero-ex/contracts/src/features/MetaTransactionsFeature.sol @@ -80,8 +80,9 @@ contract MetaTransactionsFeature is /// @dev Version of this feature. uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 2, 1); /// @dev EIP712 typehash of the `MetaTransactionData` struct. - bytes32 public immutable MTX_EIP712_TYPEHASH = keccak256( - "MetaTransactionData(" + bytes32 public immutable MTX_EIP712_TYPEHASH = + keccak256( + "MetaTransactionData(" "address signer," "address sender," "uint256 minGasPrice," @@ -92,14 +93,13 @@ contract MetaTransactionsFeature is "uint256 value," "address feeToken," "uint256 feeAmount" - ")" - ); + ")" + ); /// @dev Refunds up to `msg.value` leftover ETH at the end of the call. modifier refundsAttachedEth() { _; - uint256 remainingBalance = - LibSafeMathV06.min256(msg.value, address(this).balance); + uint256 remainingBalance = LibSafeMathV06.min256(msg.value, address(this).balance); if (remainingBalance > 0) { msg.sender.transfer(remainingBalance); } @@ -110,27 +110,17 @@ contract MetaTransactionsFeature is modifier doesNotReduceEthBalance() { uint256 initialBalance = address(this).balance - msg.value; _; - require( - initialBalance <= address(this).balance, - "MetaTransactionsFeature/ETH_LEAK" - ); + require(initialBalance <= address(this).balance, "MetaTransactionsFeature/ETH_LEAK"); } - constructor(address zeroExAddress) - public - FixinCommon() - FixinEIP712(zeroExAddress) - { + constructor(address zeroExAddress) public FixinCommon() FixinEIP712(zeroExAddress) { // solhint-disable-next-line no-empty-blocks } /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. - function migrate() - external - returns (bytes4 success) - { + function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.executeMetaTransaction.selector); _registerFeatureFunction(this.batchExecuteMetaTransactions.selector); _registerFeatureFunction(this.getMetaTransactionExecutedBlock.selector); @@ -143,10 +133,7 @@ contract MetaTransactionsFeature is /// @param mtx The meta-transaction. /// @param signature The signature by `mtx.signer`. /// @return returnResult The ABI-encoded result of the underlying call. - function executeMetaTransaction( - MetaTransactionData memory mtx, - LibSignature.Signature memory signature - ) + function executeMetaTransaction(MetaTransactionData memory mtx, LibSignature.Signature memory signature) public payable override @@ -168,10 +155,7 @@ contract MetaTransactionsFeature is /// @param mtxs The meta-transactions. /// @param signatures The signature by each respective `mtx.signer`. /// @return returnResults The ABI-encoded results of the underlying calls. - function batchExecuteMetaTransactions( - MetaTransactionData[] memory mtxs, - LibSignature.Signature[] memory signatures - ) + function batchExecuteMetaTransactions(MetaTransactionData[] memory mtxs, LibSignature.Signature[] memory signatures) public payable override @@ -181,10 +165,9 @@ contract MetaTransactionsFeature is returns (bytes[] memory returnResults) { if (mtxs.length != signatures.length) { - LibMetaTransactionsRichErrors.InvalidMetaTransactionsArrayLengthsError( - mtxs.length, - signatures.length - ).rrevert(); + LibMetaTransactionsRichErrors + .InvalidMetaTransactionsArrayLengthsError(mtxs.length, signatures.length) + .rrevert(); } returnResults = new bytes[](mtxs.length); for (uint256 i = 0; i < mtxs.length; ++i) { @@ -203,8 +186,8 @@ contract MetaTransactionsFeature is /// @return blockNumber The block height when the meta-transactioin was executed. function getMetaTransactionExecutedBlock(MetaTransactionData memory mtx) public - override view + override returns (uint256 blockNumber) { return getMetaTransactionHashExecutedBlock(getMetaTransactionHash(mtx)); @@ -213,63 +196,49 @@ contract MetaTransactionsFeature is /// @dev Get the block at which a meta-transaction hash has been executed. /// @param mtxHash The meta-transaction hash. /// @return blockNumber The block height when the meta-transactioin was executed. - function getMetaTransactionHashExecutedBlock(bytes32 mtxHash) - public - override - view - returns (uint256 blockNumber) - { + function getMetaTransactionHashExecutedBlock(bytes32 mtxHash) public view override returns (uint256 blockNumber) { return LibMetaTransactionsStorage.getStorage().mtxHashToExecutedBlockNumber[mtxHash]; } /// @dev Get the EIP712 hash of a meta-transaction. /// @param mtx The meta-transaction. /// @return mtxHash The EIP712 hash of `mtx`. - function getMetaTransactionHash(MetaTransactionData memory mtx) - public - override - view - returns (bytes32 mtxHash) - { - return _getEIP712Hash(keccak256(abi.encode( - MTX_EIP712_TYPEHASH, - mtx.signer, - mtx.sender, - mtx.minGasPrice, - mtx.maxGasPrice, - mtx.expirationTimeSeconds, - mtx.salt, - keccak256(mtx.callData), - mtx.value, - mtx.feeToken, - mtx.feeAmount - ))); + function getMetaTransactionHash(MetaTransactionData memory mtx) public view override returns (bytes32 mtxHash) { + return + _getEIP712Hash( + keccak256( + abi.encode( + MTX_EIP712_TYPEHASH, + mtx.signer, + mtx.sender, + mtx.minGasPrice, + mtx.maxGasPrice, + mtx.expirationTimeSeconds, + mtx.salt, + keccak256(mtx.callData), + mtx.value, + mtx.feeToken, + mtx.feeAmount + ) + ) + ); } /// @dev Execute a meta-transaction by `sender`. Low-level, hidden variant. /// @param state The `ExecuteState` for this metatransaction, with `sender`, /// `hash`, `mtx`, and `signature` fields filled. /// @return returnResult The ABI-encoded result of the underlying call. - function _executeMetaTransactionPrivate(ExecuteState memory state) - private - returns (bytes memory returnResult) - { + function _executeMetaTransactionPrivate(ExecuteState memory state) private returns (bytes memory returnResult) { _validateMetaTransaction(state); // Mark the transaction executed by storing the block at which it was executed. // Currently the block number just indicates that the mtx was executed and // serves no other purpose from within this contract. - LibMetaTransactionsStorage.getStorage() - .mtxHashToExecutedBlockNumber[state.hash] = block.number; + LibMetaTransactionsStorage.getStorage().mtxHashToExecutedBlockNumber[state.hash] = block.number; // Pay the fee to the sender. if (state.mtx.feeAmount > 0) { - _transferERC20TokensFrom( - state.mtx.feeToken, - state.mtx.signer, - state.sender, - state.mtx.feeAmount - ); + _transferERC20TokensFrom(state.mtx.feeToken, state.mtx.signer, state.sender, state.mtx.feeAmount); } // Execute the call based on the selector. @@ -281,82 +250,57 @@ contract MetaTransactionsFeature is } else if (state.selector == INativeOrdersFeature.fillRfqOrder.selector) { returnResult = _executeFillRfqOrderCall(state); } else { - LibMetaTransactionsRichErrors - .MetaTransactionUnsupportedFunctionError(state.hash, state.selector) - .rrevert(); + LibMetaTransactionsRichErrors.MetaTransactionUnsupportedFunctionError(state.hash, state.selector).rrevert(); } - emit MetaTransactionExecuted( - state.hash, - state.selector, - state.mtx.signer, - state.mtx.sender - ); + emit MetaTransactionExecuted(state.hash, state.selector, state.mtx.signer, state.mtx.sender); } /// @dev Validate that a meta-transaction is executable. - function _validateMetaTransaction(ExecuteState memory state) - private - view - { + function _validateMetaTransaction(ExecuteState memory state) private view { // Must be from the required sender, if set. if (state.mtx.sender != address(0) && state.mtx.sender != state.sender) { LibMetaTransactionsRichErrors - .MetaTransactionWrongSenderError( - state.hash, - state.sender, - state.mtx.sender - ).rrevert(); + .MetaTransactionWrongSenderError(state.hash, state.sender, state.mtx.sender) + .rrevert(); } // Must not be expired. if (state.mtx.expirationTimeSeconds <= block.timestamp) { LibMetaTransactionsRichErrors - .MetaTransactionExpiredError( - state.hash, - block.timestamp, - state.mtx.expirationTimeSeconds - ).rrevert(); + .MetaTransactionExpiredError(state.hash, block.timestamp, state.mtx.expirationTimeSeconds) + .rrevert(); } // Must have a valid gas price. if (state.mtx.minGasPrice > tx.gasprice || state.mtx.maxGasPrice < tx.gasprice) { LibMetaTransactionsRichErrors - .MetaTransactionGasPriceError( - state.hash, - tx.gasprice, - state.mtx.minGasPrice, - state.mtx.maxGasPrice - ).rrevert(); + .MetaTransactionGasPriceError(state.hash, tx.gasprice, state.mtx.minGasPrice, state.mtx.maxGasPrice) + .rrevert(); } // Must have enough ETH. - state.selfBalance = address(this).balance; + state.selfBalance = address(this).balance; if (state.mtx.value > state.selfBalance) { LibMetaTransactionsRichErrors - .MetaTransactionInsufficientEthError( - state.hash, - state.selfBalance, - state.mtx.value - ).rrevert(); + .MetaTransactionInsufficientEthError(state.hash, state.selfBalance, state.mtx.value) + .rrevert(); } - if (LibSignature.getSignerOfHash(state.hash, state.signature) != - state.mtx.signer) { - LibSignatureRichErrors.SignatureValidationError( - LibSignatureRichErrors.SignatureValidationErrorCodes.WRONG_SIGNER, - state.hash, - state.mtx.signer, - // TODO: Remove this field from SignatureValidationError - // when rich reverts are part of the protocol repo. - "" - ).rrevert(); + if (LibSignature.getSignerOfHash(state.hash, state.signature) != state.mtx.signer) { + LibSignatureRichErrors + .SignatureValidationError( + LibSignatureRichErrors.SignatureValidationErrorCodes.WRONG_SIGNER, + state.hash, + state.mtx.signer, + // TODO: Remove this field from SignatureValidationError + // when rich reverts are part of the protocol repo. + "" + ) + .rrevert(); } // Transaction must not have been already executed. - state.executedBlockNumber = LibMetaTransactionsStorage - .getStorage().mtxHashToExecutedBlockNumber[state.hash]; + state.executedBlockNumber = LibMetaTransactionsStorage.getStorage().mtxHashToExecutedBlockNumber[state.hash]; if (state.executedBlockNumber != 0) { LibMetaTransactionsRichErrors - .MetaTransactionAlreadyExecutedError( - state.hash, - state.executedBlockNumber - ).rrevert(); + .MetaTransactionAlreadyExecutedError(state.hash, state.executedBlockNumber) + .rrevert(); } } @@ -364,10 +308,7 @@ contract MetaTransactionsFeature is /// by decoding the call args and translating the call to the internal /// `ITransformERC20Feature._transformERC20()` variant, where we can override /// the taker address. - function _executeTransformERC20Call(ExecuteState memory state) - private - returns (bytes memory returnResult) - { + function _executeTransformERC20Call(ExecuteState memory state) private returns (bytes memory returnResult) { // HACK(dorothy-zbornak): `abi.decode()` with the individual args // will cause a stack overflow. But we can prefix the call data with an // offset to transform it into the encoding for the equivalent single struct arg, @@ -418,43 +359,38 @@ contract MetaTransactionsFeature is args = abi.decode(encodedStructArgs, (ExternalTransformERC20Args)); } // Call `ITransformERC20Feature._transformERC20()` (internal variant). - return _callSelf( - state.hash, - abi.encodeWithSelector( - ITransformERC20Feature._transformERC20.selector, - ITransformERC20Feature.TransformERC20Args({ - taker: state.mtx.signer, // taker is mtx signer - inputToken: args.inputToken, - outputToken: args.outputToken, - inputTokenAmount: args.inputTokenAmount, - minOutputTokenAmount: args.minOutputTokenAmount, - transformations: args.transformations, - useSelfBalance: false, - recipient: state.mtx.signer - }) - ), - state.mtx.value - ); + return + _callSelf( + state.hash, + abi.encodeWithSelector( + ITransformERC20Feature._transformERC20.selector, + ITransformERC20Feature.TransformERC20Args({ + taker: state.mtx.signer, // taker is mtx signer + inputToken: args.inputToken, + outputToken: args.outputToken, + inputTokenAmount: args.inputTokenAmount, + minOutputTokenAmount: args.minOutputTokenAmount, + transformations: args.transformations, + useSelfBalance: false, + recipient: state.mtx.signer + }) + ), + state.mtx.value + ); } /// @dev Extract arguments from call data by copying everything after the /// 4-byte selector into a new byte array. /// @param callData The call data from which arguments are to be extracted. /// @return args The extracted arguments as a byte array. - function _extractArgumentsFromCallData( - bytes memory callData - ) - private - pure - returns (bytes memory args) - { + function _extractArgumentsFromCallData(bytes memory callData) private pure returns (bytes memory args) { args = new bytes(callData.length - 4); uint256 fromMem; uint256 toMem; assembly { fromMem := add(callData, 36) // skip length and 4-byte selector - toMem := add(args, 32) // write after length prefix + toMem := add(args, 32) // write after length prefix } LibBytesV06.memCopy(toMem, fromMem, args.length); @@ -466,75 +402,74 @@ contract MetaTransactionsFeature is /// by decoding the call args and translating the call to the internal /// `INativeOrdersFeature._fillLimitOrder()` variant, where we can override /// the taker address. - function _executeFillLimitOrderCall(ExecuteState memory state) - private - returns (bytes memory returnResult) - { + function _executeFillLimitOrderCall(ExecuteState memory state) private returns (bytes memory returnResult) { LibNativeOrder.LimitOrder memory order; LibSignature.Signature memory signature; uint128 takerTokenFillAmount; bytes memory args = _extractArgumentsFromCallData(state.mtx.callData); - (order, signature, takerTokenFillAmount) = abi.decode(args, (LibNativeOrder.LimitOrder, LibSignature.Signature, uint128)); - - return _callSelf( - state.hash, - abi.encodeWithSelector( - INativeOrdersFeature._fillLimitOrder.selector, - order, - signature, - takerTokenFillAmount, - state.mtx.signer, // taker is mtx signer - msg.sender - ), - state.mtx.value + (order, signature, takerTokenFillAmount) = abi.decode( + args, + (LibNativeOrder.LimitOrder, LibSignature.Signature, uint128) ); + + return + _callSelf( + state.hash, + abi.encodeWithSelector( + INativeOrdersFeature._fillLimitOrder.selector, + order, + signature, + takerTokenFillAmount, + state.mtx.signer, // taker is mtx signer + msg.sender + ), + state.mtx.value + ); } /// @dev Execute a `INativeOrdersFeature.fillRfqOrder()` meta-transaction call /// by decoding the call args and translating the call to the internal /// `INativeOrdersFeature._fillRfqOrder()` variant, where we can overrideunimpleme /// the taker address. - function _executeFillRfqOrderCall(ExecuteState memory state) - private - returns (bytes memory returnResult) - { + function _executeFillRfqOrderCall(ExecuteState memory state) private returns (bytes memory returnResult) { LibNativeOrder.RfqOrder memory order; LibSignature.Signature memory signature; uint128 takerTokenFillAmount; bytes memory args = _extractArgumentsFromCallData(state.mtx.callData); - (order, signature, takerTokenFillAmount) = abi.decode(args, (LibNativeOrder.RfqOrder, LibSignature.Signature, uint128)); - - return _callSelf( - state.hash, - abi.encodeWithSelector( - INativeOrdersFeature._fillRfqOrder.selector, - order, - signature, - takerTokenFillAmount, - state.mtx.signer, // taker is mtx signer - false, - state.mtx.signer - ), - state.mtx.value + (order, signature, takerTokenFillAmount) = abi.decode( + args, + (LibNativeOrder.RfqOrder, LibSignature.Signature, uint128) ); + + return + _callSelf( + state.hash, + abi.encodeWithSelector( + INativeOrdersFeature._fillRfqOrder.selector, + order, + signature, + takerTokenFillAmount, + state.mtx.signer, // taker is mtx signer + false, + state.mtx.signer + ), + state.mtx.value + ); } /// @dev Make an arbitrary internal, meta-transaction call. /// Warning: Do not let unadulterated `callData` into this function. - function _callSelf(bytes32 hash, bytes memory callData, uint256 value) - private - returns (bytes memory returnResult) - { + function _callSelf( + bytes32 hash, + bytes memory callData, + uint256 value + ) private returns (bytes memory returnResult) { bool success; (success, returnResult) = address(this).call{value: value}(callData); if (!success) { - LibMetaTransactionsRichErrors.MetaTransactionCallFailedError( - hash, - callData, - returnResult - ).rrevert(); + LibMetaTransactionsRichErrors.MetaTransactionCallFailedError(hash, callData, returnResult).rrevert(); } } } diff --git a/contracts/zero-ex/contracts/src/features/NativeOrdersFeature.sol b/contracts/zero-ex/contracts/src/features/NativeOrdersFeature.sol index 444ebd4151..dfc65752c7 100644 --- a/contracts/zero-ex/contracts/src/features/NativeOrdersFeature.sol +++ b/contracts/zero-ex/contracts/src/features/NativeOrdersFeature.sol @@ -25,12 +25,8 @@ import "./interfaces/IFeature.sol"; import "./interfaces/INativeOrdersFeature.sol"; import "./native_orders/NativeOrdersSettlement.sol"; - /// @dev Feature for interacting with limit and RFQ orders. -contract NativeOrdersFeature is - IFeature, - NativeOrdersSettlement -{ +contract NativeOrdersFeature is IFeature, NativeOrdersSettlement { /// @dev Name of this feature. string public constant override FEATURE_NAME = "LimitOrders"; /// @dev Version of this feature. @@ -42,26 +38,14 @@ contract NativeOrdersFeature is IStaking staking, FeeCollectorController feeCollectorController, uint32 protocolFeeMultiplier - ) - public - NativeOrdersSettlement( - zeroExAddress, - weth, - staking, - feeCollectorController, - protocolFeeMultiplier - ) - { + ) public NativeOrdersSettlement(zeroExAddress, weth, staking, feeCollectorController, protocolFeeMultiplier) { // solhint-disable no-empty-blocks } /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. - function migrate() - external - returns (bytes4 success) - { + function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.transferProtocolFeesForPools.selector); _registerFeatureFunction(this.fillLimitOrder.selector); _registerFeatureFunction(this.fillRfqOrder.selector); diff --git a/contracts/zero-ex/contracts/src/features/OtcOrdersFeature.sol b/contracts/zero-ex/contracts/src/features/OtcOrdersFeature.sol index 2ee5dd9cb1..e8d38ddd69 100644 --- a/contracts/zero-ex/contracts/src/features/OtcOrdersFeature.sol +++ b/contracts/zero-ex/contracts/src/features/OtcOrdersFeature.sol @@ -35,15 +35,8 @@ import "./interfaces/IOtcOrdersFeature.sol"; import "./libs/LibNativeOrder.sol"; import "./libs/LibSignature.sol"; - /// @dev Feature for interacting with OTC orders. -contract OtcOrdersFeature is - IFeature, - IOtcOrdersFeature, - FixinCommon, - FixinEIP712, - FixinTokenSpender -{ +contract OtcOrdersFeature is IFeature, IOtcOrdersFeature, FixinCommon, FixinEIP712, FixinTokenSpender { using LibSafeMathV06 for uint256; using LibSafeMathV06 for uint128; @@ -52,24 +45,18 @@ contract OtcOrdersFeature is /// @dev Version of this feature. uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0); /// @dev ETH pseudo-token address. - address constant private ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; + address private constant ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev The WETH token contract. IEtherTokenV06 private immutable WETH; - constructor(address zeroExAddress, IEtherTokenV06 weth) - public - FixinEIP712(zeroExAddress) - { + constructor(address zeroExAddress, IEtherTokenV06 weth) public FixinEIP712(zeroExAddress) { WETH = weth; } /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. - function migrate() - external - returns (bytes4 success) - { + function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.fillOtcOrder.selector); _registerFeatureFunction(this.fillOtcOrderForEth.selector); _registerFeatureFunction(this.fillOtcOrderWithEth.selector); @@ -94,18 +81,9 @@ contract OtcOrdersFeature is LibNativeOrder.OtcOrder memory order, LibSignature.Signature memory makerSignature, uint128 takerTokenFillAmount - ) - public - override - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + ) public override returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { LibNativeOrder.OtcOrderInfo memory orderInfo = getOtcOrderInfo(order); - _validateOtcOrder( - order, - orderInfo, - makerSignature, - msg.sender - ); + _validateOtcOrder(order, orderInfo, makerSignature, msg.sender); (takerTokenFilledAmount, makerTokenFilledAmount) = _settleOtcOrder( order, takerTokenFillAmount, @@ -125,7 +103,7 @@ contract OtcOrdersFeature is } /// @dev Fill an OTC order for up to `takerTokenFillAmount` taker tokens. - /// Unwraps bought WETH into ETH. before sending it to + /// Unwraps bought WETH into ETH. before sending it to /// the taker. /// @param order The OTC order. /// @param makerSignature The order signature from the maker. @@ -137,25 +115,13 @@ contract OtcOrdersFeature is LibNativeOrder.OtcOrder memory order, LibSignature.Signature memory makerSignature, uint128 takerTokenFillAmount - ) - public - override - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { - require( - order.makerToken == WETH, - "OtcOrdersFeature::fillOtcOrderForEth/MAKER_TOKEN_NOT_WETH" - ); + ) public override returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { + require(order.makerToken == WETH, "OtcOrdersFeature::fillOtcOrderForEth/MAKER_TOKEN_NOT_WETH"); LibNativeOrder.OtcOrderInfo memory orderInfo = getOtcOrderInfo(order); - _validateOtcOrder( - order, - orderInfo, - makerSignature, - msg.sender - ); + _validateOtcOrder(order, orderInfo, makerSignature, msg.sender); (takerTokenFilledAmount, makerTokenFilledAmount) = _settleOtcOrder( order, - takerTokenFillAmount, + takerTokenFillAmount, msg.sender, address(this) ); @@ -181,13 +147,10 @@ contract OtcOrdersFeature is /// @param makerSignature The order signature from the maker. /// @return takerTokenFilledAmount How much taker token was filled. /// @return makerTokenFilledAmount How much maker token was filled. - function fillOtcOrderWithEth( - LibNativeOrder.OtcOrder memory order, - LibSignature.Signature memory makerSignature - ) + function fillOtcOrderWithEth(LibNativeOrder.OtcOrder memory order, LibSignature.Signature memory makerSignature) public - override payable + override returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { if (order.takerToken == WETH) { @@ -201,14 +164,9 @@ contract OtcOrdersFeature is } LibNativeOrder.OtcOrderInfo memory orderInfo = getOtcOrderInfo(order); - _validateOtcOrder( - order, - orderInfo, - makerSignature, - msg.sender - ); + _validateOtcOrder(order, orderInfo, makerSignature, msg.sender); - (takerTokenFilledAmount, makerTokenFilledAmount) = _settleOtcOrder( + (takerTokenFilledAmount, makerTokenFilledAmount) = _settleOtcOrder( order, msg.value.safeDowncastToUint128(), address(this), @@ -243,25 +201,12 @@ contract OtcOrdersFeature is LibNativeOrder.OtcOrder memory order, LibSignature.Signature memory makerSignature, LibSignature.Signature memory takerSignature - ) - public - override - { + ) public override { LibNativeOrder.OtcOrderInfo memory orderInfo = getOtcOrderInfo(order); address taker = LibSignature.getSignerOfHash(orderInfo.orderHash, takerSignature); - - _validateOtcOrder( - order, - orderInfo, - makerSignature, - taker - ); - _settleOtcOrder( - order, - order.takerAmount, - taker, - taker - ); + + _validateOtcOrder(order, orderInfo, makerSignature, taker); + _settleOtcOrder(order, order.takerAmount, taker, taker); emit OtcOrderFilled( orderInfo.orderHash, @@ -276,7 +221,7 @@ contract OtcOrdersFeature is /// @dev Fully fill an OTC order. "Meta-transaction" variant, /// requires order to be signed by both maker and taker. - /// Unwraps bought WETH into ETH. before sending it to + /// Unwraps bought WETH into ETH. before sending it to /// the taker. /// @param order The OTC order. /// @param makerSignature The order signature from the maker. @@ -285,29 +230,13 @@ contract OtcOrdersFeature is LibNativeOrder.OtcOrder memory order, LibSignature.Signature memory makerSignature, LibSignature.Signature memory takerSignature - ) - public - override - { - require( - order.makerToken == WETH, - "OtcOrdersFeature::fillTakerSignedOtcOrder/MAKER_TOKEN_NOT_WETH" - ); + ) public override { + require(order.makerToken == WETH, "OtcOrdersFeature::fillTakerSignedOtcOrder/MAKER_TOKEN_NOT_WETH"); LibNativeOrder.OtcOrderInfo memory orderInfo = getOtcOrderInfo(order); address taker = LibSignature.getSignerOfHash(orderInfo.orderHash, takerSignature); - - _validateOtcOrder( - order, - orderInfo, - makerSignature, - taker - ); - _settleOtcOrder( - order, - order.takerAmount, - taker, - address(this) - ); + + _validateOtcOrder(order, orderInfo, makerSignature, taker); + _settleOtcOrder(order, order.takerAmount, taker, address(this)); // Unwrap WETH WETH.withdraw(order.makerAmount); // Transfer ETH to taker @@ -328,8 +257,8 @@ contract OtcOrdersFeature is /// @param orders Array of OTC orders. /// @param makerSignatures Array of maker signatures for each order. /// @param takerSignatures Array of taker signatures for each order. - /// @param unwrapWeth Array of booleans representing whether or not - /// to unwrap bought WETH into ETH for each order. Should be set + /// @param unwrapWeth Array of booleans representing whether or not + /// to unwrap bought WETH into ETH for each order. Should be set /// to false if the maker token is not WETH. /// @return successes Array of booleans representing whether or not /// each order in `orders` was filled successfully. @@ -338,30 +267,21 @@ contract OtcOrdersFeature is LibSignature.Signature[] memory makerSignatures, LibSignature.Signature[] memory takerSignatures, bool[] memory unwrapWeth - ) - public - override - returns (bool[] memory successes) - { + ) public override returns (bool[] memory successes) { require( - orders.length == makerSignatures.length && - orders.length == takerSignatures.length && - orders.length == unwrapWeth.length, + orders.length == makerSignatures.length && + orders.length == takerSignatures.length && + orders.length == unwrapWeth.length, "OtcOrdersFeature::batchFillTakerSignedOtcOrders/MISMATCHED_ARRAY_LENGTHS" ); successes = new bool[](orders.length); for (uint256 i = 0; i != orders.length; i++) { - bytes4 fnSelector = unwrapWeth[i] + bytes4 fnSelector = unwrapWeth[i] ? this.fillTakerSignedOtcOrderForEth.selector : this.fillTakerSignedOtcOrder.selector; // Swallow reverts (successes[i], ) = _implementation.delegatecall( - abi.encodeWithSelector( - fnSelector, - orders[i], - makerSignatures[i], - takerSignatures[i] - ) + abi.encodeWithSelector(fnSelector, orders[i], makerSignatures[i], takerSignatures[i]) ); } } @@ -385,19 +305,9 @@ contract OtcOrdersFeature is address taker, bool useSelfBalance, address recipient - ) - public - override - onlySelf - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + ) public override onlySelf returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { LibNativeOrder.OtcOrderInfo memory orderInfo = getOtcOrderInfo(order); - _validateOtcOrder( - order, - orderInfo, - makerSignature, - taker - ); + _validateOtcOrder(order, orderInfo, makerSignature, taker); (takerTokenFilledAmount, makerTokenFilledAmount) = _settleOtcOrder( order, takerTokenFillAmount, @@ -416,7 +326,7 @@ contract OtcOrdersFeature is ); } - /// @dev Validates an OTC order, reverting if the order cannot be + /// @dev Validates an OTC order, reverting if the order cannot be /// filled by the given taker. /// @param order The OTC order. /// @param orderInfo Info on the order. @@ -427,53 +337,32 @@ contract OtcOrdersFeature is LibNativeOrder.OtcOrderInfo memory orderInfo, LibSignature.Signature memory makerSignature, address taker - ) - private - view - { + ) private view { // Must be fillable. if (orderInfo.status != LibNativeOrder.OrderStatus.FILLABLE) { - LibNativeOrdersRichErrors.OrderNotFillableError( - orderInfo.orderHash, - uint8(orderInfo.status) - ).rrevert(); + LibNativeOrdersRichErrors.OrderNotFillableError(orderInfo.orderHash, uint8(orderInfo.status)).rrevert(); } // Must be a valid taker for the order. if (order.taker != address(0) && order.taker != taker) { - LibNativeOrdersRichErrors.OrderNotFillableByTakerError( - orderInfo.orderHash, - taker, - order.taker - ).rrevert(); + LibNativeOrdersRichErrors.OrderNotFillableByTakerError(orderInfo.orderHash, taker, order.taker).rrevert(); } - LibNativeOrdersStorage.Storage storage stor = - LibNativeOrdersStorage.getStorage(); + LibNativeOrdersStorage.Storage storage stor = LibNativeOrdersStorage.getStorage(); // Must be fillable by the tx.origin. - if ( - order.txOrigin != tx.origin && - !stor.originRegistry[order.txOrigin][tx.origin] - ) { - LibNativeOrdersRichErrors.OrderNotFillableByOriginError( - orderInfo.orderHash, - tx.origin, - order.txOrigin - ).rrevert(); + if (order.txOrigin != tx.origin && !stor.originRegistry[order.txOrigin][tx.origin]) { + LibNativeOrdersRichErrors + .OrderNotFillableByOriginError(orderInfo.orderHash, tx.origin, order.txOrigin) + .rrevert(); } // Maker signature must be valid for the order. address makerSigner = LibSignature.getSignerOfHash(orderInfo.orderHash, makerSignature); - if ( - makerSigner != order.maker && - !stor.orderSignerRegistry[order.maker][makerSigner] - ) { - LibNativeOrdersRichErrors.OrderNotSignedByMakerError( - orderInfo.orderHash, - makerSigner, - order.maker - ).rrevert(); + if (makerSigner != order.maker && !stor.orderSignerRegistry[order.maker][makerSigner]) { + LibNativeOrdersRichErrors + .OrderNotSignedByMakerError(orderInfo.orderHash, makerSigner, order.maker) + .rrevert(); } } @@ -490,17 +379,13 @@ contract OtcOrdersFeature is uint128 takerTokenFillAmount, address payer, address recipient - ) - private - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + ) private returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { { // Unpack nonce fields uint64 nonceBucket = uint64(order.expiryAndNonce >> 128); uint128 nonce = uint128(order.expiryAndNonce); // Update tx origin nonce for the order - LibOtcOrdersStorage.getStorage().txOriginNonces - [order.txOrigin][nonceBucket] = nonce; + LibOtcOrdersStorage.getStorage().txOriginNonces[order.txOrigin][nonceBucket] = nonce; } if (takerTokenFillAmount == order.takerAmount) { @@ -508,18 +393,17 @@ contract OtcOrdersFeature is makerTokenFilledAmount = order.makerAmount; } else { // Clamp the taker token fill amount to the fillable amount. - takerTokenFilledAmount = LibSafeMathV06.min128( - takerTokenFillAmount, - order.takerAmount - ); + takerTokenFilledAmount = LibSafeMathV06.min128(takerTokenFillAmount, order.takerAmount); // Compute the maker token amount. // This should never overflow because the values are all clamped to // (2^128-1). - makerTokenFilledAmount = uint128(LibMathV06.getPartialAmountFloor( - uint256(takerTokenFilledAmount), - uint256(order.takerAmount), - uint256(order.makerAmount) - )); + makerTokenFilledAmount = uint128( + LibMathV06.getPartialAmountFloor( + uint256(takerTokenFilledAmount), + uint256(order.takerAmount), + uint256(order.makerAmount) + ) + ); } if (payer == address(this)) { @@ -528,28 +412,14 @@ contract OtcOrdersFeature is payable(order.maker).transfer(takerTokenFilledAmount); } else { // Transfer this -> maker. - _transferERC20Tokens( - order.takerToken, - order.maker, - takerTokenFilledAmount - ); + _transferERC20Tokens(order.takerToken, order.maker, takerTokenFilledAmount); } } else { // Transfer taker -> maker - _transferERC20TokensFrom( - order.takerToken, - payer, - order.maker, - takerTokenFilledAmount - ); + _transferERC20TokensFrom(order.takerToken, payer, order.maker, takerTokenFilledAmount); } // Transfer maker -> recipient. - _transferERC20TokensFrom( - order.makerToken, - order.maker, - recipient, - makerTokenFilledAmount - ); + _transferERC20TokensFrom(order.makerToken, order.maker, recipient, makerTokenFilledAmount); } /// @dev Get the order info for an OTC order. @@ -557,15 +427,14 @@ contract OtcOrdersFeature is /// @return orderInfo Info about the order. function getOtcOrderInfo(LibNativeOrder.OtcOrder memory order) public - override view + override returns (LibNativeOrder.OtcOrderInfo memory orderInfo) { // compute order hash. orderInfo.orderHash = getOtcOrderHash(order); - LibOtcOrdersStorage.Storage storage stor = - LibOtcOrdersStorage.getStorage(); + LibOtcOrdersStorage.Storage storage stor = LibOtcOrdersStorage.getStorage(); // Unpack expiry and nonce fields uint64 expiry = uint64(order.expiryAndNonce >> 192); @@ -573,9 +442,7 @@ contract OtcOrdersFeature is uint128 nonce = uint128(order.expiryAndNonce); // check tx origin nonce - uint128 lastNonce = stor.txOriginNonces - [order.txOrigin] - [nonceBucket]; + uint128 lastNonce = stor.txOriginNonces[order.txOrigin][nonceBucket]; if (nonce <= lastNonce) { orderInfo.status = LibNativeOrder.OrderStatus.INVALID; return orderInfo; @@ -594,15 +461,8 @@ contract OtcOrdersFeature is /// @dev Get the canonical hash of an OTC order. /// @param order The OTC order. /// @return orderHash The order hash. - function getOtcOrderHash(LibNativeOrder.OtcOrder memory order) - public - override - view - returns (bytes32 orderHash) - { - return _getEIP712Hash( - LibNativeOrder.getOtcOrderStructHash(order) - ); + function getOtcOrderHash(LibNativeOrder.OtcOrder memory order) public view override returns (bytes32 orderHash) { + return _getEIP712Hash(LibNativeOrder.getOtcOrderStructHash(order)); } /// @dev Get the last nonce used for a particular @@ -612,14 +472,11 @@ contract OtcOrdersFeature is /// @return lastNonce The last nonce value used. function lastOtcTxOriginNonce(address txOrigin, uint64 nonceBucket) public - override view + override returns (uint128 lastNonce) { - LibOtcOrdersStorage.Storage storage stor = - LibOtcOrdersStorage.getStorage(); - return stor.txOriginNonces - [txOrigin] - [nonceBucket]; + LibOtcOrdersStorage.Storage storage stor = LibOtcOrdersStorage.getStorage(); + return stor.txOriginNonces[txOrigin][nonceBucket]; } } diff --git a/contracts/zero-ex/contracts/src/features/OwnableFeature.sol b/contracts/zero-ex/contracts/src/features/OwnableFeature.sol index 563dd15596..8f646a577c 100644 --- a/contracts/zero-ex/contracts/src/features/OwnableFeature.sol +++ b/contracts/zero-ex/contracts/src/features/OwnableFeature.sol @@ -30,14 +30,8 @@ import "./interfaces/IFeature.sol"; import "./interfaces/IOwnableFeature.sol"; import "./SimpleFunctionRegistryFeature.sol"; - /// @dev Owner management features. -contract OwnableFeature is - IFeature, - IOwnableFeature, - FixinCommon -{ - +contract OwnableFeature is IFeature, IOwnableFeature, FixinCommon { /// @dev Name of this feature. string public constant override FEATURE_NAME = "Ownable"; /// @dev Version of this feature. @@ -64,11 +58,7 @@ contract OwnableFeature is /// @dev Change the owner of this contract. /// Only directly callable by the owner. /// @param newOwner New owner address. - function transferOwnership(address newOwner) - external - override - onlyOwner - { + function transferOwnership(address newOwner) external override onlyOwner { LibOwnableStorage.Storage storage proxyStor = LibOwnableStorage.getStorage(); if (newOwner == address(0)) { @@ -87,11 +77,11 @@ contract OwnableFeature is /// @param target The migrator contract address. /// @param data The call data. /// @param newOwner The address of the new owner. - function migrate(address target, bytes calldata data, address newOwner) - external - override - onlyOwner - { + function migrate( + address target, + bytes calldata data, + address newOwner + ) external override onlyOwner { if (newOwner == address(0)) { LibOwnableRichErrors.TransferOwnerToZeroError().rrevert(); } @@ -111,7 +101,7 @@ contract OwnableFeature is /// @dev Get the owner of this contract. /// @return owner_ The owner of this contract. - function owner() external override view returns (address owner_) { + function owner() external view override returns (address owner_) { return LibOwnableStorage.getStorage().owner; } } diff --git a/contracts/zero-ex/contracts/src/features/PancakeSwapFeature.sol b/contracts/zero-ex/contracts/src/features/PancakeSwapFeature.sol index 85a1b108d6..7a3bd801ba 100644 --- a/contracts/zero-ex/contracts/src/features/PancakeSwapFeature.sol +++ b/contracts/zero-ex/contracts/src/features/PancakeSwapFeature.sol @@ -27,13 +27,8 @@ import "../fixins/FixinCommon.sol"; import "./interfaces/IFeature.sol"; import "./interfaces/IPancakeSwapFeature.sol"; - /// @dev VIP pancake fill functions. -contract PancakeSwapFeature is - IFeature, - IPancakeSwapFeature, - FixinCommon -{ +contract PancakeSwapFeature is IFeature, IPancakeSwapFeature, FixinCommon { /// @dev Name of this feature. string public constant override FEATURE_NAME = "PancakeSwapFeature"; /// @dev Version of this feature. @@ -42,64 +37,83 @@ contract PancakeSwapFeature is IEtherTokenV06 private immutable WBNB; // 0xFF + address of the PancakeSwap factory contract. - uint256 constant private FF_PANCAKESWAP_FACTORY = 0xffbcfccbde45ce874adcb698cc183debcf179528120000000000000000000000; + uint256 private constant FF_PANCAKESWAP_FACTORY = + 0xffbcfccbde45ce874adcb698cc183debcf179528120000000000000000000000; // 0xFF + address of the PancakeSwapV2 factory contract. - uint256 constant private FF_PANCAKESWAPV2_FACTORY = 0xffca143ce32fe78f1f7019d7d551a6402fc5350c730000000000000000000000; + uint256 private constant FF_PANCAKESWAPV2_FACTORY = + 0xffca143ce32fe78f1f7019d7d551a6402fc5350c730000000000000000000000; // 0xFF + address of the BakerySwap factory contract. - uint256 constant private FF_BAKERYSWAP_FACTORY = 0xff01bf7c66c6bd861915cdaae475042d3c4bae16a70000000000000000000000; + uint256 private constant FF_BAKERYSWAP_FACTORY = 0xff01bf7c66c6bd861915cdaae475042d3c4bae16a70000000000000000000000; // 0xFF + address of the SushiSwap factory contract. - uint256 constant private FF_SUSHISWAP_FACTORY = 0xffc35DADB65012eC5796536bD9864eD8773aBc74C40000000000000000000000; + uint256 private constant FF_SUSHISWAP_FACTORY = 0xffc35DADB65012eC5796536bD9864eD8773aBc74C40000000000000000000000; // 0xFF + address of the ApeSwap factory contract. - uint256 constant private FF_APESWAP_FACTORY = 0xff0841bd0b734e4f5853f0dd8d7ea041c241fb0da60000000000000000000000; + uint256 private constant FF_APESWAP_FACTORY = 0xff0841bd0b734e4f5853f0dd8d7ea041c241fb0da60000000000000000000000; // 0xFF + address of the CafeSwap factory contract. - uint256 constant private FF_CAFESWAP_FACTORY = 0xff3e708fdbe3ada63fc94f8f61811196f1302137ad0000000000000000000000; + uint256 private constant FF_CAFESWAP_FACTORY = 0xff3e708fdbe3ada63fc94f8f61811196f1302137ad0000000000000000000000; // 0xFF + address of the CheeseSwap factory contract. - uint256 constant private FF_CHEESESWAP_FACTORY = 0xffdd538e4fd1b69b7863e1f741213276a6cf1efb3b0000000000000000000000; + uint256 private constant FF_CHEESESWAP_FACTORY = 0xffdd538e4fd1b69b7863e1f741213276a6cf1efb3b0000000000000000000000; // 0xFF + address of the JulSwap factory contract. - uint256 constant private FF_JULSWAP_FACTORY = 0xff553990f2cba90272390f62c5bdb1681ffc8996750000000000000000000000; + uint256 private constant FF_JULSWAP_FACTORY = 0xff553990f2cba90272390f62c5bdb1681ffc8996750000000000000000000000; // Init code hash of the PancakeSwap pair contract. - uint256 constant private PANCAKESWAP_PAIR_INIT_CODE_HASH = 0xd0d4c4cd0848c93cb4fd1f498d7013ee6bfb25783ea21593d5834f5d250ece66; + uint256 private constant PANCAKESWAP_PAIR_INIT_CODE_HASH = + 0xd0d4c4cd0848c93cb4fd1f498d7013ee6bfb25783ea21593d5834f5d250ece66; // Init code hash of the PancakeSwapV2 pair contract. - uint256 constant private PANCAKESWAPV2_PAIR_INIT_CODE_HASH = 0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5; + uint256 private constant PANCAKESWAPV2_PAIR_INIT_CODE_HASH = + 0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5; // Init code hash of the BakerySwap pair contract. - uint256 constant private BAKERYSWAP_PAIR_INIT_CODE_HASH = 0xe2e87433120e32c4738a7d8f3271f3d872cbe16241d67537139158d90bac61d3; + uint256 private constant BAKERYSWAP_PAIR_INIT_CODE_HASH = + 0xe2e87433120e32c4738a7d8f3271f3d872cbe16241d67537139158d90bac61d3; // Init code hash of the SushiSwap pair contract. - uint256 constant private SUSHISWAP_PAIR_INIT_CODE_HASH = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; + uint256 private constant SUSHISWAP_PAIR_INIT_CODE_HASH = + 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; // Init code hash of the ApeSwap pair contract. - uint256 constant private APESWAP_PAIR_INIT_CODE_HASH = 0xf4ccce374816856d11f00e4069e7cada164065686fbef53c6167a63ec2fd8c5b; + uint256 private constant APESWAP_PAIR_INIT_CODE_HASH = + 0xf4ccce374816856d11f00e4069e7cada164065686fbef53c6167a63ec2fd8c5b; // Init code hash of the CafeSwap pair contract. - uint256 constant private CAFESWAP_PAIR_INIT_CODE_HASH = 0x90bcdb5d0bf0e8db3852b0b7d7e05cc8f7c6eb6d511213c5ba02d1d1dbeda8d3; + uint256 private constant CAFESWAP_PAIR_INIT_CODE_HASH = + 0x90bcdb5d0bf0e8db3852b0b7d7e05cc8f7c6eb6d511213c5ba02d1d1dbeda8d3; // Init code hash of the CheeseSwap pair contract. - uint256 constant private CHEESESWAP_PAIR_INIT_CODE_HASH = 0xf52c5189a89e7ca2ef4f19f2798e3900fba7a316de7cef6c5a9446621ba86286; + uint256 private constant CHEESESWAP_PAIR_INIT_CODE_HASH = + 0xf52c5189a89e7ca2ef4f19f2798e3900fba7a316de7cef6c5a9446621ba86286; // Init code hash of the JulSwap pair contract. - uint256 constant private JULSWAP_PAIR_INIT_CODE_HASH = 0xb1e98e21a5335633815a8cfb3b580071c2e4561c50afd57a8746def9ed890b18; + uint256 private constant JULSWAP_PAIR_INIT_CODE_HASH = + 0xb1e98e21a5335633815a8cfb3b580071c2e4561c50afd57a8746def9ed890b18; // Mask of the lower 20 bytes of a bytes32. - uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; + uint256 private constant ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; // BNB pseudo-token address. - uint256 constant private ETH_TOKEN_ADDRESS_32 = 0x000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee; + uint256 private constant ETH_TOKEN_ADDRESS_32 = 0x000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee; // Maximum token quantity that can be swapped against the PancakeSwapPair contract. - uint256 constant private MAX_SWAP_AMOUNT = 2**112; + uint256 private constant MAX_SWAP_AMOUNT = 2**112; // bytes4(keccak256("executeCall(address,bytes)")) - uint256 constant private ALLOWANCE_TARGET_EXECUTE_CALL_SELECTOR_32 = 0xbca8c7b500000000000000000000000000000000000000000000000000000000; + uint256 private constant ALLOWANCE_TARGET_EXECUTE_CALL_SELECTOR_32 = + 0xbca8c7b500000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("getReserves()")) - uint256 constant private PANCAKESWAP_PAIR_RESERVES_CALL_SELECTOR_32 = 0x0902f1ac00000000000000000000000000000000000000000000000000000000; + uint256 private constant PANCAKESWAP_PAIR_RESERVES_CALL_SELECTOR_32 = + 0x0902f1ac00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("swap(uint256,uint256,address,bytes)")) - uint256 constant private PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32 = 0x022c0d9f00000000000000000000000000000000000000000000000000000000; + uint256 private constant PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32 = + 0x022c0d9f00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("swap(uint256,uint256,address)")) - uint256 constant private BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32 = 0x6d9a640a00000000000000000000000000000000000000000000000000000000; + uint256 private constant BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32 = + 0x6d9a640a00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("transferFrom(address,address,uint256)")) - uint256 constant private TRANSFER_FROM_CALL_SELECTOR_32 = 0x23b872dd00000000000000000000000000000000000000000000000000000000; + uint256 private constant TRANSFER_FROM_CALL_SELECTOR_32 = + 0x23b872dd00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("allowance(address,address)")) - uint256 constant private ALLOWANCE_CALL_SELECTOR_32 = 0xdd62ed3e00000000000000000000000000000000000000000000000000000000; + uint256 private constant ALLOWANCE_CALL_SELECTOR_32 = + 0xdd62ed3e00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("withdraw(uint256)")) - uint256 constant private WETH_WITHDRAW_CALL_SELECTOR_32 = 0x2e1a7d4d00000000000000000000000000000000000000000000000000000000; + uint256 private constant WETH_WITHDRAW_CALL_SELECTOR_32 = + 0x2e1a7d4d00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("deposit()")) - uint256 constant private WETH_DEPOSIT_CALL_SELECTOR_32 = 0xd0e30db000000000000000000000000000000000000000000000000000000000; + uint256 private constant WETH_DEPOSIT_CALL_SELECTOR_32 = + 0xd0e30db000000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("transfer(address,uint256)")) - uint256 constant private ERC20_TRANSFER_CALL_SELECTOR_32 = 0xa9059cbb00000000000000000000000000000000000000000000000000000000; + uint256 private constant ERC20_TRANSFER_CALL_SELECTOR_32 = + 0xa9059cbb00000000000000000000000000000000000000000000000000000000; /// @dev Construct this contract. /// @param wbnb The WBNB contract. @@ -110,10 +124,7 @@ contract PancakeSwapFeature is /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. - function migrate() - external - returns (bytes4 success) - { + function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.sellToPancakeSwap.selector); return LibMigrate.MIGRATE_SUCCESS; } @@ -129,12 +140,7 @@ contract PancakeSwapFeature is uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork - ) - external - payable - override - returns (uint256 buyAmount) - { + ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "PancakeSwapFeature/InvalidTokensLength"); { // Load immutables onto the stack. @@ -160,7 +166,11 @@ contract PancakeSwapFeature is let buyToken let nextPair := 0 - for {let i := 0} lt(i, numPairs) {i := add(i, 1)} { + for { + let i := 0 + } lt(i, numPairs) { + i := add(i, 1) + } { // sellToken = tokens[i] let sellToken := loadTokenAddress(i) // buyToken = tokens[i+1] @@ -179,35 +189,36 @@ contract PancakeSwapFeature is if iszero(i) { // This is the first token in the path. switch eq(sellToken, ETH_TOKEN_ADDRESS_32) - case 0 { // Not selling BNB. Selling an ERC20 instead. - // Make sure BNB was not attached to the call. - if gt(callvalue(), 0) { - revert(0, 0) - } - // For the first pair we need to transfer sellTokens into the - // pair contract. - moveTakerTokensTo(sellToken, pair, sellAmount) + case 0 { + // Not selling BNB. Selling an ERC20 instead. + // Make sure BNB was not attached to the call. + if gt(callvalue(), 0) { + revert(0, 0) } - default { - // If selling BNB, we need to wrap it to WBNB and transfer to the - // pair contract. - if iszero(eq(callvalue(), sellAmount)) { - revert(0, 0) - } - sellToken := mload(0xA40)// Re-assign to WBNB - // Call `WBNB.deposit{value: sellAmount}()` - mstore(0xB00, WETH_DEPOSIT_CALL_SELECTOR_32) - if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { - bubbleRevert() - } - // Call `WBNB.transfer(pair, sellAmount)` - mstore(0xB00, ERC20_TRANSFER_CALL_SELECTOR_32) - mstore(0xB04, pair) - mstore(0xB24, sellAmount) - if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { - bubbleRevert() - } + // For the first pair we need to transfer sellTokens into the + // pair contract. + moveTakerTokensTo(sellToken, pair, sellAmount) + } + default { + // If selling BNB, we need to wrap it to WBNB and transfer to the + // pair contract. + if iszero(eq(callvalue(), sellAmount)) { + revert(0, 0) } + sellToken := mload(0xA40) // Re-assign to WBNB + // Call `WBNB.deposit{value: sellAmount}()` + mstore(0xB00, WETH_DEPOSIT_CALL_SELECTOR_32) + if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { + bubbleRevert() + } + // Call `WBNB.transfer(pair, sellAmount)` + mstore(0xB00, ERC20_TRANSFER_CALL_SELECTOR_32) + mstore(0xB04, pair) + mstore(0xB24, sellAmount) + if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { + bubbleRevert() + } + } // No need to check results, if deposit/transfers failed the PancakeSwapPair will // reject our trade (or it may succeed if somehow the reserve was out of sync) // this is fine for the taker. @@ -231,15 +242,15 @@ contract PancakeSwapFeature is let sellReserve let buyReserve switch iszero(pairOrder) - case 0 { - // Transpose if pair order is different. - sellReserve := mload(0xC00) - buyReserve := mload(0xC20) - } - default { - sellReserve := mload(0xC20) - buyReserve := mload(0xC00) - } + case 0 { + // Transpose if pair order is different. + sellReserve := mload(0xC00) + buyReserve := mload(0xC20) + } + default { + sellReserve := mload(0xC20) + buyReserve := mload(0xC00) + } // Ensure that the sellAmount is < 2¹¹². if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) @@ -248,53 +259,47 @@ contract PancakeSwapFeature is // buyAmount = (pairSellAmount * 997 * buyReserve) / // (pairSellAmount * 997 + sellReserve * 1000); let sellAmountWithFee := mul(pairSellAmount, 997) - buyAmount := div( - mul(sellAmountWithFee, buyReserve), - add(sellAmountWithFee, mul(sellReserve, 1000)) - ) + buyAmount := div(mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000))) } let receiver // Is this the last pair contract? switch eq(add(i, 1), numPairs) + case 0 { + // Not the last pair contract, so forward bought tokens to + // the next pair contract. + nextPair := computePairAddress(buyToken, loadTokenAddress(add(i, 2))) + receiver := nextPair + } + default { + // The last pair contract. + // Forward directly to taker UNLESS they want BNB back. + switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { - // Not the last pair contract, so forward bought tokens to - // the next pair contract. - nextPair := computePairAddress( - buyToken, - loadTokenAddress(add(i, 2)) - ) - receiver := nextPair + receiver := caller() } default { - // The last pair contract. - // Forward directly to taker UNLESS they want BNB back. - switch eq(buyToken, ETH_TOKEN_ADDRESS_32) - case 0 { - receiver := caller() - } - default { - receiver := address() - } + receiver := address() } + } // Call pair.swap() switch mload(0xA20) // fork - case 2 { - mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) - } - default { - mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) - } + case 2 { + mstore(0xB00, BAKERYSWAP_PAIR_SWAP_CALL_SELECTOR_32) + } + default { + mstore(0xB00, PANCAKESWAP_PAIR_SWAP_CALL_SELECTOR_32) + } switch pairOrder - case 0 { - mstore(0xB04, buyAmount) - mstore(0xB24, 0) - } - default { - mstore(0xB04, 0) - mstore(0xB24, buyAmount) - } + case 0 { + mstore(0xB04, buyAmount) + mstore(0xB24, 0) + } + default { + mstore(0xB04, 0) + mstore(0xB24, buyAmount) + } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) @@ -357,57 +362,57 @@ contract PancakeSwapFeature is // them as two 20-byte values in a 40-byte chunk of memory // starting at 0xB0C. switch lt(tokenA, tokenB) - case 0 { - mstore(0xB14, tokenA) - mstore(0xB00, tokenB) - } - default { - mstore(0xB14, tokenB) - mstore(0xB00, tokenA) - } + case 0 { + mstore(0xB14, tokenA) + mstore(0xB00, tokenB) + } + default { + mstore(0xB14, tokenB) + mstore(0xB00, tokenA) + } let salt := keccak256(0xB0C, 0x28) // Compute the pair address by hashing all the components together. switch mload(0xA20) // fork - case 0 { - mstore(0xB00, FF_PANCAKESWAP_FACTORY) - mstore(0xB15, salt) - mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) - } - case 1 { - mstore(0xB00, FF_PANCAKESWAPV2_FACTORY) - mstore(0xB15, salt) - mstore(0xB35, PANCAKESWAPV2_PAIR_INIT_CODE_HASH) - } - case 2 { - mstore(0xB00, FF_BAKERYSWAP_FACTORY) - mstore(0xB15, salt) - mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) - } - case 3 { - mstore(0xB00, FF_SUSHISWAP_FACTORY) - mstore(0xB15, salt) - mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) - } - case 4 { - mstore(0xB00, FF_APESWAP_FACTORY) - mstore(0xB15, salt) - mstore(0xB35, APESWAP_PAIR_INIT_CODE_HASH) - } - case 5 { - mstore(0xB00, FF_CAFESWAP_FACTORY) - mstore(0xB15, salt) - mstore(0xB35, CAFESWAP_PAIR_INIT_CODE_HASH) - } - case 6 { - mstore(0xB00, FF_CHEESESWAP_FACTORY) - mstore(0xB15, salt) - mstore(0xB35, CHEESESWAP_PAIR_INIT_CODE_HASH) - } - default { - mstore(0xB00, FF_JULSWAP_FACTORY) - mstore(0xB15, salt) - mstore(0xB35, JULSWAP_PAIR_INIT_CODE_HASH) - } + case 0 { + mstore(0xB00, FF_PANCAKESWAP_FACTORY) + mstore(0xB15, salt) + mstore(0xB35, PANCAKESWAP_PAIR_INIT_CODE_HASH) + } + case 1 { + mstore(0xB00, FF_PANCAKESWAPV2_FACTORY) + mstore(0xB15, salt) + mstore(0xB35, PANCAKESWAPV2_PAIR_INIT_CODE_HASH) + } + case 2 { + mstore(0xB00, FF_BAKERYSWAP_FACTORY) + mstore(0xB15, salt) + mstore(0xB35, BAKERYSWAP_PAIR_INIT_CODE_HASH) + } + case 3 { + mstore(0xB00, FF_SUSHISWAP_FACTORY) + mstore(0xB15, salt) + mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) + } + case 4 { + mstore(0xB00, FF_APESWAP_FACTORY) + mstore(0xB15, salt) + mstore(0xB35, APESWAP_PAIR_INIT_CODE_HASH) + } + case 5 { + mstore(0xB00, FF_CAFESWAP_FACTORY) + mstore(0xB15, salt) + mstore(0xB35, CAFESWAP_PAIR_INIT_CODE_HASH) + } + case 6 { + mstore(0xB00, FF_CHEESESWAP_FACTORY) + mstore(0xB15, salt) + mstore(0xB35, CHEESESWAP_PAIR_INIT_CODE_HASH) + } + default { + mstore(0xB00, FF_JULSWAP_FACTORY) + mstore(0xB15, salt) + mstore(0xB35, JULSWAP_PAIR_INIT_CODE_HASH) + } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } @@ -446,12 +451,12 @@ contract PancakeSwapFeature is // success, or at least 32 bytes that starts with // a 32-byte boolean true. success := and( - success, // call itself succeeded + success, // call itself succeeded or( - iszero(rdsize), // no return data, or + iszero(rdsize), // no return data, or and( - iszero(lt(rdsize, 32)), // at least 32 bytes - eq(mload(0xC00), 1) // starts with uint256(1) + iszero(lt(rdsize, 32)), // at least 32 bytes + eq(mload(0xC00), 1) // starts with uint256(1) ) ) ) diff --git a/contracts/zero-ex/contracts/src/features/SimpleFunctionRegistryFeature.sol b/contracts/zero-ex/contracts/src/features/SimpleFunctionRegistryFeature.sol index fa83326055..8f75581ae6 100644 --- a/contracts/zero-ex/contracts/src/features/SimpleFunctionRegistryFeature.sol +++ b/contracts/zero-ex/contracts/src/features/SimpleFunctionRegistryFeature.sol @@ -29,13 +29,8 @@ import "../migrations/LibBootstrap.sol"; import "./interfaces/IFeature.sol"; import "./interfaces/ISimpleFunctionRegistryFeature.sol"; - /// @dev Basic registry management features. -contract SimpleFunctionRegistryFeature is - IFeature, - ISimpleFunctionRegistryFeature, - FixinCommon -{ +contract SimpleFunctionRegistryFeature is IFeature, ISimpleFunctionRegistryFeature, FixinCommon { /// @dev Name of this feature. string public constant override FEATURE_NAME = "SimpleFunctionRegistry"; /// @dev Version of this feature. @@ -45,10 +40,7 @@ contract SimpleFunctionRegistryFeature is /// @dev Initializes this feature, registering its own functions. /// @return success Magic bytes if successful. - function bootstrap() - external - returns (bytes4 success) - { + function bootstrap() external returns (bytes4 success) { // Register the registration functions (inception vibes). _extend(this.extend.selector, _implementation); _extend(this._extendSelf.selector, _implementation); @@ -64,11 +56,7 @@ contract SimpleFunctionRegistryFeature is /// Only directly callable by an authority. /// @param selector The function selector. /// @param targetImpl The address of an older implementation of the function. - function rollback(bytes4 selector, address targetImpl) - external - override - onlyOwner - { + function rollback(bytes4 selector, address targetImpl) external override onlyOwner { ( LibSimpleFunctionRegistryStorage.Storage storage stor, LibProxyStorage.Storage storage proxyStor @@ -90,10 +78,7 @@ contract SimpleFunctionRegistryFeature is } } if (i == 0) { - LibSimpleFunctionRegistryRichErrors.NotInRollbackHistoryError( - selector, - targetImpl - ).rrevert(); + LibSimpleFunctionRegistryRichErrors.NotInRollbackHistoryError(selector, targetImpl).rrevert(); } proxyStor.impls[selector] = targetImpl; emit ProxyFunctionUpdated(selector, currentImpl, targetImpl); @@ -103,11 +88,7 @@ contract SimpleFunctionRegistryFeature is /// Only directly callable by an authority. /// @param selector The function selector. /// @param impl The implementation contract for the function. - function extend(bytes4 selector, address impl) - external - override - onlyOwner - { + function extend(bytes4 selector, address impl) external override onlyOwner { _extend(selector, impl); } @@ -118,10 +99,7 @@ contract SimpleFunctionRegistryFeature is /// complete. /// @param selector The function selector. /// @param impl The implementation contract for the function. - function _extendSelf(bytes4 selector, address impl) - external - onlySelf - { + function _extendSelf(bytes4 selector, address impl) external onlySelf { _extend(selector, impl); } @@ -129,12 +107,7 @@ contract SimpleFunctionRegistryFeature is /// @param selector The function selector. /// @return rollbackLength The number of items in the rollback history for /// the function. - function getRollbackLength(bytes4 selector) - external - override - view - returns (uint256 rollbackLength) - { + function getRollbackLength(bytes4 selector) external view override returns (uint256 rollbackLength) { return LibSimpleFunctionRegistryStorage.getStorage().implHistory[selector].length; } @@ -143,21 +116,14 @@ contract SimpleFunctionRegistryFeature is /// @param idx The index in the rollback history. /// @return impl An implementation address for the function at /// index `idx`. - function getRollbackEntryAtIndex(bytes4 selector, uint256 idx) - external - override - view - returns (address impl) - { + function getRollbackEntryAtIndex(bytes4 selector, uint256 idx) external view override returns (address impl) { return LibSimpleFunctionRegistryStorage.getStorage().implHistory[selector][idx]; } /// @dev Register or replace a function. /// @param selector The function selector. /// @param impl The implementation contract for the function. - function _extend(bytes4 selector, address impl) - private - { + function _extend(bytes4 selector, address impl) private { ( LibSimpleFunctionRegistryStorage.Storage storage stor, LibProxyStorage.Storage storage proxyStor @@ -176,14 +142,8 @@ contract SimpleFunctionRegistryFeature is function _getStorages() private pure - returns ( - LibSimpleFunctionRegistryStorage.Storage storage stor, - LibProxyStorage.Storage storage proxyStor - ) + returns (LibSimpleFunctionRegistryStorage.Storage storage stor, LibProxyStorage.Storage storage proxyStor) { - return ( - LibSimpleFunctionRegistryStorage.getStorage(), - LibProxyStorage.getStorage() - ); + return (LibSimpleFunctionRegistryStorage.getStorage(), LibProxyStorage.getStorage()); } } diff --git a/contracts/zero-ex/contracts/src/features/TransformERC20Feature.sol b/contracts/zero-ex/contracts/src/features/TransformERC20Feature.sol index 85d12b4cff..cc9eaf2a32 100644 --- a/contracts/zero-ex/contracts/src/features/TransformERC20Feature.sol +++ b/contracts/zero-ex/contracts/src/features/TransformERC20Feature.sol @@ -37,14 +37,8 @@ import "../transformers/LibERC20Transformer.sol"; import "./interfaces/IFeature.sol"; import "./interfaces/ITransformERC20Feature.sol"; - /// @dev Feature to composably transform between ERC20 tokens. -contract TransformERC20Feature is - IFeature, - ITransformERC20Feature, - FixinCommon, - FixinTokenSpender -{ +contract TransformERC20Feature is IFeature, ITransformERC20Feature, FixinCommon, FixinTokenSpender { using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; @@ -65,10 +59,7 @@ contract TransformERC20Feature is /// Should be delegatecalled by `Migrate.migrate()`. /// @param transformerDeployer The trusted deployer for transformers. /// @return success `LibMigrate.SUCCESS` on success. - function migrate(address transformerDeployer) - external - returns (bytes4 success) - { + function migrate(address transformerDeployer) external returns (bytes4 success) { _registerFeatureFunction(this.getTransformerDeployer.selector); _registerFeatureFunction(this.createTransformWallet.selector); _registerFeatureFunction(this.getTransformWallet.selector); @@ -88,11 +79,7 @@ contract TransformERC20Feature is /// @dev Replace the allowed deployer for transformers. /// Only callable by the owner. /// @param transformerDeployer The address of the trusted deployer for transformers. - function setTransformerDeployer(address transformerDeployer) - external - override - onlyOwner - { + function setTransformerDeployer(address transformerDeployer) external override onlyOwner { LibTransformERC20Storage.getStorage().transformerDeployer = transformerDeployer; emit TransformerDeployerUpdated(transformerDeployer); } @@ -100,34 +87,20 @@ contract TransformERC20Feature is /// @dev Replace the optional signer for `transformERC20()` calldata. /// Only callable by the owner. /// @param quoteSigner The address of the new calldata signer. - function setQuoteSigner(address quoteSigner) - external - override - onlyOwner - { + function setQuoteSigner(address quoteSigner) external override onlyOwner { LibTransformERC20Storage.getStorage().quoteSigner = quoteSigner; emit QuoteSignerUpdated(quoteSigner); } /// @dev Return the allowed deployer for transformers. /// @return deployer The transform deployer address. - function getTransformerDeployer() - public - override - view - returns (address deployer) - { + function getTransformerDeployer() public view override returns (address deployer) { return LibTransformERC20Storage.getStorage().transformerDeployer; } /// @dev Return the optional signer for `transformERC20()` calldata. /// @return signer The signer address. - function getQuoteSigner() - public - override - view - returns (address signer) - { + function getQuoteSigner() public view override returns (address signer) { return LibTransformERC20Storage.getStorage().quoteSigner; } @@ -135,12 +108,7 @@ contract TransformERC20Feature is /// Useful if we somehow break the current wallet instance. /// Only callable by the owner. /// @return wallet The new wallet instance. - function createTransformWallet() - public - override - onlyOwner - returns (IFlashWallet wallet) - { + function createTransformWallet() public override onlyOwner returns (IFlashWallet wallet) { wallet = new FlashWallet(); LibTransformERC20Storage.getStorage().wallet = wallet; } @@ -166,24 +134,20 @@ contract TransformERC20Feature is uint256 inputTokenAmount, uint256 minOutputTokenAmount, Transformation[] memory transformations - ) - public - override - payable - returns (uint256 outputTokenAmount) - { - return _transformERC20Private( - TransformERC20Args({ - taker: msg.sender, - inputToken: inputToken, - outputToken: outputToken, - inputTokenAmount: inputTokenAmount, - minOutputTokenAmount: minOutputTokenAmount, - transformations: transformations, - useSelfBalance: false, - recipient: msg.sender - }) - ); + ) public payable override returns (uint256 outputTokenAmount) { + return + _transformERC20Private( + TransformERC20Args({ + taker: msg.sender, + inputToken: inputToken, + outputToken: outputToken, + inputTokenAmount: inputTokenAmount, + minOutputTokenAmount: minOutputTokenAmount, + transformations: transformations, + useSelfBalance: false, + recipient: msg.sender + }) + ); } /// @dev Internal version of `transformERC20()`. Only callable from within. @@ -191,9 +155,9 @@ contract TransformERC20Feature is /// @return outputTokenAmount The amount of `outputToken` received by the taker. function _transformERC20(TransformERC20Args memory args) public + payable virtual override - payable onlySelf returns (uint256 outputTokenAmount) { @@ -203,10 +167,7 @@ contract TransformERC20Feature is /// @dev Private version of `transformERC20()`. /// @param args A `TransformERC20Args` struct. /// @return outputTokenAmount The amount of `outputToken` received by the taker. - function _transformERC20Private(TransformERC20Args memory args) - private - returns (uint256 outputTokenAmount) - { + function _transformERC20Private(TransformERC20Args memory args) private returns (uint256 outputTokenAmount) { // If the input token amount is -1 and we are not selling ETH, // transform the taker's entire spendable balance. if (!args.useSelfBalance && args.inputTokenAmount == uint256(-1)) { @@ -215,10 +176,7 @@ contract TransformERC20Feature is // input token amount to the value attached to the call. args.inputTokenAmount = msg.value; } else { - args.inputTokenAmount = _getSpendableERC20BalanceOf( - args.inputToken, - args.taker - ); + args.inputTokenAmount = _getSpendableERC20BalanceOf(args.inputToken, args.taker); } } @@ -227,8 +185,10 @@ contract TransformERC20Feature is state.transformerDeployer = getTransformerDeployer(); // Remember the initial output token balance of the recipient. - state.recipientOutputTokenBalanceBefore = - LibERC20Transformer.getTokenBalanceOf(args.outputToken, args.recipient); + state.recipientOutputTokenBalanceBefore = LibERC20Transformer.getTokenBalanceOf( + args.outputToken, + args.recipient + ); // Pull input tokens from the taker to the wallet and transfer attached ETH. _transferInputTokensAndAttachedEth(args, address(state.wallet)); @@ -244,21 +204,21 @@ contract TransformERC20Feature is ); } // Transfer output tokens from wallet to recipient - outputTokenAmount = _executeOutputTokenTransfer( - args.outputToken, - state.wallet, - args.recipient - ); + outputTokenAmount = _executeOutputTokenTransfer(args.outputToken, state.wallet, args.recipient); } // Compute how much output token has been transferred to the recipient. - state.recipientOutputTokenBalanceAfter = - LibERC20Transformer.getTokenBalanceOf(args.outputToken, args.recipient); + state.recipientOutputTokenBalanceAfter = LibERC20Transformer.getTokenBalanceOf( + args.outputToken, + args.recipient + ); if (state.recipientOutputTokenBalanceAfter < state.recipientOutputTokenBalanceBefore) { - LibTransformERC20RichErrors.NegativeTransformERC20OutputError( - address(args.outputToken), - state.recipientOutputTokenBalanceBefore - state.recipientOutputTokenBalanceAfter - ).rrevert(); + LibTransformERC20RichErrors + .NegativeTransformERC20OutputError( + address(args.outputToken), + state.recipientOutputTokenBalanceBefore - state.recipientOutputTokenBalanceAfter + ) + .rrevert(); } outputTokenAmount = LibSafeMathV06.min256( outputTokenAmount, @@ -266,11 +226,9 @@ contract TransformERC20Feature is ); // Ensure enough output token has been sent to the taker. if (outputTokenAmount < args.minOutputTokenAmount) { - LibTransformERC20RichErrors.IncompleteTransformERC20Error( - address(args.outputToken), - outputTokenAmount, - args.minOutputTokenAmount - ).rrevert(); + LibTransformERC20RichErrors + .IncompleteTransformERC20Error(address(args.outputToken), outputTokenAmount, args.minOutputTokenAmount) + .rrevert(); } // Emit an event. @@ -286,33 +244,17 @@ contract TransformERC20Feature is /// @dev Return the current wallet instance that will serve as the execution /// context for transformations. /// @return wallet The wallet instance. - function getTransformWallet() - public - override - view - returns (IFlashWallet wallet) - { + function getTransformWallet() public view override returns (IFlashWallet wallet) { return LibTransformERC20Storage.getStorage().wallet; } /// @dev Transfer input tokens and any attached ETH to `to` /// @param args A `TransformERC20Args` struct. /// @param to The recipient of tokens and ETH. - function _transferInputTokensAndAttachedEth( - TransformERC20Args memory args, - address payable to - ) - private - { - if ( - LibERC20Transformer.isTokenETH(args.inputToken) && - msg.value < args.inputTokenAmount - ) { - // Token is ETH, so the caller must attach enough ETH to the call. - LibTransformERC20RichErrors.InsufficientEthAttachedError( - msg.value, - args.inputTokenAmount - ).rrevert(); + function _transferInputTokensAndAttachedEth(TransformERC20Args memory args, address payable to) private { + if (LibERC20Transformer.isTokenETH(args.inputToken) && msg.value < args.inputTokenAmount) { + // Token is ETH, so the caller must attach enough ETH to the call. + LibTransformERC20RichErrors.InsufficientEthAttachedError(msg.value, args.inputTokenAmount).rrevert(); } // Transfer any attached ETH. @@ -324,19 +266,10 @@ contract TransformERC20Feature is if (!LibERC20Transformer.isTokenETH(args.inputToken)) { if (args.useSelfBalance) { // Use EP balance input token. - _transferERC20Tokens( - args.inputToken, - to, - args.inputTokenAmount - ); + _transferERC20Tokens(args.inputToken, to, args.inputTokenAmount); } else { // Pull ERC20 tokens from taker. - _transferERC20TokensFrom( - args.inputToken, - args.taker, - to, - args.inputTokenAmount - ); + _transferERC20TokensFrom(args.inputToken, args.taker, to, args.inputTokenAmount); } } } @@ -351,9 +284,7 @@ contract TransformERC20Feature is Transformation memory transformation, address transformerDeployer, address payable recipient - ) - private - { + ) private { // Derive the transformer address from the deployment nonce. address payable transformer = LibERC20Transformer.getDeployedAddress( transformerDeployer, @@ -374,14 +305,8 @@ contract TransformERC20Feature is ) ); // Ensure the transformer returned the magic bytes. - if (resultData.length != 32 || - abi.decode(resultData, (bytes4)) != LibERC20Transformer.TRANSFORMER_SUCCESS - ) { - LibTransformERC20RichErrors.TransformerFailedError( - transformer, - transformation.data, - resultData - ).rrevert(); + if (resultData.length != 32 || abi.decode(resultData, (bytes4)) != LibERC20Transformer.TRANSFORMER_SUCCESS) { + LibTransformERC20RichErrors.TransformerFailedError(transformer, transformation.data, resultData).rrevert(); } } @@ -389,33 +314,23 @@ contract TransformERC20Feature is IERC20TokenV06 outputToken, IFlashWallet wallet, address payable recipient - ) - private - returns (uint256 transferAmount) - { - transferAmount = - LibERC20Transformer.getTokenBalanceOf(outputToken, address(wallet)); + ) private returns (uint256 transferAmount) { + transferAmount = LibERC20Transformer.getTokenBalanceOf(outputToken, address(wallet)); if (LibERC20Transformer.isTokenETH(outputToken)) { - wallet.executeCall( - recipient, - "", - transferAmount - ); + wallet.executeCall(recipient, "", transferAmount); } else { bytes memory resultData = wallet.executeCall( payable(address(outputToken)), - abi.encodeWithSelector( - IERC20TokenV06.transfer.selector, - recipient, - transferAmount - ), + abi.encodeWithSelector(IERC20TokenV06.transfer.selector, recipient, transferAmount), 0 ); if (resultData.length == 0) { // If we get back 0 returndata, this may be a non-standard ERC-20 that // does not return a boolean. Check that it at least contains code. uint256 size; - assembly { size := extcodesize(outputToken) } + assembly { + size := extcodesize(outputToken) + } require(size > 0, "invalid token address, contains no code"); } else if (resultData.length >= 32) { // If we get back at least 32 bytes, we know the target address diff --git a/contracts/zero-ex/contracts/src/features/UniswapFeature.sol b/contracts/zero-ex/contracts/src/features/UniswapFeature.sol index d4fe1ca410..0ff9509571 100644 --- a/contracts/zero-ex/contracts/src/features/UniswapFeature.sol +++ b/contracts/zero-ex/contracts/src/features/UniswapFeature.sol @@ -27,13 +27,8 @@ import "../fixins/FixinCommon.sol"; import "./interfaces/IFeature.sol"; import "./interfaces/IUniswapFeature.sol"; - /// @dev VIP uniswap fill functions. -contract UniswapFeature is - IFeature, - IUniswapFeature, - FixinCommon -{ +contract UniswapFeature is IFeature, IUniswapFeature, FixinCommon { /// @dev Name of this feature. string public constant override FEATURE_NAME = "UniswapFeature"; /// @dev Version of this feature. @@ -42,36 +37,46 @@ contract UniswapFeature is IEtherTokenV06 private immutable WETH; // 0xFF + address of the UniswapV2Factory contract. - uint256 constant private FF_UNISWAP_FACTORY = 0xFF5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f0000000000000000000000; + uint256 private constant FF_UNISWAP_FACTORY = 0xFF5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f0000000000000000000000; // 0xFF + address of the (Sushiswap) UniswapV2Factory contract. - uint256 constant private FF_SUSHISWAP_FACTORY = 0xFFC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac0000000000000000000000; + uint256 private constant FF_SUSHISWAP_FACTORY = 0xFFC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac0000000000000000000000; // Init code hash of the UniswapV2Pair contract. - uint256 constant private UNISWAP_PAIR_INIT_CODE_HASH = 0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f; + uint256 private constant UNISWAP_PAIR_INIT_CODE_HASH = + 0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f; // Init code hash of the (Sushiswap) UniswapV2Pair contract. - uint256 constant private SUSHISWAP_PAIR_INIT_CODE_HASH = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; + uint256 private constant SUSHISWAP_PAIR_INIT_CODE_HASH = + 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; // Mask of the lower 20 bytes of a bytes32. - uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; + uint256 private constant ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; // ETH pseudo-token address. - uint256 constant private ETH_TOKEN_ADDRESS_32 = 0x000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee; + uint256 private constant ETH_TOKEN_ADDRESS_32 = 0x000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee; // Maximum token quantity that can be swapped against the UniswapV2Pair contract. - uint256 constant private MAX_SWAP_AMOUNT = 2**112; + uint256 private constant MAX_SWAP_AMOUNT = 2**112; // bytes4(keccak256("executeCall(address,bytes)")) - uint256 constant private ALLOWANCE_TARGET_EXECUTE_CALL_SELECTOR_32 = 0xbca8c7b500000000000000000000000000000000000000000000000000000000; + uint256 private constant ALLOWANCE_TARGET_EXECUTE_CALL_SELECTOR_32 = + 0xbca8c7b500000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("getReserves()")) - uint256 constant private UNISWAP_PAIR_RESERVES_CALL_SELECTOR_32 = 0x0902f1ac00000000000000000000000000000000000000000000000000000000; + uint256 private constant UNISWAP_PAIR_RESERVES_CALL_SELECTOR_32 = + 0x0902f1ac00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("swap(uint256,uint256,address,bytes)")) - uint256 constant private UNISWAP_PAIR_SWAP_CALL_SELECTOR_32 = 0x022c0d9f00000000000000000000000000000000000000000000000000000000; + uint256 private constant UNISWAP_PAIR_SWAP_CALL_SELECTOR_32 = + 0x022c0d9f00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("transferFrom(address,address,uint256)")) - uint256 constant private TRANSFER_FROM_CALL_SELECTOR_32 = 0x23b872dd00000000000000000000000000000000000000000000000000000000; + uint256 private constant TRANSFER_FROM_CALL_SELECTOR_32 = + 0x23b872dd00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("allowance(address,address)")) - uint256 constant private ALLOWANCE_CALL_SELECTOR_32 = 0xdd62ed3e00000000000000000000000000000000000000000000000000000000; + uint256 private constant ALLOWANCE_CALL_SELECTOR_32 = + 0xdd62ed3e00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("withdraw(uint256)")) - uint256 constant private WETH_WITHDRAW_CALL_SELECTOR_32 = 0x2e1a7d4d00000000000000000000000000000000000000000000000000000000; + uint256 private constant WETH_WITHDRAW_CALL_SELECTOR_32 = + 0x2e1a7d4d00000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("deposit()")) - uint256 constant private WETH_DEPOSIT_CALL_SELECTOR_32 = 0xd0e30db000000000000000000000000000000000000000000000000000000000; + uint256 private constant WETH_DEPOSIT_CALL_SELECTOR_32 = + 0xd0e30db000000000000000000000000000000000000000000000000000000000; // bytes4(keccak256("transfer(address,uint256)")) - uint256 constant private ERC20_TRANSFER_CALL_SELECTOR_32 = 0xa9059cbb00000000000000000000000000000000000000000000000000000000; + uint256 private constant ERC20_TRANSFER_CALL_SELECTOR_32 = + 0xa9059cbb00000000000000000000000000000000000000000000000000000000; /// @dev Construct this contract. /// @param weth The WETH contract. @@ -82,10 +87,7 @@ contract UniswapFeature is /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. - function migrate() - external - returns (bytes4 success) - { + function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.sellToUniswap.selector); return LibMigrate.MIGRATE_SUCCESS; } @@ -101,12 +103,7 @@ contract UniswapFeature is uint256 sellAmount, uint256 minBuyAmount, bool isSushi - ) - external - payable - override - returns (uint256 buyAmount) - { + ) external payable override returns (uint256 buyAmount) { require(tokens.length > 1, "UniswapFeature/InvalidTokensLength"); { // Load immutables onto the stack. @@ -132,7 +129,11 @@ contract UniswapFeature is let buyToken let nextPair := 0 - for {let i := 0} lt(i, numPairs) {i := add(i, 1)} { + for { + let i := 0 + } lt(i, numPairs) { + i := add(i, 1) + } { // sellToken = tokens[i] let sellToken := loadTokenAddress(i) // buyToken = tokens[i+1] @@ -151,35 +152,36 @@ contract UniswapFeature is if iszero(i) { // This is the first token in the path. switch eq(sellToken, ETH_TOKEN_ADDRESS_32) - case 0 { // Not selling ETH. Selling an ERC20 instead. - // Make sure ETH was not attached to the call. - if gt(callvalue(), 0) { - revert(0, 0) - } - // For the first pair we need to transfer sellTokens into the - // pair contract. - moveTakerTokensTo(sellToken, pair, sellAmount) + case 0 { + // Not selling ETH. Selling an ERC20 instead. + // Make sure ETH was not attached to the call. + if gt(callvalue(), 0) { + revert(0, 0) } - default { - // If selling ETH, we need to wrap it to WETH and transfer to the - // pair contract. - if iszero(eq(callvalue(), sellAmount)) { - revert(0, 0) - } - sellToken := mload(0xA40)// Re-assign to WETH - // Call `WETH.deposit{value: sellAmount}()` - mstore(0xB00, WETH_DEPOSIT_CALL_SELECTOR_32) - if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { - bubbleRevert() - } - // Call `WETH.transfer(pair, sellAmount)` - mstore(0xB00, ERC20_TRANSFER_CALL_SELECTOR_32) - mstore(0xB04, pair) - mstore(0xB24, sellAmount) - if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { - bubbleRevert() - } + // For the first pair we need to transfer sellTokens into the + // pair contract. + moveTakerTokensTo(sellToken, pair, sellAmount) + } + default { + // If selling ETH, we need to wrap it to WETH and transfer to the + // pair contract. + if iszero(eq(callvalue(), sellAmount)) { + revert(0, 0) } + sellToken := mload(0xA40) // Re-assign to WETH + // Call `WETH.deposit{value: sellAmount}()` + mstore(0xB00, WETH_DEPOSIT_CALL_SELECTOR_32) + if iszero(call(gas(), sellToken, sellAmount, 0xB00, 0x4, 0x00, 0x0)) { + bubbleRevert() + } + // Call `WETH.transfer(pair, sellAmount)` + mstore(0xB00, ERC20_TRANSFER_CALL_SELECTOR_32) + mstore(0xB04, pair) + mstore(0xB24, sellAmount) + if iszero(call(gas(), sellToken, 0, 0xB00, 0x44, 0x00, 0x0)) { + bubbleRevert() + } + } // No need to check results, if deposit/transfers failed the UniswapV2Pair will // reject our trade (or it may succeed if somehow the reserve was out of sync) // this is fine for the taker. @@ -192,7 +194,7 @@ contract UniswapFeature is } // Revert if the pair contract does not return at least two words. if lt(returndatasize(), 0x40) { - revert(0,0) + revert(0, 0) } // Sell amount for this hop is the previous buy amount. @@ -202,15 +204,15 @@ contract UniswapFeature is let sellReserve let buyReserve switch iszero(pairOrder) - case 0 { - // Transpose if pair order is different. - sellReserve := mload(0xC00) - buyReserve := mload(0xC20) - } - default { - sellReserve := mload(0xC20) - buyReserve := mload(0xC00) - } + case 0 { + // Transpose if pair order is different. + sellReserve := mload(0xC00) + buyReserve := mload(0xC20) + } + default { + sellReserve := mload(0xC20) + buyReserve := mload(0xC00) + } // Ensure that the sellAmount is < 2¹¹². if gt(pairSellAmount, MAX_SWAP_AMOUNT) { revert(0, 0) @@ -219,47 +221,41 @@ contract UniswapFeature is // buyAmount = (pairSellAmount * 997 * buyReserve) / // (pairSellAmount * 997 + sellReserve * 1000); let sellAmountWithFee := mul(pairSellAmount, 997) - buyAmount := div( - mul(sellAmountWithFee, buyReserve), - add(sellAmountWithFee, mul(sellReserve, 1000)) - ) + buyAmount := div(mul(sellAmountWithFee, buyReserve), add(sellAmountWithFee, mul(sellReserve, 1000))) } let receiver // Is this the last pair contract? switch eq(add(i, 1), numPairs) + case 0 { + // Not the last pair contract, so forward bought tokens to + // the next pair contract. + nextPair := computePairAddress(buyToken, loadTokenAddress(add(i, 2))) + receiver := nextPair + } + default { + // The last pair contract. + // Forward directly to taker UNLESS they want ETH back. + switch eq(buyToken, ETH_TOKEN_ADDRESS_32) case 0 { - // Not the last pair contract, so forward bought tokens to - // the next pair contract. - nextPair := computePairAddress( - buyToken, - loadTokenAddress(add(i, 2)) - ) - receiver := nextPair + receiver := caller() } default { - // The last pair contract. - // Forward directly to taker UNLESS they want ETH back. - switch eq(buyToken, ETH_TOKEN_ADDRESS_32) - case 0 { - receiver := caller() - } - default { - receiver := address() - } + receiver := address() } + } // Call pair.swap() mstore(0xB00, UNISWAP_PAIR_SWAP_CALL_SELECTOR_32) switch pairOrder - case 0 { - mstore(0xB04, buyAmount) - mstore(0xB24, 0) - } - default { - mstore(0xB04, 0) - mstore(0xB24, buyAmount) - } + case 0 { + mstore(0xB04, buyAmount) + mstore(0xB24, 0) + } + default { + mstore(0xB04, 0) + mstore(0xB24, buyAmount) + } mstore(0xB44, receiver) mstore(0xB64, 0x80) mstore(0xB84, 0) @@ -322,27 +318,27 @@ contract UniswapFeature is // them as two 20-byte values in a 40-byte chunk of memory // starting at 0xB0C. switch lt(tokenA, tokenB) - case 0 { - mstore(0xB14, tokenA) - mstore(0xB00, tokenB) - } - default { - mstore(0xB14, tokenB) - mstore(0xB00, tokenA) - } + case 0 { + mstore(0xB14, tokenA) + mstore(0xB00, tokenB) + } + default { + mstore(0xB14, tokenB) + mstore(0xB00, tokenA) + } let salt := keccak256(0xB0C, 0x28) // Compute the pair address by hashing all the components together. switch mload(0xA20) // isSushi - case 0 { - mstore(0xB00, FF_UNISWAP_FACTORY) - mstore(0xB15, salt) - mstore(0xB35, UNISWAP_PAIR_INIT_CODE_HASH) - } - default { - mstore(0xB00, FF_SUSHISWAP_FACTORY) - mstore(0xB15, salt) - mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) - } + case 0 { + mstore(0xB00, FF_UNISWAP_FACTORY) + mstore(0xB15, salt) + mstore(0xB35, UNISWAP_PAIR_INIT_CODE_HASH) + } + default { + mstore(0xB00, FF_SUSHISWAP_FACTORY) + mstore(0xB15, salt) + mstore(0xB35, SUSHISWAP_PAIR_INIT_CODE_HASH) + } pair := and(ADDRESS_MASK, keccak256(0xB00, 0x55)) } @@ -381,12 +377,12 @@ contract UniswapFeature is // success, or at least 32 bytes that starts with // a 32-byte boolean true. success := and( - success, // call itself succeeded + success, // call itself succeeded or( - iszero(rdsize), // no return data, or + iszero(rdsize), // no return data, or and( - iszero(lt(rdsize, 32)), // at least 32 bytes - eq(mload(0xC00), 1) // starts with uint256(1) + iszero(lt(rdsize, 32)), // at least 32 bytes + eq(mload(0xC00), 1) // starts with uint256(1) ) ) ) diff --git a/contracts/zero-ex/contracts/src/features/UniswapV3Feature.sol b/contracts/zero-ex/contracts/src/features/UniswapV3Feature.sol index 5b383c3fc0..a214393a1b 100644 --- a/contracts/zero-ex/contracts/src/features/UniswapV3Feature.sol +++ b/contracts/zero-ex/contracts/src/features/UniswapV3Feature.sol @@ -29,14 +29,8 @@ import "../fixins/FixinTokenSpender.sol"; import "./interfaces/IFeature.sol"; import "./interfaces/IUniswapV3Feature.sol"; - /// @dev VIP uniswap fill functions. -contract UniswapV3Feature is - IFeature, - IUniswapV3Feature, - FixinCommon, - FixinTokenSpender -{ +contract UniswapV3Feature is IFeature, IUniswapV3Feature, FixinCommon, FixinTokenSpender { /// @dev Name of this feature. string public constant override FEATURE_NAME = "UniswapV3Feature"; /// @dev Version of this feature. @@ -81,10 +75,7 @@ contract UniswapV3Feature is /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. - function migrate() - external - returns (bytes4 success) - { + function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.sellEthForTokenToUniswapV3.selector); _registerFeatureFunction(this.sellTokenForEthToUniswapV3.selector); _registerFeatureFunction(this.sellTokenForTokenToUniswapV3.selector); @@ -102,21 +93,17 @@ contract UniswapV3Feature is bytes memory encodedPath, uint256 minBuyAmount, address recipient - ) - public - payable - override - returns (uint256 buyAmount) - { + ) public payable override returns (uint256 buyAmount) { // Wrap ETH. - WETH.deposit{ value: msg.value }(); - return _swap( - encodedPath, - msg.value, - minBuyAmount, - address(this), // we are payer because we hold the WETH - _normalizeRecipient(recipient) - ); + WETH.deposit{value: msg.value}(); + return + _swap( + encodedPath, + msg.value, + minBuyAmount, + address(this), // we are payer because we hold the WETH + _normalizeRecipient(recipient) + ); } /// @dev Sell a token for ETH directly against uniswap v3. @@ -130,11 +117,7 @@ contract UniswapV3Feature is uint256 sellAmount, uint256 minBuyAmount, address payable recipient - ) - public - override - returns (uint256 buyAmount) - { + ) public override returns (uint256 buyAmount) { buyAmount = _swap( encodedPath, sellAmount, @@ -144,8 +127,7 @@ contract UniswapV3Feature is ); WETH.withdraw(buyAmount); // Transfer ETH to recipient. - (bool success, bytes memory revertData) = - _normalizeRecipient(recipient).call{ value: buyAmount }(""); + (bool success, bytes memory revertData) = _normalizeRecipient(recipient).call{value: buyAmount}(""); if (!success) { revertData.rrevert(); } @@ -162,18 +144,8 @@ contract UniswapV3Feature is uint256 sellAmount, uint256 minBuyAmount, address recipient - ) - public - override - returns (uint256 buyAmount) - { - buyAmount = _swap( - encodedPath, - sellAmount, - minBuyAmount, - msg.sender, - _normalizeRecipient(recipient) - ); + ) public override returns (uint256 buyAmount) { + buyAmount = _swap(encodedPath, sellAmount, minBuyAmount, msg.sender, _normalizeRecipient(recipient)); } /// @dev Sell a token for another token directly against uniswap v3. @@ -188,19 +160,8 @@ contract UniswapV3Feature is uint256 sellAmount, uint256 minBuyAmount, address recipient - ) - public - override - onlySelf - returns (uint256 buyAmount) - { - buyAmount = _swap( - encodedPath, - sellAmount, - minBuyAmount, - address(this), - _normalizeRecipient(recipient) - ); + ) public override onlySelf returns (uint256 buyAmount) { + buyAmount = _swap(encodedPath, sellAmount, minBuyAmount, address(this), _normalizeRecipient(recipient)); } /// @dev The UniswapV3 pool swap callback which pays the funds requested @@ -214,10 +175,7 @@ contract UniswapV3Feature is int256 amount0Delta, int256 amount1Delta, bytes calldata data - ) - external - override - { + ) external override { IERC20TokenV06 token0; IERC20TokenV06 token1; address payer; @@ -232,9 +190,7 @@ contract UniswapV3Feature is fee := calldataload(add(p, 64)) payer := calldataload(add(p, 96)) } - (token0, token1) = token0 < token1 - ? (token0, token1) - : (token1, token0); + (token0, token1) = token0 < token1 ? (token0, token1) : (token1, token0); // Only a valid pool contract can call this function. require( msg.sender == address(_toPool(token0, fee, token1)), @@ -258,10 +214,7 @@ contract UniswapV3Feature is uint256 minBuyAmount, address payer, address recipient - ) - private - returns (uint256 buyAmount) - { + ) private returns (uint256 buyAmount) { if (sellAmount != 0) { require(sellAmount <= uint256(type(int256).max), "UniswapV3Feature/SELL_AMOUNT_OVERFLOW"); @@ -272,29 +225,19 @@ contract UniswapV3Feature is bool zeroForOne; IUniswapV3Pool pool; { - ( - IERC20TokenV06 inputToken, - uint24 fee, - IERC20TokenV06 outputToken - ) = _decodeFirstPoolInfoFromPath(encodedPath); + (IERC20TokenV06 inputToken, uint24 fee, IERC20TokenV06 outputToken) = _decodeFirstPoolInfoFromPath( + encodedPath + ); pool = _toPool(inputToken, fee, outputToken); zeroForOne = inputToken < outputToken; - _updateSwapCallbackData( - swapCallbackData, - inputToken, - outputToken, - fee, - payer - ); + _updateSwapCallbackData(swapCallbackData, inputToken, outputToken, fee, payer); } (int256 amount0, int256 amount1) = pool.swap( // Intermediate tokens go to this contract. isPathMultiHop ? address(this) : recipient, zeroForOne, int256(sellAmount), - zeroForOne - ? MIN_PRICE_SQRT_RATIO + 1 - : MAX_PRICE_SQRT_RATIO - 1, + zeroForOne ? MIN_PRICE_SQRT_RATIO + 1 : MAX_PRICE_SQRT_RATIO - 1, swapCallbackData ); { @@ -323,9 +266,7 @@ contract UniswapV3Feature is address payer, address to, uint256 amount - ) - private - { + ) private { if (payer != address(this)) { _transferERC20TokensFrom(token, payer, to, amount); } else { @@ -340,10 +281,7 @@ contract UniswapV3Feature is IERC20TokenV06 outputToken, uint24 fee, address payer - ) - private - pure - { + ) private pure { assembly { let p := add(swapCallbackData, 32) mstore(p, inputToken) @@ -358,11 +296,7 @@ contract UniswapV3Feature is IERC20TokenV06 inputToken, uint24 fee, IERC20TokenV06 outputToken - ) - private - view - returns (IUniswapV3Pool pool) - { + ) private view returns (IUniswapV3Pool pool) { // address(keccak256(abi.encodePacked( // hex"ff", // UNI_FACTORY_ADDRESS, @@ -380,10 +314,10 @@ contract UniswapV3Feature is 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), and(UINT24_MASK, fee)) - mstore(p, keccak256(p, 96)) + mstore(p, token0) + mstore(add(p, 32), token1) + mstore(add(p, 64), and(UINT24_MASK, fee)) + mstore(p, keccak256(p, 96)) p := add(p, 32) mstore(p, poolInitCodeHash) pool := and(ADDRESS_MASK, keccak256(s, 85)) @@ -391,15 +325,10 @@ contract UniswapV3Feature is } // Return whether or not an encoded uniswap path contains more than one hop. - function _isPathMultiHop(bytes memory encodedPath) - private - pure - returns (bool isMultiHop) - { + function _isPathMultiHop(bytes memory encodedPath) private pure returns (bool isMultiHop) { return encodedPath.length > SINGLE_HOP_PATH_SIZE; } - // Return the first input token, output token, and fee of an encoded uniswap path. function _decodeFirstPoolInfoFromPath(bytes memory encodedPath) private @@ -422,11 +351,7 @@ contract UniswapV3Feature is } // Skip past the first hop of an encoded uniswap path in-place. - function _shiftHopFromPathInPlace(bytes memory encodedPath) - private - pure - returns (bytes memory shiftedEncodedPath) - { + function _shiftHopFromPathInPlace(bytes memory encodedPath) private pure returns (bytes memory shiftedEncodedPath) { require(encodedPath.length >= PATH_SKIP_HOP_SIZE, "UniswapV3Feature/BAD_PATH_ENCODING"); uint256 shiftSize = PATH_SKIP_HOP_SIZE; uint256 newSize = encodedPath.length - shiftSize; @@ -437,11 +362,7 @@ contract UniswapV3Feature is } // Convert null address values to msg.sender. - function _normalizeRecipient(address recipient) - private - view - returns (address payable normalizedRecipient) - { + function _normalizeRecipient(address recipient) private view returns (address payable normalizedRecipient) { return recipient == address(0) ? msg.sender : payable(recipient); } } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IBatchFillNativeOrdersFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IBatchFillNativeOrdersFeature.sol index 7312bd5f10..62dd7621d9 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IBatchFillNativeOrdersFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IBatchFillNativeOrdersFeature.sol @@ -23,10 +23,8 @@ pragma experimental ABIEncoderV2; import "../libs/LibNativeOrder.sol"; import "../libs/LibSignature.sol"; - /// @dev Feature for batch/market filling limit and RFQ orders. interface IBatchFillNativeOrdersFeature { - /// @dev Fills multiple limit orders. /// @param orders Array of limit orders. /// @param signatures Array of signatures corresponding to each order. @@ -40,13 +38,7 @@ interface IBatchFillNativeOrdersFeature { LibSignature.Signature[] calldata signatures, uint128[] calldata takerTokenFillAmounts, bool revertIfIncomplete - ) - external - payable - returns ( - uint128[] memory takerTokenFilledAmounts, - uint128[] memory makerTokenFilledAmounts - ); + ) external payable returns (uint128[] memory takerTokenFilledAmounts, uint128[] memory makerTokenFilledAmounts); /// @dev Fills multiple RFQ orders. /// @param orders Array of RFQ orders. @@ -61,10 +53,5 @@ interface IBatchFillNativeOrdersFeature { LibSignature.Signature[] calldata signatures, uint128[] calldata takerTokenFillAmounts, bool revertIfIncomplete - ) - external - returns ( - uint128[] memory takerTokenFilledAmounts, - uint128[] memory makerTokenFilledAmounts - ); + ) external returns (uint128[] memory takerTokenFilledAmounts, uint128[] memory makerTokenFilledAmounts); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IBootstrapFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IBootstrapFeature.sol index 7b95382ed6..9d6d8055fa 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IBootstrapFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IBootstrapFeature.sol @@ -20,10 +20,8 @@ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; - /// @dev Detachable `bootstrap()` feature. interface IBootstrapFeature { - /// @dev Bootstrap the initial feature set of this contract by delegatecalling /// into `target`. Before exiting the `bootstrap()` function will /// deregister itself from the proxy to prevent being called again. diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IERC1155OrdersFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IERC1155OrdersFeature.sol index 74f785e113..75df6931dc 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IERC1155OrdersFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IERC1155OrdersFeature.sol @@ -25,10 +25,8 @@ import "../libs/LibNFTOrder.sol"; import "../libs/LibSignature.sol"; import "../../vendor/IERC1155Token.sol"; - /// @dev Feature for interacting with ERC1155 orders. interface IERC1155OrdersFeature { - /// @dev Emitted whenever an `ERC1155Order` is filled. /// @param direction Whether the order is selling or /// buying the ERC1155 token. @@ -57,10 +55,7 @@ interface IERC1155OrdersFeature { /// @dev Emitted whenever an `ERC1155Order` is cancelled. /// @param maker The maker of the order. /// @param nonce The nonce of the order that was cancelled. - event ERC1155OrderCancelled( - address maker, - uint256 nonce - ); + event ERC1155OrderCancelled(address maker, uint256 nonce); /// @dev Emitted when an `ERC1155Order` is pre-signed. /// Contains all the fields of the order. @@ -102,8 +97,7 @@ interface IERC1155OrdersFeature { uint128 erc1155SellAmount, bool unwrapNativeToken, bytes calldata callbackData - ) - external; + ) external; /// @dev Buys an ERC1155 asset by filling the given order. /// @param sellOrder The ERC1155 sell order. @@ -121,25 +115,21 @@ interface IERC1155OrdersFeature { LibSignature.Signature calldata signature, uint128 erc1155BuyAmount, bytes calldata callbackData - ) - external - payable; + ) external payable; /// @dev Cancel a single ERC1155 order by its nonce. The caller /// should be the maker of the order. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonce The order nonce. - function cancelERC1155Order(uint256 orderNonce) - external; + function cancelERC1155Order(uint256 orderNonce) external; /// @dev Cancel multiple ERC1155 orders by their nonces. The caller /// should be the maker of the orders. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonces The order nonces. - function batchCancelERC1155Orders(uint256[] calldata orderNonces) - external; + function batchCancelERC1155Orders(uint256[] calldata orderNonces) external; /// @dev Buys multiple ERC1155 assets by filling the /// given orders. @@ -160,10 +150,7 @@ interface IERC1155OrdersFeature { uint128[] calldata erc1155TokenAmounts, bytes[] calldata callbackData, bool revertIfIncomplete - ) - external - payable - returns (bool[] memory successes); + ) external payable returns (bool[] memory successes); /// @dev Callback for the ERC1155 `safeTransferFrom` function. /// This callback can be used to sell an ERC1155 asset if @@ -186,16 +173,13 @@ interface IERC1155OrdersFeature { uint256 tokenId, uint256 value, bytes calldata data - ) - external - returns (bytes4 success); + ) external returns (bytes4 success); /// @dev Approves an ERC1155 order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 order. - function preSignERC1155Order(LibNFTOrder.ERC1155Order calldata order) - external; + function preSignERC1155Order(LibNFTOrder.ERC1155Order calldata order) external; /// @dev Checks whether the given signature is valid for the /// the given ERC1155 order. Reverts if not. @@ -204,9 +188,7 @@ interface IERC1155OrdersFeature { function validateERC1155OrderSignature( LibNFTOrder.ERC1155Order calldata order, LibSignature.Signature calldata signature - ) - external - view; + ) external view; /// @dev If the given order is buying an ERC1155 asset, checks /// whether or not the given token ID satisfies the required @@ -217,10 +199,7 @@ interface IERC1155OrdersFeature { /// an ERC1155 asset. /// @param order The ERC1155 order. /// @param erc1155TokenId The ID of the ERC1155 asset. - function validateERC1155OrderProperties( - LibNFTOrder.ERC1155Order calldata order, - uint256 erc1155TokenId - ) + function validateERC1155OrderProperties(LibNFTOrder.ERC1155Order calldata order, uint256 erc1155TokenId) external view; @@ -235,8 +214,5 @@ interface IERC1155OrdersFeature { /// @dev Get the EIP-712 hash of an ERC1155 order. /// @param order The ERC1155 order. /// @return orderHash The order hash. - function getERC1155OrderHash(LibNFTOrder.ERC1155Order calldata order) - external - view - returns (bytes32 orderHash); + function getERC1155OrderHash(LibNFTOrder.ERC1155Order calldata order) external view returns (bytes32 orderHash); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IERC165Feature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IERC165Feature.sol index 5844eb72e1..63fd0d7cd9 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IERC165Feature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IERC165Feature.sol @@ -20,17 +20,12 @@ pragma solidity ^0.6; pragma experimental ABIEncoderV2; - /// @dev Implements the ERC165 `supportsInterface` function interface IERC165Feature { - /// @dev Indicates whether the 0x Exchange Proxy implements a particular /// ERC165 interface. This function should use at most 30,000 gas. /// @param interfaceId The interface identifier, as specified in ERC165. /// @return isSupported Whether the given interface is supported by the /// 0x Exchange Proxy. - function supportInterface(bytes4 interfaceId) - external - pure - returns (bool isSupported); + function supportInterface(bytes4 interfaceId) external pure returns (bool isSupported); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IERC721OrdersFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IERC721OrdersFeature.sol index 7c4622c236..a052ceffdd 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IERC721OrdersFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IERC721OrdersFeature.sol @@ -25,10 +25,8 @@ import "../libs/LibNFTOrder.sol"; import "../libs/LibSignature.sol"; import "../../vendor/IERC721Token.sol"; - /// @dev Feature for interacting with ERC721 orders. interface IERC721OrdersFeature { - /// @dev Emitted whenever an `ERC721Order` is filled. /// @param direction Whether the order is selling or /// buying the ERC721 token. @@ -57,10 +55,7 @@ interface IERC721OrdersFeature { /// @dev Emitted whenever an `ERC721Order` is cancelled. /// @param maker The maker of the order. /// @param nonce The nonce of the order that was cancelled. - event ERC721OrderCancelled( - address maker, - uint256 nonce - ); + event ERC721OrderCancelled(address maker, uint256 nonce); /// @dev Emitted when an `ERC721Order` is pre-signed. /// Contains all the fields of the order. @@ -98,8 +93,7 @@ interface IERC721OrdersFeature { uint256 erc721TokenId, bool unwrapNativeToken, bytes calldata callbackData - ) - external; + ) external; /// @dev Buys an ERC721 asset by filling the given order. /// @param sellOrder The ERC721 sell order. @@ -114,25 +108,21 @@ interface IERC721OrdersFeature { LibNFTOrder.ERC721Order calldata sellOrder, LibSignature.Signature calldata signature, bytes calldata callbackData - ) - external - payable; + ) external payable; /// @dev Cancel a single ERC721 order by its nonce. The caller /// should be the maker of the order. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonce The order nonce. - function cancelERC721Order(uint256 orderNonce) - external; + function cancelERC721Order(uint256 orderNonce) external; /// @dev Cancel multiple ERC721 orders by their nonces. The caller /// should be the maker of the orders. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonces The order nonces. - function batchCancelERC721Orders(uint256[] calldata orderNonces) - external; + function batchCancelERC721Orders(uint256[] calldata orderNonces) external; /// @dev Buys multiple ERC721 assets by filling the /// given orders. @@ -150,10 +140,7 @@ interface IERC721OrdersFeature { LibSignature.Signature[] calldata signatures, bytes[] calldata callbackData, bool revertIfIncomplete - ) - external - payable - returns (bool[] memory successes); + ) external payable returns (bool[] memory successes); /// @dev Matches a pair of complementary orders that have /// a non-negative spread. Each order is filled at @@ -171,9 +158,7 @@ interface IERC721OrdersFeature { LibNFTOrder.ERC721Order calldata buyOrder, LibSignature.Signature calldata sellOrderSignature, LibSignature.Signature calldata buyOrderSignature - ) - external - returns (uint256 profit); + ) external returns (uint256 profit); /// @dev Matches pairs of complementary orders that have /// non-negative spreads. Each order is filled at @@ -193,9 +178,7 @@ interface IERC721OrdersFeature { LibNFTOrder.ERC721Order[] calldata buyOrders, LibSignature.Signature[] calldata sellOrderSignatures, LibSignature.Signature[] calldata buyOrderSignatures - ) - external - returns (uint256[] memory profits, bool[] memory successes); + ) external returns (uint256[] memory profits, bool[] memory successes); /// @dev Callback for the ERC721 `safeTransferFrom` function. /// This callback can be used to sell an ERC721 asset if @@ -216,16 +199,13 @@ interface IERC721OrdersFeature { address from, uint256 tokenId, bytes calldata data - ) - external - returns (bytes4 success); + ) external returns (bytes4 success); /// @dev Approves an ERC721 order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC721 order. - function preSignERC721Order(LibNFTOrder.ERC721Order calldata order) - external; + function preSignERC721Order(LibNFTOrder.ERC721Order calldata order) external; /// @dev Checks whether the given signature is valid for the /// the given ERC721 order. Reverts if not. @@ -234,9 +214,7 @@ interface IERC721OrdersFeature { function validateERC721OrderSignature( LibNFTOrder.ERC721Order calldata order, LibSignature.Signature calldata signature - ) - external - view; + ) external view; /// @dev If the given order is buying an ERC721 asset, checks /// whether or not the given token ID satisfies the required @@ -247,12 +225,7 @@ interface IERC721OrdersFeature { /// an ERC721 asset. /// @param order The ERC721 order. /// @param erc721TokenId The ID of the ERC721 asset. - function validateERC721OrderProperties( - LibNFTOrder.ERC721Order calldata order, - uint256 erc721TokenId - ) - external - view; + function validateERC721OrderProperties(LibNFTOrder.ERC721Order calldata order, uint256 erc721TokenId) external view; /// @dev Get the current status of an ERC721 order. /// @param order The ERC721 order. @@ -265,10 +238,7 @@ interface IERC721OrdersFeature { /// @dev Get the EIP-712 hash of an ERC721 order. /// @param order The ERC721 order. /// @return orderHash The order hash. - function getERC721OrderHash(LibNFTOrder.ERC721Order calldata order) - external - view - returns (bytes32 orderHash); + function getERC721OrderHash(LibNFTOrder.ERC721Order calldata order) external view returns (bytes32 orderHash); /// @dev Get the order status bit vector for the given /// maker address and nonce range. @@ -279,8 +249,5 @@ interface IERC721OrdersFeature { /// 248 bits. /// @return bitVector The order status bit vector for the /// given maker and nonce range. - function getERC721OrderStatusBitVector(address maker, uint248 nonceRange) - external - view - returns (uint256 bitVector); + function getERC721OrderStatusBitVector(address maker, uint248 nonceRange) external view returns (uint256 bitVector); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IFeature.sol index b43df94c55..f39f2db4e9 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IFeature.sol @@ -20,10 +20,8 @@ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; - /// @dev Basic interface for a feature contract. interface IFeature { - // solhint-disable func-name-mixedcase /// @dev The name of this feature set. diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IFundRecoveryFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IFundRecoveryFeature.sol index c21076a4ad..d03fd9df29 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IFundRecoveryFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IFundRecoveryFeature.sol @@ -17,19 +17,16 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; - /// @dev Exchange Proxy Recovery Functions interface IFundRecoveryFeature { - /// @dev calledFrom FundRecoveryFeature.transferTrappedTokensTo() This will be delegatecalled /// in the context of the Exchange Proxy instance being used. /// @param erc20 ERC20 Token Address. /// @param amountOut Amount of tokens to withdraw. /// @param recipientWallet Recipient wallet address. - function transferTrappedTokensTo( + function transferTrappedTokensTo( IERC20TokenV06 erc20, uint256 amountOut, address payable recipientWallet - ) - external; -} \ No newline at end of file + ) external; +} diff --git a/contracts/zero-ex/contracts/src/features/interfaces/ILiquidityProviderFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/ILiquidityProviderFeature.sol index cf2bc12bea..509020eb2a 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/ILiquidityProviderFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/ILiquidityProviderFeature.sol @@ -23,10 +23,8 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../../vendor/ILiquidityProvider.sol"; - /// @dev Feature to swap directly with an on-chain liquidity provider. interface ILiquidityProviderFeature { - /// @dev Event for data pipeline. event LiquidityProviderSwap( IERC20TokenV06 inputToken, @@ -58,8 +56,5 @@ interface ILiquidityProviderFeature { uint256 sellAmount, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - payable - returns (uint256 boughtAmount); + ) external payable returns (uint256 boughtAmount); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IMetaTransactionsFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IMetaTransactionsFeature.sol index 9e50c1e068..9a4f38b34e 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IMetaTransactionsFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IMetaTransactionsFeature.sol @@ -55,21 +55,13 @@ interface IMetaTransactionsFeature { /// @param selector The selector of the function being executed. /// @param signer Who to execute the meta-transaction on behalf of. /// @param sender Who executed the meta-transaction. - event MetaTransactionExecuted( - bytes32 hash, - bytes4 indexed selector, - address signer, - address sender - ); + event MetaTransactionExecuted(bytes32 hash, bytes4 indexed selector, address signer, address sender); /// @dev Execute a single meta-transaction. /// @param mtx The meta-transaction. /// @param signature The signature by `mtx.signer`. /// @return returnResult The ABI-encoded result of the underlying call. - function executeMetaTransaction( - MetaTransactionData calldata mtx, - LibSignature.Signature calldata signature - ) + function executeMetaTransaction(MetaTransactionData calldata mtx, LibSignature.Signature calldata signature) external payable returns (bytes memory returnResult); @@ -81,10 +73,7 @@ interface IMetaTransactionsFeature { function batchExecuteMetaTransactions( MetaTransactionData[] calldata mtxs, LibSignature.Signature[] calldata signatures - ) - external - payable - returns (bytes[] memory returnResults); + ) external payable returns (bytes[] memory returnResults); /// @dev Get the block at which a meta-transaction has been executed. /// @param mtx The meta-transaction. @@ -97,16 +86,10 @@ interface IMetaTransactionsFeature { /// @dev Get the block at which a meta-transaction hash has been executed. /// @param mtxHash The meta-transaction hash. /// @return blockNumber The block height when the meta-transactioin was executed. - function getMetaTransactionHashExecutedBlock(bytes32 mtxHash) - external - view - returns (uint256 blockNumber); + function getMetaTransactionHashExecutedBlock(bytes32 mtxHash) external view returns (uint256 blockNumber); /// @dev Get the EIP712 hash of a meta-transaction. /// @param mtx The meta-transaction. /// @return mtxHash The EIP712 hash of `mtx`. - function getMetaTransactionHash(MetaTransactionData calldata mtx) - external - view - returns (bytes32 mtxHash); + function getMetaTransactionHash(MetaTransactionData calldata mtx) external view returns (bytes32 mtxHash); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IMultiplexFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IMultiplexFeature.sol index ac6f529c29..f77171f274 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IMultiplexFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IMultiplexFeature.sol @@ -22,7 +22,6 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; - interface IMultiplexFeature { // Identifies the type of subcall. enum MultiplexSubcall { @@ -125,10 +124,7 @@ interface IMultiplexFeature { IERC20TokenV06 outputToken, BatchSellSubcall[] calldata calls, uint256 minBuyAmount - ) - external - payable - returns (uint256 boughtAmount); + ) external payable returns (uint256 boughtAmount); /// @dev Sells `sellAmount` of the given `inputToken` for ETH /// using the provided calls. @@ -143,9 +139,7 @@ interface IMultiplexFeature { BatchSellSubcall[] calldata calls, uint256 sellAmount, uint256 minBuyAmount - ) - external - returns (uint256 boughtAmount); + ) external returns (uint256 boughtAmount); /// @dev Sells `sellAmount` of the given `inputToken` for /// `outputToken` using the provided calls. @@ -162,9 +156,7 @@ interface IMultiplexFeature { BatchSellSubcall[] calldata calls, uint256 sellAmount, uint256 minBuyAmount - ) - external - returns (uint256 boughtAmount); + ) external returns (uint256 boughtAmount); /// @dev Sells attached ETH via the given sequence of tokens /// and calls. `tokens[0]` must be WETH. @@ -181,10 +173,7 @@ interface IMultiplexFeature { address[] calldata tokens, MultiHopSellSubcall[] calldata calls, uint256 minBuyAmount - ) - external - payable - returns (uint256 boughtAmount); + ) external payable returns (uint256 boughtAmount); /// @dev Sells `sellAmount` of the input token (`tokens[0]`) /// for ETH via the given sequence of tokens and calls. @@ -201,9 +190,7 @@ interface IMultiplexFeature { MultiHopSellSubcall[] calldata calls, uint256 sellAmount, uint256 minBuyAmount - ) - external - returns (uint256 boughtAmount); + ) external returns (uint256 boughtAmount); /// @dev Sells `sellAmount` of the input token (`tokens[0]`) /// via the given sequence of tokens and calls. @@ -221,7 +208,5 @@ interface IMultiplexFeature { MultiHopSellSubcall[] calldata calls, uint256 sellAmount, uint256 minBuyAmount - ) - external - returns (uint256 boughtAmount); + ) external returns (uint256 boughtAmount); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/INativeOrdersEvents.sol b/contracts/zero-ex/contracts/src/features/interfaces/INativeOrdersEvents.sol index ff7c7810b6..747f8740c6 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/INativeOrdersEvents.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/INativeOrdersEvents.sol @@ -24,10 +24,8 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../libs/LibSignature.sol"; import "../libs/LibNativeOrder.sol"; - /// @dev Events emitted by NativeOrdersFeature. interface INativeOrdersEvents { - /// @dev Emitted whenever a `LimitOrder` is filled. /// @param orderHash The canonical hash of the order. /// @param maker The maker of the order. @@ -72,10 +70,7 @@ interface INativeOrdersEvents { /// @dev Emitted whenever a limit or RFQ order is cancelled. /// @param orderHash The canonical hash of the order. /// @param maker The order maker. - event OrderCancelled( - bytes32 orderHash, - address maker - ); + event OrderCancelled(bytes32 orderHash, address maker); /// @dev Emitted whenever Limit orders are cancelled by pair by a maker. /// @param maker The maker of the order. @@ -83,12 +78,7 @@ interface INativeOrdersEvents { /// @param takerToken The taker token in a pair for the orders cancelled. /// @param minValidSalt The new minimum valid salt an order with this pair must /// have. - event PairCancelledLimitOrders( - address maker, - address makerToken, - address takerToken, - uint256 minValidSalt - ); + event PairCancelledLimitOrders(address maker, address makerToken, address takerToken, uint256 minValidSalt); /// @dev Emitted whenever RFQ orders are cancelled by pair by a maker. /// @param maker The maker of the order. @@ -96,31 +86,18 @@ interface INativeOrdersEvents { /// @param takerToken The taker token in a pair for the orders cancelled. /// @param minValidSalt The new minimum valid salt an order with this pair must /// have. - event PairCancelledRfqOrders( - address maker, - address makerToken, - address takerToken, - uint256 minValidSalt - ); + event PairCancelledRfqOrders(address maker, address makerToken, address takerToken, uint256 minValidSalt); /// @dev Emitted when new addresses are allowed or disallowed to fill /// orders with a given txOrigin. /// @param origin The address doing the allowing. /// @param addrs The address being allowed/disallowed. /// @param allowed Indicates whether the address should be allowed. - event RfqOrderOriginsAllowed( - address origin, - address[] addrs, - bool allowed - ); + event RfqOrderOriginsAllowed(address origin, address[] addrs, bool allowed); /// @dev Emitted when new order signers are registered /// @param maker The maker address that is registering a designated signer. /// @param signer The address that will sign on behalf of maker. /// @param allowed Indicates whether the address should be allowed. - event OrderSignerRegistered( - address maker, - address signer, - bool allowed - ); + event OrderSignerRegistered(address maker, address signer, bool allowed); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/INativeOrdersFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/INativeOrdersFeature.sol index 26a57c645d..4218bdd464 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/INativeOrdersFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/INativeOrdersFeature.sol @@ -25,17 +25,12 @@ import "../libs/LibSignature.sol"; import "../libs/LibNativeOrder.sol"; import "./INativeOrdersEvents.sol"; - /// @dev Feature for interacting with limit orders. -interface INativeOrdersFeature is - INativeOrdersEvents -{ - +interface INativeOrdersFeature is INativeOrdersEvents { /// @dev Transfers protocol fees from the `FeeCollector` pools into /// the staking contract. /// @param poolIds Staking pool IDs - function transferProtocolFeesForPools(bytes32[] calldata poolIds) - external; + function transferProtocolFeesForPools(bytes32[] calldata poolIds) external; /// @dev Fill a limit order. The taker and sender will be the caller. /// @param order The limit order. ETH protocol fees can be @@ -49,10 +44,7 @@ interface INativeOrdersFeature is LibNativeOrder.LimitOrder calldata order, LibSignature.Signature calldata signature, uint128 takerTokenFillAmount - ) - external - payable - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); + ) external payable returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); /// @dev Fill an RFQ order for up to `takerTokenFillAmount` taker tokens. /// The taker will be the caller. @@ -65,9 +57,7 @@ interface INativeOrdersFeature is LibNativeOrder.RfqOrder calldata order, LibSignature.Signature calldata signature, uint128 takerTokenFillAmount - ) - external - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); + ) external returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); /// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens. /// The taker will be the caller. ETH protocol fees can be @@ -81,10 +71,7 @@ interface INativeOrdersFeature is LibNativeOrder.LimitOrder calldata order, LibSignature.Signature calldata signature, uint128 takerTokenFillAmount - ) - external - payable - returns (uint128 makerTokenFilledAmount); + ) external payable returns (uint128 makerTokenFilledAmount); /// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens. /// The taker will be the caller. @@ -96,9 +83,7 @@ interface INativeOrdersFeature is LibNativeOrder.RfqOrder calldata order, LibSignature.Signature calldata signature, uint128 takerTokenFillAmount - ) - external - returns (uint128 makerTokenFilledAmount); + ) external returns (uint128 makerTokenFilledAmount); /// @dev Fill a limit order. Internal variant. ETH protocol fees can be /// attached to this call. Any unspent ETH will be refunded to @@ -116,10 +101,7 @@ interface INativeOrdersFeature is uint128 takerTokenFillAmount, address taker, address sender - ) - external - payable - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); + ) external payable returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); /// @dev Fill an RFQ order. Internal variant. /// @param order The RFQ order. @@ -138,40 +120,33 @@ interface INativeOrdersFeature is address taker, bool useSelfBalance, address recipient - ) - external - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); + ) external returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); /// @dev Cancel a single limit order. The caller must be the maker or a valid order signer. /// Silently succeeds if the order has already been cancelled. /// @param order The limit order. - function cancelLimitOrder(LibNativeOrder.LimitOrder calldata order) - external; + function cancelLimitOrder(LibNativeOrder.LimitOrder calldata order) external; /// @dev Cancel a single RFQ order. The caller must be the maker or a valid order signer. /// Silently succeeds if the order has already been cancelled. /// @param order The RFQ order. - function cancelRfqOrder(LibNativeOrder.RfqOrder calldata order) - external; + function cancelRfqOrder(LibNativeOrder.RfqOrder calldata order) external; /// @dev Mark what tx.origin addresses are allowed to fill an order that /// specifies the message sender as its txOrigin. /// @param origins An array of origin addresses to update. /// @param allowed True to register, false to unregister. - function registerAllowedRfqOrigins(address[] memory origins, bool allowed) - external; + function registerAllowedRfqOrigins(address[] memory origins, bool allowed) external; /// @dev Cancel multiple limit orders. The caller must be the maker or a valid order signer. /// Silently succeeds if the order has already been cancelled. /// @param orders The limit orders. - function batchCancelLimitOrders(LibNativeOrder.LimitOrder[] calldata orders) - external; + function batchCancelLimitOrders(LibNativeOrder.LimitOrder[] calldata orders) external; /// @dev Cancel multiple RFQ orders. The caller must be the maker or a valid order signer. /// Silently succeeds if the order has already been cancelled. /// @param orders The RFQ orders. - function batchCancelRfqOrders(LibNativeOrder.RfqOrder[] calldata orders) - external; + function batchCancelRfqOrders(LibNativeOrder.RfqOrder[] calldata orders) external; /// @dev Cancel all limit orders for a given maker and pair with a salt less /// than the value provided. The caller must be the maker. Subsequent @@ -184,8 +159,7 @@ interface INativeOrdersFeature is IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt - ) - external; + ) external; /// @dev Cancel all limit orders for a given maker and pair with a salt less /// than the value provided. The caller must be a signer registered to the maker. @@ -200,8 +174,7 @@ interface INativeOrdersFeature is IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt - ) - external; + ) external; /// @dev Cancel all limit orders for a given maker and pairs with salts less /// than the values provided. The caller must be the maker. Subsequent @@ -214,8 +187,7 @@ interface INativeOrdersFeature is IERC20TokenV06[] calldata makerTokens, IERC20TokenV06[] calldata takerTokens, uint256[] calldata minValidSalts - ) - external; + ) external; /// @dev Cancel all limit orders for a given maker and pairs with salts less /// than the values provided. The caller must be a signer registered to the maker. @@ -230,8 +202,7 @@ interface INativeOrdersFeature is IERC20TokenV06[] memory makerTokens, IERC20TokenV06[] memory takerTokens, uint256[] memory minValidSalts - ) - external; + ) external; /// @dev Cancel all RFQ orders for a given maker and pair with a salt less /// than the value provided. The caller must be the maker. Subsequent @@ -244,8 +215,7 @@ interface INativeOrdersFeature is IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt - ) - external; + ) external; /// @dev Cancel all RFQ orders for a given maker and pair with a salt less /// than the value provided. The caller must be a signer registered to the maker. @@ -260,8 +230,7 @@ interface INativeOrdersFeature is IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt - ) - external; + ) external; /// @dev Cancel all RFQ orders for a given maker and pairs with salts less /// than the values provided. The caller must be the maker. Subsequent @@ -274,8 +243,7 @@ interface INativeOrdersFeature is IERC20TokenV06[] calldata makerTokens, IERC20TokenV06[] calldata takerTokens, uint256[] calldata minValidSalts - ) - external; + ) external; /// @dev Cancel all RFQ orders for a given maker and pairs with salts less /// than the values provided. The caller must be a signer registered to the maker. @@ -290,8 +258,7 @@ interface INativeOrdersFeature is IERC20TokenV06[] memory makerTokens, IERC20TokenV06[] memory takerTokens, uint256[] memory minValidSalts - ) - external; + ) external; /// @dev Get the order info for a limit order. /// @param order The limit order. @@ -312,26 +279,17 @@ interface INativeOrdersFeature is /// @dev Get the canonical hash of a limit order. /// @param order The limit order. /// @return orderHash The order hash. - function getLimitOrderHash(LibNativeOrder.LimitOrder calldata order) - external - view - returns (bytes32 orderHash); + function getLimitOrderHash(LibNativeOrder.LimitOrder calldata order) external view returns (bytes32 orderHash); /// @dev Get the canonical hash of an RFQ order. /// @param order The RFQ order. /// @return orderHash The order hash. - function getRfqOrderHash(LibNativeOrder.RfqOrder calldata order) - external - view - returns (bytes32 orderHash); + function getRfqOrderHash(LibNativeOrder.RfqOrder calldata order) external view returns (bytes32 orderHash); /// @dev Get the protocol fee multiplier. This should be multiplied by the /// gas price to arrive at the required protocol fee to fill a native order. /// @return multiplier The protocol fee multiplier. - function getProtocolFeeMultiplier() - external - view - returns (uint32 multiplier); + function getProtocolFeeMultiplier() external view returns (uint32 multiplier); /// @dev Get order info, fillable amount, and signature validity for a limit order. /// Fillable amount is determined using balances and allowances of the maker. @@ -361,10 +319,7 @@ interface INativeOrdersFeature is /// @return actualFillableTakerTokenAmount How much of the order is fillable /// based on maker funds, in taker tokens. /// @return isSignatureValid Whether the signature is valid. - function getRfqOrderRelevantState( - LibNativeOrder.RfqOrder calldata order, - LibSignature.Signature calldata signature - ) + function getRfqOrderRelevantState(LibNativeOrder.RfqOrder calldata order, LibSignature.Signature calldata signature) external view returns ( @@ -419,20 +374,10 @@ interface INativeOrdersFeature is /// This allows one to sign on behalf of a contract that calls this function /// @param signer The address from which you plan to generate signatures /// @param allowed True to register, false to unregister. - function registerAllowedOrderSigner( - address signer, - bool allowed - ) - external; + function registerAllowedOrderSigner(address signer, bool allowed) external; /// @dev checks if a given address is registered to sign on behalf of a maker address /// @param maker The maker address encoded in an order (can be a contract) /// @param signer The address that is providing a signature - function isValidOrderSigner( - address maker, - address signer - ) - external - view - returns (bool isAllowed); + function isValidOrderSigner(address maker, address signer) external view returns (bool isAllowed); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IOtcOrdersFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IOtcOrdersFeature.sol index a8da27eaee..cf20ffb03a 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IOtcOrdersFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IOtcOrdersFeature.sol @@ -23,10 +23,8 @@ pragma experimental ABIEncoderV2; import "../libs/LibNativeOrder.sol"; import "../libs/LibSignature.sol"; - /// @dev Feature for interacting with OTC orders. interface IOtcOrdersFeature { - /// @dev Emitted whenever an `OtcOrder` is filled. /// @param orderHash The canonical hash of the order. /// @param maker The maker of the order. @@ -54,12 +52,10 @@ interface IOtcOrdersFeature { LibNativeOrder.OtcOrder calldata order, LibSignature.Signature calldata makerSignature, uint128 takerTokenFillAmount - ) - external - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); + ) external returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); /// @dev Fill an OTC order for up to `takerTokenFillAmount` taker tokens. - /// Unwraps bought WETH into ETH before sending it to + /// Unwraps bought WETH into ETH before sending it to /// the taker. /// @param order The OTC order. /// @param makerSignature The order signature from the maker. @@ -71,9 +67,7 @@ interface IOtcOrdersFeature { LibNativeOrder.OtcOrder calldata order, LibSignature.Signature calldata makerSignature, uint128 takerTokenFillAmount - ) - external - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); + ) external returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); /// @dev Fill an OTC order whose taker token is WETH for up /// to `msg.value`. @@ -81,10 +75,7 @@ interface IOtcOrdersFeature { /// @param makerSignature The order signature from the maker. /// @return takerTokenFilledAmount How much taker token was filled. /// @return makerTokenFilledAmount How much maker token was filled. - function fillOtcOrderWithEth( - LibNativeOrder.OtcOrder calldata order, - LibSignature.Signature calldata makerSignature - ) + function fillOtcOrderWithEth(LibNativeOrder.OtcOrder calldata order, LibSignature.Signature calldata makerSignature) external payable returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); @@ -98,12 +89,11 @@ interface IOtcOrdersFeature { LibNativeOrder.OtcOrder calldata order, LibSignature.Signature calldata makerSignature, LibSignature.Signature calldata takerSignature - ) - external; + ) external; /// @dev Fully fill an OTC order. "Meta-transaction" variant, /// requires order to be signed by both maker and taker. - /// Unwraps bought WETH into ETH before sending it to + /// Unwraps bought WETH into ETH before sending it to /// the taker. /// @param order The OTC order. /// @param makerSignature The order signature from the maker. @@ -112,15 +102,14 @@ interface IOtcOrdersFeature { LibNativeOrder.OtcOrder calldata order, LibSignature.Signature calldata makerSignature, LibSignature.Signature calldata takerSignature - ) - external; + ) external; /// @dev Fills multiple taker-signed OTC orders. /// @param orders Array of OTC orders. /// @param makerSignatures Array of maker signatures for each order. /// @param takerSignatures Array of taker signatures for each order. - /// @param unwrapWeth Array of booleans representing whether or not - /// to unwrap bought WETH into ETH for each order. Should be set + /// @param unwrapWeth Array of booleans representing whether or not + /// to unwrap bought WETH into ETH for each order. Should be set /// to false if the maker token is not WETH. /// @return successes Array of booleans representing whether or not /// each order in `orders` was filled successfully. @@ -129,9 +118,7 @@ interface IOtcOrdersFeature { LibSignature.Signature[] calldata makerSignatures, LibSignature.Signature[] calldata takerSignatures, bool[] calldata unwrapWeth - ) - external - returns (bool[] memory successes); + ) external returns (bool[] memory successes); /// @dev Fill an OTC order for up to `takerTokenFillAmount` taker tokens. /// Internal variant. @@ -152,9 +139,7 @@ interface IOtcOrdersFeature { address taker, bool useSelfBalance, address recipient - ) - external - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); + ) external returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); /// @dev Get the order info for an OTC order. /// @param order The OTC order. @@ -167,18 +152,12 @@ interface IOtcOrdersFeature { /// @dev Get the canonical hash of an OTC order. /// @param order The OTC order. /// @return orderHash The order hash. - function getOtcOrderHash(LibNativeOrder.OtcOrder calldata order) - external - view - returns (bytes32 orderHash); + function getOtcOrderHash(LibNativeOrder.OtcOrder calldata order) external view returns (bytes32 orderHash); /// @dev Get the last nonce used for a particular /// tx.origin address and nonce bucket. /// @param txOrigin The address. /// @param nonceBucket The nonce bucket index. /// @return lastNonce The last nonce value used. - function lastOtcTxOriginNonce(address txOrigin, uint64 nonceBucket) - external - view - returns (uint128 lastNonce); + function lastOtcTxOriginNonce(address txOrigin, uint64 nonceBucket) external view returns (uint128 lastNonce); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IOwnableFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IOwnableFeature.sol index e1f7b82981..6ab93d4643 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IOwnableFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IOwnableFeature.sol @@ -22,12 +22,9 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/interfaces/IOwnableV06.sol"; - // solhint-disable no-empty-blocks /// @dev Owner management and migration features. -interface IOwnableFeature is - IOwnableV06 -{ +interface IOwnableFeature is IOwnableV06 { /// @dev Emitted when `migrate()` is called. /// @param caller The caller of `migrate()`. /// @param migrator The migration contract. @@ -42,5 +39,9 @@ interface IOwnableFeature is /// @param target The migrator contract address. /// @param newOwner The address of the new owner. /// @param data The call data. - function migrate(address target, bytes calldata data, address newOwner) external; + function migrate( + address target, + bytes calldata data, + address newOwner + ) external; } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IPancakeSwapFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IPancakeSwapFeature.sol index ce906d73fc..7a193dab9e 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IPancakeSwapFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IPancakeSwapFeature.sol @@ -22,10 +22,8 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; - /// @dev VIP PancakeSwap (and forks) fill functions. interface IPancakeSwapFeature { - enum ProtocolFork { PancakeSwap, PancakeSwapV2, @@ -48,8 +46,5 @@ interface IPancakeSwapFeature { uint256 sellAmount, uint256 minBuyAmount, ProtocolFork fork - ) - external - payable - returns (uint256 buyAmount); + ) external payable returns (uint256 buyAmount); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/ISimpleFunctionRegistryFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/ISimpleFunctionRegistryFeature.sol index bd9b55cc95..537302f078 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/ISimpleFunctionRegistryFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/ISimpleFunctionRegistryFeature.sol @@ -20,10 +20,8 @@ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; - /// @dev Basic registry management features. interface ISimpleFunctionRegistryFeature { - /// @dev A function implementation was updated via `extend()` or `rollback()`. /// @param selector The function selector. /// @param oldImpl The implementation contract address being replaced. @@ -44,18 +42,12 @@ interface ISimpleFunctionRegistryFeature { /// @param selector The function selector. /// @return rollbackLength The number of items in the rollback history for /// the function. - function getRollbackLength(bytes4 selector) - external - view - returns (uint256 rollbackLength); + function getRollbackLength(bytes4 selector) external view returns (uint256 rollbackLength); /// @dev Retrieve an entry in the rollback history for a function. /// @param selector The function selector. /// @param idx The index in the rollback history. /// @return impl An implementation address for the function at /// index `idx`. - function getRollbackEntryAtIndex(bytes4 selector, uint256 idx) - external - view - returns (address impl); + function getRollbackEntryAtIndex(bytes4 selector, uint256 idx) external view returns (address impl); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/ITokenSpenderFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/ITokenSpenderFeature.sol index a64add16c0..11f16da8a1 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/ITokenSpenderFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/ITokenSpenderFeature.sol @@ -22,10 +22,8 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; - /// @dev Feature that allows spending token allowances. interface ITokenSpenderFeature { - /// @dev Transfers ERC20 tokens from `owner` to `to`. /// Only callable from within. /// @param token The token to spend. @@ -37,18 +35,14 @@ interface ITokenSpenderFeature { address owner, address to, uint256 amount - ) - external; + ) external; /// @dev Gets the maximum amount of an ERC20 token `token` that can be /// pulled from `owner`. /// @param token The token to spend. /// @param owner The owner of the tokens. /// @return amount The amount of tokens that can be pulled. - function getSpendableERC20BalanceOf(IERC20TokenV06 token, address owner) - external - view - returns (uint256 amount); + function getSpendableERC20BalanceOf(IERC20TokenV06 token, address owner) external view returns (uint256 amount); /// @dev Get the address of the allowance target. /// @return target The target of token allowances. diff --git a/contracts/zero-ex/contracts/src/features/interfaces/ITransformERC20Feature.sol b/contracts/zero-ex/contracts/src/features/interfaces/ITransformERC20Feature.sol index 93b00a2566..bbb42270f1 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/ITransformERC20Feature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/ITransformERC20Feature.sol @@ -24,10 +24,8 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../../transformers/IERC20Transformer.sol"; import "../../external/IFlashWallet.sol"; - /// @dev Feature to composably transform between ERC20 tokens. interface ITransformERC20Feature { - /// @dev Defines a transformation to run in `transformERC20()`. struct Transformation { // The deployment nonce for the transformer. @@ -93,22 +91,18 @@ interface ITransformERC20Feature { /// Only callable by the owner. /// @param transformerDeployer The address of the new trusted deployer /// for transformers. - function setTransformerDeployer(address transformerDeployer) - external; + function setTransformerDeployer(address transformerDeployer) external; /// @dev Replace the optional signer for `transformERC20()` calldata. /// Only callable by the owner. /// @param quoteSigner The address of the new calldata signer. - function setQuoteSigner(address quoteSigner) - external; + function setQuoteSigner(address quoteSigner) external; /// @dev Deploy a new flash wallet instance and replace the current one with it. /// Useful if we somehow break the current wallet instance. /// Only callable by the owner. /// @return wallet The new wallet instance. - function createTransformWallet() - external - returns (IFlashWallet wallet); + function createTransformWallet() external returns (IFlashWallet wallet); /// @dev Executes a series of transformations to convert an ERC20 `inputToken` /// to an ERC20 `outputToken`. @@ -128,38 +122,23 @@ interface ITransformERC20Feature { uint256 inputTokenAmount, uint256 minOutputTokenAmount, Transformation[] calldata transformations - ) - external - payable - returns (uint256 outputTokenAmount); + ) external payable returns (uint256 outputTokenAmount); /// @dev Internal version of `transformERC20()`. Only callable from within. /// @param args A `TransformERC20Args` struct. /// @return outputTokenAmount The amount of `outputToken` received by the taker. - function _transformERC20(TransformERC20Args calldata args) - external - payable - returns (uint256 outputTokenAmount); + function _transformERC20(TransformERC20Args calldata args) external payable returns (uint256 outputTokenAmount); /// @dev Return the current wallet instance that will serve as the execution /// context for transformations. /// @return wallet The wallet instance. - function getTransformWallet() - external - view - returns (IFlashWallet wallet); + function getTransformWallet() external view returns (IFlashWallet wallet); /// @dev Return the allowed deployer for transformers. /// @return deployer The transform deployer address. - function getTransformerDeployer() - external - view - returns (address deployer); + function getTransformerDeployer() external view returns (address deployer); /// @dev Return the optional signer for `transformERC20()` calldata. /// @return signer The transform deployer address. - function getQuoteSigner() - external - view - returns (address signer); + function getQuoteSigner() external view returns (address signer); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IUniswapFeature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IUniswapFeature.sol index 5fe26b0406..8500bec429 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IUniswapFeature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IUniswapFeature.sol @@ -22,10 +22,8 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; - /// @dev VIP uniswap fill functions. interface IUniswapFeature { - /// @dev Efficiently sell directly to uniswap/sushiswap. /// @param tokens Sell path. /// @param sellAmount of `tokens[0]` Amount to sell. @@ -37,8 +35,5 @@ interface IUniswapFeature { uint256 sellAmount, uint256 minBuyAmount, bool isSushi - ) - external - payable - returns (uint256 buyAmount); + ) external payable returns (uint256 buyAmount); } diff --git a/contracts/zero-ex/contracts/src/features/interfaces/IUniswapV3Feature.sol b/contracts/zero-ex/contracts/src/features/interfaces/IUniswapV3Feature.sol index 19d25ca5c0..6ce1b9f5b3 100644 --- a/contracts/zero-ex/contracts/src/features/interfaces/IUniswapV3Feature.sol +++ b/contracts/zero-ex/contracts/src/features/interfaces/IUniswapV3Feature.sol @@ -22,10 +22,8 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; - /// @dev VIP uniswap v3 fill functions. interface IUniswapV3Feature { - /// @dev Sell attached ETH directly against uniswap v3. /// @param encodedPath Uniswap-encoded path, where the first token is WETH. /// @param minBuyAmount Minimum amount of the last token in the path to buy. @@ -35,10 +33,7 @@ interface IUniswapV3Feature { bytes memory encodedPath, uint256 minBuyAmount, address recipient - ) - external - payable - returns (uint256 buyAmount); + ) external payable returns (uint256 buyAmount); /// @dev Sell a token for ETH directly against uniswap v3. /// @param encodedPath Uniswap-encoded path, where the last token is WETH. @@ -51,9 +46,7 @@ interface IUniswapV3Feature { uint256 sellAmount, uint256 minBuyAmount, address payable recipient - ) - external - returns (uint256 buyAmount); + ) external returns (uint256 buyAmount); /// @dev Sell a token for another token directly against uniswap v3. /// @param encodedPath Uniswap-encoded path. @@ -66,9 +59,7 @@ interface IUniswapV3Feature { uint256 sellAmount, uint256 minBuyAmount, address recipient - ) - external - returns (uint256 buyAmount); + ) external returns (uint256 buyAmount); /// @dev Sell a token for another token directly against uniswap v3. /// Private variant, uses tokens held by `address(this)`. @@ -82,9 +73,7 @@ interface IUniswapV3Feature { uint256 sellAmount, uint256 minBuyAmount, address recipient - ) - external - returns (uint256 buyAmount); + ) external returns (uint256 buyAmount); /// @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 @@ -97,6 +86,5 @@ interface IUniswapV3Feature { int256 amount0Delta, int256 amount1Delta, bytes calldata data - ) - external; + ) external; } diff --git a/contracts/zero-ex/contracts/src/features/libs/LibNFTOrder.sol b/contracts/zero-ex/contracts/src/features/libs/LibNFTOrder.sol index af23d9abc8..35a9f0d509 100644 --- a/contracts/zero-ex/contracts/src/features/libs/LibNFTOrder.sol +++ b/contracts/zero-ex/contracts/src/features/libs/LibNFTOrder.sol @@ -25,10 +25,8 @@ import "../../vendor/IERC1155Token.sol"; import "../../vendor/IERC721Token.sol"; import "../../vendor/IPropertyValidator.sol"; - /// @dev A library for common NFT order operations. library LibNFTOrder { - enum OrderStatus { INVALID, FILLABLE, @@ -176,8 +174,7 @@ library LibNFTOrder { // "bytes feeData", // ")" // )) - uint256 private constant _FEE_TYPEHASH = - 0xe68c29f1b4e8cce0bbcac76eb1334bdc1dc1f293a517c90e9e532340e1e94115; + uint256 private constant _FEE_TYPEHASH = 0xe68c29f1b4e8cce0bbcac76eb1334bdc1dc1f293a517c90e9e532340e1e94115; // keccak256(abi.encodePacked( // "Property(", @@ -185,8 +182,7 @@ library LibNFTOrder { // "bytes propertyData", // ")" // )) - uint256 private constant _PROPERTY_TYPEHASH = - 0x6292cf854241cb36887e639065eca63b3af9f7f70270cebeda4c29b6d3bc65e8; + uint256 private constant _PROPERTY_TYPEHASH = 0x6292cf854241cb36887e639065eca63b3af9f7f70270cebeda4c29b6d3bc65e8; // keccak256(""); bytes32 private constant _EMPTY_ARRAY_KECCAK256 = @@ -204,11 +200,7 @@ library LibNFTOrder { // ERC721Order and NFTOrder fields are aligned, so // we can safely cast an ERC721Order to an NFTOrder. - function asNFTOrder(ERC721Order memory erc721Order) - internal - pure - returns (NFTOrder memory nftOrder) - { + function asNFTOrder(ERC721Order memory erc721Order) internal pure returns (NFTOrder memory nftOrder) { assembly { nftOrder := erc721Order } @@ -218,11 +210,7 @@ library LibNFTOrder { // the exception of the last field `erc1155TokenAmount` // in ERC1155Order, so we can safely cast an ERC1155Order // to an NFTOrder. - function asNFTOrder(ERC1155Order memory erc1155Order) - internal - pure - returns (NFTOrder memory nftOrder) - { + function asNFTOrder(ERC1155Order memory erc1155Order) internal pure returns (NFTOrder memory nftOrder) { assembly { nftOrder := erc1155Order } @@ -230,11 +218,7 @@ library LibNFTOrder { // ERC721Order and NFTOrder fields are aligned, so // we can safely cast an MFTOrder to an ERC721Order. - function asERC721Order(NFTOrder memory nftOrder) - internal - pure - returns (ERC721Order memory erc721Order) - { + function asERC721Order(NFTOrder memory nftOrder) internal pure returns (ERC721Order memory erc721Order) { assembly { erc721Order := nftOrder } @@ -243,13 +227,7 @@ library LibNFTOrder { // NOTE: This is only safe if `nftOrder` was previously // cast from an `ERC1155Order` and the original // `erc1155TokenAmount` memory word has not been corrupted! - function asERC1155Order( - NFTOrder memory nftOrder - ) - internal - pure - returns (ERC1155Order memory erc1155Order) - { + function asERC1155Order(NFTOrder memory nftOrder) internal pure returns (ERC1155Order memory erc1155Order) { assembly { erc1155Order := nftOrder } @@ -258,11 +236,7 @@ library LibNFTOrder { /// @dev Get the struct hash of an ERC721 order. /// @param order The ERC721 order. /// @return structHash The struct hash of the order. - function getERC721OrderStructHash(ERC721Order memory order) - internal - pure - returns (bytes32 structHash) - { + function getERC721OrderStructHash(ERC721Order memory order) internal pure returns (bytes32 structHash) { bytes32 propertiesHash = _propertiesHash(order.erc721TokenProperties); bytes32 feesHash = _feesHash(order.fees); @@ -282,7 +256,9 @@ library LibNFTOrder { // propertiesHash // )); assembly { - if lt(order, 32) { invalid() } // Don't underflow memory. + if lt(order, 32) { + invalid() + } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 224) // order + (32 * 7) @@ -295,7 +271,10 @@ library LibNFTOrder { mstore(typeHashPos, _ERC_721_ORDER_TYPEHASH) mstore(feesHashPos, feesHash) mstore(propertiesHashPos, propertiesHash) - structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ ) + structHash := keccak256( + typeHashPos, + 384 /* 32 * 12 */ + ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feeHashMemBefore) @@ -307,11 +286,7 @@ library LibNFTOrder { /// @dev Get the struct hash of an ERC1155 order. /// @param order The ERC1155 order. /// @return structHash The struct hash of the order. - function getERC1155OrderStructHash(ERC1155Order memory order) - internal - pure - returns (bytes32 structHash) - { + function getERC1155OrderStructHash(ERC1155Order memory order) internal pure returns (bytes32 structHash) { bytes32 propertiesHash = _propertiesHash(order.erc1155TokenProperties); bytes32 feesHash = _feesHash(order.fees); @@ -332,7 +307,9 @@ library LibNFTOrder { // order.erc1155TokenAmount // )); assembly { - if lt(order, 32) { invalid() } // Don't underflow memory. + if lt(order, 32) { + invalid() + } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 224) // order + (32 * 7) @@ -345,7 +322,10 @@ library LibNFTOrder { mstore(typeHashPos, _ERC_1155_ORDER_TYPEHASH) mstore(feesHashPos, feesHash) mstore(propertiesHashPos, propertiesHash) - structHash := keccak256(typeHashPos, 416 /* 32 * 12 */ ) + structHash := keccak256( + typeHashPos, + 416 /* 32 * 12 */ + ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feesHashMemBefore) @@ -356,11 +336,7 @@ library LibNFTOrder { // Hashes the `properties` array as part of computing the // EIP-712 hash of an `ERC721Order` or `ERC1155Order`. - function _propertiesHash(Property[] memory properties) - private - pure - returns (bytes32 propertiesHash) - { + function _propertiesHash(Property[] memory properties) private pure returns (bytes32 propertiesHash) { uint256 numProperties = properties.length; // We give `properties.length == 0` and `properties.length == 1` // special treatment because we expect these to be the most common. @@ -368,10 +344,7 @@ library LibNFTOrder { propertiesHash = _EMPTY_ARRAY_KECCAK256; } else if (numProperties == 1) { Property memory property = properties[0]; - if ( - address(property.propertyValidator) == address(0) && - property.propertyData.length == 0 - ) { + if (address(property.propertyValidator) == address(0) && property.propertyData.length == 0) { propertiesHash = _NULL_PROPERTY_STRUCT_HASH; } else { // propertiesHash = keccak256(abi.encodePacked(keccak256(abi.encode( @@ -395,11 +368,13 @@ library LibNFTOrder { } else { bytes32[] memory propertyStructHashArray = new bytes32[](numProperties); for (uint256 i = 0; i < numProperties; i++) { - propertyStructHashArray[i] = keccak256(abi.encode( - _PROPERTY_TYPEHASH, - properties[i].propertyValidator, - keccak256(properties[i].propertyData) - )); + propertyStructHashArray[i] = keccak256( + abi.encode( + _PROPERTY_TYPEHASH, + properties[i].propertyValidator, + keccak256(properties[i].propertyData) + ) + ); } assembly { propertiesHash := keccak256(add(propertyStructHashArray, 32), mul(numProperties, 32)) @@ -409,11 +384,7 @@ library LibNFTOrder { // Hashes the `fees` array as part of computing the // EIP-712 hash of an `ERC721Order` or `ERC1155Order`. - function _feesHash(Fee[] memory fees) - private - pure - returns (bytes32 feesHash) - { + function _feesHash(Fee[] memory fees) private pure returns (bytes32 feesHash) { uint256 numFees = fees.length; // We give `fees.length == 0` and `fees.length == 1` // special treatment because we expect these to be the most common. @@ -444,12 +415,9 @@ library LibNFTOrder { } else { bytes32[] memory feeStructHashArray = new bytes32[](numFees); for (uint256 i = 0; i < numFees; i++) { - feeStructHashArray[i] = keccak256(abi.encode( - _FEE_TYPEHASH, - fees[i].recipient, - fees[i].amount, - keccak256(fees[i].feeData) - )); + feeStructHashArray[i] = keccak256( + abi.encode(_FEE_TYPEHASH, fees[i].recipient, fees[i].amount, keccak256(fees[i].feeData)) + ); } assembly { feesHash := keccak256(add(feeStructHashArray, 32), mul(numFees, 32)) diff --git a/contracts/zero-ex/contracts/src/features/libs/LibNativeOrder.sol b/contracts/zero-ex/contracts/src/features/libs/LibNativeOrder.sol index 7179772451..8a54bb626c 100644 --- a/contracts/zero-ex/contracts/src/features/libs/LibNativeOrder.sol +++ b/contracts/zero-ex/contracts/src/features/libs/LibNativeOrder.sol @@ -25,7 +25,6 @@ import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "../../errors/LibNativeOrdersRichErrors.sol"; - /// @dev A library for common native order operations. library LibNativeOrder { using LibSafeMathV06 for uint256; @@ -115,8 +114,7 @@ library LibNativeOrder { // "uint256 salt" // ")" // )) - uint256 private constant _LIMIT_ORDER_TYPEHASH = - 0xce918627cb55462ddbb85e73de69a8b322f2bc88f4507c52fcad6d4c33c29d49; + uint256 private constant _LIMIT_ORDER_TYPEHASH = 0xce918627cb55462ddbb85e73de69a8b322f2bc88f4507c52fcad6d4c33c29d49; // The type hash for RFQ orders, which is: // keccak256(abi.encodePacked( @@ -133,8 +131,7 @@ library LibNativeOrder { // "uint256 salt" // ")" // )) - uint256 private constant _RFQ_ORDER_TYPEHASH = - 0xe593d3fdfa8b60e5e17a1b2204662ecbe15c23f2084b9ad5bae40359540a7da9; + uint256 private constant _RFQ_ORDER_TYPEHASH = 0xe593d3fdfa8b60e5e17a1b2204662ecbe15c23f2084b9ad5bae40359540a7da9; // The type hash for OTC orders, which is: // keccak256(abi.encodePacked( @@ -149,17 +146,12 @@ library LibNativeOrder { // "uint256 expiryAndNonce" // ")" // )) - uint256 private constant _OTC_ORDER_TYPEHASH = - 0x2f754524de756ae72459efbe1ec88c19a745639821de528ac3fb88f9e65e35c8; + uint256 private constant _OTC_ORDER_TYPEHASH = 0x2f754524de756ae72459efbe1ec88c19a745639821de528ac3fb88f9e65e35c8; /// @dev Get the struct hash of a limit order. /// @param order The limit order. /// @return structHash The struct hash of the order. - function getLimitOrderStructHash(LimitOrder memory order) - internal - pure - returns (bytes32 structHash) - { + function getLimitOrderStructHash(LimitOrder memory order) internal pure returns (bytes32 structHash) { // The struct hash is: // keccak256(abi.encode( // TYPE_HASH, @@ -210,11 +202,7 @@ library LibNativeOrder { /// @dev Get the struct hash of a RFQ order. /// @param order The RFQ order. /// @return structHash The struct hash of the order. - function getRfqOrderStructHash(RfqOrder memory order) - internal - pure - returns (bytes32 structHash) - { + function getRfqOrderStructHash(RfqOrder memory order) internal pure returns (bytes32 structHash) { // The struct hash is: // keccak256(abi.encode( // TYPE_HASH, @@ -259,11 +247,7 @@ library LibNativeOrder { /// @dev Get the struct hash of an OTC order. /// @param order The OTC order. /// @return structHash The struct hash of the order. - function getOtcOrderStructHash(OtcOrder memory order) - internal - pure - returns (bytes32 structHash) - { + function getOtcOrderStructHash(OtcOrder memory order) internal pure returns (bytes32 structHash) { // The struct hash is: // keccak256(abi.encode( // TYPE_HASH, @@ -301,19 +285,12 @@ library LibNativeOrder { /// @dev Refund any leftover protocol fees in `msg.value` to `msg.sender`. /// @param ethProtocolFeePaid How much ETH was paid in protocol fees. - function refundExcessProtocolFeeToSender(uint256 ethProtocolFeePaid) - internal - { + function refundExcessProtocolFeeToSender(uint256 ethProtocolFeePaid) internal { if (msg.value > ethProtocolFeePaid && msg.sender != address(this)) { uint256 refundAmount = msg.value.safeSub(ethProtocolFeePaid); - (bool success,) = msg - .sender - .call{value: refundAmount}(""); + (bool success, ) = msg.sender.call{value: refundAmount}(""); if (!success) { - LibNativeOrdersRichErrors.ProtocolFeeRefundFailed( - msg.sender, - refundAmount - ).rrevert(); + LibNativeOrdersRichErrors.ProtocolFeeRefundFailed(msg.sender, refundAmount).rrevert(); } } } diff --git a/contracts/zero-ex/contracts/src/features/libs/LibSignature.sol b/contracts/zero-ex/contracts/src/features/libs/LibSignature.sol index 91e1b0a3fd..2c3873d7a0 100644 --- a/contracts/zero-ex/contracts/src/features/libs/LibSignature.sol +++ b/contracts/zero-ex/contracts/src/features/libs/LibSignature.sol @@ -23,14 +23,12 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../../errors/LibSignatureRichErrors.sol"; - /// @dev A library for validating signatures. library LibSignature { using LibRichErrorsV06 for bytes; // '\x19Ethereum Signed Message:\n32\x00\x00\x00\x00' in a word. - uint256 private constant ETH_SIGN_HASH_PREFIX = - 0x19457468657265756d205369676e6564204d6573736167653a0a333200000000; + uint256 private constant ETH_SIGN_HASH_PREFIX = 0x19457468657265756d205369676e6564204d6573736167653a0a333200000000; /// @dev Exclusive upper limit on ECDSA signatures 'R' values. /// The valid range is given by fig (282) of the yellow paper. uint256 private constant ECDSA_SIGNATURE_R_LIMIT = @@ -65,25 +63,13 @@ library LibSignature { /// @param hash The hash that was signed. /// @param signature The signature. /// @return recovered The recovered signer address. - function getSignerOfHash( - bytes32 hash, - Signature memory signature - ) - internal - pure - returns (address recovered) - { + function getSignerOfHash(bytes32 hash, Signature memory signature) internal pure returns (address recovered) { // Ensure this is a signature type that can be validated against a hash. _validateHashCompatibleSignature(hash, signature); if (signature.signatureType == SignatureType.EIP712) { // Signed using EIP712 - recovered = ecrecover( - hash, - signature.v, - signature.r, - signature.s - ); + recovered = ecrecover(hash, signature.v, signature.r, signature.s); } else if (signature.signatureType == SignatureType.ETHSIGN) { // Signed using `eth_sign` // Need to hash `hash` with "\x19Ethereum Signed Message:\n32" prefix @@ -95,65 +81,47 @@ library LibSignature { mstore(28, hash) // length of 32 bytes ethSignHash := keccak256(0, 60) } - recovered = ecrecover( - ethSignHash, - signature.v, - signature.r, - signature.s - ); + recovered = ecrecover(ethSignHash, signature.v, signature.r, signature.s); } // `recovered` can be null if the signature values are out of range. if (recovered == address(0)) { - LibSignatureRichErrors.SignatureValidationError( - LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA, - hash - ).rrevert(); + LibSignatureRichErrors + .SignatureValidationError(LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA, hash) + .rrevert(); } } /// @dev Validates that a signature is compatible with a hash signee. /// @param hash The hash that was signed. /// @param signature The signature. - function _validateHashCompatibleSignature( - bytes32 hash, - Signature memory signature - ) - private - pure - { + function _validateHashCompatibleSignature(bytes32 hash, Signature memory signature) private pure { // Ensure the r and s are within malleability limits. - if (uint256(signature.r) >= ECDSA_SIGNATURE_R_LIMIT || - uint256(signature.s) >= ECDSA_SIGNATURE_S_LIMIT) - { - LibSignatureRichErrors.SignatureValidationError( - LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA, - hash - ).rrevert(); + if (uint256(signature.r) >= ECDSA_SIGNATURE_R_LIMIT || uint256(signature.s) >= ECDSA_SIGNATURE_S_LIMIT) { + LibSignatureRichErrors + .SignatureValidationError(LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA, hash) + .rrevert(); } // Always illegal signature. if (signature.signatureType == SignatureType.ILLEGAL) { - LibSignatureRichErrors.SignatureValidationError( - LibSignatureRichErrors.SignatureValidationErrorCodes.ILLEGAL, - hash - ).rrevert(); + LibSignatureRichErrors + .SignatureValidationError(LibSignatureRichErrors.SignatureValidationErrorCodes.ILLEGAL, hash) + .rrevert(); } // Always invalid. if (signature.signatureType == SignatureType.INVALID) { - LibSignatureRichErrors.SignatureValidationError( - LibSignatureRichErrors.SignatureValidationErrorCodes.ALWAYS_INVALID, - hash - ).rrevert(); + LibSignatureRichErrors + .SignatureValidationError(LibSignatureRichErrors.SignatureValidationErrorCodes.ALWAYS_INVALID, hash) + .rrevert(); } - // If a feature supports pre-signing, it wouldn't use + // If a feature supports pre-signing, it wouldn't use // `getSignerOfHash` on a pre-signed order. if (signature.signatureType == SignatureType.PRESIGNED) { - LibSignatureRichErrors.SignatureValidationError( - LibSignatureRichErrors.SignatureValidationErrorCodes.UNSUPPORTED, - hash - ).rrevert(); + LibSignatureRichErrors + .SignatureValidationError(LibSignatureRichErrors.SignatureValidationErrorCodes.UNSUPPORTED, hash) + .rrevert(); } // Solidity should check that the signature type is within enum range for us diff --git a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexFeature.sol b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexFeature.sol index a300f41a00..2f2671c942 100644 --- a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexFeature.sol +++ b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexFeature.sol @@ -36,7 +36,6 @@ import "./MultiplexTransformERC20.sol"; import "./MultiplexUniswapV2.sol"; import "./MultiplexUniswapV3.sol"; - /// @dev This feature enables efficient batch and multi-hop trades /// using different liquidity sources. contract MultiplexFeature is @@ -55,7 +54,7 @@ contract MultiplexFeature is /// @dev Version of this feature. uint256 public immutable override FEATURE_VERSION = _encodeVersion(2, 0, 0); /// @dev The highest bit of a uint256 value. - uint256 private constant HIGH_BIT = 2 ** 255; + uint256 private constant HIGH_BIT = 2**255; /// @dev Mask of the lower 255 bits of a uint256 value. uint256 private constant LOWER_255_BITS = HIGH_BIT - 1; @@ -74,12 +73,7 @@ contract MultiplexFeature is public FixinEIP712(zeroExAddress) MultiplexLiquidityProvider(sandbox) - MultiplexUniswapV2( - uniswapFactory, - sushiswapFactory, - uniswapPairInitCodeHash, - sushiswapPairInitCodeHash - ) + MultiplexUniswapV2(uniswapFactory, sushiswapFactory, uniswapPairInitCodeHash, sushiswapPairInitCodeHash) { WETH = weth; } @@ -87,10 +81,7 @@ contract MultiplexFeature is /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. - function migrate() - external - returns (bytes4 success) - { + function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.multiplexBatchSellEthForToken.selector); _registerFeatureFunction(this.multiplexBatchSellTokenForEth.selector); _registerFeatureFunction(this.multiplexBatchSellTokenForToken.selector); @@ -111,27 +102,23 @@ contract MultiplexFeature is IERC20TokenV06 outputToken, BatchSellSubcall[] memory calls, uint256 minBuyAmount - ) - public - override - payable - returns (uint256 boughtAmount) - { + ) public payable override returns (uint256 boughtAmount) { // Wrap ETH. WETH.deposit{value: msg.value}(); // WETH is now held by this contract, // so `useSelfBalance` is true. - return _multiplexBatchSell( - BatchSellParams({ - inputToken: WETH, - outputToken: outputToken, - sellAmount: msg.value, - calls: calls, - useSelfBalance: true, - recipient: msg.sender - }), - minBuyAmount - ); + return + _multiplexBatchSell( + BatchSellParams({ + inputToken: WETH, + outputToken: outputToken, + sellAmount: msg.value, + calls: calls, + useSelfBalance: true, + recipient: msg.sender + }), + minBuyAmount + ); } /// @dev Sells `sellAmount` of the given `inputToken` for ETH @@ -147,11 +134,7 @@ contract MultiplexFeature is BatchSellSubcall[] memory calls, uint256 sellAmount, uint256 minBuyAmount - ) - public - override - returns (uint256 boughtAmount) - { + ) public override returns (uint256 boughtAmount) { // The outputToken is implicitly WETH. The `recipient` // of the WETH is set to this contract, since we // must unwrap the WETH and transfer the resulting ETH. @@ -187,22 +170,19 @@ contract MultiplexFeature is BatchSellSubcall[] memory calls, uint256 sellAmount, uint256 minBuyAmount - ) - public - override - returns (uint256 boughtAmount) - { - return _multiplexBatchSell( - BatchSellParams({ - inputToken: inputToken, - outputToken: outputToken, - sellAmount: sellAmount, - calls: calls, - useSelfBalance: false, - recipient: msg.sender - }), - minBuyAmount - ); + ) public override returns (uint256 boughtAmount) { + return + _multiplexBatchSell( + BatchSellParams({ + inputToken: inputToken, + outputToken: outputToken, + sellAmount: sellAmount, + calls: calls, + useSelfBalance: false, + recipient: msg.sender + }), + minBuyAmount + ); } /// @dev Executes a batch sell and checks that at least @@ -211,10 +191,7 @@ contract MultiplexFeature is /// @param minBuyAmount The minimum amount of `outputToken` that /// must be bought for this function to not revert. /// @return boughtAmount The amount of `outputToken` bought. - function _multiplexBatchSell( - BatchSellParams memory params, - uint256 minBuyAmount - ) + function _multiplexBatchSell(BatchSellParams memory params, uint256 minBuyAmount) private returns (uint256 boughtAmount) { @@ -223,16 +200,12 @@ contract MultiplexFeature is // Execute the batch sell. BatchSellState memory state = _executeBatchSell(params); // Compute the change in balance of the output token. - uint256 balanceDelta = params.outputToken.balanceOf(params.recipient) - .safeSub(balanceBefore); + uint256 balanceDelta = params.outputToken.balanceOf(params.recipient).safeSub(balanceBefore); // Use the minimum of the balanceDelta and the returned bought // amount in case of weird tokens and whatnot. boughtAmount = LibSafeMathV06.min256(balanceDelta, state.boughtAmount); // Enforce `minBuyAmount`. - require( - boughtAmount >= minBuyAmount, - "MultiplexFeature::_multiplexBatchSell/UNDERBOUGHT" - ); + require(boughtAmount >= minBuyAmount, "MultiplexFeature::_multiplexBatchSell/UNDERBOUGHT"); } /// @dev Sells attached ETH via the given sequence of tokens @@ -250,31 +223,24 @@ contract MultiplexFeature is address[] memory tokens, MultiHopSellSubcall[] memory calls, uint256 minBuyAmount - ) - public - override - payable - returns (uint256 boughtAmount) - { + ) public payable override returns (uint256 boughtAmount) { // First token must be WETH. - require( - tokens[0] == address(WETH), - "MultiplexFeature::multiplexMultiHopSellEthForToken/NOT_WETH" - ); + require(tokens[0] == address(WETH), "MultiplexFeature::multiplexMultiHopSellEthForToken/NOT_WETH"); // Wrap ETH. WETH.deposit{value: msg.value}(); // WETH is now held by this contract, // so `useSelfBalance` is true. - return _multiplexMultiHopSell( - MultiHopSellParams({ - tokens: tokens, - sellAmount: msg.value, - calls: calls, - useSelfBalance: true, - recipient: msg.sender - }), - minBuyAmount - ); + return + _multiplexMultiHopSell( + MultiHopSellParams({ + tokens: tokens, + sellAmount: msg.value, + calls: calls, + useSelfBalance: true, + recipient: msg.sender + }), + minBuyAmount + ); } /// @dev Sells `sellAmount` of the input token (`tokens[0]`) @@ -293,11 +259,7 @@ contract MultiplexFeature is MultiHopSellSubcall[] memory calls, uint256 sellAmount, uint256 minBuyAmount - ) - public - override - returns (uint256 boughtAmount) - { + ) public override returns (uint256 boughtAmount) { // Last token must be WETH. require( tokens[tokens.length - 1] == address(WETH), @@ -338,21 +300,18 @@ contract MultiplexFeature is MultiHopSellSubcall[] memory calls, uint256 sellAmount, uint256 minBuyAmount - ) - public - override - returns (uint256 boughtAmount) - { - return _multiplexMultiHopSell( - MultiHopSellParams({ - tokens: tokens, - sellAmount: sellAmount, - calls: calls, - useSelfBalance: false, - recipient: msg.sender - }), - minBuyAmount - ); + ) public override returns (uint256 boughtAmount) { + return + _multiplexMultiHopSell( + MultiHopSellParams({ + tokens: tokens, + sellAmount: sellAmount, + calls: calls, + useSelfBalance: false, + recipient: msg.sender + }), + minBuyAmount + ); } /// @dev Executes a multi-hop sell and checks that at least @@ -361,10 +320,7 @@ contract MultiplexFeature is /// @param minBuyAmount The minimum amount of output tokens that /// must be bought for this function to not revert. /// @return boughtAmount The amount of output tokens bought. - function _multiplexMultiHopSell( - MultiHopSellParams memory params, - uint256 minBuyAmount - ) + function _multiplexMultiHopSell(MultiHopSellParams memory params, uint256 minBuyAmount) private returns (uint256 boughtAmount) { @@ -376,24 +332,18 @@ contract MultiplexFeature is "MultiplexFeature::_multiplexMultiHopSell/MISMATCHED_ARRAY_LENGTHS" ); // The output token is the last token in the path. - IERC20TokenV06 outputToken = IERC20TokenV06( - params.tokens[params.tokens.length - 1] - ); + IERC20TokenV06 outputToken = IERC20TokenV06(params.tokens[params.tokens.length - 1]); // Cache the recipient's balance of the output token. uint256 balanceBefore = outputToken.balanceOf(params.recipient); // Execute the multi-hop sell. MultiHopSellState memory state = _executeMultiHopSell(params); // Compute the change in balance of the output token. - uint256 balanceDelta = outputToken.balanceOf(params.recipient) - .safeSub(balanceBefore); + uint256 balanceDelta = outputToken.balanceOf(params.recipient).safeSub(balanceBefore); // Use the minimum of the balanceDelta and the returned bought // amount in case of weird tokens and whatnot. boughtAmount = LibSafeMathV06.min256(balanceDelta, state.outputTokenAmount); // Enforce `minBuyAmount`. - require( - boughtAmount >= minBuyAmount, - "MultiplexFeature::_multiplexMultiHopSell/UNDERBOUGHT" - ); + require(boughtAmount >= minBuyAmount, "MultiplexFeature::_multiplexMultiHopSell/UNDERBOUGHT"); } /// @dev Iterates through the constituent calls of a batch @@ -402,87 +352,41 @@ contract MultiplexFeature is /// @param params Batch sell parameters. /// @return state A struct containing the amounts of `inputToken` /// sold and `outputToken` bought. - function _executeBatchSell(BatchSellParams memory params) - private - returns (BatchSellState memory state) - { + function _executeBatchSell(BatchSellParams memory params) private returns (BatchSellState memory state) { // Iterate through the calls and execute each one // until the full amount has been sold. for (uint256 i = 0; i != params.calls.length; i++) { // Check if we've hit our target. - if (state.soldAmount >= params.sellAmount) { break; } + if (state.soldAmount >= params.sellAmount) { + break; + } BatchSellSubcall memory subcall = params.calls[i]; // Compute the input token amount. - uint256 inputTokenAmount = _normalizeSellAmount( - subcall.sellAmount, - params.sellAmount, - state.soldAmount - ); + uint256 inputTokenAmount = _normalizeSellAmount(subcall.sellAmount, params.sellAmount, state.soldAmount); if (subcall.id == MultiplexSubcall.RFQ) { - _batchSellRfqOrder( - state, - params, - subcall.data, - inputTokenAmount - ); + _batchSellRfqOrder(state, params, subcall.data, inputTokenAmount); } else if (subcall.id == MultiplexSubcall.OTC) { - _batchSellOtcOrder( - state, - params, - subcall.data, - inputTokenAmount - ); + _batchSellOtcOrder(state, params, subcall.data, inputTokenAmount); } else if (subcall.id == MultiplexSubcall.UniswapV2) { - _batchSellUniswapV2( - state, - params, - subcall.data, - inputTokenAmount - ); + _batchSellUniswapV2(state, params, subcall.data, inputTokenAmount); } else if (subcall.id == MultiplexSubcall.UniswapV3) { - _batchSellUniswapV3( - state, - params, - subcall.data, - inputTokenAmount - ); + _batchSellUniswapV3(state, params, subcall.data, inputTokenAmount); } else if (subcall.id == MultiplexSubcall.LiquidityProvider) { - _batchSellLiquidityProvider( - state, - params, - subcall.data, - inputTokenAmount - ); + _batchSellLiquidityProvider(state, params, subcall.data, inputTokenAmount); } else if (subcall.id == MultiplexSubcall.TransformERC20) { - _batchSellTransformERC20( - state, - params, - subcall.data, - inputTokenAmount - ); + _batchSellTransformERC20(state, params, subcall.data, inputTokenAmount); } else if (subcall.id == MultiplexSubcall.MultiHopSell) { - _nestedMultiHopSell( - state, - params, - subcall.data, - inputTokenAmount - ); + _nestedMultiHopSell(state, params, subcall.data, inputTokenAmount); } else { revert("MultiplexFeature::_executeBatchSell/INVALID_SUBCALL"); } } - require( - state.soldAmount == params.sellAmount, - "MultiplexFeature::_executeBatchSell/INCORRECT_AMOUNT_SOLD" - ); + require(state.soldAmount == params.sellAmount, "MultiplexFeature::_executeBatchSell/INCORRECT_AMOUNT_SOLD"); } // This function executes a sequence of fills "hopping" through the // path of tokens given by `params.tokens`. - function _executeMultiHopSell(MultiHopSellParams memory params) - private - returns (MultiHopSellState memory state) - { + function _executeMultiHopSell(MultiHopSellParams memory params) private returns (MultiHopSellState memory state) { // This variable is used for the input and output amounts of // each hop. After the final hop, this will contain the output // amount of the multi-hop fill. @@ -495,21 +399,12 @@ contract MultiplexFeature is // If the input tokens are currently held by `msg.sender` but // the first hop expects them elsewhere, perform a `transferFrom`. if (!params.useSelfBalance && state.from != msg.sender) { - _transferERC20TokensFrom( - IERC20TokenV06(params.tokens[0]), - msg.sender, - state.from, - params.sellAmount - ); + _transferERC20TokensFrom(IERC20TokenV06(params.tokens[0]), msg.sender, state.from, params.sellAmount); } // If the input tokens are currently held by `address(this)` but // the first hop expects them elsewhere, perform a `transfer`. if (params.useSelfBalance && state.from != address(this)) { - _transferERC20Tokens( - IERC20TokenV06(params.tokens[0]), - state.from, - params.sellAmount - ); + _transferERC20Tokens(IERC20TokenV06(params.tokens[0]), state.from, params.sellAmount); } // Iterate through the calls and execute each one. for (state.hopIndex = 0; state.hopIndex != params.calls.length; state.hopIndex++) { @@ -519,25 +414,13 @@ contract MultiplexFeature is state.to = _computeHopTarget(params, state.hopIndex + 1); if (subcall.id == MultiplexSubcall.UniswapV2) { - _multiHopSellUniswapV2( - state, - params, - subcall.data - ); + _multiHopSellUniswapV2(state, params, subcall.data); } else if (subcall.id == MultiplexSubcall.UniswapV3) { _multiHopSellUniswapV3(state, subcall.data); } else if (subcall.id == MultiplexSubcall.LiquidityProvider) { - _multiHopSellLiquidityProvider( - state, - params, - subcall.data - ); + _multiHopSellLiquidityProvider(state, params, subcall.data); } else if (subcall.id == MultiplexSubcall.BatchSell) { - _nestedBatchSell( - state, - params, - subcall.data - ); + _nestedBatchSell(state, params, subcall.data); } else { revert("MultiplexFeature::_executeMultiHopSell/INVALID_SUBCALL"); } @@ -552,19 +435,11 @@ contract MultiplexFeature is IMultiplexFeature.BatchSellParams memory params, bytes memory data, uint256 sellAmount - ) - private - { + ) private { MultiHopSellParams memory multiHopParams; // Decode the tokens and calls for the nested // multi-hop sell. - ( - multiHopParams.tokens, - multiHopParams.calls - ) = abi.decode( - data, - (address[], MultiHopSellSubcall[]) - ); + (multiHopParams.tokens, multiHopParams.calls) = abi.decode(data, (address[], MultiHopSellSubcall[])); multiHopParams.sellAmount = sellAmount; // If the batch sell is using input tokens held by // `address(this)`, then so should the nested @@ -574,8 +449,7 @@ contract MultiplexFeature is // equal to the recipient of its containing batch sell. multiHopParams.recipient = params.recipient; // Execute the nested multi-hop sell. - uint256 outputTokenAmount = - _executeMultiHopSell(multiHopParams).outputTokenAmount; + uint256 outputTokenAmount = _executeMultiHopSell(multiHopParams).outputTokenAmount; // Increment the sold and bought amounts. state.soldAmount = state.soldAmount.safeAdd(sellAmount); state.boughtAmount = state.boughtAmount.safeAdd(outputTokenAmount); @@ -585,24 +459,15 @@ contract MultiplexFeature is IMultiplexFeature.MultiHopSellState memory state, IMultiplexFeature.MultiHopSellParams memory params, bytes memory data - ) - private - { + ) private { BatchSellParams memory batchSellParams; // Decode the calls for the nested batch sell. - batchSellParams.calls = abi.decode( - data, - (BatchSellSubcall[]) - ); + batchSellParams.calls = abi.decode(data, (BatchSellSubcall[])); // The input and output tokens of the batch // sell are the current and next tokens in // `params.tokens`, respectively. - batchSellParams.inputToken = IERC20TokenV06( - params.tokens[state.hopIndex] - ); - batchSellParams.outputToken = IERC20TokenV06( - params.tokens[state.hopIndex + 1] - ); + batchSellParams.inputToken = IERC20TokenV06(params.tokens[state.hopIndex]); + batchSellParams.outputToken = IERC20TokenV06(params.tokens[state.hopIndex + 1]); // The `sellAmount` for the batch sell is the // `outputTokenAmount` from the previous hop. batchSellParams.sellAmount = state.outputTokenAmount; @@ -618,8 +483,7 @@ contract MultiplexFeature is // batch sell. batchSellParams.recipient = state.to; // Execute the nested batch sell. - state.outputTokenAmount = - _executeBatchSell(batchSellParams).boughtAmount; + state.outputTokenAmount = _executeBatchSell(batchSellParams).boughtAmount; } // This function computes the "target" address of hop index `i` within @@ -627,14 +491,7 @@ contract MultiplexFeature is // If `i == 0`, the target is the address which should hold the input // tokens prior to executing `calls[0]`. Otherwise, it is the address // that should receive `tokens[i]` upon executing `calls[i-1]`. - function _computeHopTarget( - MultiHopSellParams memory params, - uint256 i - ) - private - view - returns (address target) - { + function _computeHopTarget(MultiHopSellParams memory params, uint256 i) private view returns (address target) { if (i == params.calls.length) { // The last call should send the output tokens to the // multi-hop sell recipient. @@ -645,28 +502,15 @@ contract MultiplexFeature is // UniswapV2 (and Sushiswap) allow tokens to be // transferred into the pair contract before `swap` // is called, so we compute the pair contract's address. - (address[] memory tokens, bool isSushi) = abi.decode( - subcall.data, - (address[], bool) - ); - target = _computeUniswapPairAddress( - tokens[0], - tokens[1], - isSushi - ); + (address[] memory tokens, bool isSushi) = abi.decode(subcall.data, (address[], bool)); + target = _computeUniswapPairAddress(tokens[0], tokens[1], isSushi); } else if (subcall.id == MultiplexSubcall.LiquidityProvider) { // Similar to UniswapV2, LiquidityProvider contracts // allow tokens to be transferred in before the swap // is executed, so we the target is the address encoded // in the subcall data. - (target,) = abi.decode( - subcall.data, - (address, bytes) - ); - } else if ( - subcall.id == MultiplexSubcall.UniswapV3 || - subcall.id == MultiplexSubcall.BatchSell - ) { + (target, ) = abi.decode(subcall.data, (address, bytes)); + } else if (subcall.id == MultiplexSubcall.UniswapV3 || subcall.id == MultiplexSubcall.BatchSell) { // UniswapV3 uses a callback to pull in the tokens being // sold to it. The callback implemented in `UniswapV3Feature` // can either: @@ -696,10 +540,7 @@ contract MultiplexFeature is revert("MultiplexFeature::_computeHopTarget/INVALID_SUBCALL"); } } - require( - target != address(0), - "MultiplexFeature::_computeHopTarget/TARGET_IS_NULL" - ); + require(target != address(0), "MultiplexFeature::_computeHopTarget/TARGET_IS_NULL"); } // If `rawAmount` encodes a proportion of `totalSellAmount`, this function @@ -709,25 +550,17 @@ contract MultiplexFeature is uint256 rawAmount, uint256 totalSellAmount, uint256 soldAmount - ) - private - pure - returns (uint256 normalized) - { + ) private pure returns (uint256 normalized) { if ((rawAmount & HIGH_BIT) == HIGH_BIT) { // If the high bit of `rawAmount` is set then the lower 255 bits // specify a fraction of `totalSellAmount`. - return LibSafeMathV06.min256( - totalSellAmount - * LibSafeMathV06.min256(rawAmount & LOWER_255_BITS, 1e18) - / 1e18, - totalSellAmount.safeSub(soldAmount) - ); + return + LibSafeMathV06.min256( + (totalSellAmount * LibSafeMathV06.min256(rawAmount & LOWER_255_BITS, 1e18)) / 1e18, + totalSellAmount.safeSub(soldAmount) + ); } else { - return LibSafeMathV06.min256( - rawAmount, - totalSellAmount.safeSub(soldAmount) - ); + return LibSafeMathV06.min256(rawAmount, totalSellAmount.safeSub(soldAmount)); } } } diff --git a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexLiquidityProvider.sol b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexLiquidityProvider.sol index 15f7892cfc..902d95bdfe 100644 --- a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexLiquidityProvider.sol +++ b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexLiquidityProvider.sol @@ -29,11 +29,7 @@ import "../../fixins/FixinTokenSpender.sol"; import "../../vendor/ILiquidityProvider.sol"; import "../interfaces/IMultiplexFeature.sol"; - -abstract contract MultiplexLiquidityProvider is - FixinCommon, - FixinTokenSpender -{ +abstract contract MultiplexLiquidityProvider is FixinCommon, FixinTokenSpender { using LibERC20TokenV06 for IERC20TokenV06; using LibSafeMathV06 for uint256; @@ -50,9 +46,7 @@ abstract contract MultiplexLiquidityProvider is /// @dev The sandbox contract address. ILiquidityProviderSandbox private immutable SANDBOX; - constructor(ILiquidityProviderSandbox sandbox) - internal - { + constructor(ILiquidityProviderSandbox sandbox) internal { SANDBOX = sandbox; } @@ -62,11 +56,7 @@ abstract contract MultiplexLiquidityProvider is IMultiplexFeature.BatchSellParams calldata params, bytes calldata wrappedCallData, uint256 sellAmount - ) - external - payable - returns (uint256 boughtAmount) - { + ) external payable returns (uint256 boughtAmount) { // Revert if not a delegatecall. require( address(this) != _implementation, @@ -74,31 +64,18 @@ abstract contract MultiplexLiquidityProvider is ); // Decode the provider address and auxiliary data. - (address provider, bytes memory auxiliaryData) = abi.decode( - wrappedCallData, - (address, bytes) - ); + (address provider, bytes memory auxiliaryData) = abi.decode(wrappedCallData, (address, bytes)); if (params.useSelfBalance) { // If `useSelfBalance` is true, use the input tokens // held by `address(this)`. - _transferERC20Tokens( - params.inputToken, - provider, - sellAmount - ); + _transferERC20Tokens(params.inputToken, provider, sellAmount); } else { // Otherwise, transfer the input tokens from `msg.sender`. - _transferERC20TokensFrom( - params.inputToken, - msg.sender, - provider, - sellAmount - ); + _transferERC20TokensFrom(params.inputToken, msg.sender, provider, sellAmount); } // Cache the recipient's balance of the output token. - uint256 balanceBefore = params.outputToken - .balanceOf(params.recipient); + uint256 balanceBefore = params.outputToken.balanceOf(params.recipient); // Execute the swap. SANDBOX.executeSellTokenForToken( ILiquidityProvider(provider), @@ -110,9 +87,7 @@ abstract contract MultiplexLiquidityProvider is ); // Compute amount of output token received by the // recipient. - boughtAmount = params.outputToken - .balanceOf(params.recipient) - .safeSub(balanceBefore); + boughtAmount = params.outputToken.balanceOf(params.recipient).safeSub(balanceBefore); emit LiquidityProviderSwap( address(params.inputToken), @@ -129,9 +104,7 @@ abstract contract MultiplexLiquidityProvider is IMultiplexFeature.BatchSellParams memory params, bytes memory wrappedCallData, uint256 sellAmount - ) - internal - { + ) internal { // Swallow reverts (bool success, bytes memory resultData) = _implementation.delegatecall( abi.encodeWithSelector( @@ -156,19 +129,13 @@ abstract contract MultiplexLiquidityProvider is IMultiplexFeature.MultiHopSellState memory state, IMultiplexFeature.MultiHopSellParams memory params, bytes memory wrappedCallData - ) - internal - { + ) internal { IERC20TokenV06 inputToken = IERC20TokenV06(params.tokens[state.hopIndex]); IERC20TokenV06 outputToken = IERC20TokenV06(params.tokens[state.hopIndex + 1]); // Decode the provider address and auxiliary data. - (address provider, bytes memory auxiliaryData) = abi.decode( - wrappedCallData, - (address, bytes) - ); + (address provider, bytes memory auxiliaryData) = abi.decode(wrappedCallData, (address, bytes)); // Cache the recipient's balance of the output token. - uint256 balanceBefore = outputToken - .balanceOf(state.to); + uint256 balanceBefore = outputToken.balanceOf(state.to); // Execute the swap. SANDBOX.executeSellTokenForToken( ILiquidityProvider(provider), @@ -186,9 +153,7 @@ abstract contract MultiplexLiquidityProvider is uint256 sellAmount = state.outputTokenAmount; // Compute amount of output token received by the // recipient. - state.outputTokenAmount = outputToken - .balanceOf(state.to) - .safeSub(balanceBefore); + state.outputTokenAmount = outputToken.balanceOf(state.to).safeSub(balanceBefore); emit LiquidityProviderSwap( address(inputToken), diff --git a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexOtc.sol b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexOtc.sol index dc212047ab..6f1e1a2730 100644 --- a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexOtc.sol +++ b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexOtc.sol @@ -26,66 +26,45 @@ import "../interfaces/IMultiplexFeature.sol"; import "../interfaces/IOtcOrdersFeature.sol"; import "../libs/LibNativeOrder.sol"; - -abstract contract MultiplexOtc is - FixinEIP712 -{ +abstract contract MultiplexOtc is FixinEIP712 { using LibSafeMathV06 for uint256; - event ExpiredOtcOrder( - bytes32 orderHash, - address maker, - uint64 expiry - ); + event ExpiredOtcOrder(bytes32 orderHash, address maker, uint64 expiry); function _batchSellOtcOrder( IMultiplexFeature.BatchSellState memory state, IMultiplexFeature.BatchSellParams memory params, bytes memory wrappedCallData, uint256 sellAmount - ) - internal - { + ) internal { // Decode the Otc order and signature. - ( - LibNativeOrder.OtcOrder memory order, - LibSignature.Signature memory signature - ) = abi.decode( + (LibNativeOrder.OtcOrder memory order, LibSignature.Signature memory signature) = abi.decode( wrappedCallData, (LibNativeOrder.OtcOrder, LibSignature.Signature) ); // Validate tokens. require( - order.takerToken == params.inputToken && - order.makerToken == params.outputToken, + order.takerToken == params.inputToken && order.makerToken == params.outputToken, "MultiplexOtc::_batchSellOtcOrder/OTC_ORDER_INVALID_TOKENS" ); // Pre-emptively check if the order is expired. uint64 expiry = uint64(order.expiryAndNonce >> 192); if (expiry <= uint64(block.timestamp)) { - bytes32 orderHash = _getEIP712Hash( - LibNativeOrder.getOtcOrderStructHash(order) - ); - emit ExpiredOtcOrder( - orderHash, - order.maker, - expiry - ); + bytes32 orderHash = _getEIP712Hash(LibNativeOrder.getOtcOrderStructHash(order)); + emit ExpiredOtcOrder(orderHash, order.maker, expiry); return; } // Try filling the Otc order. Swallows reverts. try - IOtcOrdersFeature(address(this))._fillOtcOrder - ( - order, - signature, - sellAmount.safeDowncastToUint128(), - msg.sender, - params.useSelfBalance, - params.recipient - ) - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + IOtcOrdersFeature(address(this))._fillOtcOrder( + order, + signature, + sellAmount.safeDowncastToUint128(), + msg.sender, + params.useSelfBalance, + params.recipient + ) + returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { // Increment the sold and bought amounts. state.soldAmount = state.soldAmount.safeAdd(takerTokenFilledAmount); state.boughtAmount = state.boughtAmount.safeAdd(makerTokenFilledAmount); diff --git a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexRfq.sol b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexRfq.sol index 910d82f5c4..9354d0c1e5 100644 --- a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexRfq.sol +++ b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexRfq.sol @@ -26,65 +26,44 @@ import "../interfaces/IMultiplexFeature.sol"; import "../interfaces/INativeOrdersFeature.sol"; import "../libs/LibNativeOrder.sol"; - -abstract contract MultiplexRfq is - FixinEIP712 -{ +abstract contract MultiplexRfq is FixinEIP712 { using LibSafeMathV06 for uint256; - event ExpiredRfqOrder( - bytes32 orderHash, - address maker, - uint64 expiry - ); + event ExpiredRfqOrder(bytes32 orderHash, address maker, uint64 expiry); function _batchSellRfqOrder( IMultiplexFeature.BatchSellState memory state, IMultiplexFeature.BatchSellParams memory params, bytes memory wrappedCallData, uint256 sellAmount - ) - internal - { + ) internal { // Decode the RFQ order and signature. - ( - LibNativeOrder.RfqOrder memory order, - LibSignature.Signature memory signature - ) = abi.decode( + (LibNativeOrder.RfqOrder memory order, LibSignature.Signature memory signature) = abi.decode( wrappedCallData, (LibNativeOrder.RfqOrder, LibSignature.Signature) ); // Pre-emptively check if the order is expired. if (order.expiry <= uint64(block.timestamp)) { - bytes32 orderHash = _getEIP712Hash( - LibNativeOrder.getRfqOrderStructHash(order) - ); - emit ExpiredRfqOrder( - orderHash, - order.maker, - order.expiry - ); + bytes32 orderHash = _getEIP712Hash(LibNativeOrder.getRfqOrderStructHash(order)); + emit ExpiredRfqOrder(orderHash, order.maker, order.expiry); return; } // Validate tokens. require( - order.takerToken == params.inputToken && - order.makerToken == params.outputToken, + order.takerToken == params.inputToken && order.makerToken == params.outputToken, "MultiplexRfq::_batchSellRfqOrder/RFQ_ORDER_INVALID_TOKENS" ); // Try filling the RFQ order. Swallows reverts. try - INativeOrdersFeature(address(this))._fillRfqOrder - ( - order, - signature, - sellAmount.safeDowncastToUint128(), - msg.sender, - params.useSelfBalance, - params.recipient - ) - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + INativeOrdersFeature(address(this))._fillRfqOrder( + order, + signature, + sellAmount.safeDowncastToUint128(), + msg.sender, + params.useSelfBalance, + params.recipient + ) + returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { // Increment the sold and bought amounts. state.soldAmount = state.soldAmount.safeAdd(takerTokenFilledAmount); state.boughtAmount = state.boughtAmount.safeAdd(makerTokenFilledAmount); diff --git a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexTransformERC20.sol b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexTransformERC20.sol index 5a6dc35f6d..cb9f152377 100644 --- a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexTransformERC20.sol +++ b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexTransformERC20.sol @@ -24,9 +24,7 @@ import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "../interfaces/IMultiplexFeature.sol"; import "../interfaces/ITransformERC20Feature.sol"; - abstract contract MultiplexTransformERC20 { - using LibSafeMathV06 for uint256; function _batchSellTransformERC20( @@ -34,9 +32,7 @@ abstract contract MultiplexTransformERC20 { IMultiplexFeature.BatchSellParams memory params, bytes memory wrappedCallData, uint256 sellAmount - ) - internal - { + ) internal { ITransformERC20Feature.TransformERC20Args memory args; // We want the TransformedERC20 event to have // `msg.sender` as the taker. @@ -47,15 +43,9 @@ abstract contract MultiplexTransformERC20 { args.minOutputTokenAmount = 0; args.useSelfBalance = params.useSelfBalance; args.recipient = payable(params.recipient); - (args.transformations) = abi.decode( - wrappedCallData, - (ITransformERC20Feature.Transformation[]) - ); + (args.transformations) = abi.decode(wrappedCallData, (ITransformERC20Feature.Transformation[])); // Execute the transformations and swallow reverts. - try ITransformERC20Feature(address(this))._transformERC20 - (args) - returns (uint256 outputTokenAmount) - { + try ITransformERC20Feature(address(this))._transformERC20(args) returns (uint256 outputTokenAmount) { // Increment the sold and bought amounts. state.soldAmount = state.soldAmount.safeAdd(sellAmount); state.boughtAmount = state.boughtAmount.safeAdd(outputTokenAmount); diff --git a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexUniswapV2.sol b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexUniswapV2.sol index 815dac87f0..0c16dce598 100644 --- a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexUniswapV2.sol +++ b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexUniswapV2.sol @@ -27,11 +27,7 @@ import "../../fixins/FixinTokenSpender.sol"; import "../../vendor/IUniswapV2Pair.sol"; import "../interfaces/IMultiplexFeature.sol"; - -abstract contract MultiplexUniswapV2 is - FixinCommon, - FixinTokenSpender -{ +abstract contract MultiplexUniswapV2 is FixinCommon, FixinTokenSpender { using LibSafeMathV06 for uint256; // address of the UniswapV2Factory contract. @@ -48,9 +44,7 @@ abstract contract MultiplexUniswapV2 is address sushiswapFactory, bytes32 uniswapPairInitCodeHash, bytes32 sushiswapPairInitCodeHash - ) - internal - { + ) internal { UNISWAP_FACTORY = uniswapFactory; SUSHISWAP_FACTORY = sushiswapFactory; UNISWAP_PAIR_INIT_CODE_HASH = uniswapPairInitCodeHash; @@ -63,61 +57,35 @@ abstract contract MultiplexUniswapV2 is IMultiplexFeature.BatchSellParams calldata params, bytes calldata wrappedCallData, uint256 sellAmount - ) - external - payable - returns (uint256 boughtAmount) - { + ) external payable returns (uint256 boughtAmount) { // Revert is not a delegatecall. require( address(this) != _implementation, "MultiplexLiquidityProvider::_batchSellUniswapV2External/ONLY_DELEGATECALL" ); - (address[] memory tokens, bool isSushi) = abi.decode( - wrappedCallData, - (address[], bool) - ); + (address[] memory tokens, bool isSushi) = abi.decode(wrappedCallData, (address[], bool)); // Validate tokens require( tokens.length >= 2 && - tokens[0] == address(params.inputToken) && - tokens[tokens.length - 1] == address(params.outputToken), + tokens[0] == address(params.inputToken) && + tokens[tokens.length - 1] == address(params.outputToken), "MultiplexUniswapV2::_batchSellUniswapV2/INVALID_TOKENS" ); // Compute the address of the first Uniswap pair // contract that will execute a swap. - address firstPairAddress = _computeUniswapPairAddress( - tokens[0], - tokens[1], - isSushi - ); + address firstPairAddress = _computeUniswapPairAddress(tokens[0], tokens[1], isSushi); // `_sellToUniswapV2` assumes the input tokens have been // transferred into the pair contract before it is called, // so we transfer the tokens in now (either from `msg.sender` // or using the Exchange Proxy's balance). if (params.useSelfBalance) { - _transferERC20Tokens( - IERC20TokenV06(tokens[0]), - firstPairAddress, - sellAmount - ); + _transferERC20Tokens(IERC20TokenV06(tokens[0]), firstPairAddress, sellAmount); } else { - _transferERC20TokensFrom( - IERC20TokenV06(tokens[0]), - msg.sender, - firstPairAddress, - sellAmount - ); + _transferERC20TokensFrom(IERC20TokenV06(tokens[0]), msg.sender, firstPairAddress, sellAmount); } // Execute the Uniswap/Sushiswap trade. - return _sellToUniswapV2( - tokens, - sellAmount, - isSushi, - firstPairAddress, - params.recipient - ); + return _sellToUniswapV2(tokens, sellAmount, isSushi, firstPairAddress, params.recipient); } function _batchSellUniswapV2( @@ -125,17 +93,10 @@ abstract contract MultiplexUniswapV2 is IMultiplexFeature.BatchSellParams memory params, bytes memory wrappedCallData, uint256 sellAmount - ) - internal - { + ) internal { // Swallow reverts (bool success, bytes memory resultData) = _implementation.delegatecall( - abi.encodeWithSelector( - this._batchSellUniswapV2External.selector, - params, - wrappedCallData, - sellAmount - ) + abi.encodeWithSelector(this._batchSellUniswapV2External.selector, params, wrappedCallData, sellAmount) ); if (success) { // Decode the output token amount on success. @@ -150,28 +111,17 @@ abstract contract MultiplexUniswapV2 is IMultiplexFeature.MultiHopSellState memory state, IMultiplexFeature.MultiHopSellParams memory params, bytes memory wrappedCallData - ) - internal - { - (address[] memory tokens, bool isSushi) = abi.decode( - wrappedCallData, - (address[], bool) - ); + ) internal { + (address[] memory tokens, bool isSushi) = abi.decode(wrappedCallData, (address[], bool)); // Validate the tokens require( tokens.length >= 2 && - tokens[0] == params.tokens[state.hopIndex] && - tokens[tokens.length - 1] == params.tokens[state.hopIndex + 1], + tokens[0] == params.tokens[state.hopIndex] && + tokens[tokens.length - 1] == params.tokens[state.hopIndex + 1], "MultiplexUniswapV2::_multiHopSellUniswapV2/INVALID_TOKENS" ); // Execute the Uniswap/Sushiswap trade. - state.outputTokenAmount = _sellToUniswapV2( - tokens, - state.outputTokenAmount, - isSushi, - state.from, - state.to - ); + state.outputTokenAmount = _sellToUniswapV2(tokens, state.outputTokenAmount, isSushi, state.from, state.to); } function _sellToUniswapV2( @@ -180,21 +130,13 @@ abstract contract MultiplexUniswapV2 is bool isSushi, address pairAddress, address recipient - ) - private - returns (uint256 outputTokenAmount) - { + ) private returns (uint256 outputTokenAmount) { // Iterate through `tokens` perform a swap against the Uniswap // pair contract for each `(tokens[i], tokens[i+1])`. for (uint256 i = 0; i < tokens.length - 1; i++) { (address inputToken, address outputToken) = (tokens[i], tokens[i + 1]); // Compute the output token amount - outputTokenAmount = _computeUniswapOutputAmount( - pairAddress, - inputToken, - outputToken, - sellAmount - ); + outputTokenAmount = _computeUniswapOutputAmount(pairAddress, inputToken, outputToken, sellAmount); (uint256 amount0Out, uint256 amount1Out) = inputToken < outputToken ? (uint256(0), outputTokenAmount) : (outputTokenAmount, uint256(0)); @@ -205,12 +147,7 @@ abstract contract MultiplexUniswapV2 is ? _computeUniswapPairAddress(outputToken, tokens[i + 2], isSushi) : recipient; // Execute the swap. - IUniswapV2Pair(pairAddress).swap( - amount0Out, - amount1Out, - to, - new bytes(0) - ); + IUniswapV2Pair(pairAddress).swap(amount0Out, amount1Out, to, new bytes(0)); // To avoid recomputing the pair address of the next pair, store // `to` in `pairAddress`. pairAddress = to; @@ -225,31 +162,39 @@ abstract contract MultiplexUniswapV2 is address tokenA, address tokenB, bool isSushi - ) - internal - view - returns (address pairAddress) - { + ) internal view returns (address pairAddress) { // Tokens are lexicographically sorted in the Uniswap contract. - (address token0, address token1) = tokenA < tokenB - ? (tokenA, tokenB) - : (tokenB, tokenA); + (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); if (isSushi) { // Use the Sushiswap factory address and codehash - return address(uint256(keccak256(abi.encodePacked( - hex'ff', - SUSHISWAP_FACTORY, - keccak256(abi.encodePacked(token0, token1)), - SUSHISWAP_PAIR_INIT_CODE_HASH - )))); + return + address( + uint256( + keccak256( + abi.encodePacked( + hex"ff", + SUSHISWAP_FACTORY, + keccak256(abi.encodePacked(token0, token1)), + SUSHISWAP_PAIR_INIT_CODE_HASH + ) + ) + ) + ); } else { // Use the Uniswap factory address and codehash - return address(uint256(keccak256(abi.encodePacked( - hex'ff', - UNISWAP_FACTORY, - keccak256(abi.encodePacked(token0, token1)), - UNISWAP_PAIR_INIT_CODE_HASH - )))); + return + address( + uint256( + keccak256( + abi.encodePacked( + hex"ff", + UNISWAP_FACTORY, + keccak256(abi.encodePacked(token0, token1)), + UNISWAP_PAIR_INIT_CODE_HASH + ) + ) + ) + ); } } @@ -260,23 +205,13 @@ abstract contract MultiplexUniswapV2 is address inputToken, address outputToken, uint256 inputAmount - ) - private - view - returns (uint256 outputAmount) - { + ) private view returns (uint256 outputAmount) { // Input amount should be non-zero. - require( - inputAmount > 0, - "MultiplexUniswapV2::_computeUniswapOutputAmount/INSUFFICIENT_INPUT_AMOUNT" - ); + require(inputAmount > 0, "MultiplexUniswapV2::_computeUniswapOutputAmount/INSUFFICIENT_INPUT_AMOUNT"); // Query the reserves of the pair contract. - (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(pairAddress).getReserves(); + (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairAddress).getReserves(); // Reserves must be non-zero. - require( - reserve0 > 0 && reserve1 > 0, - 'MultiplexUniswapV2::_computeUniswapOutputAmount/INSUFFICIENT_LIQUIDITY' - ); + require(reserve0 > 0 && reserve1 > 0, "MultiplexUniswapV2::_computeUniswapOutputAmount/INSUFFICIENT_LIQUIDITY"); // Tokens are lexicographically sorted in the Uniswap contract. (uint256 inputReserve, uint256 outputReserve) = inputToken < outputToken ? (reserve0, reserve1) diff --git a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexUniswapV3.sol b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexUniswapV3.sol index 325bd58166..539e92303f 100644 --- a/contracts/zero-ex/contracts/src/features/multiplex/MultiplexUniswapV3.sol +++ b/contracts/zero-ex/contracts/src/features/multiplex/MultiplexUniswapV3.sol @@ -26,10 +26,7 @@ import "../../fixins/FixinTokenSpender.sol"; import "../interfaces/IMultiplexFeature.sol"; import "../interfaces/IUniswapV3Feature.sol"; - -abstract contract MultiplexUniswapV3 is - FixinTokenSpender -{ +abstract contract MultiplexUniswapV3 is FixinTokenSpender { using LibSafeMathV06 for uint256; function _batchSellUniswapV3( @@ -37,9 +34,7 @@ abstract contract MultiplexUniswapV3 is IMultiplexFeature.BatchSellParams memory params, bytes memory wrappedCallData, uint256 sellAmount - ) - internal - { + ) internal { bool success; bytes memory resultData; if (params.useSelfBalance) { @@ -78,10 +73,7 @@ abstract contract MultiplexUniswapV3 is } } - function _multiHopSellUniswapV3( - IMultiplexFeature.MultiHopSellState memory state, - bytes memory wrappedCallData - ) + function _multiHopSellUniswapV3(IMultiplexFeature.MultiHopSellState memory state, bytes memory wrappedCallData) internal { bool success; diff --git a/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersCancellation.sol b/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersCancellation.sol index b3b336952a..f73317cd75 100644 --- a/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersCancellation.sol +++ b/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersCancellation.sol @@ -30,37 +30,23 @@ import "../libs/LibNativeOrder.sol"; import "./NativeOrdersInfo.sol"; /// @dev Feature for cancelling limit and RFQ orders. -abstract contract NativeOrdersCancellation is - INativeOrdersEvents, - NativeOrdersInfo -{ +abstract contract NativeOrdersCancellation is INativeOrdersEvents, NativeOrdersInfo { using LibRichErrorsV06 for bytes; /// @dev Highest bit of a uint256, used to flag cancelled orders. uint256 private constant HIGH_BIT = 1 << 255; - constructor( - address zeroExAddress - ) - internal - NativeOrdersInfo(zeroExAddress) - { + constructor(address zeroExAddress) internal NativeOrdersInfo(zeroExAddress) { // solhint-disable no-empty-blocks } /// @dev Cancel a single limit order. The caller must be the maker or a valid order signer. /// Silently succeeds if the order has already been cancelled. /// @param order The limit order. - function cancelLimitOrder(LibNativeOrder.LimitOrder memory order) - public - { + function cancelLimitOrder(LibNativeOrder.LimitOrder memory order) public { bytes32 orderHash = getLimitOrderHash(order); if (msg.sender != order.maker && !isValidOrderSigner(order.maker, msg.sender)) { - LibNativeOrdersRichErrors.OnlyOrderMakerAllowed( - orderHash, - msg.sender, - order.maker - ).rrevert(); + LibNativeOrdersRichErrors.OnlyOrderMakerAllowed(orderHash, msg.sender, order.maker).rrevert(); } _cancelOrderHash(orderHash, order.maker); } @@ -68,16 +54,10 @@ abstract contract NativeOrdersCancellation is /// @dev Cancel a single RFQ order. The caller must be the maker or a valid order signer. /// Silently succeeds if the order has already been cancelled. /// @param order The RFQ order. - function cancelRfqOrder(LibNativeOrder.RfqOrder memory order) - public - { + function cancelRfqOrder(LibNativeOrder.RfqOrder memory order) public { bytes32 orderHash = getRfqOrderHash(order); if (msg.sender != order.maker && !isValidOrderSigner(order.maker, msg.sender)) { - LibNativeOrdersRichErrors.OnlyOrderMakerAllowed( - orderHash, - msg.sender, - order.maker - ).rrevert(); + LibNativeOrdersRichErrors.OnlyOrderMakerAllowed(orderHash, msg.sender, order.maker).rrevert(); } _cancelOrderHash(orderHash, order.maker); } @@ -85,9 +65,7 @@ abstract contract NativeOrdersCancellation is /// @dev Cancel multiple limit orders. The caller must be the maker or a valid order signer. /// Silently succeeds if the order has already been cancelled. /// @param orders The limit orders. - function batchCancelLimitOrders(LibNativeOrder.LimitOrder[] memory orders) - public - { + function batchCancelLimitOrders(LibNativeOrder.LimitOrder[] memory orders) public { for (uint256 i = 0; i < orders.length; ++i) { cancelLimitOrder(orders[i]); } @@ -96,9 +74,7 @@ abstract contract NativeOrdersCancellation is /// @dev Cancel multiple RFQ orders. The caller must be the maker or a valid order signer. /// Silently succeeds if the order has already been cancelled. /// @param orders The RFQ orders. - function batchCancelRfqOrders(LibNativeOrder.RfqOrder[] memory orders) - public - { + function batchCancelRfqOrders(LibNativeOrder.RfqOrder[] memory orders) public { for (uint256 i = 0; i < orders.length; ++i) { cancelRfqOrder(orders[i]); } @@ -115,9 +91,7 @@ abstract contract NativeOrdersCancellation is IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt - ) - public - { + ) public { _cancelPairLimitOrders(msg.sender, makerToken, takerToken, minValidSalt); } @@ -134,15 +108,10 @@ abstract contract NativeOrdersCancellation is IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt - ) - public - { + ) public { // verify that the signer is authorized for the maker if (!isValidOrderSigner(maker, msg.sender)) { - LibNativeOrdersRichErrors.InvalidSignerError( - maker, - msg.sender - ).rrevert(); + LibNativeOrdersRichErrors.InvalidSignerError(maker, msg.sender).rrevert(); } _cancelPairLimitOrders(maker, makerToken, takerToken, minValidSalt); @@ -159,22 +128,14 @@ abstract contract NativeOrdersCancellation is IERC20TokenV06[] memory makerTokens, IERC20TokenV06[] memory takerTokens, uint256[] memory minValidSalts - ) - public - { + ) public { require( - makerTokens.length == takerTokens.length && - makerTokens.length == minValidSalts.length, + makerTokens.length == takerTokens.length && makerTokens.length == minValidSalts.length, "NativeOrdersFeature/MISMATCHED_PAIR_ORDERS_ARRAY_LENGTHS" ); for (uint256 i = 0; i < makerTokens.length; ++i) { - _cancelPairLimitOrders( - msg.sender, - makerTokens[i], - takerTokens[i], - minValidSalts[i] - ); + _cancelPairLimitOrders(msg.sender, makerTokens[i], takerTokens[i], minValidSalts[i]); } } @@ -191,29 +152,18 @@ abstract contract NativeOrdersCancellation is IERC20TokenV06[] memory makerTokens, IERC20TokenV06[] memory takerTokens, uint256[] memory minValidSalts - ) - public - { + ) public { require( - makerTokens.length == takerTokens.length && - makerTokens.length == minValidSalts.length, + makerTokens.length == takerTokens.length && makerTokens.length == minValidSalts.length, "NativeOrdersFeature/MISMATCHED_PAIR_ORDERS_ARRAY_LENGTHS" ); if (!isValidOrderSigner(maker, msg.sender)) { - LibNativeOrdersRichErrors.InvalidSignerError( - maker, - msg.sender - ).rrevert(); + LibNativeOrdersRichErrors.InvalidSignerError(maker, msg.sender).rrevert(); } for (uint256 i = 0; i < makerTokens.length; ++i) { - _cancelPairLimitOrders( - maker, - makerTokens[i], - takerTokens[i], - minValidSalts[i] - ); + _cancelPairLimitOrders(maker, makerTokens[i], takerTokens[i], minValidSalts[i]); } } @@ -228,9 +178,7 @@ abstract contract NativeOrdersCancellation is IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt - ) - public - { + ) public { _cancelPairRfqOrders(msg.sender, makerToken, takerToken, minValidSalt); } @@ -247,14 +195,9 @@ abstract contract NativeOrdersCancellation is IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt - ) - public - { + ) public { if (!isValidOrderSigner(maker, msg.sender)) { - LibNativeOrdersRichErrors.InvalidSignerError( - maker, - msg.sender - ).rrevert(); + LibNativeOrdersRichErrors.InvalidSignerError(maker, msg.sender).rrevert(); } _cancelPairRfqOrders(maker, makerToken, takerToken, minValidSalt); @@ -271,22 +214,14 @@ abstract contract NativeOrdersCancellation is IERC20TokenV06[] memory makerTokens, IERC20TokenV06[] memory takerTokens, uint256[] memory minValidSalts - ) - public - { + ) public { require( - makerTokens.length == takerTokens.length && - makerTokens.length == minValidSalts.length, + makerTokens.length == takerTokens.length && makerTokens.length == minValidSalts.length, "NativeOrdersFeature/MISMATCHED_PAIR_ORDERS_ARRAY_LENGTHS" ); for (uint256 i = 0; i < makerTokens.length; ++i) { - _cancelPairRfqOrders( - msg.sender, - makerTokens[i], - takerTokens[i], - minValidSalts[i] - ); + _cancelPairRfqOrders(msg.sender, makerTokens[i], takerTokens[i], minValidSalts[i]); } } @@ -303,40 +238,26 @@ abstract contract NativeOrdersCancellation is IERC20TokenV06[] memory makerTokens, IERC20TokenV06[] memory takerTokens, uint256[] memory minValidSalts - ) - public - { + ) public { require( - makerTokens.length == takerTokens.length && - makerTokens.length == minValidSalts.length, + makerTokens.length == takerTokens.length && makerTokens.length == minValidSalts.length, "NativeOrdersFeature/MISMATCHED_PAIR_ORDERS_ARRAY_LENGTHS" ); if (!isValidOrderSigner(maker, msg.sender)) { - LibNativeOrdersRichErrors.InvalidSignerError( - maker, - msg.sender - ).rrevert(); + LibNativeOrdersRichErrors.InvalidSignerError(maker, msg.sender).rrevert(); } for (uint256 i = 0; i < makerTokens.length; ++i) { - _cancelPairRfqOrders( - maker, - makerTokens[i], - takerTokens[i], - minValidSalts[i] - ); + _cancelPairRfqOrders(maker, makerTokens[i], takerTokens[i], minValidSalts[i]); } } /// @dev Cancel a limit or RFQ order directly by its order hash. /// @param orderHash The order's order hash. /// @param maker The order's maker. - function _cancelOrderHash(bytes32 orderHash, address maker) - private - { - LibNativeOrdersStorage.Storage storage stor = - LibNativeOrdersStorage.getStorage(); + function _cancelOrderHash(bytes32 orderHash, address maker) private { + LibNativeOrdersStorage.Storage storage stor = LibNativeOrdersStorage.getStorage(); // Set the high bit on the raw taker token fill amount to indicate // a cancel. It's OK to cancel twice. stor.orderHashToTakerTokenFilledAmount[orderHash] |= HIGH_BIT; @@ -355,36 +276,23 @@ abstract contract NativeOrdersCancellation is IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt - ) - private - { - LibNativeOrdersStorage.Storage storage stor = - LibNativeOrdersStorage.getStorage(); + ) private { + LibNativeOrdersStorage.Storage storage stor = LibNativeOrdersStorage.getStorage(); - uint256 oldMinValidSalt = - stor.rfqOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt - [maker] - [address(makerToken)] - [address(takerToken)]; + uint256 oldMinValidSalt = stor.rfqOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt[maker][ + address(makerToken) + ][address(takerToken)]; // New min salt must >= the old one. if (oldMinValidSalt > minValidSalt) { - LibNativeOrdersRichErrors. - CancelSaltTooLowError(minValidSalt, oldMinValidSalt) - .rrevert(); + LibNativeOrdersRichErrors.CancelSaltTooLowError(minValidSalt, oldMinValidSalt).rrevert(); } - stor.rfqOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt - [maker] - [address(makerToken)] - [address(takerToken)] = minValidSalt; + stor.rfqOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt[maker][address(makerToken)][ + address(takerToken) + ] = minValidSalt; - emit PairCancelledRfqOrders( - maker, - address(makerToken), - address(takerToken), - minValidSalt - ); + emit PairCancelledRfqOrders(maker, address(makerToken), address(takerToken), minValidSalt); } /// @dev Cancel all limit orders for a given maker and pair with a salt less @@ -398,35 +306,22 @@ abstract contract NativeOrdersCancellation is IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt - ) - private - { - LibNativeOrdersStorage.Storage storage stor = - LibNativeOrdersStorage.getStorage(); + ) private { + LibNativeOrdersStorage.Storage storage stor = LibNativeOrdersStorage.getStorage(); - uint256 oldMinValidSalt = - stor.limitOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt - [maker] - [address(makerToken)] - [address(takerToken)]; + uint256 oldMinValidSalt = stor.limitOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt[maker][ + address(makerToken) + ][address(takerToken)]; // New min salt must >= the old one. if (oldMinValidSalt > minValidSalt) { - LibNativeOrdersRichErrors. - CancelSaltTooLowError(minValidSalt, oldMinValidSalt) - .rrevert(); + LibNativeOrdersRichErrors.CancelSaltTooLowError(minValidSalt, oldMinValidSalt).rrevert(); } - stor.limitOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt - [maker] - [address(makerToken)] - [address(takerToken)] = minValidSalt; + stor.limitOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt[maker][address(makerToken)][ + address(takerToken) + ] = minValidSalt; - emit PairCancelledLimitOrders( - maker, - address(makerToken), - address(takerToken), - minValidSalt - ); + emit PairCancelledLimitOrders(maker, address(makerToken), address(takerToken), minValidSalt); } } diff --git a/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersInfo.sol b/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersInfo.sol index 16ea926c89..c2f02fbeb3 100644 --- a/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersInfo.sol +++ b/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersInfo.sol @@ -29,12 +29,8 @@ import "../../storage/LibNativeOrdersStorage.sol"; import "../libs/LibSignature.sol"; import "../libs/LibNativeOrder.sol"; - /// @dev Feature for getting info about limit and RFQ orders. -abstract contract NativeOrdersInfo is - FixinEIP712, - FixinTokenSpender -{ +abstract contract NativeOrdersInfo is FixinEIP712, FixinTokenSpender { using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; @@ -50,12 +46,7 @@ abstract contract NativeOrdersInfo is /// @dev Highest bit of a uint256, used to flag cancelled orders. uint256 private constant HIGH_BIT = 1 << 255; - constructor( - address zeroExAddress - ) - internal - FixinEIP712(zeroExAddress) - { + constructor(address zeroExAddress) internal FixinEIP712(zeroExAddress) { // solhint-disable no-empty-blocks } @@ -69,18 +60,12 @@ abstract contract NativeOrdersInfo is { // Recover maker and compute order hash. orderInfo.orderHash = getLimitOrderHash(order); - uint256 minValidSalt = LibNativeOrdersStorage.getStorage() - .limitOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt - [order.maker] - [address(order.makerToken)] - [address(order.takerToken)]; - _populateCommonOrderInfoFields( - orderInfo, - order.takerAmount, - order.expiry, - order.salt, - minValidSalt - ); + uint256 minValidSalt = LibNativeOrdersStorage + .getStorage() + .limitOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt[order.maker][address(order.makerToken)][ + address(order.takerToken) + ]; + _populateCommonOrderInfoFields(orderInfo, order.takerAmount, order.expiry, order.salt, minValidSalt); } /// @dev Get the order info for an RFQ order. @@ -93,18 +78,12 @@ abstract contract NativeOrdersInfo is { // Recover maker and compute order hash. orderInfo.orderHash = getRfqOrderHash(order); - uint256 minValidSalt = LibNativeOrdersStorage.getStorage() - .rfqOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt - [order.maker] - [address(order.makerToken)] - [address(order.takerToken)]; - _populateCommonOrderInfoFields( - orderInfo, - order.takerAmount, - order.expiry, - order.salt, - minValidSalt - ); + uint256 minValidSalt = LibNativeOrdersStorage + .getStorage() + .rfqOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt[order.maker][address(order.makerToken)][ + address(order.takerToken) + ]; + _populateCommonOrderInfoFields(orderInfo, order.takerAmount, order.expiry, order.salt, minValidSalt); // Check for missing txOrigin. if (order.txOrigin == address(0)) { @@ -115,27 +94,15 @@ abstract contract NativeOrdersInfo is /// @dev Get the canonical hash of a limit order. /// @param order The limit order. /// @return orderHash The order hash. - function getLimitOrderHash(LibNativeOrder.LimitOrder memory order) - public - view - returns (bytes32 orderHash) - { - return _getEIP712Hash( - LibNativeOrder.getLimitOrderStructHash(order) - ); + function getLimitOrderHash(LibNativeOrder.LimitOrder memory order) public view returns (bytes32 orderHash) { + return _getEIP712Hash(LibNativeOrder.getLimitOrderStructHash(order)); } /// @dev Get the canonical hash of an RFQ order. /// @param order The RFQ order. /// @return orderHash The order hash. - function getRfqOrderHash(LibNativeOrder.RfqOrder memory order) - public - view - returns (bytes32 orderHash) - { - return _getEIP712Hash( - LibNativeOrder.getRfqOrderStructHash(order) - ); + function getRfqOrderHash(LibNativeOrder.RfqOrder memory order) public view returns (bytes32 orderHash) { + return _getEIP712Hash(LibNativeOrder.getRfqOrderStructHash(order)); } /// @dev Get order info, fillable amount, and signature validity for a limit order. @@ -169,9 +136,7 @@ abstract contract NativeOrdersInfo is }) ); address signerOfHash = LibSignature.getSignerOfHash(orderInfo.orderHash, signature); - isSignatureValid = - (order.maker == signerOfHash) || - isValidOrderSigner(order.maker, signerOfHash); + isSignatureValid = (order.maker == signerOfHash) || isValidOrderSigner(order.maker, signerOfHash); } /// @dev Get order info, fillable amount, and signature validity for an RFQ order. @@ -182,10 +147,7 @@ abstract contract NativeOrdersInfo is /// @return actualFillableTakerTokenAmount How much of the order is fillable /// based on maker funds, in taker tokens. /// @return isSignatureValid Whether the signature is valid. - function getRfqOrderRelevantState( - LibNativeOrder.RfqOrder memory order, - LibSignature.Signature memory signature - ) + function getRfqOrderRelevantState(LibNativeOrder.RfqOrder memory order, LibSignature.Signature memory signature) public view returns ( @@ -205,9 +167,7 @@ abstract contract NativeOrdersInfo is }) ); address signerOfHash = LibSignature.getSignerOfHash(orderInfo.orderHash, signature); - isSignatureValid = - (order.maker == signerOfHash) || - isValidOrderSigner(order.maker, signerOfHash); + isSignatureValid = (order.maker == signerOfHash) || isValidOrderSigner(order.maker, signerOfHash); } /// @dev Batch version of `getLimitOrderRelevantState()`, without reverting. @@ -231,27 +191,20 @@ abstract contract NativeOrdersInfo is bool[] memory isSignatureValids ) { - require( - orders.length == signatures.length, - "NativeOrdersFeature/MISMATCHED_ARRAY_LENGTHS" - ); + require(orders.length == signatures.length, "NativeOrdersFeature/MISMATCHED_ARRAY_LENGTHS"); orderInfos = new LibNativeOrder.OrderInfo[](orders.length); actualFillableTakerTokenAmounts = new uint128[](orders.length); isSignatureValids = new bool[](orders.length); for (uint256 i = 0; i < orders.length; ++i) { - try - this.getLimitOrderRelevantState(orders[i], signatures[i]) - returns ( - LibNativeOrder.OrderInfo memory orderInfo, - uint128 actualFillableTakerTokenAmount, - bool isSignatureValid - ) - { + try this.getLimitOrderRelevantState(orders[i], signatures[i]) returns ( + LibNativeOrder.OrderInfo memory orderInfo, + uint128 actualFillableTakerTokenAmount, + bool isSignatureValid + ) { orderInfos[i] = orderInfo; actualFillableTakerTokenAmounts[i] = actualFillableTakerTokenAmount; isSignatureValids[i] = isSignatureValid; - } - catch {} + } catch {} } } @@ -276,27 +229,20 @@ abstract contract NativeOrdersInfo is bool[] memory isSignatureValids ) { - require( - orders.length == signatures.length, - "NativeOrdersFeature/MISMATCHED_ARRAY_LENGTHS" - ); + require(orders.length == signatures.length, "NativeOrdersFeature/MISMATCHED_ARRAY_LENGTHS"); orderInfos = new LibNativeOrder.OrderInfo[](orders.length); actualFillableTakerTokenAmounts = new uint128[](orders.length); isSignatureValids = new bool[](orders.length); for (uint256 i = 0; i < orders.length; ++i) { - try - this.getRfqOrderRelevantState(orders[i], signatures[i]) - returns ( - LibNativeOrder.OrderInfo memory orderInfo, - uint128 actualFillableTakerTokenAmount, - bool isSignatureValid - ) - { + try this.getRfqOrderRelevantState(orders[i], signatures[i]) returns ( + LibNativeOrder.OrderInfo memory orderInfo, + uint128 actualFillableTakerTokenAmount, + bool isSignatureValid + ) { orderInfos[i] = orderInfo; actualFillableTakerTokenAmounts[i] = actualFillableTakerTokenAmount; isSignatureValids[i] = isSignatureValid; - } - catch {} + } catch {} } } @@ -314,19 +260,14 @@ abstract contract NativeOrdersInfo is uint64 expiry, uint256 salt, uint256 minValidSalt - ) - private - view - { - LibNativeOrdersStorage.Storage storage stor = - LibNativeOrdersStorage.getStorage(); + ) private view { + LibNativeOrdersStorage.Storage storage stor = LibNativeOrdersStorage.getStorage(); // Get the filled and direct cancel state. { // The high bit of the raw taker token filled amount will be set // if the order was cancelled. - uint256 rawTakerTokenFilledAmount = - stor.orderHashToTakerTokenFilledAmount[orderInfo.orderHash]; + uint256 rawTakerTokenFilledAmount = stor.orderHashToTakerTokenFilledAmount[orderInfo.orderHash]; orderInfo.takerTokenFilledAmount = uint128(rawTakerTokenFilledAmount); if (orderInfo.takerTokenFilledAmount >= takerAmount) { orderInfo.status = LibNativeOrder.OrderStatus.FILLED; @@ -354,9 +295,7 @@ abstract contract NativeOrdersInfo is /// @dev Calculate the actual fillable taker token amount of an order /// based on maker allowance and balances. - function _getActualFillableTakerTokenAmount( - GetActualFillableTakerTokenAmountParams memory params - ) + function _getActualFillableTakerTokenAmount(GetActualFillableTakerTokenAmountParams memory params) private view returns (uint128 actualFillableTakerTokenAmount) @@ -373,10 +312,7 @@ abstract contract NativeOrdersInfo is // Get the fillable maker amount based on the order quantities and // previously filled amount uint256 fillableMakerTokenAmount = LibMathV06.getPartialAmountFloor( - uint256( - params.orderTakerAmount - - params.orderInfo.takerTokenFilledAmount - ), + uint256(params.orderTakerAmount - params.orderInfo.takerTokenFilledAmount), uint256(params.orderTakerAmount), uint256(params.orderMakerAmount) ); @@ -387,28 +323,21 @@ abstract contract NativeOrdersInfo is _getSpendableERC20BalanceOf(params.makerToken, params.maker) ); // Convert to taker token amount. - return LibMathV06.getPartialAmountCeil( - fillableMakerTokenAmount, - uint256(params.orderMakerAmount), - uint256(params.orderTakerAmount) - ).safeDowncastToUint128(); + return + LibMathV06 + .getPartialAmountCeil( + fillableMakerTokenAmount, + uint256(params.orderMakerAmount), + uint256(params.orderTakerAmount) + ) + .safeDowncastToUint128(); } /// @dev checks if a given address is registered to sign on behalf of a maker address /// @param maker The maker address encoded in an order (can be a contract) /// @param signer The address that is providing a signature - function isValidOrderSigner( - address maker, - address signer - ) - public - view - returns (bool isValid) - { + function isValidOrderSigner(address maker, address signer) public view returns (bool isValid) { // returns false if it the mapping doesn't exist - return LibNativeOrdersStorage.getStorage() - .orderSignerRegistry - [maker] - [signer]; + return LibNativeOrdersStorage.getStorage().orderSignerRegistry[maker][signer]; } } diff --git a/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersProtocolFees.sol b/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersProtocolFees.sol index 2d1810ea51..cb17470dc9 100644 --- a/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersProtocolFees.sol +++ b/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersProtocolFees.sol @@ -27,11 +27,8 @@ import "../../fixins/FixinProtocolFees.sol"; import "../../errors/LibNativeOrdersRichErrors.sol"; import "../../vendor/v3/IStaking.sol"; - /// @dev Mixin for protocol fee utility functions. -abstract contract NativeOrdersProtocolFees is - FixinProtocolFees -{ +abstract contract NativeOrdersProtocolFees is FixinProtocolFees { using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; @@ -40,19 +37,14 @@ abstract contract NativeOrdersProtocolFees is IStaking staking, FeeCollectorController feeCollectorController, uint32 protocolFeeMultiplier - ) - internal - FixinProtocolFees(weth, staking, feeCollectorController, protocolFeeMultiplier) - { + ) internal FixinProtocolFees(weth, staking, feeCollectorController, protocolFeeMultiplier) { // solhint-disable no-empty-blocks } /// @dev Transfers protocol fees from the `FeeCollector` pools into /// the staking contract. /// @param poolIds Staking pool IDs - function transferProtocolFeesForPools(bytes32[] calldata poolIds) - external - { + function transferProtocolFeesForPools(bytes32[] calldata poolIds) external { for (uint256 i = 0; i < poolIds.length; ++i) { _transferFeesForPool(poolIds[i]); } @@ -61,11 +53,7 @@ abstract contract NativeOrdersProtocolFees is /// @dev Get the protocol fee multiplier. This should be multiplied by the /// gas price to arrive at the required protocol fee to fill a native order. /// @return multiplier The protocol fee multiplier. - function getProtocolFeeMultiplier() - external - view - returns (uint32 multiplier) - { + function getProtocolFeeMultiplier() external view returns (uint32 multiplier) { return PROTOCOL_FEE_MULTIPLIER; } } diff --git a/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersSettlement.sol b/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersSettlement.sol index 75b39000e1..e8ee2612ad 100644 --- a/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersSettlement.sol +++ b/contracts/zero-ex/contracts/src/features/native_orders/NativeOrdersSettlement.sol @@ -35,7 +35,6 @@ import "../libs/LibNativeOrder.sol"; import "./NativeOrdersCancellation.sol"; import "./NativeOrdersProtocolFees.sol"; - /// @dev Mixin for settling limit and RFQ orders. abstract contract NativeOrdersSettlement is INativeOrdersEvents, @@ -135,19 +134,16 @@ abstract contract NativeOrdersSettlement is LibNativeOrder.LimitOrder memory order, LibSignature.Signature memory signature, uint128 takerTokenFillAmount - ) - public - payable - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { - FillNativeOrderResults memory results = - _fillLimitOrderPrivate(FillLimitOrderPrivateParams({ + ) public payable returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { + FillNativeOrderResults memory results = _fillLimitOrderPrivate( + FillLimitOrderPrivateParams({ order: order, signature: signature, takerTokenFillAmount: takerTokenFillAmount, taker: msg.sender, sender: msg.sender - })); + }) + ); LibNativeOrder.refundExcessProtocolFeeToSender(results.ethProtocolFeePaid); (takerTokenFilledAmount, makerTokenFilledAmount) = ( results.takerTokenFilledAmount, @@ -167,19 +163,17 @@ abstract contract NativeOrdersSettlement is LibNativeOrder.RfqOrder memory order, LibSignature.Signature memory signature, uint128 takerTokenFillAmount - ) - public - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { - FillNativeOrderResults memory results = - _fillRfqOrderPrivate(FillRfqOrderPrivateParams({ + ) public returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { + FillNativeOrderResults memory results = _fillRfqOrderPrivate( + FillRfqOrderPrivateParams({ order: order, signature: signature, takerTokenFillAmount: takerTokenFillAmount, taker: msg.sender, useSelfBalance: false, recipient: msg.sender - })); + }) + ); (takerTokenFilledAmount, makerTokenFilledAmount) = ( results.takerTokenFilledAmount, results.makerTokenFilledAmount @@ -198,26 +192,21 @@ abstract contract NativeOrdersSettlement is LibNativeOrder.LimitOrder memory order, LibSignature.Signature memory signature, uint128 takerTokenFillAmount - ) - public - payable - returns (uint128 makerTokenFilledAmount) - { - FillNativeOrderResults memory results = - _fillLimitOrderPrivate(FillLimitOrderPrivateParams({ + ) public payable returns (uint128 makerTokenFilledAmount) { + FillNativeOrderResults memory results = _fillLimitOrderPrivate( + FillLimitOrderPrivateParams({ order: order, signature: signature, takerTokenFillAmount: takerTokenFillAmount, taker: msg.sender, sender: msg.sender - })); + }) + ); // Must have filled exactly the amount requested. if (results.takerTokenFilledAmount < takerTokenFillAmount) { - LibNativeOrdersRichErrors.FillOrKillFailedError( - getLimitOrderHash(order), - results.takerTokenFilledAmount, - takerTokenFillAmount - ).rrevert(); + LibNativeOrdersRichErrors + .FillOrKillFailedError(getLimitOrderHash(order), results.takerTokenFilledAmount, takerTokenFillAmount) + .rrevert(); } LibNativeOrder.refundExcessProtocolFeeToSender(results.ethProtocolFeePaid); makerTokenFilledAmount = results.makerTokenFilledAmount; @@ -235,26 +224,22 @@ abstract contract NativeOrdersSettlement is LibNativeOrder.RfqOrder memory order, LibSignature.Signature memory signature, uint128 takerTokenFillAmount - ) - public - returns (uint128 makerTokenFilledAmount) - { - FillNativeOrderResults memory results = - _fillRfqOrderPrivate(FillRfqOrderPrivateParams({ + ) public returns (uint128 makerTokenFilledAmount) { + FillNativeOrderResults memory results = _fillRfqOrderPrivate( + FillRfqOrderPrivateParams({ order: order, signature: signature, takerTokenFillAmount: takerTokenFillAmount, taker: msg.sender, useSelfBalance: false, recipient: msg.sender - })); + }) + ); // Must have filled exactly the amount requested. if (results.takerTokenFilledAmount < takerTokenFillAmount) { - LibNativeOrdersRichErrors.FillOrKillFailedError( - getRfqOrderHash(order), - results.takerTokenFilledAmount, - takerTokenFillAmount - ).rrevert(); + LibNativeOrdersRichErrors + .FillOrKillFailedError(getRfqOrderHash(order), results.takerTokenFilledAmount, takerTokenFillAmount) + .rrevert(); } makerTokenFilledAmount = results.makerTokenFilledAmount; } @@ -274,21 +259,10 @@ abstract contract NativeOrdersSettlement is uint128 takerTokenFillAmount, address taker, address sender - ) - public - virtual - payable - onlySelf - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { - FillNativeOrderResults memory results = - _fillLimitOrderPrivate(FillLimitOrderPrivateParams( - order, - signature, - takerTokenFillAmount, - taker, - sender - )); + ) public payable virtual onlySelf returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { + FillNativeOrderResults memory results = _fillLimitOrderPrivate( + FillLimitOrderPrivateParams(order, signature, takerTokenFillAmount, taker, sender) + ); (takerTokenFilledAmount, makerTokenFilledAmount) = ( results.takerTokenFilledAmount, results.makerTokenFilledAmount @@ -312,21 +286,10 @@ abstract contract NativeOrdersSettlement is address taker, bool useSelfBalance, address recipient - ) - public - virtual - onlySelf - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { - FillNativeOrderResults memory results = - _fillRfqOrderPrivate(FillRfqOrderPrivateParams( - order, - signature, - takerTokenFillAmount, - taker, - useSelfBalance, - recipient - )); + ) public virtual onlySelf returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { + FillNativeOrderResults memory results = _fillRfqOrderPrivate( + FillRfqOrderPrivateParams(order, signature, takerTokenFillAmount, taker, useSelfBalance, recipient) + ); (takerTokenFilledAmount, makerTokenFilledAmount) = ( results.takerTokenFilledAmount, results.makerTokenFilledAmount @@ -337,17 +300,10 @@ abstract contract NativeOrdersSettlement is /// specifies the message sender as its txOrigin. /// @param origins An array of origin addresses to update. /// @param allowed True to register, false to unregister. - function registerAllowedRfqOrigins( - address[] memory origins, - bool allowed - ) - external - { - require(msg.sender == tx.origin, - "NativeOrdersFeature/NO_CONTRACT_ORIGINS"); + function registerAllowedRfqOrigins(address[] memory origins, bool allowed) external { + require(msg.sender == tx.origin, "NativeOrdersFeature/NO_CONTRACT_ORIGINS"); - LibNativeOrdersStorage.Storage storage stor = - LibNativeOrdersStorage.getStorage(); + LibNativeOrdersStorage.Storage storage stor = LibNativeOrdersStorage.getStorage(); for (uint256 i = 0; i < origins.length; i++) { stor.originRegistry[msg.sender][origins[i]] = allowed; @@ -367,42 +323,30 @@ abstract contract NativeOrdersSettlement is // Must be fillable. if (orderInfo.status != LibNativeOrder.OrderStatus.FILLABLE) { - LibNativeOrdersRichErrors.OrderNotFillableError( - orderInfo.orderHash, - uint8(orderInfo.status) - ).rrevert(); + LibNativeOrdersRichErrors.OrderNotFillableError(orderInfo.orderHash, uint8(orderInfo.status)).rrevert(); } // Must be fillable by the taker. if (params.order.taker != address(0) && params.order.taker != params.taker) { - LibNativeOrdersRichErrors.OrderNotFillableByTakerError( - orderInfo.orderHash, - params.taker, - params.order.taker - ).rrevert(); + LibNativeOrdersRichErrors + .OrderNotFillableByTakerError(orderInfo.orderHash, params.taker, params.order.taker) + .rrevert(); } // Must be fillable by the sender. if (params.order.sender != address(0) && params.order.sender != params.sender) { - LibNativeOrdersRichErrors.OrderNotFillableBySenderError( - orderInfo.orderHash, - params.sender, - params.order.sender - ).rrevert(); + LibNativeOrdersRichErrors + .OrderNotFillableBySenderError(orderInfo.orderHash, params.sender, params.order.sender) + .rrevert(); } // Signature must be valid for the order. { - address signer = LibSignature.getSignerOfHash( - orderInfo.orderHash, - params.signature - ); + address signer = LibSignature.getSignerOfHash(orderInfo.orderHash, params.signature); if (signer != params.order.maker && !isValidOrderSigner(params.order.maker, signer)) { - LibNativeOrdersRichErrors.OrderNotSignedByMakerError( - orderInfo.orderHash, - signer, - params.order.maker - ).rrevert(); + LibNativeOrdersRichErrors + .OrderNotSignedByMakerError(orderInfo.orderHash, signer, params.order.maker) + .rrevert(); } } @@ -427,11 +371,13 @@ abstract contract NativeOrdersSettlement is // Pay the fee recipient. if (params.order.takerTokenFeeAmount > 0) { - results.takerTokenFeeFilledAmount = uint128(LibMathV06.getPartialAmountFloor( - results.takerTokenFilledAmount, - params.order.takerAmount, - params.order.takerTokenFeeAmount - )); + results.takerTokenFeeFilledAmount = uint128( + LibMathV06.getPartialAmountFloor( + results.takerTokenFilledAmount, + params.order.takerAmount, + params.order.takerTokenFeeAmount + ) + ); _transferERC20TokensFrom( params.order.takerToken, params.taker, @@ -466,53 +412,34 @@ abstract contract NativeOrdersSettlement is // Must be fillable. if (orderInfo.status != LibNativeOrder.OrderStatus.FILLABLE) { - LibNativeOrdersRichErrors.OrderNotFillableError( - orderInfo.orderHash, - uint8(orderInfo.status) - ).rrevert(); + LibNativeOrdersRichErrors.OrderNotFillableError(orderInfo.orderHash, uint8(orderInfo.status)).rrevert(); } { - LibNativeOrdersStorage.Storage storage stor = - LibNativeOrdersStorage.getStorage(); + LibNativeOrdersStorage.Storage storage stor = LibNativeOrdersStorage.getStorage(); // Must be fillable by the tx.origin. - if ( - params.order.txOrigin != tx.origin && - !stor.originRegistry[params.order.txOrigin][tx.origin] - ) { - LibNativeOrdersRichErrors.OrderNotFillableByOriginError( - orderInfo.orderHash, - tx.origin, - params.order.txOrigin - ).rrevert(); + if (params.order.txOrigin != tx.origin && !stor.originRegistry[params.order.txOrigin][tx.origin]) { + LibNativeOrdersRichErrors + .OrderNotFillableByOriginError(orderInfo.orderHash, tx.origin, params.order.txOrigin) + .rrevert(); } } // Must be fillable by the taker. if (params.order.taker != address(0) && params.order.taker != params.taker) { - LibNativeOrdersRichErrors.OrderNotFillableByTakerError( - orderInfo.orderHash, - params.taker, - params.order.taker - ).rrevert(); + LibNativeOrdersRichErrors + .OrderNotFillableByTakerError(orderInfo.orderHash, params.taker, params.order.taker) + .rrevert(); } // Signature must be valid for the order. { - address signer = LibSignature.getSignerOfHash( - orderInfo.orderHash, - params.signature - ); - if ( - signer != params.order.maker && - !isValidOrderSigner(params.order.maker, signer) - ) { - LibNativeOrdersRichErrors.OrderNotSignedByMakerError( - orderInfo.orderHash, - signer, - params.order.maker - ).rrevert(); + address signer = LibSignature.getSignerOfHash(orderInfo.orderHash, params.signature); + if (signer != params.order.maker && !isValidOrderSigner(params.order.maker, signer)) { + LibNativeOrdersRichErrors + .OrderNotSignedByMakerError(orderInfo.orderHash, signer, params.order.maker) + .rrevert(); } } @@ -560,11 +487,13 @@ abstract contract NativeOrdersSettlement is // Compute the maker token amount. // This should never overflow because the values are all clamped to // (2^128-1). - makerTokenFilledAmount = uint128(LibMathV06.getPartialAmountFloor( - uint256(takerTokenFilledAmount), - uint256(settleInfo.takerAmount), - uint256(settleInfo.makerAmount) - )); + makerTokenFilledAmount = uint128( + LibMathV06.getPartialAmountFloor( + uint256(takerTokenFilledAmount), + uint256(settleInfo.takerAmount), + uint256(settleInfo.makerAmount) + ) + ); if (takerTokenFilledAmount == 0 || makerTokenFilledAmount == 0) { // Nothing to do. @@ -572,50 +501,27 @@ abstract contract NativeOrdersSettlement is } // Update filled state for the order. - LibNativeOrdersStorage - .getStorage() - .orderHashToTakerTokenFilledAmount[settleInfo.orderHash] = - // OK to overwrite the whole word because we shouldn't get to this - // function if the order is cancelled. - settleInfo.takerTokenFilledAmount.safeAdd128(takerTokenFilledAmount); + LibNativeOrdersStorage.getStorage().orderHashToTakerTokenFilledAmount[settleInfo.orderHash] = settleInfo // function if the order is cancelled. // OK to overwrite the whole word because we shouldn't get to this + .takerTokenFilledAmount + .safeAdd128(takerTokenFilledAmount); if (settleInfo.payer == address(this)) { // Transfer this -> maker. - _transferERC20Tokens( - settleInfo.takerToken, - settleInfo.maker, - takerTokenFilledAmount - ); + _transferERC20Tokens(settleInfo.takerToken, settleInfo.maker, takerTokenFilledAmount); } else { // Transfer taker -> maker. - _transferERC20TokensFrom( - settleInfo.takerToken, - settleInfo.payer, - settleInfo.maker, - takerTokenFilledAmount - ); + _transferERC20TokensFrom(settleInfo.takerToken, settleInfo.payer, settleInfo.maker, takerTokenFilledAmount); } // Transfer maker -> recipient. - _transferERC20TokensFrom( - settleInfo.makerToken, - settleInfo.maker, - settleInfo.recipient, - makerTokenFilledAmount - ); + _transferERC20TokensFrom(settleInfo.makerToken, settleInfo.maker, settleInfo.recipient, makerTokenFilledAmount); } /// @dev register a signer who can sign on behalf of msg.sender /// @param signer The address from which you plan to generate signatures /// @param allowed True to register, false to unregister. - function registerAllowedOrderSigner( - address signer, - bool allowed - ) - external - { - LibNativeOrdersStorage.Storage storage stor = - LibNativeOrdersStorage.getStorage(); + function registerAllowedOrderSigner(address signer, bool allowed) external { + LibNativeOrdersStorage.Storage storage stor = LibNativeOrdersStorage.getStorage(); stor.orderSignerRegistry[msg.sender][signer] = allowed; diff --git a/contracts/zero-ex/contracts/src/features/nft_orders/ERC1155OrdersFeature.sol b/contracts/zero-ex/contracts/src/features/nft_orders/ERC1155OrdersFeature.sol index 4f2128874e..60384ee106 100644 --- a/contracts/zero-ex/contracts/src/features/nft_orders/ERC1155OrdersFeature.sol +++ b/contracts/zero-ex/contracts/src/features/nft_orders/ERC1155OrdersFeature.sol @@ -31,14 +31,8 @@ import "../libs/LibNFTOrder.sol"; import "../libs/LibSignature.sol"; import "./NFTOrders.sol"; - /// @dev Feature for interacting with ERC1155 orders. -contract ERC1155OrdersFeature is - IFeature, - IERC1155OrdersFeature, - FixinERC1155Spender, - NFTOrders -{ +contract ERC1155OrdersFeature is IFeature, IERC1155OrdersFeature, FixinERC1155Spender, NFTOrders { using LibSafeMathV06 for uint256; using LibSafeMathV06 for uint128; using LibNFTOrder for LibNFTOrder.ERC1155Order; @@ -52,19 +46,12 @@ contract ERC1155OrdersFeature is /// @dev The magic return value indicating the success of a `onERC1155Received`. bytes4 private constant ERC1155_RECEIVED_MAGIC_BYTES = this.onERC1155Received.selector; - - constructor(address zeroExAddress, IEtherTokenV06 weth) - public - NFTOrders(zeroExAddress, weth) - {} + constructor(address zeroExAddress, IEtherTokenV06 weth) public NFTOrders(zeroExAddress, weth) {} /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. - function migrate() - external - returns (bytes4 success) - { + function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.sellERC1155.selector); _registerFeatureFunction(this.buyERC1155.selector); _registerFeatureFunction(this.cancelERC1155Order.selector); @@ -101,10 +88,7 @@ contract ERC1155OrdersFeature is uint128 erc1155SellAmount, bool unwrapNativeToken, bytes memory callbackData - ) - public - override - { + ) public override { _sellERC1155( buyOrder, signature, @@ -135,29 +119,15 @@ contract ERC1155OrdersFeature is LibSignature.Signature memory signature, uint128 erc1155BuyAmount, bytes memory callbackData - ) - public - override - payable - { - uint256 ethBalanceBefore = address(this).balance - .safeSub(msg.value); - _buyERC1155( - sellOrder, - signature, - BuyParams( - erc1155BuyAmount, - msg.value, - callbackData - ) - ); + ) public payable override { + uint256 ethBalanceBefore = address(this).balance.safeSub(msg.value); + _buyERC1155(sellOrder, signature, BuyParams(erc1155BuyAmount, msg.value, callbackData)); uint256 ethBalanceAfter = address(this).balance; // Cannot use pre-existing ETH balance if (ethBalanceAfter < ethBalanceBefore) { - LibNFTOrdersRichErrors.OverspentEthError( - ethBalanceBefore - ethBalanceAfter + msg.value, - msg.value - ).rrevert(); + LibNFTOrdersRichErrors + .OverspentEthError(ethBalanceBefore - ethBalanceAfter + msg.value, msg.value) + .rrevert(); } // Refund _transferEth(msg.sender, ethBalanceAfter - ethBalanceBefore); @@ -168,16 +138,12 @@ contract ERC1155OrdersFeature is /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonce The order nonce. - function cancelERC1155Order(uint256 orderNonce) - public - override - { + function cancelERC1155Order(uint256 orderNonce) public override { // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (orderNonce & 255); // Update order cancellation bit vector to indicate that the order // has been cancelled/filled by setting the designated bit to 1. - LibERC1155OrdersStorage.getStorage().orderCancellationByMaker - [msg.sender][uint248(orderNonce >> 8)] |= flag; + LibERC1155OrdersStorage.getStorage().orderCancellationByMaker[msg.sender][uint248(orderNonce >> 8)] |= flag; emit ERC1155OrderCancelled(msg.sender, orderNonce); } @@ -187,10 +153,7 @@ contract ERC1155OrdersFeature is /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonces The order nonces. - function batchCancelERC1155Orders(uint256[] calldata orderNonces) - external - override - { + function batchCancelERC1155Orders(uint256[] calldata orderNonces) external override { for (uint256 i = 0; i < orderNonces.length; i++) { cancelERC1155Order(orderNonces[i]); } @@ -215,22 +178,16 @@ contract ERC1155OrdersFeature is uint128[] calldata erc1155FillAmounts, bytes[] memory callbackData, bool revertIfIncomplete - ) - public - override - payable - returns (bool[] memory successes) - { + ) public payable override returns (bool[] memory successes) { require( sellOrders.length == signatures.length && - sellOrders.length == erc1155FillAmounts.length && - sellOrders.length == callbackData.length, + sellOrders.length == erc1155FillAmounts.length && + sellOrders.length == callbackData.length, "ERC1155OrdersFeature::batchBuyERC1155s/ARRAY_LENGTH_MISMATCH" ); successes = new bool[](sellOrders.length); - uint256 ethBalanceBefore = address(this).balance - .safeSub(msg.value); + uint256 ethBalanceBefore = address(this).balance.safeSub(msg.value); if (revertIfIncomplete) { for (uint256 i = 0; i < sellOrders.length; i++) { // Will revert if _buyERC1155 reverts. @@ -269,10 +226,9 @@ contract ERC1155OrdersFeature is // Cannot use pre-existing ETH balance uint256 ethBalanceAfter = address(this).balance; if (ethBalanceAfter < ethBalanceBefore) { - LibNFTOrdersRichErrors.OverspentEthError( - msg.value + (ethBalanceBefore - ethBalanceAfter), - msg.value - ).rrevert(); + LibNFTOrdersRichErrors + .OverspentEthError(msg.value + (ethBalanceBefore - ethBalanceAfter), msg.value) + .rrevert(); } // Refund @@ -295,15 +251,11 @@ contract ERC1155OrdersFeature is /// indicating that the callback succeeded. function onERC1155Received( address operator, - address /* from */, + address, /* from */ uint256 tokenId, uint256 value, bytes calldata data - ) - external - override - returns (bytes4 success) - { + ) external override returns (bytes4 success) { // Decode the order, signature, and `unwrapNativeToken` from // `data`. If `data` does not encode such parameters, this // will throw. @@ -311,18 +263,12 @@ contract ERC1155OrdersFeature is LibNFTOrder.ERC1155Order memory buyOrder, LibSignature.Signature memory signature, bool unwrapNativeToken - ) = abi.decode( - data, - (LibNFTOrder.ERC1155Order, LibSignature.Signature, bool) - ); + ) = abi.decode(data, (LibNFTOrder.ERC1155Order, LibSignature.Signature, bool)); // `onERC1155Received` is called by the ERC1155 token contract. // Check that it matches the ERC1155 token in the order. if (msg.sender != address(buyOrder.erc1155Token)) { - LibNFTOrdersRichErrors.ERC1155TokenMismatchError( - msg.sender, - address(buyOrder.erc1155Token) - ).rrevert(); + LibNFTOrdersRichErrors.ERC1155TokenMismatchError(msg.sender, address(buyOrder.erc1155Token)).rrevert(); } _sellERC1155( @@ -332,9 +278,9 @@ contract ERC1155OrdersFeature is value.safeDowncastToUint128(), tokenId, unwrapNativeToken, - operator, // taker - address(this), // owner (we hold the NFT currently) - new bytes(0) // No taker callback + operator, // taker + address(this), // owner (we hold the NFT currently) + new bytes(0) // No taker callback ) ); @@ -345,18 +291,11 @@ contract ERC1155OrdersFeature is /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 order. - function preSignERC1155Order(LibNFTOrder.ERC1155Order memory order) - public - override - { - require( - order.maker == msg.sender, - "ERC1155OrdersFeature::preSignERC1155Order/MAKER_MISMATCH" - ); + function preSignERC1155Order(LibNFTOrder.ERC1155Order memory order) public override { + require(order.maker == msg.sender, "ERC1155OrdersFeature::preSignERC1155Order/MAKER_MISMATCH"); bytes32 orderHash = getERC1155OrderHash(order); - LibERC1155OrdersStorage.Storage storage stor = - LibERC1155OrdersStorage.getStorage(); + LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); // Set `preSigned` to true on the order state variable // to indicate that the order has been pre-signed. stor.orderState[orderHash].preSigned = true; @@ -383,14 +322,8 @@ contract ERC1155OrdersFeature is LibNFTOrder.ERC1155Order memory buyOrder, LibSignature.Signature memory signature, SellParams memory params - ) - private - { - uint256 erc20FillAmount = _sellNFT( - buyOrder.asNFTOrder(), - signature, - params - ); + ) private { + uint256 erc20FillAmount = _sellNFT(buyOrder.asNFTOrder(), signature, params); emit ERC1155OrderFilled( buyOrder.direction, @@ -412,15 +345,8 @@ contract ERC1155OrdersFeature is LibNFTOrder.ERC1155Order memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params - ) - public - payable - { - uint256 erc20FillAmount = _buyNFT( - sellOrder.asNFTOrder(), - signature, - params - ); + ) public payable { + uint256 erc20FillAmount = _buyNFT(sellOrder.asNFTOrder(), signature, params); emit ERC1155OrderFilled( sellOrder.direction, @@ -443,11 +369,7 @@ contract ERC1155OrdersFeature is function validateERC1155OrderSignature( LibNFTOrder.ERC1155Order memory order, LibSignature.Signature memory signature - ) - public - override - view - { + ) public view override { bytes32 orderHash = getERC1155OrderHash(order); _validateOrderSignature(orderHash, signature, order.maker); } @@ -462,15 +384,10 @@ contract ERC1155OrdersFeature is bytes32 orderHash, LibSignature.Signature memory signature, address maker - ) - internal - override - view - { + ) internal view override { if (signature.signatureType == LibSignature.SignatureType.PRESIGNED) { // Check if order hash has been pre-signed by the maker. - bool isPreSigned = LibERC1155OrdersStorage.getStorage() - .orderState[orderHash].preSigned; + bool isPreSigned = LibERC1155OrdersStorage.getStorage().orderState[orderHash].preSigned; if (!isPreSigned) { LibNFTOrdersRichErrors.InvalidSignerError(maker, address(0)).rrevert(); } @@ -495,10 +412,7 @@ contract ERC1155OrdersFeature is address to, uint256 tokenId, uint256 amount - ) - internal - override - { + ) internal override { _transferERC1155AssetFrom(IERC1155Token(token), from, to, tokenId, amount); } @@ -508,13 +422,10 @@ contract ERC1155OrdersFeature is /// @param fillAmount The amount (denominated in the NFT asset) /// that the order has been filled by. function _updateOrderState( - LibNFTOrder.NFTOrder memory /* order */, + LibNFTOrder.NFTOrder memory, /* order */ bytes32 orderHash, uint128 fillAmount - ) - internal - override - { + ) internal override { LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); uint128 filledAmount = stor.orderState[orderHash].filledAmount; // Filled amount should never overflow 128 bits @@ -531,18 +442,12 @@ contract ERC1155OrdersFeature is /// an ERC1155 asset. /// @param order The ERC1155 order. /// @param erc1155TokenId The ID of the ERC1155 asset. - function validateERC1155OrderProperties( - LibNFTOrder.ERC1155Order memory order, - uint256 erc1155TokenId - ) + function validateERC1155OrderProperties(LibNFTOrder.ERC1155Order memory order, uint256 erc1155TokenId) public - override view + override { - _validateOrderProperties( - order.asNFTOrder(), - erc1155TokenId - ); + _validateOrderProperties(order.asNFTOrder(), erc1155TokenId); } /// @dev Get the order info for an ERC1155 order. @@ -550,8 +455,8 @@ contract ERC1155OrdersFeature is /// @return orderInfo Info about the order. function getERC1155OrderInfo(LibNFTOrder.ERC1155Order memory order) public - override view + override returns (LibNFTOrder.OrderInfo memory orderInfo) { orderInfo.orderAmount = order.erc1155TokenAmount; @@ -559,19 +464,19 @@ contract ERC1155OrdersFeature is // Only buy orders with `erc1155TokenId` == 0 can be property // orders. - if (order.erc1155TokenProperties.length > 0 && - (order.direction != LibNFTOrder.TradeDirection.BUY_NFT || - order.erc1155TokenId != 0)) - { + if ( + order.erc1155TokenProperties.length > 0 && + (order.direction != LibNFTOrder.TradeDirection.BUY_NFT || order.erc1155TokenId != 0) + ) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } // Buy orders cannot use ETH as the ERC20 token, since ETH cannot be // transferred from the buyer by a contract. - if (order.direction == LibNFTOrder.TradeDirection.BUY_NFT && - address(order.erc20Token) == NATIVE_TOKEN_ADDRESS) - { + if ( + order.direction == LibNFTOrder.TradeDirection.BUY_NFT && address(order.erc20Token) == NATIVE_TOKEN_ADDRESS + ) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } @@ -583,23 +488,17 @@ contract ERC1155OrdersFeature is } { - LibERC1155OrdersStorage.Storage storage stor = - LibERC1155OrdersStorage.getStorage(); + LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); - LibERC1155OrdersStorage.OrderState storage orderState = - stor.orderState[orderInfo.orderHash]; - orderInfo.remainingAmount = order.erc1155TokenAmount - .safeSub128(orderState.filledAmount); + LibERC1155OrdersStorage.OrderState storage orderState = stor.orderState[orderInfo.orderHash]; + orderInfo.remainingAmount = order.erc1155TokenAmount.safeSub128(orderState.filledAmount); // `orderCancellationByMaker` is indexed by maker and nonce. - uint256 orderCancellationBitVector = - stor.orderCancellationByMaker[order.maker][uint248(order.nonce >> 8)]; + uint256 orderCancellationBitVector = stor.orderCancellationByMaker[order.maker][uint248(order.nonce >> 8)]; // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (order.nonce & 255); - if (orderInfo.remainingAmount == 0 || - orderCancellationBitVector & flag != 0) - { + if (orderInfo.remainingAmount == 0 || orderCancellationBitVector & flag != 0) { orderInfo.status = LibNFTOrder.OrderStatus.UNFILLABLE; return orderInfo; } @@ -614,8 +513,8 @@ contract ERC1155OrdersFeature is /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTOrder memory order) internal - override view + override returns (LibNFTOrder.OrderInfo memory orderInfo) { return getERC1155OrderInfo(order.asERC1155Order()); @@ -626,8 +525,8 @@ contract ERC1155OrdersFeature is /// @return orderHash The order hash. function getERC1155OrderHash(LibNFTOrder.ERC1155Order memory order) public - override view + override returns (bytes32 orderHash) { return _getEIP712Hash(LibNFTOrder.getERC1155OrderStructHash(order)); diff --git a/contracts/zero-ex/contracts/src/features/nft_orders/ERC721OrdersFeature.sol b/contracts/zero-ex/contracts/src/features/nft_orders/ERC721OrdersFeature.sol index 49b5d0a862..5144f7b31d 100644 --- a/contracts/zero-ex/contracts/src/features/nft_orders/ERC721OrdersFeature.sol +++ b/contracts/zero-ex/contracts/src/features/nft_orders/ERC721OrdersFeature.sol @@ -31,14 +31,8 @@ import "../libs/LibNFTOrder.sol"; import "../libs/LibSignature.sol"; import "./NFTOrders.sol"; - /// @dev Feature for interacting with ERC721 orders. -contract ERC721OrdersFeature is - IFeature, - IERC721OrdersFeature, - FixinERC721Spender, - NFTOrders -{ +contract ERC721OrdersFeature is IFeature, IERC721OrdersFeature, FixinERC721Spender, NFTOrders { using LibSafeMathV06 for uint256; using LibNFTOrder for LibNFTOrder.ERC721Order; using LibNFTOrder for LibNFTOrder.NFTOrder; @@ -51,19 +45,12 @@ contract ERC721OrdersFeature is /// @dev The magic return value indicating the success of a `onERC721Received`. bytes4 private constant ERC721_RECEIVED_MAGIC_BYTES = this.onERC721Received.selector; - - constructor(address zeroExAddress, IEtherTokenV06 weth) - public - NFTOrders(zeroExAddress, weth) - {} + constructor(address zeroExAddress, IEtherTokenV06 weth) public NFTOrders(zeroExAddress, weth) {} /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. - function migrate() - external - returns (bytes4 success) - { + function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.sellERC721.selector); _registerFeatureFunction(this.buyERC721.selector); _registerFeatureFunction(this.cancelERC721Order.selector); @@ -100,10 +87,7 @@ contract ERC721OrdersFeature is uint256 erc721TokenId, bool unwrapNativeToken, bytes memory callbackData - ) - public - override - { + ) public override { _sellERC721( buyOrder, signature, @@ -128,26 +112,15 @@ contract ERC721OrdersFeature is LibNFTOrder.ERC721Order memory sellOrder, LibSignature.Signature memory signature, bytes memory callbackData - ) - public - override - payable - { - uint256 ethBalanceBefore = address(this).balance - .safeSub(msg.value); - _buyERC721( - sellOrder, - signature, - msg.value, - callbackData - ); + ) public payable override { + uint256 ethBalanceBefore = address(this).balance.safeSub(msg.value); + _buyERC721(sellOrder, signature, msg.value, callbackData); uint256 ethBalanceAfter = address(this).balance; // Cannot use pre-existing ETH balance if (ethBalanceAfter < ethBalanceBefore) { - LibNFTOrdersRichErrors.OverspentEthError( - msg.value + (ethBalanceBefore - ethBalanceAfter), - msg.value - ).rrevert(); + LibNFTOrdersRichErrors + .OverspentEthError(msg.value + (ethBalanceBefore - ethBalanceAfter), msg.value) + .rrevert(); } // Refund _transferEth(msg.sender, ethBalanceAfter - ethBalanceBefore); @@ -158,10 +131,7 @@ contract ERC721OrdersFeature is /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonce The order nonce. - function cancelERC721Order(uint256 orderNonce) - public - override - { + function cancelERC721Order(uint256 orderNonce) public override { // Mark order as cancelled _setOrderStatusBit(msg.sender, orderNonce); emit ERC721OrderCancelled(msg.sender, orderNonce); @@ -172,10 +142,7 @@ contract ERC721OrdersFeature is /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonces The order nonces. - function batchCancelERC721Orders(uint256[] calldata orderNonces) - external - override - { + function batchCancelERC721Orders(uint256[] calldata orderNonces) external override { for (uint256 i = 0; i < orderNonces.length; i++) { cancelERC721Order(orderNonces[i]); } @@ -197,21 +164,14 @@ contract ERC721OrdersFeature is LibSignature.Signature[] memory signatures, bytes[] memory callbackData, bool revertIfIncomplete - ) - public - override - payable - returns (bool[] memory successes) - { + ) public payable override returns (bool[] memory successes) { require( - sellOrders.length == signatures.length && - sellOrders.length == callbackData.length, + sellOrders.length == signatures.length && sellOrders.length == callbackData.length, "ERC721OrdersFeature::batchBuyERC721s/ARRAY_LENGTH_MISMATCH" ); successes = new bool[](sellOrders.length); - uint256 ethBalanceBefore = address(this).balance - .safeSub(msg.value); + uint256 ethBalanceBefore = address(this).balance.safeSub(msg.value); if (revertIfIncomplete) { for (uint256 i = 0; i < sellOrders.length; i++) { // Will revert if _buyERC721 reverts. @@ -244,10 +204,9 @@ contract ERC721OrdersFeature is // Cannot use pre-existing ETH balance uint256 ethBalanceAfter = address(this).balance; if (ethBalanceAfter < ethBalanceBefore) { - LibNFTOrdersRichErrors.OverspentEthError( - msg.value + (ethBalanceBefore - ethBalanceAfter), - msg.value - ).rrevert(); + LibNFTOrdersRichErrors + .OverspentEthError(msg.value + (ethBalanceBefore - ethBalanceAfter), msg.value) + .rrevert(); } // Refund @@ -270,17 +229,12 @@ contract ERC721OrdersFeature is LibNFTOrder.ERC721Order memory buyOrder, LibSignature.Signature memory sellOrderSignature, LibSignature.Signature memory buyOrderSignature - ) - public - override - returns (uint256 profit) - { + ) public override returns (uint256 profit) { // The ERC721 tokens must match if (sellOrder.erc721Token != buyOrder.erc721Token) { - LibNFTOrdersRichErrors.ERC721TokenMismatchError( - address(sellOrder.erc721Token), - address(buyOrder.erc721Token) - ).rrevert(); + LibNFTOrdersRichErrors + .ERC721TokenMismatchError(address(sellOrder.erc721Token), address(buyOrder.erc721Token)) + .rrevert(); } LibNFTOrder.NFTOrder memory sellNFTOrder = sellOrder.asNFTOrder(); @@ -290,19 +244,8 @@ contract ERC721OrdersFeature is LibNFTOrder.OrderInfo memory sellOrderInfo = _getOrderInfo(sellNFTOrder); LibNFTOrder.OrderInfo memory buyOrderInfo = _getOrderInfo(buyNFTOrder); - _validateSellOrder( - sellNFTOrder, - sellOrderSignature, - sellOrderInfo, - buyOrder.maker - ); - _validateBuyOrder( - buyNFTOrder, - buyOrderSignature, - buyOrderInfo, - sellOrder.maker, - sellOrder.erc721TokenId - ); + _validateSellOrder(sellNFTOrder, sellOrderSignature, sellOrderInfo, buyOrder.maker); + _validateBuyOrder(buyNFTOrder, buyOrderSignature, buyOrderInfo, sellOrder.maker, sellOrder.erc721TokenId); // Mark both orders as filled. _updateOrderState(sellNFTOrder, sellOrderInfo.orderHash, 1); @@ -312,28 +255,17 @@ contract ERC721OrdersFeature is // The buyer must be willing to pay at least the amount that the // seller is asking. if (buyOrder.erc20TokenAmount < sellOrder.erc20TokenAmount) { - LibNFTOrdersRichErrors.NegativeSpreadError( - sellOrder.erc20TokenAmount, - buyOrder.erc20TokenAmount - ).rrevert(); + LibNFTOrdersRichErrors.NegativeSpreadError(sellOrder.erc20TokenAmount, buyOrder.erc20TokenAmount).rrevert(); } // The difference in ERC20 token amounts is the spread. uint256 spread = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount; // Transfer the ERC721 asset from seller to buyer. - _transferERC721AssetFrom( - sellOrder.erc721Token, - sellOrder.maker, - buyOrder.maker, - sellOrder.erc721TokenId - ); + _transferERC721AssetFrom(sellOrder.erc721Token, sellOrder.maker, buyOrder.maker, sellOrder.erc721TokenId); // Handle the ERC20 side of the order: - if ( - address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS && - buyOrder.erc20Token == WETH - ) { + if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS && buyOrder.erc20Token == WETH) { // The sell order specifies ETH, while the buy order specifies WETH. // The orders are still compatible with one another, but we'll have // to unwrap the WETH on behalf of the buyer. @@ -343,12 +275,7 @@ contract ERC721OrdersFeature is // is the amount the buyer signaled they are willing to pay // for the ERC721 asset, which may be more than the seller's // ask. - _transferERC20TokensFrom( - WETH, - buyOrder.maker, - address(this), - buyOrder.erc20TokenAmount - ); + _transferERC20TokensFrom(WETH, buyOrder.maker, address(this), buyOrder.erc20TokenAmount); // Step 2: Unwrap the WETH into ETH. We unwrap the entire // `buyOrder.erc20TokenAmount`. // The ETH will be used for three purposes: @@ -369,9 +296,9 @@ contract ERC721OrdersFeature is _payFees( buyNFTOrder, buyOrder.maker, // payer - 1, // fillAmount - 1, // orderAmount - false // useNativeToken + 1, // fillAmount + 1, // orderAmount + false // useNativeToken ); // Step 5: Pay fees for the sell order. The `erc20Token` of the @@ -382,9 +309,9 @@ contract ERC721OrdersFeature is uint256 sellOrderFees = _payFees( sellNFTOrder, address(this), // payer - 1, // fillAmount - 1, // orderAmount - true // useNativeToken + 1, // fillAmount + 1, // orderAmount + true // useNativeToken ); // Step 6: The spread must be enough to cover the sell order fees. @@ -392,10 +319,7 @@ contract ERC721OrdersFeature is // have spent ETH that was in the EP before this // `matchERC721Orders` call, which we disallow. if (spread < sellOrderFees) { - LibNFTOrdersRichErrors.SellOrderFeesExceedSpreadError( - sellOrderFees, - spread - ).rrevert(); + LibNFTOrdersRichErrors.SellOrderFeesExceedSpreadError(sellOrderFees, spread).rrevert(); } // Step 7: The spread less the sell order fees is the amount of ETH // remaining in the EP that can be sent to `msg.sender` as @@ -407,21 +331,15 @@ contract ERC721OrdersFeature is } else { // ERC20 tokens must match if (sellOrder.erc20Token != buyOrder.erc20Token) { - LibNFTOrdersRichErrors.ERC20TokenMismatchError( - address(sellOrder.erc20Token), - address(buyOrder.erc20Token) - ).rrevert(); + LibNFTOrdersRichErrors + .ERC20TokenMismatchError(address(sellOrder.erc20Token), address(buyOrder.erc20Token)) + .rrevert(); } // Step 1: Transfer the ERC20 token from the buyer to the seller. // Note that we transfer `sellOrder.erc20TokenAmount`, which // is at most `buyOrder.erc20TokenAmount`. - _transferERC20TokensFrom( - buyOrder.erc20Token, - buyOrder.maker, - sellOrder.maker, - sellOrder.erc20TokenAmount - ); + _transferERC20TokensFrom(buyOrder.erc20Token, buyOrder.maker, sellOrder.maker, sellOrder.erc20TokenAmount); // Step 2: Pay fees for the buy order. Note that these are paid // by the buyer. By signing the buy order, the buyer signals @@ -430,9 +348,9 @@ contract ERC721OrdersFeature is _payFees( buyNFTOrder, buyOrder.maker, // payer - 1, // fillAmount - 1, // orderAmount - false // useNativeToken + 1, // fillAmount + 1, // orderAmount + false // useNativeToken ); // Step 3: Pay fees for the sell order. These are paid by the buyer @@ -442,9 +360,9 @@ contract ERC721OrdersFeature is uint256 sellOrderFees = _payFees( sellNFTOrder, buyOrder.maker, // payer - 1, // fillAmount - 1, // orderAmount - false // useNativeToken + 1, // fillAmount + 1, // orderAmount + false // useNativeToken ); // Step 4: The spread must be enough to cover the sell order fees. @@ -452,10 +370,7 @@ contract ERC721OrdersFeature is // buyer than they had agreed to in the buy order, in which // case we revert here. if (spread < sellOrderFees) { - LibNFTOrdersRichErrors.SellOrderFeesExceedSpreadError( - sellOrderFees, - spread - ).rrevert(); + LibNFTOrdersRichErrors.SellOrderFeesExceedSpreadError(sellOrderFees, spread).rrevert(); } // Step 5: We calculate the profit as: @@ -466,12 +381,7 @@ contract ERC721OrdersFeature is // `msg.sender` as the profit from matching these two orders. profit = spread - sellOrderFees; if (profit > 0) { - _transferERC20TokensFrom( - buyOrder.erc20Token, - buyOrder.maker, - msg.sender, - profit - ); + _transferERC20TokensFrom(buyOrder.erc20Token, buyOrder.maker, msg.sender, profit); } } @@ -518,15 +428,11 @@ contract ERC721OrdersFeature is LibNFTOrder.ERC721Order[] memory buyOrders, LibSignature.Signature[] memory sellOrderSignatures, LibSignature.Signature[] memory buyOrderSignatures - ) - public - override - returns (uint256[] memory profits, bool[] memory successes) - { + ) public override returns (uint256[] memory profits, bool[] memory successes) { require( sellOrders.length == buyOrders.length && - sellOrderSignatures.length == buyOrderSignatures.length && - sellOrders.length == sellOrderSignatures.length, + sellOrderSignatures.length == buyOrderSignatures.length && + sellOrders.length == sellOrderSignatures.length, "ERC721OrdersFeature::batchMatchERC721Orders/ARRAY_LENGTH_MISMATCH" ); profits = new uint256[](sellOrders.length); @@ -547,7 +453,7 @@ contract ERC721OrdersFeature is ); if (successes[i]) { // If the matching succeeded, record the profit. - (uint256 profit) = abi.decode(returnData, (uint256)); + uint256 profit = abi.decode(returnData, (uint256)); profits[i] = profit; } } @@ -568,33 +474,20 @@ contract ERC721OrdersFeature is /// indicating that the callback succeeded. function onERC721Received( address operator, - address /* from */, + address, /* from */ uint256 tokenId, bytes calldata data - ) - external - override - returns (bytes4 success) - { + ) external override returns (bytes4 success) { // Decode the order, signature, and `unwrapNativeToken` from // `data`. If `data` does not encode such parameters, this // will throw. - ( - LibNFTOrder.ERC721Order memory buyOrder, - LibSignature.Signature memory signature, - bool unwrapNativeToken - ) = abi.decode( - data, - (LibNFTOrder.ERC721Order, LibSignature.Signature, bool) - ); + (LibNFTOrder.ERC721Order memory buyOrder, LibSignature.Signature memory signature, bool unwrapNativeToken) = abi + .decode(data, (LibNFTOrder.ERC721Order, LibSignature.Signature, bool)); // `onERC721Received` is called by the ERC721 token contract. // Check that it matches the ERC721 token in the order. if (msg.sender != address(buyOrder.erc721Token)) { - LibNFTOrdersRichErrors.ERC721TokenMismatchError( - msg.sender, - address(buyOrder.erc721Token) - ).rrevert(); + LibNFTOrdersRichErrors.ERC721TokenMismatchError(msg.sender, address(buyOrder.erc721Token)).rrevert(); } _sellERC721( @@ -602,9 +495,9 @@ contract ERC721OrdersFeature is signature, tokenId, unwrapNativeToken, - operator, // taker - address(this), // owner (we hold the NFT currently) - new bytes(0) // No taker callback + operator, // taker + address(this), // owner (we hold the NFT currently) + new bytes(0) // No taker callback ); return ERC721_RECEIVED_MAGIC_BYTES; @@ -614,14 +507,8 @@ contract ERC721OrdersFeature is /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC721 order. - function preSignERC721Order(LibNFTOrder.ERC721Order memory order) - public - override - { - require( - order.maker == msg.sender, - "ERC721OrdersFeature::preSignERC721Order/ONLY_MAKER" - ); + function preSignERC721Order(LibNFTOrder.ERC721Order memory order) public override { + require(order.maker == msg.sender, "ERC721OrdersFeature::preSignERC721Order/ONLY_MAKER"); bytes32 orderHash = getERC721OrderHash(order); LibERC721OrdersStorage.getStorage().preSigned[orderHash] = true; @@ -650,9 +537,7 @@ contract ERC721OrdersFeature is address taker, address currentNftOwner, bytes memory takerCallbackData - ) - private - { + ) private { _sellNFT( buyOrder.asNFTOrder(), signature, @@ -686,10 +571,7 @@ contract ERC721OrdersFeature is LibSignature.Signature memory signature, uint256 ethAvailable, bytes memory takerCallbackData - ) - public - payable - { + ) public payable { _buyNFT( sellOrder.asNFTOrder(), signature, @@ -713,18 +595,14 @@ contract ERC721OrdersFeature is ); } - /// @dev Checks whether the given signature is valid for the /// the given ERC721 order. Reverts if not. /// @param order The ERC721 order. /// @param signature The signature to validate. - function validateERC721OrderSignature( - LibNFTOrder.ERC721Order memory order, - LibSignature.Signature memory signature - ) + function validateERC721OrderSignature(LibNFTOrder.ERC721Order memory order, LibSignature.Signature memory signature) public - override view + override { bytes32 orderHash = getERC721OrderHash(order); _validateOrderSignature(orderHash, signature, order.maker); @@ -740,11 +618,7 @@ contract ERC721OrdersFeature is bytes32 orderHash, LibSignature.Signature memory signature, address maker - ) - internal - override - view - { + ) internal view override { if (signature.signatureType == LibSignature.SignatureType.PRESIGNED) { // Check if order hash has been pre-signed by the maker. bool isPreSigned = LibERC721OrdersStorage.getStorage().preSigned[orderHash]; @@ -772,10 +646,7 @@ contract ERC721OrdersFeature is address to, uint256 tokenId, uint256 amount - ) - internal - override - { + ) internal override { assert(amount == 1); _transferERC721AssetFrom(IERC721Token(token), from, to, tokenId); } @@ -787,25 +658,19 @@ contract ERC721OrdersFeature is /// that the order has been filled by. function _updateOrderState( LibNFTOrder.NFTOrder memory order, - bytes32 /* orderHash */, + bytes32, /* orderHash */ uint128 fillAmount - ) - internal - override - { + ) internal override { assert(fillAmount == 1); _setOrderStatusBit(order.maker, order.nonce); } - function _setOrderStatusBit(address maker, uint256 nonce) - private - { + function _setOrderStatusBit(address maker, uint256 nonce) private { // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (nonce & 255); // Update order status bit vector to indicate that the given order // has been cancelled/filled by setting the designated bit to 1. - LibERC721OrdersStorage.getStorage().orderStatusByMaker - [maker][uint248(nonce >> 8)] |= flag; + LibERC721OrdersStorage.getStorage().orderStatusByMaker[maker][uint248(nonce >> 8)] |= flag; } /// @dev If the given order is buying an ERC721 asset, checks @@ -817,18 +682,12 @@ contract ERC721OrdersFeature is /// an ERC721 asset. /// @param order The ERC721 order. /// @param erc721TokenId The ID of the ERC721 asset. - function validateERC721OrderProperties( - LibNFTOrder.ERC721Order memory order, - uint256 erc721TokenId - ) + function validateERC721OrderProperties(LibNFTOrder.ERC721Order memory order, uint256 erc721TokenId) public - override view + override { - _validateOrderProperties( - order.asNFTOrder(), - erc721TokenId - ); + _validateOrderProperties(order.asNFTOrder(), erc721TokenId); } /// @dev Get the current status of an ERC721 order. @@ -836,24 +695,24 @@ contract ERC721OrdersFeature is /// @return status The status of the order. function getERC721OrderStatus(LibNFTOrder.ERC721Order memory order) public - override view + override returns (LibNFTOrder.OrderStatus status) { // Only buy orders with `erc721TokenId` == 0 can be property // orders. - if (order.erc721TokenProperties.length > 0 && - (order.direction != LibNFTOrder.TradeDirection.BUY_NFT || - order.erc721TokenId != 0)) - { + if ( + order.erc721TokenProperties.length > 0 && + (order.direction != LibNFTOrder.TradeDirection.BUY_NFT || order.erc721TokenId != 0) + ) { return LibNFTOrder.OrderStatus.INVALID; } // Buy orders cannot use ETH as the ERC20 token, since ETH cannot be // transferred from the buyer by a contract. - if (order.direction == LibNFTOrder.TradeDirection.BUY_NFT && - address(order.erc20Token) == NATIVE_TOKEN_ADDRESS) - { + if ( + order.direction == LibNFTOrder.TradeDirection.BUY_NFT && address(order.erc20Token) == NATIVE_TOKEN_ADDRESS + ) { return LibNFTOrder.OrderStatus.INVALID; } @@ -864,11 +723,9 @@ contract ERC721OrdersFeature is // Check `orderStatusByMaker` state variable to see if the order // has been cancelled or previously filled. - LibERC721OrdersStorage.Storage storage stor = - LibERC721OrdersStorage.getStorage(); + LibERC721OrdersStorage.Storage storage stor = LibERC721OrdersStorage.getStorage(); // `orderStatusByMaker` is indexed by maker and nonce. - uint256 orderStatusBitVector = - stor.orderStatusByMaker[order.maker][uint248(order.nonce >> 8)]; + uint256 orderStatusBitVector = stor.orderStatusByMaker[order.maker][uint248(order.nonce >> 8)]; // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (order.nonce & 255); // If the designated bit is set, the order has been cancelled or @@ -886,8 +743,8 @@ contract ERC721OrdersFeature is /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTOrder memory order) internal - override view + override returns (LibNFTOrder.OrderInfo memory orderInfo) { LibNFTOrder.ERC721Order memory erc721Order = order.asERC721Order(); @@ -900,12 +757,7 @@ contract ERC721OrdersFeature is /// @dev Get the EIP-712 hash of an ERC721 order. /// @param order The ERC721 order. /// @return orderHash The order hash. - function getERC721OrderHash(LibNFTOrder.ERC721Order memory order) - public - override - view - returns (bytes32 orderHash) - { + function getERC721OrderHash(LibNFTOrder.ERC721Order memory order) public view override returns (bytes32 orderHash) { return _getEIP712Hash(LibNFTOrder.getERC721OrderStructHash(order)); } @@ -920,12 +772,11 @@ contract ERC721OrdersFeature is /// given maker and nonce range. function getERC721OrderStatusBitVector(address maker, uint248 nonceRange) external - override view + override returns (uint256 bitVector) { - LibERC721OrdersStorage.Storage storage stor = - LibERC721OrdersStorage.getStorage(); + LibERC721OrdersStorage.Storage storage stor = LibERC721OrdersStorage.getStorage(); return stor.orderStatusByMaker[maker][nonceRange]; } } diff --git a/contracts/zero-ex/contracts/src/features/nft_orders/NFTOrders.sol b/contracts/zero-ex/contracts/src/features/nft_orders/NFTOrders.sol index 10272683ce..07fa854668 100644 --- a/contracts/zero-ex/contracts/src/features/nft_orders/NFTOrders.sol +++ b/contracts/zero-ex/contracts/src/features/nft_orders/NFTOrders.sol @@ -34,17 +34,12 @@ import "../../vendor/ITakerCallback.sol"; import "../libs/LibSignature.sol"; import "../libs/LibNFTOrder.sol"; - /// @dev Abstract base contract inherited by ERC721OrdersFeature and NFTOrders -abstract contract NFTOrders is - FixinCommon, - FixinEIP712, - FixinTokenSpender -{ +abstract contract NFTOrders is FixinCommon, FixinEIP712, FixinTokenSpender { using LibSafeMathV06 for uint256; /// @dev Native token pseudo-address. - address constant internal NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; + address internal constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev The WETH token contract. IEtherTokenV06 internal immutable WETH; @@ -53,10 +48,7 @@ abstract contract NFTOrders is /// @dev The magic return value indicating the success of a `zeroExTakerCallback`. bytes4 private constant TAKER_CALLBACK_MAGIC_BYTES = ITakerCallback.zeroExTakerCallback.selector; - constructor(address zeroExAddress, IEtherTokenV06 weth) - public - FixinEIP712(zeroExAddress) - { + constructor(address zeroExAddress, IEtherTokenV06 weth) public FixinEIP712(zeroExAddress) { WETH = weth; } @@ -80,25 +72,13 @@ abstract contract NFTOrders is LibNFTOrder.NFTOrder memory buyOrder, LibSignature.Signature memory signature, SellParams memory params - ) - internal - returns (uint256 erc20FillAmount) - { + ) internal returns (uint256 erc20FillAmount) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(buyOrder); // Check that the order can be filled. - _validateBuyOrder( - buyOrder, - signature, - orderInfo, - params.taker, - params.tokenId - ); + _validateBuyOrder(buyOrder, signature, orderInfo, params.taker, params.tokenId); if (params.sellAmount > orderInfo.remainingAmount) { - LibNFTOrdersRichErrors.ExceedsRemainingOrderAmount( - orderInfo.remainingAmount, - params.sellAmount - ).rrevert(); + LibNFTOrdersRichErrors.ExceedsRemainingOrderAmount(orderInfo.remainingAmount, params.sellAmount).rrevert(); } _updateOrderState(buyOrder, orderInfo.orderHash, params.sellAmount); @@ -117,48 +97,31 @@ abstract contract NFTOrders is if (params.unwrapNativeToken) { // The ERC20 token must be WETH for it to be unwrapped. if (buyOrder.erc20Token != WETH) { - LibNFTOrdersRichErrors.ERC20TokenMismatchError( - address(buyOrder.erc20Token), - address(WETH) - ).rrevert(); + LibNFTOrdersRichErrors.ERC20TokenMismatchError(address(buyOrder.erc20Token), address(WETH)).rrevert(); } // Transfer the WETH from the maker to the Exchange Proxy // so we can unwrap it before sending it to the seller. // TODO: Probably safe to just use WETH.transferFrom for some // small gas savings - _transferERC20TokensFrom( - WETH, - buyOrder.maker, - address(this), - erc20FillAmount - ); + _transferERC20TokensFrom(WETH, buyOrder.maker, address(this), erc20FillAmount); // Unwrap WETH into ETH. WETH.withdraw(erc20FillAmount); // Send ETH to the seller. _transferEth(payable(params.taker), erc20FillAmount); } else { // Transfer the ERC20 token from the buyer to the seller. - _transferERC20TokensFrom( - buyOrder.erc20Token, - buyOrder.maker, - params.taker, - erc20FillAmount - ); + _transferERC20TokensFrom(buyOrder.erc20Token, buyOrder.maker, params.taker, erc20FillAmount); } if (params.takerCallbackData.length > 0) { - require( - params.taker != address(this), - "NFTOrders::_sellNFT/CANNOT_CALLBACK_SELF" - ); + require(params.taker != address(this), "NFTOrders::_sellNFT/CANNOT_CALLBACK_SELF"); // Invoke the callback - bytes4 callbackResult = ITakerCallback(params.taker) - .zeroExTakerCallback(orderInfo.orderHash, params.takerCallbackData); - // Check for the magic success bytes - require( - callbackResult == TAKER_CALLBACK_MAGIC_BYTES, - "NFTOrders::_sellNFT/CALLBACK_FAILED" + bytes4 callbackResult = ITakerCallback(params.taker).zeroExTakerCallback( + orderInfo.orderHash, + params.takerCallbackData ); + // Check for the magic success bytes + require(callbackResult == TAKER_CALLBACK_MAGIC_BYTES, "NFTOrders::_sellNFT/CALLBACK_FAILED"); } // Transfer the NFT asset to the buyer. @@ -166,22 +129,10 @@ abstract contract NFTOrders is // `onNFTReceived` callback the Exchange Proxy // holds the asset. Otherwise, transfer it from // the seller. - _transferNFTAssetFrom( - buyOrder.nft, - params.currentNftOwner, - buyOrder.maker, - params.tokenId, - params.sellAmount - ); + _transferNFTAssetFrom(buyOrder.nft, params.currentNftOwner, buyOrder.maker, params.tokenId, params.sellAmount); // The buyer pays the order fees. - _payFees( - buyOrder, - buyOrder.maker, - params.sellAmount, - orderInfo.orderAmount, - false - ); + _payFees(buyOrder, buyOrder.maker, params.sellAmount, orderInfo.orderAmount, false); } // Core settlement logic for buying an NFT asset. @@ -189,24 +140,13 @@ abstract contract NFTOrders is LibNFTOrder.NFTOrder memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params - ) - internal - returns (uint256 erc20FillAmount) - { + ) internal returns (uint256 erc20FillAmount) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(sellOrder); // Check that the order can be filled. - _validateSellOrder( - sellOrder, - signature, - orderInfo, - msg.sender - ); + _validateSellOrder(sellOrder, signature, orderInfo, msg.sender); if (params.buyAmount > orderInfo.remainingAmount) { - LibNFTOrdersRichErrors.ExceedsRemainingOrderAmount( - orderInfo.remainingAmount, - params.buyAmount - ).rrevert(); + LibNFTOrdersRichErrors.ExceedsRemainingOrderAmount(orderInfo.remainingAmount, params.buyAmount).rrevert(); } _updateOrderState(sellOrder, orderInfo.orderHash, params.buyAmount); @@ -223,47 +163,29 @@ abstract contract NFTOrders is } // Transfer the NFT asset to the buyer (`msg.sender`). - _transferNFTAssetFrom( - sellOrder.nft, - sellOrder.maker, - msg.sender, - sellOrder.nftId, - params.buyAmount - ); + _transferNFTAssetFrom(sellOrder.nft, sellOrder.maker, msg.sender, sellOrder.nftId, params.buyAmount); uint256 ethAvailable = params.ethAvailable; if (params.takerCallbackData.length > 0) { - require( - msg.sender != address(this), - "NFTOrders::_buyNFT/CANNOT_CALLBACK_SELF" - ); + require(msg.sender != address(this), "NFTOrders::_buyNFT/CANNOT_CALLBACK_SELF"); uint256 ethBalanceBeforeCallback = address(this).balance; // Invoke the callback - bytes4 callbackResult = ITakerCallback(msg.sender) - .zeroExTakerCallback(orderInfo.orderHash, params.takerCallbackData); + bytes4 callbackResult = ITakerCallback(msg.sender).zeroExTakerCallback( + orderInfo.orderHash, + params.takerCallbackData + ); // Update `ethAvailable` with amount acquired during // the callback - ethAvailable = ethAvailable.safeAdd( - address(this).balance.safeSub(ethBalanceBeforeCallback) - ); + ethAvailable = ethAvailable.safeAdd(address(this).balance.safeSub(ethBalanceBeforeCallback)); // Check for the magic success bytes - require( - callbackResult == TAKER_CALLBACK_MAGIC_BYTES, - "NFTOrders::_buyNFT/CALLBACK_FAILED" - ); + require(callbackResult == TAKER_CALLBACK_MAGIC_BYTES, "NFTOrders::_buyNFT/CALLBACK_FAILED"); } if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS) { // Transfer ETH to the seller. _transferEth(payable(sellOrder.maker), erc20FillAmount); // Fees are paid from the EP's current balance of ETH. - _payEthFees( - sellOrder, - params.buyAmount, - orderInfo.orderAmount, - erc20FillAmount, - ethAvailable - ); + _payEthFees(sellOrder, params.buyAmount, orderInfo.orderAmount, erc20FillAmount, ethAvailable); } else if (sellOrder.erc20Token == WETH) { // If there is enough ETH available, fill the WETH order // (including fees) using that ETH. @@ -274,52 +196,20 @@ abstract contract NFTOrders is // TODO: Probably safe to just use WETH.transfer for some // small gas savings // Transfer WETH to the seller. - _transferERC20Tokens( - WETH, - sellOrder.maker, - erc20FillAmount - ); + _transferERC20Tokens(WETH, sellOrder.maker, erc20FillAmount); // Fees are paid from the EP's current balance of ETH. - _payEthFees( - sellOrder, - params.buyAmount, - orderInfo.orderAmount, - erc20FillAmount, - ethAvailable - ); + _payEthFees(sellOrder, params.buyAmount, orderInfo.orderAmount, erc20FillAmount, ethAvailable); } else { // Transfer WETH from the buyer to the seller. - _transferERC20TokensFrom( - sellOrder.erc20Token, - msg.sender, - sellOrder.maker, - erc20FillAmount - ); + _transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount); // The buyer pays fees using WETH. - _payFees( - sellOrder, - msg.sender, - params.buyAmount, - orderInfo.orderAmount, - false - ); + _payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false); } } else { // Transfer ERC20 token from the buyer to the seller. - _transferERC20TokensFrom( - sellOrder.erc20Token, - msg.sender, - sellOrder.maker, - erc20FillAmount - ); + _transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount); // The buyer pays fees. - _payFees( - sellOrder, - msg.sender, - params.buyAmount, - orderInfo.orderAmount, - false - ); + _payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false); } } @@ -328,10 +218,7 @@ abstract contract NFTOrders is LibSignature.Signature memory signature, LibNFTOrder.OrderInfo memory orderInfo, address taker - ) - internal - view - { + ) internal view { // Order must be selling the NFT asset. require( sellOrder.direction == LibNFTOrder.TradeDirection.SELL_NFT, @@ -344,11 +231,9 @@ abstract contract NFTOrders is // Check that the order is valid and has not expired, been cancelled, // or been filled. if (orderInfo.status != LibNFTOrder.OrderStatus.FILLABLE) { - LibNFTOrdersRichErrors.OrderNotFillableError( - sellOrder.maker, - sellOrder.nonce, - uint8(orderInfo.status) - ).rrevert(); + LibNFTOrdersRichErrors + .OrderNotFillableError(sellOrder.maker, sellOrder.nonce, uint8(orderInfo.status)) + .rrevert(); } // Check the signature. @@ -361,10 +246,7 @@ abstract contract NFTOrders is LibNFTOrder.OrderInfo memory orderInfo, address taker, uint256 tokenId - ) - internal - view - { + ) internal view { // Order must be buying the NFT asset. require( buyOrder.direction == LibNFTOrder.TradeDirection.BUY_NFT, @@ -382,11 +264,9 @@ abstract contract NFTOrders is // Check that the order is valid and has not expired, been cancelled, // or been filled. if (orderInfo.status != LibNFTOrder.OrderStatus.FILLABLE) { - LibNFTOrdersRichErrors.OrderNotFillableError( - buyOrder.maker, - buyOrder.nonce, - uint8(orderInfo.status) - ).rrevert(); + LibNFTOrdersRichErrors + .OrderNotFillableError(buyOrder.maker, buyOrder.nonce, uint8(orderInfo.status)) + .rrevert(); } // Check that the asset with the given token ID satisfies the properties // specified by the order. @@ -401,24 +281,13 @@ abstract contract NFTOrders is uint128 orderAmount, uint256 ethSpent, uint256 ethAvailable - ) - private - { + ) private { // Pay fees using ETH. - uint256 ethFees = _payFees( - order, - address(this), - fillAmount, - orderAmount, - true - ); + uint256 ethFees = _payFees(order, address(this), fillAmount, orderAmount, true); // Update amount of ETH spent. ethSpent = ethSpent.safeAdd(ethFees); if (ethSpent > ethAvailable) { - LibNFTOrdersRichErrors.OverspentEthError( - ethSpent, - ethAvailable - ).rrevert(); + LibNFTOrdersRichErrors.OverspentEthError(ethSpent, ethAvailable).rrevert(); } } @@ -428,37 +297,24 @@ abstract contract NFTOrders is uint128 fillAmount, uint128 orderAmount, bool useNativeToken - ) - internal - returns (uint256 totalFeesPaid) - { + ) internal returns (uint256 totalFeesPaid) { // Make assertions about ETH case if (useNativeToken) { assert(payer == address(this)); - assert( - order.erc20Token == WETH || - address(order.erc20Token) == NATIVE_TOKEN_ADDRESS - ); + assert(order.erc20Token == WETH || address(order.erc20Token) == NATIVE_TOKEN_ADDRESS); } for (uint256 i = 0; i < order.fees.length; i++) { LibNFTOrder.Fee memory fee = order.fees[i]; - require( - fee.recipient != address(this), - "NFTOrders::_payFees/RECIPIENT_CANNOT_BE_EXCHANGE_PROXY" - ); + require(fee.recipient != address(this), "NFTOrders::_payFees/RECIPIENT_CANNOT_BE_EXCHANGE_PROXY"); uint256 feeFillAmount; if (fillAmount == orderAmount) { feeFillAmount = fee.amount; } else { // Round against the fee recipient - feeFillAmount = LibMathV06.getPartialAmountFloor( - fillAmount, - orderAmount, - fee.amount - ); + feeFillAmount = LibMathV06.getPartialAmountFloor(fillAmount, orderAmount, fee.amount); } if (feeFillAmount == 0) { continue; @@ -469,12 +325,7 @@ abstract contract NFTOrders is _transferEth(payable(fee.recipient), feeFillAmount); } else { // Transfer ERC20 token from payer to recipient. - _transferERC20TokensFrom( - order.erc20Token, - payer, - fee.recipient, - feeFillAmount - ); + _transferERC20TokensFrom(order.erc20Token, payer, fee.recipient, feeFillAmount); } // Note that the fee callback is _not_ called if zero // `feeData` is provided. If `feeData` is provided, we assume @@ -488,10 +339,7 @@ abstract contract NFTOrders is fee.feeData ); // Check for the magic success bytes - require( - callbackResult == FEE_CALLBACK_MAGIC_BYTES, - "NFTOrders::_payFees/CALLBACK_FAILED" - ); + require(callbackResult == FEE_CALLBACK_MAGIC_BYTES, "NFTOrders::_payFees/CALLBACK_FAILED"); } // Sum the fees paid totalFeesPaid = totalFeesPaid.safeAdd(feeFillAmount); @@ -507,13 +355,7 @@ abstract contract NFTOrders is /// an NFT asset. /// @param order The NFT order. /// @param tokenId The ID of the NFT asset. - function _validateOrderProperties( - LibNFTOrder.NFTOrder memory order, - uint256 tokenId - ) - internal - view - { + function _validateOrderProperties(LibNFTOrder.NFTOrder memory order, uint256 tokenId) internal view { // Order must be buying an NFT asset to have properties. require( order.direction == LibNFTOrder.TradeDirection.BUY_NFT, @@ -524,10 +366,7 @@ abstract contract NFTOrders is // `tokenId` matches the one specified in the order. if (order.nftProperties.length == 0) { if (tokenId != order.nftId) { - LibNFTOrdersRichErrors.TokenIdMismatchError( - tokenId, - order.nftId - ).rrevert(); + LibNFTOrdersRichErrors.TokenIdMismatchError(tokenId, order.nftId).rrevert(); } } else { // Validate each property @@ -541,18 +380,18 @@ abstract contract NFTOrders is // Call the property validator and throw a descriptive error // if the call reverts. - try property.propertyValidator.validateProperty( - order.nft, - tokenId, - property.propertyData - ) {} catch (bytes memory errorData) { - LibNFTOrdersRichErrors.PropertyValidationFailedError( - address(property.propertyValidator), - order.nft, - tokenId, - property.propertyData, - errorData - ).rrevert(); + try property.propertyValidator.validateProperty(order.nft, tokenId, property.propertyData) {} catch ( + bytes memory errorData + ) { + LibNFTOrdersRichErrors + .PropertyValidationFailedError( + address(property.propertyValidator), + order.nft, + tokenId, + property.propertyData, + errorData + ) + .rrevert(); } } } @@ -568,10 +407,7 @@ abstract contract NFTOrders is bytes32 orderHash, LibSignature.Signature memory signature, address maker - ) - internal - virtual - view; + ) internal view virtual; /// @dev Transfers an NFT asset. /// @param token The address of the NFT contract. @@ -586,9 +422,7 @@ abstract contract NFTOrders is address to, uint256 tokenId, uint256 amount - ) - internal - virtual; + ) internal virtual; /// @dev Updates storage to indicate that the given order /// has been filled by the given amount. @@ -600,16 +434,14 @@ abstract contract NFTOrders is LibNFTOrder.NFTOrder memory order, bytes32 orderHash, uint128 fillAmount - ) - internal - virtual; + ) internal virtual; /// @dev Get the order info for an NFT order. /// @param order The NFT order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTOrder memory order) internal - virtual view + virtual returns (LibNFTOrder.OrderInfo memory orderInfo); } diff --git a/contracts/zero-ex/contracts/src/fixins/FixinCommon.sol b/contracts/zero-ex/contracts/src/fixins/FixinCommon.sol index 7a129ba323..63ed69fe33 100644 --- a/contracts/zero-ex/contracts/src/fixins/FixinCommon.sol +++ b/contracts/zero-ex/contracts/src/fixins/FixinCommon.sol @@ -26,10 +26,8 @@ import "../errors/LibOwnableRichErrors.sol"; import "../features/interfaces/IOwnableFeature.sol"; import "../features/interfaces/ISimpleFunctionRegistryFeature.sol"; - /// @dev Common feature utilities. abstract contract FixinCommon { - using LibRichErrorsV06 for bytes; /// @dev The implementation address of this feature. @@ -48,10 +46,7 @@ abstract contract FixinCommon { { address owner = IOwnableFeature(address(this)).owner(); if (msg.sender != owner) { - LibOwnableRichErrors.OnlyOwnerError( - msg.sender, - owner - ).rrevert(); + LibOwnableRichErrors.OnlyOwnerError(msg.sender, owner).rrevert(); } } _; @@ -66,9 +61,7 @@ abstract contract FixinCommon { /// Can and should only be called within a `migrate()`. /// @param selector The selector of the function whose implementation /// is at `_implementation`. - function _registerFeatureFunction(bytes4 selector) - internal - { + function _registerFeatureFunction(bytes4 selector) internal { ISimpleFunctionRegistryFeature(address(this)).extend(selector, _implementation); } @@ -77,11 +70,11 @@ abstract contract FixinCommon { /// @param minor The minor version number of the feature. /// @param revision The revision number of the feature. /// @return encodedVersion The encoded version number. - function _encodeVersion(uint32 major, uint32 minor, uint32 revision) - internal - pure - returns (uint256 encodedVersion) - { + function _encodeVersion( + uint32 major, + uint32 minor, + uint32 revision + ) internal pure returns (uint256 encodedVersion) { return (uint256(major) << 64) | (uint256(minor) << 32) | uint256(revision); } } diff --git a/contracts/zero-ex/contracts/src/fixins/FixinEIP712.sol b/contracts/zero-ex/contracts/src/fixins/FixinEIP712.sol index 8b2bfcec1c..359f07addf 100644 --- a/contracts/zero-ex/contracts/src/fixins/FixinEIP712.sol +++ b/contracts/zero-ex/contracts/src/fixins/FixinEIP712.sol @@ -24,10 +24,8 @@ import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../errors/LibCommonRichErrors.sol"; import "../errors/LibOwnableRichErrors.sol"; - /// @dev EIP712 helpers for features. abstract contract FixinEIP712 { - /// @dev The domain hash separator for the entire exchange proxy. bytes32 public immutable EIP712_DOMAIN_SEPARATOR; @@ -35,15 +33,17 @@ abstract contract FixinEIP712 { // Compute `EIP712_DOMAIN_SEPARATOR` { uint256 chainId; - assembly { chainId := chainid() } + assembly { + chainId := chainid() + } EIP712_DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(" - "string name," - "string version," - "uint256 chainId," - "address verifyingContract" + "string name," + "string version," + "uint256 chainId," + "address verifyingContract" ")" ), keccak256("ZeroEx"), @@ -55,15 +55,7 @@ abstract contract FixinEIP712 { } } - function _getEIP712Hash(bytes32 structHash) - internal - view - returns (bytes32 eip712Hash) - { - return keccak256(abi.encodePacked( - hex"1901", - EIP712_DOMAIN_SEPARATOR, - structHash - )); + function _getEIP712Hash(bytes32 structHash) internal view returns (bytes32 eip712Hash) { + return keccak256(abi.encodePacked(hex"1901", EIP712_DOMAIN_SEPARATOR, structHash)); } } diff --git a/contracts/zero-ex/contracts/src/fixins/FixinERC1155Spender.sol b/contracts/zero-ex/contracts/src/fixins/FixinERC1155Spender.sol index 06d31aa34c..f43c7930b2 100644 --- a/contracts/zero-ex/contracts/src/fixins/FixinERC1155Spender.sol +++ b/contracts/zero-ex/contracts/src/fixins/FixinERC1155Spender.sol @@ -23,12 +23,10 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "../vendor/IERC1155Token.sol"; - /// @dev Helpers for moving ERC1155 assets around. abstract contract FixinERC1155Spender { - // Mask of the lower 20 bytes of a bytes32. - uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; + uint256 private constant ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; /// @dev Transfers an ERC1155 asset from `owner` to `to`. /// @param token The address of the ERC1155 token contract. @@ -42,9 +40,7 @@ abstract contract FixinERC1155Spender { address to, uint256 tokenId, uint256 amount - ) - internal - { + ) internal { require(address(token) != address(this), "FixinERC1155Spender/CANNOT_INVOKE_SELF"); assembly { @@ -59,15 +55,7 @@ abstract contract FixinERC1155Spender { mstore(add(ptr, 0x84), 0xa0) mstore(add(ptr, 0xa4), 0) - let success := call( - gas(), - and(token, ADDRESS_MASK), - 0, - ptr, - 0xc4, - 0, - 0 - ) + let success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0xc4, 0, 0) if iszero(success) { let rdsize := returndatasize() diff --git a/contracts/zero-ex/contracts/src/fixins/FixinERC721Spender.sol b/contracts/zero-ex/contracts/src/fixins/FixinERC721Spender.sol index 912bce61ad..4d3c1cc70c 100644 --- a/contracts/zero-ex/contracts/src/fixins/FixinERC721Spender.sol +++ b/contracts/zero-ex/contracts/src/fixins/FixinERC721Spender.sol @@ -23,12 +23,10 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "../vendor/IERC721Token.sol"; - /// @dev Helpers for moving ERC721 assets around. abstract contract FixinERC721Spender { - // Mask of the lower 20 bytes of a bytes32. - uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; + uint256 private constant ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; /// @dev Transfers an ERC721 asset from `owner` to `to`. /// @param token The address of the ERC721 token contract. @@ -40,9 +38,7 @@ abstract contract FixinERC721Spender { address owner, address to, uint256 tokenId - ) - internal - { + ) internal { require(address(token) != address(this), "FixinERC721Spender/CANNOT_INVOKE_SELF"); assembly { @@ -54,15 +50,7 @@ abstract contract FixinERC721Spender { mstore(add(ptr, 0x24), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x44), tokenId) - let success := call( - gas(), - and(token, ADDRESS_MASK), - 0, - ptr, - 0x64, - 0, - 0 - ) + let success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x64, 0, 0) if iszero(success) { let rdsize := returndatasize() diff --git a/contracts/zero-ex/contracts/src/fixins/FixinProtocolFees.sol b/contracts/zero-ex/contracts/src/fixins/FixinProtocolFees.sol index 6437b27a97..53d36ea3d7 100644 --- a/contracts/zero-ex/contracts/src/fixins/FixinProtocolFees.sol +++ b/contracts/zero-ex/contracts/src/fixins/FixinProtocolFees.sol @@ -26,10 +26,8 @@ import "../external/FeeCollectorController.sol"; import "../external/LibFeeCollector.sol"; import "../vendor/v3/IStaking.sol"; - /// @dev Helpers for collecting protocol fees. abstract contract FixinProtocolFees { - /// @dev The protocol fee multiplier. uint32 public immutable PROTOCOL_FEE_MULTIPLIER; /// @dev The `FeeCollectorController` contract. @@ -46,12 +44,9 @@ abstract contract FixinProtocolFees { IStaking staking, FeeCollectorController feeCollectorController, uint32 protocolFeeMultiplier - ) - internal - { + ) internal { FEE_COLLECTOR_CONTROLLER = feeCollectorController; - FEE_COLLECTOR_INIT_CODE_HASH = - feeCollectorController.FEE_COLLECTOR_INIT_CODE_HASH(); + FEE_COLLECTOR_INIT_CODE_HASH = feeCollectorController.FEE_COLLECTOR_INIT_CODE_HASH(); WETH = weth; STAKING = staking; PROTOCOL_FEE_MULTIPLIER = protocolFeeMultiplier; @@ -61,62 +56,48 @@ abstract contract FixinProtocolFees { /// The fee is stored in a per-pool fee collector contract. /// @param poolId The pool ID for which a fee is being collected. /// @return ethProtocolFeePaid How much protocol fee was collected in ETH. - function _collectProtocolFee(bytes32 poolId) - internal - returns (uint256 ethProtocolFeePaid) - { + function _collectProtocolFee(bytes32 poolId) internal returns (uint256 ethProtocolFeePaid) { uint256 protocolFeePaid = _getSingleProtocolFee(); if (protocolFeePaid == 0) { // Nothing to do. return 0; } FeeCollector feeCollector = _getFeeCollector(poolId); - (bool success,) = address(feeCollector).call{value: protocolFeePaid}(""); + (bool success, ) = address(feeCollector).call{value: protocolFeePaid}(""); require(success, "FixinProtocolFees/ETHER_TRANSFER_FALIED"); return protocolFeePaid; } /// @dev Transfer fees for a given pool to the staking contract. /// @param poolId Identifies the pool whose fees are being paid. - function _transferFeesForPool(bytes32 poolId) - internal - { + function _transferFeesForPool(bytes32 poolId) internal { // This will create a FeeCollector contract (if necessary) and wrap // fees for the pool ID. - FeeCollector feeCollector = - FEE_COLLECTOR_CONTROLLER.prepareFeeCollectorToPayFees(poolId); + FeeCollector feeCollector = FEE_COLLECTOR_CONTROLLER.prepareFeeCollectorToPayFees(poolId); // All fees in the fee collector should be in WETH now. uint256 bal = WETH.balanceOf(address(feeCollector)); if (bal > 1) { // Leave 1 wei behind to avoid high SSTORE cost of zero-->non-zero. - STAKING.payProtocolFee( - address(feeCollector), - address(feeCollector), - bal - 1); + STAKING.payProtocolFee(address(feeCollector), address(feeCollector), bal - 1); } } /// @dev Compute the CREATE2 address for a fee collector. /// @param poolId The fee collector's pool ID. - function _getFeeCollector(bytes32 poolId) - internal - view - returns (FeeCollector) - { - return FeeCollector(LibFeeCollector.getFeeCollectorAddress( - address(FEE_COLLECTOR_CONTROLLER), - FEE_COLLECTOR_INIT_CODE_HASH, - poolId - )); + function _getFeeCollector(bytes32 poolId) internal view returns (FeeCollector) { + return + FeeCollector( + LibFeeCollector.getFeeCollectorAddress( + address(FEE_COLLECTOR_CONTROLLER), + FEE_COLLECTOR_INIT_CODE_HASH, + poolId + ) + ); } /// @dev Get the cost of a single protocol fee. /// @return protocolFeeAmount The protocol fee amount, in ETH/WETH. - function _getSingleProtocolFee() - internal - view - returns (uint256 protocolFeeAmount) - { + function _getSingleProtocolFee() internal view returns (uint256 protocolFeeAmount) { return uint256(PROTOCOL_FEE_MULTIPLIER) * tx.gasprice; } } diff --git a/contracts/zero-ex/contracts/src/fixins/FixinReentrancyGuard.sol b/contracts/zero-ex/contracts/src/fixins/FixinReentrancyGuard.sol index 2dda017264..9b39623a0b 100644 --- a/contracts/zero-ex/contracts/src/fixins/FixinReentrancyGuard.sol +++ b/contracts/zero-ex/contracts/src/fixins/FixinReentrancyGuard.sol @@ -25,29 +25,23 @@ import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../errors/LibCommonRichErrors.sol"; import "../storage/LibReentrancyGuardStorage.sol"; - /// @dev Common feature utilities. abstract contract FixinReentrancyGuard { - using LibRichErrorsV06 for bytes; using LibBytesV06 for bytes; // Combinable reentrancy flags. /// @dev Reentrancy guard flag for meta-transaction functions. - uint256 constant internal REENTRANCY_MTX = 0x1; + uint256 internal constant REENTRANCY_MTX = 0x1; /// @dev Cannot reenter a function with the same reentrancy guard flags. modifier nonReentrant(uint256 reentrancyFlags) virtual { - LibReentrancyGuardStorage.Storage storage stor = - LibReentrancyGuardStorage.getStorage(); + LibReentrancyGuardStorage.Storage storage stor = LibReentrancyGuardStorage.getStorage(); { uint256 currentFlags = stor.reentrancyFlags; // Revert if any bits in `reentrancyFlags` has already been set. if ((currentFlags & reentrancyFlags) != 0) { - LibCommonRichErrors.IllegalReentrancyError( - msg.data.readBytes4(0), - reentrancyFlags - ).rrevert(); + LibCommonRichErrors.IllegalReentrancyError(msg.data.readBytes4(0), reentrancyFlags).rrevert(); } // Update reentrancy flags. stor.reentrancyFlags = currentFlags | reentrancyFlags; diff --git a/contracts/zero-ex/contracts/src/fixins/FixinTokenSpender.sol b/contracts/zero-ex/contracts/src/fixins/FixinTokenSpender.sol index 5f87ec5cf2..2b9c3ffa41 100644 --- a/contracts/zero-ex/contracts/src/fixins/FixinTokenSpender.sol +++ b/contracts/zero-ex/contracts/src/fixins/FixinTokenSpender.sol @@ -23,12 +23,10 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; - /// @dev Helpers for moving tokens around. abstract contract FixinTokenSpender { - // Mask of the lower 20 bytes of a bytes32. - uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; + uint256 private constant ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; /// @dev Transfers ERC20 tokens from `owner` to `to`. /// @param token The token to spend. @@ -40,9 +38,7 @@ abstract contract FixinTokenSpender { address owner, address to, uint256 amount - ) - internal - { + ) internal { require(address(token) != address(this), "FixinTokenSpender/CANNOT_INVOKE_SELF"); assembly { @@ -54,15 +50,7 @@ abstract contract FixinTokenSpender { mstore(add(ptr, 0x24), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x44), amount) - let success := call( - gas(), - and(token, ADDRESS_MASK), - 0, - ptr, - 0x64, - ptr, - 32 - ) + let success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x64, ptr, 32) let rdsize := returndatasize() @@ -70,12 +58,12 @@ abstract contract FixinTokenSpender { // but some don't. We accept 0-length return data as success, or at // least 32 bytes that starts with a 32-byte boolean true. success := and( - success, // call itself succeeded + success, // call itself succeeded or( - iszero(rdsize), // no return data, or + iszero(rdsize), // no return data, or and( - iszero(lt(rdsize, 32)), // at least 32 bytes - eq(mload(ptr), 1) // starts with uint256(1) + iszero(lt(rdsize, 32)), // at least 32 bytes + eq(mload(ptr), 1) // starts with uint256(1) ) ) ) @@ -95,9 +83,7 @@ abstract contract FixinTokenSpender { IERC20TokenV06 token, address to, uint256 amount - ) - internal - { + ) internal { require(address(token) != address(this), "FixinTokenSpender/CANNOT_INVOKE_SELF"); assembly { @@ -108,15 +94,7 @@ abstract contract FixinTokenSpender { mstore(add(ptr, 0x04), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x24), amount) - let success := call( - gas(), - and(token, ADDRESS_MASK), - 0, - ptr, - 0x44, - ptr, - 32 - ) + let success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x44, ptr, 32) let rdsize := returndatasize() @@ -124,12 +102,12 @@ abstract contract FixinTokenSpender { // but some don't. We accept 0-length return data as success, or at // least 32 bytes that starts with a 32-byte boolean true. success := and( - success, // call itself succeeded + success, // call itself succeeded or( - iszero(rdsize), // no return data, or + iszero(rdsize), // no return data, or and( - iszero(lt(rdsize, 32)), // at least 32 bytes - eq(mload(ptr), 1) // starts with uint256(1) + iszero(lt(rdsize, 32)), // at least 32 bytes + eq(mload(ptr), 1) // starts with uint256(1) ) ) ) @@ -141,16 +119,13 @@ abstract contract FixinTokenSpender { } } - /// @dev Transfers some amount of ETH to the given recipient and /// reverts if the transfer fails. /// @param recipient The recipient of the ETH. /// @param amount The amount of ETH to transfer. - function _transferEth(address payable recipient, uint256 amount) - internal - { + function _transferEth(address payable recipient, uint256 amount) internal { if (amount > 0) { - (bool success,) = recipient.call{value: amount}(""); + (bool success, ) = recipient.call{value: amount}(""); require(success, "FixinTokenSpender::_transferEth/TRANSFER_FAILED"); } } @@ -160,17 +135,7 @@ abstract contract FixinTokenSpender { /// @param token The token to spend. /// @param owner The owner of the tokens. /// @return amount The amount of tokens that can be pulled. - function _getSpendableERC20BalanceOf( - IERC20TokenV06 token, - address owner - ) - internal - view - returns (uint256) - { - return LibSafeMathV06.min256( - token.allowance(owner, address(this)), - token.balanceOf(owner) - ); + function _getSpendableERC20BalanceOf(IERC20TokenV06 token, address owner) internal view returns (uint256) { + return LibSafeMathV06.min256(token.allowance(owner, address(this)), token.balanceOf(owner)); } } diff --git a/contracts/zero-ex/contracts/src/liquidity-providers/CurveLiquidityProvider.sol b/contracts/zero-ex/contracts/src/liquidity-providers/CurveLiquidityProvider.sol index 78b552d1df..be9efebcb8 100644 --- a/contracts/zero-ex/contracts/src/liquidity-providers/CurveLiquidityProvider.sol +++ b/contracts/zero-ex/contracts/src/liquidity-providers/CurveLiquidityProvider.sol @@ -27,10 +27,7 @@ import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "../transformers/LibERC20Transformer.sol"; import "../vendor/ILiquidityProvider.sol"; - -contract CurveLiquidityProvider is - ILiquidityProvider -{ +contract CurveLiquidityProvider is ILiquidityProvider { using LibERC20TokenV06 for IERC20TokenV06; using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; @@ -61,14 +58,9 @@ contract CurveLiquidityProvider is address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - override - returns (uint256 boughtAmount) - { + ) external override returns (uint256 boughtAmount) { require( - !LibERC20Transformer.isTokenETH(inputToken) - && !LibERC20Transformer.isTokenETH(outputToken), + !LibERC20Transformer.isTokenETH(inputToken) && !LibERC20Transformer.isTokenETH(outputToken), "CurveLiquidityProvider/INVALID_ARGS" ); boughtAmount = _executeSwap( @@ -96,16 +88,8 @@ contract CurveLiquidityProvider is address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - payable - override - returns (uint256 boughtAmount) - { - require( - !LibERC20Transformer.isTokenETH(outputToken), - "CurveLiquidityProvider/INVALID_ARGS" - ); + ) external payable override returns (uint256 boughtAmount) { + require(!LibERC20Transformer.isTokenETH(outputToken), "CurveLiquidityProvider/INVALID_ARGS"); boughtAmount = _executeSwap( LibERC20Transformer.ETH_TOKEN, outputToken, @@ -130,15 +114,8 @@ contract CurveLiquidityProvider is address payable recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - override - returns (uint256 boughtAmount) - { - require( - !LibERC20Transformer.isTokenETH(inputToken), - "CurveLiquidityProvider/INVALID_ARGS" - ); + ) external override returns (uint256 boughtAmount) { + require(!LibERC20Transformer.isTokenETH(inputToken), "CurveLiquidityProvider/INVALID_ARGS"); boughtAmount = _executeSwap( inputToken, LibERC20Transformer.ETH_TOKEN, @@ -154,15 +131,10 @@ contract CurveLiquidityProvider is /// @dev Quotes the amount of `outputToken` that would be obtained by /// selling `sellAmount` of `inputToken`. function getSellQuote( - IERC20TokenV06 /* inputToken */, - IERC20TokenV06 /* outputToken */, + IERC20TokenV06, /* inputToken */ + IERC20TokenV06, /* outputToken */ uint256 /* sellAmount */ - ) - external - view - override - returns (uint256) - { + ) external view override returns (uint256) { revert("CurveLiquidityProvider/NOT_IMPLEMENTED"); } @@ -174,28 +146,25 @@ contract CurveLiquidityProvider is uint256 minBuyAmount, CurveData memory data, address recipient // Only used to log event. - ) - private - returns (uint256 boughtAmount) - { - uint256 sellAmount = - LibERC20Transformer.getTokenBalanceOf(inputToken, address(this)); + ) private returns (uint256 boughtAmount) { + uint256 sellAmount = LibERC20Transformer.getTokenBalanceOf(inputToken, address(this)); if (!LibERC20Transformer.isTokenETH(inputToken)) { inputToken.approveIfBelow(data.curveAddress, sellAmount); } - (bool success, bytes memory resultData) = - data.curveAddress.call - { value: LibERC20Transformer.isTokenETH(inputToken) ? sellAmount : 0 } - (abi.encodeWithSelector( - data.exchangeFunctionSelector, - data.fromCoinIdx, - data.toCoinIdx, - // dx - sellAmount, - // min dy - minBuyAmount - )); + (bool success, bytes memory resultData) = data.curveAddress.call{ + value: LibERC20Transformer.isTokenETH(inputToken) ? sellAmount : 0 + }( + abi.encodeWithSelector( + data.exchangeFunctionSelector, + data.fromCoinIdx, + data.toCoinIdx, + // dx + sellAmount, + // min dy + minBuyAmount + ) + ); if (!success) { resultData.rrevert(); } @@ -205,8 +174,7 @@ contract CurveLiquidityProvider is } else { // Not all pool contracts return a `boughtAmount`, so we return // our balance of the output token if it wasn't returned. - boughtAmount = LibERC20Transformer - .getTokenBalanceOf(outputToken, address(this)); + boughtAmount = LibERC20Transformer.getTokenBalanceOf(outputToken, address(this)); } emit LiquidityProviderFill( diff --git a/contracts/zero-ex/contracts/src/liquidity-providers/MooniswapLiquidityProvider.sol b/contracts/zero-ex/contracts/src/liquidity-providers/MooniswapLiquidityProvider.sol index 21d11be0e3..c77fa0cde9 100644 --- a/contracts/zero-ex/contracts/src/liquidity-providers/MooniswapLiquidityProvider.sol +++ b/contracts/zero-ex/contracts/src/liquidity-providers/MooniswapLiquidityProvider.sol @@ -29,10 +29,7 @@ import "../transformers/LibERC20Transformer.sol"; import "../vendor/ILiquidityProvider.sol"; import "../vendor/IMooniswapPool.sol"; - -contract MooniswapLiquidityProvider is - ILiquidityProvider -{ +contract MooniswapLiquidityProvider is ILiquidityProvider { using LibERC20TokenV06 for IERC20TokenV06; using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; @@ -62,15 +59,11 @@ contract MooniswapLiquidityProvider is address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - override - returns (uint256 boughtAmount) - { + ) external override returns (uint256 boughtAmount) { require( - !LibERC20Transformer.isTokenETH(inputToken) - && !LibERC20Transformer.isTokenETH(outputToken) - && inputToken != outputToken, + !LibERC20Transformer.isTokenETH(inputToken) && + !LibERC20Transformer.isTokenETH(outputToken) && + inputToken != outputToken, "MooniswapLiquidityProvider/INVALID_ARGS" ); boughtAmount = _executeSwap( @@ -96,16 +89,8 @@ contract MooniswapLiquidityProvider is address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - payable - override - returns (uint256 boughtAmount) - { - require( - !LibERC20Transformer.isTokenETH(outputToken), - "MooniswapLiquidityProvider/INVALID_ARGS" - ); + ) external payable override returns (uint256 boughtAmount) { + require(!LibERC20Transformer.isTokenETH(outputToken), "MooniswapLiquidityProvider/INVALID_ARGS"); boughtAmount = _executeSwap( LibERC20Transformer.ETH_TOKEN, outputToken, @@ -128,15 +113,8 @@ contract MooniswapLiquidityProvider is address payable recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - override - returns (uint256 boughtAmount) - { - require( - !LibERC20Transformer.isTokenETH(inputToken), - "MooniswapLiquidityProvider/INVALID_ARGS" - ); + ) external override returns (uint256 boughtAmount) { + require(!LibERC20Transformer.isTokenETH(inputToken), "MooniswapLiquidityProvider/INVALID_ARGS"); boughtAmount = _executeSwap( inputToken, LibERC20Transformer.ETH_TOKEN, @@ -150,15 +128,10 @@ contract MooniswapLiquidityProvider is /// @dev Quotes the amount of `outputToken` that would be obtained by /// selling `sellAmount` of `inputToken`. function getSellQuote( - IERC20TokenV06 /* inputToken */, - IERC20TokenV06 /* outputToken */, + IERC20TokenV06, /* inputToken */ + IERC20TokenV06, /* outputToken */ uint256 /* sellAmount */ - ) - external - view - override - returns (uint256) - { + ) external view override returns (uint256) { revert("MooniswapLiquidityProvider/NOT_IMPLEMENTED"); } @@ -170,25 +143,21 @@ contract MooniswapLiquidityProvider is uint256 minBuyAmount, IMooniswapPool pool, address recipient // Only used to log event - ) - private - returns (uint256 boughtAmount) - { - uint256 sellAmount = - LibERC20Transformer.getTokenBalanceOf(inputToken, address(this)); + ) private returns (uint256 boughtAmount) { + uint256 sellAmount = LibERC20Transformer.getTokenBalanceOf(inputToken, address(this)); uint256 ethValue = 0; if (inputToken == WETH) { // Selling WETH. Unwrap to ETH. - require(!_isTokenEthLike(outputToken), 'MooniswapLiquidityProvider/ETH_TO_ETH'); + require(!_isTokenEthLike(outputToken), "MooniswapLiquidityProvider/ETH_TO_ETH"); WETH.withdraw(sellAmount); ethValue = sellAmount; } else if (LibERC20Transformer.isTokenETH(inputToken)) { // Selling ETH directly. ethValue = sellAmount; - require(!_isTokenEthLike(outputToken), 'MooniswapLiquidityProvider/ETH_TO_ETH'); + require(!_isTokenEthLike(outputToken), "MooniswapLiquidityProvider/ETH_TO_ETH"); } else { // Selling a regular ERC20. - require(inputToken != outputToken, 'MooniswapLiquidityProvider/SAME_TOKEN'); + require(inputToken != outputToken, "MooniswapLiquidityProvider/SAME_TOKEN"); inputToken.approveIfBelow(address(pool), sellAmount); } @@ -217,11 +186,7 @@ contract MooniswapLiquidityProvider is } /// @dev Check if a token is ETH or WETH. - function _isTokenEthLike(IERC20TokenV06 token) - private - view - returns (bool isEthOrWeth) - { + function _isTokenEthLike(IERC20TokenV06 token) private view returns (bool isEthOrWeth) { return LibERC20Transformer.isTokenETH(token) || token == WETH; } } diff --git a/contracts/zero-ex/contracts/src/migrations/FullMigration.sol b/contracts/zero-ex/contracts/src/migrations/FullMigration.sol index 661cf0c8ff..360a38130f 100644 --- a/contracts/zero-ex/contracts/src/migrations/FullMigration.sol +++ b/contracts/zero-ex/contracts/src/migrations/FullMigration.sol @@ -28,10 +28,8 @@ import "../features/NativeOrdersFeature.sol"; import "../features/OtcOrdersFeature.sol"; import "./InitialMigration.sol"; - /// @dev A contract for deploying and configuring the full ZeroEx contract. contract FullMigration { - // solhint-disable no-empty-blocks,indent /// @dev Features to add the the proxy contract. @@ -57,9 +55,7 @@ contract FullMigration { /// @dev Instantiate this contract and set the allowed caller of `initializeZeroEx()` /// to `initializeCaller`. /// @param initializeCaller_ The allowed caller of `initializeZeroEx()`. - constructor(address payable initializeCaller_) - public - { + constructor(address payable initializeCaller_) public { initializeCaller = initializeCaller_; // Create an initial migration contract with this contract set to the // allowed `initializeCaller`. @@ -68,11 +64,7 @@ contract FullMigration { /// @dev Retrieve the bootstrapper address to use when constructing `ZeroEx`. /// @return bootstrapper The bootstrapper address. - function getBootstrapper() - external - view - returns (address bootstrapper) - { + function getBootstrapper() external view returns (address bootstrapper) { return address(_initialMigration); } @@ -89,20 +81,14 @@ contract FullMigration { ZeroEx zeroEx, Features memory features, MigrateOpts memory migrateOpts - ) - public - returns (ZeroEx _zeroEx) - { + ) public returns (ZeroEx _zeroEx) { require(msg.sender == initializeCaller, "FullMigration/INVALID_SENDER"); // Perform the initial migration with the owner set to this contract. _initialMigration.initializeZeroEx( address(uint160(address(this))), zeroEx, - InitialMigration.BootstrapFeatures({ - registry: features.registry, - ownable: features.ownable - }) + InitialMigration.BootstrapFeatures({registry: features.registry, ownable: features.ownable}) ); // Add features. @@ -119,10 +105,7 @@ contract FullMigration { /// @dev Destroy this contract. Only callable from ourselves (from `initializeZeroEx()`). /// @param ethRecipient Receiver of any ETH in this contract. - function die(address payable ethRecipient) - external - virtual - { + function die(address payable ethRecipient) external virtual { require(msg.sender == address(this), "FullMigration/INVALID_SENDER"); // This contract should not hold any funds but we send // them to the ethRecipient just in case. @@ -137,19 +120,14 @@ contract FullMigration { ZeroEx zeroEx, Features memory features, MigrateOpts memory migrateOpts - ) - private - { + ) private { IOwnableFeature ownable = IOwnableFeature(address(zeroEx)); // TransformERC20Feature { // Register the feature. ownable.migrate( address(features.transformERC20), - abi.encodeWithSelector( - TransformERC20Feature.migrate.selector, - migrateOpts.transformerDeployer - ), + abi.encodeWithSelector(TransformERC20Feature.migrate.selector, migrateOpts.transformerDeployer), address(this) ); } @@ -158,9 +136,7 @@ contract FullMigration { // Register the feature. ownable.migrate( address(features.metaTransactions), - abi.encodeWithSelector( - MetaTransactionsFeature.migrate.selector - ), + abi.encodeWithSelector(MetaTransactionsFeature.migrate.selector), address(this) ); } @@ -169,9 +145,7 @@ contract FullMigration { // Register the feature. ownable.migrate( address(features.nativeOrders), - abi.encodeWithSelector( - NativeOrdersFeature.migrate.selector - ), + abi.encodeWithSelector(NativeOrdersFeature.migrate.selector), address(this) ); } @@ -180,9 +154,7 @@ contract FullMigration { // Register the feature. ownable.migrate( address(features.otcOrders), - abi.encodeWithSelector( - OtcOrdersFeature.migrate.selector - ), + abi.encodeWithSelector(OtcOrdersFeature.migrate.selector), address(this) ); } diff --git a/contracts/zero-ex/contracts/src/migrations/InitialMigration.sol b/contracts/zero-ex/contracts/src/migrations/InitialMigration.sol index 0b5ee6b32a..7c528a7cbf 100644 --- a/contracts/zero-ex/contracts/src/migrations/InitialMigration.sol +++ b/contracts/zero-ex/contracts/src/migrations/InitialMigration.sol @@ -26,10 +26,8 @@ import "../features/SimpleFunctionRegistryFeature.sol"; import "../features/OwnableFeature.sol"; import "./LibBootstrap.sol"; - /// @dev A contract for deploying and configuring a minimal ZeroEx contract. contract InitialMigration { - /// @dev Features to bootstrap into the the proxy contract. struct BootstrapFeatures { SimpleFunctionRegistryFeature registry; @@ -62,11 +60,7 @@ contract InitialMigration { address payable owner, ZeroEx zeroEx, BootstrapFeatures memory features - ) - public - virtual - returns (ZeroEx _zeroEx) - { + ) public virtual returns (ZeroEx _zeroEx) { // Must be called by the allowed initializeCaller. require(msg.sender == initializeCaller, "InitialMigration/INVALID_SENDER"); @@ -88,28 +82,20 @@ contract InitialMigration { /// @param owner The new owner of the ZeroEx contract. /// @param features Features to bootstrap into the proxy. /// @return success Magic bytes if successful. - function bootstrap(address owner, BootstrapFeatures memory features) - public - virtual - returns (bytes4 success) - { + function bootstrap(address owner, BootstrapFeatures memory features) public virtual returns (bytes4 success) { // Deploy and migrate the initial features. // Order matters here. // Initialize Registry. LibBootstrap.delegatecallBootstrapFunction( address(features.registry), - abi.encodeWithSelector( - SimpleFunctionRegistryFeature.bootstrap.selector - ) + abi.encodeWithSelector(SimpleFunctionRegistryFeature.bootstrap.selector) ); // Initialize OwnableFeature. LibBootstrap.delegatecallBootstrapFunction( address(features.ownable), - abi.encodeWithSelector( - OwnableFeature.bootstrap.selector - ) + abi.encodeWithSelector(OwnableFeature.bootstrap.selector) ); // De-register `SimpleFunctionRegistryFeature._extendSelf`. diff --git a/contracts/zero-ex/contracts/src/migrations/LibBootstrap.sol b/contracts/zero-ex/contracts/src/migrations/LibBootstrap.sol index af4c6ab103..60b5b6c6c0 100644 --- a/contracts/zero-ex/contracts/src/migrations/LibBootstrap.sol +++ b/contracts/zero-ex/contracts/src/migrations/LibBootstrap.sol @@ -23,9 +23,7 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../errors/LibProxyRichErrors.sol"; - library LibBootstrap { - /// @dev Magic bytes returned by the bootstrapper to indicate success. /// This is `keccack('BOOTSTRAP_SUCCESS')`. bytes4 internal constant BOOTSTRAP_SUCCESS = 0xd150751b; @@ -35,17 +33,9 @@ library LibBootstrap { /// @dev Perform a delegatecall and ensure it returns the magic bytes. /// @param target The call target. /// @param data The call data. - function delegatecallBootstrapFunction( - address target, - bytes memory data - ) - internal - { + function delegatecallBootstrapFunction(address target, bytes memory data) internal { (bool success, bytes memory resultData) = target.delegatecall(data); - if (!success || - resultData.length != 32 || - abi.decode(resultData, (bytes4)) != BOOTSTRAP_SUCCESS) - { + if (!success || resultData.length != 32 || abi.decode(resultData, (bytes4)) != BOOTSTRAP_SUCCESS) { LibProxyRichErrors.BootstrapCallFailedError(target, resultData).rrevert(); } } diff --git a/contracts/zero-ex/contracts/src/migrations/LibMigrate.sol b/contracts/zero-ex/contracts/src/migrations/LibMigrate.sol index 1419003463..f8fb85878b 100644 --- a/contracts/zero-ex/contracts/src/migrations/LibMigrate.sol +++ b/contracts/zero-ex/contracts/src/migrations/LibMigrate.sol @@ -23,9 +23,7 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../errors/LibOwnableRichErrors.sol"; - library LibMigrate { - /// @dev Magic bytes returned by a migrator to indicate success. /// This is `keccack('MIGRATE_SUCCESS')`. bytes4 internal constant MIGRATE_SUCCESS = 0x2c64c5ef; @@ -35,17 +33,9 @@ library LibMigrate { /// @dev Perform a delegatecall and ensure it returns the magic bytes. /// @param target The call target. /// @param data The call data. - function delegatecallMigrateFunction( - address target, - bytes memory data - ) - internal - { + function delegatecallMigrateFunction(address target, bytes memory data) internal { (bool success, bytes memory resultData) = target.delegatecall(data); - if (!success || - resultData.length != 32 || - abi.decode(resultData, (bytes4)) != MIGRATE_SUCCESS) - { + if (!success || resultData.length != 32 || abi.decode(resultData, (bytes4)) != MIGRATE_SUCCESS) { LibOwnableRichErrors.MigrateCallFailedError(target, resultData).rrevert(); } } diff --git a/contracts/zero-ex/contracts/src/storage/LibERC1155OrdersStorage.sol b/contracts/zero-ex/contracts/src/storage/LibERC1155OrdersStorage.sol index ab523d9c2c..89e3ac8886 100644 --- a/contracts/zero-ex/contracts/src/storage/LibERC1155OrdersStorage.sol +++ b/contracts/zero-ex/contracts/src/storage/LibERC1155OrdersStorage.sol @@ -22,10 +22,8 @@ pragma experimental ABIEncoderV2; import "./LibStorage.sol"; - /// @dev Storage helpers for `ERC1155OrdersFeature`. library LibERC1155OrdersStorage { - struct OrderState { // The amount (denominated in the ERC1155 asset) // that the order has been filled by. @@ -44,12 +42,12 @@ library LibERC1155OrdersStorage { /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { - uint256 storageSlot = LibStorage.getStorageSlot( - LibStorage.StorageId.ERC1155Orders - ); + uint256 storageSlot = LibStorage.getStorageSlot(LibStorage.StorageId.ERC1155Orders); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries - assembly { stor_slot := storageSlot } + assembly { + stor_slot := storageSlot + } } } diff --git a/contracts/zero-ex/contracts/src/storage/LibERC721OrdersStorage.sol b/contracts/zero-ex/contracts/src/storage/LibERC721OrdersStorage.sol index a4b5fe5e19..57a11022e9 100644 --- a/contracts/zero-ex/contracts/src/storage/LibERC721OrdersStorage.sol +++ b/contracts/zero-ex/contracts/src/storage/LibERC721OrdersStorage.sol @@ -22,10 +22,8 @@ pragma experimental ABIEncoderV2; import "./LibStorage.sol"; - /// @dev Storage helpers for `ERC721OrdersFeature`. library LibERC721OrdersStorage { - /// @dev Storage bucket for this feature. struct Storage { // maker => nonce range => order status bit vector @@ -36,12 +34,12 @@ library LibERC721OrdersStorage { /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { - uint256 storageSlot = LibStorage.getStorageSlot( - LibStorage.StorageId.ERC721Orders - ); + uint256 storageSlot = LibStorage.getStorageSlot(LibStorage.StorageId.ERC721Orders); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries - assembly { stor_slot := storageSlot } + assembly { + stor_slot := storageSlot + } } } diff --git a/contracts/zero-ex/contracts/src/storage/LibMetaTransactionsStorage.sol b/contracts/zero-ex/contracts/src/storage/LibMetaTransactionsStorage.sol index 8ee809f1e2..6b0ab35d3a 100644 --- a/contracts/zero-ex/contracts/src/storage/LibMetaTransactionsStorage.sol +++ b/contracts/zero-ex/contracts/src/storage/LibMetaTransactionsStorage.sol @@ -22,24 +22,22 @@ pragma experimental ABIEncoderV2; import "./LibStorage.sol"; - /// @dev Storage helpers for the `MetaTransactions` feature. library LibMetaTransactionsStorage { - /// @dev Storage bucket for this feature. struct Storage { // The block number when a hash was executed. - mapping (bytes32 => uint256) mtxHashToExecutedBlockNumber; + mapping(bytes32 => uint256) mtxHashToExecutedBlockNumber; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { - uint256 storageSlot = LibStorage.getStorageSlot( - LibStorage.StorageId.MetaTransactions - ); + uint256 storageSlot = LibStorage.getStorageSlot(LibStorage.StorageId.MetaTransactions); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries - assembly { stor_slot := storageSlot } + assembly { + stor_slot := storageSlot + } } } diff --git a/contracts/zero-ex/contracts/src/storage/LibNativeOrdersStorage.sol b/contracts/zero-ex/contracts/src/storage/LibNativeOrdersStorage.sol index ceb899281e..8470ccaf83 100644 --- a/contracts/zero-ex/contracts/src/storage/LibNativeOrdersStorage.sol +++ b/contracts/zero-ex/contracts/src/storage/LibNativeOrdersStorage.sol @@ -22,10 +22,8 @@ pragma experimental ABIEncoderV2; import "./LibStorage.sol"; - /// @dev Storage helpers for `NativeOrdersFeature`. library LibNativeOrdersStorage { - /// @dev Storage bucket for this feature. struct Storage { // How much taker token has been filled in order. @@ -34,12 +32,10 @@ library LibNativeOrdersStorage { mapping(bytes32 => uint256) orderHashToTakerTokenFilledAmount; // The minimum valid order salt for a given maker and order pair (maker, taker) // for limit orders. - mapping(address => mapping(address => mapping(address => uint256))) - limitOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt; + mapping(address => mapping(address => mapping(address => uint256))) limitOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt; // The minimum valid order salt for a given maker and order pair (maker, taker) // for RFQ orders. - mapping(address => mapping(address => mapping(address => uint256))) - rfqOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt; + mapping(address => mapping(address => mapping(address => uint256))) rfqOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt; // For a given order origin, which tx.origin addresses are allowed to // fill the order. mapping(address => mapping(address => bool)) originRegistry; @@ -50,12 +46,12 @@ library LibNativeOrdersStorage { /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { - uint256 storageSlot = LibStorage.getStorageSlot( - LibStorage.StorageId.NativeOrders - ); + uint256 storageSlot = LibStorage.getStorageSlot(LibStorage.StorageId.NativeOrders); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries - assembly { stor_slot := storageSlot } + assembly { + stor_slot := storageSlot + } } } diff --git a/contracts/zero-ex/contracts/src/storage/LibOtcOrdersStorage.sol b/contracts/zero-ex/contracts/src/storage/LibOtcOrdersStorage.sol index 753571cda1..74a1a0553f 100644 --- a/contracts/zero-ex/contracts/src/storage/LibOtcOrdersStorage.sol +++ b/contracts/zero-ex/contracts/src/storage/LibOtcOrdersStorage.sol @@ -22,10 +22,8 @@ pragma experimental ABIEncoderV2; import "./LibStorage.sol"; - /// @dev Storage helpers for `OtcOrdersFeature`. library LibOtcOrdersStorage { - /// @dev Storage bucket for this feature. struct Storage { // tx origin => nonce buckets => min nonce @@ -34,12 +32,12 @@ library LibOtcOrdersStorage { /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { - uint256 storageSlot = LibStorage.getStorageSlot( - LibStorage.StorageId.OtcOrders - ); + uint256 storageSlot = LibStorage.getStorageSlot(LibStorage.StorageId.OtcOrders); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries - assembly { stor_slot := storageSlot } + assembly { + stor_slot := storageSlot + } } } diff --git a/contracts/zero-ex/contracts/src/storage/LibOwnableStorage.sol b/contracts/zero-ex/contracts/src/storage/LibOwnableStorage.sol index aa8c076cbb..7540ad6f61 100644 --- a/contracts/zero-ex/contracts/src/storage/LibOwnableStorage.sol +++ b/contracts/zero-ex/contracts/src/storage/LibOwnableStorage.sol @@ -22,10 +22,8 @@ pragma experimental ABIEncoderV2; import "./LibStorage.sol"; - /// @dev Storage helpers for the `Ownable` feature. library LibOwnableStorage { - /// @dev Storage bucket for this feature. struct Storage { // The owner of this contract. @@ -34,12 +32,12 @@ library LibOwnableStorage { /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { - uint256 storageSlot = LibStorage.getStorageSlot( - LibStorage.StorageId.Ownable - ); + uint256 storageSlot = LibStorage.getStorageSlot(LibStorage.StorageId.Ownable); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries - assembly { stor_slot := storageSlot } + assembly { + stor_slot := storageSlot + } } } diff --git a/contracts/zero-ex/contracts/src/storage/LibProxyStorage.sol b/contracts/zero-ex/contracts/src/storage/LibProxyStorage.sol index 1216af75e3..6da7b6f6db 100644 --- a/contracts/zero-ex/contracts/src/storage/LibProxyStorage.sol +++ b/contracts/zero-ex/contracts/src/storage/LibProxyStorage.sol @@ -22,10 +22,8 @@ pragma experimental ABIEncoderV2; import "./LibStorage.sol"; - /// @dev Storage helpers for the proxy contract. library LibProxyStorage { - /// @dev Storage bucket for proxy contract. struct Storage { // Mapping of function selector -> function implementation @@ -36,12 +34,12 @@ library LibProxyStorage { /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { - uint256 storageSlot = LibStorage.getStorageSlot( - LibStorage.StorageId.Proxy - ); + uint256 storageSlot = LibStorage.getStorageSlot(LibStorage.StorageId.Proxy); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries - assembly { stor_slot := storageSlot } + assembly { + stor_slot := storageSlot + } } } diff --git a/contracts/zero-ex/contracts/src/storage/LibReentrancyGuardStorage.sol b/contracts/zero-ex/contracts/src/storage/LibReentrancyGuardStorage.sol index 9aaae26e5e..a7b5c04411 100644 --- a/contracts/zero-ex/contracts/src/storage/LibReentrancyGuardStorage.sol +++ b/contracts/zero-ex/contracts/src/storage/LibReentrancyGuardStorage.sol @@ -23,10 +23,8 @@ pragma experimental ABIEncoderV2; import "./LibStorage.sol"; import "../external/IFlashWallet.sol"; - /// @dev Storage helpers for the `FixinReentrancyGuard` mixin. library LibReentrancyGuardStorage { - /// @dev Storage bucket for this feature. struct Storage { // Reentrancy flags set whenever a non-reentrant function is entered @@ -36,12 +34,12 @@ library LibReentrancyGuardStorage { /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { - uint256 storageSlot = LibStorage.getStorageSlot( - LibStorage.StorageId.ReentrancyGuard - ); + uint256 storageSlot = LibStorage.getStorageSlot(LibStorage.StorageId.ReentrancyGuard); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries - assembly { stor_slot := storageSlot } + assembly { + stor_slot := storageSlot + } } } diff --git a/contracts/zero-ex/contracts/src/storage/LibSimpleFunctionRegistryStorage.sol b/contracts/zero-ex/contracts/src/storage/LibSimpleFunctionRegistryStorage.sol index fe724e7892..1ba4ba57b7 100644 --- a/contracts/zero-ex/contracts/src/storage/LibSimpleFunctionRegistryStorage.sol +++ b/contracts/zero-ex/contracts/src/storage/LibSimpleFunctionRegistryStorage.sol @@ -22,10 +22,8 @@ pragma experimental ABIEncoderV2; import "./LibStorage.sol"; - /// @dev Storage helpers for the `SimpleFunctionRegistry` feature. library LibSimpleFunctionRegistryStorage { - /// @dev Storage bucket for this feature. struct Storage { // Mapping of function selector -> implementation history. @@ -34,12 +32,12 @@ library LibSimpleFunctionRegistryStorage { /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { - uint256 storageSlot = LibStorage.getStorageSlot( - LibStorage.StorageId.SimpleFunctionRegistry - ); + uint256 storageSlot = LibStorage.getStorageSlot(LibStorage.StorageId.SimpleFunctionRegistry); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries - assembly { stor_slot := storageSlot } + assembly { + stor_slot := storageSlot + } } } diff --git a/contracts/zero-ex/contracts/src/storage/LibStorage.sol b/contracts/zero-ex/contracts/src/storage/LibStorage.sol index 0185680eb3..375ce2e5e7 100644 --- a/contracts/zero-ex/contracts/src/storage/LibStorage.sol +++ b/contracts/zero-ex/contracts/src/storage/LibStorage.sol @@ -20,10 +20,8 @@ pragma solidity ^0.6; pragma experimental ABIEncoderV2; - /// @dev Common storage helpers library LibStorage { - /// @dev What to bit-shift a storage ID by to get its slot. /// This gives us a maximum of 2**128 inline fields in each bucket. uint256 private constant STORAGE_SLOT_EXP = 128; @@ -49,11 +47,7 @@ library LibStorage { /// See: https://solidity.readthedocs.io/en/v0.6.6/assembly.html#access-to-external-variables-functions-and-libraries /// @param storageId An entry in `StorageId` /// @return slot The storage slot. - function getStorageSlot(StorageId storageId) - internal - pure - returns (uint256 slot) - { + function getStorageSlot(StorageId storageId) internal pure returns (uint256 slot) { // This should never overflow with a reasonable `STORAGE_SLOT_EXP` // because Solidity will do a range check on `storageId` during the cast. return (uint256(storageId) + 1) << STORAGE_SLOT_EXP; diff --git a/contracts/zero-ex/contracts/src/storage/LibTransformERC20Storage.sol b/contracts/zero-ex/contracts/src/storage/LibTransformERC20Storage.sol index 687a5fe9d7..83f9a4d071 100644 --- a/contracts/zero-ex/contracts/src/storage/LibTransformERC20Storage.sol +++ b/contracts/zero-ex/contracts/src/storage/LibTransformERC20Storage.sol @@ -23,10 +23,8 @@ pragma experimental ABIEncoderV2; import "./LibStorage.sol"; import "../external/IFlashWallet.sol"; - /// @dev Storage helpers for the `TransformERC20` feature. library LibTransformERC20Storage { - /// @dev Storage bucket for this feature. struct Storage { // The current wallet instance. @@ -39,12 +37,12 @@ library LibTransformERC20Storage { /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { - uint256 storageSlot = LibStorage.getStorageSlot( - LibStorage.StorageId.TransformERC20 - ); + uint256 storageSlot = LibStorage.getStorageSlot(LibStorage.StorageId.TransformERC20); // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries - assembly { stor_slot := storageSlot } + assembly { + stor_slot := storageSlot + } } } diff --git a/contracts/zero-ex/contracts/src/transformers/AffiliateFeeTransformer.sol b/contracts/zero-ex/contracts/src/transformers/AffiliateFeeTransformer.sol index 39d1a5c6d9..7efcb45931 100644 --- a/contracts/zero-ex/contracts/src/transformers/AffiliateFeeTransformer.sol +++ b/contracts/zero-ex/contracts/src/transformers/AffiliateFeeTransformer.sol @@ -28,11 +28,8 @@ import "../errors/LibTransformERC20RichErrors.sol"; import "./Transformer.sol"; import "./LibERC20Transformer.sol"; - /// @dev A transformer that transfers tokens to arbitrary addresses. -contract AffiliateFeeTransformer is - Transformer -{ +contract AffiliateFeeTransformer is Transformer { using LibRichErrorsV06 for bytes; using LibSafeMathV06 for uint256; using LibERC20Transformer for IERC20TokenV06; @@ -54,11 +51,7 @@ contract AffiliateFeeTransformer is /// @dev Transfers tokens to recipients. /// @param context Context information. /// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`). - function transform(TransformContext calldata context) - external - override - returns (bytes4 success) - { + function transform(TransformContext calldata context) external override returns (bytes4 success) { TokenFee[] memory fees = abi.decode(context.data, (TokenFee[])); // Transfer tokens to recipients. diff --git a/contracts/zero-ex/contracts/src/transformers/FillQuoteTransformer.sol b/contracts/zero-ex/contracts/src/transformers/FillQuoteTransformer.sol index f4882e20ae..7430140048 100644 --- a/contracts/zero-ex/contracts/src/transformers/FillQuoteTransformer.sol +++ b/contracts/zero-ex/contracts/src/transformers/FillQuoteTransformer.sol @@ -35,9 +35,7 @@ import "../IZeroEx.sol"; /// @dev A transformer that fills an ERC20 market sell/buy quote. /// This transformer shortcuts bridge orders and fills them directly -contract FillQuoteTransformer is - Transformer -{ +contract FillQuoteTransformer is Transformer { using LibERC20TokenV06 for IERC20TokenV06; using LibERC20Transformer for IERC20TokenV06; using LibSafeMathV06 for uint256; @@ -88,7 +86,6 @@ contract FillQuoteTransformer is // The token being bought. // This should be an actual token, not the ETH pseudo-token. IERC20TokenV06 buyToken; - // External liquidity bridge orders. Sorted by fill sequence. IBridgeAdapter.BridgeOrder[] bridgeOrders; // Native limit orders. Sorted by fill sequence. @@ -97,19 +94,16 @@ contract FillQuoteTransformer is OtcOrderInfo[] otcOrders; // Native RFQ orders. Sorted by fill sequence. RfqOrderInfo[] rfqOrders; - // The sequence to fill the orders in. Each item will fill the next // order of that type in either `bridgeOrders`, `limitOrders`, // or `rfqOrders.` OrderType[] fillSequence; - // Amount of `sellToken` to sell or `buyToken` to buy. // For sells, setting the high-bit indicates that // `sellAmount & LOW_BITS` should be treated as a `1e18` fraction of // the current balance of `sellToken`, where // `1e18+ == 100%` and `0.5e18 == 50%`, etc. uint256 fillAmount; - // Who to transfer unused protocol fees to. // May be a valid address or one of: // `address(0)`: Stay in flash wallet. @@ -144,7 +138,7 @@ contract FillQuoteTransformer is event ProtocolFeeUnfunded(bytes32 orderHash); /// @dev The highest bit of a uint256 value. - uint256 private constant HIGH_BIT = 2 ** 255; + uint256 private constant HIGH_BIT = 2**255; /// @dev Mask of the lower 255 bits of a uint256 value. uint256 private constant LOWER_255_BITS = HIGH_BIT - 1; /// @dev If `refundReceiver` is set to this address, unpsent @@ -163,10 +157,7 @@ contract FillQuoteTransformer is /// @dev Create this contract. /// @param bridgeAdapter_ The bridge adapter contract. /// @param zeroEx_ The Exchange Proxy contract. - constructor(IBridgeAdapter bridgeAdapter_, IZeroEx zeroEx_) - public - Transformer() - { + constructor(IBridgeAdapter bridgeAdapter_, IZeroEx zeroEx_) public Transformer() { bridgeAdapter = bridgeAdapter_; zeroEx = zeroEx_; } @@ -176,31 +167,30 @@ contract FillQuoteTransformer is /// to this call. `buyToken` and excess ETH will be transferred back to the caller. /// @param context Context information. /// @return magicBytes The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`). - function transform(TransformContext calldata context) - external - override - returns (bytes4 magicBytes) - { + function transform(TransformContext calldata context) external override returns (bytes4 magicBytes) { TransformData memory data = abi.decode(context.data, (TransformData)); FillState memory state; // Validate data fields. if (data.sellToken.isTokenETH() || data.buyToken.isTokenETH()) { - LibTransformERC20RichErrors.InvalidTransformDataError( - LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_TOKENS, - context.data - ).rrevert(); + LibTransformERC20RichErrors + .InvalidTransformDataError( + LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_TOKENS, + context.data + ) + .rrevert(); } - if (data.bridgeOrders.length - + data.limitOrders.length - + data.rfqOrders.length - + data.otcOrders.length != data.fillSequence.length + if ( + data.bridgeOrders.length + data.limitOrders.length + data.rfqOrders.length + data.otcOrders.length != + data.fillSequence.length ) { - LibTransformERC20RichErrors.InvalidTransformDataError( - LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_ARRAY_LENGTH, - context.data - ).rrevert(); + LibTransformERC20RichErrors + .InvalidTransformDataError( + LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_ARRAY_LENGTH, + context.data + ) + .rrevert(); } state.takerTokenBalanceRemaining = data.sellToken.getTokenBalanceOf(address(this)); @@ -214,8 +204,7 @@ contract FillQuoteTransformer is data.sellToken.approveIfBelow(address(zeroEx), data.fillAmount); // Compute the protocol fee if a limit order is present. if (data.limitOrders.length != 0) { - state.protocolFee = uint256(zeroEx.getProtocolFeeMultiplier()) - .safeMul(tx.gasprice); + state.protocolFee = uint256(zeroEx.getProtocolFeeMultiplier()).safeMul(tx.gasprice); } } @@ -226,10 +215,14 @@ contract FillQuoteTransformer is // Check if we've hit our targets. if (data.side == Side.Sell) { // Market sell check. - if (state.soldAmount >= data.fillAmount) { break; } + if (state.soldAmount >= data.fillAmount) { + break; + } } else { // Market buy check. - if (state.boughtAmount >= data.fillAmount) { break; } + if (state.boughtAmount >= data.fillAmount) { + break; + } } state.currentOrderType = OrderType(data.fillSequence[i]); @@ -249,14 +242,10 @@ contract FillQuoteTransformer is } // Accumulate totals. - state.soldAmount = state.soldAmount - .safeAdd(results.takerTokenSoldAmount); - state.boughtAmount = state.boughtAmount - .safeAdd(results.makerTokenBoughtAmount); - state.ethRemaining = state.ethRemaining - .safeSub(results.protocolFeePaid); - state.takerTokenBalanceRemaining = state.takerTokenBalanceRemaining - .safeSub(results.takerTokenSoldAmount); + state.soldAmount = state.soldAmount.safeAdd(results.takerTokenSoldAmount); + state.boughtAmount = state.boughtAmount.safeAdd(results.makerTokenBoughtAmount); + state.ethRemaining = state.ethRemaining.safeSub(results.protocolFeePaid); + state.takerTokenBalanceRemaining = state.takerTokenBalanceRemaining.safeSub(results.takerTokenSoldAmount); state.currentIndices[uint256(state.currentOrderType)]++; } @@ -265,21 +254,15 @@ contract FillQuoteTransformer is // Market sell check. if (state.soldAmount < data.fillAmount) { LibTransformERC20RichErrors - .IncompleteFillSellQuoteError( - address(data.sellToken), - state.soldAmount, - data.fillAmount - ).rrevert(); + .IncompleteFillSellQuoteError(address(data.sellToken), state.soldAmount, data.fillAmount) + .rrevert(); } } else { // Market buy check. if (state.boughtAmount < data.fillAmount) { LibTransformERC20RichErrors - .IncompleteFillBuyQuoteError( - address(data.buyToken), - state.boughtAmount, - data.fillAmount - ).rrevert(); + .IncompleteFillBuyQuoteError(address(data.buyToken), state.boughtAmount, data.fillAmount) + .rrevert(); } } @@ -287,11 +270,11 @@ contract FillQuoteTransformer is if (state.ethRemaining > 0 && data.refundReceiver != address(0)) { bool transferSuccess; if (data.refundReceiver == REFUND_RECEIVER_RECIPIENT) { - (transferSuccess,) = context.recipient.call{value: state.ethRemaining}(""); + (transferSuccess, ) = context.recipient.call{value: state.ethRemaining}(""); } else if (data.refundReceiver == REFUND_RECEIVER_SENDER) { - (transferSuccess,) = context.sender.call{value: state.ethRemaining}(""); + (transferSuccess, ) = context.sender.call{value: state.ethRemaining}(""); } else { - (transferSuccess,) = data.refundReceiver.call{value: state.ethRemaining}(""); + (transferSuccess, ) = data.refundReceiver.call{value: state.ethRemaining}(""); } require(transferSuccess, "FillQuoteTransformer/ETHER_TRANSFER_FALIED"); } @@ -303,10 +286,7 @@ contract FillQuoteTransformer is IBridgeAdapter.BridgeOrder memory order, TransformData memory data, FillState memory state - ) - private - returns (FillOrderResults memory results) - { + ) private returns (FillOrderResults memory results) { uint256 takerTokenFillAmount = _computeTakerTokenFillAmount( data, state, @@ -327,7 +307,7 @@ contract FillQuoteTransformer is if (success) { results.makerTokenBoughtAmount = abi.decode(resultData, (uint256)); results.takerTokenSoldAmount = takerTokenFillAmount; - } + } } // Fill a single limit order. @@ -335,10 +315,7 @@ contract FillQuoteTransformer is LimitOrderInfo memory orderInfo, TransformData memory data, FillState memory state - ) - private - returns (FillOrderResults memory results) - { + ) private returns (FillOrderResults memory results) { uint256 takerTokenFillAmount = LibSafeMathV06.min256( _computeTakerTokenFillAmount( data, @@ -358,22 +335,21 @@ contract FillQuoteTransformer is } try - zeroEx.fillLimitOrder - {value: state.protocolFee} - ( - orderInfo.order, - orderInfo.signature, - takerTokenFillAmount.safeDowncastToUint128() - ) - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + zeroEx.fillLimitOrder{value: state.protocolFee}( + orderInfo.order, + orderInfo.signature, + takerTokenFillAmount.safeDowncastToUint128() + ) + returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { if (orderInfo.order.takerTokenFeeAmount > 0) { takerTokenFilledAmount = takerTokenFilledAmount.safeAdd128( - LibMathV06.getPartialAmountFloor( - takerTokenFilledAmount, - orderInfo.order.takerAmount, - orderInfo.order.takerTokenFeeAmount - ).safeDowncastToUint128() + LibMathV06 + .getPartialAmountFloor( + takerTokenFilledAmount, + orderInfo.order.takerAmount, + orderInfo.order.takerTokenFeeAmount + ) + .safeDowncastToUint128() ); } results.takerTokenSoldAmount = takerTokenFilledAmount; @@ -387,30 +363,15 @@ contract FillQuoteTransformer is RfqOrderInfo memory orderInfo, TransformData memory data, FillState memory state - ) - private - returns (FillOrderResults memory results) - { + ) private returns (FillOrderResults memory results) { uint256 takerTokenFillAmount = LibSafeMathV06.min256( - _computeTakerTokenFillAmount( - data, - state, - orderInfo.order.takerAmount, - orderInfo.order.makerAmount, - 0 - ), + _computeTakerTokenFillAmount(data, state, orderInfo.order.takerAmount, orderInfo.order.makerAmount, 0), orderInfo.maxTakerTokenFillAmount ); try - zeroEx.fillRfqOrder - ( - orderInfo.order, - orderInfo.signature, - takerTokenFillAmount.safeDowncastToUint128() - ) - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + zeroEx.fillRfqOrder(orderInfo.order, orderInfo.signature, takerTokenFillAmount.safeDowncastToUint128()) + returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { results.takerTokenSoldAmount = takerTokenFilledAmount; results.makerTokenBoughtAmount = makerTokenFilledAmount; } catch {} @@ -421,30 +382,14 @@ contract FillQuoteTransformer is OtcOrderInfo memory orderInfo, TransformData memory data, FillState memory state - ) - private - returns (FillOrderResults memory results) - { - + ) private returns (FillOrderResults memory results) { uint256 takerTokenFillAmount = LibSafeMathV06.min256( - _computeTakerTokenFillAmount( - data, - state, - orderInfo.order.takerAmount, - orderInfo.order.makerAmount, - 0 - ), + _computeTakerTokenFillAmount(data, state, orderInfo.order.takerAmount, orderInfo.order.makerAmount, 0), orderInfo.maxTakerTokenFillAmount ); try - zeroEx.fillOtcOrder - ( - orderInfo.order, - orderInfo.signature, - takerTokenFillAmount.safeDowncastToUint128() - ) - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + zeroEx.fillOtcOrder(orderInfo.order, orderInfo.signature, takerTokenFillAmount.safeDowncastToUint128()) + returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { results.takerTokenSoldAmount = takerTokenFilledAmount; results.makerTokenBoughtAmount = makerTokenFilledAmount; } catch { @@ -459,11 +404,7 @@ contract FillQuoteTransformer is uint256 orderTakerAmount, uint256 orderMakerAmount, uint256 orderTakerTokenFeeAmount - ) - private - pure - returns (uint256 takerTokenFillAmount) - { + ) private pure returns (uint256 takerTokenFillAmount) { if (data.side == Side.Sell) { takerTokenFillAmount = data.fillAmount.safeSub(state.soldAmount); if (orderTakerTokenFeeAmount != 0) { @@ -473,34 +414,31 @@ contract FillQuoteTransformer is orderTakerAmount ); } - } else { // Buy + } else { + // Buy takerTokenFillAmount = LibMathV06.getPartialAmountCeil( data.fillAmount.safeSub(state.boughtAmount), orderMakerAmount, orderTakerAmount ); } - return LibSafeMathV06.min256( - LibSafeMathV06.min256(takerTokenFillAmount, orderTakerAmount), - state.takerTokenBalanceRemaining - ); + return + LibSafeMathV06.min256( + LibSafeMathV06.min256(takerTokenFillAmount, orderTakerAmount), + state.takerTokenBalanceRemaining + ); } // Convert possible proportional values to absolute quantities. - function _normalizeFillAmount(uint256 rawAmount, uint256 balance) - private - pure - returns (uint256 normalized) - { + function _normalizeFillAmount(uint256 rawAmount, uint256 balance) private pure returns (uint256 normalized) { if ((rawAmount & HIGH_BIT) == HIGH_BIT) { // If the high bit of `rawAmount` is set then the lower 255 bits // specify a fraction of `balance`. - return LibSafeMathV06.min256( - balance - * LibSafeMathV06.min256(rawAmount & LOWER_255_BITS, 1e18) - / 1e18, - balance - ); + return + LibSafeMathV06.min256( + (balance * LibSafeMathV06.min256(rawAmount & LOWER_255_BITS, 1e18)) / 1e18, + balance + ); } return rawAmount; } diff --git a/contracts/zero-ex/contracts/src/transformers/IERC20Transformer.sol b/contracts/zero-ex/contracts/src/transformers/IERC20Transformer.sol index 0700aecd87..822e7e9c23 100644 --- a/contracts/zero-ex/contracts/src/transformers/IERC20Transformer.sol +++ b/contracts/zero-ex/contracts/src/transformers/IERC20Transformer.sol @@ -22,10 +22,8 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; - /// @dev A transformation callback used in `TransformERC20.transformERC20()`. interface IERC20Transformer { - /// @dev Context information to pass into `transform()` by `TransformERC20.transformERC20()`. struct TransformContext { // The caller of `TransformERC20.transformERC20()`. @@ -41,7 +39,5 @@ interface IERC20Transformer { /// delegatecalled in the context of the FlashWallet instance being used. /// @param context Context information. /// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`). - function transform(TransformContext calldata context) - external - returns (bytes4 success); + function transform(TransformContext calldata context) external returns (bytes4 success); } diff --git a/contracts/zero-ex/contracts/src/transformers/LibERC20Transformer.sol b/contracts/zero-ex/contracts/src/transformers/LibERC20Transformer.sol index 58b87513f5..5c24743bd3 100644 --- a/contracts/zero-ex/contracts/src/transformers/LibERC20Transformer.sol +++ b/contracts/zero-ex/contracts/src/transformers/LibERC20Transformer.sol @@ -23,18 +23,16 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; - library LibERC20Transformer { - using LibERC20TokenV06 for IERC20TokenV06; /// @dev ETH pseudo-token address. - address constant internal ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; + address internal constant ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev ETH pseudo-token. - IERC20TokenV06 constant internal ETH_TOKEN = IERC20TokenV06(ETH_TOKEN_ADDRESS); + IERC20TokenV06 internal constant ETH_TOKEN = IERC20TokenV06(ETH_TOKEN_ADDRESS); /// @dev Return value indicating success in `IERC20Transformer.transform()`. /// This is just `keccak256('TRANSFORMER_SUCCESS')`. - bytes4 constant internal TRANSFORMER_SUCCESS = 0x13c9929e; + bytes4 internal constant TRANSFORMER_SUCCESS = 0x13c9929e; /// @dev Transfer ERC20 tokens and ETH. /// @param token An ERC20 or the ETH pseudo-token address (`ETH_TOKEN_ADDRESS`). @@ -44,9 +42,7 @@ library LibERC20Transformer { IERC20TokenV06 token, address payable to, uint256 amount - ) - internal - { + ) internal { if (isTokenETH(token)) { to.transfer(amount); } else { @@ -57,11 +53,7 @@ library LibERC20Transformer { /// @dev Check if a token is the ETH pseudo-token. /// @param token The token to check. /// @return isETH `true` if the token is the ETH pseudo-token. - function isTokenETH(IERC20TokenV06 token) - internal - pure - returns (bool isETH) - { + function isTokenETH(IERC20TokenV06 token) internal pure returns (bool isETH) { return address(token) == ETH_TOKEN_ADDRESS; } @@ -69,11 +61,7 @@ library LibERC20Transformer { /// @param token An ERC20 or the ETH pseudo-token address (`ETH_TOKEN_ADDRESS`). /// @param owner Holder of the tokens. /// @return tokenBalance The balance of `owner`. - function getTokenBalanceOf(IERC20TokenV06 token, address owner) - internal - view - returns (uint256 tokenBalance) - { + function getTokenBalanceOf(IERC20TokenV06 token, address owner) internal view returns (uint256 tokenBalance) { if (isTokenETH(token)) { return owner.balance; } @@ -83,40 +71,36 @@ library LibERC20Transformer { /// @dev RLP-encode a 32-bit or less account nonce. /// @param nonce A positive integer in the range 0 <= nonce < 2^32. /// @return rlpNonce The RLP encoding. - function rlpEncodeNonce(uint32 nonce) - internal - pure - returns (bytes memory rlpNonce) - { + function rlpEncodeNonce(uint32 nonce) internal pure returns (bytes memory rlpNonce) { // See https://github.com/ethereum/wiki/wiki/RLP for RLP encoding rules. if (nonce == 0) { rlpNonce = new bytes(1); rlpNonce[0] = 0x80; } else if (nonce < 0x80) { rlpNonce = new bytes(1); - rlpNonce[0] = byte(uint8(nonce)); + rlpNonce[0] = bytes1(uint8(nonce)); } else if (nonce <= 0xFF) { rlpNonce = new bytes(2); rlpNonce[0] = 0x81; - rlpNonce[1] = byte(uint8(nonce)); + rlpNonce[1] = bytes1(uint8(nonce)); } else if (nonce <= 0xFFFF) { rlpNonce = new bytes(3); rlpNonce[0] = 0x82; - rlpNonce[1] = byte(uint8((nonce & 0xFF00) >> 8)); - rlpNonce[2] = byte(uint8(nonce)); + rlpNonce[1] = bytes1(uint8((nonce & 0xFF00) >> 8)); + rlpNonce[2] = bytes1(uint8(nonce)); } else if (nonce <= 0xFFFFFF) { rlpNonce = new bytes(4); rlpNonce[0] = 0x83; - rlpNonce[1] = byte(uint8((nonce & 0xFF0000) >> 16)); - rlpNonce[2] = byte(uint8((nonce & 0xFF00) >> 8)); - rlpNonce[3] = byte(uint8(nonce)); + rlpNonce[1] = bytes1(uint8((nonce & 0xFF0000) >> 16)); + rlpNonce[2] = bytes1(uint8((nonce & 0xFF00) >> 8)); + rlpNonce[3] = bytes1(uint8(nonce)); } else { rlpNonce = new bytes(5); rlpNonce[0] = 0x84; - rlpNonce[1] = byte(uint8((nonce & 0xFF000000) >> 24)); - rlpNonce[2] = byte(uint8((nonce & 0xFF0000) >> 16)); - rlpNonce[3] = byte(uint8((nonce & 0xFF00) >> 8)); - rlpNonce[4] = byte(uint8(nonce)); + rlpNonce[1] = bytes1(uint8((nonce & 0xFF000000) >> 24)); + rlpNonce[2] = bytes1(uint8((nonce & 0xFF0000) >> 16)); + rlpNonce[3] = bytes1(uint8((nonce & 0xFF00) >> 8)); + rlpNonce[4] = bytes1(uint8(nonce)); } } @@ -135,11 +119,20 @@ library LibERC20Transformer { // hash of the RLP-encoded deployer's account address + account nonce. // See: https://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed bytes memory rlpNonce = rlpEncodeNonce(deploymentNonce); - return address(uint160(uint256(keccak256(abi.encodePacked( - byte(uint8(0xC0 + 21 + rlpNonce.length)), - byte(uint8(0x80 + 20)), - deployer, - rlpNonce - ))))); + return + address( + uint160( + uint256( + keccak256( + abi.encodePacked( + bytes1(uint8(0xC0 + 21 + rlpNonce.length)), + bytes1(uint8(0x80 + 20)), + deployer, + rlpNonce + ) + ) + ) + ) + ); } } diff --git a/contracts/zero-ex/contracts/src/transformers/LogMetadataTransformer.sol b/contracts/zero-ex/contracts/src/transformers/LogMetadataTransformer.sol index 571d48efa4..d746aa2e79 100644 --- a/contracts/zero-ex/contracts/src/transformers/LogMetadataTransformer.sol +++ b/contracts/zero-ex/contracts/src/transformers/LogMetadataTransformer.sol @@ -23,11 +23,8 @@ pragma experimental ABIEncoderV2; import "./Transformer.sol"; import "./LibERC20Transformer.sol"; - /// @dev A transformer that just emits an event with an arbitrary byte payload. -contract LogMetadataTransformer is - Transformer -{ +contract LogMetadataTransformer is Transformer { event TransformerMetadata(address sender, address taker, bytes data); /// @dev Maximum uint256 value. @@ -36,11 +33,7 @@ contract LogMetadataTransformer is /// @dev Emits an event. /// @param context Context information. /// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`). - function transform(TransformContext calldata context) - external - override - returns (bytes4 success) - { + function transform(TransformContext calldata context) external override returns (bytes4 success) { emit TransformerMetadata(context.sender, context.recipient, context.data); return LibERC20Transformer.TRANSFORMER_SUCCESS; } diff --git a/contracts/zero-ex/contracts/src/transformers/PayTakerTransformer.sol b/contracts/zero-ex/contracts/src/transformers/PayTakerTransformer.sol index 7fdb2a949d..dad74f7355 100644 --- a/contracts/zero-ex/contracts/src/transformers/PayTakerTransformer.sol +++ b/contracts/zero-ex/contracts/src/transformers/PayTakerTransformer.sol @@ -28,11 +28,8 @@ import "../errors/LibTransformERC20RichErrors.sol"; import "./Transformer.sol"; import "./LibERC20Transformer.sol"; - /// @dev A transformer that transfers tokens to the taker. -contract PayTakerTransformer is - Transformer -{ +contract PayTakerTransformer is Transformer { // solhint-disable no-empty-blocks using LibRichErrorsV06 for bytes; using LibSafeMathV06 for uint256; @@ -51,19 +48,12 @@ contract PayTakerTransformer is uint256 private constant MAX_UINT256 = uint256(-1); /// @dev Create this contract. - constructor() - public - Transformer() - {} + constructor() public Transformer() {} /// @dev Forwards tokens to the taker. /// @param context Context information. /// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`). - function transform(TransformContext calldata context) - external - override - returns (bytes4 success) - { + function transform(TransformContext calldata context) external override returns (bytes4 success) { TransformData memory data = abi.decode(context.data, (TransformData)); // Transfer tokens directly to the taker. diff --git a/contracts/zero-ex/contracts/src/transformers/PositiveSlippageFeeTransformer.sol b/contracts/zero-ex/contracts/src/transformers/PositiveSlippageFeeTransformer.sol index 9ab087754b..9cc1eff74d 100644 --- a/contracts/zero-ex/contracts/src/transformers/PositiveSlippageFeeTransformer.sol +++ b/contracts/zero-ex/contracts/src/transformers/PositiveSlippageFeeTransformer.sol @@ -28,11 +28,8 @@ import "../errors/LibTransformERC20RichErrors.sol"; import "./Transformer.sol"; import "./LibERC20Transformer.sol"; - /// @dev A transformer that transfers tokens to arbitrary addresses. -contract PositiveSlippageFeeTransformer is - Transformer -{ +contract PositiveSlippageFeeTransformer is Transformer { using LibRichErrorsV06 for bytes; using LibSafeMathV06 for uint256; using LibERC20Transformer for IERC20TokenV06; @@ -50,11 +47,7 @@ contract PositiveSlippageFeeTransformer is /// @dev Transfers tokens to recipients. /// @param context Context information. /// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`). - function transform(TransformContext calldata context) - external - override - returns (bytes4 success) - { + function transform(TransformContext calldata context) external override returns (bytes4 success) { TokenFee memory fee = abi.decode(context.data, (TokenFee)); uint256 transformerAmount = LibERC20Transformer.getTokenBalanceOf(fee.token, address(this)); diff --git a/contracts/zero-ex/contracts/src/transformers/Transformer.sol b/contracts/zero-ex/contracts/src/transformers/Transformer.sol index 52a8c671a6..4ea65da9bc 100644 --- a/contracts/zero-ex/contracts/src/transformers/Transformer.sol +++ b/contracts/zero-ex/contracts/src/transformers/Transformer.sol @@ -24,11 +24,8 @@ import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../errors/LibTransformERC20RichErrors.sol"; import "./IERC20Transformer.sol"; - /// @dev Abstract base class for transformers. -abstract contract Transformer is - IERC20Transformer -{ +abstract contract Transformer is IERC20Transformer { using LibRichErrorsV06 for bytes; /// @dev The address of the deployer. @@ -45,21 +42,14 @@ abstract contract Transformer is /// @dev Destruct this contract. Only callable by the deployer and will not /// succeed in the context of a delegatecall (from another contract). /// @param ethRecipient The recipient of ETH held in this contract. - function die(address payable ethRecipient) - external - virtual - { + function die(address payable ethRecipient) external virtual { // Only the deployer can call this. if (msg.sender != deployer) { - LibTransformERC20RichErrors - .OnlyCallableByDeployerError(msg.sender, deployer) - .rrevert(); + LibTransformERC20RichErrors.OnlyCallableByDeployerError(msg.sender, deployer).rrevert(); } // Must be executing our own context. if (address(this) != _implementation) { - LibTransformERC20RichErrors - .InvalidExecutionContextError(address(this), _implementation) - .rrevert(); + LibTransformERC20RichErrors.InvalidExecutionContextError(address(this), _implementation).rrevert(); } selfdestruct(ethRecipient); } diff --git a/contracts/zero-ex/contracts/src/transformers/WethTransformer.sol b/contracts/zero-ex/contracts/src/transformers/WethTransformer.sol index b27b671557..8066f9c26e 100644 --- a/contracts/zero-ex/contracts/src/transformers/WethTransformer.sol +++ b/contracts/zero-ex/contracts/src/transformers/WethTransformer.sol @@ -27,11 +27,8 @@ import "../errors/LibTransformERC20RichErrors.sol"; import "./Transformer.sol"; import "./LibERC20Transformer.sol"; - /// @dev A transformer that wraps or unwraps WETH. -contract WethTransformer is - Transformer -{ +contract WethTransformer is Transformer { using LibRichErrorsV06 for bytes; using LibSafeMathV06 for uint256; using LibERC20Transformer for IERC20TokenV06; @@ -52,27 +49,22 @@ contract WethTransformer is /// @dev Construct the transformer and store the WETH address in an immutable. /// @param weth_ The weth token. - constructor(IEtherTokenV06 weth_) - public - Transformer() - { + constructor(IEtherTokenV06 weth_) public Transformer() { weth = weth_; } /// @dev Wraps and unwraps WETH. /// @param context Context information. /// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`). - function transform(TransformContext calldata context) - external - override - returns (bytes4 success) - { + function transform(TransformContext calldata context) external override returns (bytes4 success) { TransformData memory data = abi.decode(context.data, (TransformData)); if (!data.token.isTokenETH() && data.token != weth) { - LibTransformERC20RichErrors.InvalidTransformDataError( - LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_TOKENS, - context.data - ).rrevert(); + LibTransformERC20RichErrors + .InvalidTransformDataError( + LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_TOKENS, + context.data + ) + .rrevert(); } uint256 amount = data.amount; diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/AbstractBridgeAdapter.sol b/contracts/zero-ex/contracts/src/transformers/bridges/AbstractBridgeAdapter.sol index 6e1f6d6317..fc302c9e56 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/AbstractBridgeAdapter.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/AbstractBridgeAdapter.sol @@ -23,37 +23,23 @@ pragma experimental ABIEncoderV2; import "./IBridgeAdapter.sol"; abstract contract AbstractBridgeAdapter is IBridgeAdapter { - - constructor( - uint256 expectedChainId, - string memory expectedChainName - ) - public - { + constructor(uint256 expectedChainId, string memory expectedChainName) public { uint256 chainId; - assembly { chainId := chainid() } + assembly { + chainId := chainid() + } // Allow testing on Ganache if (chainId != expectedChainId && chainId != 1337) { revert(string(abi.encodePacked(expectedChainName, "BridgeAdapter.constructor: wrong chain ID"))); } } - function isSupportedSource(bytes32 source) - external - override - returns (bool isSupported) - { + function isSupportedSource(bytes32 source) external override returns (bool isSupported) { BridgeOrder memory placeholderOrder; placeholderOrder.source = source; IERC20TokenV06 placeholderToken = IERC20TokenV06(address(0)); - - (, isSupported) = _trade( - placeholderOrder, - placeholderToken, - placeholderToken, - 0, - true - ); + + (, isSupported) = _trade(placeholderOrder, placeholderToken, placeholderToken, 0, true); } function trade( @@ -61,18 +47,8 @@ abstract contract AbstractBridgeAdapter is IBridgeAdapter { IERC20TokenV06 sellToken, IERC20TokenV06 buyToken, uint256 sellAmount - ) - public - override - returns (uint256 boughtAmount) - { - (boughtAmount, ) = _trade( - order, - sellToken, - buyToken, - sellAmount, - false - ); + ) public override returns (uint256 boughtAmount) { + (boughtAmount, ) = _trade(order, sellToken, buyToken, sellAmount, false); } function _trade( @@ -81,8 +57,5 @@ abstract contract AbstractBridgeAdapter is IBridgeAdapter { IERC20TokenV06 buyToken, uint256 sellAmount, bool dryRun - ) - internal - virtual - returns (uint256 boughtAmount, bool supportedSource); + ) internal virtual returns (uint256 boughtAmount, bool supportedSource); } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/ArbitrumBridgeAdapter.sol b/contracts/zero-ex/contracts/src/transformers/bridges/ArbitrumBridgeAdapter.sol index e60c17820e..e0747bd6b8 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/ArbitrumBridgeAdapter.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/ArbitrumBridgeAdapter.sol @@ -48,10 +48,7 @@ contract ArbitrumBridgeAdapter is MixinUniswapV2, MixinZeroExBridge { - constructor(IEtherTokenV06 weth) - public - MixinCurve(weth) - {} + constructor(IEtherTokenV06 weth) public MixinCurve(weth) {} function _trade( BridgeOrder memory order, @@ -59,100 +56,65 @@ contract ArbitrumBridgeAdapter is IERC20TokenV06 buyToken, uint256 sellAmount, bool dryRun - ) - internal - override - returns (uint256 boughtAmount, bool supportedSource) - { + ) internal override returns (uint256 boughtAmount, bool supportedSource) { uint128 protocolId = uint128(uint256(order.source) >> 128); if (protocolId == BridgeProtocols.BALANCERV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeBalancerV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeBalancerV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.BALANCERV2BATCH) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeBalancerV2Batch( - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeBalancerV2Batch(sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.CURVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCurve( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCurve(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.CURVEV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCurveV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCurveV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.DODOV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeDodoV2( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeDodoV2(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.KYBERDMM) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeKyberDmm( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeKyberDmm(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNISWAPV3) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeUniswapV3( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeUniswapV3(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNISWAPV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeUniswapV2( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeUniswapV2(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.GMX) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeGMX( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeGMX(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.NERVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeNerve( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeNerve(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNKNOWN) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeZeroExBridge( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeZeroExBridge(sellToken, buyToken, sellAmount, order.bridgeData); } - emit BridgeFill( - order.source, - sellToken, - buyToken, - sellAmount, - boughtAmount - ); + emit BridgeFill(order.source, sellToken, buyToken, sellAmount, boughtAmount); } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/AvalancheBridgeAdapter.sol b/contracts/zero-ex/contracts/src/transformers/bridges/AvalancheBridgeAdapter.sol index 26f1d45013..c48a5dddaa 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/AvalancheBridgeAdapter.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/AvalancheBridgeAdapter.sol @@ -46,10 +46,7 @@ contract AvalancheBridgeAdapter is MixinWOOFi, MixinZeroExBridge { - constructor(IEtherTokenV06 weth) - public - MixinCurve(weth) - {} + constructor(IEtherTokenV06 weth) public MixinCurve(weth) {} function _trade( BridgeOrder memory order, @@ -57,95 +54,60 @@ contract AvalancheBridgeAdapter is IERC20TokenV06 buyToken, uint256 sellAmount, bool dryRun - ) - internal - override - returns (uint256 boughtAmount, bool supportedSource) - { + ) internal override returns (uint256 boughtAmount, bool supportedSource) { uint128 protocolId = uint128(uint256(order.source) >> 128); if (protocolId == BridgeProtocols.CURVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCurve( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCurve(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.CURVEV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCurveV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCurveV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNISWAPV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeUniswapV2( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeUniswapV2(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.NERVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeNerve( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeNerve(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.KYBERDMM) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeKyberDmm( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeKyberDmm(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.AAVEV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeAaveV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeAaveV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.GMX) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeGMX( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeGMX(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.PLATYPUS) { - if (dryRun) { return (0, true); } - boughtAmount = _tradePlatypus( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradePlatypus(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.WOOFI) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeWOOFi( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeWOOFi(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNKNOWN) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeZeroExBridge( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeZeroExBridge(sellToken, buyToken, sellAmount, order.bridgeData); } - emit BridgeFill( - order.source, - sellToken, - buyToken, - sellAmount, - boughtAmount - ); + emit BridgeFill(order.source, sellToken, buyToken, sellAmount, boughtAmount); } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/BSCBridgeAdapter.sol b/contracts/zero-ex/contracts/src/transformers/bridges/BSCBridgeAdapter.sol index acec88e5a4..315e97bcdc 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/BSCBridgeAdapter.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/BSCBridgeAdapter.sol @@ -44,11 +44,7 @@ contract BSCBridgeAdapter is MixinWOOFi, MixinZeroExBridge { - constructor(IEtherTokenV06 weth) - public - MixinCurve(weth) - MixinMooniswap(weth) - {} + constructor(IEtherTokenV06 weth) public MixinCurve(weth) MixinMooniswap(weth) {} function _trade( BridgeOrder memory order, @@ -56,87 +52,55 @@ contract BSCBridgeAdapter is IERC20TokenV06 buyToken, uint256 sellAmount, bool dryRun - ) - internal - override - returns (uint256 boughtAmount, bool supportedSource) - { + ) internal override returns (uint256 boughtAmount, bool supportedSource) { uint128 protocolId = uint128(uint256(order.source) >> 128); if (protocolId == BridgeProtocols.CURVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCurve( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCurve(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNISWAPV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeUniswapV2( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeUniswapV2(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.MOONISWAP) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeMooniswap( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeMooniswap(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.DODO) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeDodo( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeDodo(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.DODOV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeDodoV2( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeDodoV2(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.NERVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeNerve( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeNerve(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.KYBERDMM) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeKyberDmm( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeKyberDmm(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.WOOFI) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeWOOFi( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeWOOFi(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNKNOWN) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeZeroExBridge( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeZeroExBridge(sellToken, buyToken, sellAmount, order.bridgeData); } - emit BridgeFill( - order.source, - sellToken, - buyToken, - sellAmount, - boughtAmount - ); + emit BridgeFill(order.source, sellToken, buyToken, sellAmount, boughtAmount); } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/BridgeProtocols.sol b/contracts/zero-ex/contracts/src/transformers/bridges/BridgeProtocols.sol index 289906e7e4..61b1a6724c 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/BridgeProtocols.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/BridgeProtocols.sol @@ -22,41 +22,40 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; - library BridgeProtocols { // A incrementally increasing, append-only list of protocol IDs. // We don't use an enum so solidity doesn't throw when we pass in a // new protocol ID that hasn't been rolled up yet. - uint128 internal constant UNKNOWN = 0; - uint128 internal constant CURVE = 1; - uint128 internal constant UNISWAPV2 = 2; - uint128 internal constant UNISWAP = 3; - uint128 internal constant BALANCER = 4; - uint128 internal constant KYBER = 5; // Not used: deprecated. - uint128 internal constant MOONISWAP = 6; - uint128 internal constant MSTABLE = 7; - uint128 internal constant OASIS = 8; // Not used: deprecated. - uint128 internal constant SHELL = 9; - uint128 internal constant DODO = 10; - uint128 internal constant DODOV2 = 11; - uint128 internal constant CRYPTOCOM = 12; - uint128 internal constant BANCOR = 13; - uint128 internal constant COFIX = 14; // Not used: deprecated. - uint128 internal constant NERVE = 15; - uint128 internal constant MAKERPSM = 16; - uint128 internal constant BALANCERV2 = 17; - uint128 internal constant UNISWAPV3 = 18; - uint128 internal constant KYBERDMM = 19; - uint128 internal constant CURVEV2 = 20; - uint128 internal constant LIDO = 21; - uint128 internal constant CLIPPER = 22; // Not used: Clipper is now using PLP interface - uint128 internal constant AAVEV2 = 23; - uint128 internal constant COMPOUND = 24; + uint128 internal constant UNKNOWN = 0; + uint128 internal constant CURVE = 1; + uint128 internal constant UNISWAPV2 = 2; + uint128 internal constant UNISWAP = 3; + uint128 internal constant BALANCER = 4; + uint128 internal constant KYBER = 5; // Not used: deprecated. + uint128 internal constant MOONISWAP = 6; + uint128 internal constant MSTABLE = 7; + uint128 internal constant OASIS = 8; // Not used: deprecated. + uint128 internal constant SHELL = 9; + uint128 internal constant DODO = 10; + uint128 internal constant DODOV2 = 11; + uint128 internal constant CRYPTOCOM = 12; + uint128 internal constant BANCOR = 13; + uint128 internal constant COFIX = 14; // Not used: deprecated. + uint128 internal constant NERVE = 15; + uint128 internal constant MAKERPSM = 16; + uint128 internal constant BALANCERV2 = 17; + uint128 internal constant UNISWAPV3 = 18; + uint128 internal constant KYBERDMM = 19; + uint128 internal constant CURVEV2 = 20; + uint128 internal constant LIDO = 21; + uint128 internal constant CLIPPER = 22; // Not used: Clipper is now using PLP interface + uint128 internal constant AAVEV2 = 23; + uint128 internal constant COMPOUND = 24; uint128 internal constant BALANCERV2BATCH = 25; - uint128 internal constant GMX = 26; - uint128 internal constant PLATYPUS = 27; - uint128 internal constant BANCORV3 = 28; - uint128 internal constant VELODROME = 29; - uint128 internal constant SYNTHETIX = 30; - uint128 internal constant WOOFI = 31; + uint128 internal constant GMX = 26; + uint128 internal constant PLATYPUS = 27; + uint128 internal constant BANCORV3 = 28; + uint128 internal constant VELODROME = 29; + uint128 internal constant SYNTHETIX = 30; + uint128 internal constant WOOFI = 31; } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/CeloBridgeAdapter.sol b/contracts/zero-ex/contracts/src/transformers/bridges/CeloBridgeAdapter.sol index 9ef4003af3..38e84366a9 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/CeloBridgeAdapter.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/CeloBridgeAdapter.sol @@ -1,4 +1,3 @@ - // SPDX-License-Identifier: Apache-2.0 /* @@ -27,15 +26,8 @@ import "./mixins/MixinNerve.sol"; import "./mixins/MixinUniswapV2.sol"; import "./mixins/MixinZeroExBridge.sol"; -contract CeloBridgeAdapter is - AbstractBridgeAdapter(42220, "Celo"), - MixinNerve, - MixinUniswapV2, - MixinZeroExBridge -{ - constructor(address _weth) - public - {} +contract CeloBridgeAdapter is AbstractBridgeAdapter(42220, "Celo"), MixinNerve, MixinUniswapV2, MixinZeroExBridge { + constructor(address _weth) public {} function _trade( BridgeOrder memory order, @@ -43,42 +35,25 @@ contract CeloBridgeAdapter is IERC20TokenV06 buyToken, uint256 sellAmount, bool dryRun - ) - internal - override - returns (uint256 boughtAmount, bool supportedSource) - { + ) internal override returns (uint256 boughtAmount, bool supportedSource) { uint128 protocolId = uint128(uint256(order.source) >> 128); if (protocolId == BridgeProtocols.UNISWAPV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeUniswapV2( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeUniswapV2(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.NERVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeNerve( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeNerve(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNKNOWN) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeZeroExBridge( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeZeroExBridge(sellToken, buyToken, sellAmount, order.bridgeData); } - emit BridgeFill( - order.source, - sellToken, - buyToken, - sellAmount, - boughtAmount - ); + emit BridgeFill(order.source, sellToken, buyToken, sellAmount, boughtAmount); } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/EthereumBridgeAdapter.sol b/contracts/zero-ex/contracts/src/transformers/bridges/EthereumBridgeAdapter.sol index bede6d327a..eda3b03c46 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/EthereumBridgeAdapter.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/EthereumBridgeAdapter.sol @@ -88,191 +88,125 @@ contract EthereumBridgeAdapter is IERC20TokenV06 buyToken, uint256 sellAmount, bool dryRun - ) - internal - override - returns (uint256 boughtAmount, bool supportedSource) - { + ) internal override returns (uint256 boughtAmount, bool supportedSource) { uint128 protocolId = uint128(uint256(order.source) >> 128); if (protocolId == BridgeProtocols.CURVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCurve( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCurve(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.CURVEV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCurveV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCurveV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNISWAPV3) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeUniswapV3( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeUniswapV3(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNISWAPV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeUniswapV2( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeUniswapV2(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNISWAP) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeUniswap( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeUniswap(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.BALANCER) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeBalancer( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeBalancer(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.BALANCERV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeBalancerV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeBalancerV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.BALANCERV2BATCH) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeBalancerV2Batch( - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeBalancerV2Batch(sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.MAKERPSM) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeMakerPsm( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeMakerPsm(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.MSTABLE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeMStable( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeMStable(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.SHELL) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeShell( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeShell(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.DODO) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeDodo( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeDodo(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.DODOV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeDodoV2( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeDodoV2(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.CRYPTOCOM) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCryptoCom( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCryptoCom(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.BANCOR) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeBancor( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeBancor(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.NERVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeNerve( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeNerve(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.KYBERDMM) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeKyberDmm( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeKyberDmm(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.LIDO) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeLido( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeLido(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.AAVEV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeAaveV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeAaveV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.COMPOUND) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCompound( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCompound(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.BANCORV3) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeBancorV3( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeBancorV3(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.SYNTHETIX) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeSynthetix( - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeSynthetix(sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNKNOWN) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeZeroExBridge( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeZeroExBridge(sellToken, buyToken, sellAmount, order.bridgeData); } - emit BridgeFill( - order.source, - sellToken, - buyToken, - sellAmount, - boughtAmount - ); + emit BridgeFill(order.source, sellToken, buyToken, sellAmount, boughtAmount); } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/FantomBridgeAdapter.sol b/contracts/zero-ex/contracts/src/transformers/bridges/FantomBridgeAdapter.sol index 6e3edf43f7..dda23a9733 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/FantomBridgeAdapter.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/FantomBridgeAdapter.sol @@ -42,10 +42,7 @@ contract FantomBridgeAdapter is MixinWOOFi, MixinZeroExBridge { - constructor(IEtherTokenV06 weth) - public - MixinCurve(weth) - {} + constructor(IEtherTokenV06 weth) public MixinCurve(weth) {} function _trade( BridgeOrder memory order, @@ -53,82 +50,50 @@ contract FantomBridgeAdapter is IERC20TokenV06 buyToken, uint256 sellAmount, bool dryRun - ) - internal - override - returns (uint256 boughtAmount, bool supportedSource) - { + ) internal override returns (uint256 boughtAmount, bool supportedSource) { uint128 protocolId = uint128(uint256(order.source) >> 128); if (protocolId == BridgeProtocols.CURVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCurve( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCurve(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.CURVEV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCurveV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCurveV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNISWAPV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeUniswapV2( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeUniswapV2(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.BALANCERV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeBalancerV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeBalancerV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.NERVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeNerve( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeNerve(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.AAVEV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeAaveV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeAaveV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.WOOFI) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeWOOFi( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeWOOFi(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNKNOWN) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeZeroExBridge( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeZeroExBridge(sellToken, buyToken, sellAmount, order.bridgeData); } - emit BridgeFill( - order.source, - sellToken, - buyToken, - sellAmount, - boughtAmount - ); + emit BridgeFill(order.source, sellToken, buyToken, sellAmount, boughtAmount); } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/IBridgeAdapter.sol b/contracts/zero-ex/contracts/src/transformers/bridges/IBridgeAdapter.sol index b95a408e7e..a99827959b 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/IBridgeAdapter.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/IBridgeAdapter.sol @@ -22,9 +22,7 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; - interface IBridgeAdapter { - struct BridgeOrder { // Upper 16 bytes: uint128 protocol ID (right-aligned) // Lower 16 bytes: ASCII source name (left-aligned) @@ -50,16 +48,12 @@ interface IBridgeAdapter { uint256 outputTokenAmount ); - function isSupportedSource(bytes32 source) - external - returns (bool isSupported); + function isSupportedSource(bytes32 source) external returns (bool isSupported); function trade( BridgeOrder calldata order, IERC20TokenV06 sellToken, IERC20TokenV06 buyToken, uint256 sellAmount - ) - external - returns (uint256 boughtAmount); + ) external returns (uint256 boughtAmount); } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/OptimismBridgeAdapter.sol b/contracts/zero-ex/contracts/src/transformers/bridges/OptimismBridgeAdapter.sol index 15e62b1228..49285acad4 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/OptimismBridgeAdapter.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/OptimismBridgeAdapter.sol @@ -1,20 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 /* - Copyright 2022 ZeroEx Intl. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - */ pragma solidity ^0.6.5; @@ -44,10 +39,7 @@ contract OptimismBridgeAdapter is MixinVelodrome, MixinZeroExBridge { - constructor(IEtherTokenV06 weth) - public - MixinCurve(weth) - {} + constructor(IEtherTokenV06 weth) public MixinCurve(weth) {} function _trade( BridgeOrder memory order, @@ -55,86 +47,55 @@ contract OptimismBridgeAdapter is IERC20TokenV06 buyToken, uint256 sellAmount, bool dryRun - ) - internal - override - returns (uint256 boughtAmount, bool supportedSource) - { + ) internal override returns (uint256 boughtAmount, bool supportedSource) { uint128 protocolId = uint128(uint256(order.source) >> 128); if (protocolId == BridgeProtocols.CURVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCurve( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCurve(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.CURVEV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCurveV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCurveV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNISWAPV3) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeUniswapV3( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeUniswapV3(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.NERVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeNerve( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeNerve(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.VELODROME) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeVelodrome( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeVelodrome(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.SYNTHETIX) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeSynthetix( - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeSynthetix(sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNKNOWN) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeZeroExBridge( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); - }else if (protocolId == BridgeProtocols.BALANCERV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeBalancerV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeZeroExBridge(sellToken, buyToken, sellAmount, order.bridgeData); + } else if (protocolId == BridgeProtocols.BALANCERV2) { + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeBalancerV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.BALANCERV2BATCH) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeBalancerV2Batch( - sellAmount, - order.bridgeData - ); - } + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeBalancerV2Batch(sellAmount, order.bridgeData); + } - emit BridgeFill( - order.source, - sellToken, - buyToken, - sellAmount, - boughtAmount - ); + emit BridgeFill(order.source, sellToken, buyToken, sellAmount, boughtAmount); } -} \ No newline at end of file +} diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/PolygonBridgeAdapter.sol b/contracts/zero-ex/contracts/src/transformers/bridges/PolygonBridgeAdapter.sol index 7b7f945c7f..0ac4424407 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/PolygonBridgeAdapter.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/PolygonBridgeAdapter.sol @@ -54,10 +54,7 @@ contract PolygonBridgeAdapter is MixinWOOFi, MixinZeroExBridge { - constructor(IEtherTokenV06 weth) - public - MixinCurve(weth) - {} + constructor(IEtherTokenV06 weth) public MixinCurve(weth) {} function _trade( BridgeOrder memory order, @@ -65,124 +62,80 @@ contract PolygonBridgeAdapter is IERC20TokenV06 buyToken, uint256 sellAmount, bool dryRun - ) - internal - override - returns (uint256 boughtAmount, bool supportedSource) - { + ) internal override returns (uint256 boughtAmount, bool supportedSource) { uint128 protocolId = uint128(uint256(order.source) >> 128); if (protocolId == BridgeProtocols.CURVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCurve( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCurve(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.CURVEV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeCurveV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeCurveV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNISWAPV3) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeUniswapV3( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeUniswapV3(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNISWAPV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeUniswapV2( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeUniswapV2(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.BALANCERV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeBalancerV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeBalancerV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.BALANCERV2BATCH) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeBalancerV2Batch( - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeBalancerV2Batch(sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.MSTABLE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeMStable( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeMStable(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.DODO) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeDodo( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeDodo(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.DODOV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeDodoV2( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeDodoV2(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.NERVE) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeNerve( - sellToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeNerve(sellToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.KYBERDMM) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeKyberDmm( - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeKyberDmm(buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.AAVEV2) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeAaveV2( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeAaveV2(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.WOOFI) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeWOOFi( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeWOOFi(sellToken, buyToken, sellAmount, order.bridgeData); } else if (protocolId == BridgeProtocols.UNKNOWN) { - if (dryRun) { return (0, true); } - boughtAmount = _tradeZeroExBridge( - sellToken, - buyToken, - sellAmount, - order.bridgeData - ); + if (dryRun) { + return (0, true); + } + boughtAmount = _tradeZeroExBridge(sellToken, buyToken, sellAmount, order.bridgeData); } - emit BridgeFill( - order.source, - sellToken, - buyToken, - sellAmount, - boughtAmount - ); + emit BridgeFill(order.source, sellToken, buyToken, sellAmount, boughtAmount); } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinAaveV2.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinAaveV2.sol index ad0c51c75b..80c4b3a1a9 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinAaveV2.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinAaveV2.sol @@ -26,39 +26,39 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; // Minimal Aave V2 LendingPool interface interface ILendingPool { /** - * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. - * - E.g. User deposits 100 USDC and gets in return 100 aUSDC - * @param asset The address of the underlying asset to deposit - * @param amount The amount to be deposited - * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user - * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens - * is a different wallet - * @param referralCode Code used to register the integrator originating the operation, for potential rewards. - * 0 if the action is executed directly by the user, without any middle-man - **/ - function deposit( - address asset, - uint256 amount, - address onBehalfOf, - uint16 referralCode - ) external; + * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. + * - E.g. User deposits 100 USDC and gets in return 100 aUSDC + * @param asset The address of the underlying asset to deposit + * @param amount The amount to be deposited + * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user + * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens + * is a different wallet + * @param referralCode Code used to register the integrator originating the operation, for potential rewards. + * 0 if the action is executed directly by the user, without any middle-man + **/ + function deposit( + address asset, + uint256 amount, + address onBehalfOf, + uint16 referralCode + ) external; - /** - * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned - * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC - * @param asset The address of the underlying asset to withdraw - * @param amount The underlying amount to be withdrawn - * - Send the value type(uint256).max in order to withdraw the whole aToken balance - * @param to Address that will receive the underlying, same as msg.sender if the user - * wants to receive it on his own wallet, or a different address if the beneficiary is a - * different wallet - * @return The final amount withdrawn - **/ - function withdraw( - address asset, - uint256 amount, - address to - ) external returns (uint256); + /** + * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned + * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC + * @param asset The address of the underlying asset to withdraw + * @param amount The underlying amount to be withdrawn + * - Send the value type(uint256).max in order to withdraw the whole aToken balance + * @param to Address that will receive the underlying, same as msg.sender if the user + * wants to receive it on his own wallet, or a different address if the beneficiary is a + * different wallet + * @return The final amount withdrawn + **/ + function withdraw( + address asset, + uint256 amount, + address to + ) external returns (uint256); } contract MixinAaveV2 { @@ -69,16 +69,10 @@ contract MixinAaveV2 { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256) - { + ) internal returns (uint256) { (ILendingPool lendingPool, address aToken) = abi.decode(bridgeData, (ILendingPool, address)); - sellToken.approveIfBelow( - address(lendingPool), - sellAmount - ); + sellToken.approveIfBelow(address(lendingPool), sellAmount); if (address(buyToken) == aToken) { lendingPool.deposit(address(sellToken), sellAmount, address(this), 0); diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBalancer.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBalancer.sol index f404f5298e..b751c945f0 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBalancer.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBalancer.sol @@ -34,15 +34,14 @@ interface IBalancerPool { /// token pair for this pool. function swapExactAmountIn( IERC20TokenV06 tokenIn, - uint tokenAmountIn, + uint256 tokenAmountIn, IERC20TokenV06 tokenOut, - uint minAmountOut, - uint maxPrice - ) external returns (uint tokenAmountOut, uint spotPriceAfter); + uint256 minAmountOut, + uint256 maxPrice + ) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter); } contract MixinBalancer { - using LibERC20TokenV06 for IERC20TokenV06; function _tradeBalancer( @@ -50,25 +49,16 @@ contract MixinBalancer { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { + ) internal returns (uint256 boughtAmount) { // Decode the bridge data. - (IBalancerPool pool) = abi.decode( - bridgeData, - (IBalancerPool) - ); - sellToken.approveIfBelow( - address(pool), - sellAmount - ); + IBalancerPool pool = abi.decode(bridgeData, (IBalancerPool)); + sellToken.approveIfBelow(address(pool), sellAmount); // Sell all of this contract's `sellToken` token balance. - (boughtAmount,) = pool.swapExactAmountIn( - sellToken, // tokenIn + (boughtAmount, ) = pool.swapExactAmountIn( + sellToken, // tokenIn sellAmount, // tokenAmountIn - buyToken, // tokenOut - 1, // minAmountOut + buyToken, // tokenOut + 1, // minAmountOut uint256(-1) // maxPrice ); return boughtAmount; diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBalancerV2.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBalancerV2.sol index 599d3c0a7c..4f8319ae24 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBalancerV2.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBalancerV2.sol @@ -23,10 +23,12 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; - interface IBalancerV2Vault { + enum SwapKind { + GIVEN_IN, + GIVEN_OUT + } - enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * @@ -66,7 +68,6 @@ interface IBalancerV2Vault { } contract MixinBalancerV2 { - using LibERC20TokenV06 for IERC20TokenV06; struct BalancerV2BridgeData { @@ -79,10 +80,7 @@ contract MixinBalancerV2 { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { + ) internal returns (uint256 boughtAmount) { // Decode the bridge data. BalancerV2BridgeData memory data = abi.decode(bridgeData, (BalancerV2BridgeData)); diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBalancerV2Batch.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBalancerV2Batch.sol index ab6e293928..b9530bbfda 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBalancerV2Batch.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBalancerV2Batch.sol @@ -23,10 +23,11 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; - interface IBalancerV2BatchSwapVault { - - enum SwapKind { GIVEN_IN, GIVEN_OUT } + enum SwapKind { + GIVEN_IN, + GIVEN_OUT + } struct BatchSwapStep { bytes32 poolId; @@ -54,7 +55,6 @@ interface IBalancerV2BatchSwapVault { } contract MixinBalancerV2Batch { - using LibERC20TokenV06 for IERC20TokenV06; struct BalancerV2BatchBridgeData { @@ -63,10 +63,7 @@ contract MixinBalancerV2Batch { IERC20TokenV06[] assets; } - function _tradeBalancerV2Batch( - uint256 sellAmount, - bytes memory bridgeData - ) + function _tradeBalancerV2Batch(uint256 sellAmount, bytes memory bridgeData) internal returns (uint256 boughtAmount) { @@ -77,7 +74,9 @@ contract MixinBalancerV2Batch { address[] memory assets_ ) = abi.decode(bridgeData, (IBalancerV2BatchSwapVault, IBalancerV2BatchSwapVault.BatchSwapStep[], address[])); IERC20TokenV06[] memory assets; - assembly { assets := assets_ } + assembly { + assets := assets_ + } // Grant an allowance to the exchange to spend `fromTokenAddress` token. assets[0].approveIfBelow(address(vault), sellAmount); @@ -101,7 +100,7 @@ contract MixinBalancerV2Batch { limits, block.timestamp + 1 ); - require(amounts[amounts.length - 1] <= 0, 'Unexpected BalancerV2Batch output'); + require(amounts[amounts.length - 1] <= 0, "Unexpected BalancerV2Batch output"); return uint256(amounts[amounts.length - 1] * -1); } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBancor.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBancor.sol index 8c85611be2..8d0c60a40b 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBancor.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBancor.sol @@ -26,7 +26,6 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol"; import "../IBridgeAdapter.sol"; - interface IBancorNetwork { function convertByPath( IERC20TokenV06[] calldata _path, @@ -35,23 +34,15 @@ interface IBancorNetwork { address _beneficiary, address _affiliateAccount, uint256 _affiliateFee - ) - external - payable - returns (uint256); + ) external payable returns (uint256); } - contract MixinBancor { - /// @dev Bancor ETH pseudo-address. - IERC20TokenV06 constant public BANCOR_ETH_ADDRESS = - IERC20TokenV06(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); + IERC20TokenV06 public constant BANCOR_ETH_ADDRESS = IERC20TokenV06(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IEtherTokenV06 private immutable WETH; - constructor(IEtherTokenV06 weth) - public - { + constructor(IEtherTokenV06 weth) public { WETH = weth; } @@ -59,27 +50,22 @@ contract MixinBancor { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { + ) internal returns (uint256 boughtAmount) { // Decode the bridge data. IBancorNetwork bancorNetworkAddress; IERC20TokenV06[] memory path; { address[] memory _path; - ( - bancorNetworkAddress, - _path - ) = abi.decode(bridgeData, (IBancorNetwork, address[])); + (bancorNetworkAddress, _path) = abi.decode(bridgeData, (IBancorNetwork, address[])); // To get around `abi.decode()` not supporting interface array types. - assembly { path := _path } + assembly { + path := _path + } } require(path.length >= 2, "MixinBancor/PATH_LENGTH_MUST_BE_AT_LEAST_TWO"); require( - path[path.length - 1] == buyToken || - (path[path.length - 1] == BANCOR_ETH_ADDRESS && buyToken == WETH), + path[path.length - 1] == buyToken || (path[path.length - 1] == BANCOR_ETH_ADDRESS && buyToken == WETH), "MixinBancor/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN" ); @@ -92,11 +78,7 @@ contract MixinBancor { payableAmount = sellAmount; } else { // Grant an allowance to the Bancor Network. - LibERC20TokenV06.approveIfBelow( - path[0], - address(bancorNetworkAddress), - sellAmount - ); + LibERC20TokenV06.approveIfBelow(path[0], address(bancorNetworkAddress), sellAmount); } // Convert the tokens diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBancorV3.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBancorV3.sol index 8cf92d54de..0ec1a3ea10 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBancorV3.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinBancorV3.sol @@ -25,7 +25,6 @@ import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol"; - /* BancorV3 */ @@ -48,16 +47,12 @@ interface IBancorV3 { } contract MixinBancorV3 { - using LibERC20TokenV06 for IERC20TokenV06; - IERC20TokenV06 constant public BANCORV3_ETH_ADDRESS = - IERC20TokenV06(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); + IERC20TokenV06 public constant BANCORV3_ETH_ADDRESS = IERC20TokenV06(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IEtherTokenV06 private immutable WETH; - constructor(IEtherTokenV06 weth) - public - { + constructor(IEtherTokenV06 weth) public { WETH = weth; } @@ -65,11 +60,7 @@ contract MixinBancorV3 { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 amountOut) - - { + ) internal returns (uint256 amountOut) { IBancorV3 router; IERC20TokenV06[] memory path; address[] memory _path; @@ -78,17 +69,16 @@ contract MixinBancorV3 { { (router, _path) = abi.decode(bridgeData, (IBancorV3, address[])); // To get around `abi.decode()` not supporting interface array types. - assembly { path := _path } + assembly { + path := _path + } } require(path.length >= 2, "MixinBancorV3/PATH_LENGTH_MUST_BE_AT_LEAST_TWO"); - require( - path[path.length - 1] == buyToken, - "MixinBancorV3/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN" - ); + require(path[path.length - 1] == buyToken, "MixinBancorV3/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN"); //swap WETH->ETH as Bancor only deals in ETH - if(_path[0] == address(WETH)) { + if (_path[0] == address(WETH)) { //withdraw the sell amount of WETH for ETH WETH.withdraw(sellAmount); payableAmount = sellAmount; @@ -100,17 +90,16 @@ contract MixinBancorV3 { } // if we are buying WETH we need to swap to ETH and deposit into WETH after the swap - if(_path[1] == address(WETH)){ + if (_path[1] == address(WETH)) { _path[1] = address(BANCORV3_ETH_ADDRESS); } - uint256 amountOut = router.tradeBySourceAmount{value: payableAmount}( _path[0], _path[1], - // Sell all tokens we hold. + // Sell all tokens we hold. sellAmount, - // Minimum buy amount. + // Minimum buy amount. 1, //deadline block.timestamp + 1, @@ -119,10 +108,10 @@ contract MixinBancorV3 { ); // if we want to return WETH deposit the ETH amount we sold - if(buyToken == WETH){ + if (buyToken == WETH) { WETH.deposit{value: amountOut}(); } return amountOut; } -} \ No newline at end of file +} diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCompound.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCompound.sol index 5adfb1abf9..c7423a2d0b 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCompound.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCompound.sol @@ -25,22 +25,24 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; - /// @dev Minimal CToken interface interface ICToken { /// @dev deposits specified amount underlying tokens and mints cToken for the sender /// @param mintAmountInUnderlying amount of underlying tokens to deposit to mint cTokens /// @return status code of whether the mint was successful or not function mint(uint256 mintAmountInUnderlying) external returns (uint256); + /// @dev redeems specified amount of cTokens and returns the underlying token to the sender /// @param redeemTokensInCtokens amount of cTokens to redeem for underlying collateral /// @return status code of whether the redemption was successful or not function redeem(uint256 redeemTokensInCtokens) external returns (uint256); } + /// @dev Minimal CEther interface interface ICEther { /// @dev deposits the amount of Ether sent as value and return mints cEther for the sender - function mint() payable external; + function mint() external payable; + /// @dev redeems specified amount of cETH and returns the underlying ether to the sender /// @dev redeemTokensInCEther amount of cETH to redeem for underlying ether /// @return status code of whether the redemption was successful or not @@ -53,24 +55,19 @@ contract MixinCompound { IEtherTokenV06 private immutable WETH; - constructor(IEtherTokenV06 weth) - public - { + constructor(IEtherTokenV06 weth) public { WETH = weth; } - uint256 constant private COMPOUND_SUCCESS_CODE = 0; + uint256 private constant COMPOUND_SUCCESS_CODE = 0; function _tradeCompound( IERC20TokenV06 sellToken, IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256) - { - (address cTokenAddress) = abi.decode(bridgeData, (address)); + ) internal returns (uint256) { + address cTokenAddress = abi.decode(bridgeData, (address)); uint256 beforeBalance = buyToken.balanceOf(address(this)); if (address(buyToken) == cTokenAddress) { @@ -82,10 +79,7 @@ contract MixinCompound { // NOTE: cETH mint will revert on failure instead of returning a status code cETH.mint{value: sellAmount}(); } else { - sellToken.approveIfBelow( - cTokenAddress, - sellAmount - ); + sellToken.approveIfBelow(cTokenAddress, sellAmount); // Token -> cToken ICToken cToken = ICToken(cTokenAddress); require(cToken.mint(sellAmount) == COMPOUND_SUCCESS_CODE, "MixinCompound/FAILED_TO_MINT_CTOKEN"); diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCryptoCom.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCryptoCom.sol index 06dc461306..a3ec217c55 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCryptoCom.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCryptoCom.sol @@ -25,39 +25,34 @@ import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "./MixinUniswapV2.sol"; -contract MixinCryptoCom -{ +contract MixinCryptoCom { using LibERC20TokenV06 for IERC20TokenV06; function _tradeCryptoCom( IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { + ) internal returns (uint256 boughtAmount) { IUniswapV2Router02 router; IERC20TokenV06[] memory path; { address[] memory _path; (router, _path) = abi.decode(bridgeData, (IUniswapV2Router02, address[])); // To get around `abi.decode()` not supporting interface array types. - assembly { path := _path } + assembly { + path := _path + } } require(path.length >= 2, "MixinCryptoCom/PATH_LENGTH_MUST_BE_AT_LEAST_TWO"); - require( - path[path.length - 1] == buyToken, - "MixinCryptoCom/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN" - ); + require(path[path.length - 1] == buyToken, "MixinCryptoCom/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN"); // Grant the CryptoCom router an allowance to sell the first token. path[0].approveIfBelow(address(router), sellAmount); - uint[] memory amounts = router.swapExactTokensForTokens( - // Sell all tokens we hold. + uint256[] memory amounts = router.swapExactTokensForTokens( + // Sell all tokens we hold. sellAmount, - // Minimum buy amount. + // Minimum buy amount. 1, // Convert to `buyToken` along this path. path, @@ -66,6 +61,6 @@ contract MixinCryptoCom // Expires after this block. block.timestamp ); - return amounts[amounts.length-1]; + return amounts[amounts.length - 1]; } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCurve.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCurve.sol index 9c322f3f9c..a51f8d6b13 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCurve.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCurve.sol @@ -27,7 +27,6 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; contract MixinCurve { - using LibERC20TokenV06 for IERC20TokenV06; using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; @@ -35,13 +34,10 @@ contract MixinCurve { /// @dev Mainnet address of the WETH contract. IEtherTokenV06 private immutable WETH; - constructor(IEtherTokenV06 weth) - public - { + constructor(IEtherTokenV06 weth) public { WETH = weth; } - struct CurveBridgeData { address curveAddress; bytes4 exchangeFunctionSelector; @@ -54,10 +50,7 @@ contract MixinCurve { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { + ) internal returns (uint256 boughtAmount) { // Decode the bridge data to get the Curve metadata. CurveBridgeData memory data = abi.decode(bridgeData, (CurveBridgeData)); uint256 payableAmount; @@ -69,8 +62,8 @@ contract MixinCurve { } uint256 beforeBalance = buyToken.balanceOf(address(this)); - (bool success, bytes memory resultData) = - data.curveAddress.call{value: payableAmount}(abi.encodeWithSelector( + (bool success, bytes memory resultData) = data.curveAddress.call{value: payableAmount}( + abi.encodeWithSelector( data.exchangeFunctionSelector, data.fromCoinIdx, data.toCoinIdx, @@ -78,14 +71,15 @@ contract MixinCurve { sellAmount, // min dy 1 - )); + ) + ); if (!success) { resultData.rrevert(); } if (buyToken == WETH) { boughtAmount = address(this).balance; - WETH.deposit{ value: boughtAmount }(); + WETH.deposit{value: boughtAmount}(); } return buyToken.balanceOf(address(this)).safeSub(beforeBalance); diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCurveV2.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCurveV2.sol index ebb49f455d..17210ed3f5 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCurveV2.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinCurveV2.sol @@ -26,7 +26,6 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; contract MixinCurveV2 { - using LibERC20TokenV06 for IERC20TokenV06; using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; @@ -43,17 +42,14 @@ contract MixinCurveV2 { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { + ) internal returns (uint256 boughtAmount) { // Decode the bridge data to get the Curve metadata. CurveBridgeDataV2 memory data = abi.decode(bridgeData, (CurveBridgeDataV2)); sellToken.approveIfBelow(data.curveAddress, sellAmount); uint256 beforeBalance = buyToken.balanceOf(address(this)); - (bool success, bytes memory resultData) = - data.curveAddress.call(abi.encodeWithSelector( + (bool success, bytes memory resultData) = data.curveAddress.call( + abi.encodeWithSelector( data.exchangeFunctionSelector, data.fromCoinIdx, data.toCoinIdx, @@ -61,7 +57,8 @@ contract MixinCurveV2 { sellAmount, // min dy 1 - )); + ) + ); if (!success) { resultData.rrevert(); } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinDodo.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinDodo.sol index f4a6bdd5aa..173c28c310 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinDodo.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinDodo.sol @@ -25,51 +25,33 @@ import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../IBridgeAdapter.sol"; - interface IDODO { function sellBaseToken( uint256 amount, uint256 minReceiveQuote, bytes calldata data - ) - external - returns (uint256); + ) external returns (uint256); function buyBaseToken( uint256 amount, uint256 maxPayQuote, bytes calldata data - ) - external - returns (uint256); + ) external returns (uint256); } - interface IDODOHelper { - function querySellQuoteToken( - IDODO dodo, - uint256 amount - ) - external - view - returns (uint256); + function querySellQuoteToken(IDODO dodo, uint256 amount) external view returns (uint256); } - contract MixinDodo { - using LibERC20TokenV06 for IERC20TokenV06; function _tradeDodo( IERC20TokenV06 sellToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { - (IDODOHelper helper, IDODO pool, bool isSellBase) = - abi.decode(bridgeData, (IDODOHelper, IDODO, bool)); + ) internal returns (uint256 boughtAmount) { + (IDODOHelper helper, IDODO pool, bool isSellBase) = abi.decode(bridgeData, (IDODOHelper, IDODO, bool)); // Grant the Dodo pool contract an allowance to sell the first token. sellToken.approveIfBelow(address(pool), sellAmount); @@ -85,10 +67,7 @@ contract MixinDodo { ); } else { // Need to re-calculate the sell quote amount into buyBase - boughtAmount = helper.querySellQuoteToken( - pool, - sellAmount - ); + boughtAmount = helper.querySellQuoteToken(pool, sellAmount); pool.buyBaseToken( // amount to buy boughtAmount, diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinDodoV2.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinDodoV2.sol index 5b11d50590..32d467ec40 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinDodoV2.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinDodoV2.sol @@ -25,38 +25,25 @@ import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../IBridgeAdapter.sol"; - interface IDODOV2 { - function sellBase(address recipient) - external - returns (uint256); + function sellBase(address recipient) external returns (uint256); - function sellQuote(address recipient) - external - returns (uint256); + function sellQuote(address recipient) external returns (uint256); } - contract MixinDodoV2 { - using LibERC20TokenV06 for IERC20TokenV06; function _tradeDodoV2( IERC20TokenV06 sellToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { - (IDODOV2 pool, bool isSellBase) = - abi.decode(bridgeData, (IDODOV2, bool)); + ) internal returns (uint256 boughtAmount) { + (IDODOV2 pool, bool isSellBase) = abi.decode(bridgeData, (IDODOV2, bool)); // Transfer the tokens into the pool sellToken.compatTransfer(address(pool), sellAmount); - boughtAmount = isSellBase ? - pool.sellBase(address(this)) - : pool.sellQuote(address(this)); + boughtAmount = isSellBase ? pool.sellBase(address(this)) : pool.sellQuote(address(this)); } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinGMX.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinGMX.sol index 8c8814d513..eef5322bf4 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinGMX.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinGMX.sol @@ -25,7 +25,6 @@ import "../IBridgeAdapter.sol"; UniswapV2 */ interface IGmxRouter { - // /// @dev Swaps an exact amount of input tokens for as many output tokens as possible, along the route determined by the path. // /// The first element of path is the input token, the last is the output token, and any intermediate elements represent // /// intermediate pairs to trade through (if, for example, a direct pair does not exist). @@ -34,12 +33,14 @@ interface IGmxRouter { // /// @param _minOut The minimum amount of output tokens that must be received for the transaction not to revert. // /// @param _reciever Recipient of the output tokens. function swap( - address[] calldata _path, uint256 _amountIn, uint256 _minOut, address _receiver + address[] calldata _path, + uint256 _amountIn, + uint256 _minOut, + address _receiver ) external; } contract MixinGMX { - using LibERC20TokenV06 for IERC20TokenV06; using LibSafeMathV06 for uint256; @@ -47,10 +48,7 @@ contract MixinGMX { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - public - returns (uint256 boughtAmount) - { + ) public returns (uint256 boughtAmount) { address _router; address reader; address vault; @@ -62,14 +60,13 @@ contract MixinGMX { //decode the bridge data (_router, reader, vault, _path) = abi.decode(bridgeData, (address, address, address, address[])); // To get around `abi.decode()` not supporting interface array types. - assembly { path := _path } + assembly { + path := _path + } } require(path.length >= 2, "MixinGMX/PATH_LENGTH_MUST_BE_AT_LEAST_TWO"); - require( - path[path.length - 1] == buyToken, - "MixinGMX/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN" - ); + require(path[path.length - 1] == buyToken, "MixinGMX/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN"); //connect to the GMX router router = IGmxRouter(_router); @@ -82,9 +79,9 @@ contract MixinGMX { router.swap( // Convert to `buyToken` along this path. _path, - // Sell all tokens we hold. + // Sell all tokens we hold. sellAmount, - // Minimum buy amount. + // Minimum buy amount. 0, // Recipient is `this`. address(this) @@ -95,4 +92,4 @@ contract MixinGMX { return boughtAmount; } -} \ No newline at end of file +} diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinKyberDmm.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinKyberDmm.sol index 6819c932a6..2fe79d0f27 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinKyberDmm.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinKyberDmm.sol @@ -29,7 +29,6 @@ import "../IBridgeAdapter.sol"; KyberDmm Router */ interface IKyberDmmRouter { - /// @dev Swaps an exact amount of input tokens for as many output tokens as possible, along the route determined by the path. /// The first element of path is the input token, the last is the output token, and any intermediate elements represent /// intermediate pairs to trade through (if, for example, a direct pair does not exist). @@ -41,27 +40,23 @@ interface IKyberDmmRouter { /// @param deadline Unix timestamp after which the transaction will revert. /// @return amounts The input token amount and all subsequent output token amounts. function swapExactTokensForTokens( - uint amountIn, - uint amountOutMin, + uint256 amountIn, + uint256 amountOutMin, address[] calldata pools, address[] calldata path, address to, - uint deadline - ) external returns (uint[] memory amounts); + uint256 deadline + ) external returns (uint256[] memory amounts); } contract MixinKyberDmm { - using LibERC20TokenV06 for IERC20TokenV06; function _tradeKyberDmm( IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { + ) internal returns (uint256 boughtAmount) { address router; address[] memory pools; address[] memory path; @@ -69,17 +64,17 @@ contract MixinKyberDmm { require(pools.length >= 1, "MixinKyberDmm/POOLS_LENGTH_MUST_BE_AT_LEAST_ONE"); require(path.length == pools.length + 1, "MixinKyberDmm/ARRAY_LENGTH_MISMATCH"); - require( - path[path.length - 1] == address(buyToken), - "MixinKyberDmm/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN" - ); + require( + path[path.length - 1] == address(buyToken), + "MixinKyberDmm/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN" + ); // Grant the KyberDmm router an allowance to sell the first token. IERC20TokenV06(path[0]).approveIfBelow(address(router), sellAmount); - uint[] memory amounts = IKyberDmmRouter(router).swapExactTokensForTokens( - // Sell all tokens we hold. + uint256[] memory amounts = IKyberDmmRouter(router).swapExactTokensForTokens( + // Sell all tokens we hold. sellAmount, - // Minimum buy amount. + // Minimum buy amount. 1, pools, // Convert to `buyToken` along this path. @@ -89,6 +84,6 @@ contract MixinKyberDmm { // Expires after this block. block.timestamp ); - return amounts[amounts.length-1]; + return amounts[amounts.length - 1]; } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinLido.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinLido.sol index 4b31e44518..0ab67c7f7d 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinLido.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinLido.sol @@ -24,13 +24,13 @@ import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol"; - /// @dev Minimal interface for minting StETH interface IStETH { /// @dev Adds eth to the pool /// @param _referral optional address for referrals /// @return StETH Amount of shares generated function submit(address _referral) external payable returns (uint256 StETH); + /// @dev Retrieve the current pooled ETH representation of the shares amount /// @param _sharesAmount amount of shares /// @return amount of pooled ETH represented by the shares amount @@ -39,7 +39,6 @@ interface IStETH { /// @dev Minimal interface for wrapping/unwrapping stETH. interface IWstETH { - /** * @notice Exchanges stETH to wstETH * @param _stETHAmount amount of stETH to wrap in exchange for wstETH @@ -64,16 +63,13 @@ interface IWstETH { function unwrap(uint256 _wstETHAmount) external returns (uint256); } - contract MixinLido { using LibERC20TokenV06 for IERC20TokenV06; using LibERC20TokenV06 for IEtherTokenV06; IEtherTokenV06 private immutable WETH; - constructor(IEtherTokenV06 weth) - public - { + constructor(IEtherTokenV06 weth) public { WETH = weth; } @@ -82,13 +78,10 @@ contract MixinLido { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { + ) internal returns (uint256 boughtAmount) { if (address(sellToken) == address(WETH)) { return _tradeStETH(buyToken, sellAmount, bridgeData); - } + } return _tradeWstETH(sellToken, buyToken, sellAmount, bridgeData); } @@ -98,10 +91,10 @@ contract MixinLido { uint256 sellAmount, bytes memory bridgeData ) private returns (uint256 boughtAmount) { - (IStETH stETH) = abi.decode(bridgeData, (IStETH)); + IStETH stETH = abi.decode(bridgeData, (IStETH)); if (address(buyToken) == address(stETH)) { WETH.withdraw(sellAmount); - return stETH.getPooledEthByShares(stETH.submit{ value: sellAmount}(address(0))); + return stETH.getPooledEthByShares(stETH.submit{value: sellAmount}(address(0))); } revert("MixinLido/UNSUPPORTED_TOKEN_PAIR"); @@ -112,14 +105,13 @@ contract MixinLido { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - - ) private returns(uint256 boughtAmount){ + ) private returns (uint256 boughtAmount) { (IEtherTokenV06 stETH, IWstETH wstETH) = abi.decode(bridgeData, (IEtherTokenV06, IWstETH)); - if (address(sellToken) == address(stETH) && address(buyToken) == address(wstETH) ) { + if (address(sellToken) == address(stETH) && address(buyToken) == address(wstETH)) { sellToken.approveIfBelow(address(wstETH), sellAmount); return wstETH.wrap(sellAmount); } - if (address(sellToken) == address(wstETH) && address(buyToken) == address(stETH) ) { + if (address(sellToken) == address(wstETH) && address(buyToken) == address(stETH)) { return wstETH.unwrap(sellAmount); } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinMStable.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinMStable.sol index 0252d89ba3..0625a0965f 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinMStable.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinMStable.sol @@ -24,22 +24,17 @@ import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../IBridgeAdapter.sol"; - interface IMStable { - function swap( IERC20TokenV06 sellToken, IERC20TokenV06 buyToken, uint256 sellAmount, uint256 minBoughtAmount, address recipient - ) - external - returns (uint256 boughtAmount); + ) external returns (uint256 boughtAmount); } contract MixinMStable { - using LibERC20TokenV06 for IERC20TokenV06; function _tradeMStable( @@ -47,11 +42,8 @@ contract MixinMStable { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { - (IMStable mstable) = abi.decode(bridgeData, (IMStable)); + ) internal returns (uint256 boughtAmount) { + IMStable mstable = abi.decode(bridgeData, (IMStable)); // Grant an allowance to the exchange to spend `sellToken` token. sellToken.approveIfBelow(address(mstable), sellAmount); diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinMakerPSM.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinMakerPSM.sol index 283e9873fc..a85517b486 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinMakerPSM.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinMakerPSM.sol @@ -28,6 +28,7 @@ interface IPSM { // @dev Get the fee for selling USDC to DAI in PSM // @return tin toll in [wad] function tin() external view returns (uint256); + // @dev Get the fee for selling DAI to USDC in PSM // @return tout toll out [wad] function tout() external view returns (uint256); @@ -43,21 +44,15 @@ interface IPSM { // @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 - function sellGem( - address usr, - uint256 gemAmt - ) external; + function sellGem(address usr, uint256 gemAmt) external; + // @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 - function buyGem( - address usr, - uint256 gemAmt - ) external; + function buyGem(address usr, uint256 gemAmt) external; } contract MixinMakerPSM { - using LibERC20TokenV06 for IERC20TokenV06; using LibSafeMathV06 for uint256; @@ -68,11 +63,12 @@ contract MixinMakerPSM { // Maker units // wad: fixed point decimal with 18 decimals (for basic quantities, e.g. balances) - uint256 constant private WAD = 10 ** 18; + uint256 private constant WAD = 10**18; // ray: fixed point decimal with 27 decimals (for precise quantites, e.g. ratios) - uint256 constant private RAY = 10 ** 27; + uint256 private constant RAY = 10**27; // rad: fixed point decimal with 45 decimals (result of integer multiplication with a wad and a ray) - uint256 constant private RAD = 10 ** 45; + uint256 private constant RAD = 10**45; + // See https://github.com/makerdao/dss/blob/master/DEVELOPING.md function _tradeMakerPsm( @@ -80,10 +76,7 @@ contract MixinMakerPSM { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { + ) internal returns (uint256 boughtAmount) { // Decode the bridge data. MakerPsmBridgeData memory data = abi.decode(bridgeData, (MakerPsmBridgeData)); uint256 beforeBalance = buyToken.balanceOf(address(this)); @@ -91,21 +84,15 @@ contract MixinMakerPSM { IPSM psm = IPSM(data.psmAddress); if (address(sellToken) == data.gemTokenAddres) { - sellToken.approveIfBelow( - psm.gemJoin(), - sellAmount - ); + sellToken.approveIfBelow(psm.gemJoin(), sellAmount); psm.sellGem(address(this), sellAmount); } else if (address(buyToken) == data.gemTokenAddres) { uint256 feeDivisor = WAD.safeAdd(psm.tout()); // eg. 1.001 * 10 ** 18 with 0.1% fee [tout is in wad]; - uint256 buyTokenBaseUnit = uint256(10) ** uint256(buyToken.decimals()); - uint256 gemAmount = sellAmount.safeMul(buyTokenBaseUnit).safeDiv(feeDivisor); + uint256 buyTokenBaseUnit = uint256(10)**uint256(buyToken.decimals()); + uint256 gemAmount = sellAmount.safeMul(buyTokenBaseUnit).safeDiv(feeDivisor); - sellToken.approveIfBelow( - data.psmAddress, - sellAmount - ); + sellToken.approveIfBelow(data.psmAddress, sellAmount); psm.buyGem(address(this), gemAmount); } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinMooniswap.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinMooniswap.sol index 571b5b40ad..35a346fe8a 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinMooniswap.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinMooniswap.sol @@ -26,34 +26,26 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol"; import "../IBridgeAdapter.sol"; - /// @dev Moooniswap pool interface. interface IMooniswapPool { - function swap( IERC20TokenV06 sellToken, IERC20TokenV06 buyToken, uint256 sellAmount, uint256 minBoughtAmount, address referrer - ) - external - payable - returns (uint256 boughtAmount); + ) external payable returns (uint256 boughtAmount); } /// @dev BridgeAdapter mixin for mooniswap. contract MixinMooniswap { - using LibERC20TokenV06 for IERC20TokenV06; using LibERC20TokenV06 for IEtherTokenV06; /// @dev WETH token. IEtherTokenV06 private immutable WETH; - constructor(IEtherTokenV06 weth) - public - { + constructor(IEtherTokenV06 weth) public { WETH = weth; } @@ -62,11 +54,8 @@ contract MixinMooniswap { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { - (IMooniswapPool pool) = abi.decode(bridgeData, (IMooniswapPool)); + ) internal returns (uint256 boughtAmount) { + IMooniswapPool pool = abi.decode(bridgeData, (IMooniswapPool)); // Convert WETH to ETH. uint256 ethValue = 0; @@ -75,10 +64,7 @@ contract MixinMooniswap { ethValue = sellAmount; } else { // Grant the pool an allowance. - sellToken.approveIfBelow( - address(pool), - sellAmount - ); + sellToken.approveIfBelow(address(pool), sellAmount); } boughtAmount = pool.swap{value: ethValue}( @@ -91,7 +77,7 @@ contract MixinMooniswap { // Wrap ETH to WETH. if (buyToken == WETH) { - WETH.deposit{value:boughtAmount}(); + WETH.deposit{value: boughtAmount}(); } } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinNerve.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinNerve.sol index 6c42ba5ce9..074f37f7f5 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinNerve.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinNerve.sol @@ -26,12 +26,10 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; contract MixinNerve { - using LibERC20TokenV06 for IERC20TokenV06; using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; - struct NerveBridgeData { address pool; bytes4 exchangeFunctionSelector; @@ -43,17 +41,14 @@ contract MixinNerve { IERC20TokenV06 sellToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { + ) internal returns (uint256 boughtAmount) { // Basically a Curve fork but the swap option has a deadline // Decode the bridge data to get the Curve metadata. NerveBridgeData memory data = abi.decode(bridgeData, (NerveBridgeData)); sellToken.approveIfBelow(data.pool, sellAmount); - (bool success, bytes memory resultData) = - data.pool.call(abi.encodeWithSelector( + (bool success, bytes memory resultData) = data.pool.call( + abi.encodeWithSelector( data.exchangeFunctionSelector, data.fromCoinIdx, data.toCoinIdx, @@ -63,7 +58,8 @@ contract MixinNerve { 1, // deadline block.timestamp - )); + ) + ); if (!success) { resultData.rrevert(); } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinPlatypus.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinPlatypus.sol index b1b7118e8a..a5a1574c2e 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinPlatypus.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinPlatypus.sol @@ -24,9 +24,7 @@ import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; - interface IPlatypusRouter { - function swapTokensForTokens( address[] calldata tokenPath, address[] calldata poolPath, @@ -38,7 +36,6 @@ interface IPlatypusRouter { } contract MixinPlatypus { - using LibERC20TokenV06 for IERC20TokenV06; using LibSafeMathV06 for uint256; @@ -46,10 +43,7 @@ contract MixinPlatypus { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - public - returns (uint256 boughtAmount) - { + ) public returns (uint256 boughtAmount) { IPlatypusRouter router; address _router; address[] memory _pool; @@ -60,17 +54,16 @@ contract MixinPlatypus { (_router, _pool, _path) = abi.decode(bridgeData, (address, address[], address[])); // To get around `abi.decode()` not supporting interface array types. - assembly { path := _path } + assembly { + path := _path + } } //connect to the ptp router router = IPlatypusRouter(_router); require(path.length >= 2, "MixinPlatypus/PATH_LENGTH_MUST_BE_AT_LEAST_TWO"); - require( - path[path.length - 1] == buyToken, - "MixinPlatypus/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN" - ); + require(path[path.length - 1] == buyToken, "MixinPlatypus/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN"); // Grant the Platypus router an allowance to sell the first token. path[0].approveIfBelow(address(router), sellAmount); @@ -82,17 +75,16 @@ contract MixinPlatypus { _path, // pool to swap on _pool, - // Sell all tokens we hold. + // Sell all tokens we hold. sellAmount, - // Minimum buy amount. + // Minimum buy amount. 0, // Recipient is `this`. address(this), - block.timestamp + 1 ); //calculate the buy amount from the tokens we recieved boughtAmount = buyToken.balanceOf(address(this)).safeSub(beforeBalance); return boughtAmount; } -} \ No newline at end of file +} diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinShell.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinShell.sol index 4ddb957ce1..c64520b2b5 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinShell.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinShell.sol @@ -25,20 +25,16 @@ import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; interface IShell { - function originSwap( IERC20TokenV06 from, IERC20TokenV06 to, uint256 fromAmount, uint256 minTargetAmount, uint256 deadline - ) - external - returns (uint256 toAmount); + ) external returns (uint256 toAmount); } contract MixinShell { - using LibERC20TokenV06 for IERC20TokenV06; function _tradeShell( @@ -46,24 +42,18 @@ contract MixinShell { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { + ) internal returns (uint256 boughtAmount) { IShell pool = abi.decode(bridgeData, (IShell)); // Grant the Shell contract an allowance to sell the first token. - IERC20TokenV06(sellToken).approveIfBelow( - address(pool), - sellAmount - ); + IERC20TokenV06(sellToken).approveIfBelow(address(pool), sellAmount); boughtAmount = pool.originSwap( sellToken, buyToken, - // Sell all tokens we hold. + // Sell all tokens we hold. sellAmount, - // Minimum buy amount. + // Minimum buy amount. 1, // deadline block.timestamp + 1 diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinSynthetix.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinSynthetix.sol index 2e10ffb27c..64e600879c 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinSynthetix.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinSynthetix.sol @@ -41,30 +41,16 @@ interface ISynthetix { } contract MixinSynthetix { - address private constant rewardAddress = - 0x5C80239D97E1eB216b5c3D8fBa5DE5Be5d38e4C9; - bytes32 constant trackingCode = - 0x3058000000000000000000000000000000000000000000000000000000000000; + address private constant rewardAddress = 0x5C80239D97E1eB216b5c3D8fBa5DE5Be5d38e4C9; + bytes32 constant trackingCode = 0x3058000000000000000000000000000000000000000000000000000000000000; - function _tradeSynthetix(uint256 sellAmount, bytes memory bridgeData) - public - returns (uint256 boughtAmount) - { - ( - ISynthetix synthetix, - bytes32 sourceCurrencyKey, - bytes32 destinationCurrencyKey - ) = abi.decode( - bridgeData, - (ISynthetix, bytes32, bytes32) - ); - - boughtAmount = exchange( - synthetix, - sourceCurrencyKey, - destinationCurrencyKey, - sellAmount + function _tradeSynthetix(uint256 sellAmount, bytes memory bridgeData) public returns (uint256 boughtAmount) { + (ISynthetix synthetix, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) = abi.decode( + bridgeData, + (ISynthetix, bytes32, bytes32) ); + + boughtAmount = exchange(synthetix, sourceCurrencyKey, destinationCurrencyKey, sellAmount); } function exchange( diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinUniswap.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinUniswap.sol index d1d15744e6..5d34221caf 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinUniswap.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinUniswap.sol @@ -26,17 +26,12 @@ import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol"; import "../IBridgeAdapter.sol"; interface IUniswapExchangeFactory { - /// @dev Get the exchange for a token. /// @param token The token contract. - function getExchange(IERC20TokenV06 token) - external - view - returns (IUniswapExchange exchange); + function getExchange(IERC20TokenV06 token) external view returns (IUniswapExchange exchange); } interface IUniswapExchange { - /// @dev Buys at least `minTokensBought` tokens with ETH and transfer them /// to `recipient`. /// @param minTokensBought The minimum number of tokens to buy. @@ -47,10 +42,7 @@ interface IUniswapExchange { uint256 minTokensBought, uint256 deadline, address recipient - ) - external - payable - returns (uint256 tokensBought); + ) external payable returns (uint256 tokensBought); /// @dev Buys at least `minEthBought` ETH with tokens. /// @param tokensSold Amount of tokens to sell. @@ -61,9 +53,7 @@ interface IUniswapExchange { uint256 tokensSold, uint256 minEthBought, uint256 deadline - ) - external - returns (uint256 ethBought); + ) external returns (uint256 ethBought); /// @dev Buys at least `minTokensBought` tokens with the exchange token /// and transfer them to `recipient`. @@ -81,9 +71,7 @@ interface IUniswapExchange { uint256 deadline, address recipient, IERC20TokenV06 buyToken - ) - external - returns (uint256 tokensBought); + ) external returns (uint256 tokensBought); /// @dev Buys at least `minTokensBought` tokens with the exchange token. /// @param tokensSold Amount of tokens to sell. @@ -98,21 +86,16 @@ interface IUniswapExchange { uint256 minEthBought, uint256 deadline, IERC20TokenV06 buyToken - ) - external - returns (uint256 tokensBought); + ) external returns (uint256 tokensBought); } contract MixinUniswap { - using LibERC20TokenV06 for IERC20TokenV06; /// @dev Mainnet address of the WETH contract. IEtherTokenV06 private immutable WETH; - constructor(IEtherTokenV06 weth) - public - { + constructor(IEtherTokenV06 weth) public { WETH = weth; } @@ -121,26 +104,18 @@ contract MixinUniswap { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { - IUniswapExchangeFactory exchangeFactory = - abi.decode(bridgeData, (IUniswapExchangeFactory)); + ) internal returns (uint256 boughtAmount) { + IUniswapExchangeFactory exchangeFactory = abi.decode(bridgeData, (IUniswapExchangeFactory)); // Get the exchange for the token pair. - IUniswapExchange exchange = _getUniswapExchangeForTokenPair( - exchangeFactory, - sellToken, - buyToken - ); + IUniswapExchange exchange = _getUniswapExchangeForTokenPair(exchangeFactory, sellToken, buyToken); // Convert from WETH to a token. if (sellToken == WETH) { // Unwrap the WETH. WETH.withdraw(sellAmount); // Buy as much of `buyToken` token with ETH as possible - boughtAmount = exchange.ethToTokenTransferInput{ value: sellAmount }( + boughtAmount = exchange.ethToTokenTransferInput{value: sellAmount}( // Minimum buy amount. 1, // Expires after this block. @@ -149,13 +124,10 @@ contract MixinUniswap { address(this) ); - // Convert from a token to WETH. + // Convert from a token to WETH. } else if (buyToken == WETH) { // Grant the exchange an allowance. - sellToken.approveIfBelow( - address(exchange), - sellAmount - ); + sellToken.approveIfBelow(address(exchange), sellAmount); // Buy as much ETH with `sellToken` token as possible. boughtAmount = exchange.tokenToEthSwapInput( // Sell all tokens we hold. @@ -166,14 +138,11 @@ contract MixinUniswap { block.timestamp ); // Wrap the ETH. - WETH.deposit{ value: boughtAmount }(); - // Convert from one token to another. + WETH.deposit{value: boughtAmount}(); + // Convert from one token to another. } else { // Grant the exchange an allowance. - sellToken.approveIfBelow( - address(exchange), - sellAmount - ); + sellToken.approveIfBelow(address(exchange), sellAmount); // Buy as much `buyToken` token with `sellToken` token boughtAmount = exchange.tokenToTokenSwapInput( // Sell all tokens we hold. @@ -203,15 +172,9 @@ contract MixinUniswap { IUniswapExchangeFactory exchangeFactory, IERC20TokenV06 sellToken, IERC20TokenV06 buyToken - ) - private - view - returns (IUniswapExchange exchange) - { + ) private view returns (IUniswapExchange exchange) { // Whichever isn't WETH is the exchange token. - exchange = sellToken == WETH - ? exchangeFactory.getExchange(buyToken) - : exchangeFactory.getExchange(sellToken); + exchange = sellToken == WETH ? exchangeFactory.getExchange(buyToken) : exchangeFactory.getExchange(sellToken); require(address(exchange) != address(0), "MixinUniswap/NO_EXCHANGE"); } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinUniswapV2.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinUniswapV2.sol index 79f859f3d2..0129320a2b 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinUniswapV2.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinUniswapV2.sol @@ -29,7 +29,6 @@ import "../IBridgeAdapter.sol"; UniswapV2 */ interface IUniswapV2Router02 { - /// @dev Swaps an exact amount of input tokens for as many output tokens as possible, along the route determined by the path. /// The first element of path is the input token, the last is the output token, and any intermediate elements represent /// intermediate pairs to trade through (if, for example, a direct pair does not exist). @@ -40,47 +39,42 @@ interface IUniswapV2Router02 { /// @param deadline Unix timestamp after which the transaction will revert. /// @return amounts The input token amount and all subsequent output token amounts. function swapExactTokensForTokens( - uint amountIn, - uint amountOutMin, + uint256 amountIn, + uint256 amountOutMin, IERC20TokenV06[] calldata path, address to, - uint deadline - ) external returns (uint[] memory amounts); + uint256 deadline + ) external returns (uint256[] memory amounts); } contract MixinUniswapV2 { - using LibERC20TokenV06 for IERC20TokenV06; function _tradeUniswapV2( IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { + ) internal returns (uint256 boughtAmount) { IUniswapV2Router02 router; IERC20TokenV06[] memory path; { address[] memory _path; (router, _path) = abi.decode(bridgeData, (IUniswapV2Router02, address[])); // To get around `abi.decode()` not supporting interface array types. - assembly { path := _path } + assembly { + path := _path + } } require(path.length >= 2, "MixinUniswapV2/PATH_LENGTH_MUST_BE_AT_LEAST_TWO"); - require( - path[path.length - 1] == buyToken, - "MixinUniswapV2/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN" - ); + require(path[path.length - 1] == buyToken, "MixinUniswapV2/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN"); // Grant the Uniswap router an allowance to sell the first token. path[0].approveIfBelow(address(router), sellAmount); - uint[] memory amounts = router.swapExactTokensForTokens( - // Sell all tokens we hold. + uint256[] memory amounts = router.swapExactTokensForTokens( + // Sell all tokens we hold. sellAmount, - // Minimum buy amount. + // Minimum buy amount. 1, // Convert to `buyToken` along this path. path, @@ -89,6 +83,6 @@ contract MixinUniswapV2 { // Expires after this block. block.timestamp ); - return amounts[amounts.length-1]; + return amounts[amounts.length - 1]; } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinUniswapV3.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinUniswapV3.sol index 25260603a1..53f46a787a 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinUniswapV3.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinUniswapV3.sol @@ -26,7 +26,6 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../IBridgeAdapter.sol"; interface IUniswapV3Router { - struct ExactInputParams { bytes path; address recipient; @@ -35,36 +34,30 @@ interface IUniswapV3Router { uint256 amountOutMinimum; } - function exactInput(ExactInputParams memory params) - external - payable - returns (uint256 amountOut); + function exactInput(ExactInputParams memory params) external payable returns (uint256 amountOut); } contract MixinUniswapV3 { - using LibERC20TokenV06 for IERC20TokenV06; function _tradeUniswapV3( IERC20TokenV06 sellToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { - (IUniswapV3Router router, bytes memory path) = - abi.decode(bridgeData, (IUniswapV3Router, bytes)); + ) internal returns (uint256 boughtAmount) { + (IUniswapV3Router router, bytes memory path) = abi.decode(bridgeData, (IUniswapV3Router, bytes)); // Grant the Uniswap router an allowance to sell the sell token. sellToken.approveIfBelow(address(router), sellAmount); - boughtAmount = router.exactInput(IUniswapV3Router.ExactInputParams({ - path: path, - recipient: address(this), - deadline: block.timestamp, - amountIn: sellAmount, - amountOutMinimum: 1 - })); + boughtAmount = router.exactInput( + IUniswapV3Router.ExactInputParams({ + path: path, + recipient: address(this), + deadline: block.timestamp, + amountIn: sellAmount, + amountOutMinimum: 1 + }) + ); } } diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinVelodrome.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinVelodrome.sol index 61f9b804eb..b98b18ad3a 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinVelodrome.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinVelodrome.sol @@ -32,7 +32,7 @@ interface IVelodromeRouter { bool stable, address to, uint256 deadline - ) external returns (uint256[] memory amounts); + ) external returns (uint256[] memory amounts); } contract MixinVelodrome { @@ -43,17 +43,13 @@ contract MixinVelodrome { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { - + ) internal returns (uint256 boughtAmount) { (IVelodromeRouter router, bool stable) = abi.decode(bridgeData, (IVelodromeRouter, bool)); sellToken.approveIfBelow(address(router), sellAmount); boughtAmount = router.swapExactTokensForTokensSimple( sellAmount, - 0, + 0, address(sellToken), address(buyToken), stable, diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinWOOFi.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinWOOFi.sol index f1c19c1cf2..9b644d47d2 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinWOOFi.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinWOOFi.sol @@ -46,15 +46,10 @@ interface IWooPP { /// @param baseToken the base token to sell /// @param baseAmount the amount to sell /// @return quoteAmount the swapped quote amount - function querySellBase( - address baseToken, - uint256 baseAmount - ) external view returns (uint256 quoteAmount); - + function querySellBase(address baseToken, uint256 baseAmount) external view returns (uint256 quoteAmount); } -contract MixinWOOFi{ - +contract MixinWOOFi { using LibERC20TokenV06 for IERC20TokenV06; using LibERC20TokenV06 for IEtherTokenV06; using LibSafeMathV06 for uint256; @@ -73,64 +68,31 @@ contract MixinWOOFi{ IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - public - returns (uint256 boughtAmount) - { - (IWooPP _pool) = abi.decode(bridgeData, (IWooPP)); + ) public returns (uint256 boughtAmount) { + IWooPP _pool = abi.decode(bridgeData, (IWooPP)); uint256 beforeBalance = buyToken.balanceOf(address(this)); sellToken.approveIfBelow(address(_pool), sellAmount); - - _swap( - sellAmount, - address(sellToken), - address(buyToken), - _pool - ); + + _swap(sellAmount, address(sellToken), address(buyToken), _pool); boughtAmount = buyToken.balanceOf(address(this)).safeSub(beforeBalance); } function _swap( - uint _amountIn, - address _tokenIn, - address _tokenOut, + uint256 _amountIn, + address _tokenIn, + address _tokenOut, IWooPP pool ) internal { address quoteToken = pool.quoteToken(); if (_tokenIn == quoteToken) { - pool.sellQuote( - _tokenOut, - _amountIn, - 1, - address(this), - rebateAddress - ); + pool.sellQuote(_tokenOut, _amountIn, 1, address(this), rebateAddress); } else if (_tokenOut == quoteToken) { - pool.sellBase( - _tokenIn, - _amountIn, - 1, - address(this), - rebateAddress - ); - } else { - uint256 quoteAmount = pool.sellBase( - _tokenIn, - _amountIn, - 0, - address(this), - rebateAddress - ); + pool.sellBase(_tokenIn, _amountIn, 1, address(this), rebateAddress); + } else { + uint256 quoteAmount = pool.sellBase(_tokenIn, _amountIn, 0, address(this), rebateAddress); IERC20TokenV06(pool.quoteToken()).approveIfBelow(address(pool), quoteAmount); - pool.sellQuote( - _tokenOut, - quoteAmount, - 1, - address(this), - rebateAddress - ); + pool.sellQuote(_tokenOut, quoteAmount, 1, address(this), rebateAddress); } } - -} \ No newline at end of file +} diff --git a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinZeroExBridge.sol b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinZeroExBridge.sol index 584be64cd4..ec72dfc7df 100644 --- a/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinZeroExBridge.sol +++ b/contracts/zero-ex/contracts/src/transformers/bridges/mixins/MixinZeroExBridge.sol @@ -24,9 +24,7 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "../../../vendor/ILiquidityProvider.sol"; - contract MixinZeroExBridge { - using LibERC20TokenV06 for IERC20TokenV06; using LibSafeMathV06 for uint256; @@ -35,17 +33,10 @@ contract MixinZeroExBridge { IERC20TokenV06 buyToken, uint256 sellAmount, bytes memory bridgeData - ) - internal - returns (uint256 boughtAmount) - { - (ILiquidityProvider provider, bytes memory lpData) = - abi.decode(bridgeData, (ILiquidityProvider, bytes)); + ) internal returns (uint256 boughtAmount) { + (ILiquidityProvider provider, bytes memory lpData) = abi.decode(bridgeData, (ILiquidityProvider, bytes)); // Trade the good old fashioned way - sellToken.compatTransfer( - address(provider), - sellAmount - ); + sellToken.compatTransfer(address(provider), sellAmount); boughtAmount = provider.sellTokenForToken( sellToken, buyToken, diff --git a/contracts/zero-ex/contracts/src/vendor/IERC1155Token.sol b/contracts/zero-ex/contracts/src/vendor/IERC1155Token.sol index 48cdccde4d..2597f022d3 100644 --- a/contracts/zero-ex/contracts/src/vendor/IERC1155Token.sol +++ b/contracts/zero-ex/contracts/src/vendor/IERC1155Token.sol @@ -20,9 +20,7 @@ pragma solidity ^0.6; pragma experimental ABIEncoderV2; - interface IERC1155Token { - /// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, /// including zero value transfers as well as minting or burning. /// Operator will always be msg.sender. @@ -32,13 +30,7 @@ interface IERC1155Token { /// be used by clients and exchanges to be added to the "circulating supply" for a given token ID. /// To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event /// from `0x0` to `0x0`, with the token creator as `_operator`. - event TransferSingle( - address indexed operator, - address indexed from, - address indexed to, - uint256 id, - uint256 value - ); + event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, /// including zero value transfers as well as minting or burning. @@ -58,19 +50,12 @@ interface IERC1155Token { ); /// @dev MUST emit when an approval is updated. - event ApprovalForAll( - address indexed owner, - address indexed operator, - bool approved - ); + event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /// @dev MUST emit when the URI is updated for a token ID. /// URIs are defined in RFC 3986. /// The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema". - event URI( - string value, - uint256 indexed id - ); + event URI(string value, uint256 indexed id); /// @notice Transfers value amount of an _id from the _from address to the _to address specified. /// @dev MUST emit TransferSingle event on success. @@ -92,8 +77,7 @@ interface IERC1155Token { uint256 id, uint256 value, bytes calldata data - ) - external; + ) external; /// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call). /// @dev MUST emit TransferBatch event on success. @@ -116,8 +100,7 @@ interface IERC1155Token { uint256[] calldata ids, uint256[] calldata values, bytes calldata data - ) - external; + ) external; /// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. /// @dev MUST emit the ApprovalForAll event on success. @@ -141,10 +124,7 @@ interface IERC1155Token { /// @param owners The addresses of the token holders /// @param ids ID of the Tokens /// @return balances_ The _owner's balance of the Token types requested - function balanceOfBatch( - address[] calldata owners, - uint256[] calldata ids - ) + function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory balances_); diff --git a/contracts/zero-ex/contracts/src/vendor/IERC721Token.sol b/contracts/zero-ex/contracts/src/vendor/IERC721Token.sol index acaefc7119..6916f14ca6 100644 --- a/contracts/zero-ex/contracts/src/vendor/IERC721Token.sol +++ b/contracts/zero-ex/contracts/src/vendor/IERC721Token.sol @@ -19,37 +19,23 @@ pragma solidity ^0.6; - interface IERC721Token { - /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. - event Transfer( - address indexed _from, - address indexed _to, - uint256 indexed _tokenId - ); + event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. - event Approval( - address indexed _owner, - address indexed _approved, - uint256 indexed _tokenId - ); + event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. - event ApprovalForAll( - address indexed _owner, - address indexed _operator, - bool _approved - ); + event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized @@ -68,8 +54,7 @@ interface IERC721Token { address _to, uint256 _tokenId, bytes calldata _data - ) - external; + ) external; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, @@ -81,8 +66,7 @@ interface IERC721Token { address _from, address _to, uint256 _tokenId - ) - external; + ) external; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. @@ -90,8 +74,7 @@ interface IERC721Token { /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve - function approve(address _approved, uint256 _tokenId) - external; + function approve(address _approved, uint256 _tokenId) external; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets @@ -99,18 +82,14 @@ interface IERC721Token { /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval - function setApprovalForAll(address _operator, bool _approved) - external; + function setApprovalForAll(address _operator, bool _approved) external; /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero - function balanceOf(address _owner) - external - view - returns (uint256); + function balanceOf(address _owner) external view returns (uint256); /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE @@ -126,34 +105,24 @@ interface IERC721Token { address _from, address _to, uint256 _tokenId - ) - external; + ) external; /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT - function ownerOf(uint256 _tokenId) - external - view - returns (address); + function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none - function getApproved(uint256 _tokenId) - external - view - returns (address); + function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise - function isApprovedForAll(address _owner, address _operator) - external - view - returns (bool); + function isApprovedForAll(address _owner, address _operator) external view returns (bool); } diff --git a/contracts/zero-ex/contracts/src/vendor/IFeeRecipient.sol b/contracts/zero-ex/contracts/src/vendor/IFeeRecipient.sol index 38c88ebd1e..197c825982 100644 --- a/contracts/zero-ex/contracts/src/vendor/IFeeRecipient.sol +++ b/contracts/zero-ex/contracts/src/vendor/IFeeRecipient.sol @@ -20,9 +20,7 @@ pragma solidity ^0.6; pragma experimental ABIEncoderV2; - interface IFeeRecipient { - /// @dev A callback function invoked in the ERC721Feature for each ERC721 /// order fee that get paid. Integrators can make use of this callback /// to implement arbitrary fee-handling logic, e.g. splitting the fee @@ -38,7 +36,5 @@ interface IFeeRecipient { address tokenAddress, uint256 amount, bytes calldata feeData - ) - external - returns (bytes4 success); + ) external returns (bytes4 success); } diff --git a/contracts/zero-ex/contracts/src/vendor/ILiquidityProvider.sol b/contracts/zero-ex/contracts/src/vendor/ILiquidityProvider.sol index 201dae7998..45e48c67d7 100644 --- a/contracts/zero-ex/contracts/src/vendor/ILiquidityProvider.sol +++ b/contracts/zero-ex/contracts/src/vendor/ILiquidityProvider.sol @@ -21,9 +21,7 @@ pragma solidity ^0.6.5; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; - interface ILiquidityProvider { - /// @dev An optional event an LP can emit for each fill against a source. /// @param inputToken The input token. /// @param outputToken The output token. @@ -61,9 +59,7 @@ interface ILiquidityProvider { address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - returns (uint256 boughtAmount); + ) external returns (uint256 boughtAmount); /// @dev Trades ETH for token. ETH must either be attached to this function /// call or sent to the contract prior to calling this function to @@ -78,10 +74,7 @@ interface ILiquidityProvider { address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - payable - returns (uint256 boughtAmount); + ) external payable returns (uint256 boughtAmount); /// @dev Trades token for ETH. The token must be sent to the contract prior /// to calling this function to trigger the trade. @@ -95,9 +88,7 @@ interface ILiquidityProvider { address payable recipient, uint256 minBuyAmount, bytes calldata auxiliaryData - ) - external - returns (uint256 boughtAmount); + ) external returns (uint256 boughtAmount); /// @dev Quotes the amount of `outputToken` that would be obtained by /// selling `sellAmount` of `inputToken`. @@ -111,8 +102,5 @@ interface ILiquidityProvider { IERC20TokenV06 inputToken, IERC20TokenV06 outputToken, uint256 sellAmount - ) - external - view - returns (uint256 outputTokenAmount); + ) external view returns (uint256 outputTokenAmount); } diff --git a/contracts/zero-ex/contracts/src/vendor/IMooniswapPool.sol b/contracts/zero-ex/contracts/src/vendor/IMooniswapPool.sol index f56d8498ac..aea8933d21 100644 --- a/contracts/zero-ex/contracts/src/vendor/IMooniswapPool.sol +++ b/contracts/zero-ex/contracts/src/vendor/IMooniswapPool.sol @@ -27,15 +27,11 @@ import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol"; /// @dev Moooniswap pool interface. interface IMooniswapPool { - function swap( IERC20TokenV06 sellToken, IERC20TokenV06 buyToken, uint256 sellAmount, uint256 minBoughtAmount, address referrer - ) - external - payable - returns (uint256 boughtAmount); + ) external payable returns (uint256 boughtAmount); } diff --git a/contracts/zero-ex/contracts/src/vendor/IPropertyValidator.sol b/contracts/zero-ex/contracts/src/vendor/IPropertyValidator.sol index 9c4c54c2d4..ca360e50a7 100644 --- a/contracts/zero-ex/contracts/src/vendor/IPropertyValidator.sol +++ b/contracts/zero-ex/contracts/src/vendor/IPropertyValidator.sol @@ -20,9 +20,7 @@ pragma solidity ^0.6; pragma experimental ABIEncoderV2; - interface IPropertyValidator { - /// @dev Checks that the given ERC721/ERC1155 asset satisfies the properties encoded in `propertyData`. /// Should revert if the asset does not satisfy the specified properties. /// @param tokenAddress The ERC721/ERC1155 token contract address. @@ -32,7 +30,5 @@ interface IPropertyValidator { address tokenAddress, uint256 tokenId, bytes calldata propertyData - ) - external - view; + ) external view; } diff --git a/contracts/zero-ex/contracts/src/vendor/ITakerCallback.sol b/contracts/zero-ex/contracts/src/vendor/ITakerCallback.sol index a84108a68d..9ada07755b 100644 --- a/contracts/zero-ex/contracts/src/vendor/ITakerCallback.sol +++ b/contracts/zero-ex/contracts/src/vendor/ITakerCallback.sol @@ -20,9 +20,7 @@ pragma solidity ^0.6; pragma experimental ABIEncoderV2; - interface ITakerCallback { - /// @dev A taker callback function invoked in ERC721OrdersFeature and /// ERC1155OrdersFeature between the maker -> taker transfer and /// the taker -> maker transfer. @@ -31,10 +29,5 @@ interface ITakerCallback { /// @param callbackData Arbitrary data used by this callback. /// @return success The selector of this function, /// indicating that the callback succeeded. - function zeroExTakerCallback( - bytes32 orderHash, - bytes calldata callbackData - ) - external - returns (bytes4 success); + function zeroExTakerCallback(bytes32 orderHash, bytes calldata callbackData) external returns (bytes4 success); } diff --git a/contracts/zero-ex/contracts/src/vendor/IUniswapV2Pair.sol b/contracts/zero-ex/contracts/src/vendor/IUniswapV2Pair.sol index 76deb4347d..88bb97daee 100644 --- a/contracts/zero-ex/contracts/src/vendor/IUniswapV2Pair.sol +++ b/contracts/zero-ex/contracts/src/vendor/IUniswapV2Pair.sol @@ -19,7 +19,6 @@ pragma solidity ^0.6.12; - interface IUniswapV2Pair { event Swap( address indexed sender, @@ -31,8 +30,8 @@ interface IUniswapV2Pair { ); function swap( - uint amount0Out, - uint amount1Out, + uint256 amount0Out, + uint256 amount1Out, address to, bytes calldata data ) external; diff --git a/contracts/zero-ex/contracts/src/vendor/IUniswapV3Pool.sol b/contracts/zero-ex/contracts/src/vendor/IUniswapV3Pool.sol index b173b1ad93..a1d77b7ca4 100644 --- a/contracts/zero-ex/contracts/src/vendor/IUniswapV3Pool.sol +++ b/contracts/zero-ex/contracts/src/vendor/IUniswapV3Pool.sol @@ -19,9 +19,7 @@ pragma solidity ^0.6.12; - 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 @@ -38,7 +36,5 @@ interface IUniswapV3Pool { int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data - ) - external - returns (int256 amount0, int256 amount1); + ) external returns (int256 amount0, int256 amount1); } diff --git a/contracts/zero-ex/contracts/src/vendor/v3/IERC20Bridge.sol b/contracts/zero-ex/contracts/src/vendor/v3/IERC20Bridge.sol index 5f5d16ce4c..2fc98101de 100644 --- a/contracts/zero-ex/contracts/src/vendor/v3/IERC20Bridge.sol +++ b/contracts/zero-ex/contracts/src/vendor/v3/IERC20Bridge.sol @@ -20,7 +20,6 @@ pragma solidity ^0.6.5; interface IERC20Bridge { - /// @dev Emitted when a trade occurs. /// @param inputToken The token the bridge is converting from. /// @param outputToken The token the bridge is converting to. @@ -50,7 +49,5 @@ interface IERC20Bridge { address to, uint256 amount, bytes calldata bridgeData - ) - external - returns (bytes4 success); + ) external returns (bytes4 success); } diff --git a/contracts/zero-ex/contracts/src/vendor/v3/IStaking.sol b/contracts/zero-ex/contracts/src/vendor/v3/IStaking.sol index aa6188817d..22517479e3 100644 --- a/contracts/zero-ex/contracts/src/vendor/v3/IStaking.sol +++ b/contracts/zero-ex/contracts/src/vendor/v3/IStaking.sol @@ -21,5 +21,10 @@ pragma solidity ^0.6.5; interface IStaking { function joinStakingPoolAsMaker(bytes32) external; - function payProtocolFee(address, address, uint256) external payable; + + function payProtocolFee( + address, + address, + uint256 + ) external payable; } diff --git a/contracts/zero-ex/contracts/test/ITestSimpleFunctionRegistryFeature.sol b/contracts/zero-ex/contracts/test/ITestSimpleFunctionRegistryFeature.sol index dec6c93d44..bb4824652d 100644 --- a/contracts/zero-ex/contracts/test/ITestSimpleFunctionRegistryFeature.sol +++ b/contracts/zero-ex/contracts/test/ITestSimpleFunctionRegistryFeature.sol @@ -20,7 +20,6 @@ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; - interface ITestSimpleFunctionRegistryFeature { function testFn() external view returns (uint256 id); } diff --git a/contracts/zero-ex/contracts/test/TestBridge.sol b/contracts/zero-ex/contracts/test/TestBridge.sol index 24a28b2895..718deca80d 100644 --- a/contracts/zero-ex/contracts/test/TestBridge.sol +++ b/contracts/zero-ex/contracts/test/TestBridge.sol @@ -19,16 +19,11 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../src/vendor/v3/IERC20Bridge.sol"; - -contract TestBridge is - IERC20Bridge -{ +contract TestBridge is IERC20Bridge { IERC20TokenV06 public immutable xAsset; IERC20TokenV06 public immutable yAsset; - constructor(IERC20TokenV06 xAsset_, IERC20TokenV06 yAsset_) - public - { + constructor(IERC20TokenV06 xAsset_, IERC20TokenV06 yAsset_) public { xAsset = xAsset_; yAsset = yAsset_; } @@ -45,21 +40,10 @@ contract TestBridge is address to, uint256 amount, bytes calldata /* bridgeData */ - ) - external - override - returns (bytes4 success) - { + ) external override returns (bytes4 success) { IERC20TokenV06 takerToken = tokenAddress == address(xAsset) ? yAsset : xAsset; uint256 takerTokenBalance = takerToken.balanceOf(address(this)); - emit ERC20BridgeTransfer( - address(takerToken), - tokenAddress, - takerTokenBalance, - amount, - from, - to - ); + emit ERC20BridgeTransfer(address(takerToken), tokenAddress, takerTokenBalance, amount, from, to); return 0xdecaf000; } } diff --git a/contracts/zero-ex/contracts/test/TestCallTarget.sol b/contracts/zero-ex/contracts/test/TestCallTarget.sol index b2908bf5df..cdbdb5bd1e 100644 --- a/contracts/zero-ex/contracts/test/TestCallTarget.sol +++ b/contracts/zero-ex/contracts/test/TestCallTarget.sol @@ -20,15 +20,8 @@ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; - contract TestCallTarget { - - event CallTargetCalled( - address context, - address sender, - bytes data, - uint256 value - ); + event CallTargetCalled(address context, address sender, bytes data, uint256 value); bytes4 private constant MAGIC_BYTES = 0x12345678; bytes private constant REVERTING_DATA = hex"1337"; @@ -37,12 +30,7 @@ contract TestCallTarget { if (keccak256(msg.data) == keccak256(REVERTING_DATA)) { revert("TestCallTarget/REVERT"); } - emit CallTargetCalled( - address(this), - msg.sender, - msg.data, - msg.value - ); + emit CallTargetCalled(address(this), msg.sender, msg.data, msg.value); bytes4 rval = MAGIC_BYTES; assembly { mstore(0, rval) diff --git a/contracts/zero-ex/contracts/test/TestDelegateCaller.sol b/contracts/zero-ex/contracts/test/TestDelegateCaller.sol index 56fecb48a7..4012e6e6ea 100644 --- a/contracts/zero-ex/contracts/test/TestDelegateCaller.sol +++ b/contracts/zero-ex/contracts/test/TestDelegateCaller.sol @@ -20,18 +20,16 @@ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; - contract TestDelegateCaller { - function executeDelegateCall( - address target, - bytes calldata callData - ) - external - { + function executeDelegateCall(address target, bytes calldata callData) external { (bool success, bytes memory resultData) = target.delegatecall(callData); if (!success) { - assembly { revert(add(resultData, 32), mload(resultData)) } + assembly { + revert(add(resultData, 32), mload(resultData)) + } + } + assembly { + return(add(resultData, 32), mload(resultData)) } - assembly { return(add(resultData, 32), mload(resultData)) } } } diff --git a/contracts/zero-ex/contracts/test/TestFeeCollectorController.sol b/contracts/zero-ex/contracts/test/TestFeeCollectorController.sol index 58ad25fac5..a3ee26fae4 100644 --- a/contracts/zero-ex/contracts/test/TestFeeCollectorController.sol +++ b/contracts/zero-ex/contracts/test/TestFeeCollectorController.sol @@ -20,10 +20,8 @@ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; - /// @dev FeeCollectorControllerContract-like contract with a null init code hash. // Does not implement anything else, so finalization will fail. contract TestFeeCollectorController { - bytes32 public FEE_COLLECTOR_INIT_CODE_HASH = 0; } diff --git a/contracts/zero-ex/contracts/test/TestFeeRecipient.sol b/contracts/zero-ex/contracts/test/TestFeeRecipient.sol index 359e57aaa6..e5f25b32c6 100644 --- a/contracts/zero-ex/contracts/test/TestFeeRecipient.sol +++ b/contracts/zero-ex/contracts/test/TestFeeRecipient.sol @@ -20,18 +20,14 @@ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; - contract TestFeeRecipient { - bytes4 constant private SUCCESS = this.receiveZeroExFeeCallback.selector; - bytes4 constant private FAILURE = 0xdeadbeef; + bytes4 private constant SUCCESS = this.receiveZeroExFeeCallback.selector; + bytes4 private constant FAILURE = 0xdeadbeef; - uint256 constant private TRIGGER_REVERT = 333; - uint256 constant private TRIGGER_FAILURE = 666; + uint256 private constant TRIGGER_REVERT = 333; + uint256 private constant TRIGGER_FAILURE = 666; - event FeeReceived( - address tokenAddress, - uint256 amount - ); + event FeeReceived(address tokenAddress, uint256 amount); receive() external payable {} @@ -39,10 +35,7 @@ contract TestFeeRecipient { address tokenAddress, uint256 amount, bytes calldata /* feeData */ - ) - external - returns (bytes4 success) - { + ) external returns (bytes4 success) { emit FeeReceived(tokenAddress, amount); if (amount == TRIGGER_REVERT) { revert("TestFeeRecipient::receiveZeroExFeeCallback/REVERT"); diff --git a/contracts/zero-ex/contracts/test/TestFillQuoteTransformerBridge.sol b/contracts/zero-ex/contracts/test/TestFillQuoteTransformerBridge.sol index cb9d9a59a8..c0245bbd7b 100644 --- a/contracts/zero-ex/contracts/test/TestFillQuoteTransformerBridge.sol +++ b/contracts/zero-ex/contracts/test/TestFillQuoteTransformerBridge.sol @@ -24,28 +24,20 @@ import "@0x/contracts-utils/contracts/src/v06/LibMathV06.sol"; import "../src/vendor/v3/IERC20Bridge.sol"; import "./tokens/TestMintableERC20Token.sol"; - contract TestFillQuoteTransformerBridge { - uint256 private constant REVERT_AMOUNT = 0xdeadbeef; function sellTokenForToken( - address /* takerToken */, + address, /* takerToken */ address makerToken, address recipient, - uint256 /* minBuyAmount */, + uint256, /* minBuyAmount */ bytes calldata auxiliaryData - ) - external - returns (uint256 boughtAmount) - { + ) external returns (uint256 boughtAmount) { boughtAmount = abi.decode(auxiliaryData, (uint256)); if (REVERT_AMOUNT == boughtAmount) { revert("REVERT_AMOUNT"); } - TestMintableERC20Token(makerToken).mint( - recipient, - boughtAmount - ); + TestMintableERC20Token(makerToken).mint(recipient, boughtAmount); } } diff --git a/contracts/zero-ex/contracts/test/TestFillQuoteTransformerExchange.sol b/contracts/zero-ex/contracts/test/TestFillQuoteTransformerExchange.sol index 26294cc990..d971560003 100644 --- a/contracts/zero-ex/contracts/test/TestFillQuoteTransformerExchange.sol +++ b/contracts/zero-ex/contracts/test/TestFillQuoteTransformerExchange.sol @@ -27,10 +27,9 @@ import "./tokens/TestMintableERC20Token.sol"; import "../src/features/libs/LibNativeOrder.sol"; import "../src/features/libs/LibSignature.sol"; - contract TestFillQuoteTransformerExchange { - - bytes32 public constant EIP712_EXCHANGE_DOMAIN_HASH = 0xaa81d881b1adbbf115e15b849cb9cdc643cad3c6a90f30eb505954af943247e6; + bytes32 public constant EIP712_EXCHANGE_DOMAIN_HASH = + 0xaa81d881b1adbbf115e15b849cb9cdc643cad3c6a90f30eb505954af943247e6; uint256 private constant REVERT_AMOUNT = 0xdeadbeef; uint256 private constant PROTOCOL_FEE_MULTIPLIER = 1337; @@ -40,18 +39,14 @@ contract TestFillQuoteTransformerExchange { LibNativeOrder.LimitOrder calldata order, LibSignature.Signature calldata signature, uint128 takerTokenFillAmount - ) - external - payable - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + ) external payable returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { // The r field of the signature is the pre-filled amount. uint128 takerTokenPreFilledAmount = uint128(uint256(signature.r)); if (REVERT_AMOUNT == takerTokenPreFilledAmount) { revert("REVERT_AMOUNT"); } if (takerTokenPreFilledAmount >= order.takerAmount) { - revert('FILLED'); + revert("FILLED"); } uint256 protocolFee = PROTOCOL_FEE_MULTIPLIER * tx.gasprice; // Return excess protocol fee. @@ -62,26 +57,17 @@ contract TestFillQuoteTransformerExchange { ); // Take taker tokens. - order.takerToken.transferFrom( - msg.sender, - order.maker, - takerTokenFilledAmount - ); + order.takerToken.transferFrom(msg.sender, order.maker, takerTokenFilledAmount); // Mint maker tokens. makerTokenFilledAmount = LibSafeMathV06.safeDowncastToUint128( - uint256(takerTokenFilledAmount) - * uint256(order.makerAmount) - / uint256(order.takerAmount) + (uint256(takerTokenFilledAmount) * uint256(order.makerAmount)) / uint256(order.takerAmount) ); - TestMintableERC20Token(address(order.makerToken)) - .mint(msg.sender, makerTokenFilledAmount); + TestMintableERC20Token(address(order.makerToken)).mint(msg.sender, makerTokenFilledAmount); // Take taker token fee. uint128 takerFee = LibSafeMathV06.safeDowncastToUint128( - uint256(takerTokenFilledAmount) - * uint256(order.takerTokenFeeAmount) - / uint256(order.takerAmount) + (uint256(takerTokenFilledAmount) * uint256(order.takerTokenFeeAmount)) / uint256(order.takerAmount) ); order.takerToken.transferFrom(msg.sender, order.feeRecipient, takerFee); } @@ -90,18 +76,14 @@ contract TestFillQuoteTransformerExchange { LibNativeOrder.RfqOrder calldata order, LibSignature.Signature calldata signature, uint128 takerTokenFillAmount - ) - external - payable - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + ) external payable returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { // The r field of the signature is the pre-filled amount. uint128 takerTokenPreFilledAmount = uint128(uint256(signature.r)); if (REVERT_AMOUNT == takerTokenPreFilledAmount) { revert("REVERT_AMOUNT"); } if (takerTokenPreFilledAmount >= order.takerAmount) { - revert('FILLED'); + revert("FILLED"); } takerTokenFilledAmount = LibSafeMathV06.min128( order.takerAmount - takerTokenPreFilledAmount, @@ -109,35 +91,20 @@ contract TestFillQuoteTransformerExchange { ); // Take taker tokens. - order.takerToken.transferFrom( - msg.sender, - order.maker, - takerTokenFilledAmount - ); + order.takerToken.transferFrom(msg.sender, order.maker, takerTokenFilledAmount); // Mint maker tokens. makerTokenFilledAmount = LibSafeMathV06.safeDowncastToUint128( - uint256(takerTokenFilledAmount) - * uint256(order.makerAmount) - / uint256(order.takerAmount) + (uint256(takerTokenFilledAmount) * uint256(order.makerAmount)) / uint256(order.takerAmount) ); - TestMintableERC20Token(address(order.makerToken)) - .mint(msg.sender, makerTokenFilledAmount); + TestMintableERC20Token(address(order.makerToken)).mint(msg.sender, makerTokenFilledAmount); } - function getProtocolFeeMultiplier() - external - pure - returns (uint256) - { + function getProtocolFeeMultiplier() external pure returns (uint256) { return PROTOCOL_FEE_MULTIPLIER; } - function getLimitOrderHash(LibNativeOrder.LimitOrder calldata order) - external - pure - returns (bytes32) - { + function getLimitOrderHash(LibNativeOrder.LimitOrder calldata order) external pure returns (bytes32) { return bytes32(order.salt); } } diff --git a/contracts/zero-ex/contracts/test/TestFillQuoteTransformerHost.sol b/contracts/zero-ex/contracts/test/TestFillQuoteTransformerHost.sol index dacde4f22b..c406975203 100644 --- a/contracts/zero-ex/contracts/test/TestFillQuoteTransformerHost.sol +++ b/contracts/zero-ex/contracts/test/TestFillQuoteTransformerHost.sol @@ -24,10 +24,7 @@ import "../src/transformers/IERC20Transformer.sol"; import "./tokens/TestMintableERC20Token.sol"; import "./TestTransformerHost.sol"; - -contract TestFillQuoteTransformerHost is - TestTransformerHost -{ +contract TestFillQuoteTransformerHost is TestTransformerHost { function executeTransform( IERC20Transformer transformer, TestMintableERC20Token inputToken, @@ -35,21 +32,14 @@ contract TestFillQuoteTransformerHost is address payable sender, address payable recipient, bytes calldata data - ) - external - payable - { + ) external payable { if (inputTokenAmount != 0) { inputToken.mint(address(this), inputTokenAmount); } // Have to make this call externally because transformers aren't payable. this.rawExecuteTransform( transformer, - IERC20Transformer.TransformContext({ - sender: sender, - recipient: recipient, - data: data - }) + IERC20Transformer.TransformContext({sender: sender, recipient: recipient, data: data}) ); } } diff --git a/contracts/zero-ex/contracts/test/TestFixinProtocolFees.sol b/contracts/zero-ex/contracts/test/TestFixinProtocolFees.sol index cd7afd7ac1..be7bc87260 100644 --- a/contracts/zero-ex/contracts/test/TestFixinProtocolFees.sol +++ b/contracts/zero-ex/contracts/test/TestFixinProtocolFees.sol @@ -22,49 +22,29 @@ pragma experimental ABIEncoderV2; import "../src/fixins/FixinProtocolFees.sol"; -contract TestFixinProtocolFees is - FixinProtocolFees -{ +contract TestFixinProtocolFees is FixinProtocolFees { constructor( IEtherTokenV06 weth, IStaking staking, FeeCollectorController feeCollectorController, uint32 protocolFeeMultiplier - ) - public - FixinProtocolFees(weth, staking, feeCollectorController, protocolFeeMultiplier) - { + ) public FixinProtocolFees(weth, staking, feeCollectorController, protocolFeeMultiplier) { // solhint-disalbe no-empty-blocks } - function collectProtocolFee(bytes32 poolId) - external - payable - { + function collectProtocolFee(bytes32 poolId) external payable { _collectProtocolFee(poolId); } - function transferFeesForPool(bytes32 poolId) - external - { + function transferFeesForPool(bytes32 poolId) external { _transferFeesForPool(poolId); } - function getFeeCollector( - bytes32 poolId - ) - external - view - returns (FeeCollector) - { + function getFeeCollector(bytes32 poolId) external view returns (FeeCollector) { return _getFeeCollector(poolId); } - function getSingleProtocolFee() - external - view - returns (uint256 protocolFeeAmount) - { + function getSingleProtocolFee() external view returns (uint256 protocolFeeAmount) { return _getSingleProtocolFee(); } } diff --git a/contracts/zero-ex/contracts/test/TestFixinTokenSpender.sol b/contracts/zero-ex/contracts/test/TestFixinTokenSpender.sol index 3d01401abe..d8ec2e3aec 100644 --- a/contracts/zero-ex/contracts/test/TestFixinTokenSpender.sol +++ b/contracts/zero-ex/contracts/test/TestFixinTokenSpender.sol @@ -23,9 +23,7 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../src/fixins/FixinTokenSpender.sol"; -contract TestFixinTokenSpender is - FixinTokenSpender -{ +contract TestFixinTokenSpender is FixinTokenSpender { constructor() public {} function transferERC20TokensFrom( @@ -33,32 +31,13 @@ contract TestFixinTokenSpender is address owner, address to, uint256 amount - ) - external - { - _transferERC20TokensFrom( - token, - owner, - to, - amount - ); + ) external { + _transferERC20TokensFrom(token, owner, to, amount); } - event FallbackCalled( - address token, - address owner, - address to, - uint256 amount - ); + event FallbackCalled(address token, address owner, address to, uint256 amount); - function getSpendableERC20BalanceOf( - IERC20TokenV06 token, - address owner - ) - external - view - returns (uint256) - { + function getSpendableERC20BalanceOf(IERC20TokenV06 token, address owner) external view returns (uint256) { return _getSpendableERC20BalanceOf(token, owner); } } diff --git a/contracts/zero-ex/contracts/test/TestFullMigration.sol b/contracts/zero-ex/contracts/test/TestFullMigration.sol index c9a280da4b..f204672e66 100644 --- a/contracts/zero-ex/contracts/test/TestFullMigration.sol +++ b/contracts/zero-ex/contracts/test/TestFullMigration.sol @@ -23,10 +23,7 @@ pragma experimental ABIEncoderV2; import "../src/ZeroEx.sol"; import "../src/migrations/FullMigration.sol"; - -contract TestFullMigration is - FullMigration -{ +contract TestFullMigration is FullMigration { address public dieRecipient; // solhint-disable-next-line no-empty-blocks diff --git a/contracts/zero-ex/contracts/test/TestInitialMigration.sol b/contracts/zero-ex/contracts/test/TestInitialMigration.sol index d71a1f2762..2edbef8011 100644 --- a/contracts/zero-ex/contracts/test/TestInitialMigration.sol +++ b/contracts/zero-ex/contracts/test/TestInitialMigration.sol @@ -24,10 +24,7 @@ import "../src/ZeroEx.sol"; import "../src/features/interfaces/IBootstrapFeature.sol"; import "../src/migrations/InitialMigration.sol"; - -contract TestInitialMigration is - InitialMigration -{ +contract TestInitialMigration is InitialMigration { address public bootstrapFeature; address public dieRecipient; @@ -38,16 +35,12 @@ contract TestInitialMigration is IBootstrapFeature(address(zeroEx)).bootstrap(address(this), new bytes(0)); } - function bootstrap(address owner, BootstrapFeatures memory features) - public - override - returns (bytes4 success) - { + function bootstrap(address owner, BootstrapFeatures memory features) public override returns (bytes4 success) { success = InitialMigration.bootstrap(owner, features); // Snoop the bootstrap feature contract. - bootstrapFeature = - ZeroEx(address(uint160(address(this)))) - .getFunctionImplementation(IBootstrapFeature.bootstrap.selector); + bootstrapFeature = ZeroEx(address(uint160(address(this)))).getFunctionImplementation( + IBootstrapFeature.bootstrap.selector + ); } function die(address payable ethRecipient) public override { diff --git a/contracts/zero-ex/contracts/test/TestLibNativeOrder.sol b/contracts/zero-ex/contracts/test/TestLibNativeOrder.sol index b456403f8f..6499a24175 100644 --- a/contracts/zero-ex/contracts/test/TestLibNativeOrder.sol +++ b/contracts/zero-ex/contracts/test/TestLibNativeOrder.sol @@ -4,9 +4,7 @@ pragma experimental ABIEncoderV2; import "../src/features/libs/LibNativeOrder.sol"; - contract TestLibNativeOrder { - function getLimitOrderStructHash(LibNativeOrder.LimitOrder calldata order) external pure @@ -15,11 +13,7 @@ contract TestLibNativeOrder { return LibNativeOrder.getLimitOrderStructHash(order); } - function getRfqOrderStructHash(LibNativeOrder.RfqOrder calldata order) - external - pure - returns (bytes32 structHash) - { + function getRfqOrderStructHash(LibNativeOrder.RfqOrder calldata order) external pure returns (bytes32 structHash) { return LibNativeOrder.getRfqOrderStructHash(order); } } diff --git a/contracts/zero-ex/contracts/test/TestLibSignature.sol b/contracts/zero-ex/contracts/test/TestLibSignature.sol index b79c6da719..7935a7e6de 100644 --- a/contracts/zero-ex/contracts/test/TestLibSignature.sol +++ b/contracts/zero-ex/contracts/test/TestLibSignature.sol @@ -22,9 +22,7 @@ pragma experimental ABIEncoderV2; import "../src/features/libs/LibSignature.sol"; - contract TestLibSignature { - function getSignerOfHash(bytes32 hash, LibSignature.Signature calldata signature) external pure diff --git a/contracts/zero-ex/contracts/test/TestMetaTransactionsNativeOrdersFeature.sol b/contracts/zero-ex/contracts/test/TestMetaTransactionsNativeOrdersFeature.sol index 165fffd66e..3ea0173ad8 100644 --- a/contracts/zero-ex/contracts/test/TestMetaTransactionsNativeOrdersFeature.sol +++ b/contracts/zero-ex/contracts/test/TestMetaTransactionsNativeOrdersFeature.sol @@ -24,10 +24,7 @@ import "../src/features/interfaces/IMetaTransactionsFeature.sol"; import "../src/features/NativeOrdersFeature.sol"; import "./TestFeeCollectorController.sol"; - -contract TestMetaTransactionsNativeOrdersFeature is - NativeOrdersFeature -{ +contract TestMetaTransactionsNativeOrdersFeature is NativeOrdersFeature { constructor() public NativeOrdersFeature( @@ -56,12 +53,7 @@ contract TestMetaTransactionsNativeOrdersFeature is uint128 takerTokenFillAmount, address taker, address sender - ) - public - override - payable - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + ) public payable override returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { emit FillLimitOrderCalled( order, signature.signatureType, @@ -90,13 +82,9 @@ contract TestMetaTransactionsNativeOrdersFeature is LibSignature.Signature memory signature, uint128 takerTokenFillAmount, address taker, - bool /* useSelfBalance */, + bool, /* useSelfBalance */ address /* recipient */ - ) - public - override - returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) - { + ) public override returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) { emit FillRfqOrderCalled( order, signature.signatureType, diff --git a/contracts/zero-ex/contracts/test/TestMetaTransactionsTransformERC20Feature.sol b/contracts/zero-ex/contracts/test/TestMetaTransactionsTransformERC20Feature.sol index fe19ef34d9..a5e9540b05 100644 --- a/contracts/zero-ex/contracts/test/TestMetaTransactionsTransformERC20Feature.sol +++ b/contracts/zero-ex/contracts/test/TestMetaTransactionsTransformERC20Feature.sol @@ -23,10 +23,7 @@ pragma experimental ABIEncoderV2; import "../src/features/interfaces/IMetaTransactionsFeature.sol"; import "../src/features/TransformERC20Feature.sol"; - -contract TestMetaTransactionsTransformERC20Feature is - TransformERC20Feature -{ +contract TestMetaTransactionsTransformERC20Feature is TransformERC20Feature { event TransformERC20Called( address sender, uint256 value, @@ -42,8 +39,8 @@ contract TestMetaTransactionsTransformERC20Feature is function _transformERC20(TransformERC20Args memory args) public - override payable + override returns (uint256 outputTokenAmount) { if (msg.value == 555) { @@ -51,7 +48,7 @@ contract TestMetaTransactionsTransformERC20Feature is } if (msg.value == 666) { - revert('FAIL'); + revert("FAIL"); } if (msg.value == 777) { @@ -77,8 +74,8 @@ contract TestMetaTransactionsTransformERC20Feature is if (msg.value == 888) { // Try to reenter `batchExecuteMetaTransactions()` - IMetaTransactionsFeature.MetaTransactionData[] memory mtxs = - new IMetaTransactionsFeature.MetaTransactionData[](1); + IMetaTransactionsFeature.MetaTransactionData[] + memory mtxs = new IMetaTransactionsFeature.MetaTransactionData[](1); LibSignature.Signature[] memory signatures = new LibSignature.Signature[](1); mtxs[0] = IMetaTransactionsFeature.MetaTransactionData({ signer: address(0), @@ -92,10 +89,7 @@ contract TestMetaTransactionsTransformERC20Feature is feeToken: IERC20TokenV06(0), feeAmount: 0 }); - IMetaTransactionsFeature(address(this)).batchExecuteMetaTransactions( - mtxs, - signatures - ); + IMetaTransactionsFeature(address(this)).batchExecuteMetaTransactions(mtxs, signatures); } emit TransformERC20Called( diff --git a/contracts/zero-ex/contracts/test/TestMigrator.sol b/contracts/zero-ex/contracts/test/TestMigrator.sol index 26bb6d27a2..04024f974b 100644 --- a/contracts/zero-ex/contracts/test/TestMigrator.sol +++ b/contracts/zero-ex/contracts/test/TestMigrator.sol @@ -23,26 +23,16 @@ pragma experimental ABIEncoderV2; import "../src/migrations/LibMigrate.sol"; import "../src/features/interfaces/IOwnableFeature.sol"; - contract TestMigrator { - event TestMigrateCalled( - bytes callData, - address owner - ); + event TestMigrateCalled(bytes callData, address owner); function succeedingMigrate() external returns (bytes4 success) { - emit TestMigrateCalled( - msg.data, - IOwnableFeature(address(this)).owner() - ); + emit TestMigrateCalled(msg.data, IOwnableFeature(address(this)).owner()); return LibMigrate.MIGRATE_SUCCESS; } function failingMigrate() external returns (bytes4 success) { - emit TestMigrateCalled( - msg.data, - IOwnableFeature(address(this)).owner() - ); + emit TestMigrateCalled(msg.data, IOwnableFeature(address(this)).owner()); return 0xdeadbeef; } diff --git a/contracts/zero-ex/contracts/test/TestMintTokenERC20Transformer.sol b/contracts/zero-ex/contracts/test/TestMintTokenERC20Transformer.sol index 4d56580cc7..68193aae5c 100644 --- a/contracts/zero-ex/contracts/test/TestMintTokenERC20Transformer.sol +++ b/contracts/zero-ex/contracts/test/TestMintTokenERC20Transformer.sol @@ -25,10 +25,7 @@ import "../src/transformers/IERC20Transformer.sol"; import "../src/transformers/LibERC20Transformer.sol"; import "./tokens/TestMintableERC20Token.sol"; - -contract TestMintTokenERC20Transformer is - IERC20Transformer -{ +contract TestMintTokenERC20Transformer is IERC20Transformer { struct TransformData { IERC20TokenV06 inputToken; TestMintableERC20Token outputToken; @@ -47,11 +44,7 @@ contract TestMintTokenERC20Transformer is uint256 ethBalance ); - function transform(TransformContext calldata context) - external - override - returns (bytes4 success) - { + function transform(TransformContext calldata context) external override returns (bytes4 success) { TransformData memory data = abi.decode(context.data, (TransformData)); emit MintTransform( address(this), @@ -73,19 +66,10 @@ contract TestMintTokenERC20Transformer is // Mint output tokens. if (!LibERC20Transformer.isTokenETH(IERC20TokenV06(address(data.outputToken)))) { if (data.feeAmount > data.mintAmount) { - data.outputToken.burn( - context.recipient, - data.feeAmount - data.mintAmount - ); + data.outputToken.burn(context.recipient, data.feeAmount - data.mintAmount); } else { - data.outputToken.mint( - address(this), - data.mintAmount - ); - data.outputToken.burn( - context.recipient, - data.feeAmount - ); + data.outputToken.mint(address(this), data.mintAmount); + data.outputToken.burn(context.recipient, data.feeAmount); } } return LibERC20Transformer.TRANSFORMER_SUCCESS; diff --git a/contracts/zero-ex/contracts/test/TestNFTOrderPresigner.sol b/contracts/zero-ex/contracts/test/TestNFTOrderPresigner.sol index 14799fc239..0e986ff2f6 100644 --- a/contracts/zero-ex/contracts/test/TestNFTOrderPresigner.sol +++ b/contracts/zero-ex/contracts/test/TestNFTOrderPresigner.sol @@ -26,13 +26,10 @@ import "../src/vendor/IERC1155Token.sol"; import "../src/vendor/IERC721Token.sol"; import "../src/features/libs/LibNFTOrder.sol"; - contract TestNFTOrderPresigner { IZeroEx private immutable zeroEx; - constructor(IZeroEx _zeroEx) - public - { + constructor(IZeroEx _zeroEx) public { zeroEx = _zeroEx; } @@ -42,52 +39,35 @@ contract TestNFTOrderPresigner { uint256 id, uint256 value, bytes calldata data - ) - external - returns(bytes4 success) - { + ) external returns (bytes4 success) { return 0xf23a6e61; } - function approveERC721(IERC721Token token) - external - { + function approveERC721(IERC721Token token) external { token.setApprovalForAll(address(zeroEx), true); } - function approveERC1155(IERC1155Token token) - external - { + function approveERC1155(IERC1155Token token) external { token.setApprovalForAll(address(zeroEx), true); } - function approveERC20(IERC20TokenV06 token) - external - { + function approveERC20(IERC20TokenV06 token) external { token.approve(address(zeroEx), uint256(-1)); } - function preSignERC721Order(LibNFTOrder.ERC721Order calldata order) - external - { + function preSignERC721Order(LibNFTOrder.ERC721Order calldata order) external { zeroEx.preSignERC721Order(order); } - function preSignERC1155Order(LibNFTOrder.ERC1155Order calldata order) - external - { + function preSignERC1155Order(LibNFTOrder.ERC1155Order calldata order) external { zeroEx.preSignERC1155Order(order); } - function cancelERC721Order(uint256 orderNonce) - external - { + function cancelERC721Order(uint256 orderNonce) external { zeroEx.cancelERC721Order(orderNonce); } - function cancelERC1155Order(uint256 orderNonce) - external - { + function cancelERC1155Order(uint256 orderNonce) external { zeroEx.cancelERC1155Order(orderNonce); } } diff --git a/contracts/zero-ex/contracts/test/TestNativeOrdersFeature.sol b/contracts/zero-ex/contracts/test/TestNativeOrdersFeature.sol index b2db91d17b..16ce63284e 100644 --- a/contracts/zero-ex/contracts/test/TestNativeOrdersFeature.sol +++ b/contracts/zero-ex/contracts/test/TestNativeOrdersFeature.sol @@ -5,9 +5,7 @@ pragma experimental ABIEncoderV2; import "../src/features/NativeOrdersFeature.sol"; import "./TestFeeCollectorController.sol"; -contract TestNativeOrdersFeature is - NativeOrdersFeature -{ +contract TestNativeOrdersFeature is NativeOrdersFeature { constructor( address zeroExAddress, IEtherTokenV06 weth, diff --git a/contracts/zero-ex/contracts/test/TestOrderSignerRegistryWithContractWallet.sol b/contracts/zero-ex/contracts/test/TestOrderSignerRegistryWithContractWallet.sol index 6bd23aff34..d5412e42d4 100644 --- a/contracts/zero-ex/contracts/test/TestOrderSignerRegistryWithContractWallet.sol +++ b/contracts/zero-ex/contracts/test/TestOrderSignerRegistryWithContractWallet.sol @@ -25,20 +25,13 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../src/IZeroEx.sol"; contract TestOrderSignerRegistryWithContractWallet is OwnableV06 { - IZeroEx immutable zeroex; constructor(IZeroEx _zeroex) public { zeroex = _zeroex; } - function registerAllowedOrderSigner( - address signer, - bool allowed - ) - external - onlyOwner - { + function registerAllowedOrderSigner(address signer, bool allowed) external onlyOwner { zeroex.registerAllowedOrderSigner(signer, allowed); } @@ -46,10 +39,7 @@ contract TestOrderSignerRegistryWithContractWallet is OwnableV06 { IERC20TokenV06 token, address spender, uint256 value - ) - external - onlyOwner - { + ) external onlyOwner { token.approve(spender, value); } } diff --git a/contracts/zero-ex/contracts/test/TestPermissionlessTransformerDeployerSuicidal.sol b/contracts/zero-ex/contracts/test/TestPermissionlessTransformerDeployerSuicidal.sol index 95ed6ae3f5..f3ae3e7795 100644 --- a/contracts/zero-ex/contracts/test/TestPermissionlessTransformerDeployerSuicidal.sol +++ b/contracts/zero-ex/contracts/test/TestPermissionlessTransformerDeployerSuicidal.sol @@ -20,7 +20,6 @@ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; - contract TestPermissionlessTransformerDeployerSuicidal { function kill() external { selfdestruct(msg.sender); diff --git a/contracts/zero-ex/contracts/test/TestPermissionlessTransformerDeployerTransformer.sol b/contracts/zero-ex/contracts/test/TestPermissionlessTransformerDeployerTransformer.sol index 0eef9bb092..f5455b4600 100644 --- a/contracts/zero-ex/contracts/test/TestPermissionlessTransformerDeployerTransformer.sol +++ b/contracts/zero-ex/contracts/test/TestPermissionlessTransformerDeployerTransformer.sol @@ -22,16 +22,12 @@ pragma experimental ABIEncoderV2; import "../src/transformers/LibERC20Transformer.sol"; - contract TestPermissionlessTransformerDeployerTransformer { uint256 public constant CONSTRUCTOR_FAIL_VALUE = 3333; address payable public immutable deployer; constructor() public payable { deployer = msg.sender; - require( - msg.value != CONSTRUCTOR_FAIL_VALUE, - "TestTransformerDeployerTransformer/CONSTRUCTOR_FAIL" - ); + require(msg.value != CONSTRUCTOR_FAIL_VALUE, "TestTransformerDeployerTransformer/CONSTRUCTOR_FAIL"); } } diff --git a/contracts/zero-ex/contracts/test/TestPropertyValidator.sol b/contracts/zero-ex/contracts/test/TestPropertyValidator.sol index d2e1ce1609..4993911302 100644 --- a/contracts/zero-ex/contracts/test/TestPropertyValidator.sol +++ b/contracts/zero-ex/contracts/test/TestPropertyValidator.sol @@ -20,20 +20,12 @@ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; - contract TestPropertyValidator { - function validateProperty( address tokenAddress, uint256 tokenId, bytes calldata propertyData - ) - external - view - { - require( - propertyData.length > 0, - "TestPropertyValidator::validateProperty/REVERT" - ); + ) external view { + require(propertyData.length > 0, "TestPropertyValidator::validateProperty/REVERT"); } } diff --git a/contracts/zero-ex/contracts/test/TestRfqOriginRegistration.sol b/contracts/zero-ex/contracts/test/TestRfqOriginRegistration.sol index 0f452112dd..329de09d7e 100644 --- a/contracts/zero-ex/contracts/test/TestRfqOriginRegistration.sol +++ b/contracts/zero-ex/contracts/test/TestRfqOriginRegistration.sol @@ -27,9 +27,7 @@ contract TestRfqOriginRegistration { INativeOrdersFeature feature, address[] memory origins, bool allowed - ) - external - { + ) external { feature.registerAllowedRfqOrigins(origins, allowed); } } diff --git a/contracts/zero-ex/contracts/test/TestSimpleFunctionRegistryFeatureImpl1.sol b/contracts/zero-ex/contracts/test/TestSimpleFunctionRegistryFeatureImpl1.sol index e0ac5098f0..bfea8eaa05 100644 --- a/contracts/zero-ex/contracts/test/TestSimpleFunctionRegistryFeatureImpl1.sol +++ b/contracts/zero-ex/contracts/test/TestSimpleFunctionRegistryFeatureImpl1.sol @@ -22,15 +22,8 @@ pragma experimental ABIEncoderV2; import "../src/fixins/FixinCommon.sol"; - -contract TestSimpleFunctionRegistryFeatureImpl1 is - FixinCommon -{ - function testFn() - external - pure - returns (uint256 id) - { +contract TestSimpleFunctionRegistryFeatureImpl1 is FixinCommon { + function testFn() external pure returns (uint256 id) { return 1337; } } diff --git a/contracts/zero-ex/contracts/test/TestSimpleFunctionRegistryFeatureImpl2.sol b/contracts/zero-ex/contracts/test/TestSimpleFunctionRegistryFeatureImpl2.sol index f4efb6a2d2..4e6644f52c 100644 --- a/contracts/zero-ex/contracts/test/TestSimpleFunctionRegistryFeatureImpl2.sol +++ b/contracts/zero-ex/contracts/test/TestSimpleFunctionRegistryFeatureImpl2.sol @@ -22,15 +22,8 @@ pragma experimental ABIEncoderV2; import "../src/fixins/FixinCommon.sol"; - -contract TestSimpleFunctionRegistryFeatureImpl2 is - FixinCommon -{ - function testFn() - external - pure - returns (uint256 id) - { +contract TestSimpleFunctionRegistryFeatureImpl2 is FixinCommon { + function testFn() external pure returns (uint256 id) { return 1338; } } diff --git a/contracts/zero-ex/contracts/test/TestStaking.sol b/contracts/zero-ex/contracts/test/TestStaking.sol index 52bbf383e1..a271110130 100644 --- a/contracts/zero-ex/contracts/test/TestStaking.sol +++ b/contracts/zero-ex/contracts/test/TestStaking.sol @@ -40,10 +40,7 @@ contract TestStaking { address makerAddress, address payerAddress, uint256 amount - ) - external - payable - { + ) external payable { require(weth.transferFrom(payerAddress, address(this), amount)); balanceForPool[poolForMaker[makerAddress]] += amount; } diff --git a/contracts/zero-ex/contracts/test/TestTransformERC20.sol b/contracts/zero-ex/contracts/test/TestTransformERC20.sol index 54a5c93217..4408a4e6ac 100644 --- a/contracts/zero-ex/contracts/test/TestTransformERC20.sol +++ b/contracts/zero-ex/contracts/test/TestTransformERC20.sol @@ -22,10 +22,7 @@ pragma experimental ABIEncoderV2; import "../src/features/TransformERC20Feature.sol"; - -contract TestTransformERC20 is - TransformERC20Feature -{ +contract TestTransformERC20 is TransformERC20Feature { modifier onlySelf() override { _; } diff --git a/contracts/zero-ex/contracts/test/TestTransformerBase.sol b/contracts/zero-ex/contracts/test/TestTransformerBase.sol index 92e4a680da..7342a2f5a6 100644 --- a/contracts/zero-ex/contracts/test/TestTransformerBase.sol +++ b/contracts/zero-ex/contracts/test/TestTransformerBase.sol @@ -24,16 +24,10 @@ import "../src/transformers/Transformer.sol"; import "../src/transformers/IERC20Transformer.sol"; import "../src/transformers/LibERC20Transformer.sol"; - -contract TestTransformerBase is - IERC20Transformer, - Transformer -{ - function transform(TransformContext calldata /* context */) - external - override - returns (bytes4 success) - { +contract TestTransformerBase is IERC20Transformer, Transformer { + function transform( + TransformContext calldata /* context */ + ) external override returns (bytes4 success) { return LibERC20Transformer.TRANSFORMER_SUCCESS; } } diff --git a/contracts/zero-ex/contracts/test/TestTransformerDeployerTransformer.sol b/contracts/zero-ex/contracts/test/TestTransformerDeployerTransformer.sol index 731ef630d8..5440c5e4de 100644 --- a/contracts/zero-ex/contracts/test/TestTransformerDeployerTransformer.sol +++ b/contracts/zero-ex/contracts/test/TestTransformerDeployerTransformer.sol @@ -22,18 +22,13 @@ pragma experimental ABIEncoderV2; import "../src/transformers/LibERC20Transformer.sol"; - contract TestTransformerDeployerTransformer { - uint256 public constant CONSTRUCTOR_FAIL_VALUE = 3333; address payable public immutable deployer; constructor() public payable { deployer = msg.sender; - require( - msg.value != CONSTRUCTOR_FAIL_VALUE, - "TestTransformerDeployerTransformer/CONSTRUCTOR_FAIL" - ); + require(msg.value != CONSTRUCTOR_FAIL_VALUE, "TestTransformerDeployerTransformer/CONSTRUCTOR_FAIL"); } modifier onlyDeployer() { @@ -41,18 +36,11 @@ contract TestTransformerDeployerTransformer { _; } - function die(address payable ethRecipient) - external - onlyDeployer - { + function die(address payable ethRecipient) external onlyDeployer { selfdestruct(ethRecipient); } - function isDeployedByDeployer(uint32 nonce) - external - view - returns (bool) - { + function isDeployedByDeployer(uint32 nonce) external view returns (bool) { return LibERC20Transformer.getDeployedAddress(deployer, nonce) == address(this); } } diff --git a/contracts/zero-ex/contracts/test/TestTransformerHost.sol b/contracts/zero-ex/contracts/test/TestTransformerHost.sol index 25976f7cb7..2151074a93 100644 --- a/contracts/zero-ex/contracts/test/TestTransformerHost.sol +++ b/contracts/zero-ex/contracts/test/TestTransformerHost.sol @@ -25,23 +25,16 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../src/transformers/IERC20Transformer.sol"; import "../src/transformers/LibERC20Transformer.sol"; - contract TestTransformerHost { - using LibERC20Transformer for IERC20TokenV06; using LibRichErrorsV06 for bytes; - function rawExecuteTransform( - IERC20Transformer transformer, - IERC20Transformer.TransformContext calldata context - ) + function rawExecuteTransform(IERC20Transformer transformer, IERC20Transformer.TransformContext calldata context) external { - (bool _success, bytes memory resultData) = - address(transformer).delegatecall(abi.encodeWithSelector( - transformer.transform.selector, - context - )); + (bool _success, bytes memory resultData) = address(transformer).delegatecall( + abi.encodeWithSelector(transformer.transform.selector, context) + ); if (!_success) { resultData.rrevert(); } diff --git a/contracts/zero-ex/contracts/test/TestUniswapV3Feature.sol b/contracts/zero-ex/contracts/test/TestUniswapV3Feature.sol index cbf9fe293d..870c5395f1 100644 --- a/contracts/zero-ex/contracts/test/TestUniswapV3Feature.sol +++ b/contracts/zero-ex/contracts/test/TestUniswapV3Feature.sol @@ -8,10 +8,7 @@ contract TestUniswapV3Feature is UniswapV3Feature { IEtherTokenV06 weth, address uniFactory, bytes32 poolInitCodeHash - ) - UniswapV3Feature(weth, uniFactory, poolInitCodeHash) - public - {} + ) public UniswapV3Feature(weth, uniFactory, poolInitCodeHash) {} receive() external payable {} } diff --git a/contracts/zero-ex/contracts/test/TestWethTransformerHost.sol b/contracts/zero-ex/contracts/test/TestWethTransformerHost.sol index b5c910c5af..02cd57d663 100644 --- a/contracts/zero-ex/contracts/test/TestWethTransformerHost.sol +++ b/contracts/zero-ex/contracts/test/TestWethTransformerHost.sol @@ -25,12 +25,10 @@ import "./tokens/TestMintableERC20Token.sol"; import "./TestTransformerHost.sol"; import "./tokens/TestWeth.sol"; - -contract TestWethTransformerHost is - TestTransformerHost -{ +contract TestWethTransformerHost is TestTransformerHost { // solhint-disable TestWeth private immutable _weth; + // solhint-enable constructor(TestWeth weth) public { @@ -41,21 +39,14 @@ contract TestWethTransformerHost is uint256 wethAmount, IERC20Transformer transformer, bytes calldata data - ) - external - payable - { + ) external payable { if (wethAmount != 0) { _weth.deposit{value: wethAmount}(); } // Have to make this call externally because transformers aren't payable. this.rawExecuteTransform( transformer, - IERC20Transformer.TransformContext({ - sender: msg.sender, - recipient: msg.sender, - data: data - }) + IERC20Transformer.TransformContext({sender: msg.sender, recipient: msg.sender, data: data}) ); } } diff --git a/contracts/zero-ex/contracts/test/TestZeroExFeature.sol b/contracts/zero-ex/contracts/test/TestZeroExFeature.sol index 94b240d661..7db0846092 100644 --- a/contracts/zero-ex/contracts/test/TestZeroExFeature.sol +++ b/contracts/zero-ex/contracts/test/TestZeroExFeature.sol @@ -23,33 +23,20 @@ pragma experimental ABIEncoderV2; import "../src/fixins/FixinCommon.sol"; import "../src/ZeroEx.sol"; - -contract TestZeroExFeature is - FixinCommon -{ +contract TestZeroExFeature is FixinCommon { event PayableFnCalled(uint256 value); event NotPayableFnCalled(); - function payableFn() - external - payable - { + function payableFn() external payable { emit PayableFnCalled(msg.value); } - function notPayableFn() - external - { + function notPayableFn() external { emit NotPayableFnCalled(); } // solhint-disable no-empty-blocks - function unimplmentedFn() - external - {} + function unimplmentedFn() external {} - function internalFn() - external - onlySelf - {} + function internalFn() external onlySelf {} } diff --git a/contracts/zero-ex/contracts/test/foundry/ContractTest.sol b/contracts/zero-ex/contracts/test/foundry/ContractTest.sol index 319c6de530..c405020662 100644 --- a/contracts/zero-ex/contracts/test/foundry/ContractTest.sol +++ b/contracts/zero-ex/contracts/test/foundry/ContractTest.sol @@ -25,6 +25,6 @@ contract ContractTest is Test { function setUp() public {} function testExample() public { - assertTrue(true); + assertTrue(true); } } diff --git a/contracts/zero-ex/contracts/test/integration/TestCurve.sol b/contracts/zero-ex/contracts/test/integration/TestCurve.sol index 48110c625a..a5ea7e19ce 100644 --- a/contracts/zero-ex/contracts/test/integration/TestCurve.sol +++ b/contracts/zero-ex/contracts/test/integration/TestCurve.sol @@ -24,7 +24,6 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../tokens/TestMintableERC20Token.sol"; contract TestCurve { - event CurveCalled( uint256 value, bytes4 selector, @@ -50,10 +49,7 @@ contract TestCurve { IERC20TokenV06 sellToken_, TestMintableERC20Token buyToken_, uint256 buyAmount_ - ) - public - payable - { + ) public payable { sellToken = sellToken_; buyToken = buyToken_; buyAmount = buyAmount_; @@ -63,16 +59,13 @@ contract TestCurve { fallback() external payable { bytes4 selector = abi.decode(msg.data, (bytes4)); - bool shouldReturnBoughtAmount = - (selector & RETURN_BOUGHT_AMOUNT_SELECTOR_FLAG) != 0x0; + bool shouldReturnBoughtAmount = (selector & RETURN_BOUGHT_AMOUNT_SELECTOR_FLAG) != 0x0; bytes4 baseSelector = selector & 0xffff0000; require(baseSelector == BASE_SWAP_SELECTOR, "TestCurve/REVERT"); - ( - int128 fromCoinIdx, - int128 toCoinIdx, - uint256 sellAmount, - uint256 minBuyAmount - ) = abi.decode(msg.data[4:], (int128, int128, uint256, uint256)); + (int128 fromCoinIdx, int128 toCoinIdx, uint256 sellAmount, uint256 minBuyAmount) = abi.decode( + msg.data[4:], + (int128, int128, uint256, uint256) + ); if (fromCoinIdx == SELL_TOKEN_COIN_IDX) { sellToken.transferFrom(msg.sender, address(this), sellAmount); } @@ -81,20 +74,15 @@ contract TestCurve { } else if (toCoinIdx == ETH_COIN_IDX) { msg.sender.transfer(buyAmount); } - emit CurveCalled( - msg.value, - selector, - fromCoinIdx, - toCoinIdx, - sellAmount, - minBuyAmount - ); + emit CurveCalled(msg.value, selector, fromCoinIdx, toCoinIdx, sellAmount, minBuyAmount); if (shouldReturnBoughtAmount) { assembly { mstore(0, sload(buyAmount_slot)) return(0, 32) } } - assembly { return(0, 0) } + assembly { + return(0, 0) + } } } diff --git a/contracts/zero-ex/contracts/test/integration/TestLiquidityProvider.sol b/contracts/zero-ex/contracts/test/integration/TestLiquidityProvider.sol index 7110bc2d69..8c1dc6b972 100644 --- a/contracts/zero-ex/contracts/test/integration/TestLiquidityProvider.sol +++ b/contracts/zero-ex/contracts/test/integration/TestLiquidityProvider.sol @@ -22,7 +22,6 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; - contract TestLiquidityProvider { event SellTokenForToken( address inputToken, @@ -32,19 +31,9 @@ contract TestLiquidityProvider { uint256 inputTokenBalance ); - event SellEthForToken( - address outputToken, - address recipient, - uint256 minBuyAmount, - uint256 ethBalance - ); + event SellEthForToken(address outputToken, address recipient, uint256 minBuyAmount, uint256 ethBalance); - event SellTokenForEth( - address inputToken, - address recipient, - uint256 minBuyAmount, - uint256 inputTokenBalance - ); + event SellTokenForEth(address inputToken, address recipient, uint256 minBuyAmount, uint256 inputTokenBalance); receive() external payable {} @@ -62,10 +51,7 @@ contract TestLiquidityProvider { address recipient, uint256 minBuyAmount, bytes calldata // auxiliaryData - ) - external - returns (uint256) - { + ) external returns (uint256) { emit SellTokenForToken( inputToken, outputToken, @@ -88,16 +74,8 @@ contract TestLiquidityProvider { address recipient, uint256 minBuyAmount, bytes calldata // auxiliaryData - ) - external - returns (uint256) - { - emit SellEthForToken( - outputToken, - recipient, - minBuyAmount, - address(this).balance - ); + ) external returns (uint256) { + emit SellEthForToken(outputToken, recipient, minBuyAmount, address(this).balance); uint256 outputTokenBalance = IERC20TokenV06(outputToken).balanceOf(address(this)); IERC20TokenV06(outputToken).transfer(recipient, outputTokenBalance); } @@ -113,16 +91,8 @@ contract TestLiquidityProvider { address payable recipient, uint256 minBuyAmount, bytes calldata // auxiliaryData - ) - external - returns (uint256) - { - emit SellTokenForEth( - inputToken, - recipient, - minBuyAmount, - IERC20TokenV06(inputToken).balanceOf(address(this)) - ); + ) external returns (uint256) { + emit SellTokenForEth(inputToken, recipient, minBuyAmount, IERC20TokenV06(inputToken).balanceOf(address(this))); recipient.transfer(address(this).balance); } } diff --git a/contracts/zero-ex/contracts/test/integration/TestMooniswap.sol b/contracts/zero-ex/contracts/test/integration/TestMooniswap.sol index 49ecfdb5b0..900b345ac6 100644 --- a/contracts/zero-ex/contracts/test/integration/TestMooniswap.sol +++ b/contracts/zero-ex/contracts/test/integration/TestMooniswap.sol @@ -24,7 +24,6 @@ import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../tokens/TestMintableERC20Token.sol"; contract TestMooniswap { - event MooniswapCalled( uint256 value, IERC20TokenV06 sellToken, @@ -36,10 +35,7 @@ contract TestMooniswap { uint256 public nextBuyAmount; - function setNextBoughtAmount(uint256 amt) - external - payable - { + function setNextBoughtAmount(uint256 amt) external payable { nextBuyAmount = amt; } @@ -49,11 +45,7 @@ contract TestMooniswap { uint256 sellAmount, uint256 minBuyAmount, address referral - ) - external - payable - returns(uint256 boughtAmount) - { + ) external payable returns (uint256 boughtAmount) { emit MooniswapCalled( msg.value, sellToken, @@ -64,11 +56,11 @@ contract TestMooniswap { ); boughtAmount = nextBuyAmount; nextBuyAmount = 0; - require(boughtAmount >= minBuyAmount, 'UNDERBOUGHT'); + require(boughtAmount >= minBuyAmount, "UNDERBOUGHT"); if (sellToken != IERC20TokenV06(0)) { sellToken.transferFrom(msg.sender, address(this), sellAmount); } else { - require(sellAmount == msg.value, 'NOT_ENOUGH_ETH'); + require(sellAmount == msg.value, "NOT_ENOUGH_ETH"); } if (address(buyToken) == address(0)) { msg.sender.transfer(boughtAmount); diff --git a/contracts/zero-ex/contracts/test/integration/TestUniswapV2Factory.sol b/contracts/zero-ex/contracts/test/integration/TestUniswapV2Factory.sol index 4a311919ff..3c67d226cf 100644 --- a/contracts/zero-ex/contracts/test/integration/TestUniswapV2Factory.sol +++ b/contracts/zero-ex/contracts/test/integration/TestUniswapV2Factory.sol @@ -13,30 +13,18 @@ contract TestUniswapV2Factory { event PoolCreated(TestUniswapV2Pool pool); bytes32 public immutable POOL_INIT_CODE_HASH; - mapping (IERC20TokenV06 => mapping (IERC20TokenV06 => TestUniswapV2Pool)) public getPool; + mapping(IERC20TokenV06 => mapping(IERC20TokenV06 => TestUniswapV2Pool)) public getPool; CreationParameters public creationParameters; constructor() public { POOL_INIT_CODE_HASH = keccak256(type(TestUniswapV2Pool).creationCode); } - function createPool(IERC20TokenV06 tokenA, IERC20TokenV06 tokenB) - external - returns (TestUniswapV2Pool pool) - { - (IERC20TokenV06 token0, IERC20TokenV06 token1) = tokenA < tokenB - ? (tokenA, tokenB) - : (tokenB, tokenA); - require( - getPool[token0][token1] == TestUniswapV2Pool(0), - "TestUniswapV2Factory/POOL_ALREADY_EXISTS" - ); - creationParameters = CreationParameters({ - token0: token0, - token1: token1 - }); - pool = new TestUniswapV2Pool - { salt: keccak256(abi.encodePacked(token0, token1)) }(); + function createPool(IERC20TokenV06 tokenA, IERC20TokenV06 tokenB) external returns (TestUniswapV2Pool pool) { + (IERC20TokenV06 token0, IERC20TokenV06 token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); + require(getPool[token0][token1] == TestUniswapV2Pool(0), "TestUniswapV2Factory/POOL_ALREADY_EXISTS"); + creationParameters = CreationParameters({token0: token0, token1: token1}); + pool = new TestUniswapV2Pool{salt: keccak256(abi.encodePacked(token0, token1))}(); getPool[token0][token1] = pool; getPool[token1][token0] = pool; emit PoolCreated(pool); diff --git a/contracts/zero-ex/contracts/test/integration/TestUniswapV2Pool.sol b/contracts/zero-ex/contracts/test/integration/TestUniswapV2Pool.sol index 3f08a0d538..a5a18c3067 100644 --- a/contracts/zero-ex/contracts/test/integration/TestUniswapV2Pool.sol +++ b/contracts/zero-ex/contracts/test/integration/TestUniswapV2Pool.sol @@ -22,8 +22,8 @@ contract TestUniswapV2Pool is IUniswapV2Pair { uint32 blockTimestampLast; constructor() public { - IUniswapV2PoolDeployer.CreationParameters memory params = - IUniswapV2PoolDeployer(msg.sender).creationParameters(); + IUniswapV2PoolDeployer.CreationParameters memory params = IUniswapV2PoolDeployer(msg.sender) + .creationParameters(); (token0, token1) = (params.token0, params.token1); } @@ -32,10 +32,7 @@ contract TestUniswapV2Pool is IUniswapV2Pair { uint256 amount1Out, address to, bytes calldata /* data */ - ) - external - override - { + ) external override { if (amount0Out > 0) { token0.transfer(to, amount0Out); } @@ -48,9 +45,7 @@ contract TestUniswapV2Pool is IUniswapV2Pair { uint112 reserve0_, uint112 reserve1_, uint32 blockTimestampLast_ - ) - external - { + ) external { reserve0 = reserve0_; reserve1 = reserve1_; blockTimestampLast = blockTimestampLast_; @@ -58,9 +53,13 @@ contract TestUniswapV2Pool is IUniswapV2Pair { function getReserves() external - override view - returns (uint112, uint112, uint32) + override + returns ( + uint112, + uint112, + uint32 + ) { return (reserve0, reserve1, blockTimestampLast); } diff --git a/contracts/zero-ex/contracts/test/integration/TestUniswapV3Factory.sol b/contracts/zero-ex/contracts/test/integration/TestUniswapV3Factory.sol index e8566dd2f5..07e8726445 100644 --- a/contracts/zero-ex/contracts/test/integration/TestUniswapV3Factory.sol +++ b/contracts/zero-ex/contracts/test/integration/TestUniswapV3Factory.sol @@ -14,31 +14,22 @@ contract TestUniswapV3Factory { event PoolCreated(TestUniswapV3Pool pool); bytes32 public immutable POOL_INIT_CODE_HASH; - mapping (IERC20TokenV06 => mapping (IERC20TokenV06 => mapping (uint24 => TestUniswapV3Pool))) public getPool; + mapping(IERC20TokenV06 => mapping(IERC20TokenV06 => mapping(uint24 => TestUniswapV3Pool))) public getPool; CreationParameters public creationParameters; constructor() public { POOL_INIT_CODE_HASH = keccak256(type(TestUniswapV3Pool).creationCode); } - function createPool(IERC20TokenV06 tokenA, IERC20TokenV06 tokenB, uint24 fee) - external - returns (TestUniswapV3Pool pool) - { - (IERC20TokenV06 token0, IERC20TokenV06 token1) = tokenA < tokenB - ? (tokenA, tokenB) - : (tokenB, tokenA); - require( - getPool[token0][token1][fee] == TestUniswapV3Pool(0), - "TestUniswapV3Factory/POOL_ALREADY_EXISTS" - ); - creationParameters = CreationParameters({ - token0: token0, - token1: token1, - fee: fee - }); - pool = new TestUniswapV3Pool - { salt: keccak256(abi.encode(token0, token1, fee)) }(); + function createPool( + IERC20TokenV06 tokenA, + IERC20TokenV06 tokenB, + uint24 fee + ) external returns (TestUniswapV3Pool pool) { + (IERC20TokenV06 token0, IERC20TokenV06 token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); + require(getPool[token0][token1][fee] == TestUniswapV3Pool(0), "TestUniswapV3Factory/POOL_ALREADY_EXISTS"); + creationParameters = CreationParameters({token0: token0, token1: token1, fee: fee}); + pool = new TestUniswapV3Pool{salt: keccak256(abi.encode(token0, token1, fee))}(); getPool[token0][token1][fee] = pool; getPool[token1][token0][fee] = pool; emit PoolCreated(pool); diff --git a/contracts/zero-ex/contracts/test/integration/TestUniswapV3Pool.sol b/contracts/zero-ex/contracts/test/integration/TestUniswapV3Pool.sol index d2bd190974..7408fa6826 100644 --- a/contracts/zero-ex/contracts/test/integration/TestUniswapV3Pool.sol +++ b/contracts/zero-ex/contracts/test/integration/TestUniswapV3Pool.sol @@ -19,8 +19,7 @@ interface IUniswapV3SwapCallback { int256 amount0Delta, int256 amount1Delta, bytes calldata data - ) - external; + ) external; } contract TestUniswapV3Pool is IUniswapV3Pool { @@ -29,8 +28,8 @@ contract TestUniswapV3Pool is IUniswapV3Pool { uint24 public immutable fee; constructor() public { - IUniswapV3PoolDeployer.CreationParameters memory params = - IUniswapV3PoolDeployer(msg.sender).creationParameters(); + IUniswapV3PoolDeployer.CreationParameters memory params = IUniswapV3PoolDeployer(msg.sender) + .creationParameters(); (token0, token1, fee) = (params.token0, params.token1, params.fee); } @@ -40,11 +39,7 @@ contract TestUniswapV3Pool is IUniswapV3Pool { int256 amountSpecified, uint160, bytes calldata data - ) - external - override - returns (int256 amount0, int256 amount1) - { + ) external override returns (int256 amount0, int256 amount1) { uint256 balance0Before = token0.balanceOf(address(this)); uint256 balance1Before = token1.balanceOf(address(this)); if (zeroForOne) { @@ -58,18 +53,9 @@ contract TestUniswapV3Pool is IUniswapV3Pool { amount1 = int256(amountSpecified); token0.transfer(recipient, balance0Before); } - IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback( - amount0, - amount1, - data - ); - int256 balance0Change = int256(token0.balanceOf(address(this))) - - int256(balance0Before); - int256 balance1Change = int256(token1.balanceOf(address(this))) - - int256(balance1Before); - require( - balance0Change >= amount0 && balance1Change >= amount1, - "TestUniswapV3Pool/SWAP_NOT_PAID" - ); + IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data); + int256 balance0Change = int256(token0.balanceOf(address(this))) - int256(balance0Before); + int256 balance1Change = int256(token1.balanceOf(address(this))) - int256(balance1Before); + require(balance0Change >= amount0 && balance1Change >= amount1, "TestUniswapV3Pool/SWAP_NOT_PAID"); } } diff --git a/contracts/zero-ex/contracts/test/tokens/TestMintableERC1155Token.sol b/contracts/zero-ex/contracts/test/tokens/TestMintableERC1155Token.sol index 778ab870c6..2febe7be5f 100644 --- a/contracts/zero-ex/contracts/test/tokens/TestMintableERC1155Token.sol +++ b/contracts/zero-ex/contracts/test/tokens/TestMintableERC1155Token.sol @@ -22,9 +22,7 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; - interface IERC1155Receiver { - /// @notice Handle the receipt of a single ERC1155 token type /// @dev The smart contract calls this function on the recipient /// after a `safeTransferFrom`. This function MAY throw to revert and reject the @@ -43,9 +41,7 @@ interface IERC1155Receiver { uint256 id, uint256 value, bytes calldata data - ) - external - returns(bytes4 success); + ) external returns (bytes4 success); /// @notice Handle the receipt of multiple ERC1155 token types /// @dev The smart contract calls this function on the recipient @@ -65,9 +61,7 @@ interface IERC1155Receiver { uint256[] calldata ids, uint256[] calldata values, bytes calldata data - ) - external - returns(bytes4 success); + ) external returns (bytes4 success); } contract TestMintableERC1155Token { @@ -82,13 +76,7 @@ contract TestMintableERC1155Token { /// be used by clients and exchanges to be added to the "circulating supply" for a given token ID. /// To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event /// from `0x0` to `0x0`, with the token creator as `_operator`. - event TransferSingle( - address indexed operator, - address indexed from, - address indexed to, - uint256 id, - uint256 value - ); + event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, /// including zero value transfers as well as minting or burning. @@ -108,43 +96,30 @@ contract TestMintableERC1155Token { ); /// @dev MUST emit when an approval is updated. - event ApprovalForAll( - address indexed owner, - address indexed operator, - bool approved - ); + event ApprovalForAll(address indexed owner, address indexed operator, bool approved); // selectors for receiver callbacks - bytes4 constant public ERC1155_RECEIVED = 0xf23a6e61; - bytes4 constant public ERC1155_BATCH_RECEIVED = 0xbc197c81; + bytes4 public constant ERC1155_RECEIVED = 0xf23a6e61; + bytes4 public constant ERC1155_BATCH_RECEIVED = 0xbc197c81; // id => (owner => balance) - mapping (uint256 => mapping(address => uint256)) internal balances; + mapping(uint256 => mapping(address => uint256)) internal balances; // owner => (operator => approved) - mapping (address => mapping(address => bool)) internal operatorApproval; - + mapping(address => mapping(address => bool)) internal operatorApproval; function mint( address to, uint256 id, uint256 quantity - ) - external - { + ) external { // Grant the items to the caller balances[id][to] = quantity.safeAdd(balances[id][to]); // Emit the Transfer/Mint event. // the 0x0 source address implies a mint // It will also provide the circulating supply info. - emit TransferSingle( - msg.sender, - address(0x0), - to, - id, - quantity - ); + emit TransferSingle(msg.sender, address(0x0), to, id, quantity); // if `to` is a contract then trigger its callback uint256 receiverCodeSize; @@ -159,10 +134,7 @@ contract TestMintableERC1155Token { quantity, "" ); - require( - callbackReturnValue == ERC1155_RECEIVED, - "BAD_RECEIVER_RETURN_VALUE" - ); + require(callbackReturnValue == ERC1155_RECEIVED, "BAD_RECEIVER_RETURN_VALUE"); } } @@ -186,18 +158,10 @@ contract TestMintableERC1155Token { uint256 id, uint256 value, bytes calldata data - ) - external - { + ) external { // sanity checks - require( - to != address(0x0), - "CANNOT_TRANSFER_TO_ADDRESS_ZERO" - ); - require( - from == msg.sender || operatorApproval[from][msg.sender] == true, - "INSUFFICIENT_ALLOWANCE" - ); + require(to != address(0x0), "CANNOT_TRANSFER_TO_ADDRESS_ZERO"); + require(from == msg.sender || operatorApproval[from][msg.sender] == true, "INSUFFICIENT_ALLOWANCE"); // perform transfer balances[id][from] = balances[id][from].safeSub(value); @@ -211,17 +175,8 @@ contract TestMintableERC1155Token { receiverCodeSize := extcodesize(to) } if (receiverCodeSize > 0) { - bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155Received( - msg.sender, - from, - id, - value, - data - ); - require( - callbackReturnValue == ERC1155_RECEIVED, - "BAD_RECEIVER_RETURN_VALUE" - ); + bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155Received(msg.sender, from, id, value, data); + require(callbackReturnValue == ERC1155_RECEIVED, "BAD_RECEIVER_RETURN_VALUE"); } } @@ -246,25 +201,14 @@ contract TestMintableERC1155Token { uint256[] calldata ids, uint256[] calldata values, bytes calldata data - ) - external - { + ) external { // sanity checks - require( - to != address(0x0), - "CANNOT_TRANSFER_TO_ADDRESS_ZERO" - ); - require( - ids.length == values.length, - "TOKEN_AND_VALUES_LENGTH_MISMATCH" - ); + require(to != address(0x0), "CANNOT_TRANSFER_TO_ADDRESS_ZERO"); + require(ids.length == values.length, "TOKEN_AND_VALUES_LENGTH_MISMATCH"); // Only supporting a global operator approval allows us to do // only 1 check and not to touch storage to handle allowances. - require( - from == msg.sender || operatorApproval[from][msg.sender] == true, - "INSUFFICIENT_ALLOWANCE" - ); + require(from == msg.sender || operatorApproval[from][msg.sender] == true, "INSUFFICIENT_ALLOWANCE"); // perform transfers for (uint256 i = 0; i < ids.length; ++i) { @@ -290,10 +234,7 @@ contract TestMintableERC1155Token { values, data ); - require( - callbackReturnValue == ERC1155_BATCH_RECEIVED, - "BAD_RECEIVER_RETURN_VALUE" - ); + require(callbackReturnValue == ERC1155_BATCH_RECEIVED, "BAD_RECEIVER_RETURN_VALUE"); } } @@ -326,12 +267,13 @@ contract TestMintableERC1155Token { /// @param owners The addresses of the token holders /// @param ids ID of the Tokens /// @return balances_ The _owner's balance of the Token types requested - function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory balances_) { + function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) + external + view + returns (uint256[] memory balances_) + { // sanity check - require( - owners.length == ids.length, - "OWNERS_AND_IDS_MUST_HAVE_SAME_LENGTH" - ); + require(owners.length == ids.length, "OWNERS_AND_IDS_MUST_HAVE_SAME_LENGTH"); // get balances balances_ = new uint256[](owners.length); diff --git a/contracts/zero-ex/contracts/test/tokens/TestMintableERC20Token.sol b/contracts/zero-ex/contracts/test/tokens/TestMintableERC20Token.sol index c76aa5aa8c..ddc12d66af 100644 --- a/contracts/zero-ex/contracts/test/tokens/TestMintableERC20Token.sol +++ b/contracts/zero-ex/contracts/test/tokens/TestMintableERC20Token.sol @@ -20,68 +20,46 @@ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; - contract TestMintableERC20Token { - event Transfer( - address token, - address from, - address to, - uint256 value - ); + event Transfer(address token, address from, address to, uint256 value); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; - function transfer(address to, uint256 amount) - external - virtual - returns (bool) - { + function transfer(address to, uint256 amount) external virtual returns (bool) { return transferFrom(msg.sender, to, amount); } - function approve(address spender, uint256 amount) - external - virtual - returns (bool) - { + function approve(address spender, uint256 amount) external virtual returns (bool) { allowance[msg.sender][spender] = amount; return true; } - function approveAs(address owner, address spender, uint256 amount) - external - returns (bool) - { + function approveAs( + address owner, + address spender, + uint256 amount + ) external returns (bool) { allowance[owner][spender] = amount; return true; } - function mint(address owner, uint256 amount) - external - virtual - { + function mint(address owner, uint256 amount) external virtual { balanceOf[owner] += amount; } - function burn(address owner, uint256 amount) - external - virtual - { + function burn(address owner, uint256 amount) external virtual { require(balanceOf[owner] >= amount, "TestMintableERC20Token/INSUFFICIENT_FUNDS"); balanceOf[owner] -= amount; } - function transferFrom(address from, address to, uint256 amount) - public - virtual - returns (bool) - { + function transferFrom( + address from, + address to, + uint256 amount + ) public virtual returns (bool) { if (from != msg.sender) { - require( - allowance[from][msg.sender] >= amount, - "TestMintableERC20Token/INSUFFICIENT_ALLOWANCE" - ); + require(allowance[from][msg.sender] >= amount, "TestMintableERC20Token/INSUFFICIENT_ALLOWANCE"); allowance[from][msg.sender] -= amount; } require(balanceOf[from] >= amount, "TestMintableERC20Token/INSUFFICIENT_FUNDS"); @@ -91,13 +69,7 @@ contract TestMintableERC20Token { return true; } - function getSpendableAmount(address owner, address spender) - external - view - returns (uint256) - { - return balanceOf[owner] < allowance[owner][spender] - ? balanceOf[owner] - : allowance[owner][spender]; + function getSpendableAmount(address owner, address spender) external view returns (uint256) { + return balanceOf[owner] < allowance[owner][spender] ? balanceOf[owner] : allowance[owner][spender]; } } diff --git a/contracts/zero-ex/contracts/test/tokens/TestMintableERC721Token.sol b/contracts/zero-ex/contracts/test/tokens/TestMintableERC721Token.sol index a581c58af7..6e4d8537db 100644 --- a/contracts/zero-ex/contracts/test/tokens/TestMintableERC721Token.sol +++ b/contracts/zero-ex/contracts/test/tokens/TestMintableERC721Token.sol @@ -22,9 +22,7 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; - interface IERC721Receiver { - /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the @@ -42,9 +40,7 @@ interface IERC721Receiver { address _from, uint256 _tokenId, bytes calldata _data - ) - external - returns (bytes4); + ) external returns (bytes4); } contract TestMintableERC721Token { @@ -55,100 +51,64 @@ contract TestMintableERC721Token { /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. - event Transfer( - address _from, - address _to, - uint256 _tokenId - ); + event Transfer(address _from, address _to, uint256 _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. - event Approval( - address indexed _owner, - address indexed _approved, - uint256 indexed _tokenId - ); + event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. - event ApprovalForAll( - address indexed _owner, - address indexed _operator, - bool _approved - ); + event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); // Function selector for ERC721Receiver.onERC721Received // 0x150b7a02 - bytes4 constant private ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); + bytes4 private constant ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); // Mapping of tokenId => owner - mapping (uint256 => address) private owners; + mapping(uint256 => address) private owners; // Mapping of tokenId => approved address - mapping (uint256 => address) private approvals; + mapping(uint256 => address) private approvals; // Mapping of owner => number of tokens owned - mapping (address => uint256) private balances; + mapping(address => uint256) private balances; // Mapping of owner => operator => approved - mapping (address => mapping (address => bool)) private operatorApprovals; + mapping(address => mapping(address => bool)) private operatorApprovals; /// @dev Function to mint a new token /// Reverts if the given token ID already exists /// @param _to Address of the beneficiary that will own the minted token - /// @param _tokenId ID of the token to be minted by the msg.sender - function mint(address _to, uint256 _tokenId) - external - { - require( - _to != address(0), - "ERC721_ZERO_TO_ADDRESS" - ); + /// @param _tokenId ID of the token to be minted by the msg.sender + function mint(address _to, uint256 _tokenId) external { + require(_to != address(0), "ERC721_ZERO_TO_ADDRESS"); address owner = owners[_tokenId]; - require( - owner == address(0), - "ERC721_OWNER_ALREADY_EXISTS" - ); + require(owner == address(0), "ERC721_OWNER_ALREADY_EXISTS"); owners[_tokenId] = _to; balances[_to] = balances[_to].safeAdd(1); - emit Transfer( - address(0), - _to, - _tokenId - ); + emit Transfer(address(0), _to, _tokenId); } /// @dev Function to burn a token /// Reverts if the given token ID doesn't exist /// @param _owner Owner of token with given token ID /// @param _tokenId ID of the token to be burned by the msg.sender - function burn(address _owner, uint256 _tokenId) - external - { - require( - _owner != address(0), - "ERC721_ZERO_OWNER_ADDRESS" - ); + function burn(address _owner, uint256 _tokenId) external { + require(_owner != address(0), "ERC721_ZERO_OWNER_ADDRESS"); address owner = owners[_tokenId]; - require( - owner == _owner, - "ERC721_OWNER_MISMATCH" - ); + require(owner == _owner, "ERC721_OWNER_MISMATCH"); owners[_tokenId] = address(0); balances[_owner] = balances[_owner].safeSub(1); - emit Transfer( - _owner, - address(0), - _tokenId - ); + emit Transfer(_owner, address(0), _tokenId); } /// @notice Transfers the ownership of an NFT from one address to another address @@ -168,30 +128,16 @@ contract TestMintableERC721Token { address _to, uint256 _tokenId, bytes calldata _data - ) - external - { - transferFrom( - _from, - _to, - _tokenId - ); + ) external { + transferFrom(_from, _to, _tokenId); uint256 receiverCodeSize; assembly { receiverCodeSize := extcodesize(_to) } if (receiverCodeSize > 0) { - bytes4 selector = IERC721Receiver(_to).onERC721Received( - msg.sender, - _from, - _tokenId, - _data - ); - require( - selector == ERC721_RECEIVED, - "ERC721_INVALID_SELECTOR" - ); + bytes4 selector = IERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); + require(selector == ERC721_RECEIVED, "ERC721_INVALID_SELECTOR"); } } @@ -205,30 +151,16 @@ contract TestMintableERC721Token { address _from, address _to, uint256 _tokenId - ) - external - { - transferFrom( - _from, - _to, - _tokenId - ); + ) external { + transferFrom(_from, _to, _tokenId); uint256 receiverCodeSize; assembly { receiverCodeSize := extcodesize(_to) } if (receiverCodeSize > 0) { - bytes4 selector = IERC721Receiver(_to).onERC721Received( - msg.sender, - _from, - _tokenId, - "" - ); - require( - selector == ERC721_RECEIVED, - "ERC721_INVALID_SELECTOR" - ); + bytes4 selector = IERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, ""); + require(selector == ERC721_RECEIVED, "ERC721_INVALID_SELECTOR"); } } @@ -238,21 +170,12 @@ contract TestMintableERC721Token { /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve - function approve(address _approved, uint256 _tokenId) - external - { + function approve(address _approved, uint256 _tokenId) external { address owner = ownerOf(_tokenId); - require( - msg.sender == owner || isApprovedForAll(owner, msg.sender), - "ERC721_INVALID_SENDER" - ); + require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721_INVALID_SENDER"); approvals[_tokenId] = _approved; - emit Approval( - owner, - _approved, - _tokenId - ); + emit Approval(owner, _approved, _tokenId); } /// @notice Enable or disable approval for a third party ("operator") to manage @@ -261,15 +184,9 @@ contract TestMintableERC721Token { /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval - function setApprovalForAll(address _operator, bool _approved) - external - { + function setApprovalForAll(address _operator, bool _approved) external { operatorApprovals[msg.sender][_operator] = _approved; - emit ApprovalForAll( - msg.sender, - _operator, - _approved - ); + emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Count all NFTs assigned to an owner @@ -277,15 +194,8 @@ contract TestMintableERC721Token { /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero - function balanceOf(address _owner) - external - view - returns (uint256) - { - require( - _owner != address(0), - "ERC721_ZERO_OWNER" - ); + function balanceOf(address _owner) external view returns (uint256) { + require(_owner != address(0), "ERC721_ZERO_OWNER"); return balances[_owner]; } @@ -303,26 +213,16 @@ contract TestMintableERC721Token { address _from, address _to, uint256 _tokenId - ) - public - { - require( - _to != address(0), - "ERC721_ZERO_TO_ADDRESS" - ); + ) public { + require(_to != address(0), "ERC721_ZERO_TO_ADDRESS"); address owner = ownerOf(_tokenId); - require( - _from == owner, - "ERC721_OWNER_MISMATCH" - ); + require(_from == owner, "ERC721_OWNER_MISMATCH"); address spender = msg.sender; address approvedAddress = getApproved(_tokenId); require( - spender == owner || - isApprovedForAll(owner, spender) || - approvedAddress == spender, + spender == owner || isApprovedForAll(owner, spender) || approvedAddress == spender, "ERC721_INVALID_SPENDER" ); @@ -334,11 +234,7 @@ contract TestMintableERC721Token { balances[_from] = balances[_from].safeSub(1); balances[_to] = balances[_to].safeAdd(1); - emit Transfer( - _from, - _to, - _tokenId - ); + emit Transfer(_from, _to, _tokenId); } /// @notice Find the owner of an NFT @@ -346,16 +242,9 @@ contract TestMintableERC721Token { /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT - function ownerOf(uint256 _tokenId) - public - view - returns (address) - { + function ownerOf(uint256 _tokenId) public view returns (address) { address owner = owners[_tokenId]; - require( - owner != address(0), - "ERC721_ZERO_OWNER" - ); + require(owner != address(0), "ERC721_ZERO_OWNER"); return owner; } @@ -363,11 +252,7 @@ contract TestMintableERC721Token { /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none - function getApproved(uint256 _tokenId) - public - view - returns (address) - { + function getApproved(uint256 _tokenId) public view returns (address) { return approvals[_tokenId]; } @@ -375,11 +260,7 @@ contract TestMintableERC721Token { /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise - function isApprovedForAll(address _owner, address _operator) - public - view - returns (bool) - { + function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } } diff --git a/contracts/zero-ex/contracts/test/tokens/TestTokenSpenderERC20Token.sol b/contracts/zero-ex/contracts/test/tokens/TestTokenSpenderERC20Token.sol index e860f7481b..204d94b8bf 100644 --- a/contracts/zero-ex/contracts/test/tokens/TestTokenSpenderERC20Token.sol +++ b/contracts/zero-ex/contracts/test/tokens/TestTokenSpenderERC20Token.sol @@ -22,25 +22,16 @@ pragma experimental ABIEncoderV2; import "./TestMintableERC20Token.sol"; - -contract TestTokenSpenderERC20Token is - TestMintableERC20Token -{ - - event TransferFromCalled( - address sender, - address from, - address to, - uint256 amount - ); +contract TestTokenSpenderERC20Token is TestMintableERC20Token { + event TransferFromCalled(address sender, address from, address to, uint256 amount); // `transferFrom()` behavior depends on the value of `amount`. - uint256 constant private EMPTY_RETURN_AMOUNT = 1337; - uint256 constant private FALSE_RETURN_AMOUNT = 1338; - uint256 constant private REVERT_RETURN_AMOUNT = 1339; - uint256 constant private TRIGGER_FALLBACK_SUCCESS_AMOUNT = 1340; - uint256 constant private EXTRA_RETURN_TRUE_AMOUNT = 1341; - uint256 constant private EXTRA_RETURN_FALSE_AMOUNT = 1342; + uint256 private constant EMPTY_RETURN_AMOUNT = 1337; + uint256 private constant FALSE_RETURN_AMOUNT = 1338; + uint256 private constant REVERT_RETURN_AMOUNT = 1339; + uint256 private constant TRIGGER_FALLBACK_SUCCESS_AMOUNT = 1340; + uint256 private constant EXTRA_RETURN_TRUE_AMOUNT = 1341; + uint256 private constant EXTRA_RETURN_FALSE_AMOUNT = 1342; bool private _isGreedyRevert; @@ -48,14 +39,16 @@ contract TestTokenSpenderERC20Token is _isGreedyRevert = isGreedy; } - function transferFrom(address from, address to, uint256 amount) - public - override - returns (bool) - { + function transferFrom( + address from, + address to, + uint256 amount + ) public override returns (bool) { emit TransferFromCalled(msg.sender, from, to, amount); if (amount == EMPTY_RETURN_AMOUNT) { - assembly { return(0, 0) } + assembly { + return(0, 0) + } } if (amount == FALSE_RETURN_AMOUNT) { return false; @@ -68,8 +61,7 @@ contract TestTokenSpenderERC20Token is assert(!_isGreedyRevert); return false; } - if (amount == EXTRA_RETURN_TRUE_AMOUNT - || amount == EXTRA_RETURN_FALSE_AMOUNT) { + if (amount == EXTRA_RETURN_TRUE_AMOUNT || amount == EXTRA_RETURN_FALSE_AMOUNT) { bool ret = amount == EXTRA_RETURN_TRUE_AMOUNT; assembly { @@ -86,9 +78,7 @@ contract TestTokenSpenderERC20Token is uint256 balance, address spender, uint256 allowance_ - ) - external - { + ) external { balanceOf[owner] = balance; allowance[owner][spender] = allowance_; } diff --git a/contracts/zero-ex/contracts/test/tokens/TestWeth.sol b/contracts/zero-ex/contracts/test/tokens/TestWeth.sol index 37007d284a..1afdcd1dda 100644 --- a/contracts/zero-ex/contracts/test/tokens/TestWeth.sol +++ b/contracts/zero-ex/contracts/test/tokens/TestWeth.sol @@ -22,32 +22,21 @@ pragma experimental ABIEncoderV2; import "./TestMintableERC20Token.sol"; - -contract TestWeth is - TestMintableERC20Token -{ +contract TestWeth is TestMintableERC20Token { event Deposit(address owner, uint256 value); event Withdrawal(address owner, uint256 value); - function deposit() - external - payable - { + function deposit() external payable { this.mint(msg.sender, msg.value); emit Deposit(msg.sender, msg.value); } - function depositTo(address owner) - external - payable - { + function depositTo(address owner) external payable { this.mint(owner, msg.value); emit Deposit(owner, msg.value); } - function withdraw(uint256 amount) - external - { + function withdraw(uint256 amount) external { require(balanceOf[msg.sender] >= amount, "TestWeth/INSUFFICIENT_FUNDS"); balanceOf[msg.sender] -= amount; msg.sender.transfer(amount); diff --git a/contracts/zero-ex/test/artifacts.ts b/contracts/zero-ex/test/artifacts.ts index 82b7284332..d4e7e073aa 100644 --- a/contracts/zero-ex/test/artifacts.ts +++ b/contracts/zero-ex/test/artifacts.ts @@ -389,7 +389,8 @@ export const artifacts = { TestNoEthRecipient: TestNoEthRecipient as ContractArtifact, TestOrderSignerRegistryWithContractWallet: TestOrderSignerRegistryWithContractWallet as ContractArtifact, TestPermissionlessTransformerDeployerSuicidal: TestPermissionlessTransformerDeployerSuicidal as ContractArtifact, - TestPermissionlessTransformerDeployerTransformer: TestPermissionlessTransformerDeployerTransformer as ContractArtifact, + TestPermissionlessTransformerDeployerTransformer: + TestPermissionlessTransformerDeployerTransformer as ContractArtifact, TestPropertyValidator: TestPropertyValidator as ContractArtifact, TestRfqOriginRegistration: TestRfqOriginRegistration as ContractArtifact, TestSimpleFunctionRegistryFeatureImpl1: TestSimpleFunctionRegistryFeatureImpl1 as ContractArtifact, diff --git a/package.json b/package.json index 6ae01b89b8..a9db0d0d04 100644 --- a/package.json +++ b/package.json @@ -12,8 +12,8 @@ "deps_versions:ci": "node ./node_modules/@0x/monorepo-scripts/lib/deps_versions.js", "fix": "wsrun --fast-exit --parallel --exclude-missing -p $PKG -c fix", "ganache": "ganache-cli -p 8545 --gasLimit 10000000 --networkId 50 -m \"${npm_package_config_mnemonic}\"", - "prettier": "prettier --write '**/*.{ts,tsx,json}' --config .prettierrc", - "prettier:ci": "prettier --list-different '**/*.{ts,tsx,json}' --config .prettierrc", + "prettier": "prettier --write '**/*.{ts,tsx,json,sol}' --config .prettierrc", + "prettier:ci": "prettier --list-different '**/*.{ts,tsx,json,sol}' --config .prettierrc", "report_coverage": "lcov-result-merger './packages/*/coverage/lcov.info' | coveralls", "test:installation": "node ./node_modules/@0x/monorepo-scripts/lib/test_installation.js", "test:installation:local": "IS_LOCAL_PUBLISH=true node ./node_modules/@0x/monorepo-scripts/lib/test_installation.js", @@ -70,6 +70,7 @@ "lerna": "^3.0.0-beta.25", "npm-run-all": "^4.1.2", "prettier": "2.7.1", + "prettier-plugin-solidity": "^1.0.0-beta.24", "source-map-support": "^0.5.6", "typescript": "4.6.3", "wsrun": "^5.2.4" diff --git a/yarn.lock b/yarn.lock index 66cb76a440..81b0c9195a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3337,6 +3337,13 @@ resolved "https://registry.yarnpkg.com/@sinonjs/text-encoding/-/text-encoding-0.7.2.tgz#5981a8db18b56ba38ef0efb7d995b12aa7b51918" integrity sha512-sXXKG+uL9IrKqViTtao2Ws6dy0znu9sOaP1di/jKGW1M6VssO8vlpXCQcpZ+jisQ1tTFAC5Jo/EOzFbggBagFQ== +"@solidity-parser/parser@^0.14.3": + version "0.14.3" + resolved "https://registry.yarnpkg.com/@solidity-parser/parser/-/parser-0.14.3.tgz#0d627427b35a40d8521aaa933cc3df7d07bfa36f" + integrity sha512-29g2SZ29HtsqA58pLCtopI1P/cPy5/UAzlcAXO6T/CNJimG6yA8kx4NaseMyJULiC+TEs02Y9/yeHzClqoA0hw== + dependencies: + antlr4ts "^0.5.0-alpha.4" + "@szmarczak/http-timer@^1.1.2": version "1.1.2" resolved "https://registry.yarnpkg.com/@szmarczak/http-timer/-/http-timer-1.1.2.tgz#b1665e2c461a2cd92f4c1bbf50d5454de0d4b421" @@ -4255,6 +4262,11 @@ ansi@^0.3.0, ansi@~0.3.1: resolved "https://registry.yarnpkg.com/ansi/-/ansi-0.3.1.tgz#0c42d4fb17160d5a9af1e484bace1c66922c1b21" integrity sha512-iFY7JCgHbepc0b82yLaw4IMortylNb6wG4kL+4R0C3iv6i+RHGHux/yUX5BTiRvSX/shMnngjR1YyNMnXEFh5A== +antlr4ts@^0.5.0-alpha.4: + version "0.5.0-alpha.4" + resolved "https://registry.yarnpkg.com/antlr4ts/-/antlr4ts-0.5.0-alpha.4.tgz#71702865a87478ed0b40c0709f422cf14d51652a" + integrity sha512-WPQDt1B74OfPv/IMS2ekXAKkTZIHl88uMetg6q3OTqgFxZ/dxDXI0EWLyZid/1Pe6hTftyg5N7gel5wNAGxXyQ== + any-promise@1.3.0, any-promise@^1.0.0: version "1.3.0" resolved "https://registry.yarnpkg.com/any-promise/-/any-promise-1.3.0.tgz#abc6afeedcea52e809cdc0376aed3ce39635d17f" @@ -7388,6 +7400,11 @@ emittery@^0.4.1: resolved "https://registry.yarnpkg.com/emittery/-/emittery-0.4.1.tgz#abe9d3297389ba424ac87e53d1c701962ce7433d" integrity sha512-r4eRSeStEGf6M5SKdrQhhLK5bOwOBxQhIE3YSTnZE3GpKiLfnnhE+tPtrJE79+eDJgm39BM6LSoI8SCx4HbwlQ== +emoji-regex@^10.1.0: + version "10.1.0" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-10.1.0.tgz#d50e383743c0f7a5945c47087295afc112e3cf66" + integrity sha512-xAEnNCT3w2Tg6MA7ly6QqYJvEoY1tm9iIjJ3yMKK9JPlWuRHAMoe5iETwQnx3M9TVbFMfsrBgWKR+IsmswwNjg== + emoji-regex@^7.0.1: version "7.0.3" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-7.0.3.tgz#933a04052860c85e83c122479c4748a8e4c72156" @@ -13982,6 +13999,18 @@ preserve@^0.2.0: resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" integrity sha512-s/46sYeylUfHNjI+sA/78FAHlmIuKqI9wNnzEOGehAlUUYeObv5C2mOinXBjyUyWmJ2SfcS2/ydApH4hTF4WXQ== +prettier-plugin-solidity@^1.0.0-beta.24: + version "1.0.0-beta.24" + resolved "https://registry.yarnpkg.com/prettier-plugin-solidity/-/prettier-plugin-solidity-1.0.0-beta.24.tgz#67573ca87098c14f7ccff3639ddd8a4cab2a87eb" + integrity sha512-6JlV5BBTWzmDSq4kZ9PTXc3eLOX7DF5HpbqmmaF+kloyUwOZbJ12hIYsUaZh2fVgZdV2t0vWcvY6qhILhlzgqg== + dependencies: + "@solidity-parser/parser" "^0.14.3" + emoji-regex "^10.1.0" + escape-string-regexp "^4.0.0" + semver "^7.3.7" + solidity-comments-extractor "^0.0.7" + string-width "^4.2.3" + prettier@2.7.1, prettier@^2.3.1: version "2.7.1" resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.7.1.tgz#e235806850d057f97bb08368a4f7d899f7760c64" @@ -15456,6 +15485,11 @@ solc@^0.8: semver "^5.5.0" tmp "0.0.33" +solidity-comments-extractor@^0.0.7: + version "0.0.7" + resolved "https://registry.yarnpkg.com/solidity-comments-extractor/-/solidity-comments-extractor-0.0.7.tgz#99d8f1361438f84019795d928b931f4e5c39ca19" + integrity sha512-wciNMLg/Irp8OKGrh3S2tfvZiZ0NEyILfcRCXCD4mp7SgK/i9gzLfhY2hY7VMCQJ3kH9UB9BzNdibIVMchzyYw== + solidity-parser-antlr@^0.4.2: version "0.4.11" resolved "https://registry.yarnpkg.com/solidity-parser-antlr/-/solidity-parser-antlr-0.4.11.tgz#af43e1f13b3b88309a875455f5d6e565b05ee5f1"