diff options
Diffstat (limited to 'packages/contracts')
112 files changed, 3554 insertions, 597 deletions
diff --git a/packages/contracts/.solhint.json b/packages/contracts/.solhint.json new file mode 100644 index 000000000..076afe9f3 --- /dev/null +++ b/packages/contracts/.solhint.json @@ -0,0 +1,20 @@ +{ + "extends": "default", + "rules": { + "avoid-low-level-calls": false, + "avoid-tx-origin": "warn", + "bracket-align": false, + "code-complexity": false, + "const-name-snakecase": "error", + "expression-indent": "error", + "function-max-lines": false, + "func-order": "error", + "indent": ["error", 4], + "max-line-length": ["warn", 160], + "no-inline-assembly": false, + "quotes": ["error", "double"], + "separate-by-one-line-in-contract": "error", + "space-after-comma": "error", + "statement-indent": "error" + } +} diff --git a/packages/contracts/compiler.json b/packages/contracts/compiler.json index 56c8b1761..5ace566d8 100644 --- a/packages/contracts/compiler.json +++ b/packages/contracts/compiler.json @@ -28,6 +28,7 @@ "ERC721Proxy", "Exchange", "ExchangeWrapper", + "Forwarder", "IAssetData", "IAssetProxy", "IValidator", diff --git a/packages/contracts/package.json b/packages/contracts/package.json index e0e82adc7..98b133e63 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,7 +1,7 @@ { "private": true, "name": "contracts", - "version": "2.1.33", + "version": "2.1.34", "engines": { "node": ">=6.12" }, @@ -20,22 +20,20 @@ "test:coverage": "SOLIDITY_COVERAGE=true run-s build run_mocha coverage:report:text coverage:report:lcov", "test:profiler": "SOLIDITY_PROFILER=true run-s build run_mocha profiler:report:html", "test:trace": "SOLIDITY_REVERT_TRACE=true run-s build run_mocha", - "run_mocha": - "mocha --require source-map-support/register --require make-promises-safe 'lib/test/**/*.js' --timeout 100000 --bail --exit", + "run_mocha": "mocha --require source-map-support/register --require make-promises-safe 'lib/test/**/*.js' --timeout 100000 --bail --exit", "compile": "sol-compiler --contracts-dir src", "clean": "shx rm -rf lib generated_contract_wrappers", - "generate_contract_wrappers": - "abi-gen --abis ${npm_package_config_abis} --template ../contract_templates/contract.handlebars --partials '../contract_templates/partials/**/*.handlebars' --output generated_contract_wrappers --backend ethers", - "lint": "tslint --project . --exclude **/src/generated_contract_wrappers/**/* --exclude **/lib/**/*", + "generate_contract_wrappers": "abi-gen --abis ${npm_package_config_abis} --template ../contract_templates/contract.handlebars --partials '../contract_templates/partials/**/*.handlebars' --output generated_contract_wrappers --backend ethers", + "lint": "tslint --project . --exclude **/src/generated_contract_wrappers/**/* --exclude **/lib/**/* && yarn lint-contracts", "coverage:report:text": "istanbul report text", "coverage:report:html": "istanbul report html && open coverage/index.html", "profiler:report:html": "istanbul report html && open coverage/index.html", "coverage:report:lcov": "istanbul report lcov", - "test:circleci": "yarn test" + "test:circleci": "yarn test", + "lint-contracts": "solhint src/2.0.0/**/**/**/**/*.sol" }, "config": { - "abis": - "../migrations/artifacts/2.0.0/@(AssetProxyOwner|DummyERC20Token|DummyERC721Receiver|DummyERC721Token|ERC20Proxy|ERC721Proxy|Exchange|ExchangeWrapper|IAssetData|IAssetProxy|MixinAuthorizable|MultiSigWallet|MultiSigWalletWithTimeLock|TestAssetProxyOwner|TestAssetProxyDispatcher|TestLibBytes|TestLibs|TestSignatureValidator|TestValidator|TestWallet|TokenRegistry|Whitelist|WETH9|ZRXToken).json" + "abis": "../migrations/artifacts/2.0.0/@(AssetProxyOwner|DummyERC20Token|DummyERC721Receiver|DummyERC721Token|ERC20Proxy|ERC721Proxy|Forwarder|Exchange|ExchangeWrapper|IAssetData|IAssetProxy|MixinAuthorizable|MultiSigWallet|MultiSigWalletWithTimeLock|TestAssetProxyOwner|TestAssetProxyDispatcher|TestLibBytes|TestLibs|TestSignatureValidator|TestValidator|TestWallet|TokenRegistry|Whitelist|WETH9|ZRXToken).json" }, "repository": { "type": "git", @@ -48,11 +46,11 @@ }, "homepage": "https://github.com/0xProject/0x-monorepo/packages/contracts/README.md", "devDependencies": { - "@0xproject/abi-gen": "^0.3.2", - "@0xproject/dev-utils": "^0.4.4", - "@0xproject/tslint-config": "^0.4.20", - "@0xproject/subproviders": "^0.10.1", - "@0xproject/sol-cov": "^0.1.1", + "@0xproject/abi-gen": "^0.3.3", + "@0xproject/dev-utils": "^0.4.5", + "@0xproject/tslint-config": "^0.4.21", + "@0xproject/subproviders": "^0.10.5", + "@0xproject/sol-cov": "^0.1.2", "@types/lodash": "4.14.104", "@types/bn.js": "^4.11.0", "@types/node": "^8.0.53", @@ -68,24 +66,24 @@ "npm-run-all": "^4.1.2", "shx": "^0.2.2", "solc": "^0.4.24", + "solhint": "^1.2.1", "tslint": "5.8.0", "typescript": "2.7.1", "yargs": "^10.0.3" }, "dependencies": { - "@0xproject/base-contract": "^0.3.4", + "@0xproject/base-contract": "^0.3.5", "@0xproject/order-utils": "^1.0.0", - "@0xproject/sol-compiler": "^0.5.2", + "@0xproject/sol-compiler": "^0.5.3", "@0xproject/types": "^1.0.0", - "@0xproject/typescript-typings": "^0.4.1", - "@0xproject/utils": "^0.7.1", - "@0xproject/web3-wrapper": "^0.7.1", - "ethereum-types": "^0.0.1", + "@0xproject/typescript-typings": "^0.4.2", + "@0xproject/utils": "^0.7.2", + "@0xproject/web3-wrapper": "^0.7.2", + "ethereum-types": "^0.0.2", "bn.js": "^4.11.8", "ethereumjs-abi": "^0.6.4", "ethereumjs-util": "^5.1.1", "ethers": "3.0.22", - "lodash": "^4.17.4", - "web3": "^0.20.0" + "lodash": "^4.17.4" } -} +}
\ No newline at end of file diff --git a/packages/contracts/src/1.0.0/MultiSigWalletWithTImeLockExceptRemoveAuthorizedAddress/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol b/packages/contracts/src/1.0.0/MultiSigWalletWithTImeLockExceptRemoveAuthorizedAddress/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol index 241e02d4a..aee722c53 100644 --- a/packages/contracts/src/1.0.0/MultiSigWalletWithTImeLockExceptRemoveAuthorizedAddress/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol +++ b/packages/contracts/src/1.0.0/MultiSigWalletWithTImeLockExceptRemoveAuthorizedAddress/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol @@ -18,7 +18,7 @@ pragma solidity ^0.4.10; -import "../../current/multisig/MultiSigWalletWithTimeLock.sol"; +import "../../2.0.0/multisig/MultiSigWalletWithTimeLock.sol"; contract MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress is MultiSigWalletWithTimeLock { @@ -79,4 +79,4 @@ contract MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress is MultiSigWall } return true; } -}
\ No newline at end of file +} diff --git a/packages/contracts/src/2.0.0/forwarder/Forwarder.sol b/packages/contracts/src/2.0.0/forwarder/Forwarder.sol new file mode 100644 index 000000000..546e7f22c --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/Forwarder.sol @@ -0,0 +1,56 @@ +/* + + Copyright 2018 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.4.24; +pragma experimental ABIEncoderV2; + +import "./MixinFees.sol"; +import "./MixinForwarderCore.sol"; +import "./MixinConstants.sol"; +import "./MixinMarketBuyZrx.sol"; +import "./MixinExpectedResults.sol"; +import "./MixinTransfer.sol"; + + +contract Forwarder is + MixinConstants, + MixinExpectedResults, + MixinFees, + MixinMarketBuyZrx, + MixinTransfer, + MixinForwarderCore +{ + + constructor ( + address _exchange, + address _etherToken, + address _zrxToken, + bytes memory _zrxAssetData, + bytes memory _wethAssetData + ) + public + MixinConstants( + _exchange, + _etherToken, + _zrxToken, + _zrxAssetData, + _wethAssetData + ) + MixinForwarderCore() + {} +} diff --git a/packages/contracts/src/2.0.0/forwarder/MixinConstants.sol b/packages/contracts/src/2.0.0/forwarder/MixinConstants.sol new file mode 100644 index 000000000..2b064d579 --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/MixinConstants.sol @@ -0,0 +1,43 @@ +/* + + Copyright 2018 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.4.24; + +import "./mixins/MConstants.sol"; + + +contract MixinConstants is + MConstants +{ + + constructor ( + address _exchange, + address _etherToken, + address _zrxToken, + bytes memory _zrxAssetData, + bytes memory _wethAssetData + ) + public + { + EXCHANGE = IExchange(_exchange); + ETHER_TOKEN = IEtherToken(_etherToken); + ZRX_TOKEN = IERC20Token(_zrxToken); + ZRX_ASSET_DATA = _zrxAssetData; + WETH_ASSET_DATA = _wethAssetData; + } +} diff --git a/packages/contracts/src/2.0.0/forwarder/MixinErrorMessages.sol b/packages/contracts/src/2.0.0/forwarder/MixinErrorMessages.sol new file mode 100644 index 000000000..1b3e3f488 --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/MixinErrorMessages.sol @@ -0,0 +1,35 @@ +/* + + Copyright 2018 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. + +*/ + +// solhint-disable +pragma solidity 0.4.24; + + +/// This contract is intended to serve as a reference, but is not actually used for efficiency reasons. +contract MixinErrorMessages { + string constant VALUE_GREATER_THAN_ZERO = "VALUE_GREATER_THAN_ZERO"; + string constant FEE_PROPORTION_TOO_LARGE = "FEE_PROPORTION_TOO_LARGE"; + string constant TAKER_ASSET_ZRX_REQUIRED = "TAKER_ASSET_ZRX_REQUIRED"; + string constant TAKER_ASSET_WETH_REQUIRED = "TAKER_ASSET_WETH_REQUIRED"; + string constant SAME_ASSET_TYPE_REQUIRED = "SAME_ASSET_TYPE_REQUIRED"; + string constant UNACCEPTABLE_THRESHOLD = "UNACCEPTABLE_THRESHOLD"; + string constant UNSUPPORTED_TOKEN_PROXY = "UNSUPPORTED_TOKEN_PROXY"; + string constant ASSET_AMOUNT_MATCH_ORDER_SIZE = "ASSET_AMOUNT_MUST_MATCH_ORDER_SIZE"; + string constant DEFAULT_FUNCTION_WETH_CONTRACT_ONLY = "DEFAULT_FUNCTION_WETH_CONTRACT_ONLY"; + string constant INVALID_MSG_VALUE = "INVALID_MSG_VALUE"; +} diff --git a/packages/contracts/src/2.0.0/forwarder/MixinExpectedResults.sol b/packages/contracts/src/2.0.0/forwarder/MixinExpectedResults.sol new file mode 100644 index 000000000..a575c9675 --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/MixinExpectedResults.sol @@ -0,0 +1,161 @@ +/* + + Copyright 2018 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.4.24; +pragma experimental ABIEncoderV2; + +import "../utils/LibBytes/LibBytes.sol"; +import "../protocol/Exchange/libs/LibFillResults.sol"; +import "../protocol/Exchange/libs/LibMath.sol"; +import "../protocol/Exchange/libs/LibOrder.sol"; +import "./mixins/MConstants.sol"; +import "./mixins/MExpectedResults.sol"; + + +contract MixinExpectedResults is + LibMath, + LibFillResults, + MConstants, + MExpectedResults +{ + + /// @dev Calculates a total FillResults for buying makerAssetFillAmount over all orders. + /// Including the fees required to be paid. + /// @param orders An array of Order struct containing order specifications. + /// @param makerAssetFillAmount A number representing the amount of this order to fill. + /// @return totalFillResults Amounts filled and fees paid by maker and taker. + function calculateMarketBuyResults( + LibOrder.Order[] memory orders, + uint256 makerAssetFillAmount + ) + public + view + returns (FillResults memory totalFillResults) + { + for (uint256 i = 0; i < orders.length; i++) { + uint256 remainingMakerAssetFillAmount = safeSub(makerAssetFillAmount, totalFillResults.makerAssetFilledAmount); + uint256 remainingTakerAssetFillAmount = getPartialAmount( + orders[i].takerAssetAmount, + orders[i].makerAssetAmount, + remainingMakerAssetFillAmount + ); + FillResults memory singleFillResult = calculateFillResults(orders[i], remainingTakerAssetFillAmount); + addFillResults(totalFillResults, singleFillResult); + if (totalFillResults.makerAssetFilledAmount == makerAssetFillAmount) { + break; + } + } + return totalFillResults; + } + + /// @dev Calculates a FillResults total for selling takerAssetFillAmount over all orders. + /// Including the fees required to be paid. + /// @param orders An array of Order struct containing order specifications. + /// @param takerAssetFillAmount A number representing the amount of this order to fill. + /// @return totalFillResults Amounts filled and fees paid by maker and taker. + function calculateMarketSellResults( + LibOrder.Order[] memory orders, + uint256 takerAssetFillAmount + ) + public + view + returns (FillResults memory totalFillResults) + { + for (uint256 i = 0; i < orders.length; i++) { + uint256 remainingTakerAssetFillAmount = safeSub(takerAssetFillAmount, totalFillResults.takerAssetFilledAmount); + FillResults memory singleFillResult = calculateFillResults(orders[i], remainingTakerAssetFillAmount); + addFillResults(totalFillResults, singleFillResult); + if (totalFillResults.takerAssetFilledAmount == takerAssetFillAmount) { + break; + } + } + return totalFillResults; + } + + /// @dev Calculates fill results for buyFeeTokens. This handles fees on buying ZRX + /// so the end result is the expected amount of ZRX (not less after fees). + /// @param orders An array of Order struct containing order specifications. + /// @param zrxFillAmount A number representing the amount zrx to buy + /// @return totalFillResults Expected fill result amounts from buying fees + function calculateMarketBuyZrxResults( + LibOrder.Order[] memory orders, + uint256 zrxFillAmount + ) + public + view + returns (FillResults memory totalFillResults) + { + for (uint256 i = 0; i < orders.length; i++) { + uint256 remainingZrxFillAmount = safeSub(zrxFillAmount, totalFillResults.makerAssetFilledAmount); + // Convert the remaining amount of makerToken to buy into remaining amount + // of takerToken to sell, assuming entire amount can be sold in the current order + uint256 remainingWethSellAmount = getPartialAmount( + orders[i].takerAssetAmount, + safeSub(orders[i].makerAssetAmount, orders[i].takerFee), // our exchange rate after fees + remainingZrxFillAmount + ); + FillResults memory singleFillResult = calculateFillResults(orders[i], safeAdd(remainingWethSellAmount, 1)); + + singleFillResult.makerAssetFilledAmount = safeSub(singleFillResult.makerAssetFilledAmount, singleFillResult.takerFeePaid); + addFillResults(totalFillResults, singleFillResult); + // As we compensate for the rounding issue above have slightly more ZRX than the requested zrxFillAmount + if (totalFillResults.makerAssetFilledAmount >= zrxFillAmount) { + break; + } + } + return totalFillResults; + } + + /// @dev Simulates the 0x Exchange fillOrder validation and calculations, without performing any state changes. + /// @param order An Order struct containing order specifications. + /// @param takerAssetFillAmount A number representing the amount of this order to fill. + /// @return fillResults Amounts filled and fees paid by maker and taker. + function calculateFillResults( + LibOrder.Order memory order, + uint256 takerAssetFillAmount + ) + internal + view + returns (FillResults memory fillResults) + { + LibOrder.OrderInfo memory orderInfo = EXCHANGE.getOrderInfo(order); + if (orderInfo.orderStatus != uint8(LibOrder.OrderStatus.FILLABLE)) { + return fillResults; + } + uint256 remainingTakerAssetAmount = safeSub(order.takerAssetAmount, orderInfo.orderTakerAssetFilledAmount); + uint256 takerAssetFilledAmount = min256(takerAssetFillAmount, remainingTakerAssetAmount); + + fillResults.takerAssetFilledAmount = takerAssetFilledAmount; + fillResults.makerAssetFilledAmount = getPartialAmount( + takerAssetFilledAmount, + order.takerAssetAmount, + order.makerAssetAmount + ); + fillResults.makerFeePaid = getPartialAmount( + takerAssetFilledAmount, + order.takerAssetAmount, + order.makerFee + ); + fillResults.takerFeePaid = getPartialAmount( + takerAssetFilledAmount, + order.takerAssetAmount, + order.takerFee + ); + return fillResults; + } +} diff --git a/packages/contracts/src/2.0.0/forwarder/MixinFees.sol b/packages/contracts/src/2.0.0/forwarder/MixinFees.sol new file mode 100644 index 000000000..8ea00a1d5 --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/MixinFees.sol @@ -0,0 +1,126 @@ +/* + + Copyright 2018 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.4.24; + +import "../protocol/Exchange/libs/LibMath.sol"; +import "./mixins/MConstants.sol"; +import "./mixins/MFees.sol"; + + +contract MixinFees is + LibMath, + MConstants, + MFees +{ + + uint16 constant public PERCENTAGE_DENOMINATOR = 10000; // 9800 == 98%, 10000 == 100% + uint16 constant public MAX_FEE = 1000; // 10% + uint16 constant public ALLOWABLE_EXCHANGE_PERCENTAGE = 9500; // 95% + + /// @dev Default payabale function, this allows us to withdraw WETH + function () + public + payable + { + require( + msg.sender == address(ETHER_TOKEN), + "DEFAULT_FUNCTION_WETH_CONTRACT_ONLY" + ); + } + + /// @dev Pays the feeRecipient feeProportion of the total takerEthAmount, denominated in ETH + /// @param takerEthAmount The total amount that was transacted in WETH, fees are calculated from this value. + /// @param feeProportion The proportion of fees + /// @param feeRecipient The recipient of the fees + /// @return ethFeeAmount Amount of ETH paid to feeRecipient as fee. + function payEthFee( + uint256 takerEthAmount, + uint16 feeProportion, + address feeRecipient + ) + internal + returns (uint256 ethFeeAmount) + { + if (feeProportion > 0 && feeRecipient != address(0)) { + require( + feeProportion <= MAX_FEE, + "FEE_PROPORTION_TOO_LARGE" + ); + // 1.5% is 150, allowing for 2 decimal precision, i.e 0.05% is 5 + ethFeeAmount = getPartialAmount( + feeProportion, + PERCENTAGE_DENOMINATOR, + takerEthAmount + ); + feeRecipient.transfer(ethFeeAmount); + } + return ethFeeAmount; + } + + /// @dev Withdraws the remaining WETH, deduct and pay fees from this amount based on the takerTokenAmount to the feeRecipient. + /// If a user overpaid ETH initially, the fees are calculated from the amount traded and deducted from withdrawAmount. + /// Any remaining ETH is sent back to the user. + /// @param ethWithdrawAmount The amount to withdraw from the WETH contract. + /// @param wethAmountSold The total amount that was transacted in WETH, fees are calculated from this value. + /// @param feeProportion The proportion of fees + /// @param feeRecipient The recipient of the fees + function withdrawPayAndDeductEthFee( + uint256 ethWithdrawAmount, + uint256 wethAmountSold, + uint16 feeProportion, + address feeRecipient + ) + internal + { + // Return all of the excess WETH if any after deducting fees on the amount + if (ethWithdrawAmount > 0) { + ETHER_TOKEN.withdraw(ethWithdrawAmount); + // Fees proportional to the amount traded + uint256 ethFeeAmount = payEthFee( + wethAmountSold, + feeProportion, + feeRecipient + ); + uint256 unspentEthAmount = safeSub(ethWithdrawAmount, ethFeeAmount); + if (unspentEthAmount > 0) { + msg.sender.transfer(unspentEthAmount); + } + } + } + + /// @dev Checks whether the amount of tokens sold against the amount of tokens requested + /// is within a certain threshold. This ensures the caller gets a fair deal when + /// performing any token fee abstraction. Threshold is 95%. If fee abstraction costs more than + /// 5% of the total transaction, we return false. + /// @param requestedSellAmount The amount the user requested, or sent in to a payable function + /// @param tokenAmountSold The amount of the token that was sold after fee abstraction + /// @return bool of whether this is within an acceptable threshold + function isAcceptableThreshold(uint256 requestedSellAmount, uint256 tokenAmountSold) + internal + pure + returns (bool) + { + uint256 acceptableSellAmount = getPartialAmount( + ALLOWABLE_EXCHANGE_PERCENTAGE, + PERCENTAGE_DENOMINATOR, + requestedSellAmount + ); + return tokenAmountSold >= acceptableSellAmount; + } +} diff --git a/packages/contracts/src/2.0.0/forwarder/MixinForwarderCore.sol b/packages/contracts/src/2.0.0/forwarder/MixinForwarderCore.sol new file mode 100644 index 000000000..eadeaf5ba --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/MixinForwarderCore.sol @@ -0,0 +1,431 @@ +/* + + Copyright 2018 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.4.24; +pragma experimental ABIEncoderV2; + +import "../utils/LibBytes/LibBytes.sol"; +import "./mixins/MFees.sol"; +import "./mixins/MMarketBuyZrx.sol"; +import "./mixins/MExpectedResults.sol"; +import "./mixins/MTransfer.sol"; +import "./mixins/MConstants.sol"; +import "./mixins/MForwarderCore.sol"; +import "../protocol/Exchange/libs/LibOrder.sol"; +import "../protocol/Exchange/libs/LibFillResults.sol"; + + +contract MixinForwarderCore is + LibFillResults, + MConstants, + MExpectedResults, + MFees, + MMarketBuyZrx, + MTransfer, + MForwarderCore +{ + bytes4 constant internal ERC20_DATA_ID = bytes4(keccak256("ERC20Token(address)")); + bytes4 constant internal ERC721_DATA_ID = bytes4(keccak256("ERC721Token(address,uint256,bytes)")); + uint256 constant internal MAX_UINT = 2**256 - 1; + + constructor () + public + { + address proxyAddress = EXCHANGE.getAssetProxy(ERC20_DATA_ID); + if (proxyAddress != address(0)) { + ETHER_TOKEN.approve(proxyAddress, MAX_UINT); + ZRX_TOKEN.approve(proxyAddress, MAX_UINT); + } + } + + /// @dev Market sells ETH for ERC20 tokens, performing fee abstraction if required. This does not support ERC721 tokens. This function is payable + /// and will convert all incoming ETH into WETH and perform the trade on behalf of the caller. + /// This function allows for a deduction of a proportion of incoming ETH sent to the feeRecipient. + /// The caller is sent all tokens from the operation. + /// If the purchased token amount does not meet an acceptable threshold then this function reverts. + /// @param orders An array of Order struct containing order specifications. + /// @param signatures An array of Proof that order has been created by maker. + /// @param feeOrders An array of Order struct containing order specifications for fees. + /// @param feeSignatures An array of Proof that order has been created by maker for the fee orders. + /// @param feeProportion A proportion deducted off the incoming ETH and sent to feeRecipient. The maximum value for this + /// is 1000, aka 10%. Supports up to 2 decimal places. I.e 0.59% is 59. + /// @param feeRecipient An address of the fee recipient whom receives feeProportion of ETH. + /// @return FillResults amounts filled and fees paid by maker and taker. + function marketSellEthForERC20( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + LibOrder.Order[] memory feeOrders, + bytes[] memory feeSignatures, + uint16 feeProportion, + address feeRecipient + ) + public + payable + returns (FillResults memory totalFillResults) + { + uint256 takerEthAmount = msg.value; + require( + takerEthAmount > 0, + "VALUE_GREATER_THAN_ZERO" + ); + // Deduct the fee from the total amount of ETH sent in + uint256 ethFeeAmount = payEthFee( + takerEthAmount, + feeProportion, + feeRecipient + ); + uint256 wethSellAmount = safeSub(takerEthAmount, ethFeeAmount); + + // Deposit the remaining to be used for trading + ETHER_TOKEN.deposit.value(wethSellAmount)(); + // Populate the known assetData, as it is always WETH the caller can provide null bytes to save gas + // marketSellOrders fills the remaining + address makerTokenAddress = LibBytes.readAddress(orders[0].makerAssetData, 16); + orders[0].takerAssetData = WETH_ASSET_DATA; + if (makerTokenAddress == address(ZRX_TOKEN)) { + // If this is ZRX then we market sell from the orders, rather than a 2 step of buying ZRX fees from feeOrders + // then buying ZRX from orders + totalFillResults = marketSellEthForZRXInternal( + orders, + signatures, + wethSellAmount + ); + } else { + totalFillResults = marketSellEthForERC20Internal( + orders, + signatures, + feeOrders, + feeSignatures, + wethSellAmount + ); + } + // Prevent accidental WETH owned by this contract and it being spent + require( + takerEthAmount >= totalFillResults.takerAssetFilledAmount, + "INVALID_MSG_VALUE" + ); + // Ensure no WETH is left in this contract + require( + wethSellAmount == totalFillResults.takerAssetFilledAmount, + "UNACCEPTABLE_THRESHOLD" + ); + // Transfer all tokens to msg.sender + transferERC20Token( + makerTokenAddress, + msg.sender, + totalFillResults.makerAssetFilledAmount + ); + return totalFillResults; + } + + /// @dev Buys the exact amount of assets (ERC20 and ERC721), performing fee abstraction if required. + /// All order assets must be of the same type. Deducts a proportional fee to fee recipient. + /// This function is payable and will convert all incoming ETH into WETH and perform the trade on behalf of the caller. + /// The caller is sent all assets from the fill of orders. This function will revert unless the requested amount of assets are purchased. + /// Any excess ETH sent will be returned to the caller + /// @param orders An array of Order struct containing order specifications. + /// @param signatures An array of Proof that order has been created by maker. + /// @param feeOrders An array of Order struct containing order specifications for fees. + /// @param makerTokenFillAmount The amount of maker asset to buy. + /// @param feeSignatures An array of Proof that order has been created by maker for the fee orders. + /// @param feeProportion A proportion deducted off the ETH spent and sent to feeRecipient. The maximum value for this + /// is 1000, aka 10%. Supports up to 2 decimal places. I.e 0.59% is 59. + /// @param feeRecipient An address of the fee recipient whom receives feeProportion of ETH. + /// @return FillResults amounts filled and fees paid by maker and taker. + function marketBuyTokensWithEth( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + LibOrder.Order[] memory feeOrders, + bytes[] memory feeSignatures, + uint256 makerTokenFillAmount, + uint16 feeProportion, + address feeRecipient + ) + public + payable + returns (FillResults memory totalFillResults) + { + uint256 takerEthAmount = msg.value; + require( + takerEthAmount > 0, + "VALUE_GREATER_THAN_ZERO" + ); + require( + makerTokenFillAmount > 0, + "VALUE_GREATER_THAN_ZERO" + ); + bytes4 assetDataId = LibBytes.readBytes4(orders[0].makerAssetData, 0); + require( + assetDataId == ERC20_DATA_ID || assetDataId == ERC721_DATA_ID, + "UNSUPPORTED_TOKEN_PROXY" + ); + + ETHER_TOKEN.deposit.value(takerEthAmount)(); + if (assetDataId == ERC20_DATA_ID) { + totalFillResults = marketBuyERC20TokensInternal( + orders, + signatures, + feeOrders, + feeSignatures, + makerTokenFillAmount + ); + } else if (assetDataId == ERC721_DATA_ID) { + totalFillResults = batchBuyERC721TokensInternal( + orders, + signatures, + feeOrders, + feeSignatures + ); + } + // Prevent accidental WETH owned by this contract and it being spent + require( + takerEthAmount >= totalFillResults.takerAssetFilledAmount, + "INVALID_MSG_VALUE" + ); + withdrawPayAndDeductEthFee( + safeSub(takerEthAmount, totalFillResults.takerAssetFilledAmount), + totalFillResults.takerAssetFilledAmount, + feeProportion, + feeRecipient + ); + return totalFillResults; + } + + /// @dev Market sells WETH for ERC20 tokens. + /// @param orders An array of Order struct containing order specifications. + /// @param signatures An array of Proof that order has been created by maker. + /// @param feeOrders An array of Order struct containing order specifications for fees. + /// @param feeSignatures An array of Proof that order has been created by maker for the fee orders. + /// @param wethSellAmount The amount of WETH to sell. + /// @return FillResults amounts filled and fees paid by maker and taker. + function marketSellEthForERC20Internal( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + LibOrder.Order[] memory feeOrders, + bytes[] memory feeSignatures, + uint256 wethSellAmount + ) + internal + returns (FillResults memory totalFillResults) + { + uint256 remainingWethSellAmount = wethSellAmount; + FillResults memory calculatedMarketSellResults = calculateMarketSellResults(orders, wethSellAmount); + if (calculatedMarketSellResults.takerFeePaid > 0) { + // Fees are required for these orders. Buy enough ZRX to cover the future market buy + FillResults memory feeTokensResults = marketBuyZrxInternal( + feeOrders, + feeSignatures, + calculatedMarketSellResults.takerFeePaid + ); + // Ensure the token abstraction was fair if fees were proportionally too high, we fail + require( + isAcceptableThreshold( + wethSellAmount, + safeSub(wethSellAmount, feeTokensResults.takerAssetFilledAmount) + ), + "UNACCEPTABLE_THRESHOLD" + ); + remainingWethSellAmount = safeSub(remainingWethSellAmount, feeTokensResults.takerAssetFilledAmount); + totalFillResults.takerFeePaid = feeTokensResults.takerFeePaid; + totalFillResults.takerAssetFilledAmount = feeTokensResults.takerAssetFilledAmount; + } + // Make our market sell to buy the requested tokens with the remaining balance + FillResults memory requestedTokensResults = EXCHANGE.marketSellOrders( + orders, + remainingWethSellAmount, + signatures + ); + // Update our return FillResult with the market sell + addFillResults(totalFillResults, requestedTokensResults); + return totalFillResults; + } + + /// @dev Market sells WETH for ZRX tokens. + /// @param orders An array of Order struct containing order specifications. + /// @param signatures An array of Proof that order has been created by maker. + /// @param wethSellAmount The amount of WETH to sell. + /// @return FillResults amounts filled and fees paid by maker and taker. + function marketSellEthForZRXInternal( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + uint256 wethSellAmount + ) + internal + returns (FillResults memory totalFillResults) + { + // Make our market sell to buy the requested tokens with the remaining balance + totalFillResults = EXCHANGE.marketSellOrders( + orders, + wethSellAmount, + signatures + ); + // Exchange does not special case ZRX in the makerAssetFilledAmount, if fees were deducted then using this amount + // for future transfers is invalid. + uint256 zrxAmountBought = safeSub(totalFillResults.makerAssetFilledAmount, totalFillResults.takerFeePaid); + require( + isAcceptableThreshold(totalFillResults.makerAssetFilledAmount, zrxAmountBought), + "UNACCEPTABLE_THRESHOLD" + ); + totalFillResults.makerAssetFilledAmount = zrxAmountBought; + return totalFillResults; + } + + /// @dev Buys an exact amount of an ERC20 token using WETH. + /// @param orders Orders to fill. The maker asset is the ERC20 token to buy. The taker asset is WETH. + /// @param signatures Proof that the orders were created by their respective makers. + /// @param feeOrders to fill. The maker asset is ZRX and the taker asset is WETH. + /// @param feeSignatures Proof that the feeOrders were created by their respective makers. + /// @param makerTokenFillAmount Amount of the ERC20 token to buy. + /// @return totalFillResults Aggregated fill results of buying the ERC20 and ZRX tokens. + function marketBuyERC20TokensInternal( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + LibOrder.Order[] memory feeOrders, + bytes[] memory feeSignatures, + uint256 makerTokenFillAmount + ) + internal + returns (LibFillResults.FillResults memory totalFillResults) + { + // We read the maker token address to check if it is ZRX and later use it for transfer + address makerTokenAddress = LibBytes.readAddress(orders[0].makerAssetData, 16); + // We assume that asset being bought by taker is the same for each order. + // Rather than passing this in as calldata, we copy the makerAssetData from the first order onto all later orders. + orders[0].takerAssetData = WETH_ASSET_DATA; + // We can short cut here for effeciency and use buyFeeTokensInternal if maker asset token is ZRX + // this buys us exactly that amount taking into account the fees. This saves gas and calculates the rate correctly + FillResults memory marketBuyResults; + if (makerTokenAddress == address(ZRX_TOKEN)) { + marketBuyResults = marketBuyZrxInternal( + orders, + signatures, + makerTokenFillAmount + ); + // When buying ZRX we round up which can result in a small margin excess + require( + marketBuyResults.makerAssetFilledAmount >= makerTokenFillAmount, + "UNACCEPTABLE_THRESHOLD" + ); + addFillResults(totalFillResults, marketBuyResults); + require( + isAcceptableThreshold( + safeAdd(totalFillResults.makerAssetFilledAmount, totalFillResults.takerFeePaid), // Total ZRX + totalFillResults.makerAssetFilledAmount // amount going to msg.sender + ), + "UNACCEPTABLE_THRESHOLD" + ); + } else { + FillResults memory calculatedMarketBuyResults = calculateMarketBuyResults(orders, makerTokenFillAmount); + if (calculatedMarketBuyResults.takerFeePaid > 0) { + // Fees are required for these orders. Buy enough ZRX to cover the future market buy + FillResults memory zrxMarketBuyResults = marketBuyZrxInternal( + feeOrders, + feeSignatures, + calculatedMarketBuyResults.takerFeePaid + ); + totalFillResults.takerAssetFilledAmount = zrxMarketBuyResults.takerAssetFilledAmount; + totalFillResults.takerFeePaid = zrxMarketBuyResults.takerFeePaid; + } + // Make our market buy of the requested tokens with the remaining balance + marketBuyResults = EXCHANGE.marketBuyOrders( + orders, + makerTokenFillAmount, + signatures + ); + require( + marketBuyResults.makerAssetFilledAmount == makerTokenFillAmount, + "UNACCEPTABLE_THRESHOLD" + ); + addFillResults(totalFillResults, marketBuyResults); + require( + isAcceptableThreshold( + totalFillResults.takerAssetFilledAmount, + marketBuyResults.takerAssetFilledAmount + ), + "UNACCEPTABLE_THRESHOLD" + ); + } + // Transfer all purchased tokens to msg.sender + transferERC20Token( + makerTokenAddress, + msg.sender, + marketBuyResults.makerAssetFilledAmount + ); + return totalFillResults; + } + + /// @dev Buys an all of the ERC721 tokens in the orders. + /// @param orders Orders to fill. The maker asset is the ERC721 token to buy. The taker asset is WETH. + /// @param signatures Proof that the orders were created by their respective makers. + /// @param feeOrders to fill. The maker asset is ZRX and the taker asset is WETH. + /// @param feeSignatures Proof that the feeOrders were created by their respective makers. + /// @return totalFillResults Aggregated fill results of buying the ERC721 tokens and ZRX tokens. + function batchBuyERC721TokensInternal( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + LibOrder.Order[] memory feeOrders, + bytes[] memory feeSignatures + ) + internal + returns (LibFillResults.FillResults memory totalFillResults) + { + uint256 totalZrxFeeAmount; + uint256 ordersLength = orders.length; + uint256[] memory takerAssetFillAmounts = new uint256[](ordersLength); + for (uint256 i = 0; i < ordersLength; i++) { + // Total up the fees + totalZrxFeeAmount = safeAdd(totalZrxFeeAmount, orders[i].takerFee); + // We assume that asset being bought by taker is the same for each order. + // Rather than passing this in as calldata, we set the takerAssetData as WETH asset data + orders[i].takerAssetData = WETH_ASSET_DATA; + // Populate takerAssetFillAmounts for later batchFill + takerAssetFillAmounts[i] = orders[i].takerAssetAmount; + } + if (totalZrxFeeAmount > 0) { + // Fees are required for these orders. Buy enough ZRX to cover the future fill + FillResults memory zrxMarketBuyResults = marketBuyZrxInternal( + feeOrders, + feeSignatures, + totalZrxFeeAmount + ); + totalFillResults.takerFeePaid = zrxMarketBuyResults.takerFeePaid; + totalFillResults.takerAssetFilledAmount = zrxMarketBuyResults.takerAssetFilledAmount; + } + FillResults memory batchFillResults = EXCHANGE.batchFillOrKillOrders( + orders, + takerAssetFillAmounts, + signatures + ); + addFillResults(totalFillResults, batchFillResults); + require( + isAcceptableThreshold( + totalFillResults.takerAssetFilledAmount, + batchFillResults.takerAssetFilledAmount + ), + "UNACCEPTABLE_THRESHOLD" + ); + // Transfer all of the tokens filled from the batchFill + for (i = 0; i < ordersLength; i++) { + transferERC721Token( + orders[i].makerAssetData, + msg.sender + ); + } + return totalFillResults; + } +} diff --git a/packages/contracts/src/2.0.0/forwarder/MixinMarketBuyZrx.sol b/packages/contracts/src/2.0.0/forwarder/MixinMarketBuyZrx.sol new file mode 100644 index 000000000..e272f8aad --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/MixinMarketBuyZrx.sol @@ -0,0 +1,83 @@ +/* + + Copyright 2018 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.4.24; +pragma experimental ABIEncoderV2; + +import "../protocol/Exchange/libs/LibFillResults.sol"; +import "../protocol/Exchange/libs/LibOrder.sol"; +import "../protocol/Exchange/libs/LibMath.sol"; +import "./mixins/MConstants.sol"; +import "./mixins/MMarketBuyZrx.sol"; + + +contract MixinMarketBuyZrx is + LibMath, + LibFillResults, + MConstants, + MMarketBuyZrx +{ + + /// @dev Buys zrxBuyAmount of ZRX fee tokens, taking into account the fees on buying fee tokens. This will guarantee + /// At least zrxBuyAmount of ZRX fee tokens are purchased (sometimes slightly over due to rounding issues). + /// It is possible that a request to buy 200 ZRX fee tokens will require purchasing 202 ZRX tokens + /// As 2 ZRX is required to purchase the 200 ZRX fee tokens. This guarantees at least 200 ZRX for future purchases. + /// @param orders An array of Order struct containing order specifications for fees. + /// @param signatures An array of Proof that order has been created by maker for the fee orders. + /// @param zrxBuyAmount The number of requested ZRX fee tokens. + /// @return totalFillResults Amounts filled and fees paid by maker and taker. makerTokenAmount is the zrx amount deducted of fees + function marketBuyZrxInternal( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + uint256 zrxBuyAmount + ) + internal + returns (FillResults memory totalFillResults) + { + for (uint256 i = 0; i < orders.length; i++) { + // All of these are ZRX/WETH, we can drop the respective assetData from callData + orders[i].makerAssetData = ZRX_ASSET_DATA; + orders[i].takerAssetData = WETH_ASSET_DATA; + // Calculate the remaining amount of makerToken to buy + uint256 remainingZrxBuyAmount = safeSub(zrxBuyAmount, totalFillResults.makerAssetFilledAmount); + // Convert the remaining amount of makerToken to buy into remaining amount + // of takerToken to sell, assuming entire amount can be sold in the current order + uint256 remainingWethSellAmount = getPartialAmount( + orders[i].takerAssetAmount, + safeSub(orders[i].makerAssetAmount, orders[i].takerFee), // our exchange rate after fees + remainingZrxBuyAmount + ); + // Attempt to sell the remaining amount of takerToken + // Round up the amount to ensure we don't under buy by a fractional amount + FillResults memory singleFillResult = EXCHANGE.fillOrder( + orders[i], + safeAdd(remainingWethSellAmount, 1), + signatures[i] + ); + // We didn't buy the full amount when buying ZRX as some were taken for fees + singleFillResult.makerAssetFilledAmount = safeSub(singleFillResult.makerAssetFilledAmount, singleFillResult.takerFeePaid); + // Update amounts filled and fees paid by maker and taker + addFillResults(totalFillResults, singleFillResult); + // Stop execution if the entire amount of makerToken has been bought + if (totalFillResults.makerAssetFilledAmount >= zrxBuyAmount) { + break; + } + } + return totalFillResults; + } +} diff --git a/packages/contracts/src/2.0.0/forwarder/MixinTransfer.sol b/packages/contracts/src/2.0.0/forwarder/MixinTransfer.sol new file mode 100644 index 000000000..6c49330f2 --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/MixinTransfer.sol @@ -0,0 +1,120 @@ +/* + + Copyright 2018 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.4.24; + +import "../utils/LibBytes/LibBytes.sol"; +import "../tokens/ERC721Token/IERC721Token.sol"; +import "./mixins/MTransfer.sol"; + + +contract MixinTransfer is + MTransfer +{ + + using LibBytes for bytes; + + bytes4 constant internal ERC20_TRANSFER_SELECTOR = bytes4(keccak256("transfer(address,uint256)")); + bytes4 constant internal ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,uint256,bytes)")); + bytes4 constant internal ERC721_RECEIVED_OPERATOR = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); + + function onERC721Received( + address, + uint256, + bytes memory + ) + public + pure + returns(bytes4) + { + return ERC721_RECEIVED; + } + + function onERC721Received( + address, + address, + uint256, + bytes memory + ) + public + pure + returns(bytes4) + { + return ERC721_RECEIVED_OPERATOR; + } + + function transferERC20Token( + address token, + address to, + uint256 amount + ) + internal + { + // Transfer tokens. + // We do a raw call so we can check the success separate + // from the return data. + bool success = token.call(abi.encodeWithSelector( + ERC20_TRANSFER_SELECTOR, + to, + amount + )); + require( + success, + "TRANSFER_FAILED" + ); + + // Check return data. + // If there is no return data, we assume the token incorrectly + // does not return a bool. In this case we expect it to revert + // on failure, which was handled above. + // If the token does return data, we require that it is a single + // value that evaluates to true. + assembly { + if returndatasize { + success := 0 + if eq(returndatasize, 32) { + // First 64 bytes of memory are reserved scratch space + returndatacopy(0, 0, 32) + success := mload(0) + } + } + } + require( + success, + "TRANSFER_FAILED" + ); + } + + function transferERC721Token( + bytes memory assetData, + address to + ) + internal + { + // Decode asset data. + address token = assetData.readAddress(16); + uint256 tokenId = assetData.readUint256(36); + bytes memory receiverData = assetData.readBytesWithLength(100); + IERC721Token(token).safeTransferFrom( + address(this), + to, + tokenId, + receiverData + ); + } +} diff --git a/packages/contracts/src/2.0.0/forwarder/interfaces/IExpectedResults.sol b/packages/contracts/src/2.0.0/forwarder/interfaces/IExpectedResults.sol new file mode 100644 index 000000000..89187b750 --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/interfaces/IExpectedResults.sol @@ -0,0 +1,66 @@ +/* + + Copyright 2018 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.4.24; +pragma experimental ABIEncoderV2; + +import "../../protocol/Exchange/libs/LibFillResults.sol"; +import "../../protocol/Exchange/libs/LibOrder.sol"; + + +contract IExpectedResults { + + /// @dev Calculates a total FillResults for buying makerAssetFillAmount over all orders. + /// Including the fees required to be paid. + /// @param orders An array of Order struct containing order specifications. + /// @param makerAssetFillAmount A number representing the amount of this order to fill. + /// @return totalFillResults Amounts filled and fees paid by maker and taker. + function calculateMarketBuyResults( + LibOrder.Order[] memory orders, + uint256 makerAssetFillAmount + ) + public + view + returns (LibFillResults.FillResults memory totalFillResults); + + /// @dev Calculates a FillResults total for selling takerAssetFillAmount over all orders. + /// Including the fees required to be paid. + /// @param orders An array of Order struct containing order specifications. + /// @param takerAssetFillAmount A number representing the amount of this order to fill. + /// @return totalFillResults Amounts filled and fees paid by maker and taker. + function calculateMarketSellResults( + LibOrder.Order[] memory orders, + uint256 takerAssetFillAmount + ) + public + view + returns (LibFillResults.FillResults memory totalFillResults); + + /// @dev Calculates fill results for buyFeeTokens. This handles fees on buying ZRX + /// so the end result is the expected amount of ZRX (not less after fees). + /// @param orders An array of Order struct containing order specifications. + /// @param zrxFillAmount A number representing the amount zrx to buy + /// @return totalFillResults Expected fill result amounts from buying fees + function calculateMarketBuyZrxResults( + LibOrder.Order[] memory orders, + uint256 zrxFillAmount + ) + public + view + returns (LibFillResults.FillResults memory totalFillResults); +} diff --git a/packages/contracts/src/2.0.0/forwarder/interfaces/IForwarder.sol b/packages/contracts/src/2.0.0/forwarder/interfaces/IForwarder.sol new file mode 100644 index 000000000..745dd29a9 --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/interfaces/IForwarder.sol @@ -0,0 +1,30 @@ +/* + + Copyright 2018 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.4.24; +pragma experimental ABIEncoderV2; + +import "./IForwarderCore.sol"; +import "./IExpectedResults.sol"; + + +// solhint-disable no-empty-blocks +contract IForwarder is + IForwarderCore, + IExpectedResults +{} diff --git a/packages/contracts/src/2.0.0/forwarder/interfaces/IForwarderCore.sol b/packages/contracts/src/2.0.0/forwarder/interfaces/IForwarderCore.sol new file mode 100644 index 000000000..7ac2a8af3 --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/interfaces/IForwarderCore.sol @@ -0,0 +1,79 @@ +/* + + Copyright 2018 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.4.24; +pragma experimental ABIEncoderV2; + +import "../../protocol/Exchange/libs/LibOrder.sol"; +import "../../protocol/Exchange/libs/LibFillResults.sol"; + + +contract IForwarderCore { + + /// @dev Market sells ETH for ERC20 tokens, performing fee abstraction if required. This does not support ERC721 tokens. This function is payable + /// and will convert all incoming ETH into WETH and perform the trade on behalf of the caller. + /// This function allows for a deduction of a proportion of incoming ETH sent to the feeRecipient. + /// The caller is sent all tokens from the operation. + /// If the purchased token amount does not meet an acceptable threshold then this function reverts. + /// @param orders An array of Order struct containing order specifications. + /// @param signatures An array of Proof that order has been created by maker. + /// @param feeOrders An array of Order struct containing order specifications for fees. + /// @param feeSignatures An array of Proof that order has been created by maker for the fee orders. + /// @param feeProportion A proportion deducted off the incoming ETH and sent to feeRecipient. The maximum value for this + /// is 1000, aka 10%. Supports up to 2 decimal places. I.e 0.59% is 59. + /// @param feeRecipient An address of the fee recipient whom receives feeProportion of ETH. + /// @return FillResults amounts filled and fees paid by maker and taker. + function marketSellEthForERC20( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + LibOrder.Order[] memory feeOrders, + bytes[] memory feeSignatures, + uint16 feeProportion, + address feeRecipient + ) + public + payable + returns (LibFillResults.FillResults memory totalFillResults); + + /// @dev Buys the exact amount of assets (ERC20 and ERC721), performing fee abstraction if required. + /// All order assets must be of the same type. Deducts a proportional fee to fee recipient. + /// This function is payable and will convert all incoming ETH into WETH and perform the trade on behalf of the caller. + /// The caller is sent all assets from the fill of orders. This function will revert unless the requested amount of assets are purchased. + /// Any excess ETH sent will be returned to the caller + /// @param orders An array of Order struct containing order specifications. + /// @param signatures An array of Proof that order has been created by maker. + /// @param feeOrders An array of Order struct containing order specifications for fees. + /// @param makerTokenFillAmount The amount of maker asset to buy. + /// @param feeSignatures An array of Proof that order has been created by maker for the fee orders. + /// @param feeProportion A proportion deducted off the ETH spent and sent to feeRecipient. The maximum value for this + /// is 1000, aka 10%. Supports up to 2 decimal places. I.e 0.59% is 59. + /// @param feeRecipient An address of the fee recipient whom receives feeProportion of ETH. + /// @return FillResults amounts filled and fees paid by maker and taker. + function marketBuyTokensWithEth( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + LibOrder.Order[] memory feeOrders, + bytes[] memory feeSignatures, + uint256 makerTokenFillAmount, + uint16 feeProportion, + address feeRecipient + ) + public + payable + returns (LibFillResults.FillResults memory totalFillResults); +} diff --git a/packages/contracts/src/2.0.0/forwarder/mixins/MConstants.sol b/packages/contracts/src/2.0.0/forwarder/mixins/MConstants.sol new file mode 100644 index 000000000..348bf169e --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/mixins/MConstants.sol @@ -0,0 +1,35 @@ +/* + + Copyright 2018 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.4.24; + +import "../../protocol/Exchange/interfaces/IExchange.sol"; +import "../../tokens/EtherToken/IEtherToken.sol"; +import "../../tokens/ERC20Token/IERC20Token.sol"; + + +contract MConstants { + + // solhint-disable var-name-mixedcase + IExchange internal EXCHANGE; + IEtherToken internal ETHER_TOKEN; + IERC20Token internal ZRX_TOKEN; + bytes internal ZRX_ASSET_DATA; + bytes internal WETH_ASSET_DATA; + // solhint-enable var-name-mixedcase +} diff --git a/packages/contracts/src/2.0.0/forwarder/mixins/MExpectedResults.sol b/packages/contracts/src/2.0.0/forwarder/mixins/MExpectedResults.sol new file mode 100644 index 000000000..cf03bb32e --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/mixins/MExpectedResults.sol @@ -0,0 +1,42 @@ +/* + + Copyright 2018 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.4.24; +pragma experimental ABIEncoderV2; + +import "../../protocol/Exchange/libs/LibFillResults.sol"; +import "../../protocol/Exchange/libs/LibOrder.sol"; +import "../interfaces/IExpectedResults.sol"; + + +contract MExpectedResults is + IExpectedResults +{ + + /// @dev Simulates the 0x Exchange fillOrder validation and calculations, without performing any state changes. + /// @param order An Order struct containing order specifications. + /// @param takerAssetFillAmount A number representing the amount of this order to fill. + /// @return fillResults Amounts filled and fees paid by maker and taker. + function calculateFillResults( + LibOrder.Order memory order, + uint256 takerAssetFillAmount + ) + internal + view + returns (LibFillResults.FillResults memory fillResults); +} diff --git a/packages/contracts/src/2.0.0/forwarder/mixins/MFees.sol b/packages/contracts/src/2.0.0/forwarder/mixins/MFees.sol new file mode 100644 index 000000000..f332637ea --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/mixins/MFees.sol @@ -0,0 +1,63 @@ +/* + + Copyright 2018 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.4.24; + + +contract MFees { + + /// @dev Pays the feeRecipient feeProportion of the total takerEthAmount, denominated in ETH + /// @param takerEthAmount The total amount that was transacted in WETH, fees are calculated from this value. + /// @param feeProportion The proportion of fees + /// @param feeRecipient The recipient of the fees + /// @return ethFeeAmount Amount of ETH paid to feeRecipient as fee. + function payEthFee( + uint256 takerEthAmount, + uint16 feeProportion, + address feeRecipient + ) + internal + returns (uint256 ethFeeAmount); + + /// @dev Withdraws the remaining WETH, deduct and pay fees from this amount based on the takerTokenAmount to the feeRecipient. + /// If a user overpaid ETH initially, the fees are calculated from the amount traded and deducted from withdrawAmount. + /// Any remaining ETH is sent back to the user. + /// @param ethWithdrawAmount The amount to withdraw from the WETH contract. + /// @param wethAmountSold The total amount that was transacted in WETH, fees are calculated from this value. + /// @param feeProportion The proportion of fees + /// @param feeRecipient The recipient of the fees + function withdrawPayAndDeductEthFee( + uint256 ethWithdrawAmount, + uint256 wethAmountSold, + uint16 feeProportion, + address feeRecipient + ) + internal; + + /// @dev Checks whether the amount of tokens sold against the amount of tokens requested + /// is within a certain threshold. This ensures the caller gets a fair deal when + /// performing any token fee abstraction. Threshold is 95%. If fee abstraction costs more than + /// 5% of the total transaction, we return false. + /// @param requestedSellAmount The amount the user requested, or sent in to a payable function + /// @param tokenAmountSold The amount of the token that was sold after fee abstraction + /// @return bool of whether this is within an acceptable threshold + function isAcceptableThreshold(uint256 requestedSellAmount, uint256 tokenAmountSold) + internal + pure + returns (bool); +} diff --git a/packages/contracts/src/2.0.0/forwarder/mixins/MForwarderCore.sol b/packages/contracts/src/2.0.0/forwarder/mixins/MForwarderCore.sol new file mode 100644 index 000000000..4a54e76b1 --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/mixins/MForwarderCore.sol @@ -0,0 +1,92 @@ +/* + + Copyright 2018 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.4.24; +pragma experimental ABIEncoderV2; + +import "../../protocol/Exchange/libs/LibOrder.sol"; +import "../../protocol/Exchange/libs/LibFillResults.sol"; +import "../interfaces/IForwarderCore.sol"; + + +contract MForwarderCore is + IForwarderCore +{ + + /// @dev Market sells WETH for ERC20 tokens. + /// @param orders An array of Order struct containing order specifications. + /// @param signatures An array of Proof that order has been created by maker. + /// @param feeOrders An array of Order struct containing order specifications for fees. + /// @param feeSignatures An array of Proof that order has been created by maker for the fee orders. + /// @param wethSellAmount The amount of WETH to sell. + /// @return FillResults amounts filled and fees paid by maker and taker. + function marketSellEthForERC20Internal( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + LibOrder.Order[] memory feeOrders, + bytes[] memory feeSignatures, + uint256 wethSellAmount + ) + internal + returns (LibFillResults.FillResults memory totalFillResults); + + /// @dev Market sells WETH for ZRX tokens. + /// @param orders An array of Order struct containing order specifications. + /// @param signatures An array of Proof that order has been created by maker. + /// @param wethSellAmount The amount of WETH to sell. + /// @return FillResults amounts filled and fees paid by maker and taker. + function marketSellEthForZRXInternal( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + uint256 wethSellAmount + ) + internal + returns (LibFillResults.FillResults memory totalFillResults); + + /// @dev Buys an exact amount of an ERC20 token using WETH. + /// @param orders Orders to fill. The maker asset is the ERC20 token to buy. The taker asset is WETH. + /// @param signatures Proof that the orders were created by their respective makers. + /// @param feeOrders to fill. The maker asset is ZRX and the taker asset is WETH. + /// @param feeSignatures Proof that the feeOrders were created by their respective makers. + /// @param makerTokenFillAmount Amount of the ERC20 token to buy. + /// @return totalFillResults Aggregated fill results of buying the ERC20 and ZRX tokens. + function marketBuyERC20TokensInternal( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + LibOrder.Order[] memory feeOrders, + bytes[] memory feeSignatures, + uint256 makerTokenFillAmount + ) + internal + returns (LibFillResults.FillResults memory totalFillResults); + + /// @dev Buys an all of the ERC721 tokens in the orders. + /// @param orders Orders to fill. The maker asset is the ERC721 token to buy. The taker asset is WETH. + /// @param signatures Proof that the orders were created by their respective makers. + /// @param feeOrders to fill. The maker asset is ZRX and the taker asset is WETH. + /// @param feeSignatures Proof that the feeOrders were created by their respective makers. + /// @return totalFillResults Aggregated fill results of buying the ERC721 tokens and ZRX tokens. + function batchBuyERC721TokensInternal( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + LibOrder.Order[] memory feeOrders, + bytes[] memory feeSignatures + ) + internal + returns (LibFillResults.FillResults memory totalFillResults); +} diff --git a/packages/contracts/src/2.0.0/forwarder/mixins/MMarketBuyZrx.sol b/packages/contracts/src/2.0.0/forwarder/mixins/MMarketBuyZrx.sol new file mode 100644 index 000000000..3501ef001 --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/mixins/MMarketBuyZrx.sol @@ -0,0 +1,42 @@ +/* + + Copyright 2018 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.4.24; + +import "../../protocol/Exchange/libs/LibFillResults.sol"; +import "../../protocol/Exchange/libs/LibOrder.sol"; + + +contract MMarketBuyZrx { + + /// @dev Buys zrxBuyAmount of ZRX fee tokens, taking into account the fees on buying fee tokens. This will guarantee + /// At least zrxBuyAmount of ZRX fee tokens are purchased (sometimes slightly over due to rounding issues). + /// It is possible that a request to buy 200 ZRX fee tokens will require purchasing 202 ZRX tokens + /// As 2 ZRX is required to purchase the 200 ZRX fee tokens. This guarantees at least 200 ZRX for future purchases. + /// @param orders An array of Order struct containing order specifications for fees. + /// @param signatures An array of Proof that order has been created by maker for the fee orders. + /// @param zrxBuyAmount The number of requested ZRX fee tokens. + /// @return totalFillResults Amounts filled and fees paid by maker and taker. makerTokenAmount is the zrx amount deducted of fees + function marketBuyZrxInternal( + LibOrder.Order[] memory orders, + bytes[] memory signatures, + uint256 zrxBuyAmount + ) + internal + returns (LibFillResults.FillResults memory totalFillResults); +} diff --git a/packages/contracts/src/2.0.0/forwarder/mixins/MTransfer.sol b/packages/contracts/src/2.0.0/forwarder/mixins/MTransfer.sol new file mode 100644 index 000000000..418a6288b --- /dev/null +++ b/packages/contracts/src/2.0.0/forwarder/mixins/MTransfer.sol @@ -0,0 +1,46 @@ +/* + + Copyright 2018 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.4.24; + + +contract MTransfer { + + function onERC721Received(address, uint256, bytes memory) + public + pure + returns(bytes4); + + function onERC721Received(address, address, uint256, bytes memory) + public + pure + returns(bytes4); + + function transferERC20Token( + address token, + address to, + uint256 amount + ) + internal; + + function transferERC721Token( + bytes memory assetData, + address to + ) + internal; +} diff --git a/packages/contracts/src/2.0.0/multisig/MultiSigWallet.sol b/packages/contracts/src/2.0.0/multisig/MultiSigWallet.sol index 79fd92029..eb54fe047 100644 --- a/packages/contracts/src/2.0.0/multisig/MultiSigWallet.sol +++ b/packages/contracts/src/2.0.0/multisig/MultiSigWallet.sol @@ -1,5 +1,7 @@ +// solhint-disable pragma solidity ^0.4.10; + /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <stefan.george@consensys.net> contract MultiSigWallet { diff --git a/packages/contracts/src/2.0.0/multisig/MultiSigWalletWithTimeLock.sol b/packages/contracts/src/2.0.0/multisig/MultiSigWalletWithTimeLock.sol index 9766c2158..8c5e6e1e6 100644 --- a/packages/contracts/src/2.0.0/multisig/MultiSigWalletWithTimeLock.sol +++ b/packages/contracts/src/2.0.0/multisig/MultiSigWalletWithTimeLock.sol @@ -16,10 +16,12 @@ */ +// solhint-disable pragma solidity ^0.4.10; import "./MultiSigWallet.sol"; + /// @title Multisignature wallet with time lock- Allows multiple parties to execute a transaction after a time lock has passed. /// @author Amir Bandeali - <amir@0xProject.com> contract MultiSigWalletWithTimeLock is MultiSigWallet { diff --git a/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC20Proxy.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC20Proxy.sol index aed62f54f..b5cec6b64 100644 --- a/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC20Proxy.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC20Proxy.sol @@ -16,18 +16,19 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "../../utils/LibBytes/LibBytes.sol"; import "./MixinAuthorizable.sol"; + contract ERC20Proxy is MixinAuthorizable { // Id of this proxy. - bytes4 constant PROXY_ID = bytes4(keccak256("ERC20Token(address)")); + bytes4 constant internal PROXY_ID = bytes4(keccak256("ERC20Token(address)")); + // solhint-disable-next-line payable-fallback function () external { diff --git a/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC721Proxy.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC721Proxy.sol index b73dc36cc..1f9958b43 100644 --- a/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC721Proxy.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC721Proxy.sol @@ -16,18 +16,19 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "../../utils/LibBytes/LibBytes.sol"; import "./MixinAuthorizable.sol"; + contract ERC721Proxy is MixinAuthorizable { // Id of this proxy. - bytes4 constant PROXY_ID = bytes4(keccak256("ERC721Token(address,uint256,bytes)")); + bytes4 constant internal PROXY_ID = bytes4(keccak256("ERC721Token(address,uint256,bytes)")); + // solhint-disable-next-line payable-fallback function () external { diff --git a/packages/contracts/src/2.0.0/protocol/AssetProxy/MixinAuthorizable.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/MixinAuthorizable.sol index 3b9584a44..ff4660a31 100644 --- a/packages/contracts/src/2.0.0/protocol/AssetProxy/MixinAuthorizable.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/MixinAuthorizable.sol @@ -16,12 +16,12 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "../../utils/Ownable/Ownable.sol"; import "./mixins/MAuthorizable.sol"; + contract MixinAuthorizable is Ownable, MAuthorizable diff --git a/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetData.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetData.sol index 7ebd6acf0..3e76e38dd 100644 --- a/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetData.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetData.sol @@ -16,13 +16,15 @@ */ -pragma solidity ^0.4.23; +// solhint-disable +pragma solidity 0.4.24; + // @dev Interface of the asset proxy's assetData. // The asset proxies take an ABI encoded `bytes assetData` as argument. // This argument is ABI encoded as one of the methods of this interface. interface IAssetData { - + function ERC20Token(address tokenContract) external pure; diff --git a/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetProxy.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetProxy.sol index eacd5a412..3651dd694 100644 --- a/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetProxy.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetProxy.sol @@ -16,11 +16,11 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "./IAuthorizable.sol"; + contract IAssetProxy is IAuthorizable { diff --git a/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAuthorizable.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAuthorizable.sol index cedd1744c..8fac43a47 100644 --- a/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAuthorizable.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAuthorizable.sol @@ -16,22 +16,15 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "../../../utils/Ownable/IOwnable.sol"; + contract IAuthorizable is IOwnable { - /// @dev Gets all authorized addresses. - /// @return Array of authorized addresses. - function getAuthorizedAddresses() - external - view - returns (address[]); - /// @dev Authorizes an address. /// @param target Address to authorize. function addAuthorizedAddress(address target) @@ -50,4 +43,11 @@ contract IAuthorizable is uint256 index ) external; + + /// @dev Gets all authorized addresses. + /// @return Array of authorized addresses. + function getAuthorizedAddresses() + external + view + returns (address[] memory); } diff --git a/packages/contracts/src/2.0.0/protocol/AssetProxy/libs/LibAssetProxyErrors.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/libs/LibAssetProxyErrors.sol index 338cb12e2..1d9a70cc1 100644 --- a/packages/contracts/src/2.0.0/protocol/AssetProxy/libs/LibAssetProxyErrors.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/libs/LibAssetProxyErrors.sol @@ -16,7 +16,9 @@ */ -pragma solidity ^0.4.24; +// solhint-disable +pragma solidity 0.4.24; + /// @dev This contract documents the revert reasons used in the AssetProxy contracts. /// This contract is intended to serve as a reference, but is not actually used for efficiency reasons. diff --git a/packages/contracts/src/2.0.0/protocol/AssetProxy/mixins/MAuthorizable.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/mixins/MAuthorizable.sol index 6f35bd7ec..8afc8c8d8 100644 --- a/packages/contracts/src/2.0.0/protocol/AssetProxy/mixins/MAuthorizable.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/mixins/MAuthorizable.sol @@ -16,11 +16,11 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "../interfaces/IAuthorizable.sol"; + contract MAuthorizable is IAuthorizable { diff --git a/packages/contracts/src/2.0.0/protocol/AssetProxyOwner/AssetProxyOwner.sol b/packages/contracts/src/2.0.0/protocol/AssetProxyOwner/AssetProxyOwner.sol index eb58b3374..8b7333646 100644 --- a/packages/contracts/src/2.0.0/protocol/AssetProxyOwner/AssetProxyOwner.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxyOwner/AssetProxyOwner.sol @@ -16,15 +16,14 @@ */ -pragma solidity ^0.4.10; +pragma solidity 0.4.10; import "../../multisig/MultiSigWalletWithTimeLock.sol"; -import "../../utils/LibBytes/LibBytes.sol"; + contract AssetProxyOwner is MultiSigWalletWithTimeLock { - using LibBytes for bytes; event AssetProxyRegistration(address assetProxyContract, bool isRegistered); @@ -32,14 +31,14 @@ contract AssetProxyOwner is // if this contract is allowed to call the AssetProxy's `removeAuthorizedAddressAtIndex` method without a time lock. mapping (address => bool) public isAssetProxyRegistered; - bytes4 constant REMOVE_AUTHORIZED_ADDRESS_AT_INDEX_SELECTOR = bytes4(keccak256("removeAuthorizedAddressAtIndex(address,uint256)")); + bytes4 constant internal REMOVE_AUTHORIZED_ADDRESS_AT_INDEX_SELECTOR = bytes4(keccak256("removeAuthorizedAddressAtIndex(address,uint256)")); /// @dev Function will revert if the transaction does not call `removeAuthorizedAddressAtIndex` /// on an approved AssetProxy contract. modifier validRemoveAuthorizedAddressAtIndexTx(uint256 transactionId) { Transaction storage tx = transactions[transactionId]; require(isAssetProxyRegistered[tx.destination]); - require(tx.data.readBytes4(0) == REMOVE_AUTHORIZED_ADDRESS_AT_INDEX_SELECTOR); + require(readBytes4(tx.data, 0) == REMOVE_AUTHORIZED_ADDRESS_AT_INDEX_SELECTOR); _; } @@ -88,6 +87,7 @@ contract AssetProxyOwner is { Transaction storage tx = transactions[transactionId]; tx.executed = true; + // solhint-disable-next-line avoid-call-value if (tx.destination.call.value(tx.value)(tx.data)) Execution(transactionId); else { @@ -95,4 +95,25 @@ contract AssetProxyOwner is tx.executed = false; } } + + /// @dev Reads an unpadded bytes4 value from a position in a byte array. + /// @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 + returns (bytes4 result) + { + require(b.length >= index + 4); + assembly { + result := mload(add(b, 32)) + // Solidity does not require us to clean the trailing bytes. + // We do it anyway + result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) + } + return result; + } } diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/Exchange.sol b/packages/contracts/src/2.0.0/protocol/Exchange/Exchange.sol index d36e9633e..7507d3da1 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/Exchange.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/Exchange.sol @@ -16,7 +16,7 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "./libs/LibConstants.sol"; @@ -27,6 +27,8 @@ import "./MixinAssetProxyDispatcher.sol"; import "./MixinTransactions.sol"; import "./MixinMatchOrders.sol"; + +// solhint-disable no-empty-blocks contract Exchange is MixinExchangeCore, MixinMatchOrders, diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/MixinAssetProxyDispatcher.sol b/packages/contracts/src/2.0.0/protocol/Exchange/MixinAssetProxyDispatcher.sol index 9e9d88ce7..e9f882194 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/MixinAssetProxyDispatcher.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/MixinAssetProxyDispatcher.sol @@ -16,13 +16,14 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; import "../../utils/Ownable/Ownable.sol"; import "../../utils/LibBytes/LibBytes.sol"; import "./mixins/MAssetProxyDispatcher.sol"; import "../AssetProxy/interfaces/IAssetProxy.sol"; + contract MixinAssetProxyDispatcher is Ownable, MAssetProxyDispatcher @@ -150,6 +151,7 @@ contract MixinAssetProxyDispatcher is /////// Setup Data Area /////// // This area holds `assetData`. let dataArea := add(cdStart, 132) + // solhint-disable-next-line no-empty-blocks for {} lt(dataArea, cdEnd) {} { mstore(dataArea, mload(assetData)) dataArea := add(dataArea, 32) diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/MixinExchangeCore.sol b/packages/contracts/src/2.0.0/protocol/Exchange/MixinExchangeCore.sol index c0ed023ac..ec84b1e19 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/MixinExchangeCore.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/MixinExchangeCore.sol @@ -16,7 +16,7 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "./libs/LibConstants.sol"; @@ -28,6 +28,7 @@ import "./mixins/MSignatureValidator.sol"; import "./mixins/MTransactions.sol"; import "./mixins/MAssetProxyDispatcher.sol"; + contract MixinExchangeCore is LibConstants, LibMath, @@ -48,8 +49,6 @@ contract MixinExchangeCore is // Orders with specified senderAddress and with a salt less than their epoch to are considered cancelled mapping (address => mapping (address => uint256)) public orderEpoch; - ////// Core exchange functions ////// - /// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch /// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress). /// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled. @@ -174,6 +173,7 @@ contract MixinExchangeCore is } // Validate order expiration + // solhint-disable-next-line not-rely-on-time if (block.timestamp >= order.expirationTimeSeconds) { orderInfo.orderStatus = uint8(OrderStatus.EXPIRED); return orderInfo; @@ -374,21 +374,19 @@ contract MixinExchangeCore is returns (FillResults memory fillResults) { // Compute proportional transfer amounts - // TODO: All three are multiplied by the same fraction. This can - // potentially be optimized. fillResults.takerAssetFilledAmount = takerAssetFilledAmount; fillResults.makerAssetFilledAmount = getPartialAmount( - fillResults.takerAssetFilledAmount, + takerAssetFilledAmount, order.takerAssetAmount, order.makerAssetAmount ); fillResults.makerFeePaid = getPartialAmount( - fillResults.takerAssetFilledAmount, + takerAssetFilledAmount, order.takerAssetAmount, order.makerFee ); fillResults.takerFeePaid = getPartialAmount( - fillResults.takerAssetFilledAmount, + takerAssetFilledAmount, order.takerAssetAmount, order.takerFee ); @@ -396,7 +394,7 @@ contract MixinExchangeCore is return fillResults; } - /// @dev Settles an order by transferring assets between counterparties. + /// @dev Settles an order by transferring assets between counterparties. /// @param order Order struct containing order specifications. /// @param takerAddress Address selling takerAsset and buying makerAsset. /// @param fillResults Amounts to be filled and fees paid by maker and taker. diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/MixinMatchOrders.sol b/packages/contracts/src/2.0.0/protocol/Exchange/MixinMatchOrders.sol index 1a43eec79..56b309a1b 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/MixinMatchOrders.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/MixinMatchOrders.sol @@ -11,7 +11,7 @@ limitations under the License. */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "./libs/LibConstants.sol"; @@ -23,6 +23,7 @@ import "./mixins/MMatchOrders.sol"; import "./mixins/MTransactions.sol"; import "./mixins/MAssetProxyDispatcher.sol"; + contract MixinMatchOrders is LibConstants, LibMath, @@ -40,7 +41,6 @@ contract MixinMatchOrders is /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders. - /// TODO: Make this function external once supported by Solidity (See Solidity Issues #3199, #1603) function matchOrders( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, @@ -183,7 +183,6 @@ contract MixinMatchOrders is leftTakerAssetFilledAmount = leftTakerAssetAmountRemaining; // The right order receives an amount proportional to how much was spent. - // TODO: Can we ensure rounding error is in the correct direction? rightTakerAssetFilledAmount = getPartialAmount( rightOrder.takerAssetAmount, rightOrder.makerAssetAmount, @@ -194,7 +193,6 @@ contract MixinMatchOrders is rightTakerAssetFilledAmount = rightTakerAssetAmountRemaining; // The left order receives an amount proportional to how much was spent. - // TODO: Can we ensure rounding error is in the correct direction? leftTakerAssetFilledAmount = getPartialAmount( rightOrder.makerAssetAmount, rightOrder.takerAssetAmount, diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/MixinSignatureValidator.sol b/packages/contracts/src/2.0.0/protocol/Exchange/MixinSignatureValidator.sol index 29172057a..ac7382715 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/MixinSignatureValidator.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/MixinSignatureValidator.sol @@ -16,7 +16,7 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; import "../../utils/LibBytes/LibBytes.sol"; import "./mixins/MSignatureValidator.sol"; @@ -24,6 +24,7 @@ import "./mixins/MTransactions.sol"; import "./interfaces/IWallet.sol"; import "./interfaces/IValidator.sol"; + contract MixinSignatureValidator is MSignatureValidator, MTransactions @@ -90,7 +91,6 @@ contract MixinSignatureValidator is view returns (bool isValid) { - // TODO: Domain separation: make hash depend on role. (Taker sig should not be valid as maker sig, etc.) require( signature.length > 0, "LENGTH_GREATER_THAN_0_REQUIRED" diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/MixinTransactions.sol b/packages/contracts/src/2.0.0/protocol/Exchange/MixinTransactions.sol index 31f7f2847..88d2da7d7 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/MixinTransactions.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/MixinTransactions.sol @@ -15,13 +15,14 @@ limitations under the License. */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; import "./libs/LibExchangeErrors.sol"; import "./mixins/MSignatureValidator.sol"; import "./mixins/MTransactions.sol"; import "./libs/LibEIP712.sol"; + contract MixinTransactions is LibEIP712, MSignatureValidator, @@ -36,7 +37,7 @@ contract MixinTransactions is address public currentContextAddress; // Hash for the EIP712 ZeroEx Transaction Schema - bytes32 constant EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = keccak256(abi.encodePacked( + bytes32 constant internal EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = keccak256(abi.encodePacked( "ZeroExTransaction(", "uint256 salt,", "address signerAddress,", @@ -44,41 +45,6 @@ contract MixinTransactions is ")" )); - /// @dev Calculates EIP712 hash of the Transaction. - /// @param salt Arbitrary number to ensure uniqueness of transaction hash. - /// @param signerAddress Address of transaction signer. - /// @param data AbiV2 encoded calldata. - /// @return EIP712 hash of the Transaction. - function hashZeroExTransaction( - uint256 salt, - address signerAddress, - bytes memory data - ) - internal - pure - returns (bytes32 result) - { - bytes32 schemaHash = EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH; - bytes32 dataHash = keccak256(data); - // Assembly for more efficiently computing: - // keccak256(abi.encode( - // EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH, - // salt, - // signerAddress, - // keccak256(data) - // )); - assembly { - let memPtr := mload(64) - mstore(memPtr, schemaHash) - mstore(add(memPtr, 32), salt) - mstore(add(memPtr, 64), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) - mstore(add(memPtr, 96), dataHash) - result := keccak256(memPtr, 128) - } - - return result; - } - /// @dev Executes an exchange method call in the context of signer. /// @param salt Arbitrary number to ensure uniqueness of transaction hash. /// @param signerAddress Address of transaction signer. @@ -133,9 +99,47 @@ contract MixinTransactions is "FAILED_EXECUTION" ); - // Reset current transaction signer - // TODO: Check if gas is paid when currentContextAddress is already 0. - currentContextAddress = address(0); + // Reset current transaction signer if it was previously updated + if (signerAddress != msg.sender) { + currentContextAddress = address(0); + } + } + + /// @dev Calculates EIP712 hash of the Transaction. + /// @param salt Arbitrary number to ensure uniqueness of transaction hash. + /// @param signerAddress Address of transaction signer. + /// @param data AbiV2 encoded calldata. + /// @return EIP712 hash of the Transaction. + function hashZeroExTransaction( + uint256 salt, + address signerAddress, + bytes memory data + ) + internal + pure + returns (bytes32 result) + { + bytes32 schemaHash = EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH; + bytes32 dataHash = keccak256(data); + + // Assembly for more efficiently computing: + // keccak256(abi.encode( + // EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH, + // salt, + // signerAddress, + // keccak256(data) + // )); + + assembly { + let memPtr := mload(64) + mstore(memPtr, schemaHash) + mstore(add(memPtr, 32), salt) + mstore(add(memPtr, 64), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) + mstore(add(memPtr, 96), dataHash) + result := keccak256(memPtr, 128) + } + + return result; } /// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`). diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/MixinWrapperFunctions.sol b/packages/contracts/src/2.0.0/protocol/Exchange/MixinWrapperFunctions.sol index 00668ca43..a16d2f897 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/MixinWrapperFunctions.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/MixinWrapperFunctions.sol @@ -16,7 +16,7 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "./libs/LibMath.sol"; @@ -24,6 +24,7 @@ import "./libs/LibOrder.sol"; import "./libs/LibFillResults.sol"; import "./mixins/MExchangeCore.sol"; + contract MixinWrapperFunctions is LibMath, LibFillResults, diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IAssetProxyDispatcher.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IAssetProxyDispatcher.sol index 66f3b5796..8db8d6f6c 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IAssetProxyDispatcher.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IAssetProxyDispatcher.sol @@ -16,7 +16,8 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; + contract IAssetProxyDispatcher { diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchange.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchange.sol index 9f21c18d7..b92abba04 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchange.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchange.sol @@ -16,7 +16,7 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "./IExchangeCore.sol"; @@ -26,6 +26,8 @@ import "./ITransactions.sol"; import "./IAssetProxyDispatcher.sol"; import "./IWrapperFunctions.sol"; + +// solhint-disable no-empty-blocks contract IExchange is IExchangeCore, IMatchOrders, diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchangeCore.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchangeCore.sol index 98222f33f..9995e0385 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchangeCore.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchangeCore.sol @@ -16,12 +16,13 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "../libs/LibOrder.sol"; import "../libs/LibFillResults.sol"; + contract IExchangeCore { /// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IMatchOrders.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IMatchOrders.sol index df009d063..73447f3ae 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IMatchOrders.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IMatchOrders.sol @@ -15,12 +15,13 @@ limitations under the License. */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "../libs/LibOrder.sol"; import "../libs/LibFillResults.sol"; + contract IMatchOrders { /// @dev Match two complementary orders that have a profitable spread. @@ -32,7 +33,6 @@ contract IMatchOrders { /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders. - /// TODO: Make this function external once supported by Solidity (See Solidity Issues #3199, #1603) function matchOrders( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ISignatureValidator.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ISignatureValidator.sol index 511463309..1fd0eccf0 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ISignatureValidator.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ISignatureValidator.sol @@ -16,7 +16,8 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; + contract ISignatureValidator { diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ITransactions.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ITransactions.sol index a7cab8f55..4446c55ce 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ITransactions.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ITransactions.sol @@ -15,7 +15,8 @@ limitations under the License. */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; + contract ITransactions { diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IValidator.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IValidator.sol index 0b1796a66..2dd69100c 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IValidator.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IValidator.sol @@ -16,7 +16,8 @@ */ -pragma solidity ^0.4.23; +pragma solidity 0.4.24; + contract IValidator { diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWallet.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWallet.sol index c86a2c057..c97161ca6 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWallet.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWallet.sol @@ -16,7 +16,8 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; + contract IWallet { diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWrapperFunctions.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWrapperFunctions.sol index 84bb683bc..ad7a56a06 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWrapperFunctions.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWrapperFunctions.sol @@ -16,13 +16,15 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "../libs/LibOrder.sol"; import "../libs/LibFillResults.sol"; + contract IWrapperFunctions { + /// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled. /// @param order LibOrder.Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibConstants.sol b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibConstants.sol index 488ca956c..6918d755e 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibConstants.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibConstants.sol @@ -16,13 +16,15 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; + contract LibConstants { // Asset data for ZRX token. Used for fee transfers. // @TODO: Hardcode constant when we deploy. Currently // not constant to make testing easier. + // solhint-disable-next-line var-name-mixedcase bytes public ZRX_ASSET_DATA; // @TODO: Remove when we deploy. diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibEIP712.sol b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibEIP712.sol index b983347a4..1fc41dafd 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibEIP712.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibEIP712.sol @@ -16,17 +16,18 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; + contract LibEIP712 { // EIP191 header for EIP712 prefix - string constant EIP191_HEADER = "\x19\x01"; + string constant internal EIP191_HEADER = "\x19\x01"; // EIP712 Domain Name value - string constant EIP712_DOMAIN_NAME = "0x Protocol"; + string constant internal EIP712_DOMAIN_NAME = "0x Protocol"; // EIP712 Domain Version value - string constant EIP712_DOMAIN_VERSION = "2"; + string constant internal EIP712_DOMAIN_VERSION = "2"; // Hash of the EIP712 Domain Separator Schema bytes32 public constant EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256(abi.encodePacked( @@ -38,6 +39,7 @@ contract LibEIP712 { )); // Hash of the EIP712 Domain Separator data + // solhint-disable-next-line var-name-mixedcase bytes32 public EIP712_DOMAIN_HASH; constructor () diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibExchangeErrors.sol b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibExchangeErrors.sol index 01aa78a1d..a0f75bc06 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibExchangeErrors.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibExchangeErrors.sol @@ -16,7 +16,9 @@ */ -pragma solidity ^0.4.24; +// solhint-disable +pragma solidity 0.4.24; + /// @dev This contract documents the revert reasons used in the Exchange contract. /// This contract is intended to serve as a reference, but is not actually used for efficiency reasons. diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibFillResults.sol b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibFillResults.sol index 63f1b8c87..1b4181d94 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibFillResults.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibFillResults.sol @@ -16,10 +16,11 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; import "../../../utils/SafeMath/SafeMath.sol"; + contract LibFillResults is SafeMath { diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibMath.sol b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibMath.sol index bfe2fd33f..46c13d390 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibMath.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibMath.sol @@ -16,10 +16,11 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; import "../../../utils/SafeMath/SafeMath.sol"; + contract LibMath is SafeMath { diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibOrder.sol b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibOrder.sol index 954f94f76..68f2c8aed 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibOrder.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibOrder.sol @@ -16,16 +16,17 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; import "./LibEIP712.sol"; + contract LibOrder is LibEIP712 { // Hash for the EIP712 Order Schema - bytes32 constant EIP712_ORDER_SCHEMA_HASH = keccak256(abi.encodePacked( + bytes32 constant internal EIP712_ORDER_SCHEMA_HASH = keccak256(abi.encodePacked( "Order(", "address makerAddress,", "address takerAddress,", @@ -54,6 +55,7 @@ contract LibOrder is CANCELLED // Order has been cancelled } + // solhint-disable max-line-length struct Order { address makerAddress; // Address that created the order. address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order. @@ -68,6 +70,7 @@ contract LibOrder is bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy. bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy. } + // solhint-enable max-line-length struct OrderInfo { uint8 orderStatus; // Status that describes order's validity and fillability. @@ -98,34 +101,39 @@ contract LibOrder is bytes32 schemaHash = EIP712_ORDER_SCHEMA_HASH; bytes32 makerAssetDataHash = keccak256(order.makerAssetData); bytes32 takerAssetDataHash = keccak256(order.takerAssetData); + // Assembly for more efficiently computing: - // keccak256(abi.encode( - // order.makerAddress, - // order.takerAddress, - // order.feeRecipientAddress, - // order.senderAddress, - // order.makerAssetAmount, - // order.takerAssetAmount, - // order.makerFee, - // order.takerFee, - // order.expirationTimeSeconds, - // order.salt, - // keccak256(order.makerAssetData), - // keccak256(order.takerAssetData) - // )); + // keccak256(abi.encode( + // order.makerAddress, + // order.takerAddress, + // order.feeRecipientAddress, + // order.senderAddress, + // order.makerAssetAmount, + // order.takerAssetAmount, + // order.makerFee, + // order.takerFee, + // order.expirationTimeSeconds, + // order.salt, + // keccak256(order.makerAssetData), + // keccak256(order.takerAssetData) + // )); + assembly { // Backup + // solhint-disable-next-line space-after-comma let temp1 := mload(sub(order, 32)) let temp2 := mload(add(order, 320)) let temp3 := mload(add(order, 352)) // Hash in place + // solhint-disable-next-line space-after-comma mstore(sub(order, 32), schemaHash) mstore(add(order, 320), makerAssetDataHash) mstore(add(order, 352), takerAssetDataHash) result := keccak256(sub(order, 32), 416) // Restore + // solhint-disable-next-line space-after-comma mstore(sub(order, 32), temp1) mstore(add(order, 320), temp2) mstore(add(order, 352), temp3) diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MAssetProxyDispatcher.sol b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MAssetProxyDispatcher.sol index 5bf59c6ce..c6904300a 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MAssetProxyDispatcher.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MAssetProxyDispatcher.sol @@ -16,11 +16,11 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "../interfaces/IAssetProxyDispatcher.sol"; + contract MAssetProxyDispatcher is IAssetProxyDispatcher { diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MExchangeCore.sol b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MExchangeCore.sol index 6e406e1c4..9e3b5a2e2 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MExchangeCore.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MExchangeCore.sol @@ -16,13 +16,14 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "../libs/LibOrder.sol"; import "../libs/LibFillResults.sol"; import "../interfaces/IExchangeCore.sol"; + contract MExchangeCore is IExchangeCore { @@ -101,7 +102,6 @@ contract MExchangeCore is internal view; - /// @dev Validates context for cancelOrder. Succeeds or throws. /// @param order to be cancelled. /// @param orderInfo OrderStatus, orderHash, and amount already filled of order. diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MMatchOrders.sol b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MMatchOrders.sol index abe7c3596..a31ec1585 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MMatchOrders.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MMatchOrders.sol @@ -15,13 +15,14 @@ limitations under the License. */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "../libs/LibOrder.sol"; import "../libs/LibFillResults.sol"; import "../interfaces/IMatchOrders.sol"; + contract MMatchOrders is IMatchOrders { diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MSignatureValidator.sol b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MSignatureValidator.sol index 6cc1d7a10..f14f2ba00 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MSignatureValidator.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MSignatureValidator.sol @@ -16,10 +16,11 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; import "../interfaces/ISignatureValidator.sol"; + contract MSignatureValidator is ISignatureValidator { diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MTransactions.sol b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MTransactions.sol index e2f89de01..f2b5e4b16 100644 --- a/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MTransactions.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MTransactions.sol @@ -15,10 +15,11 @@ limitations under the License. */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; import "../interfaces/ITransactions.sol"; + contract MTransactions is ITransactions { diff --git a/packages/contracts/src/2.0.0/test/DummyERC20Token/DummyERC20Token.sol b/packages/contracts/src/2.0.0/test/DummyERC20Token/DummyERC20Token.sol index b2fe2df06..97801166a 100644 --- a/packages/contracts/src/2.0.0/test/DummyERC20Token/DummyERC20Token.sol +++ b/packages/contracts/src/2.0.0/test/DummyERC20Token/DummyERC20Token.sol @@ -16,12 +16,12 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "../Mintable/Mintable.sol"; import "../../utils/Ownable/Ownable.sol"; + contract DummyERC20Token is Mintable, Ownable { string public name; string public symbol; diff --git a/packages/contracts/src/2.0.0/test/DummyERC721Receiver/DummyERC721Receiver.sol b/packages/contracts/src/2.0.0/test/DummyERC721Receiver/DummyERC721Receiver.sol index c584d0b54..5dce74a14 100644 --- a/packages/contracts/src/2.0.0/test/DummyERC721Receiver/DummyERC721Receiver.sol +++ b/packages/contracts/src/2.0.0/test/DummyERC721Receiver/DummyERC721Receiver.sol @@ -23,10 +23,11 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; import "../../tokens/ERC721Token/IERC721Receiver.sol"; + contract DummyERC721Receiver is IERC721Receiver { diff --git a/packages/contracts/src/2.0.0/test/DummyERC721Token/DummyERC721Token.sol b/packages/contracts/src/2.0.0/test/DummyERC721Token/DummyERC721Token.sol index 78ea96447..627746a52 100644 --- a/packages/contracts/src/2.0.0/test/DummyERC721Token/DummyERC721Token.sol +++ b/packages/contracts/src/2.0.0/test/DummyERC721Token/DummyERC721Token.sol @@ -16,12 +16,13 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "../../tokens/ERC721Token/ERC721Token.sol"; import "../../utils/Ownable/Ownable.sol"; + +// solhint-disable no-empty-blocks contract DummyERC721Token is Ownable, ERC721Token diff --git a/packages/contracts/src/2.0.0/test/ExchangeWrapper/ExchangeWrapper.sol b/packages/contracts/src/2.0.0/test/ExchangeWrapper/ExchangeWrapper.sol index 5baaf6e5a..2fa0e3c5e 100644 --- a/packages/contracts/src/2.0.0/test/ExchangeWrapper/ExchangeWrapper.sol +++ b/packages/contracts/src/2.0.0/test/ExchangeWrapper/ExchangeWrapper.sol @@ -16,16 +16,18 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "../../protocol/Exchange/interfaces/IExchange.sol"; import "../../protocol/Exchange/libs/LibOrder.sol"; + contract ExchangeWrapper { // Exchange contract. - IExchange EXCHANGE; + // solhint-disable-next-line var-name-mixedcase + IExchange internal EXCHANGE; constructor (address _exchange) public @@ -33,6 +35,35 @@ contract ExchangeWrapper { EXCHANGE = IExchange(_exchange); } + /// @dev Cancels all orders created by sender with a salt less than or equal to the targetOrderEpoch + /// and senderAddress equal to this contract. + /// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled. + /// @param salt Arbitrary value to gaurantee uniqueness of 0x transaction hash. + /// @param makerSignature Proof that maker wishes to call this function with given params. + function cancelOrdersUpTo( + uint256 targetOrderEpoch, + uint256 salt, + bytes makerSignature + ) + external + { + address makerAddress = msg.sender; + + // Encode arguments into byte array. + bytes memory data = abi.encodeWithSelector( + EXCHANGE.cancelOrdersUpTo.selector, + targetOrderEpoch + ); + + // Call `cancelOrdersUpTo` via `executeTransaction`. + EXCHANGE.executeTransaction( + salt, + makerAddress, + data, + makerSignature + ); + } + /// @dev Fills an order using `msg.sender` as the taker. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. @@ -66,33 +97,4 @@ contract ExchangeWrapper { takerSignature ); } - - /// @dev Cancels all orders created by sender with a salt less than or equal to the targetOrderEpoch - /// and senderAddress equal to this contract. - /// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled. - /// @param salt Arbitrary value to gaurantee uniqueness of 0x transaction hash. - /// @param makerSignature Proof that maker wishes to call this function with given params. - function cancelOrdersUpTo( - uint256 targetOrderEpoch, - uint256 salt, - bytes makerSignature - ) - external - { - address makerAddress = msg.sender; - - // Encode arguments into byte array. - bytes memory data = abi.encodeWithSelector( - EXCHANGE.cancelOrdersUpTo.selector, - targetOrderEpoch - ); - - // Call `cancelOrdersUpTo` via `executeTransaction`. - EXCHANGE.executeTransaction( - salt, - makerAddress, - data, - makerSignature - ); - } } diff --git a/packages/contracts/src/2.0.0/test/Mintable/Mintable.sol b/packages/contracts/src/2.0.0/test/Mintable/Mintable.sol index a91bfee9e..767cc8d25 100644 --- a/packages/contracts/src/2.0.0/test/Mintable/Mintable.sol +++ b/packages/contracts/src/2.0.0/test/Mintable/Mintable.sol @@ -16,17 +16,20 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "../../tokens/UnlimitedAllowanceToken/UnlimitedAllowanceToken.sol"; import "../../utils/SafeMath/SafeMath.sol"; + /* * Mintable * Base contract that creates a mintable UnlimitedAllowanceToken */ -contract Mintable is UnlimitedAllowanceToken, SafeMath { +contract Mintable is + UnlimitedAllowanceToken, + SafeMath +{ function mint(uint256 _value) public { diff --git a/packages/contracts/src/2.0.0/test/TestAssetProxyDispatcher/TestAssetProxyDispatcher.sol b/packages/contracts/src/2.0.0/test/TestAssetProxyDispatcher/TestAssetProxyDispatcher.sol index 2ae69e0ef..07986f4bb 100644 --- a/packages/contracts/src/2.0.0/test/TestAssetProxyDispatcher/TestAssetProxyDispatcher.sol +++ b/packages/contracts/src/2.0.0/test/TestAssetProxyDispatcher/TestAssetProxyDispatcher.sol @@ -16,17 +16,18 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "../../protocol/Exchange/MixinAssetProxyDispatcher.sol"; + contract TestAssetProxyDispatcher is MixinAssetProxyDispatcher { function publicDispatchTransferFrom( bytes memory assetData, address from, address to, - uint256 amount) + uint256 amount + ) public { dispatchTransferFrom(assetData, from, to, amount); diff --git a/packages/contracts/src/2.0.0/test/TestAssetProxyOwner/TestAssetProxyOwner.sol b/packages/contracts/src/2.0.0/test/TestAssetProxyOwner/TestAssetProxyOwner.sol index 2abcd17a0..75e782d43 100644 --- a/packages/contracts/src/2.0.0/test/TestAssetProxyOwner/TestAssetProxyOwner.sol +++ b/packages/contracts/src/2.0.0/test/TestAssetProxyOwner/TestAssetProxyOwner.sol @@ -16,14 +16,17 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.10; import "../../protocol/AssetProxyOwner/AssetProxyOwner.sol"; + +// solhint-disable no-empty-blocks contract TestAssetProxyOwner is AssetProxyOwner { - constructor( + + function TestAssetProxyOwner( address[] memory _owners, address[] memory _assetProxyContracts, uint256 _required, @@ -31,8 +34,7 @@ contract TestAssetProxyOwner is ) public AssetProxyOwner(_owners, _assetProxyContracts, _required, _secondsTimeLocked) - { - } + {} function testValidRemoveAuthorizedAddressAtIndexTx(uint256 id) public @@ -48,9 +50,23 @@ contract TestAssetProxyOwner is /// @return Successful if data is a call to `removeAuthorizedAddressAtIndex`. function isFunctionRemoveAuthorizedAddressAtIndex(bytes memory data) public - pure returns (bool) { - return data.readBytes4(0) == REMOVE_AUTHORIZED_ADDRESS_AT_INDEX_SELECTOR; + return readBytes4(data, 0) == REMOVE_AUTHORIZED_ADDRESS_AT_INDEX_SELECTOR; + } + + /// @dev Reads an unpadded bytes4 value from a position in a byte array. + /// @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 + returns (bytes4 result) + { + result = readBytes4(b, index); + return result; } } diff --git a/packages/contracts/src/2.0.0/test/TestLibBytes/TestLibBytes.sol b/packages/contracts/src/2.0.0/test/TestLibBytes/TestLibBytes.sol index f45faaf36..00d861e61 100644 --- a/packages/contracts/src/2.0.0/test/TestLibBytes/TestLibBytes.sol +++ b/packages/contracts/src/2.0.0/test/TestLibBytes/TestLibBytes.sol @@ -16,11 +16,11 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "../../utils/LibBytes/LibBytes.sol"; + contract TestLibBytes { using LibBytes for bytes; diff --git a/packages/contracts/src/2.0.0/test/TestLibs/TestLibs.sol b/packages/contracts/src/2.0.0/test/TestLibs/TestLibs.sol index 010080703..5a349527b 100644 --- a/packages/contracts/src/2.0.0/test/TestLibs/TestLibs.sol +++ b/packages/contracts/src/2.0.0/test/TestLibs/TestLibs.sol @@ -16,13 +16,14 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "../../protocol/Exchange/libs/LibMath.sol"; import "../../protocol/Exchange/libs/LibOrder.sol"; import "../../protocol/Exchange/libs/LibFillResults.sol"; + contract TestLibs is LibMath, LibOrder, @@ -31,7 +32,8 @@ contract TestLibs is function publicGetPartialAmount( uint256 numerator, uint256 denominator, - uint256 target) + uint256 target + ) public pure returns (uint256 partialAmount) @@ -47,7 +49,8 @@ contract TestLibs is function publicIsRoundingError( uint256 numerator, uint256 denominator, - uint256 target) + uint256 target + ) public pure returns (bool isError) diff --git a/packages/contracts/src/2.0.0/test/TestSignatureValidator/TestSignatureValidator.sol b/packages/contracts/src/2.0.0/test/TestSignatureValidator/TestSignatureValidator.sol index 0f84678cf..e1a610469 100644 --- a/packages/contracts/src/2.0.0/test/TestSignatureValidator/TestSignatureValidator.sol +++ b/packages/contracts/src/2.0.0/test/TestSignatureValidator/TestSignatureValidator.sol @@ -16,12 +16,12 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "../../protocol/Exchange/MixinSignatureValidator.sol"; import "../../protocol/Exchange/MixinTransactions.sol"; + contract TestSignatureValidator is MixinSignatureValidator, MixinTransactions diff --git a/packages/contracts/src/2.0.0/test/TestValidator/TestValidator.sol b/packages/contracts/src/2.0.0/test/TestValidator/TestValidator.sol index f9271bf7a..6278aede0 100644 --- a/packages/contracts/src/2.0.0/test/TestValidator/TestValidator.sol +++ b/packages/contracts/src/2.0.0/test/TestValidator/TestValidator.sol @@ -16,16 +16,18 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; import "../../protocol/Exchange/interfaces/IValidator.sol"; + contract TestValidator is IValidator { // The single valid signer for this wallet. - address VALID_SIGNER; + // solhint-disable-next-line var-name-mixedcase + address internal VALID_SIGNER; /// @dev constructs a new `TestValidator` with a single valid signer. /// @param validSigner The sole, valid signer. @@ -38,6 +40,7 @@ contract TestValidator is /// @param signerAddress Address that should have signed the given hash. /// @param signature Proof of signing. /// @return Validity of signature. + // solhint-disable no-unused-vars function isValidSignature( bytes32 hash, address signerAddress, @@ -49,4 +52,5 @@ contract TestValidator is { return (signerAddress == VALID_SIGNER); } + // solhint-enable no-unused-vars } diff --git a/packages/contracts/src/2.0.0/test/TestWallet/TestWallet.sol b/packages/contracts/src/2.0.0/test/TestWallet/TestWallet.sol index 17dee9e9c..0415823e3 100644 --- a/packages/contracts/src/2.0.0/test/TestWallet/TestWallet.sol +++ b/packages/contracts/src/2.0.0/test/TestWallet/TestWallet.sol @@ -16,20 +16,20 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; import "../../protocol/Exchange/interfaces/IWallet.sol"; import "../../utils/LibBytes/LibBytes.sol"; + contract TestWallet is IWallet { using LibBytes for bytes; - string constant LENGTH_65_REQUIRED = "LENGTH_65_REQUIRED"; - // The owner of this wallet. - address WALLET_OWNER; + // solhint-disable-next-line var-name-mixedcase + address internal WALLET_OWNER; /// @dev constructs a new `TestWallet` with a single owner. /// @param walletOwner The owner of this wallet. @@ -52,7 +52,7 @@ contract TestWallet is { require( eip712Signature.length == 65, - LENGTH_65_REQUIRED + "LENGTH_65_REQUIRED" ); uint8 v = uint8(eip712Signature[0]); diff --git a/packages/contracts/src/2.0.0/test/Whitelist/Whitelist.sol b/packages/contracts/src/2.0.0/test/Whitelist/Whitelist.sol index 8b52858b1..60cac26ea 100644 --- a/packages/contracts/src/2.0.0/test/Whitelist/Whitelist.sol +++ b/packages/contracts/src/2.0.0/test/Whitelist/Whitelist.sol @@ -16,29 +16,28 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "../../protocol/Exchange/interfaces/IExchange.sol"; import "../../protocol/Exchange/libs/LibOrder.sol"; import "../../utils/Ownable/Ownable.sol"; + contract Whitelist is Ownable { - // Revert reasons - string constant MAKER_NOT_WHITELISTED = "MAKER_NOT_WHITELISTED"; // Maker address not whitelisted. - string constant TAKER_NOT_WHITELISTED = "TAKER_NOT_WHITELISTED"; // Taker address not whitelisted. - string constant INVALID_SENDER = "INVALID_SENDER"; // Sender must equal transaction origin. // Mapping of address => whitelist status. mapping (address => bool) public isWhitelisted; // Exchange contract. - IExchange EXCHANGE; + // solhint-disable var-name-mixedcase + IExchange internal EXCHANGE; + bytes internal TX_ORIGIN_SIGNATURE; + // solhint-enable var-name-mixedcase - byte constant VALIDATOR_SIGNATURE_BYTE = "\x06"; - bytes TX_ORIGIN_SIGNATURE; + byte constant internal VALIDATOR_SIGNATURE_BYTE = "\x06"; constructor (address _exchange) public @@ -60,6 +59,27 @@ contract Whitelist is isWhitelisted[target] = isApproved; } + /// @dev Verifies signer is same as signer of current Ethereum transaction. + /// NOTE: This function can currently be used to validate signatures coming from outside of this contract. + /// Extra safety checks can be added for a production contract. + /// @param signerAddress Address that should have signed the given hash. + /// @param signature Proof of signing. + /// @return Validity of order signature. + // solhint-disable no-unused-vars + function isValidSignature( + bytes32 hash, + address signerAddress, + bytes signature + ) + external + view + returns (bool isValid) + { + // solhint-disable-next-line avoid-tx-origin + return signerAddress == tx.origin; + } + // solhint-enable no-unused-vars + /// @dev Fills an order using `msg.sender` as the taker. /// The transaction will revert if both the maker and taker are not whitelisted. /// Orders should specify this contract as the `senderAddress` in order to gaurantee @@ -80,20 +100,21 @@ contract Whitelist is // This contract must be the entry point for the transaction. require( + // solhint-disable-next-line avoid-tx-origin takerAddress == tx.origin, - INVALID_SENDER + "INVALID_SENDER" ); // Check if maker is on the whitelist. require( isWhitelisted[order.makerAddress], - MAKER_NOT_WHITELISTED + "MAKER_NOT_WHITELISTED" ); // Check if taker is on the whitelist. require( isWhitelisted[takerAddress], - TAKER_NOT_WHITELISTED + "TAKER_NOT_WHITELISTED" ); // Encode arguments into byte array. @@ -112,22 +133,4 @@ contract Whitelist is TX_ORIGIN_SIGNATURE ); } - - /// @dev Verifies signer is same as signer of current Ethereum transaction. - /// NOTE: This function can currently be used to validate signatures coming from outside of this contract. - /// Extra safety checks can be added for a production contract. - /// @param signerAddress Address that should have signed the given hash. - /// @param signature Proof of signing. - /// @return Validity of order signature. - function isValidSignature( - bytes32 hash, - address signerAddress, - bytes signature - ) - external - view - returns (bool isValid) - { - return signerAddress == tx.origin; - } } diff --git a/packages/contracts/src/2.0.0/tokens/ERC20Token/ERC20Token.sol b/packages/contracts/src/2.0.0/tokens/ERC20Token/ERC20Token.sol index b6961a6ec..d9950145d 100644 --- a/packages/contracts/src/2.0.0/tokens/ERC20Token/ERC20Token.sol +++ b/packages/contracts/src/2.0.0/tokens/ERC20Token/ERC20Token.sol @@ -16,19 +16,15 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "./IERC20Token.sol"; -contract ERC20Token is IERC20Token { - string constant INSUFFICIENT_BALANCE = "ERC20_INSUFFICIENT_BALANCE"; - string constant INSUFFICIENT_ALLOWANCE = "ERC20_INSUFFICIENT_ALLOWANCE"; - string constant OVERFLOW = "Transfer would result in an overflow."; +contract ERC20Token is IERC20Token { - mapping (address => uint256) balances; - mapping (address => mapping (address => uint256)) allowed; + mapping (address => uint256) internal balances; + mapping (address => mapping (address => uint256)) internal allowed; uint256 public totalSupply; @@ -38,11 +34,11 @@ contract ERC20Token is IERC20Token { { require( balances[msg.sender] >= _value, - INSUFFICIENT_BALANCE + "ERC20_INSUFFICIENT_BALANCE" ); require( balances[_to] + _value >= balances[_to], - OVERFLOW + "OVERFLOW" ); balances[msg.sender] -= _value; balances[_to] += _value; @@ -56,15 +52,15 @@ contract ERC20Token is IERC20Token { { require( balances[_from] >= _value, - INSUFFICIENT_BALANCE + "ERC20_INSUFFICIENT_BALANCE" ); require( allowed[_from][msg.sender] >= _value, - INSUFFICIENT_ALLOWANCE + "ERC20_INSUFFICIENT_ALLOWANCE" ); require( balances[_to] + _value >= balances[_to], - OVERFLOW + "OVERFLOW" ); balances[_to] += _value; balances[_from] -= _value; @@ -83,7 +79,8 @@ contract ERC20Token is IERC20Token { } function balanceOf(address _owner) - public view + public + view returns (uint256) { return balances[_owner]; diff --git a/packages/contracts/src/2.0.0/tokens/ERC20Token/IERC20Token.sol b/packages/contracts/src/2.0.0/tokens/ERC20Token/IERC20Token.sol index eb879b6a8..5ee5e1011 100644 --- a/packages/contracts/src/2.0.0/tokens/ERC20Token/IERC20Token.sol +++ b/packages/contracts/src/2.0.0/tokens/ERC20Token/IERC20Token.sol @@ -16,8 +16,8 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; + contract IERC20Token { @@ -59,6 +59,7 @@ contract IERC20Token { public view returns (uint256); + // solhint-disable-next-line no-simple-event-func-name event Transfer( address indexed _from, address indexed _to, diff --git a/packages/contracts/src/2.0.0/tokens/ERC721Token/ERC721Token.sol b/packages/contracts/src/2.0.0/tokens/ERC721Token/ERC721Token.sol index 41ba149e3..60603aa19 100644 --- a/packages/contracts/src/2.0.0/tokens/ERC721Token/ERC721Token.sol +++ b/packages/contracts/src/2.0.0/tokens/ERC721Token/ERC721Token.sol @@ -23,12 +23,13 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; import "./IERC721Token.sol"; import "./IERC721Receiver.sol"; import "../../utils/SafeMath/SafeMath.sol"; + /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md @@ -40,7 +41,7 @@ contract ERC721Token is { // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` - bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; + bytes4 constant internal ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; @@ -72,7 +73,7 @@ contract ERC721Token is _; } - function ERC721Token( + constructor ( string _name, string _symbol) public diff --git a/packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Receiver.sol b/packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Receiver.sol index b0fff3c90..f2e8f3c88 100644 --- a/packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Receiver.sol +++ b/packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Receiver.sol @@ -23,7 +23,8 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; + /** * @title ERC721 token receiver interface @@ -37,7 +38,7 @@ contract IERC721Receiver { * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ - bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; + bytes4 constant internal ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT diff --git a/packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Token.sol b/packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Token.sol index 345712d67..4d57ece38 100644 --- a/packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Token.sol +++ b/packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Token.sol @@ -23,7 +23,8 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; + /** * @title ERC721 Non-Fungible Token Standard basic interface @@ -39,11 +40,13 @@ contract IERC721Token { address indexed _to, uint256 _tokenId ); + event Approval( address indexed _owner, address indexed _approved, uint256 _tokenId ); + event ApprovalForAll( address indexed _owner, address indexed _operator, @@ -54,6 +57,7 @@ contract IERC721Token { public view returns (string); + function symbol() public view @@ -63,10 +67,12 @@ contract IERC721Token { public view returns (uint256 _balance); + function ownerOf(uint256 _tokenId) public view returns (address _owner); + function exists(uint256 _tokenId) public view @@ -74,6 +80,7 @@ contract IERC721Token { function approve(address _to, uint256 _tokenId) public; + function getApproved(uint256 _tokenId) public view @@ -81,6 +88,7 @@ contract IERC721Token { function setApprovalForAll(address _operator, bool _approved) public; + function isApprovedForAll(address _owner, address _operator) public view @@ -89,17 +97,22 @@ contract IERC721Token { function transferFrom( address _from, address _to, - uint256 _tokenId) + uint256 _tokenId + ) public; + function safeTransferFrom( address _from, address _to, - uint256 _tokenId) + uint256 _tokenId + ) public; + function safeTransferFrom( address _from, address _to, uint256 _tokenId, - bytes _data) + bytes _data + ) public; } diff --git a/packages/contracts/src/2.0.0/tokens/EtherToken/IEtherToken.sol b/packages/contracts/src/2.0.0/tokens/EtherToken/IEtherToken.sol new file mode 100644 index 000000000..9e2e68766 --- /dev/null +++ b/packages/contracts/src/2.0.0/tokens/EtherToken/IEtherToken.sol @@ -0,0 +1,33 @@ +/* + + Copyright 2018 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.4.24; + +import "../ERC20Token/IERC20Token.sol"; + + +contract IEtherToken is + IERC20Token +{ + function deposit() + public + payable; + + function withdraw(uint256 amount) + public; +} diff --git a/packages/contracts/src/2.0.0/tokens/WETH9/WETH9.sol b/packages/contracts/src/2.0.0/tokens/EtherToken/WETH9.sol index 733ca414b..1fdb04de5 100644 --- a/packages/contracts/src/2.0.0/tokens/WETH9/WETH9.sol +++ b/packages/contracts/src/2.0.0/tokens/EtherToken/WETH9.sol @@ -13,8 +13,10 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. +// solhint-disable pragma solidity ^0.4.18; + contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; diff --git a/packages/contracts/src/2.0.0/tokens/UnlimitedAllowanceToken/UnlimitedAllowanceToken.sol b/packages/contracts/src/2.0.0/tokens/UnlimitedAllowanceToken/UnlimitedAllowanceToken.sol index f62602ab3..9feb5c914 100644 --- a/packages/contracts/src/2.0.0/tokens/UnlimitedAllowanceToken/UnlimitedAllowanceToken.sol +++ b/packages/contracts/src/2.0.0/tokens/UnlimitedAllowanceToken/UnlimitedAllowanceToken.sol @@ -16,14 +16,14 @@ */ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; import "../ERC20Token/ERC20Token.sol"; + contract UnlimitedAllowanceToken is ERC20Token { - uint256 constant MAX_UINT = 2**256 - 1; + uint256 constant internal 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. @@ -37,15 +37,15 @@ contract UnlimitedAllowanceToken is ERC20Token { uint256 allowance = allowed[_from][msg.sender]; require( balances[_from] >= _value, - INSUFFICIENT_BALANCE + "ERC20_INSUFFICIENT_BALANCE" ); require( allowance >= _value, - INSUFFICIENT_ALLOWANCE + "ERC20_INSUFFICIENT_ALLOWANCE" ); require( balances[_to] + _value >= balances[_to], - OVERFLOW + "OVERFLOW" ); balances[_to] += _value; balances[_from] -= _value; diff --git a/packages/contracts/src/2.0.0/tokens/ZRXToken/ZRXToken.sol b/packages/contracts/src/2.0.0/tokens/ZRXToken/ZRXToken.sol index 2e5b61e0b..28c0b2fb3 100644 --- a/packages/contracts/src/2.0.0/tokens/ZRXToken/ZRXToken.sol +++ b/packages/contracts/src/2.0.0/tokens/ZRXToken/ZRXToken.sol @@ -16,18 +16,24 @@ */ -pragma solidity ^0.4.11; +pragma solidity 0.4.11; +// solhint-disable-next-line max-line-length import { UnlimitedAllowanceToken_v1 as UnlimitedAllowanceToken } from "../../../1.0.0/UnlimitedAllowanceToken/UnlimitedAllowanceToken_v1.sol"; + contract ZRXToken is UnlimitedAllowanceToken { + // solhint-disable const-name-snakecase uint8 constant public decimals = 18; uint public totalSupply = 10**27; // 1 billion tokens, 18 decimal places string constant public name = "0x Protocol Token"; string constant public symbol = "ZRX"; + // solhint-enableconst-name-snakecase - function ZRXToken() { + function ZRXToken() + public + { balances[msg.sender] = totalSupply; } } diff --git a/packages/contracts/src/2.0.0/utils/LibBytes/LibBytes.sol b/packages/contracts/src/2.0.0/utils/LibBytes/LibBytes.sol index 78b1ddf7c..504e950a8 100644 --- a/packages/contracts/src/2.0.0/utils/LibBytes/LibBytes.sol +++ b/packages/contracts/src/2.0.0/utils/LibBytes/LibBytes.sol @@ -16,7 +16,8 @@ */ -pragma solidity ^0.4.24; +pragma solidity 0.4.24; + library LibBytes { @@ -114,6 +115,7 @@ library LibBytes { // Copy whole words front to back // 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) {} { mstore(dest, mload(source)) source := add(source, 32) @@ -144,6 +146,7 @@ library LibBytes { // 2**255, so they can be safely re-interpreted as signed. // 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) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) @@ -156,13 +159,17 @@ library LibBytes { } } } - + /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) - function slice(bytes memory b, uint256 from, uint256 to) + function slice( + bytes memory b, + uint256 from, + uint256 to + ) internal pure returns (bytes memory result) @@ -191,7 +198,11 @@ library LibBytes { /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. - function sliceDestructive(bytes memory b, uint256 from, uint256 to) + function sliceDestructive( + bytes memory b, + uint256 from, + uint256 to + ) internal pure returns (bytes memory result) @@ -343,7 +354,10 @@ library LibBytes { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address - let neighbors := and(mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000) + let neighbors := and( + mload(add(b, index)), + 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 + ) // Make sure input address is clean. // (Solidity does not guarantee this) @@ -443,7 +457,8 @@ library LibBytes { /// @return bytes4 value from byte array. function readBytes4( bytes memory b, - uint256 index) + uint256 index + ) internal pure returns (bytes4 result) @@ -508,7 +523,7 @@ library LibBytes { // Assert length of <b> is valid, given // length of input require( - b.length >= index + 32 /* 32 bytes to store length */ + input.length, + b.length >= index + 32 + input.length, // 32 bytes to store length "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); diff --git a/packages/contracts/src/2.0.0/utils/Ownable/IOwnable.sol b/packages/contracts/src/2.0.0/utils/Ownable/IOwnable.sol index e77680903..116b8dc89 100644 --- a/packages/contracts/src/2.0.0/utils/Ownable/IOwnable.sol +++ b/packages/contracts/src/2.0.0/utils/Ownable/IOwnable.sol @@ -1,5 +1,4 @@ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; /* * Ownable diff --git a/packages/contracts/src/2.0.0/utils/Ownable/Ownable.sol b/packages/contracts/src/2.0.0/utils/Ownable/Ownable.sol index 6f5761cc7..aca65aad2 100644 --- a/packages/contracts/src/2.0.0/utils/Ownable/Ownable.sol +++ b/packages/contracts/src/2.0.0/utils/Ownable/Ownable.sol @@ -1,5 +1,4 @@ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; /* * Ownable @@ -10,6 +9,7 @@ pragma experimental ABIEncoderV2; import "./IOwnable.sol"; + contract Ownable is IOwnable { address public owner; diff --git a/packages/contracts/src/2.0.0/utils/SafeMath/SafeMath.sol b/packages/contracts/src/2.0.0/utils/SafeMath/SafeMath.sol index e137f6ca5..190989181 100644 --- a/packages/contracts/src/2.0.0/utils/SafeMath/SafeMath.sol +++ b/packages/contracts/src/2.0.0/utils/SafeMath/SafeMath.sol @@ -1,42 +1,54 @@ -pragma solidity ^0.4.24; -pragma experimental ABIEncoderV2; +pragma solidity 0.4.24; + contract SafeMath { - function safeMul(uint a, uint b) + function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { - uint c = a * b; - assert(a == 0 || c / a == b); + if (a == 0) { + return 0; + } + uint256 c = a * b; + require( + c / a == b, + "UINT256_OVERFLOW" + ); return c; } - function safeDiv(uint a, uint b) + function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { - uint c = a / b; + uint256 c = a / b; return c; } - function safeSub(uint a, uint b) + function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { - assert(b <= a); + require( + b <= a, + "UINT256_OVERFLOW" + ); return a - b; } - function safeAdd(uint a, uint b) + function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { - uint c = a + b; - assert(c >= a); + uint256 c = a + b; + require( + c >= a, + "UINT256_OVERFLOW" + ); return c; } diff --git a/packages/contracts/test/asset_proxy/authorizable.ts b/packages/contracts/test/asset_proxy/authorizable.ts index 5a0586c28..e99c6cee3 100644 --- a/packages/contracts/test/asset_proxy/authorizable.ts +++ b/packages/contracts/test/asset_proxy/authorizable.ts @@ -5,7 +5,7 @@ import * as chai from 'chai'; import { MixinAuthorizableContract } from '../../generated_contract_wrappers/mixin_authorizable'; import { artifacts } from '../utils/artifacts'; -import { expectRevertReasonOrAlwaysFailingTransactionAsync } from '../utils/assertions'; +import { expectTransactionFailedAsync } from '../utils/assertions'; import { chaiSetup } from '../utils/chai_setup'; import { constants } from '../utils/constants'; import { provider, txDefaults, web3Wrapper } from '../utils/web3_wrapper'; @@ -44,7 +44,7 @@ describe('Authorizable', () => { }); describe('addAuthorizedAddress', () => { it('should throw if not called by owner', async () => { - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( authorizable.addAuthorizedAddress.sendTransactionAsync(notOwner, { from: notOwner }), RevertReason.OnlyContractOwner, ); @@ -62,7 +62,7 @@ describe('Authorizable', () => { await authorizable.addAuthorizedAddress.sendTransactionAsync(address, { from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( authorizable.addAuthorizedAddress.sendTransactionAsync(address, { from: owner }), RevertReason.TargetAlreadyAuthorized, ); @@ -75,7 +75,7 @@ describe('Authorizable', () => { await authorizable.addAuthorizedAddress.sendTransactionAsync(address, { from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( authorizable.removeAuthorizedAddress.sendTransactionAsync(address, { from: notOwner, }), @@ -99,7 +99,7 @@ describe('Authorizable', () => { }); it('should throw if owner attempts to remove an address that is not authorized', async () => { - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( authorizable.removeAuthorizedAddress.sendTransactionAsync(address, { from: owner, }), @@ -115,7 +115,7 @@ describe('Authorizable', () => { constants.AWAIT_TRANSACTION_MINED_MS, ); const index = new BigNumber(0); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, { from: notOwner, }), @@ -128,7 +128,7 @@ describe('Authorizable', () => { constants.AWAIT_TRANSACTION_MINED_MS, ); const index = new BigNumber(1); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, { from: owner, }), @@ -137,7 +137,7 @@ describe('Authorizable', () => { }); it('should throw if owner attempts to remove an address that is not authorized', async () => { const index = new BigNumber(0); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, { from: owner, }), @@ -156,7 +156,7 @@ describe('Authorizable', () => { constants.AWAIT_TRANSACTION_MINED_MS, ); const address1Index = new BigNumber(0); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address2, address1Index, { from: owner, }), diff --git a/packages/contracts/test/asset_proxy/proxies.ts b/packages/contracts/test/asset_proxy/proxies.ts index fc1e53352..36e0800d6 100644 --- a/packages/contracts/test/asset_proxy/proxies.ts +++ b/packages/contracts/test/asset_proxy/proxies.ts @@ -7,17 +7,17 @@ import { LogWithDecodedArgs } from 'ethereum-types'; import ethUtil = require('ethereumjs-util'); import * as _ from 'lodash'; -import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c20_token'; +import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_erc20_token'; import { DummyERC721ReceiverContract, - TokenReceivedContractEventArgs, -} from '../../generated_contract_wrappers/dummy_e_r_c721_receiver'; -import { DummyERC721TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c721_token'; -import { ERC20ProxyContract } from '../../generated_contract_wrappers/e_r_c20_proxy'; -import { ERC721ProxyContract } from '../../generated_contract_wrappers/e_r_c721_proxy'; + DummyERC721ReceiverTokenReceivedEventArgs, +} from '../../generated_contract_wrappers/dummy_erc721_receiver'; +import { DummyERC721TokenContract } from '../../generated_contract_wrappers/dummy_erc721_token'; +import { ERC20ProxyContract } from '../../generated_contract_wrappers/erc20_proxy'; +import { ERC721ProxyContract } from '../../generated_contract_wrappers/erc721_proxy'; import { IAssetProxyContract } from '../../generated_contract_wrappers/i_asset_proxy'; import { artifacts } from '../utils/artifacts'; -import { expectRevertReasonOrAlwaysFailingTransactionAsync } from '../utils/assertions'; +import { expectTransactionFailedAsync } from '../utils/assertions'; import { chaiSetup } from '../utils/chai_setup'; import { constants } from '../utils/constants'; import { ERC20Wrapper } from '../utils/erc20_wrapper'; @@ -184,7 +184,7 @@ describe('Asset Transfer Proxies', () => { constants.AWAIT_TRANSACTION_MINED_MS, ); // Perform a transfer; expect this to fail. - return expectRevertReasonOrAlwaysFailingTransactionAsync( + await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, data, @@ -205,7 +205,7 @@ describe('Asset Transfer Proxies', () => { takerAddress, amount, ); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, data, @@ -272,12 +272,12 @@ describe('Asset Transfer Proxies', () => { to: erc721Proxy.address, data, from: exchangeAddress, - gas: constants.TRANSFER_FROM_GAS, + gas: constants.MAX_TRANSFER_FROM_GAS, }), ); // Verify that no log was emitted by erc721 receiver expect(tx.logs.length).to.be.equal(1); - const tokenReceivedLog = tx.logs[0] as LogWithDecodedArgs<TokenReceivedContractEventArgs>; + const tokenReceivedLog = tx.logs[0] as LogWithDecodedArgs<DummyERC721ReceiverTokenReceivedEventArgs>; expect(tokenReceivedLog.args.from).to.be.equal(makerAddress); expect(tokenReceivedLog.args.tokenId).to.be.bignumber.equal(erc721MakerTokenId); expect(tokenReceivedLog.args.data).to.be.equal(constants.NULL_BYTES); @@ -311,12 +311,12 @@ describe('Asset Transfer Proxies', () => { to: erc721Proxy.address, data, from: exchangeAddress, - gas: constants.TRANSFER_FROM_GAS, + gas: constants.MAX_TRANSFER_FROM_GAS, }), ); // Validate log emitted by erc721 receiver expect(tx.logs.length).to.be.equal(1); - const tokenReceivedLog = tx.logs[0] as LogWithDecodedArgs<TokenReceivedContractEventArgs>; + const tokenReceivedLog = tx.logs[0] as LogWithDecodedArgs<DummyERC721ReceiverTokenReceivedEventArgs>; expect(tokenReceivedLog.args.from).to.be.equal(makerAddress); expect(tokenReceivedLog.args.tokenId).to.be.bignumber.equal(erc721MakerTokenId); expect(tokenReceivedLog.args.data).to.be.equal(receiverData); @@ -344,12 +344,12 @@ describe('Asset Transfer Proxies', () => { erc20Proxy.address, // the ERC20 proxy does not have an ERC721 receiver amount, ); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, data, from: exchangeAddress, - gas: constants.TRANSFER_FROM_GAS, + gas: constants.MAX_TRANSFER_FROM_GAS, }), RevertReason.TransferFailed, ); @@ -369,7 +369,7 @@ describe('Asset Transfer Proxies', () => { takerAddress, amount, ); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, data, @@ -393,7 +393,7 @@ describe('Asset Transfer Proxies', () => { takerAddress, amount, ); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, data, @@ -421,7 +421,7 @@ describe('Asset Transfer Proxies', () => { takerAddress, amount, ); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, data, @@ -442,7 +442,7 @@ describe('Asset Transfer Proxies', () => { takerAddress, amount, ); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, data, diff --git a/packages/contracts/test/exchange/core.ts b/packages/contracts/test/exchange/core.ts index db56623f9..d9f3851d1 100644 --- a/packages/contracts/test/exchange/core.ts +++ b/packages/contracts/test/exchange/core.ts @@ -8,13 +8,13 @@ import { LogWithDecodedArgs } from 'ethereum-types'; import ethUtil = require('ethereumjs-util'); import * as _ from 'lodash'; -import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c20_token'; -import { DummyERC721TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c721_token'; -import { ERC20ProxyContract } from '../../generated_contract_wrappers/e_r_c20_proxy'; -import { ERC721ProxyContract } from '../../generated_contract_wrappers/e_r_c721_proxy'; -import { CancelContractEventArgs, ExchangeContract } from '../../generated_contract_wrappers/exchange'; +import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_erc20_token'; +import { DummyERC721TokenContract } from '../../generated_contract_wrappers/dummy_erc721_token'; +import { ERC20ProxyContract } from '../../generated_contract_wrappers/erc20_proxy'; +import { ERC721ProxyContract } from '../../generated_contract_wrappers/erc721_proxy'; +import { ExchangeCancelEventArgs, ExchangeContract } from '../../generated_contract_wrappers/exchange'; import { artifacts } from '../utils/artifacts'; -import { expectRevertReasonOrAlwaysFailingTransactionAsync } from '../utils/assertions'; +import { expectTransactionFailedAsync } from '../utils/assertions'; import { chaiSetup } from '../utils/chai_setup'; import { constants } from '../utils/constants'; import { ERC20Wrapper } from '../utils/erc20_wrapper'; @@ -144,7 +144,7 @@ describe('Exchange core', () => { const invalidSigBuff = Buffer.concat([v, invalidR, invalidS, signatureType]); const invalidSigHex = `0x${invalidSigBuff.toString('hex')}`; signedOrder.signature = invalidSigHex; - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.fillOrderAsync(signedOrder, takerAddress), RevertReason.InvalidOrderSignature, ); @@ -153,7 +153,7 @@ describe('Exchange core', () => { it('should throw if no value is filled', async () => { signedOrder = orderFactory.newSignedOrder(); await exchangeWrapper.fillOrderAsync(signedOrder, takerAddress); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.fillOrderAsync(signedOrder, takerAddress), RevertReason.OrderUnfillable, ); @@ -167,7 +167,7 @@ describe('Exchange core', () => { }); it('should throw if not sent by maker', async () => { - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.cancelOrderAsync(signedOrder, takerAddress), RevertReason.InvalidMaker, ); @@ -178,7 +178,7 @@ describe('Exchange core', () => { makerAssetAmount: new BigNumber(0), }); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.cancelOrderAsync(signedOrder, makerAddress), RevertReason.OrderUnfillable, ); @@ -189,7 +189,7 @@ describe('Exchange core', () => { takerAssetAmount: new BigNumber(0), }); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.cancelOrderAsync(signedOrder, makerAddress), RevertReason.OrderUnfillable, ); @@ -197,7 +197,7 @@ describe('Exchange core', () => { it('should be able to cancel a full order', async () => { await exchangeWrapper.cancelOrderAsync(signedOrder, makerAddress); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount: signedOrder.takerAssetAmount.div(2), }), @@ -209,7 +209,7 @@ describe('Exchange core', () => { const res = await exchangeWrapper.cancelOrderAsync(signedOrder, makerAddress); expect(res.logs).to.have.length(1); - const log = res.logs[0] as LogWithDecodedArgs<CancelContractEventArgs>; + const log = res.logs[0] as LogWithDecodedArgs<ExchangeCancelEventArgs>; const logArgs = log.args; expect(signedOrder.makerAddress).to.be.equal(logArgs.makerAddress); @@ -222,7 +222,7 @@ describe('Exchange core', () => { it('should throw if already cancelled', async () => { await exchangeWrapper.cancelOrderAsync(signedOrder, makerAddress); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.cancelOrderAsync(signedOrder, makerAddress), RevertReason.OrderUnfillable, ); @@ -232,7 +232,7 @@ describe('Exchange core', () => { signedOrder = orderFactory.newSignedOrder({ expirationTimeSeconds: new BigNumber(Math.floor((Date.now() - 10000) / 1000)), }); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.cancelOrderAsync(signedOrder, makerAddress), RevertReason.OrderUnfillable, ); @@ -250,7 +250,7 @@ describe('Exchange core', () => { }); const fillTakerAssetAmount2 = new BigNumber(1); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount: fillTakerAssetAmount2, }), @@ -264,7 +264,7 @@ describe('Exchange core', () => { const orderEpoch = new BigNumber(1); await exchangeWrapper.cancelOrdersUpToAsync(orderEpoch, makerAddress); const lesserOrderEpoch = new BigNumber(0); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.cancelOrdersUpToAsync(lesserOrderEpoch, makerAddress), RevertReason.InvalidNewOrderEpoch, ); @@ -273,7 +273,7 @@ describe('Exchange core', () => { it('should fail to set orderEpoch equal to existing orderEpoch', async () => { const orderEpoch = new BigNumber(1); await exchangeWrapper.cancelOrdersUpToAsync(orderEpoch, makerAddress); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.cancelOrdersUpToAsync(orderEpoch, makerAddress), RevertReason.InvalidNewOrderEpoch, ); @@ -363,7 +363,7 @@ describe('Exchange core', () => { expect(initialOwnerTakerAsset).to.be.bignumber.equal(takerAddress); // Call Exchange const takerAssetFillAmount = signedOrder.takerAssetAmount; - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount }), RevertReason.TransferFailed, ); @@ -386,7 +386,7 @@ describe('Exchange core', () => { expect(initialOwnerTakerAsset).to.be.bignumber.not.equal(takerAddress); // Call Exchange const takerAssetFillAmount = signedOrder.takerAssetAmount; - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount }), RevertReason.TransferFailed, ); @@ -409,7 +409,7 @@ describe('Exchange core', () => { expect(initialOwnerTakerAsset).to.be.bignumber.equal(takerAddress); // Call Exchange const takerAssetFillAmount = signedOrder.takerAssetAmount; - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount }), RevertReason.InvalidAmount, ); @@ -432,7 +432,7 @@ describe('Exchange core', () => { expect(initialOwnerTakerAsset).to.be.bignumber.equal(takerAddress); // Call Exchange const takerAssetFillAmount = signedOrder.takerAssetAmount; - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount }), RevertReason.InvalidAmount, ); @@ -449,7 +449,7 @@ describe('Exchange core', () => { }); // Call Exchange const takerAssetFillAmount = signedOrder.takerAssetAmount.div(2); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount }), RevertReason.RoundingError, ); @@ -475,7 +475,7 @@ describe('Exchange core', () => { expect(initialOwnerTakerAsset).to.be.bignumber.equal(takerAddress); // Call Exchange const takerAssetFillAmount = signedOrder.takerAssetAmount; - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount }), RevertReason.LengthGreaterThan131Required, ); diff --git a/packages/contracts/test/exchange/dispatcher.ts b/packages/contracts/test/exchange/dispatcher.ts index afbf958d9..11f74d776 100644 --- a/packages/contracts/test/exchange/dispatcher.ts +++ b/packages/contracts/test/exchange/dispatcher.ts @@ -6,15 +6,15 @@ import * as chai from 'chai'; import { LogWithDecodedArgs } from 'ethereum-types'; import * as _ from 'lodash'; -import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c20_token'; -import { ERC20ProxyContract } from '../../generated_contract_wrappers/e_r_c20_proxy'; -import { ERC721ProxyContract } from '../../generated_contract_wrappers/e_r_c721_proxy'; +import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_erc20_token'; +import { ERC20ProxyContract } from '../../generated_contract_wrappers/erc20_proxy'; +import { ERC721ProxyContract } from '../../generated_contract_wrappers/erc721_proxy'; import { - AssetProxyRegisteredContractEventArgs, + TestAssetProxyDispatcherAssetProxyRegisteredEventArgs, TestAssetProxyDispatcherContract, } from '../../generated_contract_wrappers/test_asset_proxy_dispatcher'; import { artifacts } from '../utils/artifacts'; -import { expectRevertReasonOrAlwaysFailingTransactionAsync } from '../utils/assertions'; +import { expectTransactionFailedAsync } from '../utils/assertions'; import { chaiSetup } from '../utils/chai_setup'; import { constants } from '../utils/constants'; import { ERC20Wrapper } from '../utils/erc20_wrapper'; @@ -129,7 +129,7 @@ describe('AssetProxyDispatcher', () => { txDefaults, ); // Register new ERC20 Transfer Proxy contract - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( assetProxyDispatcher.registerAssetProxy.sendTransactionAsync(newErc20TransferProxy.address, { from: owner, }), @@ -138,7 +138,7 @@ describe('AssetProxyDispatcher', () => { }); it('should throw if requesting address is not owner', async () => { - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( assetProxyDispatcher.registerAssetProxy.sendTransactionAsync(erc20Proxy.address, { from: notOwner }), RevertReason.OnlyContractOwner, ); @@ -150,7 +150,7 @@ describe('AssetProxyDispatcher', () => { await assetProxyDispatcher.registerAssetProxy.sendTransactionAsync(erc20Proxy.address, { from: owner }), ); const logs = txReceipt.logs; - const log = logs[0] as LogWithDecodedArgs<AssetProxyRegisteredContractEventArgs>; + const log = logs[0] as LogWithDecodedArgs<TestAssetProxyDispatcherAssetProxyRegisteredEventArgs>; expect(log.args.id).to.equal(AssetProxyId.ERC20); expect(log.args.assetProxy).to.equal(erc20Proxy.address); }); @@ -210,7 +210,7 @@ describe('AssetProxyDispatcher', () => { const encodedAssetData = assetProxyUtils.encodeERC20AssetData(zrxToken.address); // Perform a transfer from makerAddress to takerAddress const amount = new BigNumber(10); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( assetProxyDispatcher.publicDispatchTransferFrom.sendTransactionAsync( encodedAssetData, makerAddress, diff --git a/packages/contracts/test/exchange/fill_order.ts b/packages/contracts/test/exchange/fill_order.ts index 22eb401d9..029bd66e2 100644 --- a/packages/contracts/test/exchange/fill_order.ts +++ b/packages/contracts/test/exchange/fill_order.ts @@ -65,14 +65,7 @@ describe('FillOrder Tests', () => { describe('fillOrder', () => { const test = (fillScenarios: FillScenario[]) => { _.forEach(fillScenarios, fillScenario => { - const orderScenario = fillScenario.orderScenario; - const description = `Combinatorial OrderFill: ${orderScenario.feeRecipientScenario} ${ - orderScenario.makerAssetAmountScenario - } ${orderScenario.takerAssetAmountScenario} ${orderScenario.makerFeeScenario} ${ - orderScenario.takerFeeScenario - } ${orderScenario.expirationTimeSecondsScenario} ${orderScenario.makerAssetDataScenario} ${ - orderScenario.takerAssetDataScenario - }`; + const description = `Combinatorial OrderFill: ${JSON.stringify(fillScenario)}`; it(description, async () => { await coreCombinatorialUtils.testFillOrderScenarioAsync(provider, fillScenario); }); diff --git a/packages/contracts/test/exchange/match_orders.ts b/packages/contracts/test/exchange/match_orders.ts index 0d07d156f..16041e968 100644 --- a/packages/contracts/test/exchange/match_orders.ts +++ b/packages/contracts/test/exchange/match_orders.ts @@ -6,13 +6,13 @@ import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as chai from 'chai'; import * as _ from 'lodash'; -import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c20_token'; -import { DummyERC721TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c721_token'; -import { ERC20ProxyContract } from '../../generated_contract_wrappers/e_r_c20_proxy'; -import { ERC721ProxyContract } from '../../generated_contract_wrappers/e_r_c721_proxy'; +import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_erc20_token'; +import { DummyERC721TokenContract } from '../../generated_contract_wrappers/dummy_erc721_token'; +import { ERC20ProxyContract } from '../../generated_contract_wrappers/erc20_proxy'; +import { ERC721ProxyContract } from '../../generated_contract_wrappers/erc721_proxy'; import { ExchangeContract } from '../../generated_contract_wrappers/exchange'; import { artifacts } from '../utils/artifacts'; -import { expectRevertReasonOrAlwaysFailingTransactionAsync } from '../utils/assertions'; +import { expectTransactionFailedAsync } from '../utils/assertions'; import { chaiSetup } from '../utils/chai_setup'; import { constants } from '../utils/constants'; import { ERC20Wrapper } from '../utils/erc20_wrapper'; @@ -602,7 +602,7 @@ describe('matchOrders', () => { // Cancel left order await exchangeWrapper.cancelOrderAsync(signedOrderLeft, signedOrderLeft.makerAddress); // Match orders - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.matchOrdersAsync(signedOrderLeft, signedOrderRight, takerAddress), RevertReason.OrderUnfillable, ); @@ -627,7 +627,7 @@ describe('matchOrders', () => { // Cancel right order await exchangeWrapper.cancelOrderAsync(signedOrderRight, signedOrderRight.makerAddress); // Match orders - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.matchOrdersAsync(signedOrderLeft, signedOrderRight, takerAddress), RevertReason.OrderUnfillable, ); @@ -650,7 +650,7 @@ describe('matchOrders', () => { feeRecipientAddress: feeRecipientAddressRight, }); // Match orders - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.matchOrdersAsync(signedOrderLeft, signedOrderRight, takerAddress), RevertReason.NegativeSpreadRequired, ); @@ -673,7 +673,7 @@ describe('matchOrders', () => { feeRecipientAddress: feeRecipientAddressRight, }); // Match orders - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.matchOrdersAsync(signedOrderLeft, signedOrderRight, takerAddress), // We are assuming assetData fields of the right order are the // reverse of the left order, rather than checking equality. This @@ -702,7 +702,7 @@ describe('matchOrders', () => { feeRecipientAddress: feeRecipientAddressRight, }); // Match orders - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.matchOrdersAsync(signedOrderLeft, signedOrderRight, takerAddress), RevertReason.InvalidOrderSignature, ); diff --git a/packages/contracts/test/exchange/signature_validator.ts b/packages/contracts/test/exchange/signature_validator.ts index 1db7dfc6d..8cd6409a5 100644 --- a/packages/contracts/test/exchange/signature_validator.ts +++ b/packages/contracts/test/exchange/signature_validator.ts @@ -6,14 +6,14 @@ import { LogWithDecodedArgs } from 'ethereum-types'; import ethUtil = require('ethereumjs-util'); import { - SignatureValidatorApprovalContractEventArgs, TestSignatureValidatorContract, + TestSignatureValidatorSignatureValidatorApprovalEventArgs, } from '../../generated_contract_wrappers/test_signature_validator'; import { TestValidatorContract } from '../../generated_contract_wrappers/test_validator'; import { TestWalletContract } from '../../generated_contract_wrappers/test_wallet'; import { addressUtils } from '../utils/address_utils'; import { artifacts } from '../utils/artifacts'; -import { expectRevertOrOtherErrorAsync } from '../utils/assertions'; +import { expectContractCallFailed } from '../utils/assertions'; import { chaiSetup } from '../utils/chai_setup'; import { constants } from '../utils/constants'; import { LogDecoder } from '../utils/log_decoder'; @@ -101,7 +101,7 @@ describe('MixinSignatureValidator', () => { it('should revert when signature is empty', async () => { const emptySignature = '0x'; const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( signatureValidator.publicIsValidSignature.callAsync( orderHashHex, signedOrder.makerAddress, @@ -115,7 +115,7 @@ describe('MixinSignatureValidator', () => { const unsupportedSignatureType = SignatureType.NSignatureTypes; const unsupportedSignatureHex = `0x${unsupportedSignatureType}`; const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( signatureValidator.publicIsValidSignature.callAsync( orderHashHex, signedOrder.makerAddress, @@ -128,7 +128,7 @@ describe('MixinSignatureValidator', () => { it('should revert when SignatureType=Illegal', async () => { const unsupportedSignatureHex = `0x${SignatureType.Illegal}`; const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( signatureValidator.publicIsValidSignature.callAsync( orderHashHex, signedOrder.makerAddress, @@ -155,7 +155,7 @@ describe('MixinSignatureValidator', () => { const signatureBuffer = Buffer.concat([fillerData, signatureType]); const signatureHex = ethUtil.bufferToHex(signatureBuffer); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( signatureValidator.publicIsValidSignature.callAsync( orderHashHex, signedOrder.makerAddress, @@ -477,7 +477,7 @@ describe('MixinSignatureValidator', () => { ), ); expect(res.logs.length).to.equal(1); - const log = res.logs[0] as LogWithDecodedArgs<SignatureValidatorApprovalContractEventArgs>; + const log = res.logs[0] as LogWithDecodedArgs<TestSignatureValidatorSignatureValidatorApprovalEventArgs>; const logArgs = log.args; expect(logArgs.signerAddress).to.equal(signerAddress); expect(logArgs.validatorAddress).to.equal(testValidator.address); @@ -495,7 +495,7 @@ describe('MixinSignatureValidator', () => { ), ); expect(res.logs.length).to.equal(1); - const log = res.logs[0] as LogWithDecodedArgs<SignatureValidatorApprovalContractEventArgs>; + const log = res.logs[0] as LogWithDecodedArgs<TestSignatureValidatorSignatureValidatorApprovalEventArgs>; const logArgs = log.args; expect(logArgs.signerAddress).to.equal(signerAddress); expect(logArgs.validatorAddress).to.equal(testValidator.address); diff --git a/packages/contracts/test/exchange/transactions.ts b/packages/contracts/test/exchange/transactions.ts index 4f8b49e0e..0d66b11b8 100644 --- a/packages/contracts/test/exchange/transactions.ts +++ b/packages/contracts/test/exchange/transactions.ts @@ -5,13 +5,13 @@ import { BigNumber } from '@0xproject/utils'; import * as chai from 'chai'; import * as _ from 'lodash'; -import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c20_token'; -import { ERC20ProxyContract } from '../../generated_contract_wrappers/e_r_c20_proxy'; +import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_erc20_token'; +import { ERC20ProxyContract } from '../../generated_contract_wrappers/erc20_proxy'; import { ExchangeContract } from '../../generated_contract_wrappers/exchange'; import { ExchangeWrapperContract } from '../../generated_contract_wrappers/exchange_wrapper'; import { WhitelistContract } from '../../generated_contract_wrappers/whitelist'; import { artifacts } from '../utils/artifacts'; -import { expectRevertReasonOrAlwaysFailingTransactionAsync } from '../utils/assertions'; +import { expectTransactionFailedAsync } from '../utils/assertions'; import { chaiSetup } from '../utils/chai_setup'; import { constants } from '../utils/constants'; import { ERC20Wrapper } from '../utils/erc20_wrapper'; @@ -134,7 +134,7 @@ describe('Exchange transactions', () => { }); it('should throw if not called by specified sender', async () => { - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.executeTransactionAsync(signedTx, takerAddress), RevertReason.FailedExecution, ); @@ -177,7 +177,7 @@ describe('Exchange transactions', () => { it('should throw if the a 0x transaction with the same transactionHash has already been executed', async () => { await exchangeWrapper.executeTransactionAsync(signedTx, senderAddress); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.executeTransactionAsync(signedTx, senderAddress), RevertReason.InvalidTxHash, ); @@ -197,7 +197,7 @@ describe('Exchange transactions', () => { }); it('should throw if not called by specified sender', async () => { - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.executeTransactionAsync(signedTx, makerAddress), RevertReason.FailedExecution, ); @@ -205,7 +205,7 @@ describe('Exchange transactions', () => { it('should cancel the order when signed by maker and called by sender', async () => { await exchangeWrapper.executeTransactionAsync(signedTx, senderAddress); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.fillOrderAsync(signedOrder, senderAddress), RevertReason.OrderUnfillable, ); @@ -250,7 +250,7 @@ describe('Exchange transactions', () => { signedOrder.signature, ); const signedFillTx = takerTransactionFactory.newSignedTransaction(fillData); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapperContract.fillOrder.sendTransactionAsync( orderWithoutExchangeAddress, takerAssetFillAmount, @@ -370,7 +370,7 @@ describe('Exchange transactions', () => { orderWithoutExchangeAddress = orderUtils.getOrderWithoutExchangeAddress(signedOrder); const takerAssetFillAmount = signedOrder.takerAssetAmount; const salt = generatePseudoRandomSalt(); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( whitelist.fillOrderIfWhitelisted.sendTransactionAsync( orderWithoutExchangeAddress, takerAssetFillAmount, @@ -392,7 +392,7 @@ describe('Exchange transactions', () => { orderWithoutExchangeAddress = orderUtils.getOrderWithoutExchangeAddress(signedOrder); const takerAssetFillAmount = signedOrder.takerAssetAmount; const salt = generatePseudoRandomSalt(); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( whitelist.fillOrderIfWhitelisted.sendTransactionAsync( orderWithoutExchangeAddress, takerAssetFillAmount, diff --git a/packages/contracts/test/exchange/wrapper.ts b/packages/contracts/test/exchange/wrapper.ts index 7942f7695..655d55b83 100644 --- a/packages/contracts/test/exchange/wrapper.ts +++ b/packages/contracts/test/exchange/wrapper.ts @@ -6,13 +6,13 @@ import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as chai from 'chai'; import * as _ from 'lodash'; -import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c20_token'; -import { DummyERC721TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c721_token'; -import { ERC20ProxyContract } from '../../generated_contract_wrappers/e_r_c20_proxy'; -import { ERC721ProxyContract } from '../../generated_contract_wrappers/e_r_c721_proxy'; +import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_erc20_token'; +import { DummyERC721TokenContract } from '../../generated_contract_wrappers/dummy_erc721_token'; +import { ERC20ProxyContract } from '../../generated_contract_wrappers/erc20_proxy'; +import { ERC721ProxyContract } from '../../generated_contract_wrappers/erc721_proxy'; import { ExchangeContract } from '../../generated_contract_wrappers/exchange'; import { artifacts } from '../utils/artifacts'; -import { expectRevertReasonOrAlwaysFailingTransactionAsync } from '../utils/assertions'; +import { expectTransactionFailedAsync } from '../utils/assertions'; import { chaiSetup } from '../utils/chai_setup'; import { constants } from '../utils/constants'; import { ERC20Wrapper } from '../utils/erc20_wrapper'; @@ -174,7 +174,7 @@ describe('Exchange wrappers', () => { expirationTimeSeconds: new BigNumber(Math.floor((Date.now() - 10000) / 1000)), }); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.fillOrKillOrderAsync(signedOrder, takerAddress), RevertReason.OrderUnfillable, ); @@ -187,7 +187,7 @@ describe('Exchange wrappers', () => { takerAssetFillAmount: signedOrder.takerAssetAmount.div(2), }); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.fillOrKillOrderAsync(signedOrder, takerAddress), RevertReason.CompleteFillFailed, ); @@ -500,7 +500,7 @@ describe('Exchange wrappers', () => { await exchangeWrapper.fillOrKillOrderAsync(signedOrders[0], takerAddress); - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.batchFillOrKillOrdersAsync(signedOrders, takerAddress, { takerAssetFillAmounts, }), @@ -703,7 +703,7 @@ describe('Exchange wrappers', () => { orderFactory.newSignedOrder(), ]; - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.marketSellOrdersAsync(signedOrders, takerAddress, { takerAssetFillAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(1000), 18), }), @@ -921,7 +921,7 @@ describe('Exchange wrappers', () => { orderFactory.newSignedOrder(), ]; - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( exchangeWrapper.marketBuyOrdersAsync(signedOrders, takerAddress, { makerAssetFillAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(1000), 18), }), diff --git a/packages/contracts/test/forwarder/forwarder.ts b/packages/contracts/test/forwarder/forwarder.ts new file mode 100644 index 000000000..f0bf6ac03 --- /dev/null +++ b/packages/contracts/test/forwarder/forwarder.ts @@ -0,0 +1,818 @@ +import { BlockchainLifecycle } from '@0xproject/dev-utils'; +import { assetProxyUtils } from '@0xproject/order-utils'; +import { RevertReason, SignedOrder } from '@0xproject/types'; +import { BigNumber } from '@0xproject/utils'; +import { Web3Wrapper } from '@0xproject/web3-wrapper'; +import * as chai from 'chai'; +import { TransactionReceiptWithDecodedLogs } from 'ethereum-types'; + +import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_erc20_token'; +import { DummyERC721TokenContract } from '../../generated_contract_wrappers/dummy_erc721_token'; +import { ExchangeContract } from '../../generated_contract_wrappers/exchange'; +import { ForwarderContract } from '../../generated_contract_wrappers/forwarder'; +import { WETH9Contract } from '../../generated_contract_wrappers/weth9'; +import { artifacts } from '../utils/artifacts'; +import { expectTransactionFailedAsync } from '../utils/assertions'; +import { chaiSetup } from '../utils/chai_setup'; +import { constants } from '../utils/constants'; +import { ERC20Wrapper } from '../utils/erc20_wrapper'; +import { ERC721Wrapper } from '../utils/erc721_wrapper'; +import { ExchangeWrapper } from '../utils/exchange_wrapper'; +import { formatters } from '../utils/formatters'; +import { ForwarderWrapper } from '../utils/forwarder_wrapper'; +import { OrderFactory } from '../utils/order_factory'; +import { ContractName, ERC20BalancesByOwner } from '../utils/types'; +import { provider, txDefaults, web3Wrapper } from '../utils/web3_wrapper'; + +chaiSetup.configure(); +const expect = chai.expect; +const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); +const DECIMALS_DEFAULT = 18; +// Set a gasPrice so when checking balance of msg.sender we can accurately calculate gasPrice*gasUsed +const DEFAULT_GAS_PRICE = new BigNumber(1); + +describe(ContractName.Forwarder, () => { + let makerAddress: string; + let owner: string; + let takerAddress: string; + let feeRecipientAddress: string; + let otherAddress: string; + let defaultMakerAssetAddress: string; + + let weth: DummyERC20TokenContract; + let zrxToken: DummyERC20TokenContract; + let erc721Token: DummyERC721TokenContract; + let forwarderContract: ForwarderContract; + let wethContract: WETH9Contract; + let forwarderWrapper: ForwarderWrapper; + let exchangeWrapper: ExchangeWrapper; + + let signedOrder: SignedOrder; + let signedOrders: SignedOrder[]; + let orderWithFee: SignedOrder; + let signedOrdersWithFee: SignedOrder[]; + let feeOrder: SignedOrder; + let feeOrders: SignedOrder[]; + let orderFactory: OrderFactory; + let erc20Wrapper: ERC20Wrapper; + let erc20Balances: ERC20BalancesByOwner; + let tx: TransactionReceiptWithDecodedLogs; + + let erc721MakerAssetIds: BigNumber[]; + let feeProportion: number = 0; + + before(async () => { + await blockchainLifecycle.startAsync(); + const accounts = await web3Wrapper.getAvailableAddressesAsync(); + const usedAddresses = ([owner, makerAddress, takerAddress, feeRecipientAddress, otherAddress] = accounts); + + const erc721Wrapper = new ERC721Wrapper(provider, usedAddresses, owner); + erc20Wrapper = new ERC20Wrapper(provider, usedAddresses, owner); + + const numDummyErc20ToDeploy = 3; + let erc20TokenA; + [erc20TokenA, zrxToken] = await erc20Wrapper.deployDummyTokensAsync( + numDummyErc20ToDeploy, + constants.DUMMY_TOKEN_DECIMALS, + ); + const erc20Proxy = await erc20Wrapper.deployProxyAsync(); + await erc20Wrapper.setBalancesAndAllowancesAsync(); + + [erc721Token] = await erc721Wrapper.deployDummyTokensAsync(); + const erc721Proxy = await erc721Wrapper.deployProxyAsync(); + await erc721Wrapper.setBalancesAndAllowancesAsync(); + const erc721Balances = await erc721Wrapper.getBalancesAsync(); + erc721MakerAssetIds = erc721Balances[makerAddress][erc721Token.address]; + + wethContract = await WETH9Contract.deployFrom0xArtifactAsync(artifacts.EtherToken, provider, txDefaults); + weth = new DummyERC20TokenContract(wethContract.abi, wethContract.address, provider); + erc20Wrapper.addDummyTokenContract(weth); + + const wethAssetData = assetProxyUtils.encodeERC20AssetData(wethContract.address); + const zrxAssetData = assetProxyUtils.encodeERC20AssetData(zrxToken.address); + const exchangeInstance = await ExchangeContract.deployFrom0xArtifactAsync( + artifacts.Exchange, + provider, + txDefaults, + zrxAssetData, + ); + const exchangeContract = new ExchangeContract(exchangeInstance.abi, exchangeInstance.address, provider); + exchangeWrapper = new ExchangeWrapper(exchangeContract, provider); + await exchangeWrapper.registerAssetProxyAsync(erc20Proxy.address, owner); + await exchangeWrapper.registerAssetProxyAsync(erc721Proxy.address, owner); + + await erc20Proxy.addAuthorizedAddress.sendTransactionAsync(exchangeInstance.address, { + from: owner, + }); + await erc721Proxy.addAuthorizedAddress.sendTransactionAsync(exchangeInstance.address, { + from: owner, + }); + + defaultMakerAssetAddress = erc20TokenA.address; + const defaultTakerAssetAddress = wethContract.address; + const defaultOrderParams = { + exchangeAddress: exchangeInstance.address, + makerAddress, + feeRecipientAddress, + makerAssetData: assetProxyUtils.encodeERC20AssetData(defaultMakerAssetAddress), + takerAssetData: assetProxyUtils.encodeERC20AssetData(defaultTakerAssetAddress), + makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(200), DECIMALS_DEFAULT), + takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(10), DECIMALS_DEFAULT), + makerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(1), DECIMALS_DEFAULT), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(0), DECIMALS_DEFAULT), + }; + const privateKey = constants.TESTRPC_PRIVATE_KEYS[accounts.indexOf(makerAddress)]; + orderFactory = new OrderFactory(privateKey, defaultOrderParams); + + const forwarderInstance = await ForwarderContract.deployFrom0xArtifactAsync( + artifacts.Forwarder, + provider, + txDefaults, + exchangeInstance.address, + wethContract.address, + zrxToken.address, + zrxAssetData, + wethAssetData, + ); + forwarderContract = new ForwarderContract(forwarderInstance.abi, forwarderInstance.address, provider); + forwarderWrapper = new ForwarderWrapper(forwarderContract, provider, zrxToken.address); + erc20Wrapper.addTokenOwnerAddress(forwarderInstance.address); + + web3Wrapper.abiDecoder.addABI(forwarderContract.abi); + web3Wrapper.abiDecoder.addABI(exchangeInstance.abi); + }); + after(async () => { + await blockchainLifecycle.revertAsync(); + }); + beforeEach(async () => { + await blockchainLifecycle.startAsync(); + feeProportion = 0; + erc20Balances = await erc20Wrapper.getBalancesAsync(); + signedOrder = orderFactory.newSignedOrder(); + signedOrders = [signedOrder]; + feeOrder = orderFactory.newSignedOrder({ + makerAssetData: assetProxyUtils.encodeERC20AssetData(zrxToken.address), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(1), DECIMALS_DEFAULT), + }); + feeOrders = [feeOrder]; + orderWithFee = orderFactory.newSignedOrder({ + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(1), DECIMALS_DEFAULT), + }); + signedOrdersWithFee = [orderWithFee]; + }); + afterEach(async () => { + await blockchainLifecycle.revertAsync(); + }); + describe('calculations', () => { + it('throws if partially filled orders passed in are not enough to satisfy requested amount', async () => { + feeOrders = [feeOrder]; + const makerTokenFillAmount = feeOrder.makerAssetAmount.div(2); + const fillAmountWei = await forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + feeOrders, + [], + feeProportion, + makerTokenFillAmount, + ); + // Fill the feeOrder + tx = await forwarderWrapper.marketBuyTokensWithEthAsync(feeOrders, [], makerTokenFillAmount, { + from: takerAddress, + value: fillAmountWei, + }); + return expect( + forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + feeOrders, + [], + feeProportion, + makerTokenFillAmount, + ), + ).to.be.rejectedWith('Unable to satisfy makerAssetFillAmount with provided orders'); + }); + it('throws if orders passed are cancelled', async () => { + tx = await exchangeWrapper.cancelOrderAsync(feeOrder, makerAddress); + // Cancel the feeOrder + return expect( + forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + feeOrders, + [], + feeProportion, + feeOrder.makerAssetAmount.div(2), + ), + ).to.be.rejectedWith('Unable to satisfy makerAssetFillAmount with provided orders'); + }); + }); + describe('marketSellEthForERC20 without extra fees', () => { + it('should fill the order', async () => { + const fillAmount = signedOrder.takerAssetAmount.div(2); + const makerBalanceBefore = erc20Balances[makerAddress][defaultMakerAssetAddress]; + const takerBalanceBefore = erc20Balances[takerAddress][defaultMakerAssetAddress]; + feeOrders = []; + tx = await forwarderWrapper.marketSellEthForERC20Async(signedOrders, feeOrders, { + value: fillAmount, + from: takerAddress, + }); + const newBalances = await erc20Wrapper.getBalancesAsync(); + const makerBalanceAfter = newBalances[makerAddress][defaultMakerAssetAddress]; + const takerBalanceAfter = newBalances[takerAddress][defaultMakerAssetAddress]; + const makerTokenFillAmount = fillAmount + .times(signedOrder.makerAssetAmount) + .dividedToIntegerBy(signedOrder.takerAssetAmount); + + expect(makerBalanceAfter).to.be.bignumber.equal(makerBalanceBefore.minus(makerTokenFillAmount)); + expect(takerBalanceAfter).to.be.bignumber.equal(takerBalanceBefore.plus(makerTokenFillAmount)); + expect(newBalances[forwarderContract.address][weth.address]).to.be.bignumber.equal(new BigNumber(0)); + }); + it('should fill the order and perform fee abstraction', async () => { + const fillAmount = signedOrder.takerAssetAmount.div(4); + const takerBalanceBefore = erc20Balances[takerAddress][defaultMakerAssetAddress]; + tx = await forwarderWrapper.marketSellEthForERC20Async(signedOrdersWithFee, feeOrders, { + value: fillAmount, + from: takerAddress, + }); + const newBalances = await erc20Wrapper.getBalancesAsync(); + const takerBalanceAfter = newBalances[takerAddress][defaultMakerAssetAddress]; + + const acceptPercentage = 98; + const acceptableThreshold = takerBalanceBefore.plus(fillAmount.times(acceptPercentage).dividedBy(100)); + const isWithinThreshold = takerBalanceAfter.greaterThanOrEqualTo(acceptableThreshold); + expect(isWithinThreshold).to.be.true(); + expect(newBalances[forwarderContract.address][weth.address]).to.be.bignumber.equal(new BigNumber(0)); + }); + it('should fill the order when token is ZRX with fees', async () => { + orderWithFee = orderFactory.newSignedOrder({ + makerAssetData: assetProxyUtils.encodeERC20AssetData(zrxToken.address), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(1), DECIMALS_DEFAULT), + }); + signedOrdersWithFee = [orderWithFee]; + feeOrders = []; + const fillAmount = signedOrder.takerAssetAmount.div(4); + const takerBalanceBefore = erc20Balances[takerAddress][zrxToken.address]; + tx = await forwarderWrapper.marketSellEthForERC20Async(signedOrdersWithFee, feeOrders, { + value: fillAmount, + from: takerAddress, + }); + const newBalances = await erc20Wrapper.getBalancesAsync(); + const takerBalanceAfter = newBalances[takerAddress][zrxToken.address]; + + const acceptPercentage = 98; + const acceptableThreshold = takerBalanceBefore.plus(fillAmount.times(acceptPercentage).dividedBy(100)); + const isWithinThreshold = takerBalanceAfter.greaterThanOrEqualTo(acceptableThreshold); + expect(isWithinThreshold).to.be.true(); + expect(newBalances[forwarderContract.address][weth.address]).to.be.bignumber.equal(new BigNumber(0)); + }); + it('should fail if sent an ETH amount too high', async () => { + signedOrder = orderFactory.newSignedOrder({ + makerAssetData: assetProxyUtils.encodeERC20AssetData(zrxToken.address), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(1), DECIMALS_DEFAULT), + }); + const fillAmount = signedOrder.takerAssetAmount.times(2); + return expectTransactionFailedAsync( + forwarderWrapper.marketSellEthForERC20Async(signedOrdersWithFee, feeOrders, { + value: fillAmount, + from: takerAddress, + }), + RevertReason.UnacceptableThreshold, + ); + }); + it('should fail if fee abstraction amount is too high', async () => { + orderWithFee = orderFactory.newSignedOrder({ + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(50), DECIMALS_DEFAULT), + }); + signedOrdersWithFee = [orderWithFee]; + feeOrder = orderFactory.newSignedOrder({ + makerAssetData: assetProxyUtils.encodeERC20AssetData(zrxToken.address), + makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(1), DECIMALS_DEFAULT), + }); + feeOrders = [feeOrder]; + const fillAmount = signedOrder.takerAssetAmount.div(4); + return expectTransactionFailedAsync( + forwarderWrapper.marketSellEthForERC20Async(signedOrdersWithFee, feeOrders, { + value: fillAmount, + from: takerAddress, + }), + RevertReason.TransferFailed, + ); + }); + it('throws when mixed ERC721 and ERC20 assets with ERC20 first', async () => { + const makerAssetId = erc721MakerAssetIds[0]; + const erc721SignedOrder = orderFactory.newSignedOrder({ + makerAssetAmount: new BigNumber(1), + makerAssetData: assetProxyUtils.encodeERC721AssetData(erc721Token.address, makerAssetId), + }); + const erc20SignedOrder = orderFactory.newSignedOrder(); + signedOrders = [erc20SignedOrder, erc721SignedOrder]; + const fillAmountWei = erc20SignedOrder.takerAssetAmount.plus(erc721SignedOrder.takerAssetAmount); + return expectTransactionFailedAsync( + forwarderWrapper.marketSellEthForERC20Async(signedOrders, feeOrders, { + from: takerAddress, + value: fillAmountWei, + }), + RevertReason.InvalidOrderSignature, + ); + }); + }); + describe('marketSellEthForERC20 with extra fees', () => { + it('should fill the order and send fee to fee recipient', async () => { + const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(feeRecipientAddress); + const fillAmount = signedOrder.takerAssetAmount.div(2); + feeProportion = 150; // 1.5% + feeOrders = []; + tx = await forwarderWrapper.marketSellEthForERC20Async( + signedOrders, + feeOrders, + { + from: takerAddress, + value: fillAmount, + gasPrice: DEFAULT_GAS_PRICE, + }, + { + feeProportion, + feeRecipient: feeRecipientAddress, + }, + ); + const newBalances = await erc20Wrapper.getBalancesAsync(); + const makerBalanceBefore = erc20Balances[makerAddress][defaultMakerAssetAddress]; + const makerBalanceAfter = newBalances[makerAddress][defaultMakerAssetAddress]; + const takerBalanceAfter = newBalances[takerAddress][defaultMakerAssetAddress]; + const afterEthBalance = await web3Wrapper.getBalanceInWeiAsync(feeRecipientAddress); + const takerBoughtAmount = takerBalanceAfter.minus(erc20Balances[takerAddress][defaultMakerAssetAddress]); + + expect(makerBalanceAfter).to.be.bignumber.equal(makerBalanceBefore.minus(takerBoughtAmount)); + expect(afterEthBalance).to.be.bignumber.equal( + initEthBalance.plus(fillAmount.times(feeProportion).dividedBy(10000)), + ); + expect(newBalances[forwarderContract.address][weth.address]).to.be.bignumber.equal(new BigNumber(0)); + }); + it('should fail if the fee is set too high', async () => { + const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(feeRecipientAddress); + const fillAmount = signedOrder.takerAssetAmount.div(2); + feeProportion = 1500; // 15.0% + feeOrders = []; + await expectTransactionFailedAsync( + forwarderWrapper.marketSellEthForERC20Async( + signedOrders, + feeOrders, + { from: takerAddress, value: fillAmount, gasPrice: DEFAULT_GAS_PRICE }, + { feeProportion, feeRecipient: feeRecipientAddress }, + ), + RevertReason.FeeProportionTooLarge, + ); + const afterEthBalance = await web3Wrapper.getBalanceInWeiAsync(feeRecipientAddress); + expect(afterEthBalance).to.be.bignumber.equal(initEthBalance); + }); + }); + describe('marketBuyTokensWithEth', () => { + it('should buy the exact amount of assets', async () => { + const makerAssetAmount = signedOrder.makerAssetAmount.div(2); + const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(takerAddress); + const balancesBefore = await erc20Wrapper.getBalancesAsync(); + const rate = signedOrder.makerAssetAmount.dividedBy(signedOrder.takerAssetAmount); + const fillAmountWei = makerAssetAmount.dividedToIntegerBy(rate); + feeOrders = []; + tx = await forwarderWrapper.marketBuyTokensWithEthAsync(signedOrders, feeOrders, makerAssetAmount, { + from: takerAddress, + value: fillAmountWei, + gasPrice: DEFAULT_GAS_PRICE, + }); + const newBalances = await erc20Wrapper.getBalancesAsync(); + const takerBalanceBefore = balancesBefore[takerAddress][defaultMakerAssetAddress]; + const takerBalanceAfter = newBalances[takerAddress][defaultMakerAssetAddress]; + const afterEthBalance = await web3Wrapper.getBalanceInWeiAsync(takerAddress); + const expectedEthBalanceAfterGasCosts = initEthBalance.minus(fillAmountWei).minus(tx.gasUsed); + expect(takerBalanceAfter).to.be.bignumber.eq(takerBalanceBefore.plus(makerAssetAmount)); + expect(afterEthBalance).to.be.bignumber.eq(expectedEthBalanceAfterGasCosts); + }); + it('should buy the exact amount of assets and return excess ETH', async () => { + const makerAssetAmount = signedOrder.makerAssetAmount.div(2); + const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(takerAddress); + const balancesBefore = await erc20Wrapper.getBalancesAsync(); + const rate = signedOrder.makerAssetAmount.dividedBy(signedOrder.takerAssetAmount); + const fillAmount = makerAssetAmount.dividedToIntegerBy(rate); + const excessFillAmount = fillAmount.times(2); + feeOrders = []; + tx = await forwarderWrapper.marketBuyTokensWithEthAsync(signedOrders, feeOrders, makerAssetAmount, { + from: takerAddress, + value: excessFillAmount, + gasPrice: DEFAULT_GAS_PRICE, + }); + const newBalances = await erc20Wrapper.getBalancesAsync(); + const takerBalanceBefore = balancesBefore[takerAddress][defaultMakerAssetAddress]; + const takerBalanceAfter = newBalances[takerAddress][defaultMakerAssetAddress]; + const afterEthBalance = await web3Wrapper.getBalanceInWeiAsync(takerAddress); + const expectedEthBalanceAfterGasCosts = initEthBalance.minus(fillAmount).minus(tx.gasUsed); + expect(takerBalanceAfter).to.be.bignumber.eq(takerBalanceBefore.plus(makerAssetAmount)); + expect(afterEthBalance).to.be.bignumber.eq(expectedEthBalanceAfterGasCosts); + }); + it('should buy the exact amount of assets with fee abstraction', async () => { + const makerAssetAmount = signedOrder.makerAssetAmount.div(2); + const balancesBefore = await erc20Wrapper.getBalancesAsync(); + const rate = signedOrder.makerAssetAmount.dividedBy(signedOrder.takerAssetAmount); + const fillAmount = makerAssetAmount.dividedToIntegerBy(rate); + const excessFillAmount = fillAmount.times(2); + tx = await forwarderWrapper.marketBuyTokensWithEthAsync(signedOrdersWithFee, feeOrders, makerAssetAmount, { + from: takerAddress, + value: excessFillAmount, + }); + const newBalances = await erc20Wrapper.getBalancesAsync(); + const takerBalanceBefore = balancesBefore[takerAddress][defaultMakerAssetAddress]; + const takerBalanceAfter = newBalances[takerAddress][defaultMakerAssetAddress]; + expect(takerBalanceAfter).to.be.bignumber.eq(takerBalanceBefore.plus(makerAssetAmount)); + }); + it('should buy the exact amount of assets when buying zrx with fee abstraction', async () => { + signedOrder = orderFactory.newSignedOrder({ + makerAssetData: assetProxyUtils.encodeERC20AssetData(zrxToken.address), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(1), DECIMALS_DEFAULT), + }); + signedOrdersWithFee = [signedOrder]; + feeOrders = []; + const makerAssetAmount = signedOrder.makerAssetAmount.div(2); + const takerWeiBalanceBefore = await web3Wrapper.getBalanceInWeiAsync(takerAddress); + const balancesBefore = await erc20Wrapper.getBalancesAsync(); + const fillAmountWei = await forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + signedOrdersWithFee, + feeOrders, + feeProportion, + makerAssetAmount, + ); + tx = await forwarderWrapper.marketBuyTokensWithEthAsync(signedOrdersWithFee, feeOrders, makerAssetAmount, { + from: takerAddress, + value: fillAmountWei, + gasPrice: DEFAULT_GAS_PRICE, + }); + const newBalances = await erc20Wrapper.getBalancesAsync(); + const takerTokenBalanceBefore = balancesBefore[takerAddress][zrxToken.address]; + const takerTokenBalanceAfter = newBalances[takerAddress][zrxToken.address]; + const takerWeiBalanceAfter = await web3Wrapper.getBalanceInWeiAsync(takerAddress); + const expectedCostAfterGas = fillAmountWei.plus(tx.gasUsed); + expect(takerTokenBalanceAfter).to.be.bignumber.greaterThan(takerTokenBalanceBefore.plus(makerAssetAmount)); + expect(takerWeiBalanceAfter).to.be.bignumber.equal(takerWeiBalanceBefore.minus(expectedCostAfterGas)); + }); + it('throws if fees are higher than 5% when buying zrx', async () => { + const highFeeZRXOrder = orderFactory.newSignedOrder({ + makerAssetData: assetProxyUtils.encodeERC20AssetData(zrxToken.address), + makerAssetAmount: signedOrder.makerAssetAmount, + takerFee: signedOrder.makerAssetAmount.times(0.06), + }); + signedOrdersWithFee = [highFeeZRXOrder]; + feeOrders = []; + const makerAssetAmount = signedOrder.makerAssetAmount.div(2); + const fillAmountWei = await forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + signedOrdersWithFee, + feeOrders, + feeProportion, + makerAssetAmount, + ); + return expectTransactionFailedAsync( + forwarderWrapper.marketBuyTokensWithEthAsync(signedOrdersWithFee, feeOrders, makerAssetAmount, { + from: takerAddress, + value: fillAmountWei, + }), + RevertReason.UnacceptableThreshold, + ); + }); + it('throws if fees are higher than 5% when buying erc20', async () => { + const highFeeERC20Order = orderFactory.newSignedOrder({ + takerFee: signedOrder.makerAssetAmount.times(0.06), + }); + signedOrdersWithFee = [highFeeERC20Order]; + feeOrders = [feeOrder]; + const makerAssetAmount = signedOrder.makerAssetAmount.div(2); + const fillAmountWei = await forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + signedOrdersWithFee, + feeOrders, + feeProportion, + makerAssetAmount, + ); + return expectTransactionFailedAsync( + forwarderWrapper.marketBuyTokensWithEthAsync(signedOrdersWithFee, feeOrders, makerAssetAmount, { + from: takerAddress, + value: fillAmountWei, + }), + RevertReason.UnacceptableThreshold as any, + ); + }); + it('throws if makerAssetAmount is 0', async () => { + const makerAssetAmount = new BigNumber(0); + const fillAmountWei = await forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + signedOrdersWithFee, + feeOrders, + feeProportion, + makerAssetAmount, + ); + return expectTransactionFailedAsync( + forwarderWrapper.marketBuyTokensWithEthAsync(signedOrdersWithFee, feeOrders, makerAssetAmount, { + from: takerAddress, + value: fillAmountWei, + }), + RevertReason.ValueGreaterThanZero as any, + ); + }); + it('throws if the amount of ETH sent in is less than the takerAssetFilledAmount', async () => { + const makerAssetAmount = signedOrder.makerAssetAmount; + const fillAmount = signedOrder.takerAssetAmount.div(2); + const zero = new BigNumber(0); + // Deposit enough taker balance to fill the order + const wethDepositTxHash = await wethContract.deposit.sendTransactionAsync({ + from: takerAddress, + value: signedOrder.takerAssetAmount, + }); + await web3Wrapper.awaitTransactionSuccessAsync(wethDepositTxHash); + // Transfer all of this WETH to the forwarding contract + const wethTransferTxHash = await wethContract.transfer.sendTransactionAsync( + forwarderContract.address, + signedOrder.takerAssetAmount, + { from: takerAddress }, + ); + await web3Wrapper.awaitTransactionSuccessAsync(wethTransferTxHash); + // We use the contract directly to get around wrapper validations and calculations + const formattedOrders = formatters.createMarketSellOrders(signedOrders, zero); + const formattedFeeOrders = formatters.createMarketSellOrders(feeOrders, zero); + return expectTransactionFailedAsync( + forwarderContract.marketBuyTokensWithEth.sendTransactionAsync( + formattedOrders.orders, + formattedOrders.signatures, + formattedFeeOrders.orders, + formattedFeeOrders.signatures, + makerAssetAmount, + zero, + constants.NULL_ADDRESS, + { value: fillAmount, from: takerAddress }, + ), + RevertReason.InvalidMsgValue, + ); + }); + }); + describe('marketBuyTokensWithEth - ERC721', async () => { + it('buys ERC721 assets', async () => { + const makerAssetId = erc721MakerAssetIds[0]; + signedOrder = orderFactory.newSignedOrder({ + makerAssetAmount: new BigNumber(1), + makerAssetData: assetProxyUtils.encodeERC721AssetData(erc721Token.address, makerAssetId), + }); + feeOrders = []; + signedOrders = [signedOrder]; + const makerAssetAmount = new BigNumber(signedOrders.length); + const fillAmountWei = await forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + signedOrders, + feeOrders, + feeProportion, + makerAssetAmount, + ); + tx = await forwarderWrapper.marketBuyTokensWithEthAsync(signedOrders, feeOrders, makerAssetAmount, { + from: takerAddress, + value: fillAmountWei, + }); + const newOwnerTakerAsset = await erc721Token.ownerOf.callAsync(makerAssetId); + expect(newOwnerTakerAsset).to.be.bignumber.equal(takerAddress); + }); + it('buys ERC721 assets with fee abstraction', async () => { + const makerAssetId = erc721MakerAssetIds[0]; + signedOrder = orderFactory.newSignedOrder({ + makerAssetAmount: new BigNumber(1), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(1), DECIMALS_DEFAULT), + makerAssetData: assetProxyUtils.encodeERC721AssetData(erc721Token.address, makerAssetId), + }); + signedOrders = [signedOrder]; + const makerAssetAmount = new BigNumber(signedOrders.length); + const fillAmountWei = await forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + signedOrders, + feeOrders, + feeProportion, + makerAssetAmount, + ); + tx = await forwarderWrapper.marketBuyTokensWithEthAsync(signedOrders, feeOrders, makerAssetAmount, { + from: takerAddress, + value: fillAmountWei, + }); + const newOwnerTakerAsset = await erc721Token.ownerOf.callAsync(makerAssetId); + expect(newOwnerTakerAsset).to.be.bignumber.equal(takerAddress); + }); + it('buys ERC721 assets with fee abstraction and pays fee to fee recipient', async () => { + const makerAssetId = erc721MakerAssetIds[0]; + signedOrder = orderFactory.newSignedOrder({ + makerAssetAmount: new BigNumber(1), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(1), DECIMALS_DEFAULT), + makerAssetData: assetProxyUtils.encodeERC721AssetData(erc721Token.address, makerAssetId), + }); + signedOrders = [signedOrder]; + feeProportion = 100; + const initTakerBalanceWei = await web3Wrapper.getBalanceInWeiAsync(takerAddress); + const initFeeRecipientBalanceWei = await web3Wrapper.getBalanceInWeiAsync(feeRecipientAddress); + const makerAssetAmount = new BigNumber(signedOrders.length); + const fillAmountWei = await forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + signedOrders, + feeOrders, + feeProportion, + makerAssetAmount, + ); + tx = await forwarderWrapper.marketBuyTokensWithEthAsync( + signedOrders, + feeOrders, + makerAssetAmount, + { + from: takerAddress, + value: fillAmountWei, + gasPrice: DEFAULT_GAS_PRICE, + }, + { + feeProportion, + feeRecipient: feeRecipientAddress, + }, + ); + const afterFeeRecipientEthBalance = await web3Wrapper.getBalanceInWeiAsync(feeRecipientAddress); + const afterTakerBalanceWei = await web3Wrapper.getBalanceInWeiAsync(takerAddress); + const takerFilledAmount = initTakerBalanceWei.minus(afterTakerBalanceWei).plus(tx.gasUsed); + const newOwnerTakerAsset = await erc721Token.ownerOf.callAsync(makerAssetId); + expect(newOwnerTakerAsset).to.be.bignumber.equal(takerAddress); + const balanceDiff = afterFeeRecipientEthBalance.minus(initFeeRecipientBalanceWei); + expect(takerFilledAmount.dividedToIntegerBy(balanceDiff)).to.be.bignumber.equal(101); + expect(takerFilledAmount.minus(balanceDiff).dividedToIntegerBy(balanceDiff)).to.be.bignumber.equal(100); + }); + it('buys multiple ERC721 assets with fee abstraction and pays fee to fee recipient', async () => { + const makerAssetId1 = erc721MakerAssetIds[0]; + const makerAssetId2 = erc721MakerAssetIds[1]; + const signedOrder1 = orderFactory.newSignedOrder({ + makerAssetAmount: new BigNumber(1), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(3), DECIMALS_DEFAULT), + makerAssetData: assetProxyUtils.encodeERC721AssetData(erc721Token.address, makerAssetId1), + }); + const signedOrder2 = orderFactory.newSignedOrder({ + makerAssetAmount: new BigNumber(1), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(4), DECIMALS_DEFAULT), + makerAssetData: assetProxyUtils.encodeERC721AssetData(erc721Token.address, makerAssetId2), + }); + signedOrders = [signedOrder1, signedOrder2]; + feeProportion = 10; + const makerAssetAmount = new BigNumber(signedOrders.length); + const fillAmountWei = await forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + signedOrders, + feeOrders, + feeProportion, + makerAssetAmount, + ); + tx = await forwarderWrapper.marketBuyTokensWithEthAsync(signedOrders, feeOrders, makerAssetAmount, { + from: takerAddress, + value: fillAmountWei, + }); + const newOwnerTakerAsset1 = await erc721Token.ownerOf.callAsync(makerAssetId1); + expect(newOwnerTakerAsset1).to.be.bignumber.equal(takerAddress); + const newOwnerTakerAsset2 = await erc721Token.ownerOf.callAsync(makerAssetId2); + expect(newOwnerTakerAsset2).to.be.bignumber.equal(takerAddress); + }); + it('buys ERC721 assets with fee abstraction and handles fee orders filled and excess eth', async () => { + const makerAssetId = erc721MakerAssetIds[0]; + feeProportion = 0; + // In this scenario a total of 6 ZRX fees need to be paid. + // There are two fee orders, but the first fee order is partially filled while + // the Forwarding contract tx is in the mempool. + const erc721MakerAssetAmount = new BigNumber(1); + signedOrder = orderFactory.newSignedOrder({ + makerAssetAmount: erc721MakerAssetAmount, + takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(10), DECIMALS_DEFAULT), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(6), DECIMALS_DEFAULT), + makerAssetData: assetProxyUtils.encodeERC721AssetData(erc721Token.address, makerAssetId), + }); + signedOrders = [signedOrder]; + const firstFeeOrder = orderFactory.newSignedOrder({ + makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(8), DECIMALS_DEFAULT), + takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(0.1), DECIMALS_DEFAULT), + makerAssetData: assetProxyUtils.encodeERC20AssetData(zrxToken.address), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(0), DECIMALS_DEFAULT), + }); + const secondFeeOrder = orderFactory.newSignedOrder({ + makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(8), DECIMALS_DEFAULT), + takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(0.12), DECIMALS_DEFAULT), + makerAssetData: assetProxyUtils.encodeERC20AssetData(zrxToken.address), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(0), DECIMALS_DEFAULT), + }); + feeOrders = [firstFeeOrder, secondFeeOrder]; + const makerAssetAmount = new BigNumber(signedOrders.length); + const fillAmountWei = await forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + signedOrders, + feeOrders, + feeProportion, + erc721MakerAssetAmount, + ); + // Simulate another otherAddress user partially filling firstFeeOrder + const firstFeeOrderFillAmount = firstFeeOrder.makerAssetAmount.div(2); + tx = await forwarderWrapper.marketBuyTokensWithEthAsync([firstFeeOrder], [], firstFeeOrderFillAmount, { + from: otherAddress, + value: fillAmountWei, + }); + // For tests we calculate how much this should've cost given that firstFeeOrder was filled + const expectedFillAmountWei = await forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + signedOrders, + feeOrders, + feeProportion, + erc721MakerAssetAmount, + ); + // With 4 ZRX remaining in firstFeeOrder, the secondFeeOrder will need to be filled to make up + // the total amount of fees required (6) + // Since the fee orders can be filled while the transaction is pending the user safely sends in + // extra ether to cover any slippage + const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(takerAddress); + const slippageFillAmountWei = fillAmountWei.times(2); + tx = await forwarderWrapper.marketBuyTokensWithEthAsync(signedOrders, feeOrders, makerAssetAmount, { + from: takerAddress, + value: slippageFillAmountWei, + gasPrice: DEFAULT_GAS_PRICE, + }); + const afterEthBalance = await web3Wrapper.getBalanceInWeiAsync(takerAddress); + const expectedEthBalanceAfterGasCosts = initEthBalance.minus(expectedFillAmountWei).minus(tx.gasUsed); + const newOwnerTakerAsset = await erc721Token.ownerOf.callAsync(makerAssetId); + expect(newOwnerTakerAsset).to.be.bignumber.equal(takerAddress); + expect(afterEthBalance).to.be.bignumber.equal(expectedEthBalanceAfterGasCosts); + }); + it('buys ERC721 assets with fee abstraction and handles fee orders filled', async () => { + const makerAssetId = erc721MakerAssetIds[0]; + feeProportion = 0; + // In this scenario a total of 6 ZRX fees need to be paid. + // There are two fee orders, but the first fee order is partially filled while + // the Forwarding contract tx is in the mempool. + const erc721MakerAssetAmount = new BigNumber(1); + signedOrder = orderFactory.newSignedOrder({ + makerAssetAmount: erc721MakerAssetAmount, + takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(10), DECIMALS_DEFAULT), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(6), DECIMALS_DEFAULT), + makerAssetData: assetProxyUtils.encodeERC721AssetData(erc721Token.address, makerAssetId), + }); + const zrxMakerAssetAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(8), DECIMALS_DEFAULT); + signedOrders = [signedOrder]; + const firstFeeOrder = orderFactory.newSignedOrder({ + makerAssetAmount: zrxMakerAssetAmount, + takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(0.1), DECIMALS_DEFAULT), + makerAssetData: assetProxyUtils.encodeERC20AssetData(zrxToken.address), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(0), DECIMALS_DEFAULT), + }); + const secondFeeOrder = orderFactory.newSignedOrder({ + makerAssetAmount: zrxMakerAssetAmount, + takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(0.12), DECIMALS_DEFAULT), + makerAssetData: assetProxyUtils.encodeERC20AssetData(zrxToken.address), + takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(0), DECIMALS_DEFAULT), + }); + feeOrders = [firstFeeOrder, secondFeeOrder]; + const makerAssetAmount = new BigNumber(signedOrders.length); + const fillAmountWei = await forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + signedOrders, + feeOrders, + feeProportion, + erc721MakerAssetAmount, + ); + // Simulate another otherAddress user partially filling firstFeeOrder + const firstFeeOrderFillAmount = firstFeeOrder.makerAssetAmount.div(2); + tx = await forwarderWrapper.marketBuyTokensWithEthAsync([firstFeeOrder], [], firstFeeOrderFillAmount, { + from: otherAddress, + value: fillAmountWei, + }); + const expectedFillAmountWei = await forwarderWrapper.calculateMarketBuyFillAmountWeiAsync( + signedOrders, + feeOrders, + feeProportion, + erc721MakerAssetAmount, + ); + tx = await forwarderWrapper.marketBuyTokensWithEthAsync(signedOrders, feeOrders, makerAssetAmount, { + from: takerAddress, + value: expectedFillAmountWei, + }); + const newOwnerTakerAsset = await erc721Token.ownerOf.callAsync(makerAssetId); + expect(newOwnerTakerAsset).to.be.bignumber.equal(takerAddress); + }); + it('throws when mixed ERC721 and ERC20 assets', async () => { + const makerAssetId = erc721MakerAssetIds[0]; + const erc721SignedOrder = orderFactory.newSignedOrder({ + makerAssetAmount: new BigNumber(1), + makerAssetData: assetProxyUtils.encodeERC721AssetData(erc721Token.address, makerAssetId), + }); + const erc20SignedOrder = orderFactory.newSignedOrder(); + signedOrders = [erc721SignedOrder, erc20SignedOrder]; + const makerAssetAmount = new BigNumber(signedOrders.length); + const fillAmountWei = erc20SignedOrder.takerAssetAmount.plus(erc721SignedOrder.takerAssetAmount); + return expectTransactionFailedAsync( + forwarderWrapper.marketBuyTokensWithEthAsync(signedOrders, feeOrders, makerAssetAmount, { + from: takerAddress, + value: fillAmountWei, + }), + RevertReason.LibBytesGreaterOrEqualTo32LengthRequired, + ); + }); + it('throws when mixed ERC721 and ERC20 assets with ERC20 first', async () => { + const makerAssetId = erc721MakerAssetIds[0]; + const erc721SignedOrder = orderFactory.newSignedOrder({ + makerAssetAmount: new BigNumber(1), + makerAssetData: assetProxyUtils.encodeERC721AssetData(erc721Token.address, makerAssetId), + }); + const erc20SignedOrder = orderFactory.newSignedOrder(); + signedOrders = [erc20SignedOrder, erc721SignedOrder]; + const makerAssetAmount = new BigNumber(signedOrders.length); + const fillAmountWei = erc20SignedOrder.takerAssetAmount.plus(erc721SignedOrder.takerAssetAmount); + return expectTransactionFailedAsync( + forwarderWrapper.marketBuyTokensWithEthAsync(signedOrders, feeOrders, makerAssetAmount, { + from: takerAddress, + value: fillAmountWei, + }), + RevertReason.InvalidTakerAmount, + ); + }); + }); +}); +// tslint:disable:max-file-line-count +// tslint:enable:no-unnecessary-type-assertion diff --git a/packages/contracts/test/libraries/lib_bytes.ts b/packages/contracts/test/libraries/lib_bytes.ts index 963b51b8f..c80b61e19 100644 --- a/packages/contracts/test/libraries/lib_bytes.ts +++ b/packages/contracts/test/libraries/lib_bytes.ts @@ -9,7 +9,7 @@ import * as _ from 'lodash'; import { TestLibBytesContract } from '../../generated_contract_wrappers/test_lib_bytes'; import { artifacts } from '../utils/artifacts'; -import { expectRevertOrOtherErrorAsync } from '../utils/assertions'; +import { expectContractCallFailed } from '../utils/assertions'; import { chaiSetup } from '../utils/chai_setup'; import { constants } from '../utils/constants'; import { provider, txDefaults, web3Wrapper } from '../utils/web3_wrapper'; @@ -100,7 +100,7 @@ describe('LibBytes', () => { describe('popLastByte', () => { it('should revert if length is 0', async () => { - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicPopLastByte.callAsync(constants.NULL_BYTES), RevertReason.LibBytesGreaterThanZeroLengthRequired, ); @@ -116,7 +116,7 @@ describe('LibBytes', () => { describe('popLast20Bytes', () => { it('should revert if length is less than 20', async () => { - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicPopLast20Bytes.callAsync(byteArrayShorterThan20Bytes), RevertReason.LibBytesGreaterOrEqualTo20LengthRequired, ); @@ -184,7 +184,7 @@ describe('LibBytes', () => { describe('deepCopyBytes', () => { it('should revert if dest is shorter than source', async () => { - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicDeepCopyBytes.callAsync(byteArrayShorterThan32Bytes, byteArrayLongerThan32Bytes), RevertReason.LibBytesGreaterOrEqualToSourceBytesLengthRequired, ); @@ -237,7 +237,7 @@ describe('LibBytes', () => { it('should fail if the byte array is too short to hold an address', async () => { const shortByteArray = '0xabcdef'; const offset = new BigNumber(0); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicReadAddress.callAsync(shortByteArray, offset), RevertReason.LibBytesGreaterOrEqualTo20LengthRequired, ); @@ -245,7 +245,7 @@ describe('LibBytes', () => { it('should fail if the length between the offset and end of the byte array is too short to hold an address', async () => { const byteArray = testAddress; const badOffset = new BigNumber(ethUtil.toBuffer(byteArray).byteLength); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicReadAddress.callAsync(byteArray, badOffset), RevertReason.LibBytesGreaterOrEqualTo20LengthRequired, ); @@ -281,7 +281,7 @@ describe('LibBytes', () => { }); it('should fail if the byte array is too short to hold an address', async () => { const offset = new BigNumber(0); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicWriteAddress.callAsync(byteArrayShorterThan20Bytes, offset, testAddress), RevertReason.LibBytesGreaterOrEqualTo20LengthRequired, ); @@ -289,7 +289,7 @@ describe('LibBytes', () => { it('should fail if the length between the offset and end of the byte array is too short to hold an address', async () => { const byteArray = byteArrayLongerThan32Bytes; const badOffset = new BigNumber(ethUtil.toBuffer(byteArray).byteLength); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicWriteAddress.callAsync(byteArray, badOffset, testAddress), RevertReason.LibBytesGreaterOrEqualTo20LengthRequired, ); @@ -313,14 +313,14 @@ describe('LibBytes', () => { }); it('should fail if the byte array is too short to hold a bytes32', async () => { const offset = new BigNumber(0); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicReadBytes32.callAsync(byteArrayShorterThan32Bytes, offset), RevertReason.LibBytesGreaterOrEqualTo32LengthRequired, ); }); it('should fail if the length between the offset and end of the byte array is too short to hold a bytes32', async () => { const badOffset = new BigNumber(ethUtil.toBuffer(testBytes32).byteLength); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicReadBytes32.callAsync(testBytes32, badOffset), RevertReason.LibBytesGreaterOrEqualTo32LengthRequired, ); @@ -356,7 +356,7 @@ describe('LibBytes', () => { }); it('should fail if the byte array is too short to hold a bytes32', async () => { const offset = new BigNumber(0); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicWriteBytes32.callAsync(byteArrayShorterThan32Bytes, offset, testBytes32), RevertReason.LibBytesGreaterOrEqualTo32LengthRequired, ); @@ -364,7 +364,7 @@ describe('LibBytes', () => { it('should fail if the length between the offset and end of the byte array is too short to hold a bytes32', async () => { const byteArray = byteArrayLongerThan32Bytes; const badOffset = new BigNumber(ethUtil.toBuffer(byteArray).byteLength); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicWriteBytes32.callAsync(byteArray, badOffset, testBytes32), RevertReason.LibBytesGreaterOrEqualTo32LengthRequired, ); @@ -392,7 +392,7 @@ describe('LibBytes', () => { }); it('should fail if the byte array is too short to hold a uint256', async () => { const offset = new BigNumber(0); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicReadUint256.callAsync(byteArrayShorterThan32Bytes, offset), RevertReason.LibBytesGreaterOrEqualTo32LengthRequired, ); @@ -402,7 +402,7 @@ describe('LibBytes', () => { const testUint256AsBuffer = ethUtil.toBuffer(formattedTestUint256); const byteArray = ethUtil.bufferToHex(testUint256AsBuffer); const badOffset = new BigNumber(testUint256AsBuffer.byteLength); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicReadUint256.callAsync(byteArray, badOffset), RevertReason.LibBytesGreaterOrEqualTo32LengthRequired, ); @@ -442,7 +442,7 @@ describe('LibBytes', () => { }); it('should fail if the byte array is too short to hold a uint256', async () => { const offset = new BigNumber(0); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicWriteUint256.callAsync(byteArrayShorterThan32Bytes, offset, testUint256), RevertReason.LibBytesGreaterOrEqualTo32LengthRequired, ); @@ -450,7 +450,7 @@ describe('LibBytes', () => { it('should fail if the length between the offset and end of the byte array is too short to hold a uint256', async () => { const byteArray = byteArrayLongerThan32Bytes; const badOffset = new BigNumber(ethUtil.toBuffer(byteArray).byteLength); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicWriteUint256.callAsync(byteArray, badOffset, testUint256), RevertReason.LibBytesGreaterOrEqualTo32LengthRequired, ); @@ -461,7 +461,7 @@ describe('LibBytes', () => { // AssertionError: expected promise to be rejected with an error including 'revert' but it was fulfilled with '0x08c379a0' it('should revert if byte array has a length < 4', async () => { const byteArrayLessThan4Bytes = '0x010101'; - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicReadBytes4.callAsync(byteArrayLessThan4Bytes, new BigNumber(0)), RevertReason.LibBytesGreaterOrEqualTo4LengthRequired, ); @@ -516,28 +516,28 @@ describe('LibBytes', () => { it('should fail if the byte array is too short to hold the length of a nested byte array', async () => { // The length of the nested array is 32 bytes. By storing less than 32 bytes, a length cannot be read. const offset = new BigNumber(0); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicReadBytesWithLength.callAsync(byteArrayShorterThan32Bytes, offset), RevertReason.LibBytesGreaterOrEqualTo32LengthRequired, ); }); it('should fail if we store a nested byte array length, without a nested byte array', async () => { const offset = new BigNumber(0); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicReadBytesWithLength.callAsync(testBytes32, offset), RevertReason.LibBytesGreaterOrEqualToNestedBytesLengthRequired, ); }); it('should fail if the length between the offset and end of the byte array is too short to hold the length of a nested byte array', async () => { const badOffset = new BigNumber(ethUtil.toBuffer(byteArrayShorterThan32Bytes).byteLength); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicReadBytesWithLength.callAsync(byteArrayShorterThan32Bytes, badOffset), RevertReason.LibBytesGreaterOrEqualTo32LengthRequired, ); }); it('should fail if the length between the offset and end of the byte array is too short to hold the nested byte array', async () => { const badOffset = new BigNumber(ethUtil.toBuffer(testBytes32).byteLength); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicReadBytesWithLength.callAsync(testBytes32, badOffset), RevertReason.LibBytesGreaterOrEqualTo32LengthRequired, ); @@ -649,7 +649,7 @@ describe('LibBytes', () => { it('should fail if the byte array is too short to hold the length of a nested byte array', async () => { const offset = new BigNumber(0); const emptyByteArray = ethUtil.bufferToHex(new Buffer(1)); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicWriteBytesWithLength.callAsync(emptyByteArray, offset, longData), RevertReason.LibBytesGreaterOrEqualToNestedBytesLengthRequired, ); @@ -657,7 +657,7 @@ describe('LibBytes', () => { it('should fail if the length between the offset and end of the byte array is too short to hold the length of a nested byte array)', async () => { const emptyByteArray = ethUtil.bufferToHex(new Buffer(shortTestBytesAsBuffer.byteLength)); const badOffset = new BigNumber(ethUtil.toBuffer(shortTestBytesAsBuffer).byteLength); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( libBytes.publicWriteBytesWithLength.callAsync(emptyByteArray, badOffset, shortData), RevertReason.LibBytesGreaterOrEqualToNestedBytesLengthRequired, ); diff --git a/packages/contracts/test/multisig/asset_proxy_owner.ts b/packages/contracts/test/multisig/asset_proxy_owner.ts index cde86dd46..6a9843153 100644 --- a/packages/contracts/test/multisig/asset_proxy_owner.ts +++ b/packages/contracts/test/multisig/asset_proxy_owner.ts @@ -4,18 +4,19 @@ import * as chai from 'chai'; import { LogWithDecodedArgs } from 'ethereum-types'; import { + AssetProxyOwnerAssetProxyRegistrationEventArgs, AssetProxyOwnerContract, - AssetProxyRegistrationContractEventArgs, - ExecutionContractEventArgs, - ExecutionFailureContractEventArgs, - SubmissionContractEventArgs, + AssetProxyOwnerExecutionEventArgs, + AssetProxyOwnerExecutionFailureEventArgs, + AssetProxyOwnerSubmissionEventArgs, } from '../../generated_contract_wrappers/asset_proxy_owner'; import { MixinAuthorizableContract } from '../../generated_contract_wrappers/mixin_authorizable'; import { TestAssetProxyOwnerContract } from '../../generated_contract_wrappers/test_asset_proxy_owner'; import { artifacts } from '../utils/artifacts'; import { - expectRevertOrAlwaysFailingTransactionAsync, - expectRevertOrContractCallFailedAsync, + expectContractCallFailedWithoutReasonAsync, + expectContractCreationFailedWithoutReason, + expectTransactionFailedWithoutReasonAsync, } from '../utils/assertions'; import { chaiSetup } from '../utils/chai_setup'; import { constants } from '../utils/constants'; @@ -108,7 +109,7 @@ describe('AssetProxyOwner', () => { }); it('should throw if a null address is included in assetProxyContracts', async () => { const assetProxyContractAddresses = [erc20Proxy.address, constants.NULL_ADDRESS]; - return expectRevertOrAlwaysFailingTransactionAsync( + return expectContractCreationFailedWithoutReason( AssetProxyOwnerContract.deployFrom0xArtifactAsync( artifacts.AssetProxyOwner, provider, @@ -147,10 +148,29 @@ describe('AssetProxyOwner', () => { }); }); + describe('readBytes4', () => { + it('should revert if byte array has a length < 4', async () => { + const byteArrayLessThan4Bytes = '0x010101'; + return expectContractCallFailedWithoutReasonAsync( + testAssetProxyOwner.publicReadBytes4.callAsync(byteArrayLessThan4Bytes, new BigNumber(0)), + ); + }); + it('should return the first 4 bytes of a byte array of arbitrary length', async () => { + const byteArrayLongerThan32Bytes = + '0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const first4Bytes = await testAssetProxyOwner.publicReadBytes4.callAsync( + byteArrayLongerThan32Bytes, + new BigNumber(0), + ); + const expectedFirst4Bytes = byteArrayLongerThan32Bytes.slice(0, 10); + expect(first4Bytes).to.equal(expectedFirst4Bytes); + }); + }); + describe('registerAssetProxy', () => { it('should throw if not called by multisig', async () => { const isRegistered = true; - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( testAssetProxyOwner.registerAssetProxy.sendTransactionAsync(erc20Proxy.address, isRegistered, { from: owners[0], }), @@ -170,14 +190,16 @@ describe('AssetProxyOwner', () => { owners[0], ); - const log = submitTxRes.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const log = submitTxRes.logs[0] as LogWithDecodedArgs<AssetProxyOwnerSubmissionEventArgs>; const txId = log.args.transactionId; await multiSigWrapper.confirmTransactionAsync(txId, owners[1]); await increaseTimeAndMineBlockAsync(SECONDS_TIME_LOCKED.toNumber()); const executeTxRes = await multiSigWrapper.executeTransactionAsync(txId, owners[0]); - const registerLog = executeTxRes.logs[0] as LogWithDecodedArgs<AssetProxyRegistrationContractEventArgs>; + const registerLog = executeTxRes.logs[0] as LogWithDecodedArgs< + AssetProxyOwnerAssetProxyRegistrationEventArgs + >; expect(registerLog.args.assetProxyContract).to.equal(addressToRegister); expect(registerLog.args.isRegistered).to.equal(isRegistered); @@ -199,14 +221,14 @@ describe('AssetProxyOwner', () => { registerAssetProxyData, owners[0], ); - const log = submitTxRes.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const log = submitTxRes.logs[0] as LogWithDecodedArgs<AssetProxyOwnerSubmissionEventArgs>; const txId = log.args.transactionId; await multiSigWrapper.confirmTransactionAsync(txId, owners[1]); await increaseTimeAndMineBlockAsync(SECONDS_TIME_LOCKED.toNumber()); const executeTxRes = await multiSigWrapper.executeTransactionAsync(txId, owners[0]); - const failureLog = executeTxRes.logs[0] as LogWithDecodedArgs<ExecutionFailureContractEventArgs>; + const failureLog = executeTxRes.logs[0] as LogWithDecodedArgs<AssetProxyOwnerExecutionFailureEventArgs>; expect(failureLog.args.transactionId).to.be.bignumber.equal(txId); const isAssetProxyRegistered = await testAssetProxyOwner.isAssetProxyRegistered.callAsync( @@ -233,10 +255,8 @@ describe('AssetProxyOwner', () => { owners[0], ); const registerAssetProxySubmitLog = registerAssetProxySubmitRes.logs[0] as LogWithDecodedArgs< - SubmissionContractEventArgs + AssetProxyOwnerSubmissionEventArgs >; - const registerAssetProxyTxId = registerAssetProxySubmitLog.args.transactionId; - await multiSigWrapper.confirmTransactionAsync(registerAssetProxyTxId, owners[1]); const addAuthorizedAddressData = erc20Proxy.addAuthorizedAddress.getABIEncodedTransactionData(authorized); const erc20AddAuthorizedAddressSubmitRes = await multiSigWrapper.submitTransactionAsync( @@ -250,13 +270,16 @@ describe('AssetProxyOwner', () => { owners[0], ); const erc20AddAuthorizedAddressSubmitLog = erc20AddAuthorizedAddressSubmitRes.logs[0] as LogWithDecodedArgs< - SubmissionContractEventArgs + AssetProxyOwnerSubmissionEventArgs >; const erc721AddAuthorizedAddressSubmitLog = erc721AddAuthorizedAddressSubmitRes - .logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + .logs[0] as LogWithDecodedArgs<AssetProxyOwnerSubmissionEventArgs>; + + const registerAssetProxyTxId = registerAssetProxySubmitLog.args.transactionId; const erc20AddAuthorizedAddressTxId = erc20AddAuthorizedAddressSubmitLog.args.transactionId; const erc721AddAuthorizedAddressTxId = erc721AddAuthorizedAddressSubmitLog.args.transactionId; + await multiSigWrapper.confirmTransactionAsync(registerAssetProxyTxId, owners[1]); await multiSigWrapper.confirmTransactionAsync(erc20AddAuthorizedAddressTxId, owners[1]); await multiSigWrapper.confirmTransactionAsync(erc721AddAuthorizedAddressTxId, owners[1]); await increaseTimeAndMineBlockAsync(SECONDS_TIME_LOCKED.toNumber()); @@ -275,9 +298,9 @@ describe('AssetProxyOwner', () => { notRemoveAuthorizedAddressData, owners[0], ); - const log = submitTxRes.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const log = submitTxRes.logs[0] as LogWithDecodedArgs<AssetProxyOwnerSubmissionEventArgs>; const txId = log.args.transactionId; - return expectRevertOrContractCallFailedAsync( + return expectContractCallFailedWithoutReasonAsync( testAssetProxyOwner.testValidRemoveAuthorizedAddressAtIndexTx.callAsync(txId), ); }); @@ -292,7 +315,7 @@ describe('AssetProxyOwner', () => { removeAuthorizedAddressAtIndexData, owners[0], ); - const log = submitTxRes.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const log = submitTxRes.logs[0] as LogWithDecodedArgs<AssetProxyOwnerSubmissionEventArgs>; const txId = log.args.transactionId; const isValidRemoveAuthorizedAddressAtIndexTx = await testAssetProxyOwner.testValidRemoveAuthorizedAddressAtIndexTx.callAsync( txId, @@ -310,9 +333,9 @@ describe('AssetProxyOwner', () => { removeAuthorizedAddressAtIndexData, owners[0], ); - const log = submitTxRes.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const log = submitTxRes.logs[0] as LogWithDecodedArgs<AssetProxyOwnerSubmissionEventArgs>; const txId = log.args.transactionId; - return expectRevertOrContractCallFailedAsync( + return expectContractCallFailedWithoutReasonAsync( testAssetProxyOwner.testValidRemoveAuthorizedAddressAtIndexTx.callAsync(txId), ); }); @@ -329,10 +352,10 @@ describe('AssetProxyOwner', () => { removeAuthorizedAddressAtIndexData, owners[0], ); - const log = res.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const log = res.logs[0] as LogWithDecodedArgs<AssetProxyOwnerSubmissionEventArgs>; const txId = log.args.transactionId; - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( testAssetProxyOwner.executeRemoveAuthorizedAddressAtIndex.sendTransactionAsync(txId, { from: owners[1], }), @@ -349,12 +372,12 @@ describe('AssetProxyOwner', () => { removeAuthorizedAddressAtIndexData, owners[0], ); - const log = res.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const log = res.logs[0] as LogWithDecodedArgs<AssetProxyOwnerSubmissionEventArgs>; const txId = log.args.transactionId; await multiSigWrapper.confirmTransactionAsync(txId, owners[1]); - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( testAssetProxyOwner.executeRemoveAuthorizedAddressAtIndex.sendTransactionAsync(txId, { from: owners[1], }), @@ -371,12 +394,12 @@ describe('AssetProxyOwner', () => { addAuthorizedAddressData, owners[0], ); - const log = res.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const log = res.logs[0] as LogWithDecodedArgs<AssetProxyOwnerSubmissionEventArgs>; const txId = log.args.transactionId; await multiSigWrapper.confirmTransactionAsync(txId, owners[1]); - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( testAssetProxyOwner.executeRemoveAuthorizedAddressAtIndex.sendTransactionAsync(txId, { from: owners[1], }), @@ -393,13 +416,13 @@ describe('AssetProxyOwner', () => { removeAuthorizedAddressAtIndexData, owners[0], ); - const submitLog = submitRes.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const submitLog = submitRes.logs[0] as LogWithDecodedArgs<AssetProxyOwnerSubmissionEventArgs>; const txId = submitLog.args.transactionId; await multiSigWrapper.confirmTransactionAsync(txId, owners[1]); const execRes = await multiSigWrapper.executeRemoveAuthorizedAddressAtIndexAsync(txId, owners[0]); - const execLog = execRes.logs[0] as LogWithDecodedArgs<ExecutionContractEventArgs>; + const execLog = execRes.logs[0] as LogWithDecodedArgs<AssetProxyOwnerExecutionEventArgs>; expect(execLog.args.transactionId).to.be.bignumber.equal(txId); const tx = await testAssetProxyOwner.transactions.callAsync(txId); @@ -420,20 +443,20 @@ describe('AssetProxyOwner', () => { removeAuthorizedAddressAtIndexData, owners[0], ); - const submitLog = submitRes.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const submitLog = submitRes.logs[0] as LogWithDecodedArgs<AssetProxyOwnerSubmissionEventArgs>; const txId = submitLog.args.transactionId; await multiSigWrapper.confirmTransactionAsync(txId, owners[1]); const execRes = await multiSigWrapper.executeRemoveAuthorizedAddressAtIndexAsync(txId, owners[0]); - const execLog = execRes.logs[0] as LogWithDecodedArgs<ExecutionContractEventArgs>; + const execLog = execRes.logs[0] as LogWithDecodedArgs<AssetProxyOwnerExecutionEventArgs>; expect(execLog.args.transactionId).to.be.bignumber.equal(txId); const tx = await testAssetProxyOwner.transactions.callAsync(txId); const isExecuted = tx[3]; expect(isExecuted).to.equal(true); - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( testAssetProxyOwner.executeRemoveAuthorizedAddressAtIndex.sendTransactionAsync(txId, { from: owners[1], }), diff --git a/packages/contracts/test/multisig/multi_sig_with_time_lock.ts b/packages/contracts/test/multisig/multi_sig_with_time_lock.ts index a746403d2..a8e9243a9 100644 --- a/packages/contracts/test/multisig/multi_sig_with_time_lock.ts +++ b/packages/contracts/test/multisig/multi_sig_with_time_lock.ts @@ -5,10 +5,10 @@ import { LogWithDecodedArgs } from 'ethereum-types'; import { MultiSigWalletWithTimeLockContract, - SubmissionContractEventArgs, + MultiSigWalletWithTimeLockSubmissionEventArgs, } from '../../generated_contract_wrappers/multi_sig_wallet_with_time_lock'; import { artifacts } from '../utils/artifacts'; -import { expectRevertOrAlwaysFailingTransactionAsync } from '../utils/assertions'; +import { expectTransactionFailedWithoutReasonAsync } from '../utils/assertions'; import { chaiSetup } from '../utils/chai_setup'; import { constants } from '../utils/constants'; import { increaseTimeAndMineBlockAsync } from '../utils/increase_time'; @@ -67,7 +67,7 @@ describe('MultiSigWalletWithTimeLock', () => { }); it('should throw when not called by wallet', async () => { - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( multiSig.changeTimeLock.sendTransactionAsync(SECONDS_TIME_LOCKED, { from: owners[0] }), ); }); @@ -76,9 +76,9 @@ describe('MultiSigWalletWithTimeLock', () => { const destination = multiSig.address; const changeTimeLockData = multiSig.changeTimeLock.getABIEncodedTransactionData(SECONDS_TIME_LOCKED); const res = await multiSigWrapper.submitTransactionAsync(destination, changeTimeLockData, owners[0]); - const log = res.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const log = res.logs[0] as LogWithDecodedArgs<MultiSigWalletWithTimeLockSubmissionEventArgs>; const txId = log.args.transactionId; - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( multiSig.executeTransaction.sendTransactionAsync(txId, { from: owners[0] }), ); }); @@ -87,7 +87,7 @@ describe('MultiSigWalletWithTimeLock', () => { const destination = multiSig.address; const changeTimeLockData = multiSig.changeTimeLock.getABIEncodedTransactionData(SECONDS_TIME_LOCKED); const subRes = await multiSigWrapper.submitTransactionAsync(destination, changeTimeLockData, owners[0]); - const subLog = subRes.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const subLog = subRes.logs[0] as LogWithDecodedArgs<MultiSigWalletWithTimeLockSubmissionEventArgs>; const txId = subLog.args.transactionId; const confirmRes = await multiSigWrapper.confirmTransactionAsync(txId, owners[1]); @@ -105,7 +105,7 @@ describe('MultiSigWalletWithTimeLock', () => { const destination = multiSig.address; const changeTimeLockData = multiSig.changeTimeLock.getABIEncodedTransactionData(SECONDS_TIME_LOCKED); const subRes = await multiSigWrapper.submitTransactionAsync(destination, changeTimeLockData, owners[0]); - const subLog = subRes.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const subLog = subRes.logs[0] as LogWithDecodedArgs<MultiSigWalletWithTimeLockSubmissionEventArgs>; const txId = subLog.args.transactionId; await multiSigWrapper.confirmTransactionAsync(txId, owners[1]); @@ -141,13 +141,13 @@ describe('MultiSigWalletWithTimeLock', () => { changeTimeLockData, owners[0], ); - const log = res.logs[0] as LogWithDecodedArgs<SubmissionContractEventArgs>; + const log = res.logs[0] as LogWithDecodedArgs<MultiSigWalletWithTimeLockSubmissionEventArgs>; txId = log.args.transactionId; await multiSigWrapper.confirmTransactionAsync(txId, owners[1]); }); it('should throw if it has enough confirmations but is not past the time lock', async () => { - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( multiSig.executeTransaction.sendTransactionAsync(txId, { from: owners[0] }), ); }); diff --git a/packages/contracts/test/token_registry.ts b/packages/contracts/test/token_registry.ts index 32f8cdee3..7cc43be9b 100644 --- a/packages/contracts/test/token_registry.ts +++ b/packages/contracts/test/token_registry.ts @@ -7,7 +7,7 @@ import * as _ from 'lodash'; import { TokenRegistryContract } from '../generated_contract_wrappers/token_registry'; import { artifacts } from './utils/artifacts'; -import { expectRevertOrAlwaysFailingTransactionAsync } from './utils/assertions'; +import { expectTransactionFailedWithoutReasonAsync } from './utils/assertions'; import { chaiSetup } from './utils/chai_setup'; import { constants } from './utils/constants'; import { TokenRegWrapper } from './utils/token_registry_wrapper'; @@ -75,7 +75,7 @@ describe('TokenRegistry', () => { describe('addToken', () => { it('should throw when not called by owner', async () => { - return expectRevertOrAlwaysFailingTransactionAsync(tokenRegWrapper.addTokenAsync(token1, notOwner)); + return expectTransactionFailedWithoutReasonAsync(tokenRegWrapper.addTokenAsync(token1, notOwner)); }); it('should add token metadata when called by owner', async () => { @@ -87,20 +87,18 @@ describe('TokenRegistry', () => { it('should throw if token already exists', async () => { await tokenRegWrapper.addTokenAsync(token1, owner); - return expectRevertOrAlwaysFailingTransactionAsync(tokenRegWrapper.addTokenAsync(token1, owner)); + return expectTransactionFailedWithoutReasonAsync(tokenRegWrapper.addTokenAsync(token1, owner)); }); it('should throw if token address is null', async () => { - return expectRevertOrAlwaysFailingTransactionAsync(tokenRegWrapper.addTokenAsync(nullToken, owner)); + return expectTransactionFailedWithoutReasonAsync(tokenRegWrapper.addTokenAsync(nullToken, owner)); }); it('should throw if name already exists', async () => { await tokenRegWrapper.addTokenAsync(token1, owner); const duplicateNameToken = _.assign({}, token2, { name: token1.name }); - return expectRevertOrAlwaysFailingTransactionAsync( - tokenRegWrapper.addTokenAsync(duplicateNameToken, owner), - ); + return expectTransactionFailedWithoutReasonAsync(tokenRegWrapper.addTokenAsync(duplicateNameToken, owner)); }); it('should throw if symbol already exists', async () => { @@ -109,7 +107,7 @@ describe('TokenRegistry', () => { symbol: token1.symbol, }); - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( tokenRegWrapper.addTokenAsync(duplicateSymbolToken, owner), ); }); @@ -136,7 +134,7 @@ describe('TokenRegistry', () => { describe('setTokenName', () => { it('should throw when not called by owner', async () => { - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( tokenReg.setTokenName.sendTransactionAsync(token1.address, token2.name, { from: notOwner }), ); }); @@ -162,13 +160,13 @@ describe('TokenRegistry', () => { it('should throw if the name already exists', async () => { await tokenRegWrapper.addTokenAsync(token2, owner); - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( tokenReg.setTokenName.sendTransactionAsync(token1.address, token2.name, { from: owner }), ); }); it('should throw if token does not exist', async () => { - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( tokenReg.setTokenName.sendTransactionAsync(nullToken.address, token2.name, { from: owner }), ); }); @@ -176,7 +174,7 @@ describe('TokenRegistry', () => { describe('setTokenSymbol', () => { it('should throw when not called by owner', async () => { - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( tokenReg.setTokenSymbol.sendTransactionAsync(token1.address, token2.symbol, { from: notOwner, }), @@ -202,7 +200,7 @@ describe('TokenRegistry', () => { it('should throw if the symbol already exists', async () => { await tokenRegWrapper.addTokenAsync(token2, owner); - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( tokenReg.setTokenSymbol.sendTransactionAsync(token1.address, token2.symbol, { from: owner, }), @@ -210,7 +208,7 @@ describe('TokenRegistry', () => { }); it('should throw if token does not exist', async () => { - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( tokenReg.setTokenSymbol.sendTransactionAsync(nullToken.address, token2.symbol, { from: owner, }), @@ -221,7 +219,7 @@ describe('TokenRegistry', () => { describe('removeToken', () => { it('should throw if not called by owner', async () => { const index = new BigNumber(0); - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( tokenReg.removeToken.sendTransactionAsync(token1.address, index, { from: notOwner }), ); }); @@ -240,7 +238,7 @@ describe('TokenRegistry', () => { it('should throw if token does not exist', async () => { const index = new BigNumber(0); - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( tokenReg.removeToken.sendTransactionAsync(nullToken.address, index, { from: owner }), ); }); @@ -248,7 +246,7 @@ describe('TokenRegistry', () => { it('should throw if token at given index does not match address', async () => { await tokenRegWrapper.addTokenAsync(token2, owner); const incorrectIndex = new BigNumber(0); - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( tokenReg.removeToken.sendTransactionAsync(token2.address, incorrectIndex, { from: owner }), ); }); diff --git a/packages/contracts/test/tokens/ether_token.ts b/packages/contracts/test/tokens/ether_token.ts index 25ef15595..a104fc915 100644 --- a/packages/contracts/test/tokens/ether_token.ts +++ b/packages/contracts/test/tokens/ether_token.ts @@ -5,7 +5,7 @@ import * as chai from 'chai'; import { WETH9Contract } from '../../generated_contract_wrappers/weth9'; import { artifacts } from '../utils/artifacts'; -import { expectInsufficientFundsAsync, expectRevertOrAlwaysFailingTransactionAsync } from '../utils/assertions'; +import { expectInsufficientFundsAsync, expectTransactionFailedWithoutReasonAsync } from '../utils/assertions'; import { chaiSetup } from '../utils/chai_setup'; import { constants } from '../utils/constants'; import { provider, txDefaults, web3Wrapper } from '../utils/web3_wrapper'; @@ -74,7 +74,7 @@ describe('EtherToken', () => { const initEthTokenBalance = await etherToken.balanceOf.callAsync(account); const ethTokensToWithdraw = initEthTokenBalance.plus(1); - return expectRevertOrAlwaysFailingTransactionAsync( + return expectTransactionFailedWithoutReasonAsync( etherToken.withdraw.sendTransactionAsync(ethTokensToWithdraw), ); }); diff --git a/packages/contracts/test/tokens/unlimited_allowance_token.ts b/packages/contracts/test/tokens/unlimited_allowance_token.ts index 09a24950c..81d931fc5 100644 --- a/packages/contracts/test/tokens/unlimited_allowance_token.ts +++ b/packages/contracts/test/tokens/unlimited_allowance_token.ts @@ -3,9 +3,9 @@ import { RevertReason } from '@0xproject/types'; import { BigNumber } from '@0xproject/utils'; import * as chai from 'chai'; -import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c20_token'; +import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_erc20_token'; import { artifacts } from '../utils/artifacts'; -import { expectRevertOrOtherErrorAsync } from '../utils/assertions'; +import { expectContractCallFailed } from '../utils/assertions'; import { chaiSetup } from '../utils/chai_setup'; import { constants } from '../utils/constants'; import { provider, txDefaults, web3Wrapper } from '../utils/web3_wrapper'; @@ -54,7 +54,7 @@ describe('UnlimitedAllowanceToken', () => { it('should throw if owner has insufficient balance', async () => { const ownerBalance = await token.balanceOf.callAsync(owner); const amountToTransfer = ownerBalance.plus(1); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( token.transfer.callAsync(spender, amountToTransfer, { from: owner }), RevertReason.Erc20InsufficientBalance, ); @@ -93,7 +93,7 @@ describe('UnlimitedAllowanceToken', () => { await token.approve.sendTransactionAsync(spender, amountToTransfer, { from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( token.transferFrom.callAsync(owner, spender, amountToTransfer, { from: spender, }), @@ -109,7 +109,7 @@ describe('UnlimitedAllowanceToken', () => { const isSpenderAllowanceInsufficient = spenderAllowance.cmp(amountToTransfer) < 0; expect(isSpenderAllowanceInsufficient).to.be.true(); - return expectRevertOrOtherErrorAsync( + return expectContractCallFailed( token.transferFrom.callAsync(owner, spender, amountToTransfer, { from: spender, }), diff --git a/packages/contracts/test/utils/artifacts.ts b/packages/contracts/test/utils/artifacts.ts index 23e93c085..d3f808218 100644 --- a/packages/contracts/test/utils/artifacts.ts +++ b/packages/contracts/test/utils/artifacts.ts @@ -8,6 +8,7 @@ import * as ERC20Proxy from '../../artifacts/ERC20Proxy.json'; import * as ERC721Proxy from '../../artifacts/ERC721Proxy.json'; import * as Exchange from '../../artifacts/Exchange.json'; import * as ExchangeWrapper from '../../artifacts/ExchangeWrapper.json'; +import * as Forwarder from '../../artifacts/Forwarder.json'; import * as IAssetProxy from '../../artifacts/IAssetProxy.json'; import * as MixinAuthorizable from '../../artifacts/MixinAuthorizable.json'; import * as MultiSigWallet from '../../artifacts/MultiSigWallet.json'; @@ -34,6 +35,7 @@ export const artifacts = { Exchange: (Exchange as any) as ContractArtifact, ExchangeWrapper: (ExchangeWrapper as any) as ContractArtifact, EtherToken: (EtherToken as any) as ContractArtifact, + Forwarder: (Forwarder as any) as ContractArtifact, IAssetProxy: (IAssetProxy as any) as ContractArtifact, MixinAuthorizable: (MixinAuthorizable as any) as ContractArtifact, MultiSigWallet: (MultiSigWallet as any) as ContractArtifact, diff --git a/packages/contracts/test/utils/assertions.ts b/packages/contracts/test/utils/assertions.ts index baba892d3..112a470f6 100644 --- a/packages/contracts/test/utils/assertions.ts +++ b/packages/contracts/test/utils/assertions.ts @@ -1,108 +1,159 @@ import { RevertReason } from '@0xproject/types'; +import { logUtils } from '@0xproject/utils'; +import { NodeType } from '@0xproject/web3-wrapper'; import * as chai from 'chai'; -import { TransactionReceipt, TransactionReceiptWithDecodedLogs } from 'ethereum-types'; +import { TransactionReceipt, TransactionReceiptStatus, TransactionReceiptWithDecodedLogs } from 'ethereum-types'; import * as _ from 'lodash'; -import { constants } from './constants'; import { web3Wrapper } from './web3_wrapper'; const expect = chai.expect; -function _expectEitherErrorAsync<T>(p: Promise<T>, error1: string, error2: string): PromiseLike<void> { - return expect(p) - .to.be.rejected() - .then(e => { - expect(e).to.satisfy( - (err: Error) => _.includes(err.message, error1) || _.includes(err.message, error2), - `expected promise to reject with error message that includes "${error1}" or "${error2}", but got: ` + - `"${e.message}"\n`, - ); - }); +let nodeType: NodeType | undefined; + +// Represents the return value of a `sendTransaction` call. The Promise should +// resolve with either a transaction receipt or a transaction hash. +export type sendTransactionResult = Promise<TransactionReceipt | TransactionReceiptWithDecodedLogs | string>; + +async function _getGanacheOrGethError(ganacheError: string, gethError: string): Promise<string> { + if (_.isUndefined(nodeType)) { + nodeType = await web3Wrapper.getNodeTypeAsync(); + } + switch (nodeType) { + case NodeType.Ganache: + return ganacheError; + case NodeType.Geth: + return gethError; + default: + throw new Error(`Unknown node type: ${nodeType}`); + } +} + +async function _getInsufficientFundsErrorMessageAsync(): Promise<string> { + return _getGanacheOrGethError("sender doesn't have enough funds", 'insufficient funds'); +} + +async function _getTransactionFailedErrorMessageAsync(): Promise<string> { + return _getGanacheOrGethError('revert', 'always failing transaction'); +} + +async function _getContractCallFailedErrorMessageAsync(): Promise<string> { + return _getGanacheOrGethError('revert', 'Contract call failed'); } /** * Rejects if the given Promise does not reject with an error indicating * insufficient funds. - * @param p the Promise which is expected to reject + * @param p a promise resulting from a contract call or sendTransaction call. * @returns a new Promise which will reject if the conditions are not met and * otherwise resolve with no value. */ -export function expectInsufficientFundsAsync<T>(p: Promise<T>): PromiseLike<void> { - return _expectEitherErrorAsync(p, 'insufficient funds', "sender doesn't have enough funds"); +export async function expectInsufficientFundsAsync<T>(p: Promise<T>): Promise<void> { + const errMessage = await _getInsufficientFundsErrorMessageAsync(); + return expect(p).to.be.rejectedWith(errMessage); } /** - * Rejects if the given Promise does not reject with a "revert" error or the - * given otherError. - * @param p the Promise which is expected to reject - * @param otherError the other error which is accepted as a valid reject error. + * Resolves if the the sendTransaction call fails with the given revert reason. + * However, since Geth does not support revert reasons for sendTransaction, this + * falls back to expectTransactionFailedWithoutReasonAsync if the backing + * Ethereum node is Geth. + * @param p a Promise resulting from a sendTransaction call + * @param reason a specific revert reason * @returns a new Promise which will reject if the conditions are not met and * otherwise resolve with no value. */ -export function expectRevertOrOtherErrorAsync<T>(p: Promise<T>, otherError: string): PromiseLike<void> { - return _expectEitherErrorAsync(p, constants.REVERT, otherError); -} +export async function expectTransactionFailedAsync(p: sendTransactionResult, reason: RevertReason): Promise<void> { + // HACK(albrow): This dummy `catch` should not be necessary, but if you + // remove it, there is an uncaught exception and the Node process will + // forcibly exit. It's possible this is a false positive in + // make-promises-safe. + p.catch(e => { + _.noop(e); + }); -/** - * Rejects if the given Promise does not reject with a "revert" or "always - * failing transaction" error. - * @param p the Promise which is expected to reject - * @returns a new Promise which will reject if the conditions are not met and - * otherwise resolve with no value. - */ -export function expectRevertOrAlwaysFailingTransactionAsync<T>(p: Promise<T>): PromiseLike<void> { - return expectRevertOrOtherErrorAsync(p, 'always failing transaction'); + if (_.isUndefined(nodeType)) { + nodeType = await web3Wrapper.getNodeTypeAsync(); + } + switch (nodeType) { + case NodeType.Ganache: + return expect(p).to.be.rejectedWith(reason); + case NodeType.Geth: + logUtils.warn( + 'WARNING: Geth does not support revert reasons for sendTransaction. This test will pass if the transaction fails for any reason.', + ); + return expectTransactionFailedWithoutReasonAsync(p); + default: + throw new Error(`Unknown node type: ${nodeType}`); + } } /** - * Rejects if at least one the following conditions is not met: - * 1) The given Promise rejects with the given revert reason. - * 2) The given Promise rejects with an error containing "always failing transaction" - * 3) The given Promise fulfills with a txReceipt that has a status of 0 or '0', indicating the transaction failed. - * 4) The given Promise fulfills with a txHash and corresponding txReceipt has a status of 0 or '0'. - * @param p the Promise which is expected to reject - * @param reason a specific revert reason + * Resolves if the transaction fails without a revert reason, or if the + * corresponding transactionReceipt has a status of 0 or '0', indicating + * failure. + * @param p a Promise resulting from a sendTransaction call * @returns a new Promise which will reject if the conditions are not met and * otherwise resolve with no value. */ -export async function expectRevertReasonOrAlwaysFailingTransactionAsync( - p: Promise<string | TransactionReceiptWithDecodedLogs | TransactionReceipt>, - reason: RevertReason, -): Promise<void> { +export async function expectTransactionFailedWithoutReasonAsync(p: sendTransactionResult): Promise<void> { return p .then(async result => { - let txReceiptStatus: string | 0 | 1 | null; - if (typeof result === 'string') { - // Result is a txHash. We need to make a web3 call to get the receipt. + let txReceiptStatus: TransactionReceiptStatus; + if (_.isString(result)) { + // Result is a txHash. We need to make a web3 call to get the + // receipt, then get the status from the receipt. const txReceipt = await web3Wrapper.awaitTransactionMinedAsync(result); txReceiptStatus = txReceipt.status; } else if ('status' in result) { - // Result is a TransactionReceiptWithDecodedLogs or TransactionReceipt - // and status is a field of result. + // Result is a transaction receipt, so we can get the status + // directly. txReceiptStatus = result.status; } else { - throw new Error('Unexpected result type'); + throw new Error('Unexpected result type: ' + typeof result); } expect(_.toString(txReceiptStatus)).to.equal( '0', - 'transactionReceipt had a non-zero status, indicating success', + 'Expected transaction to fail but receipt had a non-zero status, indicating success', ); }) - .catch(err => { - expect(err.message).to.satisfy( - (msg: string) => _.includes(msg, reason) || _.includes(msg, 'always failing transaction'), - `Expected ${reason} or 'always failing transaction' but error message was ${err.message}`, - ); + .catch(async err => { + // If the promise rejects, we expect a specific error message, + // depending on the backing Ethereum node type. + const errMessage = await _getTransactionFailedErrorMessageAsync(); + expect(err.message).to.include(errMessage); }); } /** - * Rejects if the given Promise does not reject with a "revert" or "Contract - * call failed" error. - * @param p the Promise which is expected to reject + * Resolves if the the contract call fails with the given revert reason. + * @param p a Promise resulting from a contract call + * @param reason a specific revert reason + * @returns a new Promise which will reject if the conditions are not met and + * otherwise resolve with no value. + */ +export async function expectContractCallFailed<T>(p: Promise<T>, reason: RevertReason): Promise<void> { + return expect(p).to.be.rejectedWith(reason); +} + +/** + * Resolves if the contract call fails without a revert reason. + * @param p a Promise resulting from a contract call + * @returns a new Promise which will reject if the conditions are not met and + * otherwise resolve with no value. + */ +export async function expectContractCallFailedWithoutReasonAsync<T>(p: Promise<T>): Promise<void> { + const errMessage = await _getContractCallFailedErrorMessageAsync(); + return expect(p).to.be.rejectedWith(errMessage); +} + +/** + * Resolves if the contract creation/deployment fails without a revert reason. + * @param p a Promise resulting from a contract creation/deployment * @returns a new Promise which will reject if the conditions are not met and * otherwise resolve with no value. */ -export function expectRevertOrContractCallFailedAsync<T>(p: Promise<T>): PromiseLike<void> { - return expectRevertOrOtherErrorAsync<T>(p, 'Contract call failed'); +export async function expectContractCreationFailedWithoutReason<T>(p: Promise<T>): Promise<void> { + const errMessage = await _getTransactionFailedErrorMessageAsync(); + return expect(p).to.be.rejectedWith(errMessage); } diff --git a/packages/contracts/test/utils/asset_wrapper.ts b/packages/contracts/test/utils/asset_wrapper.ts index 402a7ab28..f291170a2 100644 --- a/packages/contracts/test/utils/asset_wrapper.ts +++ b/packages/contracts/test/utils/asset_wrapper.ts @@ -84,8 +84,15 @@ export class AssetWrapper { userAddress, ); } else if (tokenOwner === userAddress && desiredBalance.eq(0)) { - // Burn token - await erc721Wrapper.burnAsync(assetProxyData.tokenAddress, assetProxyData.tokenId, userAddress); + // Transfer token to someone else + const userAddresses = await (erc721Wrapper as any)._web3Wrapper.getAvailableAddressesAsync(); + const nonOwner = _.find(userAddresses, a => a !== userAddress); + await erc721Wrapper.transferFromAsync( + assetProxyData.tokenAddress, + assetProxyData.tokenId, + tokenOwner, + nonOwner, + ); return; } else if ( (userAddress !== tokenOwner && desiredBalance.eq(0)) || diff --git a/packages/contracts/test/utils/constants.ts b/packages/contracts/test/utils/constants.ts index 8e68f376d..e8995f9d6 100644 --- a/packages/contracts/test/utils/constants.ts +++ b/packages/contracts/test/utils/constants.ts @@ -18,16 +18,16 @@ const TESTRPC_PRIVATE_KEYS_STRINGS = [ export const constants = { INVALID_OPCODE: 'invalid opcode', - REVERT: 'revert', TESTRPC_NETWORK_ID: 50, // Note(albrow): In practice V8 and most other engines limit the minimum // interval for setInterval to 10ms. We still set it to 0 here in order to // ensure we always use the minimum interval. AWAIT_TRANSACTION_MINED_MS: 0, MAX_ETHERTOKEN_WITHDRAW_GAS: 43000, + MAX_EXECUTE_TRANSACTION_GAS: 1000000, MAX_TOKEN_TRANSFERFROM_GAS: 80000, MAX_TOKEN_APPROVE_GAS: 60000, - TRANSFER_FROM_GAS: 150000, + MAX_TRANSFER_FROM_GAS: 150000, DUMMY_TOKEN_NAME: '', DUMMY_TOKEN_SYMBOL: '', DUMMY_TOKEN_DECIMALS: new BigNumber(18), diff --git a/packages/contracts/test/utils/core_combinatorial_utils.ts b/packages/contracts/test/utils/core_combinatorial_utils.ts index 718be17e0..7c16ef201 100644 --- a/packages/contracts/test/utils/core_combinatorial_utils.ts +++ b/packages/contracts/test/utils/core_combinatorial_utils.ts @@ -14,10 +14,10 @@ import { LogWithDecodedArgs, Provider, TxData } from 'ethereum-types'; import * as _ from 'lodash'; import 'make-promises-safe'; -import { ExchangeContract, FillContractEventArgs } from '../../generated_contract_wrappers/exchange'; +import { ExchangeContract, ExchangeFillEventArgs } from '../../generated_contract_wrappers/exchange'; import { artifacts } from './artifacts'; -import { expectRevertReasonOrAlwaysFailingTransactionAsync } from './assertions'; +import { expectTransactionFailedAsync } from './assertions'; import { AssetWrapper } from './asset_wrapper'; import { chaiSetup } from './chai_setup'; import { constants } from './constants'; @@ -75,7 +75,7 @@ export async function coreCombinatorialUtilsFactoryAsync( const zrxAssetData = assetProxyUtils.encodeERC20AssetData(zrxToken.address); const erc20FiveDecimalTokenCount = 2; - const fiveDecimals = new BigNumber(18); + const fiveDecimals = new BigNumber(5); const [erc20FiveDecimalTokenA, erc20FiveDecimalTokenB] = await erc20Wrapper.deployDummyTokensAsync( erc20FiveDecimalTokenCount, fiveDecimals, @@ -146,13 +146,39 @@ export class CoreCombinatorialUtils { public exchangeWrapper: ExchangeWrapper; public assetWrapper: AssetWrapper; public static generateFillOrderCombinations(): FillScenario[] { - const takerScenarios = [TakerScenario.Unspecified]; - const feeRecipientScenarios = [FeeRecipientAddressScenario.EthUserAddress]; - const makerAssetAmountScenario = [OrderAssetAmountScenario.Large]; - const takerAssetAmountScenario = [OrderAssetAmountScenario.Large]; - const makerFeeScenario = [OrderAssetAmountScenario.Large]; - const takerFeeScenario = [OrderAssetAmountScenario.Large]; - const expirationTimeSecondsScenario = [ExpirationTimeSecondsScenario.InFuture]; + const takerScenarios = [ + TakerScenario.Unspecified, + // TakerScenario.CorrectlySpecified, + // TakerScenario.IncorrectlySpecified, + ]; + const feeRecipientScenarios = [ + FeeRecipientAddressScenario.EthUserAddress, + // FeeRecipientAddressScenario.BurnAddress, + ]; + const makerAssetAmountScenario = [ + OrderAssetAmountScenario.Large, + // OrderAssetAmountScenario.Zero, + // OrderAssetAmountScenario.Small, + ]; + const takerAssetAmountScenario = [ + OrderAssetAmountScenario.Large, + // OrderAssetAmountScenario.Zero, + // OrderAssetAmountScenario.Small, + ]; + const makerFeeScenario = [ + OrderAssetAmountScenario.Large, + // OrderAssetAmountScenario.Small, + // OrderAssetAmountScenario.Zero, + ]; + const takerFeeScenario = [ + OrderAssetAmountScenario.Large, + // OrderAssetAmountScenario.Small, + // OrderAssetAmountScenario.Zero, + ]; + const expirationTimeSecondsScenario = [ + ExpirationTimeSecondsScenario.InFuture, + ExpirationTimeSecondsScenario.InPast, + ]; const makerAssetDataScenario = [ AssetDataScenario.ERC20FiveDecimals, AssetDataScenario.ERC20NonZRXEighteenDecimals, @@ -165,7 +191,55 @@ export class CoreCombinatorialUtils { AssetDataScenario.ERC721, AssetDataScenario.ZRXFeeToken, ]; - const takerAssetFillAmountScenario = [TakerAssetFillAmountScenario.ExactlyRemainingFillableTakerAssetAmount]; + const takerAssetFillAmountScenario = [ + TakerAssetFillAmountScenario.ExactlyRemainingFillableTakerAssetAmount, + // TakerAssetFillAmountScenario.GreaterThanRemainingFillableTakerAssetAmount, + // TakerAssetFillAmountScenario.LessThanRemainingFillableTakerAssetAmount, + ]; + const makerAssetBalanceScenario = [ + BalanceAmountScenario.Higher, + // BalanceAmountScenario.Exact, + // BalanceAmountScenario.TooLow, + ]; + const makerAssetAllowanceScenario = [ + AllowanceAmountScenario.Higher, + // AllowanceAmountScenario.Exact, + // AllowanceAmountScenario.TooLow, + // AllowanceAmountScenario.Unlimited, + ]; + const makerZRXBalanceScenario = [ + BalanceAmountScenario.Higher, + // BalanceAmountScenario.Exact, + // BalanceAmountScenario.TooLow, + ]; + const makerZRXAllowanceScenario = [ + AllowanceAmountScenario.Higher, + // AllowanceAmountScenario.Exact, + // AllowanceAmountScenario.TooLow, + // AllowanceAmountScenario.Unlimited, + ]; + const takerAssetBalanceScenario = [ + BalanceAmountScenario.Higher, + // BalanceAmountScenario.Exact, + // BalanceAmountScenario.TooLow, + ]; + const takerAssetAllowanceScenario = [ + AllowanceAmountScenario.Higher, + // AllowanceAmountScenario.Exact, + // AllowanceAmountScenario.TooLow, + // AllowanceAmountScenario.Unlimited, + ]; + const takerZRXBalanceScenario = [ + BalanceAmountScenario.Higher, + // BalanceAmountScenario.Exact, + // BalanceAmountScenario.TooLow, + ]; + const takerZRXAllowanceScenario = [ + AllowanceAmountScenario.Higher, + // AllowanceAmountScenario.Exact, + // AllowanceAmountScenario.TooLow, + // AllowanceAmountScenario.Unlimited, + ]; const fillScenarioArrays = CoreCombinatorialUtils._getAllCombinations([ takerScenarios, feeRecipientScenarios, @@ -177,9 +251,18 @@ export class CoreCombinatorialUtils { makerAssetDataScenario, takerAssetDataScenario, takerAssetFillAmountScenario, + makerAssetBalanceScenario, + makerAssetAllowanceScenario, + makerZRXBalanceScenario, + makerZRXAllowanceScenario, + takerAssetBalanceScenario, + takerAssetAllowanceScenario, + takerZRXBalanceScenario, + takerZRXAllowanceScenario, ]); const fillScenarios = _.map(fillScenarioArrays, fillScenarioArray => { + // tslint:disable:custom-no-magic-numbers const fillScenario: FillScenario = { orderScenario: { takerScenario: fillScenarioArray[0] as TakerScenario, @@ -194,18 +277,19 @@ export class CoreCombinatorialUtils { }, takerAssetFillAmountScenario: fillScenarioArray[9] as TakerAssetFillAmountScenario, makerStateScenario: { - traderAssetBalance: BalanceAmountScenario.Higher, - traderAssetAllowance: AllowanceAmountScenario.Higher, - zrxFeeBalance: BalanceAmountScenario.Higher, - zrxFeeAllowance: AllowanceAmountScenario.Higher, + traderAssetBalance: fillScenarioArray[10] as BalanceAmountScenario, + traderAssetAllowance: fillScenarioArray[11] as AllowanceAmountScenario, + zrxFeeBalance: fillScenarioArray[12] as BalanceAmountScenario, + zrxFeeAllowance: fillScenarioArray[13] as AllowanceAmountScenario, }, takerStateScenario: { - traderAssetBalance: BalanceAmountScenario.Higher, - traderAssetAllowance: AllowanceAmountScenario.Higher, - zrxFeeBalance: BalanceAmountScenario.Higher, - zrxFeeAllowance: AllowanceAmountScenario.Higher, + traderAssetBalance: fillScenarioArray[14] as BalanceAmountScenario, + traderAssetAllowance: fillScenarioArray[15] as AllowanceAmountScenario, + zrxFeeBalance: fillScenarioArray[16] as BalanceAmountScenario, + zrxFeeAllowance: fillScenarioArray[17] as AllowanceAmountScenario, }, }; + // tslint:enable:custom-no-magic-numbers return fillScenario; }); @@ -334,7 +418,7 @@ export class CoreCombinatorialUtils { fillRevertReasonIfExists: RevertReason | undefined, ): Promise<void> { if (!_.isUndefined(fillRevertReasonIfExists)) { - return expectRevertReasonOrAlwaysFailingTransactionAsync( + return expectTransactionFailedAsync( this.exchangeWrapper.fillOrderAsync(signedOrder, this.takerAddress, { takerAssetFillAmount }), fillRevertReasonIfExists, ); @@ -383,7 +467,7 @@ export class CoreCombinatorialUtils { expect(txReceipt.logs.length).to.be.equal(1, 'logs length'); // tslint:disable-next-line:no-unnecessary-type-assertion - const log = txReceipt.logs[0] as LogWithDecodedArgs<FillContractEventArgs>; + const log = txReceipt.logs[0] as LogWithDecodedArgs<ExchangeFillEventArgs>; expect(log.args.makerAddress).to.be.equal(makerAddress, 'log.args.makerAddress'); expect(log.args.takerAddress).to.be.equal(this.takerAddress, 'log.args.this.takerAddress'); expect(log.args.feeRecipientAddress).to.be.equal(feeRecipient, 'log.args.feeRecipientAddress'); @@ -768,25 +852,17 @@ export class CoreCombinatorialUtils { case AllowanceAmountScenario.TooLow: const tooLowAllowance = takerFee.minus(1); - await this.assetWrapper.setProxyAllowanceAsync( - signedOrder.takerAddress, - this.zrxAssetData, - tooLowAllowance, - ); + await this.assetWrapper.setProxyAllowanceAsync(this.takerAddress, this.zrxAssetData, tooLowAllowance); break; case AllowanceAmountScenario.Exact: const exactAllowance = takerFee; - await this.assetWrapper.setProxyAllowanceAsync( - signedOrder.takerAddress, - this.zrxAssetData, - exactAllowance, - ); + await this.assetWrapper.setProxyAllowanceAsync(this.takerAddress, this.zrxAssetData, exactAllowance); break; case AllowanceAmountScenario.Unlimited: await this.assetWrapper.setProxyAllowanceAsync( - signedOrder.takerAddress, + this.takerAddress, this.zrxAssetData, constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS, ); diff --git a/packages/contracts/test/utils/erc20_wrapper.ts b/packages/contracts/test/utils/erc20_wrapper.ts index 53e9791bc..cf1433791 100644 --- a/packages/contracts/test/utils/erc20_wrapper.ts +++ b/packages/contracts/test/utils/erc20_wrapper.ts @@ -4,8 +4,8 @@ import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Provider } from 'ethereum-types'; import * as _ from 'lodash'; -import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c20_token'; -import { ERC20ProxyContract } from '../../generated_contract_wrappers/e_r_c20_proxy'; +import { DummyERC20TokenContract } from '../../generated_contract_wrappers/dummy_erc20_token'; +import { ERC20ProxyContract } from '../../generated_contract_wrappers/erc20_proxy'; import { artifacts } from './artifacts'; import { constants } from './constants'; @@ -138,6 +138,14 @@ export class ERC20Wrapper { }); return balancesByOwner; } + public addDummyTokenContract(dummy: DummyERC20TokenContract): void { + if (!_.isUndefined(this._dummyTokenContracts)) { + this._dummyTokenContracts.push(dummy); + } + } + public addTokenOwnerAddress(address: string): void { + this._tokenOwnerAddresses.push(address); + } public getTokenOwnerAddresses(): string[] { return this._tokenOwnerAddresses; } diff --git a/packages/contracts/test/utils/erc721_wrapper.ts b/packages/contracts/test/utils/erc721_wrapper.ts index 6347f56e7..a38dfb811 100644 --- a/packages/contracts/test/utils/erc721_wrapper.ts +++ b/packages/contracts/test/utils/erc721_wrapper.ts @@ -4,8 +4,8 @@ import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Provider } from 'ethereum-types'; import * as _ from 'lodash'; -import { DummyERC721TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c721_token'; -import { ERC721ProxyContract } from '../../generated_contract_wrappers/e_r_c721_proxy'; +import { DummyERC721TokenContract } from '../../generated_contract_wrappers/dummy_erc721_token'; +import { ERC721ProxyContract } from '../../generated_contract_wrappers/erc721_proxy'; import { artifacts } from './artifacts'; import { constants } from './constants'; diff --git a/packages/contracts/test/utils/forwarder_wrapper.ts b/packages/contracts/test/utils/forwarder_wrapper.ts new file mode 100644 index 000000000..d227420ee --- /dev/null +++ b/packages/contracts/test/utils/forwarder_wrapper.ts @@ -0,0 +1,220 @@ +import { assetProxyUtils } from '@0xproject/order-utils'; +import { AssetProxyId, SignedOrder } from '@0xproject/types'; +import { BigNumber } from '@0xproject/utils'; +import { Web3Wrapper } from '@0xproject/web3-wrapper'; +import { Provider, TransactionReceiptWithDecodedLogs, TxDataPayable } from 'ethereum-types'; +import * as _ from 'lodash'; + +import { ForwarderContract } from '../../generated_contract_wrappers/forwarder'; + +import { constants } from './constants'; +import { formatters } from './formatters'; +import { LogDecoder } from './log_decoder'; +import { MarketSellOrders } from './types'; + +const DEFAULT_FEE_PROPORTION = 0; +const PERCENTAGE_DENOMINATOR = 10000; +const ZERO_AMOUNT = new BigNumber(0); +const INSUFFICENT_ORDERS_FOR_MAKER_AMOUNT = 'Unable to satisfy makerAssetFillAmount with provided orders'; + +export class ForwarderWrapper { + private _web3Wrapper: Web3Wrapper; + private _forwarderContract: ForwarderContract; + private _logDecoder: LogDecoder; + private _zrxAddress: string; + private static _createOptimizedSellOrders(signedOrders: SignedOrder[]): MarketSellOrders { + const marketSellOrders = formatters.createMarketSellOrders(signedOrders, ZERO_AMOUNT); + const assetDataId = assetProxyUtils.decodeAssetDataId(signedOrders[0].makerAssetData); + // Contract will fill this in for us as all of the assetData is assumed to be the same + for (let i = 0; i < signedOrders.length; i++) { + if (i !== 0 && assetDataId === AssetProxyId.ERC20) { + // Forwarding contract will fill this in from the first order + marketSellOrders.orders[i].makerAssetData = constants.NULL_BYTES; + } + marketSellOrders.orders[i].takerAssetData = constants.NULL_BYTES; + } + return marketSellOrders; + } + private static _createOptimizedZRXSellOrders(signedOrders: SignedOrder[]): MarketSellOrders { + const marketSellOrders = formatters.createMarketSellOrders(signedOrders, ZERO_AMOUNT); + // Contract will fill this in for us as all of the assetData is assumed to be the same + for (let i = 0; i < signedOrders.length; i++) { + marketSellOrders.orders[i].makerAssetData = constants.NULL_BYTES; + marketSellOrders.orders[i].takerAssetData = constants.NULL_BYTES; + } + return marketSellOrders; + } + private static _calculateAdditionalFeeProportionAmount(feeProportion: number, fillAmountWei: BigNumber): BigNumber { + if (feeProportion > 0) { + // Add to the total ETH transaction to ensure all NFTs can be filled after fees + // 150 = 1.5% = 0.015 + const denominator = new BigNumber(1).minus(new BigNumber(feeProportion).dividedBy(PERCENTAGE_DENOMINATOR)); + return fillAmountWei.dividedBy(denominator).round(0, BigNumber.ROUND_FLOOR); + } + return fillAmountWei; + } + constructor(contractInstance: ForwarderContract, provider: Provider, zrxAddress: string) { + this._forwarderContract = contractInstance; + this._web3Wrapper = new Web3Wrapper(provider); + this._logDecoder = new LogDecoder(this._web3Wrapper, this._forwarderContract.address); + // this._web3Wrapper.abiDecoder.addABI(contractInstance.abi); + this._zrxAddress = zrxAddress; + } + public async marketBuyTokensWithEthAsync( + orders: SignedOrder[], + feeOrders: SignedOrder[], + makerTokenBuyAmount: BigNumber, + txData: TxDataPayable, + opts: { feeProportion?: number; feeRecipient?: string } = {}, + ): Promise<TransactionReceiptWithDecodedLogs> { + const params = ForwarderWrapper._createOptimizedSellOrders(orders); + const feeParams = ForwarderWrapper._createOptimizedZRXSellOrders(feeOrders); + const feeProportion = _.isUndefined(opts.feeProportion) ? DEFAULT_FEE_PROPORTION : opts.feeProportion; + const feeRecipient = _.isUndefined(opts.feeRecipient) ? constants.NULL_ADDRESS : opts.feeRecipient; + const txHash: string = await this._forwarderContract.marketBuyTokensWithEth.sendTransactionAsync( + params.orders, + params.signatures, + feeParams.orders, + feeParams.signatures, + makerTokenBuyAmount, + feeProportion, + feeRecipient, + txData, + ); + const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); + return tx; + } + public async marketSellEthForERC20Async( + orders: SignedOrder[], + feeOrders: SignedOrder[], + txData: TxDataPayable, + opts: { feeProportion?: number; feeRecipient?: string } = {}, + ): Promise<TransactionReceiptWithDecodedLogs> { + const assetDataId = assetProxyUtils.decodeAssetDataId(orders[0].makerAssetData); + if (assetDataId !== AssetProxyId.ERC20) { + throw new Error('Asset type not supported by marketSellEthForERC20'); + } + const params = ForwarderWrapper._createOptimizedSellOrders(orders); + const feeParams = ForwarderWrapper._createOptimizedZRXSellOrders(feeOrders); + const feeProportion = _.isUndefined(opts.feeProportion) ? DEFAULT_FEE_PROPORTION : opts.feeProportion; + const feeRecipient = _.isUndefined(opts.feeRecipient) ? constants.NULL_ADDRESS : opts.feeRecipient; + const txHash: string = await this._forwarderContract.marketSellEthForERC20.sendTransactionAsync( + params.orders, + params.signatures, + feeParams.orders, + feeParams.signatures, + feeProportion, + feeRecipient, + txData, + ); + const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); + return tx; + } + public async calculateMarketBuyFillAmountWeiAsync( + orders: SignedOrder[], + feeOrders: SignedOrder[], + feeProportion: number, + makerAssetFillAmount: BigNumber, + ): Promise<BigNumber> { + const assetProxyId = assetProxyUtils.decodeAssetDataId(orders[0].makerAssetData); + switch (assetProxyId) { + case AssetProxyId.ERC20: { + const fillAmountWei = this._calculateMarketBuyERC20FillAmountAsync( + orders, + feeOrders, + feeProportion, + makerAssetFillAmount, + ); + return fillAmountWei; + } + case AssetProxyId.ERC721: { + const fillAmountWei = await this._calculateMarketBuyERC721FillAmountAsync( + orders, + feeOrders, + feeProportion, + ); + return fillAmountWei; + } + default: + throw new Error(`Invalid Asset Proxy Id: ${assetProxyId}`); + } + } + private async _calculateMarketBuyERC20FillAmountAsync( + orders: SignedOrder[], + feeOrders: SignedOrder[], + feeProportion: number, + makerAssetFillAmount: BigNumber, + ): Promise<BigNumber> { + const makerAssetData = assetProxyUtils.decodeAssetData(orders[0].makerAssetData); + const makerAssetToken = makerAssetData.tokenAddress; + const params = formatters.createMarketBuyOrders(orders, makerAssetFillAmount); + + let fillAmountWei; + if (makerAssetToken === this._zrxAddress) { + // If buying ZRX we buy the tokens and fees from the ZRX order in one step + const expectedBuyFeeTokensFillResults = await this._forwarderContract.calculateMarketBuyZrxResults.callAsync( + params.orders, + makerAssetFillAmount, + ); + if (expectedBuyFeeTokensFillResults.makerAssetFilledAmount.lessThan(makerAssetFillAmount)) { + throw new Error(INSUFFICENT_ORDERS_FOR_MAKER_AMOUNT); + } + fillAmountWei = expectedBuyFeeTokensFillResults.takerAssetFilledAmount; + } else { + const expectedMarketBuyFillResults = await this._forwarderContract.calculateMarketBuyResults.callAsync( + params.orders, + makerAssetFillAmount, + ); + if (expectedMarketBuyFillResults.makerAssetFilledAmount.lessThan(makerAssetFillAmount)) { + throw new Error(INSUFFICENT_ORDERS_FOR_MAKER_AMOUNT); + } + fillAmountWei = expectedMarketBuyFillResults.takerAssetFilledAmount; + const expectedFeeAmount = expectedMarketBuyFillResults.takerFeePaid; + if (expectedFeeAmount.greaterThan(ZERO_AMOUNT)) { + const expectedFeeFillFillAmountWei = await this._calculateMarketBuyERC20FillAmountAsync( + feeOrders, + [], + DEFAULT_FEE_PROPORTION, + expectedFeeAmount, + ); + fillAmountWei = fillAmountWei.plus(expectedFeeFillFillAmountWei); + } + } + fillAmountWei = ForwarderWrapper._calculateAdditionalFeeProportionAmount(feeProportion, fillAmountWei); + return fillAmountWei; + } + private async _calculateMarketBuyERC721FillAmountAsync( + orders: SignedOrder[], + feeOrders: SignedOrder[], + feeProportion: number, + ): Promise<BigNumber> { + // Total cost when buying ERC721 is the total cost of all ERC721 orders + any fee abstraction + let fillAmountWei = _.reduce( + orders, + (totalAmount: BigNumber, order: SignedOrder) => { + return totalAmount.plus(order.takerAssetAmount); + }, + ZERO_AMOUNT, + ); + const totalFees = _.reduce( + orders, + (totalAmount: BigNumber, order: SignedOrder) => { + return totalAmount.plus(order.takerFee); + }, + ZERO_AMOUNT, + ); + if (totalFees.greaterThan(ZERO_AMOUNT)) { + // Calculate the ZRX fee abstraction cost + const emptyFeeOrders: SignedOrder[] = []; + const expectedFeeAmountWei = await this._calculateMarketBuyERC20FillAmountAsync( + feeOrders, + emptyFeeOrders, + DEFAULT_FEE_PROPORTION, + totalFees, + ); + fillAmountWei = fillAmountWei.plus(expectedFeeAmountWei); + } + fillAmountWei = ForwarderWrapper._calculateAdditionalFeeProportionAmount(feeProportion, fillAmountWei); + return fillAmountWei; + } +} diff --git a/packages/contracts/test/utils/multi_sig_wrapper.ts b/packages/contracts/test/utils/multi_sig_wrapper.ts index 6e7746dfc..2024c177d 100644 --- a/packages/contracts/test/utils/multi_sig_wrapper.ts +++ b/packages/contracts/test/utils/multi_sig_wrapper.ts @@ -6,6 +6,7 @@ import * as _ from 'lodash'; import { AssetProxyOwnerContract } from '../../generated_contract_wrappers/asset_proxy_owner'; import { MultiSigWalletContract } from '../../generated_contract_wrappers/multi_sig_wallet'; +import { constants } from './constants'; import { LogDecoder } from './log_decoder'; export class MultiSigWrapper { @@ -36,7 +37,10 @@ export class MultiSigWrapper { return tx; } public async executeTransactionAsync(txId: BigNumber, from: string): Promise<TransactionReceiptWithDecodedLogs> { - const txHash = await this._multiSig.executeTransaction.sendTransactionAsync(txId, { from }); + const txHash = await this._multiSig.executeTransaction.sendTransactionAsync(txId, { + from, + gas: constants.MAX_EXECUTE_TRANSACTION_GAS, + }); const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); return tx; } @@ -48,6 +52,7 @@ export class MultiSigWrapper { const txHash = await (this ._multiSig as AssetProxyOwnerContract).executeRemoveAuthorizedAddressAtIndex.sendTransactionAsync(txId, { from, + gas: constants.MAX_EXECUTE_TRANSACTION_GAS, }); const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); return tx; diff --git a/packages/contracts/test/utils/order_factory_from_scenario.ts b/packages/contracts/test/utils/order_factory_from_scenario.ts index 9670c1a59..526505871 100644 --- a/packages/contracts/test/utils/order_factory_from_scenario.ts +++ b/packages/contracts/test/utils/order_factory_from_scenario.ts @@ -2,7 +2,7 @@ import { assetProxyUtils, generatePseudoRandomSalt } from '@0xproject/order-util import { Order } from '@0xproject/types'; import { BigNumber, errorUtils } from '@0xproject/utils'; -import { DummyERC721TokenContract } from '../../generated_contract_wrappers/dummy_e_r_c721_token'; +import { DummyERC721TokenContract } from '../../generated_contract_wrappers/dummy_erc721_token'; import { constants } from './constants'; import { diff --git a/packages/contracts/test/utils/types.ts b/packages/contracts/test/utils/types.ts index b792bb90a..67313b647 100644 --- a/packages/contracts/test/utils/types.ts +++ b/packages/contracts/test/utils/types.ts @@ -102,6 +102,7 @@ export enum ContractName { TestWallet = 'TestWallet', Authorizable = 'Authorizable', Whitelist = 'Whitelist', + Forwarder = 'Forwarder', } export interface SignedTransaction { @@ -227,3 +228,10 @@ export interface FillScenario { makerStateScenario: TraderStateScenario; takerStateScenario: TraderStateScenario; } + +export interface FillResults { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; +} |