diff options
author | Jacob Evans <dekz@dekz.net> | 2018-07-02 09:21:16 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-07-02 09:21:16 +0800 |
commit | ad570b8ae162a213b4b88c417ecd64d4661df18b (patch) | |
tree | d9acfb9e2459c4dfcac191061fefebe015ff5771 /packages/contracts/src | |
parent | b9165c03af40983d885af2b18e729f11746de91d (diff) | |
parent | b9b00e10d39c3c84bc72892ef37f1313e904414d (diff) | |
download | dexon-0x-contracts-ad570b8ae162a213b4b88c417ecd64d4661df18b.tar.gz dexon-0x-contracts-ad570b8ae162a213b4b88c417ecd64d4661df18b.tar.zst dexon-0x-contracts-ad570b8ae162a213b4b88c417ecd64d4661df18b.zip |
Merge branch 'v2-prototype' into eth-lightwallet-subprovider-final
Diffstat (limited to 'packages/contracts/src')
-rw-r--r-- | packages/contracts/src/1.0.0/Arbitrage/Arbitrage.sol (renamed from packages/contracts/src/contracts/previous/Arbitrage/Arbitrage.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/ERC20Token/ERC20Token_v1.sol (renamed from packages/contracts/src/contracts/previous/ERC20Token/ERC20Token_v1.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/EtherDelta/AccountLevels.sol (renamed from packages/contracts/src/contracts/previous/EtherDelta/AccountLevels.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/EtherDelta/EtherDelta.sol (renamed from packages/contracts/src/contracts/previous/EtherDelta/EtherDelta.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/Exchange/Exchange_v1.sol (renamed from packages/contracts/src/contracts/previous/Exchange/Exchange_v1.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/Exchange/IExchange_v1.sol (renamed from packages/contracts/src/contracts/previous/Exchange/IExchange_v1.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/MultiSigWalletWithTImeLockExceptRemoveAuthorizedAddress/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol (renamed from packages/contracts/src/contracts/previous/MultiSigWalletWithTImeLockExceptRemoveAuthorizedAddress/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/Ownable/IOwnable_v1.sol (renamed from packages/contracts/src/contracts/previous/Ownable/IOwnable_v1.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/Ownable/Ownable_v1.sol (renamed from packages/contracts/src/contracts/previous/Ownable/Ownable_v1.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/SafeMath/SafeMath_v1.sol (renamed from packages/contracts/src/contracts/previous/SafeMath/SafeMath_v1.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/Token/Token_v1.sol (renamed from packages/contracts/src/contracts/previous/Token/Token_v1.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/TokenRegistry/ITokenRegistery.sol (renamed from packages/contracts/src/contracts/previous/TokenRegistry/ITokenRegistery.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/TokenRegistry/TokenRegistry.sol (renamed from packages/contracts/src/contracts/previous/TokenRegistry/TokenRegistry.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/TokenTransferProxy/TokenTransferProxy_v1.sol (renamed from packages/contracts/src/contracts/previous/TokenTransferProxy/TokenTransferProxy_v1.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/1.0.0/UnlimitedAllowanceToken/UnlimitedAllowanceToken_v1.sol (renamed from packages/contracts/src/contracts/previous/UnlimitedAllowanceToken/UnlimitedAllowanceToken_v1.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/multisig/MultiSigWallet.sol (renamed from packages/contracts/src/contracts/current/multisig/MultiSigWallet.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/multisig/MultiSigWalletWithTimeLock.sol (renamed from packages/contracts/src/contracts/current/multisig/MultiSigWalletWithTimeLock.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/AssetProxy/ERC20Proxy.sol | 132 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/AssetProxy/ERC721Proxy.sol | 218 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/AssetProxy/MixinAuthorizable.sol (renamed from packages/contracts/src/contracts/current/protocol/AssetProxy/MixinAuthorizable.sol) | 14 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetData.sol (renamed from packages/contracts/src/contracts/current/protocol/AssetProxy/libs/LibTransferErrors.sol) | 23 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetProxy.sol (renamed from packages/contracts/src/contracts/current/protocol/AssetProxy/interfaces/IAssetProxy.sol) | 18 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAuthorizable.sol (renamed from packages/contracts/src/contracts/current/protocol/AssetProxy/interfaces/IAuthorizable.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/AssetProxy/libs/LibAssetProxyErrors.sol (renamed from packages/contracts/src/contracts/current/protocol/AssetProxy/libs/LibAssetProxyErrors.sol) | 18 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/AssetProxy/mixins/MAuthorizable.sol (renamed from packages/contracts/src/contracts/current/protocol/AssetProxy/mixins/MAuthorizable.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/AssetProxyOwner/AssetProxyOwner.sol (renamed from packages/contracts/src/contracts/current/protocol/AssetProxyOwner/AssetProxyOwner.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/Exchange.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/Exchange.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/MixinAssetProxyDispatcher.sol | 175 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/MixinExchangeCore.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/MixinExchangeCore.sol) | 31 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/MixinMatchOrders.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/MixinMatchOrders.sol) | 17 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/MixinSignatureValidator.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/MixinSignatureValidator.sol) | 36 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/MixinTransactions.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/MixinTransactions.sol) | 17 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/MixinWrapperFunctions.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/MixinWrapperFunctions.sol) | 20 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IAssetProxyDispatcher.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IAssetProxyDispatcher.sol) | 16 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchange.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IExchange.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchangeCore.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IExchangeCore.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IMatchOrders.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IMatchOrders.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ISignatureValidator.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/interfaces/ISignatureValidator.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ITransactions.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/interfaces/ITransactions.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IValidator.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IValidator.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWallet.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IWallet.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWrapperFunctions.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IWrapperFunctions.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/libs/LibConstants.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/libs/LibConstants.sol) | 3 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/libs/LibEIP712.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/libs/LibEIP712.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/libs/LibExchangeErrors.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/libs/LibExchangeErrors.sol) | 8 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/libs/LibFillResults.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/libs/LibFillResults.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/libs/LibMath.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/libs/LibMath.sol) | 1 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/libs/LibOrder.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/libs/LibOrder.sol) | 15 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/mixins/MAssetProxyDispatcher.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/mixins/MAssetProxyDispatcher.sol) | 11 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/mixins/MExchangeCore.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/mixins/MExchangeCore.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/mixins/MMatchOrders.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/mixins/MMatchOrders.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/mixins/MSignatureValidator.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/mixins/MSignatureValidator.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/protocol/Exchange/mixins/MTransactions.sol (renamed from packages/contracts/src/contracts/current/protocol/Exchange/mixins/MTransactions.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/test/DummyERC20Token/DummyERC20Token.sol (renamed from packages/contracts/src/contracts/current/test/DummyERC20Token/DummyERC20Token.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/test/DummyERC721Receiver/DummyERC721Receiver.sol (renamed from packages/contracts/src/contracts/current/test/DummyERC721Receiver/DummyERC721Receiver.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/test/DummyERC721Token/DummyERC721Token.sol (renamed from packages/contracts/src/contracts/current/test/DummyERC721Token/DummyERC721Token.sol) | 16 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/test/ExchangeWrapper/ExchangeWrapper.sol (renamed from packages/contracts/src/contracts/current/test/ExchangeWrapper/ExchangeWrapper.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/test/Mintable/Mintable.sol (renamed from packages/contracts/src/contracts/current/test/Mintable/Mintable.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/test/TestAssetProxyDispatcher/TestAssetProxyDispatcher.sol (renamed from packages/contracts/src/contracts/current/test/TestAssetProxyDispatcher/TestAssetProxyDispatcher.sol) | 3 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/test/TestAssetProxyOwner/TestAssetProxyOwner.sol (renamed from packages/contracts/src/contracts/current/test/TestAssetProxyOwner/TestAssetProxyOwner.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/test/TestLibBytes/TestLibBytes.sol (renamed from packages/contracts/src/contracts/current/test/TestLibBytes/TestLibBytes.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/test/TestLibs/TestLibs.sol (renamed from packages/contracts/src/contracts/current/test/TestLibs/TestLibs.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/test/TestSignatureValidator/TestSignatureValidator.sol (renamed from packages/contracts/src/contracts/current/test/TestSignatureValidator/TestSignatureValidator.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/test/TestValidator/TestValidator.sol (renamed from packages/contracts/src/contracts/current/test/TestValidator/TestValidator.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/test/TestWallet/TestWallet.sol (renamed from packages/contracts/src/contracts/current/test/TestWallet/TestWallet.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/test/Whitelist/Whitelist.sol (renamed from packages/contracts/src/contracts/current/test/Whitelist/Whitelist.sol) | 10 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/tokens/ERC20Token/ERC20Token.sol (renamed from packages/contracts/src/contracts/current/tokens/ERC20Token/ERC20Token.sol) | 5 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/tokens/ERC20Token/IERC20Token.sol (renamed from packages/contracts/src/contracts/current/tokens/ERC20Token/IERC20Token.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/tokens/ERC721Token/ERC721Token.sol (renamed from packages/contracts/src/contracts/current/tokens/ERC721Token/ERC721Token.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Receiver.sol (renamed from packages/contracts/src/contracts/current/tokens/ERC721Token/IERC721Receiver.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Token.sol (renamed from packages/contracts/src/contracts/current/tokens/ERC721Token/IERC721Token.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/tokens/UnlimitedAllowanceToken/UnlimitedAllowanceToken.sol (renamed from packages/contracts/src/contracts/current/tokens/UnlimitedAllowanceToken/UnlimitedAllowanceToken.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/tokens/WETH9/WETH9.sol (renamed from packages/contracts/src/contracts/current/tokens/WETH9/WETH9.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/tokens/ZRXToken/ZRXToken.sol (renamed from packages/contracts/src/contracts/current/tokens/ZRXToken/ZRXToken.sol) | 2 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/utils/LibBytes/LibBytes.sol (renamed from packages/contracts/src/contracts/current/utils/LibBytes/LibBytes.sol) | 67 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/utils/Ownable/IOwnable.sol (renamed from packages/contracts/src/contracts/current/utils/Ownable/IOwnable.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/utils/Ownable/Ownable.sol (renamed from packages/contracts/src/contracts/current/utils/Ownable/Ownable.sol) | 5 | ||||
-rw-r--r-- | packages/contracts/src/2.0.0/utils/SafeMath/SafeMath.sol (renamed from packages/contracts/src/contracts/current/utils/SafeMath/SafeMath.sol) | 0 | ||||
-rw-r--r-- | packages/contracts/src/contracts/current/protocol/AssetProxy/ERC20Proxy.sol | 44 | ||||
-rw-r--r-- | packages/contracts/src/contracts/current/protocol/AssetProxy/ERC721Proxy.sol | 44 | ||||
-rw-r--r-- | packages/contracts/src/contracts/current/protocol/AssetProxy/MixinAssetProxy.sol | 75 | ||||
-rw-r--r-- | packages/contracts/src/contracts/current/protocol/AssetProxy/MixinERC20Transfer.sol | 82 | ||||
-rw-r--r-- | packages/contracts/src/contracts/current/protocol/AssetProxy/MixinERC721Transfer.sol | 94 | ||||
-rw-r--r-- | packages/contracts/src/contracts/current/protocol/AssetProxy/mixins/MAssetProxy.sol | 40 | ||||
-rw-r--r-- | packages/contracts/src/contracts/current/protocol/Exchange/MixinAssetProxyDispatcher.sol | 118 | ||||
-rw-r--r-- | packages/contracts/src/contracts/current/test/TestAssetDataDecoders/TestAssetDataDecoders.sol | 56 | ||||
-rw-r--r-- | packages/contracts/src/utils/address_utils.ts | 10 | ||||
-rw-r--r-- | packages/contracts/src/utils/artifacts.ts | 51 | ||||
-rw-r--r-- | packages/contracts/src/utils/assertions.ts | 63 | ||||
-rw-r--r-- | packages/contracts/src/utils/chai_setup.ts | 13 | ||||
-rw-r--r-- | packages/contracts/src/utils/constants.ts | 62 | ||||
-rw-r--r-- | packages/contracts/src/utils/coverage.ts | 21 | ||||
-rw-r--r-- | packages/contracts/src/utils/erc20_wrapper.ts | 118 | ||||
-rw-r--r-- | packages/contracts/src/utils/erc721_wrapper.ts | 147 | ||||
-rw-r--r-- | packages/contracts/src/utils/exchange_wrapper.ts | 250 | ||||
-rw-r--r-- | packages/contracts/src/utils/formatters.ts | 68 | ||||
-rw-r--r-- | packages/contracts/src/utils/increase_time.ts | 31 | ||||
-rw-r--r-- | packages/contracts/src/utils/log_decoder.ts | 55 | ||||
-rw-r--r-- | packages/contracts/src/utils/match_order_tester.ts | 330 | ||||
-rw-r--r-- | packages/contracts/src/utils/multi_sig_wrapper.ts | 55 | ||||
-rw-r--r-- | packages/contracts/src/utils/order_factory.ts | 37 | ||||
-rw-r--r-- | packages/contracts/src/utils/order_utils.ts | 51 | ||||
-rw-r--r-- | packages/contracts/src/utils/profiler.ts | 27 | ||||
-rw-r--r-- | packages/contracts/src/utils/revert_trace.ts | 21 | ||||
-rw-r--r-- | packages/contracts/src/utils/signing_utils.ts | 29 | ||||
-rw-r--r-- | packages/contracts/src/utils/token_registry_wrapper.ts | 66 | ||||
-rw-r--r-- | packages/contracts/src/utils/transaction_factory.ts | 47 | ||||
-rw-r--r-- | packages/contracts/src/utils/types.ts | 152 | ||||
-rw-r--r-- | packages/contracts/src/utils/web3_wrapper.ts | 82 |
109 files changed, 695 insertions, 2525 deletions
diff --git a/packages/contracts/src/contracts/previous/Arbitrage/Arbitrage.sol b/packages/contracts/src/1.0.0/Arbitrage/Arbitrage.sol index 5054afc2f..5054afc2f 100644 --- a/packages/contracts/src/contracts/previous/Arbitrage/Arbitrage.sol +++ b/packages/contracts/src/1.0.0/Arbitrage/Arbitrage.sol diff --git a/packages/contracts/src/contracts/previous/ERC20Token/ERC20Token_v1.sol b/packages/contracts/src/1.0.0/ERC20Token/ERC20Token_v1.sol index e05ee2d5e..e05ee2d5e 100644 --- a/packages/contracts/src/contracts/previous/ERC20Token/ERC20Token_v1.sol +++ b/packages/contracts/src/1.0.0/ERC20Token/ERC20Token_v1.sol diff --git a/packages/contracts/src/contracts/previous/EtherDelta/AccountLevels.sol b/packages/contracts/src/1.0.0/EtherDelta/AccountLevels.sol index 8d7a930d3..8d7a930d3 100644 --- a/packages/contracts/src/contracts/previous/EtherDelta/AccountLevels.sol +++ b/packages/contracts/src/1.0.0/EtherDelta/AccountLevels.sol diff --git a/packages/contracts/src/contracts/previous/EtherDelta/EtherDelta.sol b/packages/contracts/src/1.0.0/EtherDelta/EtherDelta.sol index fe599ca0a..fe599ca0a 100644 --- a/packages/contracts/src/contracts/previous/EtherDelta/EtherDelta.sol +++ b/packages/contracts/src/1.0.0/EtherDelta/EtherDelta.sol diff --git a/packages/contracts/src/contracts/previous/Exchange/Exchange_v1.sol b/packages/contracts/src/1.0.0/Exchange/Exchange_v1.sol index 3f8e7368d..3f8e7368d 100644 --- a/packages/contracts/src/contracts/previous/Exchange/Exchange_v1.sol +++ b/packages/contracts/src/1.0.0/Exchange/Exchange_v1.sol diff --git a/packages/contracts/src/contracts/previous/Exchange/IExchange_v1.sol b/packages/contracts/src/1.0.0/Exchange/IExchange_v1.sol index ec4bce7b0..ec4bce7b0 100644 --- a/packages/contracts/src/contracts/previous/Exchange/IExchange_v1.sol +++ b/packages/contracts/src/1.0.0/Exchange/IExchange_v1.sol diff --git a/packages/contracts/src/contracts/previous/MultiSigWalletWithTImeLockExceptRemoveAuthorizedAddress/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol b/packages/contracts/src/1.0.0/MultiSigWalletWithTImeLockExceptRemoveAuthorizedAddress/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol index 241e02d4a..241e02d4a 100644 --- a/packages/contracts/src/contracts/previous/MultiSigWalletWithTImeLockExceptRemoveAuthorizedAddress/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol +++ b/packages/contracts/src/1.0.0/MultiSigWalletWithTImeLockExceptRemoveAuthorizedAddress/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol diff --git a/packages/contracts/src/contracts/previous/Ownable/IOwnable_v1.sol b/packages/contracts/src/1.0.0/Ownable/IOwnable_v1.sol index 7e22d544d..7e22d544d 100644 --- a/packages/contracts/src/contracts/previous/Ownable/IOwnable_v1.sol +++ b/packages/contracts/src/1.0.0/Ownable/IOwnable_v1.sol diff --git a/packages/contracts/src/contracts/previous/Ownable/Ownable_v1.sol b/packages/contracts/src/1.0.0/Ownable/Ownable_v1.sol index c87438fa4..c87438fa4 100644 --- a/packages/contracts/src/contracts/previous/Ownable/Ownable_v1.sol +++ b/packages/contracts/src/1.0.0/Ownable/Ownable_v1.sol diff --git a/packages/contracts/src/contracts/previous/SafeMath/SafeMath_v1.sol b/packages/contracts/src/1.0.0/SafeMath/SafeMath_v1.sol index 341d611ec..341d611ec 100644 --- a/packages/contracts/src/contracts/previous/SafeMath/SafeMath_v1.sol +++ b/packages/contracts/src/1.0.0/SafeMath/SafeMath_v1.sol diff --git a/packages/contracts/src/contracts/previous/Token/Token_v1.sol b/packages/contracts/src/1.0.0/Token/Token_v1.sol index de619fb7e..de619fb7e 100644 --- a/packages/contracts/src/contracts/previous/Token/Token_v1.sol +++ b/packages/contracts/src/1.0.0/Token/Token_v1.sol diff --git a/packages/contracts/src/contracts/previous/TokenRegistry/ITokenRegistery.sol b/packages/contracts/src/1.0.0/TokenRegistry/ITokenRegistery.sol index b8bdaf3b9..b8bdaf3b9 100644 --- a/packages/contracts/src/contracts/previous/TokenRegistry/ITokenRegistery.sol +++ b/packages/contracts/src/1.0.0/TokenRegistry/ITokenRegistery.sol diff --git a/packages/contracts/src/contracts/previous/TokenRegistry/TokenRegistry.sol b/packages/contracts/src/1.0.0/TokenRegistry/TokenRegistry.sol index 7417a10a3..7417a10a3 100644 --- a/packages/contracts/src/contracts/previous/TokenRegistry/TokenRegistry.sol +++ b/packages/contracts/src/1.0.0/TokenRegistry/TokenRegistry.sol diff --git a/packages/contracts/src/contracts/previous/TokenTransferProxy/TokenTransferProxy_v1.sol b/packages/contracts/src/1.0.0/TokenTransferProxy/TokenTransferProxy_v1.sol index e3659d8ba..e3659d8ba 100644 --- a/packages/contracts/src/contracts/previous/TokenTransferProxy/TokenTransferProxy_v1.sol +++ b/packages/contracts/src/1.0.0/TokenTransferProxy/TokenTransferProxy_v1.sol diff --git a/packages/contracts/src/contracts/previous/UnlimitedAllowanceToken/UnlimitedAllowanceToken_v1.sol b/packages/contracts/src/1.0.0/UnlimitedAllowanceToken/UnlimitedAllowanceToken_v1.sol index 46379c43d..46379c43d 100644 --- a/packages/contracts/src/contracts/previous/UnlimitedAllowanceToken/UnlimitedAllowanceToken_v1.sol +++ b/packages/contracts/src/1.0.0/UnlimitedAllowanceToken/UnlimitedAllowanceToken_v1.sol diff --git a/packages/contracts/src/contracts/current/multisig/MultiSigWallet.sol b/packages/contracts/src/2.0.0/multisig/MultiSigWallet.sol index 79fd92029..79fd92029 100644 --- a/packages/contracts/src/contracts/current/multisig/MultiSigWallet.sol +++ b/packages/contracts/src/2.0.0/multisig/MultiSigWallet.sol diff --git a/packages/contracts/src/contracts/current/multisig/MultiSigWalletWithTimeLock.sol b/packages/contracts/src/2.0.0/multisig/MultiSigWalletWithTimeLock.sol index 9766c2158..9766c2158 100644 --- a/packages/contracts/src/contracts/current/multisig/MultiSigWalletWithTimeLock.sol +++ b/packages/contracts/src/2.0.0/multisig/MultiSigWalletWithTimeLock.sol diff --git a/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC20Proxy.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC20Proxy.sol new file mode 100644 index 000000000..aed62f54f --- /dev/null +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC20Proxy.sol @@ -0,0 +1,132 @@ +/* + + 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 "./MixinAuthorizable.sol"; + +contract ERC20Proxy is + MixinAuthorizable +{ + // Id of this proxy. + bytes4 constant PROXY_ID = bytes4(keccak256("ERC20Token(address)")); + + function () + external + { + assembly { + // The first 4 bytes of calldata holds the function selector + let selector := and(calldataload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) + + // `transferFrom` will be called with the following parameters: + // assetData Encoded byte array. + // from Address to transfer asset from. + // to Address to transfer asset to. + // amount Amount of asset to transfer. + // bytes4(keccak256("transferFrom(bytes,address,address,uint256)")) = 0xa85e59e4 + if eq(selector, 0xa85e59e400000000000000000000000000000000000000000000000000000000) { + + // To lookup a value in a mapping, we load from the storage location keccak256(k, p), + // where k is the key left padded to 32 bytes and p is the storage slot + let start := mload(64) + mstore(start, and(caller, 0xffffffffffffffffffffffffffffffffffffffff)) + mstore(add(start, 32), authorized_slot) + + // Revert if authorized[msg.sender] == false + if iszero(sload(keccak256(start, 64))) { + // Revert with `Error("SENDER_NOT_AUTHORIZED")` + mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) + mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000) + mstore(64, 0x0000001553454e4445525f4e4f545f415554484f52495a454400000000000000) + mstore(96, 0) + revert(0, 100) + } + + /////// Token contract address /////// + // The token address is found as follows: + // * It is stored at offset 4 in `assetData` contents. + // * This is stored at offset 32 from `assetData`. + // * The offset to `assetData` from Params is stored at offset + // 4 in calldata. + // * The offset of Params in calldata is 4. + // So we read location 4 and add 32 + 4 + 4 to it. + let token := calldataload(add(calldataload(4), 40)) + + /////// Setup Header Area /////// + // This area holds the 4-byte `transferFrom` selector. + // Any trailing data in transferFromSelector will be + // overwritten in the next `mstore` call. + mstore(0, 0x23b872dd00000000000000000000000000000000000000000000000000000000) + + /////// Setup Params Area /////// + // We copy the fields `from`, `to` and `amount` in bulk + // from our own calldata to the new calldata. + calldatacopy(4, 36, 96) + + /////// Call `token.transferFrom` using the calldata /////// + let success := call( + gas, // forward all gas + token, // call address of token contract + 0, // don't send any ETH + 0, // pointer to start of input + 100, // length of input + 0, // write output over input + 32 // output size should be 32 bytes + ) + + /////// 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 + // nonzero 32 bytes value. + // So the transfer succeeded if the call succeeded and either + // returned nothing, or returned a non-zero 32 byte value. + success := and(success, or( + iszero(returndatasize), + and( + eq(returndatasize, 32), + gt(mload(0), 0) + ) + )) + if success { + return(0, 0) + } + + // Revert with `Error("TRANSFER_FAILED")` + mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) + mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000) + mstore(64, 0x0000000f5452414e534645525f4641494c454400000000000000000000000000) + mstore(96, 0) + revert(0, 100) + } + } + } + + /// @dev Gets the proxy id associated with the proxy address. + /// @return Proxy id. + function getProxyId() + external + pure + returns (bytes4) + { + return PROXY_ID; + } +} diff --git a/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC721Proxy.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC721Proxy.sol new file mode 100644 index 000000000..b73dc36cc --- /dev/null +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/ERC721Proxy.sol @@ -0,0 +1,218 @@ +/* + + 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 "./MixinAuthorizable.sol"; + +contract ERC721Proxy is + MixinAuthorizable +{ + // Id of this proxy. + bytes4 constant PROXY_ID = bytes4(keccak256("ERC721Token(address,uint256,bytes)")); + + function () + external + { + assembly { + // The first 4 bytes of calldata holds the function selector + let selector := and(calldataload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) + + // `transferFrom` will be called with the following parameters: + // assetData Encoded byte array. + // from Address to transfer asset from. + // to Address to transfer asset to. + // amount Amount of asset to transfer. + // bytes4(keccak256("transferFrom(bytes,address,address,uint256)")) = 0xa85e59e4 + if eq(selector, 0xa85e59e400000000000000000000000000000000000000000000000000000000) { + + // To lookup a value in a mapping, we load from the storage location keccak256(k, p), + // where k is the key left padded to 32 bytes and p is the storage slot + let start := mload(64) + mstore(start, and(caller, 0xffffffffffffffffffffffffffffffffffffffff)) + mstore(add(start, 32), authorized_slot) + + // Revert if authorized[msg.sender] == false + if iszero(sload(keccak256(start, 64))) { + // Revert with `Error("SENDER_NOT_AUTHORIZED")` + mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) + mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000) + mstore(64, 0x0000001553454e4445525f4e4f545f415554484f52495a454400000000000000) + mstore(96, 0) + revert(0, 100) + } + + // `transferFrom`. + // The function is marked `external`, so no abi decodeding is done for + // us. Instead, we expect the `calldata` memory to contain the + // following: + // + // | Area | Offset | Length | Contents | + // |----------|--------|---------|-------------------------------------| + // | Header | 0 | 4 | function selector | + // | Params | | 4 * 32 | function parameters: | + // | | 4 | | 1. offset to assetData (*) | + // | | 36 | | 2. from | + // | | 68 | | 3. to | + // | | 100 | | 4. amount | + // | Data | | | assetData: | + // | | 132 | 32 | assetData Length | + // | | 164 | ** | assetData Contents | + // + // (*): offset is computed from start of function parameters, so offset + // by an additional 4 bytes in the calldata. + // + // WARNING: The ABIv2 specification allows additional padding between + // the Params and Data section. This will result in a larger + // offset to assetData. + + // Asset data itself is encoded as follows: + // + // | Area | Offset | Length | Contents | + // |----------|--------|---------|-------------------------------------| + // | Header | 0 | 4 | function selector | + // | Params | | 3 * 32 | function parameters: | + // | | 4 | 12 + 20 | 1. token address | + // | | 36 | | 2. tokenId | + // | | 68 | | 3. offset to receiverData (*) | + // | Data | | | receiverData: | + // | | 100 | 32 | receiverData Length | + // | | 132 | ** | receiverData Contents | + + // We construct calldata for the `token.safeTransferFrom` ABI. + // The layout of this calldata is in the table below. + // + // | Area | Offset | Length | Contents | + // |----------|--------|---------|-------------------------------------| + // | Header | 0 | 4 | function selector | + // | Params | | 4 * 32 | function parameters: | + // | | 4 | | 1. from | + // | | 36 | | 2. to | + // | | 68 | | 3. tokenId | + // | | 100 | | 4. offset to receiverData (*) | + // | Data | | | receiverData: | + // | | 132 | 32 | receiverData Length | + // | | 164 | ** | receiverData Contents | + + // There exists only 1 of each token. + // require(amount == 1, "INVALID_AMOUNT") + if sub(calldataload(100), 1) { + // Revert with `Error("INVALID_AMOUNT")` + mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) + mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000) + mstore(64, 0x0000000e494e56414c49445f414d4f554e540000000000000000000000000000) + mstore(96, 0) + revert(0, 100) + } + + // Require assetData to be at least 132 bytes + let offset := calldataload(4) + if lt(calldataload(add(offset, 4)), 132) { + // Revert with `Error("LENGTH_GREATER_THAN_131_REQUIRED")` + mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) + mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000) + mstore(64, 0x000000204c454e4754485f475245415445525f5448414e5f3133315f52455155) + mstore(96, 0x4952454400000000000000000000000000000000000000000000000000000000) + revert(0, 100) + } + + /////// Setup State /////// + // `cdStart` is the start of the calldata for + // `token.safeTransferFrom` (equal to free memory ptr). + let cdStart := mload(64) + // `dataAreaLength` is the total number of words + // needed to store `receiverData` + // As-per the ABI spec, this value is padded up to + // the nearest multiple of 32, + // and includes 32-bytes for length. + // It's calculated as folows: + // - Unpadded length in bytes = `mload(receiverData) + 32` + // - Add 31 to convert rounding down to rounding up. + // Combined with the previous and this is `63`. + // - Round down to nearest multiple of 32 by clearing + // bits 0x1F. This is done with `and` and a mask. + + /////// Setup Header Area /////// + // This area holds the 4-byte `transferFromSelector`. + // Any trailing data in transferFromSelector will be + // overwritten in the next `mstore` call. + mstore(cdStart, 0xb88d4fde00000000000000000000000000000000000000000000000000000000) + + /////// Setup Params Area /////// + // Each parameter is padded to 32-bytes. + // The entire Params Area is 128 bytes. + // Notes: + // 1. A 20-byte mask is applied to addresses + // to zero-out the unused bytes. + // 2. The offset to `receiverData` is the length + // of the Params Area (128 bytes). + + let length := calldataload(add(offset, 136)) + let token := calldataload(add(offset, 40)) + + // Round length up to multiple of 32 + length := and(add(length, 31), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE0) + + // Copy `from` and `to` + calldatacopy(add(cdStart, 4), 36, 64) + + // TokenId + mstore(add(cdStart, 68), calldataload(add(offset, 72))) + + // Offset to receiverData + mstore(add(cdStart, 100), 128) + + // receiverData (including length) + calldatacopy(add(cdStart, 132), add(offset, 136), add(length, 32)) + + /////// Call `token.safeTransferFrom` using the calldata /////// + let success := call( + gas, // forward all gas + token, // call address of token contract + 0, // don't send any ETH + cdStart, // pointer to start of input + add(length, 164), // length of input + 0, // write output to null + 0 // output size is 0 bytes + ) + if success { + return(0, 0) + } + + // Revert with `Error("TRANSFER_FAILED")` + mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) + mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000) + mstore(64, 0x0000000f5452414e534645525f4641494c454400000000000000000000000000) + mstore(96, 0) + revert(0, 100) + } + } + } + + /// @dev Gets the proxy id associated with the proxy address. + /// @return Proxy id. + function getProxyId() + external + pure + returns (bytes4) + { + return PROXY_ID; + } +} diff --git a/packages/contracts/src/contracts/current/protocol/AssetProxy/MixinAuthorizable.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/MixinAuthorizable.sol index 37c12f861..3b9584a44 100644 --- a/packages/contracts/src/contracts/current/protocol/AssetProxy/MixinAuthorizable.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/MixinAuthorizable.sol @@ -19,12 +19,10 @@ pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; -import "./libs/LibAssetProxyErrors.sol"; import "../../utils/Ownable/Ownable.sol"; import "./mixins/MAuthorizable.sol"; contract MixinAuthorizable is - LibAssetProxyErrors, Ownable, MAuthorizable { @@ -33,7 +31,7 @@ contract MixinAuthorizable is modifier onlyAuthorized { require( authorized[msg.sender], - SENDER_NOT_AUTHORIZED + "SENDER_NOT_AUTHORIZED" ); _; } @@ -49,7 +47,7 @@ contract MixinAuthorizable is { require( !authorized[target], - TARGET_ALREADY_AUTHORIZED + "TARGET_ALREADY_AUTHORIZED" ); authorized[target] = true; @@ -65,7 +63,7 @@ contract MixinAuthorizable is { require( authorized[target], - TARGET_NOT_AUTHORIZED + "TARGET_NOT_AUTHORIZED" ); delete authorized[target]; @@ -91,15 +89,15 @@ contract MixinAuthorizable is { require( authorized[target], - TARGET_NOT_AUTHORIZED + "TARGET_NOT_AUTHORIZED" ); require( index < authorities.length, - INDEX_OUT_OF_BOUNDS + "INDEX_OUT_OF_BOUNDS" ); require( authorities[index] == target, - AUTHORIZED_ADDRESS_MISMATCH + "AUTHORIZED_ADDRESS_MISMATCH" ); delete authorized[target]; diff --git a/packages/contracts/src/contracts/current/protocol/AssetProxy/libs/LibTransferErrors.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetData.sol index ba784ab22..7ebd6acf0 100644 --- a/packages/contracts/src/contracts/current/protocol/AssetProxy/libs/LibTransferErrors.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetData.sol @@ -16,10 +16,23 @@ */ -pragma solidity ^0.4.24; +pragma solidity ^0.4.23; -contract LibTransferErrors { - /// Transfer errors /// - string constant INVALID_AMOUNT = "INVALID_AMOUNT"; // Transfer amount must equal 1. - string constant TRANSFER_FAILED = "TRANSFER_FAILED"; // Transfer failed. +// @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; + + function ERC721Token( + address tokenContract, + uint256 tokenId, + bytes receiverData + ) + external + pure; + } diff --git a/packages/contracts/src/contracts/current/protocol/AssetProxy/interfaces/IAssetProxy.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetProxy.sol index 22f43b12f..eacd5a412 100644 --- a/packages/contracts/src/contracts/current/protocol/AssetProxy/interfaces/IAssetProxy.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAssetProxy.sol @@ -38,24 +38,10 @@ contract IAssetProxy is ) external; - /// @dev Makes multiple transfers of assets. Either succeeds or throws. - /// @param assetData Array of byte arrays encoded for the respective asset proxy. - /// @param from Array of addresses to transfer assets from. - /// @param to Array of addresses to transfer assets to. - /// @param amounts Array of amounts of assets to transfer. - function batchTransferFrom( - bytes[] memory assetData, - address[] memory from, - address[] memory to, - uint256[] memory amounts - ) - public; - /// @dev Gets the proxy id associated with the proxy address. /// @return Proxy id. function getProxyId() external - view - returns (uint8); + pure + returns (bytes4); } - diff --git a/packages/contracts/src/contracts/current/protocol/AssetProxy/interfaces/IAuthorizable.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAuthorizable.sol index cedd1744c..cedd1744c 100644 --- a/packages/contracts/src/contracts/current/protocol/AssetProxy/interfaces/IAuthorizable.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/interfaces/IAuthorizable.sol diff --git a/packages/contracts/src/contracts/current/protocol/AssetProxy/libs/LibAssetProxyErrors.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/libs/LibAssetProxyErrors.sol index dca4f400f..338cb12e2 100644 --- a/packages/contracts/src/contracts/current/protocol/AssetProxy/libs/LibAssetProxyErrors.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/libs/LibAssetProxyErrors.sol @@ -18,11 +18,19 @@ 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. contract LibAssetProxyErrors { + /// Authorizable errors /// - string constant SENDER_NOT_AUTHORIZED = "SENDER_NOT_AUTHORIZED"; // Sender not authorized to call this method. - string constant TARGET_NOT_AUTHORIZED = "TARGET_NOT_AUTHORIZED"; // Target address not authorized to call this method. - string constant TARGET_ALREADY_AUTHORIZED = "TARGET_ALREADY_AUTHORIZED"; // Target address must not already be authorized. - string constant INDEX_OUT_OF_BOUNDS = "INDEX_OUT_OF_BOUNDS"; // Specified array index is out of bounds. - string constant AUTHORIZED_ADDRESS_MISMATCH = "AUTHORIZED_ADDRESS_MISMATCH"; // Address at index does not match given target address. + string constant SENDER_NOT_AUTHORIZED = "SENDER_NOT_AUTHORIZED"; // Sender not authorized to call this method. + string constant TARGET_NOT_AUTHORIZED = "TARGET_NOT_AUTHORIZED"; // Target address not authorized to call this method. + string constant TARGET_ALREADY_AUTHORIZED = "TARGET_ALREADY_AUTHORIZED"; // Target address must not already be authorized. + string constant INDEX_OUT_OF_BOUNDS = "INDEX_OUT_OF_BOUNDS"; // Specified array index is out of bounds. + string constant AUTHORIZED_ADDRESS_MISMATCH = "AUTHORIZED_ADDRESS_MISMATCH"; // Address at index does not match given target address. + + /// Transfer errors /// + string constant INVALID_AMOUNT = "INVALID_AMOUNT"; // Transfer amount must equal 1. + string constant TRANSFER_FAILED = "TRANSFER_FAILED"; // Transfer failed. + string constant LENGTH_GREATER_THAN_131_REQUIRED = "LENGTH_GREATER_THAN_131_REQUIRED"; // Byte array must have a length greater than 0. } diff --git a/packages/contracts/src/contracts/current/protocol/AssetProxy/mixins/MAuthorizable.sol b/packages/contracts/src/2.0.0/protocol/AssetProxy/mixins/MAuthorizable.sol index 6f35bd7ec..6f35bd7ec 100644 --- a/packages/contracts/src/contracts/current/protocol/AssetProxy/mixins/MAuthorizable.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxy/mixins/MAuthorizable.sol diff --git a/packages/contracts/src/contracts/current/protocol/AssetProxyOwner/AssetProxyOwner.sol b/packages/contracts/src/2.0.0/protocol/AssetProxyOwner/AssetProxyOwner.sol index eb58b3374..eb58b3374 100644 --- a/packages/contracts/src/contracts/current/protocol/AssetProxyOwner/AssetProxyOwner.sol +++ b/packages/contracts/src/2.0.0/protocol/AssetProxyOwner/AssetProxyOwner.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/Exchange.sol b/packages/contracts/src/2.0.0/protocol/Exchange/Exchange.sol index d36e9633e..d36e9633e 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/Exchange.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/Exchange.sol diff --git a/packages/contracts/src/2.0.0/protocol/Exchange/MixinAssetProxyDispatcher.sol b/packages/contracts/src/2.0.0/protocol/Exchange/MixinAssetProxyDispatcher.sol new file mode 100644 index 000000000..9e9d88ce7 --- /dev/null +++ b/packages/contracts/src/2.0.0/protocol/Exchange/MixinAssetProxyDispatcher.sol @@ -0,0 +1,175 @@ +/* + + 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/Ownable/Ownable.sol"; +import "../../utils/LibBytes/LibBytes.sol"; +import "./mixins/MAssetProxyDispatcher.sol"; +import "../AssetProxy/interfaces/IAssetProxy.sol"; + +contract MixinAssetProxyDispatcher is + Ownable, + MAssetProxyDispatcher +{ + using LibBytes for bytes; + + // Mapping from Asset Proxy Id's to their respective Asset Proxy + mapping (bytes4 => IAssetProxy) public assetProxies; + + /// @dev Registers an asset proxy to its asset proxy id. + /// Once an asset proxy is registered, it cannot be unregistered. + /// @param assetProxy Address of new asset proxy to register. + function registerAssetProxy(address assetProxy) + external + onlyOwner + { + IAssetProxy assetProxyContract = IAssetProxy(assetProxy); + + // Ensure that no asset proxy exists with current id. + bytes4 assetProxyId = assetProxyContract.getProxyId(); + address currentAssetProxy = assetProxies[assetProxyId]; + require( + currentAssetProxy == address(0), + "ASSET_PROXY_ALREADY_EXISTS" + ); + + // Add asset proxy and log registration. + assetProxies[assetProxyId] = assetProxyContract; + emit AssetProxyRegistered( + assetProxyId, + assetProxy + ); + } + + /// @dev Gets an asset proxy. + /// @param assetProxyId Id of the asset proxy. + /// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered. + function getAssetProxy(bytes4 assetProxyId) + external + view + returns (address) + { + return assetProxies[assetProxyId]; + } + + /// @dev Forwards arguments to assetProxy and calls `transferFrom`. Either succeeds or throws. + /// @param assetData Byte array encoded for the asset. + /// @param from Address to transfer token from. + /// @param to Address to transfer token to. + /// @param amount Amount of token to transfer. + function dispatchTransferFrom( + bytes memory assetData, + address from, + address to, + uint256 amount + ) + internal + { + // Do nothing if no amount should be transferred. + if (amount > 0) { + // Ensure assetData length is valid + require( + assetData.length > 3, + "LENGTH_GREATER_THAN_3_REQUIRED" + ); + + // Lookup assetProxy + bytes4 assetProxyId; + assembly { + assetProxyId := and(mload( + add(assetData, 32)), + 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000 + ) + } + address assetProxy = assetProxies[assetProxyId]; + + // Ensure that assetProxy exists + require( + assetProxy != address(0), + "ASSET_PROXY_DOES_NOT_EXIST" + ); + + // We construct calldata for the `assetProxy.transferFrom` ABI. + // The layout of this calldata is in the table below. + // + // | Area | Offset | Length | Contents | + // | -------- |--------|---------|-------------------------------------------- | + // | Header | 0 | 4 | function selector | + // | Params | | 4 * 32 | function parameters: | + // | | 4 | | 1. offset to assetData (*) | + // | | 36 | | 2. from | + // | | 68 | | 3. to | + // | | 100 | | 4. amount | + // | Data | | | assetData: | + // | | 132 | 32 | assetData Length | + // | | 164 | ** | assetData Contents | + + assembly { + /////// Setup State /////// + // `cdStart` is the start of the calldata for `assetProxy.transferFrom` (equal to free memory ptr). + let cdStart := mload(64) + // `dataAreaLength` is the total number of words needed to store `assetData` + // As-per the ABI spec, this value is padded up to the nearest multiple of 32, + // and includes 32-bytes for length. + let dataAreaLength := and(add(mload(assetData), 63), 0xFFFFFFFFFFFE0) + // `cdEnd` is the end of the calldata for `assetProxy.transferFrom`. + let cdEnd := add(cdStart, add(132, dataAreaLength)) + + + /////// Setup Header Area /////// + // This area holds the 4-byte `transferFromSelector`. + // bytes4(keccak256("transferFrom(bytes,address,address,uint256)")) = 0xa85e59e4 + mstore(cdStart, 0xa85e59e400000000000000000000000000000000000000000000000000000000) + + /////// Setup Params Area /////// + // Each parameter is padded to 32-bytes. The entire Params Area is 128 bytes. + // Notes: + // 1. The offset to `assetData` is the length of the Params Area (128 bytes). + // 2. A 20-byte mask is applied to addresses to zero-out the unused bytes. + mstore(add(cdStart, 4), 128) + mstore(add(cdStart, 36), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) + mstore(add(cdStart, 68), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) + mstore(add(cdStart, 100), amount) + + /////// Setup Data Area /////// + // This area holds `assetData`. + let dataArea := add(cdStart, 132) + for {} lt(dataArea, cdEnd) {} { + mstore(dataArea, mload(assetData)) + dataArea := add(dataArea, 32) + assetData := add(assetData, 32) + } + + /////// Call `assetProxy.transferFrom` using the constructed calldata /////// + let success := call( + gas, // forward all gas + assetProxy, // call address of asset proxy + 0, // don't send any ETH + cdStart, // pointer to start of input + sub(cdEnd, cdStart), // length of input + cdStart, // write output over input + 512 // reserve 512 bytes for output + ) + if iszero(success) { + revert(cdStart, returndatasize()) + } + } + } + } +} diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/MixinExchangeCore.sol b/packages/contracts/src/2.0.0/protocol/Exchange/MixinExchangeCore.sol index b207b3e57..c0ed023ac 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/MixinExchangeCore.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/MixinExchangeCore.sol @@ -20,11 +20,9 @@ pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; import "./libs/LibConstants.sol"; -import "../../utils/LibBytes/LibBytes.sol"; import "./libs/LibFillResults.sol"; import "./libs/LibOrder.sol"; import "./libs/LibMath.sol"; -import "./libs/LibExchangeErrors.sol"; import "./mixins/MExchangeCore.sol"; import "./mixins/MSignatureValidator.sol"; import "./mixins/MTransactions.sol"; @@ -35,14 +33,11 @@ contract MixinExchangeCore is LibMath, LibOrder, LibFillResults, - LibExchangeErrors, MAssetProxyDispatcher, MExchangeCore, MSignatureValidator, MTransactions { - using LibBytes for bytes; - // Mapping of orderHash => amount of takerAsset already bought by maker mapping (bytes32 => uint256) public filled; @@ -73,7 +68,7 @@ contract MixinExchangeCore is // Ensure orderEpoch is monotonically increasing require( newOrderEpoch > oldOrderEpoch, - INVALID_NEW_ORDER_EPOCH + "INVALID_NEW_ORDER_EPOCH" ); // Update orderEpoch @@ -285,20 +280,20 @@ contract MixinExchangeCore is // An order can only be filled if its status is FILLABLE. require( orderInfo.orderStatus == uint8(OrderStatus.FILLABLE), - ORDER_UNFILLABLE + "ORDER_UNFILLABLE" ); // Revert if fill amount is invalid require( takerAssetFillAmount != 0, - INVALID_TAKER_AMOUNT + "INVALID_TAKER_AMOUNT" ); // Validate sender is allowed to fill this order if (order.senderAddress != address(0)) { require( order.senderAddress == msg.sender, - INVALID_SENDER + "INVALID_SENDER" ); } @@ -306,7 +301,7 @@ contract MixinExchangeCore is if (order.takerAddress != address(0)) { require( order.takerAddress == takerAddress, - INVALID_TAKER + "INVALID_TAKER" ); } @@ -318,7 +313,7 @@ contract MixinExchangeCore is order.makerAddress, signature ), - INVALID_ORDER_SIGNATURE + "INVALID_ORDER_SIGNATURE" ); } @@ -329,7 +324,7 @@ contract MixinExchangeCore is order.takerAssetAmount, order.makerAssetAmount ), - ROUNDING_ERROR + "ROUNDING_ERROR" ); } @@ -347,14 +342,14 @@ contract MixinExchangeCore is // An order can only be cancelled if its status is FILLABLE. require( orderInfo.orderStatus == uint8(OrderStatus.FILLABLE), - ORDER_UNFILLABLE + "ORDER_UNFILLABLE" ); // Validate sender is allowed to cancel this order if (order.senderAddress != address(0)) { require( order.senderAddress == msg.sender, - INVALID_SENDER + "INVALID_SENDER" ); } @@ -362,7 +357,7 @@ contract MixinExchangeCore is address makerAddress = getCurrentContextAddress(); require( order.makerAddress == makerAddress, - INVALID_MAKER + "INVALID_MAKER" ); } @@ -412,33 +407,27 @@ contract MixinExchangeCore is ) private { - uint8 makerAssetProxyId = uint8(order.makerAssetData.popLastByte()); - uint8 takerAssetProxyId = uint8(order.takerAssetData.popLastByte()); bytes memory zrxAssetData = ZRX_ASSET_DATA; dispatchTransferFrom( order.makerAssetData, - makerAssetProxyId, order.makerAddress, takerAddress, fillResults.makerAssetFilledAmount ); dispatchTransferFrom( order.takerAssetData, - takerAssetProxyId, takerAddress, order.makerAddress, fillResults.takerAssetFilledAmount ); dispatchTransferFrom( zrxAssetData, - ZRX_PROXY_ID, order.makerAddress, order.feeRecipientAddress, fillResults.makerFeePaid ); dispatchTransferFrom( zrxAssetData, - ZRX_PROXY_ID, takerAddress, order.feeRecipientAddress, fillResults.takerFeePaid diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/MixinMatchOrders.sol b/packages/contracts/src/2.0.0/protocol/Exchange/MixinMatchOrders.sol index e36fcc2c5..1a43eec79 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/MixinMatchOrders.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/MixinMatchOrders.sol @@ -15,11 +15,9 @@ pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; import "./libs/LibConstants.sol"; -import "../../utils/LibBytes/LibBytes.sol"; import "./libs/LibMath.sol"; import "./libs/LibOrder.sol"; import "./libs/LibFillResults.sol"; -import "./libs/LibExchangeErrors.sol"; import "./mixins/MExchangeCore.sol"; import "./mixins/MMatchOrders.sol"; import "./mixins/MTransactions.sol"; @@ -28,14 +26,11 @@ import "./mixins/MAssetProxyDispatcher.sol"; contract MixinMatchOrders is LibConstants, LibMath, - LibExchangeErrors, MAssetProxyDispatcher, MExchangeCore, MMatchOrders, MTransactions { - using LibBytes for bytes; - /// @dev Match two complementary orders that have a profitable spread. /// Each order is filled at their respective price point. However, the calculations are /// carried out as though the orders are both being filled at the right order's price point. @@ -144,7 +139,7 @@ contract MixinMatchOrders is require( safeMul(leftOrder.makerAssetAmount, rightOrder.makerAssetAmount) >= safeMul(leftOrder.takerAssetAmount, rightOrder.takerAssetAmount), - NEGATIVE_SPREAD_REQUIRED + "NEGATIVE_SPREAD_REQUIRED" ); } @@ -242,27 +237,22 @@ contract MixinMatchOrders is ) private { - uint8 leftMakerAssetProxyId = uint8(leftOrder.makerAssetData.popLastByte()); - uint8 rightMakerAssetProxyId = uint8(rightOrder.makerAssetData.popLastByte()); bytes memory zrxAssetData = ZRX_ASSET_DATA; // Order makers and taker dispatchTransferFrom( leftOrder.makerAssetData, - leftMakerAssetProxyId, leftOrder.makerAddress, rightOrder.makerAddress, matchedFillResults.right.takerAssetFilledAmount ); dispatchTransferFrom( rightOrder.makerAssetData, - rightMakerAssetProxyId, rightOrder.makerAddress, leftOrder.makerAddress, matchedFillResults.left.takerAssetFilledAmount ); dispatchTransferFrom( leftOrder.makerAssetData, - leftMakerAssetProxyId, leftOrder.makerAddress, takerAddress, matchedFillResults.leftMakerAssetSpreadAmount @@ -271,14 +261,12 @@ contract MixinMatchOrders is // Maker fees dispatchTransferFrom( zrxAssetData, - ZRX_PROXY_ID, leftOrder.makerAddress, leftOrder.feeRecipientAddress, matchedFillResults.left.makerFeePaid ); dispatchTransferFrom( zrxAssetData, - ZRX_PROXY_ID, rightOrder.makerAddress, rightOrder.feeRecipientAddress, matchedFillResults.right.makerFeePaid @@ -288,7 +276,6 @@ contract MixinMatchOrders is if (leftOrder.feeRecipientAddress == rightOrder.feeRecipientAddress) { dispatchTransferFrom( zrxAssetData, - ZRX_PROXY_ID, takerAddress, leftOrder.feeRecipientAddress, safeAdd( @@ -299,14 +286,12 @@ contract MixinMatchOrders is } else { dispatchTransferFrom( zrxAssetData, - ZRX_PROXY_ID, takerAddress, leftOrder.feeRecipientAddress, matchedFillResults.left.takerFeePaid ); dispatchTransferFrom( zrxAssetData, - ZRX_PROXY_ID, takerAddress, rightOrder.feeRecipientAddress, matchedFillResults.right.takerFeePaid diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/MixinSignatureValidator.sol b/packages/contracts/src/2.0.0/protocol/Exchange/MixinSignatureValidator.sol index cbb55bfce..29172057a 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/MixinSignatureValidator.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/MixinSignatureValidator.sol @@ -19,23 +19,17 @@ pragma solidity ^0.4.24; import "../../utils/LibBytes/LibBytes.sol"; -import "./libs/LibExchangeErrors.sol"; import "./mixins/MSignatureValidator.sol"; import "./mixins/MTransactions.sol"; import "./interfaces/IWallet.sol"; import "./interfaces/IValidator.sol"; contract MixinSignatureValidator is - LibExchangeErrors, MSignatureValidator, MTransactions { using LibBytes for bytes; - // Personal message headers - string constant ETH_PERSONAL_MESSAGE = "\x19Ethereum Signed Message:\n32"; - string constant TREZOR_PERSONAL_MESSAGE = "\x19Ethereum Signed Message:\n\x20"; - // Mapping of hash => signer => signed mapping (bytes32 => mapping (address => bool)) public preSigned; @@ -59,7 +53,7 @@ contract MixinSignatureValidator is signerAddress, signature ), - INVALID_SIGNATURE + "INVALID_SIGNATURE" ); preSigned[hash][signerAddress] = true; } @@ -99,14 +93,14 @@ contract MixinSignatureValidator is // 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 + "LENGTH_GREATER_THAN_0_REQUIRED" ); // Ensure signature is supported uint8 signatureTypeRaw = uint8(signature.popLastByte()); require( signatureTypeRaw < uint8(SignatureType.NSignatureTypes), - SIGNATURE_UNSUPPORTED + "SIGNATURE_UNSUPPORTED" ); // Pop last byte off of signature byte array. @@ -124,7 +118,7 @@ contract MixinSignatureValidator is // it an explicit option. This aids testing and analysis. It is // also the initialization value for the enum type. if (signatureType == SignatureType.Illegal) { - revert(SIGNATURE_ILLEGAL); + revert("SIGNATURE_ILLEGAL"); // Always invalid signature. // Like Illegal, this is always implicitly available and therefore @@ -133,7 +127,7 @@ contract MixinSignatureValidator is } else if (signatureType == SignatureType.Invalid) { require( signature.length == 0, - LENGTH_0_REQUIRED + "LENGTH_0_REQUIRED" ); isValid = false; return isValid; @@ -142,7 +136,7 @@ contract MixinSignatureValidator is } else if (signatureType == SignatureType.EIP712) { require( signature.length == 65, - LENGTH_65_REQUIRED + "LENGTH_65_REQUIRED" ); v = uint8(signature[0]); r = signature.readBytes32(1); @@ -155,13 +149,16 @@ contract MixinSignatureValidator is } else if (signatureType == SignatureType.EthSign) { require( signature.length == 65, - LENGTH_65_REQUIRED + "LENGTH_65_REQUIRED" ); v = uint8(signature[0]); r = signature.readBytes32(1); s = signature.readBytes32(33); recovered = ecrecover( - keccak256(abi.encodePacked(ETH_PERSONAL_MESSAGE, hash)), + keccak256(abi.encodePacked( + "\x19Ethereum Signed Message:\n32", + hash + )), v, r, s @@ -180,7 +177,7 @@ contract MixinSignatureValidator is } else if (signatureType == SignatureType.Caller) { require( signature.length == 0, - LENGTH_0_REQUIRED + "LENGTH_0_REQUIRED" ); isValid = signerAddress == msg.sender; return isValid; @@ -230,13 +227,16 @@ contract MixinSignatureValidator is } else if (signatureType == SignatureType.Trezor) { require( signature.length == 65, - LENGTH_65_REQUIRED + "LENGTH_65_REQUIRED" ); v = uint8(signature[0]); r = signature.readBytes32(1); s = signature.readBytes32(33); recovered = ecrecover( - keccak256(abi.encodePacked(TREZOR_PERSONAL_MESSAGE, hash)), + keccak256(abi.encodePacked( + "\x19Ethereum Signed Message:\n\x20", + hash + )), v, r, s @@ -250,6 +250,6 @@ contract MixinSignatureValidator is // that we currently support. In this case returning false // may lead the caller to incorrectly believe that the // signature was invalid.) - revert(SIGNATURE_UNSUPPORTED); + revert("SIGNATURE_UNSUPPORTED"); } } diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/MixinTransactions.sol b/packages/contracts/src/2.0.0/protocol/Exchange/MixinTransactions.sol index 20a4a12df..31f7f2847 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/MixinTransactions.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/MixinTransactions.sol @@ -20,12 +20,10 @@ pragma solidity ^0.4.24; import "./libs/LibExchangeErrors.sol"; import "./mixins/MSignatureValidator.sol"; import "./mixins/MTransactions.sol"; -import "./libs/LibExchangeErrors.sol"; import "./libs/LibEIP712.sol"; contract MixinTransactions is LibEIP712, - LibExchangeErrors, MSignatureValidator, MTransactions { @@ -62,6 +60,13 @@ contract MixinTransactions is { 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) @@ -90,7 +95,7 @@ contract MixinTransactions is // Prevent reentrancy require( currentContextAddress == address(0), - REENTRANCY_ILLEGAL + "REENTRANCY_ILLEGAL" ); bytes32 transactionHash = hashEIP712Message(hashZeroExTransaction( @@ -102,7 +107,7 @@ contract MixinTransactions is // Validate transaction has not been executed require( !transactions[transactionHash], - INVALID_TX_HASH + "INVALID_TX_HASH" ); // Transaction always valid if signer is sender of transaction @@ -114,7 +119,7 @@ contract MixinTransactions is signerAddress, signature ), - INVALID_TX_SIGNATURE + "INVALID_TX_SIGNATURE" ); // Set the current transaction signer @@ -125,7 +130,7 @@ contract MixinTransactions is transactions[transactionHash] = true; require( address(this).delegatecall(data), - FAILED_EXECUTION + "FAILED_EXECUTION" ); // Reset current transaction signer diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/MixinWrapperFunctions.sol b/packages/contracts/src/2.0.0/protocol/Exchange/MixinWrapperFunctions.sol index 724f95518..00668ca43 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/MixinWrapperFunctions.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/MixinWrapperFunctions.sol @@ -22,13 +22,11 @@ pragma experimental ABIEncoderV2; import "./libs/LibMath.sol"; import "./libs/LibOrder.sol"; import "./libs/LibFillResults.sol"; -import "./libs/LibExchangeErrors.sol"; import "./mixins/MExchangeCore.sol"; contract MixinWrapperFunctions is LibMath, LibFillResults, - LibExchangeErrors, MExchangeCore { /// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled. @@ -50,7 +48,7 @@ contract MixinWrapperFunctions is ); require( fillResults.takerAssetFilledAmount == takerAssetFillAmount, - COMPLETE_FILL_FAILED + "COMPLETE_FILL_FAILED" ); return fillResults; } @@ -366,14 +364,6 @@ contract MixinWrapperFunctions is signatures[i] ); - // HACK: the proxyId is "popped" from the byte array before a fill is settled - // by subtracting from the length of the array. Since the popped byte is - // still in memory, we can "unpop" it by incrementing the length of the byte array. - assembly { - let len := mload(takerAssetData) - mstore(takerAssetData, add(len, 1)) - } - // Update amounts filled and fees paid by maker and taker addFillResults(totalFillResults, singleFillResults); @@ -467,14 +457,6 @@ contract MixinWrapperFunctions is signatures[i] ); - // HACK: the proxyId is "popped" from the byte array before a fill is settled - // by subtracting from the length of the array. Since the popped byte is - // still in memory, we can "unpop" it by incrementing the length of the byte array. - assembly { - let len := mload(makerAssetData) - mstore(makerAssetData, add(len, 1)) - } - // Update amounts filled and fees paid by maker and taker addFillResults(totalFillResults, singleFillResults); diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IAssetProxyDispatcher.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IAssetProxyDispatcher.sol index 2c331dc34..66f3b5796 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IAssetProxyDispatcher.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IAssetProxyDispatcher.sol @@ -20,22 +20,16 @@ pragma solidity ^0.4.24; contract IAssetProxyDispatcher { - /// @dev Registers an asset proxy to an asset proxy id. - /// An id can only be assigned to a single proxy at a given time. - /// @param assetProxyId Id to register`newAssetProxy` under. - /// @param newAssetProxy Address of new asset proxy to register, or 0x0 to unset assetProxyId. - /// @param oldAssetProxy Existing asset proxy to overwrite, or 0x0 if assetProxyId is currently unused. - function registerAssetProxy( - uint8 assetProxyId, - address newAssetProxy, - address oldAssetProxy - ) + /// @dev Registers an asset proxy to its asset proxy id. + /// Once an asset proxy is registered, it cannot be unregistered. + /// @param assetProxy Address of new asset proxy to register. + function registerAssetProxy(address assetProxy) external; /// @dev Gets an asset proxy. /// @param assetProxyId Id of the asset proxy. /// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered. - function getAssetProxy(uint8 assetProxyId) + function getAssetProxy(bytes4 assetProxyId) external view returns (address); diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IExchange.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchange.sol index 9f21c18d7..9f21c18d7 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IExchange.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchange.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IExchangeCore.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchangeCore.sol index 98222f33f..98222f33f 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IExchangeCore.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IExchangeCore.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IMatchOrders.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IMatchOrders.sol index df009d063..df009d063 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IMatchOrders.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IMatchOrders.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/ISignatureValidator.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ISignatureValidator.sol index 511463309..511463309 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/ISignatureValidator.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ISignatureValidator.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/ITransactions.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ITransactions.sol index a7cab8f55..a7cab8f55 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/ITransactions.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/ITransactions.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IValidator.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IValidator.sol index 0b1796a66..0b1796a66 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IValidator.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IValidator.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IWallet.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWallet.sol index c86a2c057..c86a2c057 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IWallet.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWallet.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IWrapperFunctions.sol b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWrapperFunctions.sol index 84bb683bc..84bb683bc 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/interfaces/IWrapperFunctions.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/interfaces/IWrapperFunctions.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/libs/LibConstants.sol b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibConstants.sol index 4a9452448..488ca956c 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/libs/LibConstants.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibConstants.sol @@ -25,9 +25,6 @@ contract LibConstants { // not constant to make testing easier. bytes public ZRX_ASSET_DATA; - // Proxy Id for ZRX token. - uint8 constant ZRX_PROXY_ID = 1; - // @TODO: Remove when we deploy. constructor (bytes memory zrxAssetData) public diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/libs/LibEIP712.sol b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibEIP712.sol index b983347a4..b983347a4 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/libs/LibEIP712.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibEIP712.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/libs/LibExchangeErrors.sol b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibExchangeErrors.sol index a43f0f927..01aa78a1d 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/libs/LibExchangeErrors.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibExchangeErrors.sol @@ -18,7 +18,10 @@ 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. contract LibExchangeErrors { + /// Order validation errors /// string constant ORDER_UNFILLABLE = "ORDER_UNFILLABLE"; // Order cannot be filled. string constant INVALID_MAKER = "INVALID_MAKER"; // Invalid makerAddress. @@ -51,14 +54,15 @@ contract LibExchangeErrors { string constant FAILED_EXECUTION = "FAILED_EXECUTION"; // Transaction execution failed. /// registerAssetProxy errors /// - string constant ASSET_PROXY_MISMATCH = "ASSET_PROXY_MISMATCH"; // oldAssetProxy proxy does not match currentAssetProxy. - string constant ASSET_PROXY_ID_MISMATCH = "ASSET_PROXY_ID_MISMATCH"; // newAssetProxyId does not match given assetProxyId. + string constant ASSET_PROXY_ALREADY_EXISTS = "ASSET_PROXY_ALREADY_EXISTS"; // AssetProxy with same id already exists. /// dispatchTransferFrom errors /// string constant ASSET_PROXY_DOES_NOT_EXIST = "ASSET_PROXY_DOES_NOT_EXIST"; // No assetProxy registered at given id. + string constant TRANSFER_FAILED = "TRANSFER_FAILED"; // Asset transfer unsuccesful. /// Length validation errors /// string constant LENGTH_GREATER_THAN_0_REQUIRED = "LENGTH_GREATER_THAN_0_REQUIRED"; // Byte array must have a length greater than 0. + string constant LENGTH_GREATER_THAN_3_REQUIRED = "LENGTH_GREATER_THAN_3_REQUIRED"; // Byte array must have a length greater than 3. string constant LENGTH_0_REQUIRED = "LENGTH_0_REQUIRED"; // Byte array must have a length of 0. string constant LENGTH_65_REQUIRED = "LENGTH_65_REQUIRED"; // Byte array must have a length of 65. } diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/libs/LibFillResults.sol b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibFillResults.sol index 63f1b8c87..63f1b8c87 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/libs/LibFillResults.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibFillResults.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/libs/LibMath.sol b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibMath.sol index 233547b9f..bfe2fd33f 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/libs/LibMath.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibMath.sol @@ -23,7 +23,6 @@ import "../../../utils/SafeMath/SafeMath.sol"; contract LibMath is SafeMath { - string constant ROUNDING_ERROR_ON_PARTIAL_AMOUNT = "A rounding error occurred when calculating partial transfer amounts."; /// @dev Calculates partial value given a numerator and denominator. /// @param numerator Numerator. diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/libs/LibOrder.sol b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibOrder.sol index f3f1e9277..954f94f76 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/libs/LibOrder.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/libs/LibOrder.sol @@ -98,6 +98,21 @@ 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) + // )); assembly { // Backup let temp1 := mload(sub(order, 32)) diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/mixins/MAssetProxyDispatcher.sol b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MAssetProxyDispatcher.sol index 788f42c60..5bf59c6ce 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/mixins/MAssetProxyDispatcher.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MAssetProxyDispatcher.sol @@ -26,21 +26,18 @@ contract MAssetProxyDispatcher is { // Logs registration of new asset proxy - event AssetProxySet( - uint8 id, // Id of new registered AssetProxy. - address newAssetProxy, // Address of new registered AssetProxy. - address oldAssetProxy // Address of AssetProxy that was overwritten at given id (or null address). + event AssetProxyRegistered( + bytes4 id, // Id of new registered AssetProxy. + address assetProxy // Address of new registered AssetProxy. ); /// @dev Forwards arguments to assetProxy and calls `transferFrom`. Either succeeds or throws. - /// @param assetData Byte array encoded for the respective asset proxy. - /// @param assetProxyId Id of assetProxy to dispach to. + /// @param assetData Byte array encoded for the asset. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param amount Amount of token to transfer. function dispatchTransferFrom( bytes memory assetData, - uint8 assetProxyId, address from, address to, uint256 amount diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/mixins/MExchangeCore.sol b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MExchangeCore.sol index 6e406e1c4..6e406e1c4 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/mixins/MExchangeCore.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MExchangeCore.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/mixins/MMatchOrders.sol b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MMatchOrders.sol index abe7c3596..abe7c3596 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/mixins/MMatchOrders.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MMatchOrders.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/mixins/MSignatureValidator.sol b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MSignatureValidator.sol index 6cc1d7a10..6cc1d7a10 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/mixins/MSignatureValidator.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MSignatureValidator.sol diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/mixins/MTransactions.sol b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MTransactions.sol index e2f89de01..e2f89de01 100644 --- a/packages/contracts/src/contracts/current/protocol/Exchange/mixins/MTransactions.sol +++ b/packages/contracts/src/2.0.0/protocol/Exchange/mixins/MTransactions.sol diff --git a/packages/contracts/src/contracts/current/test/DummyERC20Token/DummyERC20Token.sol b/packages/contracts/src/2.0.0/test/DummyERC20Token/DummyERC20Token.sol index b2fe2df06..b2fe2df06 100644 --- a/packages/contracts/src/contracts/current/test/DummyERC20Token/DummyERC20Token.sol +++ b/packages/contracts/src/2.0.0/test/DummyERC20Token/DummyERC20Token.sol diff --git a/packages/contracts/src/contracts/current/test/DummyERC721Receiver/DummyERC721Receiver.sol b/packages/contracts/src/2.0.0/test/DummyERC721Receiver/DummyERC721Receiver.sol index c584d0b54..c584d0b54 100644 --- a/packages/contracts/src/contracts/current/test/DummyERC721Receiver/DummyERC721Receiver.sol +++ b/packages/contracts/src/2.0.0/test/DummyERC721Receiver/DummyERC721Receiver.sol diff --git a/packages/contracts/src/contracts/current/test/DummyERC721Token/DummyERC721Token.sol b/packages/contracts/src/2.0.0/test/DummyERC721Token/DummyERC721Token.sol index 5503eb2f2..78ea96447 100644 --- a/packages/contracts/src/contracts/current/test/DummyERC721Token/DummyERC721Token.sol +++ b/packages/contracts/src/2.0.0/test/DummyERC721Token/DummyERC721Token.sol @@ -56,4 +56,20 @@ contract DummyERC721Token is ); _mint(to, tokenId); } + + /** + * @dev Function to burn a token + * @dev Reverts if the given token ID doesn't exist + * @param tokenId uint256 ID of the token to be minted by the msg.sender + */ + function burn(address owner, uint256 tokenId) + public + onlyOwner + { + require( + exists(tokenId), + "Token with tokenId does not exist." + ); + _burn(owner, tokenId); + } } diff --git a/packages/contracts/src/contracts/current/test/ExchangeWrapper/ExchangeWrapper.sol b/packages/contracts/src/2.0.0/test/ExchangeWrapper/ExchangeWrapper.sol index 5baaf6e5a..5baaf6e5a 100644 --- a/packages/contracts/src/contracts/current/test/ExchangeWrapper/ExchangeWrapper.sol +++ b/packages/contracts/src/2.0.0/test/ExchangeWrapper/ExchangeWrapper.sol diff --git a/packages/contracts/src/contracts/current/test/Mintable/Mintable.sol b/packages/contracts/src/2.0.0/test/Mintable/Mintable.sol index a91bfee9e..a91bfee9e 100644 --- a/packages/contracts/src/contracts/current/test/Mintable/Mintable.sol +++ b/packages/contracts/src/2.0.0/test/Mintable/Mintable.sol diff --git a/packages/contracts/src/contracts/current/test/TestAssetProxyDispatcher/TestAssetProxyDispatcher.sol b/packages/contracts/src/2.0.0/test/TestAssetProxyDispatcher/TestAssetProxyDispatcher.sol index d469a07f0..2ae69e0ef 100644 --- a/packages/contracts/src/contracts/current/test/TestAssetProxyDispatcher/TestAssetProxyDispatcher.sol +++ b/packages/contracts/src/2.0.0/test/TestAssetProxyDispatcher/TestAssetProxyDispatcher.sol @@ -24,12 +24,11 @@ import "../../protocol/Exchange/MixinAssetProxyDispatcher.sol"; contract TestAssetProxyDispatcher is MixinAssetProxyDispatcher { function publicDispatchTransferFrom( bytes memory assetData, - uint8 assetProxyId, address from, address to, uint256 amount) public { - dispatchTransferFrom(assetData, assetProxyId, from, to, amount); + dispatchTransferFrom(assetData, from, to, amount); } } diff --git a/packages/contracts/src/contracts/current/test/TestAssetProxyOwner/TestAssetProxyOwner.sol b/packages/contracts/src/2.0.0/test/TestAssetProxyOwner/TestAssetProxyOwner.sol index 2abcd17a0..2abcd17a0 100644 --- a/packages/contracts/src/contracts/current/test/TestAssetProxyOwner/TestAssetProxyOwner.sol +++ b/packages/contracts/src/2.0.0/test/TestAssetProxyOwner/TestAssetProxyOwner.sol diff --git a/packages/contracts/src/contracts/current/test/TestLibBytes/TestLibBytes.sol b/packages/contracts/src/2.0.0/test/TestLibBytes/TestLibBytes.sol index f45faaf36..f45faaf36 100644 --- a/packages/contracts/src/contracts/current/test/TestLibBytes/TestLibBytes.sol +++ b/packages/contracts/src/2.0.0/test/TestLibBytes/TestLibBytes.sol diff --git a/packages/contracts/src/contracts/current/test/TestLibs/TestLibs.sol b/packages/contracts/src/2.0.0/test/TestLibs/TestLibs.sol index 010080703..010080703 100644 --- a/packages/contracts/src/contracts/current/test/TestLibs/TestLibs.sol +++ b/packages/contracts/src/2.0.0/test/TestLibs/TestLibs.sol diff --git a/packages/contracts/src/contracts/current/test/TestSignatureValidator/TestSignatureValidator.sol b/packages/contracts/src/2.0.0/test/TestSignatureValidator/TestSignatureValidator.sol index 0f84678cf..0f84678cf 100644 --- a/packages/contracts/src/contracts/current/test/TestSignatureValidator/TestSignatureValidator.sol +++ b/packages/contracts/src/2.0.0/test/TestSignatureValidator/TestSignatureValidator.sol diff --git a/packages/contracts/src/contracts/current/test/TestValidator/TestValidator.sol b/packages/contracts/src/2.0.0/test/TestValidator/TestValidator.sol index f9271bf7a..f9271bf7a 100644 --- a/packages/contracts/src/contracts/current/test/TestValidator/TestValidator.sol +++ b/packages/contracts/src/2.0.0/test/TestValidator/TestValidator.sol diff --git a/packages/contracts/src/contracts/current/test/TestWallet/TestWallet.sol b/packages/contracts/src/2.0.0/test/TestWallet/TestWallet.sol index 17dee9e9c..17dee9e9c 100644 --- a/packages/contracts/src/contracts/current/test/TestWallet/TestWallet.sol +++ b/packages/contracts/src/2.0.0/test/TestWallet/TestWallet.sol diff --git a/packages/contracts/src/contracts/current/test/Whitelist/Whitelist.sol b/packages/contracts/src/2.0.0/test/Whitelist/Whitelist.sol index d35815474..8b52858b1 100644 --- a/packages/contracts/src/contracts/current/test/Whitelist/Whitelist.sol +++ b/packages/contracts/src/2.0.0/test/Whitelist/Whitelist.sol @@ -23,13 +23,13 @@ import "../../protocol/Exchange/interfaces/IExchange.sol"; import "../../protocol/Exchange/libs/LibOrder.sol"; import "../../utils/Ownable/Ownable.sol"; -contract Whitelist is +contract Whitelist is Ownable { // Revert reasons - string constant MAKER_NOT_WHITELISTED = "Maker address not whitelisted."; - string constant TAKER_NOT_WHITELISTED = "Taker address not whitelisted."; - string constant INVALID_SENDER = "Sender must equal transaction origin."; + 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; @@ -77,7 +77,7 @@ contract Whitelist is public { address takerAddress = msg.sender; - + // This contract must be the entry point for the transaction. require( takerAddress == tx.origin, diff --git a/packages/contracts/src/contracts/current/tokens/ERC20Token/ERC20Token.sol b/packages/contracts/src/2.0.0/tokens/ERC20Token/ERC20Token.sol index f0bcdafef..b6961a6ec 100644 --- a/packages/contracts/src/contracts/current/tokens/ERC20Token/ERC20Token.sol +++ b/packages/contracts/src/2.0.0/tokens/ERC20Token/ERC20Token.sol @@ -23,8 +23,8 @@ import "./IERC20Token.sol"; contract ERC20Token is IERC20Token { - string constant INSUFFICIENT_BALANCE = "Insufficient balance to complete transfer."; - string constant INSUFFICIENT_ALLOWANCE = "Insufficient allowance to complete transfer."; + string constant INSUFFICIENT_BALANCE = "ERC20_INSUFFICIENT_BALANCE"; + string constant INSUFFICIENT_ALLOWANCE = "ERC20_INSUFFICIENT_ALLOWANCE"; string constant OVERFLOW = "Transfer would result in an overflow."; mapping (address => uint256) balances; @@ -97,4 +97,3 @@ contract ERC20Token is IERC20Token { return allowed[_owner][_spender]; } } - diff --git a/packages/contracts/src/contracts/current/tokens/ERC20Token/IERC20Token.sol b/packages/contracts/src/2.0.0/tokens/ERC20Token/IERC20Token.sol index eb879b6a8..eb879b6a8 100644 --- a/packages/contracts/src/contracts/current/tokens/ERC20Token/IERC20Token.sol +++ b/packages/contracts/src/2.0.0/tokens/ERC20Token/IERC20Token.sol diff --git a/packages/contracts/src/contracts/current/tokens/ERC721Token/ERC721Token.sol b/packages/contracts/src/2.0.0/tokens/ERC721Token/ERC721Token.sol index 41ba149e3..41ba149e3 100644 --- a/packages/contracts/src/contracts/current/tokens/ERC721Token/ERC721Token.sol +++ b/packages/contracts/src/2.0.0/tokens/ERC721Token/ERC721Token.sol diff --git a/packages/contracts/src/contracts/current/tokens/ERC721Token/IERC721Receiver.sol b/packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Receiver.sol index b0fff3c90..b0fff3c90 100644 --- a/packages/contracts/src/contracts/current/tokens/ERC721Token/IERC721Receiver.sol +++ b/packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Receiver.sol diff --git a/packages/contracts/src/contracts/current/tokens/ERC721Token/IERC721Token.sol b/packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Token.sol index 345712d67..345712d67 100644 --- a/packages/contracts/src/contracts/current/tokens/ERC721Token/IERC721Token.sol +++ b/packages/contracts/src/2.0.0/tokens/ERC721Token/IERC721Token.sol diff --git a/packages/contracts/src/contracts/current/tokens/UnlimitedAllowanceToken/UnlimitedAllowanceToken.sol b/packages/contracts/src/2.0.0/tokens/UnlimitedAllowanceToken/UnlimitedAllowanceToken.sol index f62602ab3..f62602ab3 100644 --- a/packages/contracts/src/contracts/current/tokens/UnlimitedAllowanceToken/UnlimitedAllowanceToken.sol +++ b/packages/contracts/src/2.0.0/tokens/UnlimitedAllowanceToken/UnlimitedAllowanceToken.sol diff --git a/packages/contracts/src/contracts/current/tokens/WETH9/WETH9.sol b/packages/contracts/src/2.0.0/tokens/WETH9/WETH9.sol index 733ca414b..733ca414b 100644 --- a/packages/contracts/src/contracts/current/tokens/WETH9/WETH9.sol +++ b/packages/contracts/src/2.0.0/tokens/WETH9/WETH9.sol diff --git a/packages/contracts/src/contracts/current/tokens/ZRXToken/ZRXToken.sol b/packages/contracts/src/2.0.0/tokens/ZRXToken/ZRXToken.sol index 2d8e74f2c..2e5b61e0b 100644 --- a/packages/contracts/src/contracts/current/tokens/ZRXToken/ZRXToken.sol +++ b/packages/contracts/src/2.0.0/tokens/ZRXToken/ZRXToken.sol @@ -18,7 +18,7 @@ pragma solidity ^0.4.11; -import { UnlimitedAllowanceToken_v1 as UnlimitedAllowanceToken } from "../../../previous/UnlimitedAllowanceToken/UnlimitedAllowanceToken_v1.sol"; +import { UnlimitedAllowanceToken_v1 as UnlimitedAllowanceToken } from "../../../1.0.0/UnlimitedAllowanceToken/UnlimitedAllowanceToken_v1.sol"; contract ZRXToken is UnlimitedAllowanceToken { diff --git a/packages/contracts/src/contracts/current/utils/LibBytes/LibBytes.sol b/packages/contracts/src/2.0.0/utils/LibBytes/LibBytes.sol index e4cbf318b..78b1ddf7c 100644 --- a/packages/contracts/src/contracts/current/utils/LibBytes/LibBytes.sol +++ b/packages/contracts/src/2.0.0/utils/LibBytes/LibBytes.sol @@ -19,17 +19,8 @@ pragma solidity ^0.4.24; library LibBytes { - using LibBytes for bytes; - // Revert reasons - string constant GREATER_THAN_ZERO_LENGTH_REQUIRED = "GREATER_THAN_ZERO_LENGTH_REQUIRED"; - string constant GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED = "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"; - string constant GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED = "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"; - string constant GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED = "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"; - string constant GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED = "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"; - string constant GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED = "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED"; - string constant FROM_LESS_THAN_TO_REQUIRED = "FROM_LESS_THAN_TO_REQUIRED"; - string constant TO_LESS_THAN_LENGTH_REQUIRED = "TO_LESS_THAN_LENGTH_REQUIRED"; + using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. @@ -176,8 +167,14 @@ library LibBytes { pure returns (bytes memory result) { - require(from <= to, FROM_LESS_THAN_TO_REQUIRED); - require(to < b.length, TO_LESS_THAN_LENGTH_REQUIRED); + require( + from <= to, + "FROM_LESS_THAN_TO_REQUIRED" + ); + require( + to < b.length, + "TO_LESS_THAN_LENGTH_REQUIRED" + ); // Create a new bytes structure and copy contents result = new bytes(to - from); @@ -199,8 +196,14 @@ library LibBytes { pure returns (bytes memory result) { - require(from <= to, FROM_LESS_THAN_TO_REQUIRED); - require(to < b.length, TO_LESS_THAN_LENGTH_REQUIRED); + require( + from <= to, + "FROM_LESS_THAN_TO_REQUIRED" + ); + require( + to < b.length, + "TO_LESS_THAN_LENGTH_REQUIRED" + ); // Create a new bytes structure around [from, to) in-place. assembly { @@ -220,7 +223,7 @@ library LibBytes { { require( b.length > 0, - GREATER_THAN_ZERO_LENGTH_REQUIRED + "GREATER_THAN_ZERO_LENGTH_REQUIRED" ); // Store last byte. @@ -244,7 +247,7 @@ library LibBytes { { require( b.length >= 20, - GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED + "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Store last 20 bytes. @@ -290,7 +293,7 @@ library LibBytes { { require( b.length >= index + 20, // 20 is length of address - GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED + "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: @@ -322,7 +325,7 @@ library LibBytes { { require( b.length >= index + 20, // 20 is length of address - GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED + "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: @@ -365,7 +368,7 @@ library LibBytes { { require( b.length >= index + 32, - GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED + "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter @@ -392,7 +395,7 @@ library LibBytes { { require( b.length >= index + 32, - GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED + "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter @@ -447,7 +450,7 @@ library LibBytes { { require( b.length >= index + 4, - GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED + "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED" ); assembly { result := mload(add(b, 32)) @@ -459,6 +462,8 @@ library LibBytes { } /// @dev Reads nested bytes from a specific position. + /// @dev NOTE: the returned value overlaps with the input value. + /// Both should be treated as immutable. /// @param b Byte array containing nested bytes. /// @param index Index of nested bytes. /// @return result Nested bytes. @@ -478,17 +483,13 @@ library LibBytes { // length of nested bytes require( b.length >= index + nestedBytesLength, - GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED + "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); - - // Allocate memory and copy value to result - result = new bytes(nestedBytesLength); - memCopy( - result.contentAddress(), - b.contentAddress() + index, - nestedBytesLength - ); - + + // Return a pointer to the byte array as it exists inside `b` + assembly { + result := add(b, index) + } return result; } @@ -508,7 +509,7 @@ library LibBytes { // length of input require( b.length >= index + 32 /* 32 bytes to store length */ + input.length, - GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED + "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); // Copy <input> into <b> @@ -533,7 +534,7 @@ library LibBytes { // Dest length must be >= source length, or some bytes would not be copied. require( dest.length >= sourceLen, - GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED + "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED" ); memCopy( dest.contentAddress(), diff --git a/packages/contracts/src/contracts/current/utils/Ownable/IOwnable.sol b/packages/contracts/src/2.0.0/utils/Ownable/IOwnable.sol index e77680903..e77680903 100644 --- a/packages/contracts/src/contracts/current/utils/Ownable/IOwnable.sol +++ b/packages/contracts/src/2.0.0/utils/Ownable/IOwnable.sol diff --git a/packages/contracts/src/contracts/current/utils/Ownable/Ownable.sol b/packages/contracts/src/2.0.0/utils/Ownable/Ownable.sol index 99b93d0d2..6f5761cc7 100644 --- a/packages/contracts/src/contracts/current/utils/Ownable/Ownable.sol +++ b/packages/contracts/src/2.0.0/utils/Ownable/Ownable.sol @@ -13,9 +13,6 @@ import "./IOwnable.sol"; contract Ownable is IOwnable { address public owner; - // Revert reasons - string constant ONLY_CONTRACT_OWNER = "ONLY_CONTRACT_OWNER"; - constructor () public { @@ -25,7 +22,7 @@ contract Ownable is IOwnable { modifier onlyOwner() { require( msg.sender == owner, - ONLY_CONTRACT_OWNER + "ONLY_CONTRACT_OWNER" ); _; } diff --git a/packages/contracts/src/contracts/current/utils/SafeMath/SafeMath.sol b/packages/contracts/src/2.0.0/utils/SafeMath/SafeMath.sol index e137f6ca5..e137f6ca5 100644 --- a/packages/contracts/src/contracts/current/utils/SafeMath/SafeMath.sol +++ b/packages/contracts/src/2.0.0/utils/SafeMath/SafeMath.sol diff --git a/packages/contracts/src/contracts/current/protocol/AssetProxy/ERC20Proxy.sol b/packages/contracts/src/contracts/current/protocol/AssetProxy/ERC20Proxy.sol deleted file mode 100644 index 7ca823d1f..000000000 --- a/packages/contracts/src/contracts/current/protocol/AssetProxy/ERC20Proxy.sol +++ /dev/null @@ -1,44 +0,0 @@ -/* - - 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 "./MixinAssetProxy.sol"; -import "./MixinAuthorizable.sol"; -import "./MixinERC20Transfer.sol"; - -contract ERC20Proxy is - MixinAssetProxy, - MixinAuthorizable, - MixinERC20Transfer -{ - // Id of this proxy. - uint8 constant PROXY_ID = 1; - - /// @dev Gets the proxy id associated with the proxy address. - /// @return Proxy id. - function getProxyId() - external - view - returns (uint8) - { - return PROXY_ID; - } -} diff --git a/packages/contracts/src/contracts/current/protocol/AssetProxy/ERC721Proxy.sol b/packages/contracts/src/contracts/current/protocol/AssetProxy/ERC721Proxy.sol deleted file mode 100644 index 7ff25aea3..000000000 --- a/packages/contracts/src/contracts/current/protocol/AssetProxy/ERC721Proxy.sol +++ /dev/null @@ -1,44 +0,0 @@ -/* - - 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 "./MixinAssetProxy.sol"; -import "./MixinAuthorizable.sol"; -import "./MixinERC721Transfer.sol"; - -contract ERC721Proxy is - MixinAssetProxy, - MixinAuthorizable, - MixinERC721Transfer -{ - // Id of this proxy. - uint8 constant PROXY_ID = 2; - - /// @dev Gets the proxy id associated with the proxy address. - /// @return Proxy id. - function getProxyId() - external - view - returns (uint8) - { - return PROXY_ID; - } -} diff --git a/packages/contracts/src/contracts/current/protocol/AssetProxy/MixinAssetProxy.sol b/packages/contracts/src/contracts/current/protocol/AssetProxy/MixinAssetProxy.sol deleted file mode 100644 index 9032658e7..000000000 --- a/packages/contracts/src/contracts/current/protocol/AssetProxy/MixinAssetProxy.sol +++ /dev/null @@ -1,75 +0,0 @@ -/* - - 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 "./mixins/MAuthorizable.sol"; -import "./mixins/MAssetProxy.sol"; - -contract MixinAssetProxy is - MAuthorizable, - MAssetProxy -{ - - /// @dev Transfers assets. Either succeeds or throws. - /// @param assetData Encoded byte array. - /// @param from Address to transfer asset from. - /// @param to Address to transfer asset to. - /// @param amount Amount of asset to transfer. - function transferFrom( - bytes assetData, - address from, - address to, - uint256 amount - ) - external - onlyAuthorized - { - transferFromInternal( - assetData, - from, - to, - amount - ); - } - - /// @dev Makes multiple transfers of assets. Either succeeds or throws. - /// @param assetData Array of byte arrays encoded for the respective asset proxy. - /// @param from Array of addresses to transfer assets from. - /// @param to Array of addresses to transfer assets to. - /// @param amounts Array of amounts of assets to transfer. - function batchTransferFrom( - bytes[] memory assetData, - address[] memory from, - address[] memory to, - uint256[] memory amounts - ) - public - onlyAuthorized - { - for (uint256 i = 0; i < assetData.length; i++) { - transferFromInternal( - assetData[i], - from[i], - to[i], - amounts[i] - ); - } - } -} diff --git a/packages/contracts/src/contracts/current/protocol/AssetProxy/MixinERC20Transfer.sol b/packages/contracts/src/contracts/current/protocol/AssetProxy/MixinERC20Transfer.sol deleted file mode 100644 index 0e7f3fc89..000000000 --- a/packages/contracts/src/contracts/current/protocol/AssetProxy/MixinERC20Transfer.sol +++ /dev/null @@ -1,82 +0,0 @@ -/* - - 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 "../../tokens/ERC20Token/IERC20Token.sol"; -import "./libs/LibTransferErrors.sol"; - -contract MixinERC20Transfer is - LibTransferErrors -{ - using LibBytes for bytes; - - /// @dev Internal version of `transferFrom`. - /// @param assetData Encoded byte array. - /// @param from Address to transfer asset from. - /// @param to Address to transfer asset to. - /// @param amount Amount of asset to transfer. - function transferFromInternal( - bytes memory assetData, - address from, - address to, - uint256 amount - ) - internal - { - // Decode asset data. - address token = assetData.readAddress(0); - - // Transfer tokens. - // We do a raw call so we can check the success separate - // from the return data. - bool success = token.call(abi.encodeWithSelector( - IERC20Token(token).transferFrom.selector, - from, - 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 - ); - } -} diff --git a/packages/contracts/src/contracts/current/protocol/AssetProxy/MixinERC721Transfer.sol b/packages/contracts/src/contracts/current/protocol/AssetProxy/MixinERC721Transfer.sol deleted file mode 100644 index 944068bbb..000000000 --- a/packages/contracts/src/contracts/current/protocol/AssetProxy/MixinERC721Transfer.sol +++ /dev/null @@ -1,94 +0,0 @@ -/* - - 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 "../../tokens/ERC721Token/ERC721Token.sol"; -import "./libs/LibTransferErrors.sol"; - -contract MixinERC721Transfer is - LibTransferErrors -{ - using LibBytes for bytes; - - /// @dev Internal version of `transferFrom`. - /// @param assetData Encoded byte array. - /// @param from Address to transfer asset from. - /// @param to Address to transfer asset to. - /// @param amount Amount of asset to transfer. - function transferFromInternal( - bytes memory assetData, - address from, - address to, - uint256 amount - ) - internal - { - // There exists only 1 of each token. - require( - amount == 1, - INVALID_AMOUNT - ); - - // Decode asset data. - ( - address token, - uint256 tokenId, - bytes memory receiverData - ) = decodeERC721AssetData(assetData); - - ERC721Token(token).safeTransferFrom( - from, - to, - tokenId, - receiverData - ); - } - - /// @dev Decodes ERC721 Asset data. - /// @param assetData Encoded byte array. - /// @return proxyId Intended ERC721 proxy id. - /// @return token ERC721 token address. - /// @return tokenId ERC721 token id. - /// @return receiverData Additional data with no specific format, which - /// is passed to the receiving contract's onERC721Received. - function decodeERC721AssetData(bytes memory assetData) - internal - pure - returns ( - address token, - uint256 tokenId, - bytes memory receiverData - ) - { - // Decode asset data. - token = assetData.readAddress(0); - tokenId = assetData.readUint256(20); - if (assetData.length > 52) { - receiverData = assetData.readBytesWithLength(52); - } - - return ( - token, - tokenId, - receiverData - ); - } -} diff --git a/packages/contracts/src/contracts/current/protocol/AssetProxy/mixins/MAssetProxy.sol b/packages/contracts/src/contracts/current/protocol/AssetProxy/mixins/MAssetProxy.sol deleted file mode 100644 index a52cb56f9..000000000 --- a/packages/contracts/src/contracts/current/protocol/AssetProxy/mixins/MAssetProxy.sol +++ /dev/null @@ -1,40 +0,0 @@ -/* - - 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 "../interfaces/IAssetProxy.sol"; - -contract MAssetProxy is - IAssetProxy -{ - - /// @dev Internal version of `transferFrom`. - /// @param assetData Encoded byte array. - /// @param from Address to transfer asset from. - /// @param to Address to transfer asset to. - /// @param amount Amount of asset to transfer. - function transferFromInternal( - bytes memory assetData, - address from, - address to, - uint256 amount - ) - internal; -} diff --git a/packages/contracts/src/contracts/current/protocol/Exchange/MixinAssetProxyDispatcher.sol b/packages/contracts/src/contracts/current/protocol/Exchange/MixinAssetProxyDispatcher.sol deleted file mode 100644 index b8d6c0722..000000000 --- a/packages/contracts/src/contracts/current/protocol/Exchange/MixinAssetProxyDispatcher.sol +++ /dev/null @@ -1,118 +0,0 @@ -/* - - 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/Ownable/Ownable.sol"; -import "./libs/LibExchangeErrors.sol"; -import "./mixins/MAssetProxyDispatcher.sol"; -import "../AssetProxy/interfaces/IAssetProxy.sol"; - -contract MixinAssetProxyDispatcher is - Ownable, - LibExchangeErrors, - MAssetProxyDispatcher -{ - // Mapping from Asset Proxy Id's to their respective Asset Proxy - mapping (uint8 => IAssetProxy) public assetProxies; - - /// @dev Registers an asset proxy to an asset proxy id. - /// An id can only be assigned to a single proxy at a given time. - /// @param assetProxyId Id to register`newAssetProxy` under. - /// @param newAssetProxy Address of new asset proxy to register, or 0x0 to unset assetProxyId. - /// @param oldAssetProxy Existing asset proxy to overwrite, or 0x0 if assetProxyId is currently unused. - function registerAssetProxy( - uint8 assetProxyId, - address newAssetProxy, - address oldAssetProxy - ) - external - onlyOwner - { - // Ensure the existing asset proxy is not unintentionally overwritten - address currentAssetProxy = assetProxies[assetProxyId]; - require( - oldAssetProxy == currentAssetProxy, - ASSET_PROXY_MISMATCH - ); - - IAssetProxy assetProxy = IAssetProxy(newAssetProxy); - - // Ensure that the id of newAssetProxy matches the passed in assetProxyId, unless it is being reset to 0. - if (newAssetProxy != address(0)) { - uint8 newAssetProxyId = assetProxy.getProxyId(); - require( - newAssetProxyId == assetProxyId, - ASSET_PROXY_ID_MISMATCH - ); - } - - // Add asset proxy and log registration. - assetProxies[assetProxyId] = assetProxy; - emit AssetProxySet( - assetProxyId, - newAssetProxy, - oldAssetProxy - ); - } - - /// @dev Gets an asset proxy. - /// @param assetProxyId Id of the asset proxy. - /// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered. - function getAssetProxy(uint8 assetProxyId) - external - view - returns (address) - { - return assetProxies[assetProxyId]; - } - - /// @dev Forwards arguments to assetProxy and calls `transferFrom`. Either succeeds or throws. - /// @param assetData Byte array encoded for the respective asset proxy. - /// @param assetProxyId Id of assetProxy to dispach to. - /// @param from Address to transfer token from. - /// @param to Address to transfer token to. - /// @param amount Amount of token to transfer. - function dispatchTransferFrom( - bytes memory assetData, - uint8 assetProxyId, - address from, - address to, - uint256 amount - ) - internal - { - // Do nothing if no amount should be transferred. - if (amount > 0) { - // Lookup assetProxy - IAssetProxy assetProxy = assetProxies[assetProxyId]; - // Ensure that assetProxy exists - require( - assetProxy != address(0), - ASSET_PROXY_DOES_NOT_EXIST - ); - // transferFrom will either succeed or throw. - assetProxy.transferFrom( - assetData, - from, - to, - amount - ); - } - } -} diff --git a/packages/contracts/src/contracts/current/test/TestAssetDataDecoders/TestAssetDataDecoders.sol b/packages/contracts/src/contracts/current/test/TestAssetDataDecoders/TestAssetDataDecoders.sol deleted file mode 100644 index 5987291d2..000000000 --- a/packages/contracts/src/contracts/current/test/TestAssetDataDecoders/TestAssetDataDecoders.sol +++ /dev/null @@ -1,56 +0,0 @@ -/* - - 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/AssetProxy/ERC20Proxy.sol"; -import "../../protocol/AssetProxy/ERC721Proxy.sol"; - -contract TestAssetDataDecoders is - ERC721Proxy -{ - /// @dev Decodes ERC721 Asset data. - /// @param assetData Encoded byte array. - /// @return proxyId Intended ERC721 proxy id. - /// @return token ERC721 token address. - /// @return tokenId ERC721 token id. - /// @return receiverData Additional data with no specific format, which - /// is passed to the receiving contract's onERC721Received. - function publicDecodeERC721Data(bytes memory assetData) - public - pure - returns ( - address token, - uint256 tokenId, - bytes memory receiverData - ) - { - ( - token, - tokenId, - receiverData - ) = decodeERC721AssetData(assetData); - - return ( - token, - tokenId, - receiverData - ); - } -} diff --git a/packages/contracts/src/utils/address_utils.ts b/packages/contracts/src/utils/address_utils.ts deleted file mode 100644 index a9fb6921a..000000000 --- a/packages/contracts/src/utils/address_utils.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { crypto, generatePseudoRandomSalt } from '@0xproject/order-utils'; - -export const addressUtils = { - generatePseudoRandomAddress(): string { - const randomBigNum = generatePseudoRandomSalt(); - const randomBuff = crypto.solSHA3([randomBigNum]); - const randomAddress = `0x${randomBuff.slice(0, 20).toString('hex')}`; - return randomAddress; - }, -}; diff --git a/packages/contracts/src/utils/artifacts.ts b/packages/contracts/src/utils/artifacts.ts deleted file mode 100644 index a46bab9ae..000000000 --- a/packages/contracts/src/utils/artifacts.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { ContractArtifact } from '@0xproject/sol-compiler'; - -import * as AssetProxyOwner from '../artifacts/AssetProxyOwner.json'; -import * as DummyERC20Token from '../artifacts/DummyERC20Token.json'; -import * as DummyERC721Receiver from '../artifacts/DummyERC721Receiver.json'; -import * as DummyERC721Token from '../artifacts/DummyERC721Token.json'; -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 MixinAuthorizable from '../artifacts/MixinAuthorizable.json'; -import * as MultiSigWallet from '../artifacts/MultiSigWallet.json'; -import * as MultiSigWalletWithTimeLock from '../artifacts/MultiSigWalletWithTimeLock.json'; -import * as TestAssetDataDecoders from '../artifacts/TestAssetDataDecoders.json'; -import * as TestAssetProxyDispatcher from '../artifacts/TestAssetProxyDispatcher.json'; -import * as TestAssetProxyOwner from '../artifacts/TestAssetProxyOwner.json'; -import * as TestLibBytes from '../artifacts/TestLibBytes.json'; -import * as TestLibs from '../artifacts/TestLibs.json'; -import * as TestSignatureValidator from '../artifacts/TestSignatureValidator.json'; -import * as TestValidator from '../artifacts/TestValidator.json'; -import * as TestWallet from '../artifacts/TestWallet.json'; -import * as TokenRegistry from '../artifacts/TokenRegistry.json'; -import * as EtherToken from '../artifacts/WETH9.json'; -import * as Whitelist from '../artifacts/Whitelist.json'; -import * as ZRX from '../artifacts/ZRXToken.json'; - -export const artifacts = { - AssetProxyOwner: (AssetProxyOwner as any) as ContractArtifact, - DummyERC20Token: (DummyERC20Token as any) as ContractArtifact, - DummyERC721Receiver: (DummyERC721Receiver as any) as ContractArtifact, - DummyERC721Token: (DummyERC721Token as any) as ContractArtifact, - ERC20Proxy: (ERC20Proxy as any) as ContractArtifact, - ERC721Proxy: (ERC721Proxy as any) as ContractArtifact, - Exchange: (Exchange as any) as ContractArtifact, - ExchangeWrapper: (ExchangeWrapper as any) as ContractArtifact, - EtherToken: (EtherToken as any) as ContractArtifact, - MixinAuthorizable: (MixinAuthorizable as any) as ContractArtifact, - MultiSigWallet: (MultiSigWallet as any) as ContractArtifact, - MultiSigWalletWithTimeLock: (MultiSigWalletWithTimeLock as any) as ContractArtifact, - TestAssetProxyOwner: (TestAssetProxyOwner as any) as ContractArtifact, - TestAssetProxyDispatcher: (TestAssetProxyDispatcher as any) as ContractArtifact, - TestAssetDataDecoders: (TestAssetDataDecoders as any) as ContractArtifact, - TestLibBytes: (TestLibBytes as any) as ContractArtifact, - TestLibs: (TestLibs as any) as ContractArtifact, - TestSignatureValidator: (TestSignatureValidator as any) as ContractArtifact, - TestValidator: (TestValidator as any) as ContractArtifact, - TestWallet: (TestWallet as any) as ContractArtifact, - TokenRegistry: (TokenRegistry as any) as ContractArtifact, - Whitelist: (Whitelist as any) as ContractArtifact, - ZRX: (ZRX as any) as ContractArtifact, -}; diff --git a/packages/contracts/src/utils/assertions.ts b/packages/contracts/src/utils/assertions.ts deleted file mode 100644 index 615e648f3..000000000 --- a/packages/contracts/src/utils/assertions.ts +++ /dev/null @@ -1,63 +0,0 @@ -import * as chai from 'chai'; -import * as _ from 'lodash'; - -import { constants } from './constants'; - -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`, - ); - }); -} - -/** - * Rejects if the given Promise does not reject with an error indicating - * insufficient funds. - * @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 expectInsufficientFundsAsync<T>(p: Promise<T>): PromiseLike<void> { - return _expectEitherErrorAsync(p, 'insufficient funds', "sender doesn't have enough funds"); -} - -/** - * 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. - * @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); -} - -/** - * 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'); -} - -/** - * 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 - * @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'); -} diff --git a/packages/contracts/src/utils/chai_setup.ts b/packages/contracts/src/utils/chai_setup.ts deleted file mode 100644 index 1a8733093..000000000 --- a/packages/contracts/src/utils/chai_setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -import * as chai from 'chai'; -import chaiAsPromised = require('chai-as-promised'); -import ChaiBigNumber = require('chai-bignumber'); -import * as dirtyChai from 'dirty-chai'; - -export const chaiSetup = { - configure(): void { - chai.config.includeStack = true; - chai.use(ChaiBigNumber()); - chai.use(dirtyChai); - chai.use(chaiAsPromised); - }, -}; diff --git a/packages/contracts/src/utils/constants.ts b/packages/contracts/src/utils/constants.ts deleted file mode 100644 index f21b8c7a0..000000000 --- a/packages/contracts/src/utils/constants.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { BigNumber } from '@0xproject/utils'; -import { Web3Wrapper } from '@0xproject/web3-wrapper'; -import * as ethUtil from 'ethereumjs-util'; -import * as _ from 'lodash'; - -const TESTRPC_PRIVATE_KEYS_STRINGS = [ - '0xf2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d', - '0x5d862464fe9303452126c8bc94274b8c5f9874cbd219789b3eb2128075a76f72', - '0xdf02719c4df8b9b8ac7f551fcb5d9ef48fa27eef7a66453879f4d8fdc6e78fb1', - '0xff12e391b79415e941a94de3bf3a9aee577aed0731e297d5cfa0b8a1e02fa1d0', - '0x752dd9cf65e68cfaba7d60225cbdbc1f4729dd5e5507def72815ed0d8abc6249', - '0xefb595a0178eb79a8df953f87c5148402a224cdf725e88c0146727c6aceadccd', - '0x83c6d2cc5ddcf9711a6d59b417dc20eb48afd58d45290099e5987e3d768f328f', - '0xbb2d3f7c9583780a7d3904a2f55d792707c345f21de1bacb2d389934d82796b2', - '0xb2fd4d29c1390b71b8795ae81196bfd60293adf99f9d32a0aff06288fcdac55f', - '0x23cb7121166b9a2f93ae0b7c05bde02eae50d64449b2cbb42bc84e9d38d6cc89', -]; - -export const constants = { - INVALID_OPCODE: 'invalid opcode', - REVERT: 'revert', - LIB_BYTES_GREATER_THAN_ZERO_LENGTH_REQUIRED: 'GREATER_THAN_ZERO_LENGTH_REQUIRED', - LIB_BYTES_GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED: 'GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED', - LIB_BYTES_GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED: 'GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED', - LIB_BYTES_GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED: 'GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED', - LIB_BYTES_GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED: 'GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED', - LIB_BYTES_GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED: 'GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED', - ERC20_INSUFFICIENT_BALANCE: 'Insufficient balance to complete transfer.', - ERC20_INSUFFICIENT_ALLOWANCE: 'Insufficient allowance to complete transfer.', - EXCHANGE_LENGTH_GREATER_THAN_0_REQUIRED: 'LENGTH_GREATER_THAN_0_REQUIRED', - EXCHANGE_SIGNATURE_UNSUPPORTED: 'SIGNATURE_UNSUPPORTED', - EXCHANGE_SIGNATURE_ILLEGAL: 'SIGNATURE_ILLEGAL', - EXCHANGE_LENGTH_0_REQUIRED: 'LENGTH_0_REQUIRED', - EXCHANGE_LENGTH_65_REQUIRED: 'LENGTH_65_REQUIRED', - 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_TOKEN_TRANSFERFROM_GAS: 80000, - MAX_TOKEN_APPROVE_GAS: 60000, - DUMMY_TOKEN_NAME: '', - DUMMY_TOKEN_SYMBOL: '', - DUMMY_TOKEN_DECIMALS: new BigNumber(18), - DUMMY_TOKEN_TOTAL_SUPPLY: new BigNumber(0), - NULL_BYTES: '0x', - NUM_DUMMY_ERC20_TO_DEPLOY: 3, - NUM_DUMMY_ERC721_TO_DEPLOY: 1, - NUM_ERC721_TOKENS_TO_MINT: 2, - NULL_ADDRESS: '0x0000000000000000000000000000000000000000', - UNLIMITED_ALLOWANCE_IN_BASE_UNITS: new BigNumber(2).pow(256).minus(1), - TESTRPC_PRIVATE_KEYS: _.map(TESTRPC_PRIVATE_KEYS_STRINGS, privateKeyString => ethUtil.toBuffer(privateKeyString)), - INITIAL_ERC20_BALANCE: Web3Wrapper.toBaseUnitAmount(new BigNumber(10000), 18), - INITIAL_ERC20_ALLOWANCE: Web3Wrapper.toBaseUnitAmount(new BigNumber(10000), 18), - STATIC_ORDER_PARAMS: { - makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(100), 18), - takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(200), 18), - makerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(1), 18), - takerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(1), 18), - }, -}; diff --git a/packages/contracts/src/utils/coverage.ts b/packages/contracts/src/utils/coverage.ts deleted file mode 100644 index de29a3ecc..000000000 --- a/packages/contracts/src/utils/coverage.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { devConstants } from '@0xproject/dev-utils'; -import { CoverageSubprovider, SolCompilerArtifactAdapter } from '@0xproject/sol-cov'; -import * as _ from 'lodash'; - -let coverageSubprovider: CoverageSubprovider; - -export const coverage = { - getCoverageSubproviderSingleton(): CoverageSubprovider { - if (_.isUndefined(coverageSubprovider)) { - coverageSubprovider = coverage._getCoverageSubprovider(); - } - return coverageSubprovider; - }, - _getCoverageSubprovider(): CoverageSubprovider { - const defaultFromAddress = devConstants.TESTRPC_FIRST_ADDRESS; - const solCompilerArtifactAdapter = new SolCompilerArtifactAdapter(); - const isVerbose = true; - const subprovider = new CoverageSubprovider(solCompilerArtifactAdapter, defaultFromAddress, isVerbose); - return subprovider; - }, -}; diff --git a/packages/contracts/src/utils/erc20_wrapper.ts b/packages/contracts/src/utils/erc20_wrapper.ts deleted file mode 100644 index 91c9d50b7..000000000 --- a/packages/contracts/src/utils/erc20_wrapper.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { BigNumber } from '@0xproject/utils'; -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 { artifacts } from './artifacts'; -import { constants } from './constants'; -import { ERC20BalancesByOwner } from './types'; -import { txDefaults } from './web3_wrapper'; - -export class ERC20Wrapper { - private _tokenOwnerAddresses: string[]; - private _contractOwnerAddress: string; - private _web3Wrapper: Web3Wrapper; - private _provider: Provider; - private _dummyTokenContracts: DummyERC20TokenContract[]; - private _proxyContract?: ERC20ProxyContract; - constructor(provider: Provider, tokenOwnerAddresses: string[], contractOwnerAddress: string) { - this._dummyTokenContracts = []; - this._web3Wrapper = new Web3Wrapper(provider); - this._provider = provider; - this._tokenOwnerAddresses = tokenOwnerAddresses; - this._contractOwnerAddress = contractOwnerAddress; - } - public async deployDummyTokensAsync(): Promise<DummyERC20TokenContract[]> { - for (let i = 0; i < constants.NUM_DUMMY_ERC20_TO_DEPLOY; i++) { - this._dummyTokenContracts.push( - await DummyERC20TokenContract.deployFrom0xArtifactAsync( - artifacts.DummyERC20Token, - this._provider, - txDefaults, - constants.DUMMY_TOKEN_NAME, - constants.DUMMY_TOKEN_SYMBOL, - constants.DUMMY_TOKEN_DECIMALS, - constants.DUMMY_TOKEN_TOTAL_SUPPLY, - ), - ); - } - return this._dummyTokenContracts; - } - public async deployProxyAsync(): Promise<ERC20ProxyContract> { - this._proxyContract = await ERC20ProxyContract.deployFrom0xArtifactAsync( - artifacts.ERC20Proxy, - this._provider, - txDefaults, - ); - return this._proxyContract; - } - public async setBalancesAndAllowancesAsync(): Promise<void> { - this._validateDummyTokenContractsExistOrThrow(); - this._validateProxyContractExistsOrThrow(); - for (const dummyTokenContract of this._dummyTokenContracts) { - for (const tokenOwnerAddress of this._tokenOwnerAddresses) { - await this._web3Wrapper.awaitTransactionSuccessAsync( - await dummyTokenContract.setBalance.sendTransactionAsync( - tokenOwnerAddress, - constants.INITIAL_ERC20_BALANCE, - { from: this._contractOwnerAddress }, - ), - constants.AWAIT_TRANSACTION_MINED_MS, - ); - await this._web3Wrapper.awaitTransactionSuccessAsync( - await dummyTokenContract.approve.sendTransactionAsync( - (this._proxyContract as ERC20ProxyContract).address, - constants.INITIAL_ERC20_ALLOWANCE, - { from: tokenOwnerAddress }, - ), - constants.AWAIT_TRANSACTION_MINED_MS, - ); - } - } - } - public async getBalancesAsync(): Promise<ERC20BalancesByOwner> { - this._validateDummyTokenContractsExistOrThrow(); - const balancesByOwner: ERC20BalancesByOwner = {}; - const balances: BigNumber[] = []; - const balanceInfo: Array<{ tokenOwnerAddress: string; tokenAddress: string }> = []; - for (const dummyTokenContract of this._dummyTokenContracts) { - for (const tokenOwnerAddress of this._tokenOwnerAddresses) { - balances.push(await dummyTokenContract.balanceOf.callAsync(tokenOwnerAddress)); - balanceInfo.push({ - tokenOwnerAddress, - tokenAddress: dummyTokenContract.address, - }); - } - } - _.forEach(balances, (balance, balanceIndex) => { - const tokenAddress = balanceInfo[balanceIndex].tokenAddress; - const tokenOwnerAddress = balanceInfo[balanceIndex].tokenOwnerAddress; - if (_.isUndefined(balancesByOwner[tokenOwnerAddress])) { - balancesByOwner[tokenOwnerAddress] = {}; - } - const wrappedBalance = new BigNumber(balance); - balancesByOwner[tokenOwnerAddress][tokenAddress] = wrappedBalance; - }); - return balancesByOwner; - } - public getTokenOwnerAddresses(): string[] { - return this._tokenOwnerAddresses; - } - public getTokenAddresses(): string[] { - const tokenAddresses = _.map(this._dummyTokenContracts, dummyTokenContract => dummyTokenContract.address); - return tokenAddresses; - } - private _validateDummyTokenContractsExistOrThrow(): void { - if (_.isUndefined(this._dummyTokenContracts)) { - throw new Error('Dummy ERC20 tokens not yet deployed, please call "deployDummyTokensAsync"'); - } - } - private _validateProxyContractExistsOrThrow(): void { - if (_.isUndefined(this._proxyContract)) { - throw new Error('ERC20 proxy contract not yet deployed, please call "deployProxyAsync"'); - } - } -} diff --git a/packages/contracts/src/utils/erc721_wrapper.ts b/packages/contracts/src/utils/erc721_wrapper.ts deleted file mode 100644 index b20d9acd2..000000000 --- a/packages/contracts/src/utils/erc721_wrapper.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { generatePseudoRandomSalt } from '@0xproject/order-utils'; -import { BigNumber } from '@0xproject/utils'; -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 { artifacts } from './artifacts'; -import { constants } from './constants'; -import { ERC721TokenIdsByOwner } from './types'; -import { txDefaults } from './web3_wrapper'; - -export class ERC721Wrapper { - private _tokenOwnerAddresses: string[]; - private _contractOwnerAddress: string; - private _web3Wrapper: Web3Wrapper; - private _provider: Provider; - private _dummyTokenContracts: DummyERC721TokenContract[]; - private _proxyContract?: ERC721ProxyContract; - private _initialTokenIdsByOwner: ERC721TokenIdsByOwner = {}; - constructor(provider: Provider, tokenOwnerAddresses: string[], contractOwnerAddress: string) { - this._web3Wrapper = new Web3Wrapper(provider); - this._provider = provider; - this._dummyTokenContracts = []; - this._tokenOwnerAddresses = tokenOwnerAddresses; - this._contractOwnerAddress = contractOwnerAddress; - } - public async deployDummyTokensAsync(): Promise<DummyERC721TokenContract[]> { - for (let i = 0; i < constants.NUM_DUMMY_ERC721_TO_DEPLOY; i++) { - this._dummyTokenContracts.push( - await DummyERC721TokenContract.deployFrom0xArtifactAsync( - artifacts.DummyERC721Token, - this._provider, - txDefaults, - constants.DUMMY_TOKEN_NAME, - constants.DUMMY_TOKEN_SYMBOL, - ), - ); - } - return this._dummyTokenContracts; - } - public async deployProxyAsync(): Promise<ERC721ProxyContract> { - this._proxyContract = await ERC721ProxyContract.deployFrom0xArtifactAsync( - artifacts.ERC721Proxy, - this._provider, - txDefaults, - ); - return this._proxyContract; - } - public async setBalancesAndAllowancesAsync(): Promise<void> { - this._validateDummyTokenContractsExistOrThrow(); - this._validateProxyContractExistsOrThrow(); - this._initialTokenIdsByOwner = {}; - for (const dummyTokenContract of this._dummyTokenContracts) { - for (const tokenOwnerAddress of this._tokenOwnerAddresses) { - for (let i = 0; i < constants.NUM_ERC721_TOKENS_TO_MINT; i++) { - const tokenId = generatePseudoRandomSalt(); - await this._web3Wrapper.awaitTransactionSuccessAsync( - await dummyTokenContract.mint.sendTransactionAsync(tokenOwnerAddress, tokenId, { - from: this._contractOwnerAddress, - }), - constants.AWAIT_TRANSACTION_MINED_MS, - ); - if (_.isUndefined(this._initialTokenIdsByOwner[tokenOwnerAddress])) { - this._initialTokenIdsByOwner[tokenOwnerAddress] = { - [dummyTokenContract.address]: [], - }; - } - if (_.isUndefined(this._initialTokenIdsByOwner[tokenOwnerAddress][dummyTokenContract.address])) { - this._initialTokenIdsByOwner[tokenOwnerAddress][dummyTokenContract.address] = []; - } - this._initialTokenIdsByOwner[tokenOwnerAddress][dummyTokenContract.address].push(tokenId); - } - const shouldApprove = true; - await this._web3Wrapper.awaitTransactionSuccessAsync( - await dummyTokenContract.setApprovalForAll.sendTransactionAsync( - (this._proxyContract as ERC721ProxyContract).address, - shouldApprove, - { from: tokenOwnerAddress }, - ), - constants.AWAIT_TRANSACTION_MINED_MS, - ); - } - } - } - public async getBalancesAsync(): Promise<ERC721TokenIdsByOwner> { - this._validateDummyTokenContractsExistOrThrow(); - this._validateBalancesAndAllowancesSetOrThrow(); - const tokenIdsByOwner: ERC721TokenIdsByOwner = {}; - const tokenOwnerAddresses: string[] = []; - const tokenInfo: Array<{ tokenId: BigNumber; tokenAddress: string }> = []; - for (const dummyTokenContract of this._dummyTokenContracts) { - for (const tokenOwnerAddress of this._tokenOwnerAddresses) { - const initialTokenOwnerIds = this._initialTokenIdsByOwner[tokenOwnerAddress][ - dummyTokenContract.address - ]; - for (const tokenId of initialTokenOwnerIds) { - tokenOwnerAddresses.push(await dummyTokenContract.ownerOf.callAsync(tokenId)); - tokenInfo.push({ - tokenId, - tokenAddress: dummyTokenContract.address, - }); - } - } - } - _.forEach(tokenOwnerAddresses, (tokenOwnerAddress, ownerIndex) => { - const tokenAddress = tokenInfo[ownerIndex].tokenAddress; - const tokenId = tokenInfo[ownerIndex].tokenId; - if (_.isUndefined(tokenIdsByOwner[tokenOwnerAddress])) { - tokenIdsByOwner[tokenOwnerAddress] = { - [tokenAddress]: [], - }; - } - if (_.isUndefined(tokenIdsByOwner[tokenOwnerAddress][tokenAddress])) { - tokenIdsByOwner[tokenOwnerAddress][tokenAddress] = []; - } - tokenIdsByOwner[tokenOwnerAddress][tokenAddress].push(tokenId); - }); - return tokenIdsByOwner; - } - public getTokenOwnerAddresses(): string[] { - return this._tokenOwnerAddresses; - } - public getTokenAddresses(): string[] { - const tokenAddresses = _.map(this._dummyTokenContracts, dummyTokenContract => dummyTokenContract.address); - return tokenAddresses; - } - private _validateDummyTokenContractsExistOrThrow(): void { - if (_.isUndefined(this._dummyTokenContracts)) { - throw new Error('Dummy ERC721 tokens not yet deployed, please call "deployDummyTokensAsync"'); - } - } - private _validateProxyContractExistsOrThrow(): void { - if (_.isUndefined(this._proxyContract)) { - throw new Error('ERC721 proxy contract not yet deployed, please call "deployProxyAsync"'); - } - } - private _validateBalancesAndAllowancesSetOrThrow(): void { - if (_.keys(this._initialTokenIdsByOwner).length === 0) { - throw new Error( - 'Dummy ERC721 balances and allowances not yet set, please call "setBalancesAndAllowancesAsync"', - ); - } - } -} diff --git a/packages/contracts/src/utils/exchange_wrapper.ts b/packages/contracts/src/utils/exchange_wrapper.ts deleted file mode 100644 index 06eb70644..000000000 --- a/packages/contracts/src/utils/exchange_wrapper.ts +++ /dev/null @@ -1,250 +0,0 @@ -import { AssetProxyId, SignedOrder } from '@0xproject/types'; -import { BigNumber } from '@0xproject/utils'; -import { Web3Wrapper } from '@0xproject/web3-wrapper'; -import { Provider, TransactionReceiptWithDecodedLogs } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { ExchangeContract } from '../generated_contract_wrappers/exchange'; - -import { constants } from './constants'; -import { formatters } from './formatters'; -import { LogDecoder } from './log_decoder'; -import { orderUtils } from './order_utils'; -import { OrderInfo, SignedTransaction } from './types'; - -export class ExchangeWrapper { - private _exchange: ExchangeContract; - private _web3Wrapper: Web3Wrapper; - private _logDecoder: LogDecoder; - constructor(exchangeContract: ExchangeContract, provider: Provider) { - this._exchange = exchangeContract; - this._web3Wrapper = new Web3Wrapper(provider); - this._logDecoder = new LogDecoder(this._web3Wrapper, this._exchange.address); - } - public async fillOrderAsync( - signedOrder: SignedOrder, - from: string, - opts: { takerAssetFillAmount?: BigNumber } = {}, - ): Promise<TransactionReceiptWithDecodedLogs> { - const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount); - const txHash = await this._exchange.fillOrder.sendTransactionAsync( - params.order, - params.takerAssetFillAmount, - params.signature, - { from }, - ); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async cancelOrderAsync(signedOrder: SignedOrder, from: string): Promise<TransactionReceiptWithDecodedLogs> { - const params = orderUtils.createCancel(signedOrder); - const txHash = await this._exchange.cancelOrder.sendTransactionAsync(params.order, { from }); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async fillOrKillOrderAsync( - signedOrder: SignedOrder, - from: string, - opts: { takerAssetFillAmount?: BigNumber } = {}, - ): Promise<TransactionReceiptWithDecodedLogs> { - const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount); - const txHash = await this._exchange.fillOrKillOrder.sendTransactionAsync( - params.order, - params.takerAssetFillAmount, - params.signature, - { from }, - ); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async fillOrderNoThrowAsync( - signedOrder: SignedOrder, - from: string, - opts: { takerAssetFillAmount?: BigNumber; gas?: number } = {}, - ): Promise<TransactionReceiptWithDecodedLogs> { - const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount); - const txHash = await this._exchange.fillOrderNoThrow.sendTransactionAsync( - params.order, - params.takerAssetFillAmount, - params.signature, - { from, gas: opts.gas }, - ); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async batchFillOrdersAsync( - orders: SignedOrder[], - from: string, - opts: { takerAssetFillAmounts?: BigNumber[] } = {}, - ): Promise<TransactionReceiptWithDecodedLogs> { - const params = formatters.createBatchFill(orders, opts.takerAssetFillAmounts); - const txHash = await this._exchange.batchFillOrders.sendTransactionAsync( - params.orders, - params.takerAssetFillAmounts, - params.signatures, - { from }, - ); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async batchFillOrKillOrdersAsync( - orders: SignedOrder[], - from: string, - opts: { takerAssetFillAmounts?: BigNumber[] } = {}, - ): Promise<TransactionReceiptWithDecodedLogs> { - const params = formatters.createBatchFill(orders, opts.takerAssetFillAmounts); - const txHash = await this._exchange.batchFillOrKillOrders.sendTransactionAsync( - params.orders, - params.takerAssetFillAmounts, - params.signatures, - { from }, - ); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async batchFillOrdersNoThrowAsync( - orders: SignedOrder[], - from: string, - opts: { takerAssetFillAmounts?: BigNumber[]; gas?: number } = {}, - ): Promise<TransactionReceiptWithDecodedLogs> { - const params = formatters.createBatchFill(orders, opts.takerAssetFillAmounts); - const txHash = await this._exchange.batchFillOrdersNoThrow.sendTransactionAsync( - params.orders, - params.takerAssetFillAmounts, - params.signatures, - { from, gas: opts.gas }, - ); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async marketSellOrdersAsync( - orders: SignedOrder[], - from: string, - opts: { takerAssetFillAmount: BigNumber }, - ): Promise<TransactionReceiptWithDecodedLogs> { - const params = formatters.createMarketSellOrders(orders, opts.takerAssetFillAmount); - const txHash = await this._exchange.marketSellOrders.sendTransactionAsync( - params.orders, - params.takerAssetFillAmount, - params.signatures, - { from }, - ); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async marketSellOrdersNoThrowAsync( - orders: SignedOrder[], - from: string, - opts: { takerAssetFillAmount: BigNumber; gas?: number }, - ): Promise<TransactionReceiptWithDecodedLogs> { - const params = formatters.createMarketSellOrders(orders, opts.takerAssetFillAmount); - const txHash = await this._exchange.marketSellOrdersNoThrow.sendTransactionAsync( - params.orders, - params.takerAssetFillAmount, - params.signatures, - { from, gas: opts.gas }, - ); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async marketBuyOrdersAsync( - orders: SignedOrder[], - from: string, - opts: { makerAssetFillAmount: BigNumber }, - ): Promise<TransactionReceiptWithDecodedLogs> { - const params = formatters.createMarketBuyOrders(orders, opts.makerAssetFillAmount); - const txHash = await this._exchange.marketBuyOrders.sendTransactionAsync( - params.orders, - params.makerAssetFillAmount, - params.signatures, - { from }, - ); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async marketBuyOrdersNoThrowAsync( - orders: SignedOrder[], - from: string, - opts: { makerAssetFillAmount: BigNumber; gas?: number }, - ): Promise<TransactionReceiptWithDecodedLogs> { - const params = formatters.createMarketBuyOrders(orders, opts.makerAssetFillAmount); - const txHash = await this._exchange.marketBuyOrdersNoThrow.sendTransactionAsync( - params.orders, - params.makerAssetFillAmount, - params.signatures, - { from, gas: opts.gas }, - ); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async batchCancelOrdersAsync( - orders: SignedOrder[], - from: string, - ): Promise<TransactionReceiptWithDecodedLogs> { - const params = formatters.createBatchCancel(orders); - const txHash = await this._exchange.batchCancelOrders.sendTransactionAsync(params.orders, { from }); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async cancelOrdersUpToAsync(salt: BigNumber, from: string): Promise<TransactionReceiptWithDecodedLogs> { - const txHash = await this._exchange.cancelOrdersUpTo.sendTransactionAsync(salt, { from }); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async registerAssetProxyAsync( - assetProxyId: AssetProxyId, - assetProxyAddress: string, - from: string, - opts: { oldAssetProxyAddressIfExists?: string } = {}, - ): Promise<TransactionReceiptWithDecodedLogs> { - const oldAssetProxyAddress = _.isUndefined(opts.oldAssetProxyAddressIfExists) - ? constants.NULL_ADDRESS - : opts.oldAssetProxyAddressIfExists; - const txHash = await this._exchange.registerAssetProxy.sendTransactionAsync( - assetProxyId, - assetProxyAddress, - oldAssetProxyAddress, - { from }, - ); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async executeTransactionAsync( - signedTx: SignedTransaction, - from: string, - ): Promise<TransactionReceiptWithDecodedLogs> { - const txHash = await this._exchange.executeTransaction.sendTransactionAsync( - signedTx.salt, - signedTx.signerAddress, - signedTx.data, - signedTx.signature, - { from }, - ); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async getTakerAssetFilledAmountAsync(orderHashHex: string): Promise<BigNumber> { - const filledAmount = new BigNumber(await this._exchange.filled.callAsync(orderHashHex)); - return filledAmount; - } - public async getOrderInfoAsync(signedOrder: SignedOrder): Promise<OrderInfo> { - const orderInfo = (await this._exchange.getOrderInfo.callAsync(signedOrder)) as OrderInfo; - return orderInfo; - } - public async matchOrdersAsync( - signedOrderLeft: SignedOrder, - signedOrderRight: SignedOrder, - from: string, - ): Promise<TransactionReceiptWithDecodedLogs> { - const params = orderUtils.createMatchOrders(signedOrderLeft, signedOrderRight); - const txHash = await this._exchange.matchOrders.sendTransactionAsync( - params.left, - params.right, - params.leftSignature, - params.rightSignature, - { from }, - ); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } -} diff --git a/packages/contracts/src/utils/formatters.ts b/packages/contracts/src/utils/formatters.ts deleted file mode 100644 index 32e4787d6..000000000 --- a/packages/contracts/src/utils/formatters.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { SignedOrder } from '@0xproject/types'; -import { BigNumber } from '@0xproject/utils'; -import * as _ from 'lodash'; - -import { constants } from './constants'; -import { orderUtils } from './order_utils'; -import { BatchCancelOrders, BatchFillOrders, MarketBuyOrders, MarketSellOrders } from './types'; - -export const formatters = { - createBatchFill(signedOrders: SignedOrder[], takerAssetFillAmounts: BigNumber[] = []): BatchFillOrders { - const batchFill: BatchFillOrders = { - orders: [], - signatures: [], - takerAssetFillAmounts, - }; - _.forEach(signedOrders, signedOrder => { - const orderWithoutExchangeAddress = orderUtils.getOrderWithoutExchangeAddress(signedOrder); - batchFill.orders.push(orderWithoutExchangeAddress); - batchFill.signatures.push(signedOrder.signature); - if (takerAssetFillAmounts.length < signedOrders.length) { - batchFill.takerAssetFillAmounts.push(signedOrder.takerAssetAmount); - } - }); - return batchFill; - }, - createMarketSellOrders(signedOrders: SignedOrder[], takerAssetFillAmount: BigNumber): MarketSellOrders { - const marketSellOrders: MarketSellOrders = { - orders: [], - signatures: [], - takerAssetFillAmount, - }; - _.forEach(signedOrders, (signedOrder, i) => { - const orderWithoutExchangeAddress = orderUtils.getOrderWithoutExchangeAddress(signedOrder); - if (i !== 0) { - orderWithoutExchangeAddress.takerAssetData = constants.NULL_BYTES; - } - marketSellOrders.orders.push(orderWithoutExchangeAddress); - marketSellOrders.signatures.push(signedOrder.signature); - }); - return marketSellOrders; - }, - createMarketBuyOrders(signedOrders: SignedOrder[], makerAssetFillAmount: BigNumber): MarketBuyOrders { - const marketBuyOrders: MarketBuyOrders = { - orders: [], - signatures: [], - makerAssetFillAmount, - }; - _.forEach(signedOrders, (signedOrder, i) => { - const orderWithoutExchangeAddress = orderUtils.getOrderWithoutExchangeAddress(signedOrder); - if (i !== 0) { - orderWithoutExchangeAddress.makerAssetData = constants.NULL_BYTES; - } - marketBuyOrders.orders.push(orderWithoutExchangeAddress); - marketBuyOrders.signatures.push(signedOrder.signature); - }); - return marketBuyOrders; - }, - createBatchCancel(signedOrders: SignedOrder[]): BatchCancelOrders { - const batchCancel: BatchCancelOrders = { - orders: [], - }; - _.forEach(signedOrders, signedOrder => { - const orderWithoutExchangeAddress = orderUtils.getOrderWithoutExchangeAddress(signedOrder); - batchCancel.orders.push(orderWithoutExchangeAddress); - }); - return batchCancel; - }, -}; diff --git a/packages/contracts/src/utils/increase_time.ts b/packages/contracts/src/utils/increase_time.ts deleted file mode 100644 index 4565d8dbc..000000000 --- a/packages/contracts/src/utils/increase_time.ts +++ /dev/null @@ -1,31 +0,0 @@ -import * as _ from 'lodash'; - -import { constants } from './constants'; -import { web3Wrapper } from './web3_wrapper'; - -let firstAccount: string | undefined; - -/** - * Increases time by the given number of seconds and then mines a block so that - * the current block timestamp has the offset applied. - * @param seconds the number of seconds by which to incrase the time offset. - * @returns a new Promise which will resolve with the new total time offset or - * reject if the time could not be increased. - */ -export async function increaseTimeAndMineBlockAsync(seconds: number): Promise<number> { - if (_.isUndefined(firstAccount)) { - const accounts = await web3Wrapper.getAvailableAddressesAsync(); - firstAccount = accounts[0]; - } - - const offset = await web3Wrapper.increaseTimeAsync(seconds); - // Note: we need to send a transaction after increasing time so - // that a block is actually mined. The contract looks at the - // last mined block for the timestamp. - await web3Wrapper.awaitTransactionSuccessAsync( - await web3Wrapper.sendTransactionAsync({ from: firstAccount, to: firstAccount, value: 0 }), - constants.AWAIT_TRANSACTION_MINED_MS, - ); - - return offset; -} diff --git a/packages/contracts/src/utils/log_decoder.ts b/packages/contracts/src/utils/log_decoder.ts deleted file mode 100644 index 07127ba79..000000000 --- a/packages/contracts/src/utils/log_decoder.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { ContractArtifact } from '@0xproject/sol-compiler'; -import { AbiDecoder, BigNumber } from '@0xproject/utils'; -import { Web3Wrapper } from '@0xproject/web3-wrapper'; -import { - AbiDefinition, - DecodedLogArgs, - LogEntry, - LogWithDecodedArgs, - RawLog, - TransactionReceiptWithDecodedLogs, -} from 'ethereum-types'; -import * as _ from 'lodash'; - -import { artifacts } from './artifacts'; -import { constants } from './constants'; - -export class LogDecoder { - private _web3Wrapper: Web3Wrapper; - private _contractAddress: string; - private _abiDecoder: AbiDecoder; - public static wrapLogBigNumbers(log: any): any { - const argNames = _.keys(log.args); - for (const argName of argNames) { - const isWeb3BigNumber = _.startsWith(log.args[argName].constructor.toString(), 'function BigNumber('); - if (isWeb3BigNumber) { - log.args[argName] = new BigNumber(log.args[argName]); - } - } - } - constructor(web3Wrapper: Web3Wrapper, contractAddress: string) { - this._web3Wrapper = web3Wrapper; - this._contractAddress = contractAddress; - const abiArrays: AbiDefinition[][] = []; - _.forEach(artifacts, (artifact: ContractArtifact) => { - const compilerOutput = artifact.compilerOutput; - abiArrays.push(compilerOutput.abi); - }); - this._abiDecoder = new AbiDecoder(abiArrays); - } - public decodeLogOrThrow<ArgsType extends DecodedLogArgs>(log: LogEntry): LogWithDecodedArgs<ArgsType> | RawLog { - const logWithDecodedArgsOrLog = this._abiDecoder.tryToDecodeLogOrNoop(log); - // tslint:disable-next-line:no-unnecessary-type-assertion - if (_.isUndefined((logWithDecodedArgsOrLog as LogWithDecodedArgs<ArgsType>).args)) { - throw new Error(`Unable to decode log: ${JSON.stringify(log)}`); - } - LogDecoder.wrapLogBigNumbers(logWithDecodedArgsOrLog); - return logWithDecodedArgsOrLog; - } - public async getTxWithDecodedLogsAsync(txHash: string): Promise<TransactionReceiptWithDecodedLogs> { - const tx = await this._web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - tx.logs = _.filter(tx.logs, log => log.address === this._contractAddress); - tx.logs = _.map(tx.logs, log => this.decodeLogOrThrow(log)); - return tx; - } -} diff --git a/packages/contracts/src/utils/match_order_tester.ts b/packages/contracts/src/utils/match_order_tester.ts deleted file mode 100644 index fbb1b99db..000000000 --- a/packages/contracts/src/utils/match_order_tester.ts +++ /dev/null @@ -1,330 +0,0 @@ -import { assetProxyUtils, orderHashUtils } from '@0xproject/order-utils'; -import { AssetProxyId, SignedOrder } from '@0xproject/types'; -import { BigNumber } from '@0xproject/utils'; -import * as chai from 'chai'; -import * as _ from 'lodash'; - -import { chaiSetup } from '../utils/chai_setup'; -import { ERC20Wrapper } from '../utils/erc20_wrapper'; -import { ERC721Wrapper } from '../utils/erc721_wrapper'; -import { ExchangeWrapper } from '../utils/exchange_wrapper'; -import { - ERC20BalancesByOwner, - ERC721TokenIdsByOwner, - TransferAmountsByMatchOrders as TransferAmounts, -} from '../utils/types'; - -chaiSetup.configure(); -const expect = chai.expect; - -export class MatchOrderTester { - private _exchangeWrapper: ExchangeWrapper; - private _erc20Wrapper: ERC20Wrapper; - private _erc721Wrapper: ERC721Wrapper; - private _feeTokenAddress: string; - - /// @dev Compares a pair of ERC20 balances and a pair of ERC721 token owners. - /// @param expectedNewERC20BalancesByOwner Expected ERC20 balances. - /// @param realERC20BalancesByOwner Actual ERC20 balances. - /// @param expectedNewERC721TokenIdsByOwner Expected ERC721 token owners. - /// @param realERC721TokenIdsByOwner Actual ERC20 token owners. - /// @return True only if ERC20 balances match and ERC721 token owners match. - private static _compareExpectedAndRealBalances( - expectedNewERC20BalancesByOwner: ERC20BalancesByOwner, - realERC20BalancesByOwner: ERC20BalancesByOwner, - expectedNewERC721TokenIdsByOwner: ERC721TokenIdsByOwner, - realERC721TokenIdsByOwner: ERC721TokenIdsByOwner, - ): boolean { - // ERC20 Balances - const doesErc20BalancesMatch = _.isEqual(expectedNewERC20BalancesByOwner, realERC20BalancesByOwner); - if (!doesErc20BalancesMatch) { - return false; - } - // ERC721 Token Ids - const sortedExpectedNewERC721TokenIdsByOwner = _.mapValues( - expectedNewERC721TokenIdsByOwner, - tokenIdsByOwner => { - _.mapValues(tokenIdsByOwner, tokenIds => { - _.sortBy(tokenIds); - }); - }, - ); - const sortedNewERC721TokenIdsByOwner = _.mapValues(realERC721TokenIdsByOwner, tokenIdsByOwner => { - _.mapValues(tokenIdsByOwner, tokenIds => { - _.sortBy(tokenIds); - }); - }); - const doesErc721TokenIdsMatch = _.isEqual( - sortedExpectedNewERC721TokenIdsByOwner, - sortedNewERC721TokenIdsByOwner, - ); - return doesErc721TokenIdsMatch; - } - /// @dev Constructs new MatchOrderTester. - /// @param exchangeWrapper Used to call to the Exchange. - /// @param erc20Wrapper Used to fetch ERC20 balances. - /// @param erc721Wrapper Used to fetch ERC721 token owners. - /// @param feeTokenAddress Address of ERC20 fee token. - constructor( - exchangeWrapper: ExchangeWrapper, - erc20Wrapper: ERC20Wrapper, - erc721Wrapper: ERC721Wrapper, - feeTokenAddress: string, - ) { - this._exchangeWrapper = exchangeWrapper; - this._erc20Wrapper = erc20Wrapper; - this._erc721Wrapper = erc721Wrapper; - this._feeTokenAddress = feeTokenAddress; - } - /// @dev Matches two complementary orders and validates results. - /// Validation either succeeds or throws. - /// @param signedOrderLeft First matched order. - /// @param signedOrderRight Second matched order. - /// @param takerAddress Address of taker (the address who matched the two orders) - /// @param erc20BalancesByOwner Current ERC20 balances. - /// @param erc721TokenIdsByOwner Current ERC721 token owners. - /// @param initialTakerAssetFilledAmountLeft Current amount the left order has been filled. - /// @param initialTakerAssetFilledAmountRight Current amount the right order has been filled. - /// @return New ERC20 balances & ERC721 token owners. - public async matchOrdersAndVerifyBalancesAsync( - signedOrderLeft: SignedOrder, - signedOrderRight: SignedOrder, - takerAddress: string, - erc20BalancesByOwner: ERC20BalancesByOwner, - erc721TokenIdsByOwner: ERC721TokenIdsByOwner, - initialTakerAssetFilledAmountLeft?: BigNumber, - initialTakerAssetFilledAmountRight?: BigNumber, - ): Promise<[ERC20BalancesByOwner, ERC721TokenIdsByOwner]> { - // Verify Left order preconditions - const orderTakerAssetFilledAmountLeft = await this._exchangeWrapper.getTakerAssetFilledAmountAsync( - orderHashUtils.getOrderHashHex(signedOrderLeft), - ); - const expectedOrderFilledAmountLeft = initialTakerAssetFilledAmountLeft - ? initialTakerAssetFilledAmountLeft - : new BigNumber(0); - expect(expectedOrderFilledAmountLeft).to.be.bignumber.equal(orderTakerAssetFilledAmountLeft); - // Verify Right order preconditions - const orderTakerAssetFilledAmountRight = await this._exchangeWrapper.getTakerAssetFilledAmountAsync( - orderHashUtils.getOrderHashHex(signedOrderRight), - ); - const expectedOrderFilledAmountRight = initialTakerAssetFilledAmountRight - ? initialTakerAssetFilledAmountRight - : new BigNumber(0); - expect(expectedOrderFilledAmountRight).to.be.bignumber.equal(orderTakerAssetFilledAmountRight); - // Match left & right orders - await this._exchangeWrapper.matchOrdersAsync(signedOrderLeft, signedOrderRight, takerAddress); - const newERC20BalancesByOwner = await this._erc20Wrapper.getBalancesAsync(); - const newERC721TokenIdsByOwner = await this._erc721Wrapper.getBalancesAsync(); - // Calculate expected balance changes - const expectedTransferAmounts = await this._calculateExpectedTransferAmountsAsync( - signedOrderLeft, - signedOrderRight, - orderTakerAssetFilledAmountLeft, - orderTakerAssetFilledAmountRight, - ); - let expectedERC20BalancesByOwner: ERC20BalancesByOwner; - let expectedERC721TokenIdsByOwner: ERC721TokenIdsByOwner; - [expectedERC20BalancesByOwner, expectedERC721TokenIdsByOwner] = this._calculateExpectedBalances( - signedOrderLeft, - signedOrderRight, - takerAddress, - erc20BalancesByOwner, - erc721TokenIdsByOwner, - expectedTransferAmounts, - ); - // Assert our expected balances are equal to the actual balances - const didExpectedBalancesMatchRealBalances = MatchOrderTester._compareExpectedAndRealBalances( - expectedERC20BalancesByOwner, - newERC20BalancesByOwner, - expectedERC721TokenIdsByOwner, - newERC721TokenIdsByOwner, - ); - expect(didExpectedBalancesMatchRealBalances).to.be.true(); - return [newERC20BalancesByOwner, newERC721TokenIdsByOwner]; - } - /// @dev Calculates expected transfer amounts between order makers, fee recipients, and - /// the taker when two orders are matched. - /// @param signedOrderLeft First matched order. - /// @param signedOrderRight Second matched order. - /// @param orderTakerAssetFilledAmountLeft How much left order has been filled, prior to matching orders. - /// @param orderTakerAssetFilledAmountRight How much the right order has been filled, prior to matching orders. - /// @return TransferAmounts A struct containing the expected transfer amounts. - private async _calculateExpectedTransferAmountsAsync( - signedOrderLeft: SignedOrder, - signedOrderRight: SignedOrder, - orderTakerAssetFilledAmountLeft: BigNumber, - orderTakerAssetFilledAmountRight: BigNumber, - ): Promise<TransferAmounts> { - let amountBoughtByLeftMaker = await this._exchangeWrapper.getTakerAssetFilledAmountAsync( - orderHashUtils.getOrderHashHex(signedOrderLeft), - ); - amountBoughtByLeftMaker = amountBoughtByLeftMaker.minus(orderTakerAssetFilledAmountLeft); - const amountSoldByLeftMaker = amountBoughtByLeftMaker - .times(signedOrderLeft.makerAssetAmount) - .dividedToIntegerBy(signedOrderLeft.takerAssetAmount); - const amountReceivedByRightMaker = amountBoughtByLeftMaker - .times(signedOrderRight.takerAssetAmount) - .dividedToIntegerBy(signedOrderRight.makerAssetAmount); - const amountReceivedByTaker = amountSoldByLeftMaker.minus(amountReceivedByRightMaker); - let amountBoughtByRightMaker = await this._exchangeWrapper.getTakerAssetFilledAmountAsync( - orderHashUtils.getOrderHashHex(signedOrderRight), - ); - amountBoughtByRightMaker = amountBoughtByRightMaker.minus(orderTakerAssetFilledAmountRight); - const amountSoldByRightMaker = amountBoughtByRightMaker - .times(signedOrderRight.makerAssetAmount) - .dividedToIntegerBy(signedOrderRight.takerAssetAmount); - const amountReceivedByLeftMaker = amountSoldByRightMaker; - const feePaidByLeftMaker = signedOrderLeft.makerFee - .times(amountSoldByLeftMaker) - .dividedToIntegerBy(signedOrderLeft.makerAssetAmount); - const feePaidByRightMaker = signedOrderRight.makerFee - .times(amountSoldByRightMaker) - .dividedToIntegerBy(signedOrderRight.makerAssetAmount); - const feePaidByTakerLeft = signedOrderLeft.takerFee - .times(amountSoldByLeftMaker) - .dividedToIntegerBy(signedOrderLeft.makerAssetAmount); - const feePaidByTakerRight = signedOrderRight.takerFee - .times(amountSoldByRightMaker) - .dividedToIntegerBy(signedOrderRight.makerAssetAmount); - const totalFeePaidByTaker = feePaidByTakerLeft.add(feePaidByTakerRight); - const feeReceivedLeft = feePaidByLeftMaker.add(feePaidByTakerLeft); - const feeReceivedRight = feePaidByRightMaker.add(feePaidByTakerRight); - // Return values - const expectedTransferAmounts = { - // Left Maker - amountBoughtByLeftMaker, - amountSoldByLeftMaker, - amountReceivedByLeftMaker, - feePaidByLeftMaker, - // Right Maker - amountBoughtByRightMaker, - amountSoldByRightMaker, - amountReceivedByRightMaker, - feePaidByRightMaker, - // Taker - amountReceivedByTaker, - feePaidByTakerLeft, - feePaidByTakerRight, - totalFeePaidByTaker, - // Fee Recipients - feeReceivedLeft, - feeReceivedRight, - }; - return expectedTransferAmounts; - } - /// @dev Calculates the expected balances of order makers, fee recipients, and the taker, - /// as a result of matching two orders. - /// @param signedOrderLeft First matched order. - /// @param signedOrderRight Second matched order. - /// @param takerAddress Address of taker (the address who matched the two orders) - /// @param erc20BalancesByOwner Current ERC20 balances. - /// @param erc721TokenIdsByOwner Current ERC721 token owners. - /// @param expectedTransferAmounts A struct containing the expected transfer amounts. - /// @return Expected ERC20 balances & ERC721 token owners after orders have been matched. - private _calculateExpectedBalances( - signedOrderLeft: SignedOrder, - signedOrderRight: SignedOrder, - takerAddress: string, - erc20BalancesByOwner: ERC20BalancesByOwner, - erc721TokenIdsByOwner: ERC721TokenIdsByOwner, - expectedTransferAmounts: TransferAmounts, - ): [ERC20BalancesByOwner, ERC721TokenIdsByOwner] { - const makerAddressLeft = signedOrderLeft.makerAddress; - const makerAddressRight = signedOrderRight.makerAddress; - const feeRecipientAddressLeft = signedOrderLeft.feeRecipientAddress; - const feeRecipientAddressRight = signedOrderRight.feeRecipientAddress; - // Operations are performed on copies of the balances - const expectedNewERC20BalancesByOwner = _.cloneDeep(erc20BalancesByOwner); - const expectedNewERC721TokenIdsByOwner = _.cloneDeep(erc721TokenIdsByOwner); - // Left Maker Asset (Right Taker Asset) - const makerAssetProxyIdLeft = assetProxyUtils.decodeAssetDataId(signedOrderLeft.makerAssetData); - if (makerAssetProxyIdLeft === AssetProxyId.ERC20) { - // Decode asset data - const erc20AssetData = assetProxyUtils.decodeERC20AssetData(signedOrderLeft.makerAssetData); - const makerAssetAddressLeft = erc20AssetData.tokenAddress; - const takerAssetAddressRight = makerAssetAddressLeft; - // Left Maker - expectedNewERC20BalancesByOwner[makerAddressLeft][makerAssetAddressLeft] = expectedNewERC20BalancesByOwner[ - makerAddressLeft - ][makerAssetAddressLeft].minus(expectedTransferAmounts.amountSoldByLeftMaker); - // Right Maker - expectedNewERC20BalancesByOwner[makerAddressRight][ - takerAssetAddressRight - ] = expectedNewERC20BalancesByOwner[makerAddressRight][takerAssetAddressRight].add( - expectedTransferAmounts.amountReceivedByRightMaker, - ); - // Taker - expectedNewERC20BalancesByOwner[takerAddress][makerAssetAddressLeft] = expectedNewERC20BalancesByOwner[ - takerAddress - ][makerAssetAddressLeft].add(expectedTransferAmounts.amountReceivedByTaker); - } else if (makerAssetProxyIdLeft === AssetProxyId.ERC721) { - // Decode asset data - const erc721AssetData = assetProxyUtils.decodeERC721AssetData(signedOrderLeft.makerAssetData); - const makerAssetAddressLeft = erc721AssetData.tokenAddress; - const makerAssetIdLeft = erc721AssetData.tokenId; - const takerAssetAddressRight = makerAssetAddressLeft; - const takerAssetIdRight = makerAssetIdLeft; - // Left Maker - _.remove(expectedNewERC721TokenIdsByOwner[makerAddressLeft][makerAssetAddressLeft], makerAssetIdLeft); - // Right Maker - expectedNewERC721TokenIdsByOwner[makerAddressRight][takerAssetAddressRight].push(takerAssetIdRight); - // Taker: Since there is only 1 asset transferred, the taker does not receive any of the left maker asset. - } - // Left Taker Asset (Right Maker Asset) - // Note: This exchange is only between the order makers: the Taker does not receive any of the left taker asset. - const takerAssetProxyIdLeft = assetProxyUtils.decodeAssetDataId(signedOrderLeft.takerAssetData); - if (takerAssetProxyIdLeft === AssetProxyId.ERC20) { - // Decode asset data - const erc20AssetData = assetProxyUtils.decodeERC20AssetData(signedOrderLeft.takerAssetData); - const takerAssetAddressLeft = erc20AssetData.tokenAddress; - const makerAssetAddressRight = takerAssetAddressLeft; - // Left Maker - expectedNewERC20BalancesByOwner[makerAddressLeft][takerAssetAddressLeft] = expectedNewERC20BalancesByOwner[ - makerAddressLeft - ][takerAssetAddressLeft].add(expectedTransferAmounts.amountReceivedByLeftMaker); - // Right Maker - expectedNewERC20BalancesByOwner[makerAddressRight][ - makerAssetAddressRight - ] = expectedNewERC20BalancesByOwner[makerAddressRight][makerAssetAddressRight].minus( - expectedTransferAmounts.amountSoldByRightMaker, - ); - } else if (takerAssetProxyIdLeft === AssetProxyId.ERC721) { - // Decode asset data - const erc721AssetData = assetProxyUtils.decodeERC721AssetData(signedOrderRight.makerAssetData); - const makerAssetAddressRight = erc721AssetData.tokenAddress; - const makerAssetIdRight = erc721AssetData.tokenId; - const takerAssetAddressLeft = makerAssetAddressRight; - const takerAssetIdLeft = makerAssetIdRight; - // Right Maker - _.remove(expectedNewERC721TokenIdsByOwner[makerAddressRight][makerAssetAddressRight], makerAssetIdRight); - // Left Maker - expectedNewERC721TokenIdsByOwner[makerAddressLeft][takerAssetAddressLeft].push(takerAssetIdLeft); - } - // Left Maker Fees - expectedNewERC20BalancesByOwner[makerAddressLeft][this._feeTokenAddress] = expectedNewERC20BalancesByOwner[ - makerAddressLeft - ][this._feeTokenAddress].minus(expectedTransferAmounts.feePaidByLeftMaker); - // Right Maker Fees - expectedNewERC20BalancesByOwner[makerAddressRight][this._feeTokenAddress] = expectedNewERC20BalancesByOwner[ - makerAddressRight - ][this._feeTokenAddress].minus(expectedTransferAmounts.feePaidByRightMaker); - // Taker Fees - expectedNewERC20BalancesByOwner[takerAddress][this._feeTokenAddress] = expectedNewERC20BalancesByOwner[ - takerAddress - ][this._feeTokenAddress].minus(expectedTransferAmounts.totalFeePaidByTaker); - // Left Fee Recipient Fees - expectedNewERC20BalancesByOwner[feeRecipientAddressLeft][ - this._feeTokenAddress - ] = expectedNewERC20BalancesByOwner[feeRecipientAddressLeft][this._feeTokenAddress].add( - expectedTransferAmounts.feeReceivedLeft, - ); - // Right Fee Recipient Fees - expectedNewERC20BalancesByOwner[feeRecipientAddressRight][ - this._feeTokenAddress - ] = expectedNewERC20BalancesByOwner[feeRecipientAddressRight][this._feeTokenAddress].add( - expectedTransferAmounts.feeReceivedRight, - ); - - return [expectedNewERC20BalancesByOwner, expectedNewERC721TokenIdsByOwner]; - } -} diff --git a/packages/contracts/src/utils/multi_sig_wrapper.ts b/packages/contracts/src/utils/multi_sig_wrapper.ts deleted file mode 100644 index b0d4fa8ab..000000000 --- a/packages/contracts/src/utils/multi_sig_wrapper.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { BigNumber } from '@0xproject/utils'; -import { Web3Wrapper } from '@0xproject/web3-wrapper'; -import { Provider, TransactionReceiptWithDecodedLogs } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { AssetProxyOwnerContract } from '../generated_contract_wrappers/asset_proxy_owner'; -import { MultiSigWalletContract } from '../generated_contract_wrappers/multi_sig_wallet'; - -import { LogDecoder } from './log_decoder'; - -export class MultiSigWrapper { - private _multiSig: MultiSigWalletContract; - private _web3Wrapper: Web3Wrapper; - private _logDecoder: LogDecoder; - constructor(multiSigContract: MultiSigWalletContract, provider: Provider) { - this._multiSig = multiSigContract; - this._web3Wrapper = new Web3Wrapper(provider); - this._logDecoder = new LogDecoder(this._web3Wrapper, this._multiSig.address); - } - public async submitTransactionAsync( - destination: string, - data: string, - from: string, - opts: { value?: BigNumber } = {}, - ): Promise<TransactionReceiptWithDecodedLogs> { - const value = _.isUndefined(opts.value) ? new BigNumber(0) : opts.value; - const txHash = await this._multiSig.submitTransaction.sendTransactionAsync(destination, value, data, { - from, - }); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async confirmTransactionAsync(txId: BigNumber, from: string): Promise<TransactionReceiptWithDecodedLogs> { - const txHash = await this._multiSig.confirmTransaction.sendTransactionAsync(txId, { from }); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async executeTransactionAsync(txId: BigNumber, from: string): Promise<TransactionReceiptWithDecodedLogs> { - const txHash = await this._multiSig.executeTransaction.sendTransactionAsync(txId, { from }); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } - public async executeRemoveAuthorizedAddressAtIndexAsync( - txId: BigNumber, - from: string, - ): Promise<TransactionReceiptWithDecodedLogs> { - // tslint:disable-next-line:no-unnecessary-type-assertion - const txHash = await (this - ._multiSig as AssetProxyOwnerContract).executeRemoveAuthorizedAddressAtIndex.sendTransactionAsync(txId, { - from, - }); - const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); - return tx; - } -} diff --git a/packages/contracts/src/utils/order_factory.ts b/packages/contracts/src/utils/order_factory.ts deleted file mode 100644 index 009dbc396..000000000 --- a/packages/contracts/src/utils/order_factory.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { generatePseudoRandomSalt, orderHashUtils } from '@0xproject/order-utils'; -import { Order, SignatureType, SignedOrder } from '@0xproject/types'; -import { BigNumber } from '@0xproject/utils'; - -import { constants } from './constants'; -import { signingUtils } from './signing_utils'; - -export class OrderFactory { - private _defaultOrderParams: Partial<Order>; - private _privateKey: Buffer; - constructor(privateKey: Buffer, defaultOrderParams: Partial<Order>) { - this._defaultOrderParams = defaultOrderParams; - this._privateKey = privateKey; - } - public newSignedOrder( - customOrderParams: Partial<Order> = {}, - signatureType: SignatureType = SignatureType.EthSign, - ): SignedOrder { - const tenMinutes = 10 * 60 * 1000; - const randomExpiration = new BigNumber(Date.now() + tenMinutes); - const order = ({ - senderAddress: constants.NULL_ADDRESS, - expirationTimeSeconds: randomExpiration, - salt: generatePseudoRandomSalt(), - takerAddress: constants.NULL_ADDRESS, - ...this._defaultOrderParams, - ...customOrderParams, - } as any) as Order; - const orderHashBuff = orderHashUtils.getOrderHashBuffer(order); - const signature = signingUtils.signMessage(orderHashBuff, this._privateKey, signatureType); - const signedOrder = { - ...order, - signature: `0x${signature.toString('hex')}`, - }; - return signedOrder; - } -} diff --git a/packages/contracts/src/utils/order_utils.ts b/packages/contracts/src/utils/order_utils.ts deleted file mode 100644 index a9f994d80..000000000 --- a/packages/contracts/src/utils/order_utils.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { OrderWithoutExchangeAddress, SignedOrder } from '@0xproject/types'; -import { BigNumber } from '@0xproject/utils'; - -import { constants } from './constants'; -import { CancelOrder, MatchOrder } from './types'; - -export const orderUtils = { - createFill: (signedOrder: SignedOrder, takerAssetFillAmount?: BigNumber) => { - const fill = { - order: orderUtils.getOrderWithoutExchangeAddress(signedOrder), - takerAssetFillAmount: takerAssetFillAmount || signedOrder.takerAssetAmount, - signature: signedOrder.signature, - }; - return fill; - }, - createCancel(signedOrder: SignedOrder, takerAssetCancelAmount?: BigNumber): CancelOrder { - const cancel = { - order: orderUtils.getOrderWithoutExchangeAddress(signedOrder), - takerAssetCancelAmount: takerAssetCancelAmount || signedOrder.takerAssetAmount, - }; - return cancel; - }, - getOrderWithoutExchangeAddress(signedOrder: SignedOrder): OrderWithoutExchangeAddress { - const orderStruct = { - senderAddress: signedOrder.senderAddress, - makerAddress: signedOrder.makerAddress, - takerAddress: signedOrder.takerAddress, - feeRecipientAddress: signedOrder.feeRecipientAddress, - makerAssetAmount: signedOrder.makerAssetAmount, - takerAssetAmount: signedOrder.takerAssetAmount, - makerFee: signedOrder.makerFee, - takerFee: signedOrder.takerFee, - expirationTimeSeconds: signedOrder.expirationTimeSeconds, - salt: signedOrder.salt, - makerAssetData: signedOrder.makerAssetData, - takerAssetData: signedOrder.takerAssetData, - }; - return orderStruct; - }, - createMatchOrders(signedOrderLeft: SignedOrder, signedOrderRight: SignedOrder): MatchOrder { - const fill = { - left: orderUtils.getOrderWithoutExchangeAddress(signedOrderLeft), - right: orderUtils.getOrderWithoutExchangeAddress(signedOrderRight), - leftSignature: signedOrderLeft.signature, - rightSignature: signedOrderRight.signature, - }; - fill.right.makerAssetData = constants.NULL_BYTES; - fill.right.takerAssetData = constants.NULL_BYTES; - return fill; - }, -}; diff --git a/packages/contracts/src/utils/profiler.ts b/packages/contracts/src/utils/profiler.ts deleted file mode 100644 index 85ee24f22..000000000 --- a/packages/contracts/src/utils/profiler.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { devConstants } from '@0xproject/dev-utils'; -import { ProfilerSubprovider, SolCompilerArtifactAdapter } from '@0xproject/sol-cov'; -import * as _ from 'lodash'; - -let profilerSubprovider: ProfilerSubprovider; - -export const profiler = { - start(): void { - profiler.getProfilerSubproviderSingleton().start(); - }, - stop(): void { - profiler.getProfilerSubproviderSingleton().stop(); - }, - getProfilerSubproviderSingleton(): ProfilerSubprovider { - if (_.isUndefined(profilerSubprovider)) { - profilerSubprovider = profiler._getProfilerSubprovider(); - } - return profilerSubprovider; - }, - _getProfilerSubprovider(): ProfilerSubprovider { - const defaultFromAddress = devConstants.TESTRPC_FIRST_ADDRESS; - const solCompilerArtifactAdapter = new SolCompilerArtifactAdapter(); - const isVerbose = true; - const subprovider = new ProfilerSubprovider(solCompilerArtifactAdapter, defaultFromAddress, isVerbose); - return subprovider; - }, -}; diff --git a/packages/contracts/src/utils/revert_trace.ts b/packages/contracts/src/utils/revert_trace.ts deleted file mode 100644 index 0bf8384bc..000000000 --- a/packages/contracts/src/utils/revert_trace.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { devConstants } from '@0xproject/dev-utils'; -import { RevertTraceSubprovider, SolCompilerArtifactAdapter } from '@0xproject/sol-cov'; -import * as _ from 'lodash'; - -let revertTraceSubprovider: RevertTraceSubprovider; - -export const revertTrace = { - getRevertTraceSubproviderSingleton(): RevertTraceSubprovider { - if (_.isUndefined(revertTraceSubprovider)) { - revertTraceSubprovider = revertTrace._getRevertTraceSubprovider(); - } - return revertTraceSubprovider; - }, - _getRevertTraceSubprovider(): RevertTraceSubprovider { - const defaultFromAddress = devConstants.TESTRPC_FIRST_ADDRESS; - const solCompilerArtifactAdapter = new SolCompilerArtifactAdapter(); - const isVerbose = true; - const subprovider = new RevertTraceSubprovider(solCompilerArtifactAdapter, defaultFromAddress, isVerbose); - return subprovider; - }, -}; diff --git a/packages/contracts/src/utils/signing_utils.ts b/packages/contracts/src/utils/signing_utils.ts deleted file mode 100644 index 9c711c72c..000000000 --- a/packages/contracts/src/utils/signing_utils.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { SignatureType } from '@0xproject/types'; -import * as ethUtil from 'ethereumjs-util'; - -export const signingUtils = { - signMessage(message: Buffer, privateKey: Buffer, signatureType: SignatureType): Buffer { - if (signatureType === SignatureType.EthSign) { - const prefixedMessage = ethUtil.hashPersonalMessage(message); - const ecSignature = ethUtil.ecsign(prefixedMessage, privateKey); - const signature = Buffer.concat([ - ethUtil.toBuffer(ecSignature.v), - ecSignature.r, - ecSignature.s, - ethUtil.toBuffer(signatureType), - ]); - return signature; - } else if (signatureType === SignatureType.EIP712) { - const ecSignature = ethUtil.ecsign(message, privateKey); - const signature = Buffer.concat([ - ethUtil.toBuffer(ecSignature.v), - ecSignature.r, - ecSignature.s, - ethUtil.toBuffer(signatureType), - ]); - return signature; - } else { - throw new Error(`${signatureType} is not a valid signature type`); - } - }, -}; diff --git a/packages/contracts/src/utils/token_registry_wrapper.ts b/packages/contracts/src/utils/token_registry_wrapper.ts deleted file mode 100644 index 91895aa59..000000000 --- a/packages/contracts/src/utils/token_registry_wrapper.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { Web3Wrapper } from '@0xproject/web3-wrapper'; -import { Provider } from 'ethereum-types'; - -import { TokenRegistryContract } from '../generated_contract_wrappers/token_registry'; - -import { Token } from './types'; - -import { constants } from './constants'; - -export class TokenRegWrapper { - private _tokenReg: TokenRegistryContract; - private _web3Wrapper: Web3Wrapper; - constructor(tokenRegContract: TokenRegistryContract, provider: Provider) { - this._tokenReg = tokenRegContract; - this._web3Wrapper = new Web3Wrapper(provider); - } - public async addTokenAsync(token: Token, from: string): Promise<string> { - const txHash = await this._tokenReg.addToken.sendTransactionAsync( - token.address as string, - token.name, - token.symbol, - token.decimals, - token.ipfsHash, - token.swarmHash, - { from }, - ); - await this._web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - return txHash; - } - public async getTokenMetaDataAsync(tokenAddress: string): Promise<Token> { - const data = await this._tokenReg.getTokenMetaData.callAsync(tokenAddress); - const token: Token = { - address: data[0], - name: data[1], - symbol: data[2], - decimals: data[3], - ipfsHash: data[4], - swarmHash: data[5], - }; - return token; - } - public async getTokenByNameAsync(tokenName: string): Promise<Token> { - const data = await this._tokenReg.getTokenByName.callAsync(tokenName); - const token: Token = { - address: data[0], - name: data[1], - symbol: data[2], - decimals: data[3], - ipfsHash: data[4], - swarmHash: data[5], - }; - return token; - } - public async getTokenBySymbolAsync(tokenSymbol: string): Promise<Token> { - const data = await this._tokenReg.getTokenBySymbol.callAsync(tokenSymbol); - const token: Token = { - address: data[0], - name: data[1], - symbol: data[2], - decimals: data[3], - ipfsHash: data[4], - swarmHash: data[5], - }; - return token; - } -} diff --git a/packages/contracts/src/utils/transaction_factory.ts b/packages/contracts/src/utils/transaction_factory.ts deleted file mode 100644 index 348c0715d..000000000 --- a/packages/contracts/src/utils/transaction_factory.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { EIP712Schema, EIP712Types, EIP712Utils, generatePseudoRandomSalt } from '@0xproject/order-utils'; -import { SignatureType } from '@0xproject/types'; -import * as ethUtil from 'ethereumjs-util'; - -import { signingUtils } from './signing_utils'; -import { SignedTransaction } from './types'; - -const EIP712_ZEROEX_TRANSACTION_SCHEMA: EIP712Schema = { - name: 'ZeroExTransaction', - parameters: [ - { name: 'salt', type: EIP712Types.Uint256 }, - { name: 'signerAddress', type: EIP712Types.Address }, - { name: 'data', type: EIP712Types.Bytes }, - ], -}; - -export class TransactionFactory { - private _signerBuff: Buffer; - private _exchangeAddress: string; - private _privateKey: Buffer; - constructor(privateKey: Buffer, exchangeAddress: string) { - this._privateKey = privateKey; - this._exchangeAddress = exchangeAddress; - this._signerBuff = ethUtil.privateToAddress(this._privateKey); - } - public newSignedTransaction(data: string, signatureType: SignatureType = SignatureType.EthSign): SignedTransaction { - const salt = generatePseudoRandomSalt(); - const signerAddress = `0x${this._signerBuff.toString('hex')}`; - const executeTransactionData = { - salt, - signerAddress, - data, - }; - const executeTransactionHashBuff = EIP712Utils.structHash( - EIP712_ZEROEX_TRANSACTION_SCHEMA, - executeTransactionData, - ); - const txHash = EIP712Utils.createEIP712Message(executeTransactionHashBuff, this._exchangeAddress); - const signature = signingUtils.signMessage(txHash, this._privateKey, signatureType); - const signedTx = { - exchangeAddress: this._exchangeAddress, - signature: `0x${signature.toString('hex')}`, - ...executeTransactionData, - }; - return signedTx; - } -} diff --git a/packages/contracts/src/utils/types.ts b/packages/contracts/src/utils/types.ts deleted file mode 100644 index 5dfac64fc..000000000 --- a/packages/contracts/src/utils/types.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { OrderWithoutExchangeAddress } from '@0xproject/types'; -import { BigNumber } from '@0xproject/utils'; -import { AbiDefinition } from 'ethereum-types'; - -export interface ERC20BalancesByOwner { - [ownerAddress: string]: { - [tokenAddress: string]: BigNumber; - }; -} - -export interface ERC721TokenIdsByOwner { - [ownerAddress: string]: { - [tokenAddress: string]: BigNumber[]; - }; -} - -export interface SubmissionContractEventArgs { - transactionId: BigNumber; -} - -export interface BatchFillOrders { - orders: OrderWithoutExchangeAddress[]; - signatures: string[]; - takerAssetFillAmounts: BigNumber[]; -} - -export interface MarketSellOrders { - orders: OrderWithoutExchangeAddress[]; - signatures: string[]; - takerAssetFillAmount: BigNumber; -} - -export interface MarketBuyOrders { - orders: OrderWithoutExchangeAddress[]; - signatures: string[]; - makerAssetFillAmount: BigNumber; -} - -export interface BatchCancelOrders { - orders: OrderWithoutExchangeAddress[]; -} - -export interface CancelOrdersBefore { - salt: BigNumber; -} - -export interface TransactionDataParams { - name: string; - abi: AbiDefinition[]; - args: any[]; -} - -export interface MultiSigConfig { - owners: string[]; - confirmationsRequired: number; - secondsRequired: number; -} - -export interface MultiSigConfigByNetwork { - [networkName: string]: MultiSigConfig; -} - -export interface Token { - address?: string; - name: string; - symbol: string; - decimals: number; - ipfsHash: string; - swarmHash: string; -} - -export enum OrderStatus { - INVALID, - INVALID_MAKER_ASSET_AMOUNT, - INVALID_TAKER_ASSET_AMOUNT, - FILLABLE, - EXPIRED, - FULLY_FILLED, - CANCELLED, -} - -export enum ContractName { - TokenRegistry = 'TokenRegistry', - MultiSigWalletWithTimeLock = 'MultiSigWalletWithTimeLock', - Exchange = 'Exchange', - ZRXToken = 'ZRXToken', - DummyERC20Token = 'DummyERC20Token', - EtherToken = 'WETH9', - AssetProxyOwner = 'AssetProxyOwner', - AccountLevels = 'AccountLevels', - EtherDelta = 'EtherDelta', - Arbitrage = 'Arbitrage', - TestAssetDataDecoders = 'TestAssetDataDecoders', - TestAssetProxyDispatcher = 'TestAssetProxyDispatcher', - TestLibs = 'TestLibs', - TestSignatureValidator = 'TestSignatureValidator', - ERC20Proxy = 'ERC20Proxy', - ERC721Proxy = 'ERC721Proxy', - DummyERC721Receiver = 'DummyERC721Receiver', - DummyERC721Token = 'DummyERC721Token', - TestLibBytes = 'TestLibBytes', - TestWallet = 'TestWallet', - Authorizable = 'Authorizable', - Whitelist = 'Whitelist', -} - -export interface SignedTransaction { - exchangeAddress: string; - salt: BigNumber; - signerAddress: string; - data: string; - signature: string; -} - -export interface TransferAmountsByMatchOrders { - // Left Maker - amountBoughtByLeftMaker: BigNumber; - amountSoldByLeftMaker: BigNumber; - amountReceivedByLeftMaker: BigNumber; - feePaidByLeftMaker: BigNumber; - // Right Maker - amountBoughtByRightMaker: BigNumber; - amountSoldByRightMaker: BigNumber; - amountReceivedByRightMaker: BigNumber; - feePaidByRightMaker: BigNumber; - // Taker - amountReceivedByTaker: BigNumber; - feePaidByTakerLeft: BigNumber; - feePaidByTakerRight: BigNumber; - totalFeePaidByTaker: BigNumber; - // Fee Recipients - feeReceivedLeft: BigNumber; - feeReceivedRight: BigNumber; -} - -export interface OrderInfo { - orderStatus: number; - orderHash: string; - orderTakerAssetFilledAmount: BigNumber; -} - -export interface CancelOrder { - order: OrderWithoutExchangeAddress; - takerAssetCancelAmount: BigNumber; -} - -export interface MatchOrder { - left: OrderWithoutExchangeAddress; - right: OrderWithoutExchangeAddress; - leftSignature: string; - rightSignature: string; -} diff --git a/packages/contracts/src/utils/web3_wrapper.ts b/packages/contracts/src/utils/web3_wrapper.ts deleted file mode 100644 index c9d83a02d..000000000 --- a/packages/contracts/src/utils/web3_wrapper.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { devConstants, env, EnvVars, web3Factory } from '@0xproject/dev-utils'; -import { prependSubprovider } from '@0xproject/subproviders'; -import { logUtils } from '@0xproject/utils'; -import { Web3Wrapper } from '@0xproject/web3-wrapper'; -import * as _ from 'lodash'; - -import { coverage } from './coverage'; -import { profiler } from './profiler'; -import { revertTrace } from './revert_trace'; - -enum ProviderType { - Ganache = 'ganache', - Geth = 'geth', -} - -let testProvider: ProviderType; -switch (process.env.TEST_PROVIDER) { - case undefined: - testProvider = ProviderType.Ganache; - break; - case 'ganache': - testProvider = ProviderType.Ganache; - break; - case 'geth': - testProvider = ProviderType.Geth; - break; - default: - throw new Error(`Unknown TEST_PROVIDER: ${process.env.TEST_PROVIDER}`); -} - -const ganacheTxDefaults = { - from: devConstants.TESTRPC_FIRST_ADDRESS, - gas: devConstants.GAS_LIMIT, -}; -const gethTxDefaults = { - from: devConstants.TESTRPC_FIRST_ADDRESS, -}; -export const txDefaults = testProvider === ProviderType.Ganache ? ganacheTxDefaults : gethTxDefaults; - -const gethConfigs = { - shouldUseInProcessGanache: false, - rpcUrl: 'http://localhost:8501', - shouldUseFakeGasEstimate: false, -}; -const ganacheConfigs = { - shouldUseInProcessGanache: true, -}; -const providerConfigs = testProvider === ProviderType.Ganache ? ganacheConfigs : gethConfigs; - -export const provider = web3Factory.getRpcProvider(providerConfigs); -const isCoverageEnabled = env.parseBoolean(EnvVars.SolidityCoverage); -const isProfilerEnabled = env.parseBoolean(EnvVars.SolidityProfiler); -const isRevertTraceEnabled = env.parseBoolean(EnvVars.SolidityRevertTrace); -const enabledSubproviderCount = _.filter([isCoverageEnabled, isProfilerEnabled, isRevertTraceEnabled], _.identity) - .length; -if (enabledSubproviderCount > 1) { - throw new Error(`Only one of coverage, profiler, or revert trace subproviders can be enabled at a time`); -} -if (isCoverageEnabled) { - const coverageSubprovider = coverage.getCoverageSubproviderSingleton(); - prependSubprovider(provider, coverageSubprovider); -} -if (isProfilerEnabled) { - if (testProvider === ProviderType.Ganache) { - logUtils.warn( - "Gas costs in Ganache traces are incorrect and we don't recommend using it for profiling. Please switch to Geth", - ); - process.exit(1); - } - const profilerSubprovider = profiler.getProfilerSubproviderSingleton(); - logUtils.log( - "By default profilerSubprovider is stopped so that you don't get noise from setup code. Don't forget to start it before the code you want to profile and stop it afterwards", - ); - profilerSubprovider.stop(); - prependSubprovider(provider, profilerSubprovider); -} -if (isRevertTraceEnabled) { - const revertTraceSubprovider = revertTrace.getRevertTraceSubproviderSingleton(); - prependSubprovider(provider, revertTraceSubprovider); -} - -export const web3Wrapper = new Web3Wrapper(provider); |