Compare commits

...

510 Commits

Author SHA1 Message Date
Jacob Evans
1166b43946 Publish
- @0x/contracts-asset-proxy@2.3.0-beta.3
 - @0x/contracts-coordinator@2.1.0-beta.3
 - @0x/contracts-dev-utils@0.1.0-beta.3
 - @0x/contracts-erc1155@1.2.0-beta.3
 - @0x/contracts-erc20@2.3.0-beta.3
 - @0x/contracts-erc721@2.2.0-beta.3
 - @0x/contracts-exchange-forwarder@3.1.0-beta.3
 - @0x/contracts-exchange-libs@3.1.0-beta.3
 - @0x/contracts-exchange@2.2.0-beta.3
 - @0x/contracts-extensions@4.1.0-beta.3
 - @0x/contracts-integrations@1.0.3-beta.1
 - @0x/contracts-multisig@3.2.0-beta.3
 - @0x/contracts-staking@1.1.0-beta.3
 - @0x/contracts-test-utils@3.2.0-beta.3
 - @0x/contracts-tests@0.0.4
 - @0x/contracts-utils@3.3.0-beta.3
 - 0x.js@8.0.0-beta.2
 - @0x/abi-gen-wrappers@5.4.0-beta.3
 - @0x/abi-gen@4.4.0-beta.3
 - @0x/asset-buyer@6.2.0-beta.3
 - @0x/asset-swapper@2.1.0-beta.3
 - @0x/base-contract@5.5.0-beta.3
 - @0x/contract-addresses@3.3.0-beta.4
 - @0x/contract-wrappers@12.2.0-beta.3
 - @0x/contracts-gen@1.1.0-beta.3
 - @0x/dev-utils@2.4.0-beta.3
 - @0x/instant@1.0.35
 - @0x/migrations@4.4.0-beta.3
 - @0x/monorepo-scripts@1.0.41
 - @0x/order-utils@8.5.0-beta.3
 - @0x/orderbook@0.1.0-beta.3
 - @0x/sol-compiler@3.2.0-beta.3
 - @0x/sol-coverage@3.1.0-beta.3
 - @0x/sol-doc@2.1.0-beta.3
 - @0x/sol-profiler@3.2.0-beta.3
 - @0x/sol-trace@2.1.0-beta.3
 - @0x/sol-tracing-utils@6.1.0-beta.3
2019-11-20 19:34:17 +11:00
Jacob Evans
0a6903c4c3 Updated CHANGELOGS & MD docs 2019-11-20 19:33:49 +11:00
Jacob Evans
62fae9af93 All modified CHANGELOGS are beta 2019-11-20 19:16:55 +11:00
James Towle
509a1c2eb5 Merge pull request #2328 from 0xProject/refactor/integrations/match-orders
Match Orders Integration tests
2019-11-19 16:40:52 -08:00
David Sun
8b94bbbc5e Merge pull request #2350 from 0xProject/fix/asset-swapper/rebase-and-pay-protocol-fees
asset-swapper V3 rebase, pay protocol fees, etc.
2019-11-19 16:40:15 -05:00
Alex Towle
bb923d2b7d Addressed more review feedback and fixed a bug in Actor 2019-11-19 13:03:18 -08:00
Lawrence Forman
38adc72954 @0x/asset-swapper: Remove redundant protocol fee calculation. 2019-11-19 15:11:27 -05:00
Lawrence Forman
362c7c57fa @0x/monorepo-scripts: Add Set to EXTERNAL_TYPE_MAP. 2019-11-19 14:49:38 -05:00
Lawrence Forman
6529b7eebf @0x/asset-swapper: Fix static test errors. 2019-11-19 14:49:38 -05:00
Lawrence Forman
439c98a6e5 @0x/asset-swapper: Rebase against development and pay protocol fees. 2019-11-19 14:49:38 -05:00
Lawrence Forman
32258ef666 @0x/migrations: Deploy Forwarder AFTER hooking up staking. 2019-11-19 14:49:38 -05:00
Amir Bandeali
176e088d4e Merge pull request #2349 from 0xProject/feat/3.0/migrations-patch
Redeploy 3.0 contracts
2019-11-19 07:57:24 -08:00
Alex Towle
4fe57ba025 @0x:contracts-integrations Addressed review comments 2019-11-18 17:56:07 -08:00
Alex Towle
2818e56932 @0x:contracts-integrations Addressed some lingering review comments 2019-11-18 17:56:07 -08:00
Alex Towle
5428a19617 @0x:contracts-integrations Fixed naming collision of fee recipients 2019-11-18 17:56:07 -08:00
Alex Towle
b58cbca61a @0x:contracts-integrations Addressed review feedback 2019-11-18 17:56:07 -08:00
Alex Towle
5fc6a03784 @0x:contracts-integrations Reduced reliance on DevUtils even more 2019-11-18 17:56:07 -08:00
Alex Towle
eb4ad0ba1b @0x:contracts-integrations Reduced reliance on devUtils 2019-11-18 17:56:07 -08:00
Alex Towle
72cdd1ea50 @0x:contracts-integrations Removed dependence on number_utils from staking 2019-11-18 17:56:07 -08:00
Alex Towle
18769f0b8f @0x:contracts-integrations Fixed issues after rebase 2019-11-18 17:56:07 -08:00
Alex Towle
b7d92c3c12 @0x:contracts-integrations Added tests with protocol fees for batch order matching 2019-11-18 17:56:07 -08:00
Alex Towle
b976101dca @0x:contracts-integrations Refactored match_orders_test to handle weth fees for matchOrdersWithMaximalFill 2019-11-18 17:56:07 -08:00
Alex Towle
8943b670a4 @0x:contracts-integrations Refactored match_order_test to do some testing with Weth protocol fees 2019-11-18 17:56:07 -08:00
Alex Towle
c92ff7c622 @0x:contracts-integrations Polished up match order tester 2019-11-18 17:56:07 -08:00
Alex Towle
301b5e1721 @0x:contracts-integrations Added a sanity check for different token types 2019-11-18 17:56:07 -08:00
Alex Towle
4e50b9b479 @0x:contracts-integrations Refactored match_orders_test 2019-11-18 17:56:07 -08:00
Alex Towle
f8b7b8cc28 @0x:contracts-integrations Made an initial refactor of MatchOrderTester 2019-11-18 17:56:07 -08:00
Alex Towle
2a6ea74be7 @0x:contracts-integrations Moved matchOrders into integrations 2019-11-18 17:56:06 -08:00
Jacob Evans
6d6a0c12cd Merge pull request #2343 from 0xProject/optimize/refactor-templates
abi-gen-wrappers: Move shared logic into BaseContract
2019-11-19 11:53:30 +10:00
Amir Bandeali
784a03300a Update CHANGELOGs 2019-11-18 16:10:54 -08:00
Amir Bandeali
392f578567 Make timelock configs synchronous 2019-11-18 16:10:54 -08:00
Amir Bandeali
a91b1d2dd2 Update mainnet ZrxVault in MixinDeploymentConstants 2019-11-18 16:10:54 -08:00
Amir Bandeali
400b3d961e Fix custom timelock config 2019-11-18 16:10:54 -08:00
Amir Bandeali
4f128470bd Update addresses for all networks 2019-11-18 16:10:54 -08:00
Amir Bandeali
fe06f41136 Add UniswapBridge and Eth2DaiBridge deployments to testnet migration script 2019-11-18 16:10:54 -08:00
Amir Bandeali
f81a99565e Update staking logic contract address, add UniswapBridge and Eth2DaiBridge addresses 2019-11-18 16:10:54 -08:00
Jacob Evans
81e146650b Merge branch 'development' into optimize/refactor-templates 2019-11-19 10:07:46 +10:00
Jacob Evans
bd4e04d331 Update mesh-rpc-client to 7.0.4-beta-0xv3 2019-11-19 09:55:48 +10:00
Fabio B
7663d2c64b Merge pull request #2347 from 0xProject/refactor/supportDocsForContractPackages
docs: Generate MD docs for contracts-* packages and a few others
2019-11-18 23:54:24 +00:00
fabioberger
443c3c2802 Add missing export from stakiong 2019-11-19 00:02:43 +01:00
fabioberger
17a546af5d Add more exessive type ignores 2019-11-18 23:42:45 +01:00
fabioberger
71faf46735 Add exception for EnvVars because we use it in a lot of places 2019-11-18 23:04:15 +01:00
fabioberger
ac28744df6 Stop exporting types from integrations package 2019-11-18 23:00:16 +01:00
fabioberger
adaf304b4e Add missing staking exports 2019-11-18 22:44:48 +01:00
fabioberger
16b13f9768 Fix exports from exchange 2019-11-18 22:32:47 +01:00
fabioberger
d64bf98dc0 Update mesh dep 2019-11-18 22:21:24 +01:00
Jacob Evans
71f57d13fa Update Wrappers after rebase 2019-11-18 20:43:44 +10:00
Jacob Evans
469c10e45f Fix Rich Error test bind context 2019-11-18 20:37:27 +10:00
Jacob Evans
62def596af Reuse getABIEncodedTransactionData 2019-11-18 20:37:27 +10:00
Jacob Evans
aa10844d9e Remove Lodash as a dependency in BaseContract 2019-11-18 20:37:27 +10:00
Jacob Evans
be52079182 Re-enable estimateGas in sendTransaction 2019-11-18 20:37:27 +10:00
Jacob Evans
255aca8789 Moved shared logic into BaseContract
Shared validation and default application can be moved into BaseContract

Assignment before return can be skipped here as it saves a line and
makes a dramatic difference.

Store the functionSignature once and reuse, this saving is large for
Exchange functions with order tuples.
2019-11-18 20:35:38 +10:00
fabioberger
117f4a282d Add EnvVars type 2019-11-18 10:29:25 +00:00
fabioberger
e1ea65525f Add doc generation to several more packages and fix up their index.ts files so all public interface types are exported 2019-11-18 10:29:25 +00:00
fabioberger
d0a3495b5f Refactor docgen command to also support generating docs for contracts-* packages 2019-11-18 10:24:48 +00:00
xianny
9e9e0d6592 Publish
- @0x/contracts-asset-proxy@2.3.0-beta.2
 - @0x/contracts-coordinator@2.1.0-beta.2
 - @0x/contracts-dev-utils@0.1.0-beta.2
 - @0x/contracts-erc1155@1.2.0-beta.2
 - @0x/contracts-erc20@2.3.0-beta.2
 - @0x/contracts-erc721@2.2.0-beta.2
 - @0x/contracts-exchange-forwarder@3.1.0-beta.2
 - @0x/contracts-exchange-libs@3.1.0-beta.2
 - @0x/contracts-exchange@2.2.0-beta.2
 - @0x/contracts-extensions@4.1.0-beta.2
 - @0x/contracts-integrations@1.0.2
 - @0x/contracts-multisig@3.2.0-beta.2
 - @0x/contracts-staking@1.1.0-beta.2
 - @0x/contracts-test-utils@3.2.0-beta.2
 - @0x/contracts-tests@0.0.3
 - @0x/contracts-utils@3.3.0-beta.2
 - 0x.js@8.0.0-beta.1
 - @0x/abi-gen-wrappers@5.4.0-beta.2
 - @0x/abi-gen@4.4.0-beta.2
 - @0x/assert@2.2.0-beta.2
 - @0x/asset-buyer@6.2.0-beta.2
 - @0x/asset-swapper@2.1.0-beta.2
 - @0x/base-contract@5.5.0-beta.2
 - @0x/connect@5.1.0-beta.2
 - @0x/contract-addresses@3.3.0-beta.3
 - @0x/contract-artifacts@2.3.0-beta.3
 - @0x/contract-wrappers@12.2.0-beta.2
 - @0x/contracts-gen@1.1.0-beta.2
 - @0x/dev-utils@2.4.0-beta.2
 - ethereum-types@2.2.0-beta.2
 - @0x/instant@1.0.34
 - @0x/json-schemas@4.1.0-beta.2
 - @0x/migrations@4.4.0-beta.2
 - @0x/monorepo-scripts@1.0.40
 - @0x/order-utils@8.5.0-beta.2
 - @0x/orderbook@0.1.0-beta.2
 - @0x/sol-compiler@3.2.0-beta.2
 - @0x/sol-coverage@3.1.0-beta.2
 - @0x/sol-doc@2.1.0-beta.2
 - @0x/sol-profiler@3.2.0-beta.2
 - @0x/sol-resolver@2.1.0-beta.2
 - @0x/sol-trace@2.1.0-beta.2
 - @0x/sol-tracing-utils@6.1.0-beta.2
 - @0x/sra-spec@2.1.0-beta.2
 - @0x/subproviders@5.1.0-beta.2
 - @0x/tslint-config@3.1.0-beta.2
 - @0x/types@2.5.0-beta.2
 - @0x/typescript-typings@4.4.0-beta.2
 - @0x/utils@4.6.0-beta.2
 - @0x/web3-wrapper@6.1.0-beta.2
2019-11-17 18:03:29 -05:00
xianny
cb5f9ba97d Updated CHANGELOGS & MD docs 2019-11-17 18:03:13 -05:00
xianny
34538f2ced prettier 2019-11-17 17:14:28 -05:00
xianny
2575644920 update CHANGELOG.json for beta publish 2019-11-17 17:11:35 -05:00
Greg Hysz
b4b43a9e9e Updated Coordinator wrappers and artifacts (#2346)
* Updated Coordinator wrappers and artifacts

* Use contracts-coordinator package for Coordinator

* disable custom CoordinatorWrapper

* trim disallowed artifact fields; fix exports for docs; lint
2019-11-16 19:22:22 -05:00
F. Eugene Aumson
df97b20913 abi-gen/Py: fix incorrect method return types and other small issues (#2345)
* .gitignore gen'd Python staking contract wrappers

* abi-gen/test-cli: check Python type hints in lint

* sra_client.py: Update doc for replicating examples

* abi-gen/Py: fix call() return type incl. tx hash

Previously, generated wrappers for contract methods were including type
hints that suggested that a call() (as opposed to a send_transaction())
might return either the underlying return type or a transaction hash.
This doesn't make sense because a call() will never return a TX hash.
Now, the type hint just has the return type of the underlying method.

* abi-gen: fix test_cli:lint checking wrong code

test_cli:lint is meant to be a rudimentary test of the code generated by
abi-gen.  However, previously, this script was incorporated into `yarn
lint`, and in CircleCI `static-tests` runs independently of `build`.
Consequently, the runs of test_cli:lint were checking the OLD code,
which was previously generated and checked in to git, NOT the code
generated with the version of abi-gen represented by the git repo.  Now,
test_cli:lint happens during `yarn test` rather than `yarn lint`,
because `yarn test` IS dependent on `yarn build`.

* contract_wrappers.py: fix misplaced doc

Previously, the routines `order_to_jsdict()` and `jsdict_to_order()`
were moved from contract_wrappers.exchange.types to
contract_wrappers.order_conversions.  However, the module-level
docstring describing those routines was accidentally left behind in
exchange.types.

* abi-gen/Py: stop documenting return types for TXs

Previously the send_transaction() interface included docstring
documentation for the return types of the contract method, but that
doesn't make any sense because send_transaction() returns a transaction
hash rather than any actual return values.

* abi-gen/Py: stop gen'ing send_tx for const methods

* abi-gen/Py: add build_tx to contract methods

* abi-gen/Py: fix incorrect method return types

Fixes #2298 .

* abi-gen/Py: rm validator arg to no-input methods

* abi-gen: mv Py Handlebars helpers to own module

Move all existing Python-related Handlebars helpers to the newly created
python_handlebars_helpers module.

* abi-gen: refactor internal interface

No functionality is changed.  Sole purpose of this commit is to
facilitate an upcoming commit.

* abi-gen: refactor internal interface

No functionality is changed.  Sole purpose of this commit is to
facilitate an upcoming commit.

* abi-gen/Py: name tuples w/internalType, not hash

Use the new `internalType` field on the `DataItem`s in the contract
artifact to give generated tuple classes a better name than just hashing
their component field names.

* Fix CI errors

* abi-gen/Py/wrapper: make internal member private

* Update CHANGELOGs
2019-11-15 18:27:45 -05:00
mzhu25
9e3cc379ed Merge pull request #2335 from 0xProject/refactor/integrations/move-balance-stores
`@0x/contracts-integrations`: Restructure directories, welcome core.ts and balance stores
2019-11-15 11:10:02 -08:00
Michael Zhu
c1d78a94a2 move ValidatorWalletAction to signature_validator.ts 2019-11-15 09:53:06 -08:00
Michael Zhu
7f4cbba076 Refactor integrations directory structure; move core.ts, balance stores, and FillOrderWrapper to integrations 2019-11-15 09:49:20 -08:00
Fabio B
bdca84fe72 Merge pull request #2342 from 0xProject/update/bigNumberDep
Update BigNumber dep to ~9.0.0
2019-11-15 11:53:47 +00:00
fabioberger
cf8fd7103b Add changelog entry re: BigNumber version change in packages that export BigNumber 2019-11-15 11:11:08 +00:00
fabioberger
8e8cdbd413 Update BigNumber dep to ~9.0.0 2019-11-15 11:04:53 +00:00
Jacob Evans
30f01681d4 Merge pull request #2341 from 0xProject/fix/parity-revert-errors
RevertError: Decode Parity revert errors
2019-11-15 20:31:40 +10:00
Fabio B
ecf1ad8da1 Merge pull request #2340 from 0xProject/fix/ciPublish
Fix CI test-publish
2019-11-15 10:23:28 +00:00
Jacob Evans
42dc112a13 RevertError: Decode Parity revert errors 2019-11-15 19:39:06 +10:00
Jacob Evans
58276cefce Merge pull request #2323 from 0xProject/feat/3.0-staking-ganache
ganache: Added Staking, Forwarder, ERC20Bridge
2019-11-15 13:05:37 +10:00
Amir Bandeali
4b6501a739 Merge pull request #2338 from 0xProject/fix/contracts/exchange/marketBuyOrdersNoThrow-rounding
Round up in `marketBuyOrdersNoThrow()`
2019-11-14 18:57:29 -08:00
Jacob Evans
724085e068 Remove TestStaking
CHANGELOG updates
Rebase and clean imports
Fix lint
2019-11-15 12:34:41 +10:00
Jacob Evans
21fab3ef9f Added Staking and ERC20 Bridge to migrations 2019-11-15 11:38:43 +10:00
Amir Bandeali
db8837f4ce Redeploy DevUtils and ZeroExGovernor on testnets 2019-11-15 11:34:31 +10:00
Lawrence Forman
5781cdf6da ran prettier (again) 2019-11-14 18:36:34 -05:00
Lawrence Forman
874eb1602f @0x/contracts-exchange: Round up in marketBuyOrdersNoThrow() so marketBuyOrdersFillOrKill() doesn't throw up. 2019-11-14 17:55:11 -05:00
fabioberger
82149917b7 Update mesh-rpc-client dep to latest version 2019-11-14 22:54:39 +00:00
F. Eugene Aumson
f11d8a5bd8 @0x/order-utils refactors for v3: orderParsingUtils, signatureUtils, orderHashUtils, RevertErrors, transactionHashUtils (#2321)
* move orderParsingUtils from order-utils to connect

* Remove many functions from signatureUtils

Removed from the exported object, that is.  All of them are used in
other existing code, so they were all moved to be as local to their
usage as possible.

* remove orderHashUtils.isValidOrderHash()

* Move all *RevertErrors from order-utils...

...into their respective @0x/contracts- packages.

* Refactor @0x/order-utils' orderHashUtils away

- Move existing routines into @0x/contracts-test-utils

- Migrate non-contract-test callers to a newly-exposed getOrderHash()
method in DevUtils.

* Move all *RevertErrors from @0x/utils...

...into their respective @0x/contracts- packages.

* rm transactionHashUtils.isValidTransactionHash()

* DevUtils.sol: Fail yarn test if too big to deploy

* Refactor @0x/order-utils transactionHashUtils away

- Move existing routines into @0x/contracts-test-utils

- Migrate non-contract-test callers to a newly-exposed
getTransactionHash() method in DevUtils.

* Consolidate `Removed export...` CHANGELOG entries

* Rm EthBalanceChecker from devutils wrapper exports

* Stop importing from '.' or '.../src'

* fix builds

* fix prettier; dangling promise

* increase max bundle size
2019-11-14 17:14:24 -05:00
Xianny
f0d7d10fe7 update abi-gen with new method interfaces (#2325)
* update abi-gen with new method interfaces

* wip: get all packages to build

* wip: get all packages to build

* Fix two contract wrapper calls

* Export necessary types part of the contract wrapper public interfaces

* Revive and fix wrapper_unit_tests

* Remove duplicate type

* Fix lib_exchange_rich_error_decoder tests

* Fix remaining test failures in contracts-* packages

* Prettier fixes

* remove transactionHelper

* lint and update changelogs

* Fix prettier

* Revert changes to reference docs

* Add back changelog already published and add revert changelog entry

* Add missing CHANGELOG entries

* Add missing comma

* Update mesh-rpc-client dep

* Update Mesh RPC logic in @0x/orderbook to v6.0.1-beta

* Align package versions
2019-11-14 11:22:29 -05:00
Fabio B
9d4d9ce978 Merge pull request #2337 from 0xProject/refactor/0xjsInterfaceAndDocs
Remove IWallet/IValidator from 0x.js & update doc gen
2019-11-14 15:38:04 +00:00
fabioberger
96a38602b8 Fix package.json 2019-11-14 14:57:11 +00:00
fabioberger
90d3558d31 Add CHANGELOG entry 2019-11-14 14:56:35 +00:00
fabioberger
e491a56dd0 Remove IValidator and IWallet contracts from 0x.js interface since no beginner uses them 2019-11-14 14:53:26 +00:00
fabioberger
4d8eb61924 Stop generating and uploading docs for asset-buyer since about to get removed 2019-11-14 14:51:44 +00:00
fabioberger
17fab541c6 Stop pushing ethereum-types and web3-wrapper docs to S3 since we no longer want to render them on the website 2019-11-14 14:49:55 +00:00
Amir Bandeali
91de35e8e9 Merge pull request #2333 from 0xProject/fix/staking/operator-share
Fix 100% operator share
2019-11-13 10:17:28 -08:00
Amir Bandeali
f61964676a Add test for when operatorShare == 0 2019-11-13 09:48:04 -08:00
Amir Bandeali
41a34c19bb Add zrxVault config tests in migrations 2019-11-13 09:46:33 -08:00
Amir Bandeali
d90810d127 Add tests for setting operator share to 100% 2019-11-12 22:42:55 -08:00
Amir Bandeali
7f3d281faa Allow operator share to be set to existing share 2019-11-12 20:14:48 -08:00
Greg Hysz
812c306805 Merge pull request #2332 from 0xProject/fix/staking/paramDocsForRewardsPaidOutEvent
Updated `RewardsPaid` event docs
2019-11-12 17:47:47 -08:00
Steve Klebanoff
fc1c59f374 Merge pull request #2329 from 0xProject/feature/debug-subprovider
Add DebugSubprovider
2019-11-12 15:18:00 -08:00
Amir Bandeali
35eac1e3ff Merge pull request #2322 from 0xProject/feat/3.0-mainnet-migrations
Mainnet migrations
2019-11-12 14:50:36 -08:00
Greg Hysen
e16041d7fa Updated RewardsPaid event docs 2019-11-12 14:24:39 -08:00
Amir Bandeali
b8fc84ecc8 Remove test constants from Staking ABI 2019-11-12 13:53:58 -08:00
Amir Bandeali
572c576e15 Update DevUtils addresses on all networks 2019-11-12 13:53:58 -08:00
Amir Bandeali
9df7f80fbb Move extension deployments after contract configurations 2019-11-12 13:53:58 -08:00
Amir Bandeali
f003400135 Add check for if ERC20BridgeProxy is registered in the Exchange 2019-11-12 13:53:58 -08:00
Amir Bandeali
ca7616c1d2 Update CHANGELOGs 2019-11-12 13:53:58 -08:00
Amir Bandeali
a4a2bfdf35 Finish ZrxVault and StakingProxy configs without batch transaction 2019-11-12 13:53:58 -08:00
Amir Bandeali
eb6bbb6e78 Replace Staking artifact with TestStaking to allow params to be passed into constructor 2019-11-12 13:53:58 -08:00
Amir Bandeali
4d0172f634 Fix directory to write standard input 2019-11-12 13:53:58 -08:00
Amir Bandeali
3b61e0e126 Add v3 mainnet addresses 2019-11-12 13:53:58 -08:00
Amir Bandeali
1540a91835 Update testnet migrations to do most configuration outside of batch transsaction 2019-11-12 13:53:58 -08:00
Amir Bandeali
2bcce9eed0 Add mainnet ZrxVault address to deployment constants 2019-11-12 13:53:58 -08:00
Amir Bandeali
1e53564386 Redeploy DevUtils and ZeroExGovernor on testnets 2019-11-12 13:53:58 -08:00
Amir Bandeali
d1c72706ef Add governor and staking configs for each network 2019-11-12 13:53:58 -08:00
Amir Bandeali
bd9e531257 Add flag for saving standard input during compilation 2019-11-12 13:53:58 -08:00
mzhu25
48436424db Merge pull request #2317 from 0xProject/feature/integration-tests/hot-fuzz
`@0x/contracts-integrations`: Pool management, stake management fuzz tests
2019-11-12 13:43:19 -08:00
Michael Zhu
4f10d7f859 post-rebase woes 2019-11-12 13:10:34 -08:00
Francesco Agosti
80e5a29444 Merge pull request #2326 from 0xProject/feature/remove_network_id_from_sra
Remove chainId from @0x/connect related tooling
2019-11-12 13:08:25 -08:00
F. Eugene Aumson
0ec8a4a160 sra_client.py: remove support for chainId parameter 2019-11-12 15:28:11 -05:00
F. Eugene Aumson
810bf7af0c Merge branch 'development' into feature/remove_network_id_from_sra 2019-11-12 15:26:00 -05:00
Michael Zhu
e7825206bf asyncIterator polyfill 2019-11-12 12:06:01 -08:00
Michael Zhu
2b887c336a devutils 😕 2019-11-12 12:05:39 -08:00
Michael Zhu
48ecd32d5d address comments 2019-11-12 12:05:39 -08:00
Michael Zhu
1f5a0987cb static tests, my nemesis 2019-11-12 12:05:39 -08:00
Michael Zhu
f33a9d162a moveStake assertion; use SimulationEnvironment to track global stake and staking pools 2019-11-12 12:05:38 -08:00
Michael Zhu
c2919bcdb0 tslint needs to _chill_ 2019-11-12 12:05:38 -08:00
Michael Zhu
120d554a6b split up pool/stake management simulations, change some types 2019-11-12 12:05:38 -08:00
Michael Zhu
44f268a7ee decouple state (SimulationEnvironment) and Simulation 2019-11-12 12:05:38 -08:00
Michael Zhu
3c7a0bcd85 add createStakingPool and decreaseStakingPoolOperatorShare 2019-11-12 12:05:14 -08:00
Michael Zhu
8e2e9e9331 proof of concept with a single actor and valid stakes/unstakes 2019-11-12 12:05:14 -08:00
Michael Zhu
91c26fc046 rename Result -> FunctionResult 2019-11-12 12:02:49 -08:00
Fabio B
afcfe58add Merge pull request #2330 from 0xProject/refactor/reduceContractPkgBundle
Reduce bundle-size of contracts-* packages
2019-11-13 04:00:05 +08:00
Steve Klebanoff
8d423be223 Use strings instead of bignumbers, and add JSON.stringify call 2019-11-12 11:30:24 -08:00
fabioberger
03b7314550 Disable linter for txn returning PromiseWithTransactionHash 2019-11-12 19:24:29 +00:00
fragosti
1a7e425780 Run linters 2019-11-12 11:18:23 -08:00
fabioberger
8bc5faff3c Move DeploymentManager back into test dir since only used in integrations package 2019-11-12 16:55:36 +00:00
Fabio B
2676278a66 Merge pull request #1990 from 0xProject/removeTestnetFaucet
Remove testnet-faucet from monorepo
2019-11-12 22:23:51 +08:00
fabioberger
6376b3baf3 Update yarn.lock 2019-11-12 13:50:24 +00:00
fabioberger
e569abe740 Update yarn.lock 2019-11-12 13:50:10 +00:00
fabioberger
71be9ef92a Update yarn.lock 2019-11-12 13:50:10 +00:00
fabioberger
4990c4903d Remove testnet-faucet from monorepo 2019-11-12 13:49:38 +00:00
fabioberger
9d468e2383 Move dep back since used in types 2019-11-12 13:05:25 +00:00
fabioberger
109cac013c Add CHANGELOG entries 2019-11-12 13:04:26 +00:00
fabioberger
0d8a9921cd Fix package.json 2019-11-12 12:33:09 +00:00
fabioberger
2a5f5f7312 Move deps to devDeps not used in src dir 2019-11-12 12:27:21 +00:00
fabioberger
fe54fbefbb Improve comment in npmignores 2019-11-12 11:47:11 +00:00
fabioberger
fc824b8d06 Fix prettier issues 2019-11-12 11:35:34 +00:00
fabioberger
d91a7b6d0e Add generate-artifacts and generated-wrappers nested under test dir to prettierignore 2019-11-12 11:35:28 +00:00
fabioberger
aa4b3f93fa Add ERC20 artifacts explicitly to TransactionHelper 2019-11-12 11:27:41 +00:00
fabioberger
efe8225d18 Fix import ordering 2019-11-12 10:52:04 +00:00
fabioberger
b2c0f8c158 Fix .prettierrc to proper json 2019-11-12 10:45:20 +00:00
fabioberger
66dce8794d Add missing dep 2019-11-12 10:45:08 +00:00
fabioberger
30d54407e6 Fix remaining imports 2019-11-12 10:13:25 +00:00
fabioberger
6324a92ec5 Refactor contracts-* exports so none in test dir so npmignore works as intended 2019-11-11 21:49:29 +00:00
fabioberger
67e7b5c124 Merge branch 'development' into refactor/reduceContractPkgBundle 2019-11-11 21:00:36 +00:00
Fabio B
35099d9b2f Merge pull request #2324 from 0xProject/refactor/removeUnusedContractWrappers
Remove unused contract wrappers
2019-11-12 04:59:18 +08:00
fabioberger
e07f7b54e0 Stop using directory level exports 2019-11-11 19:50:13 +00:00
fabioberger
5c409929b4 Remove ethBalanceChecker dir 2019-11-11 19:29:47 +00:00
fabioberger
1a504fdde9 Remove last references of eth_balance_checker in python tooling 2019-11-11 19:01:04 +00:00
fabioberger
4b06fd511b Uniform dep version 2019-11-11 18:18:02 +00:00
fabioberger
def6727286 Remove EthBalanceChecker from Python lib 2019-11-11 18:17:26 +00:00
fabioberger
bedaa0db16 Fix deps 2019-11-11 17:54:57 +00:00
fabioberger
90640a4fcf Fix linter 2019-11-11 17:53:07 +00:00
fabioberger
0142d07f10 Fix linter 2019-11-11 17:53:07 +00:00
fabioberger
c9d85cfc7d Remove EthBalanceChecker as standalone contract artifact/wrapper 2019-11-11 17:53:07 +00:00
fabioberger
64304c1991 Bump dummyTransactionCount to 6 to avoide changing all contract addresses now that we don't deploy DutchAuction anymore 2019-11-11 17:53:07 +00:00
fabioberger
993adc3578 Pass down DevUtils to fillOrder combinatorial tests 2019-11-11 17:53:07 +00:00
fabioberger
8813bd26f6 Pass around DevUtilsContract so it's only instantiated once 2019-11-11 17:53:07 +00:00
fabioberger
35925de320 Update CHANGELOGs 2019-11-11 17:53:07 +00:00
fabioberger
3b426a3f07 Update migration to continue deploying the old coordinator contract 2019-11-11 17:53:07 +00:00
fabioberger
5104fd5dcf Remove unused import 2019-11-11 17:53:07 +00:00
fabioberger
a5a9ca9e46 Deploy OrderValidator _not_ OrderValidationUtils in migrations script 2019-11-11 17:53:07 +00:00
fabioberger
ba0f07e3b2 Fix prettier issues 2019-11-11 17:52:32 +00:00
fabioberger
8614475324 Move TradeSide and TransferType types to contract-exchange package 2019-11-11 17:52:32 +00:00
fabioberger
744dda144b Remove unused types from order-utils export 2019-11-11 17:52:32 +00:00
fabioberger
13d47915f4 Fix linter issues 2019-11-11 17:52:32 +00:00
fabioberger
3059b85e41 Remove ZRX exports from 0x.js too 2019-11-11 17:52:32 +00:00
fabioberger
184ea4a67f Remove ZRXToken related exports 2019-11-11 17:52:32 +00:00
fabioberger
8032f536ed Add caret to version 2019-11-11 17:52:32 +00:00
fabioberger
fba3870ef1 Move ExchangeTransferSimulator into contract-exchange tests since that's the only place it's still used and we no longer want to expose it to external developers 2019-11-11 17:50:48 +00:00
fabioberger
2915ee08ea Remove ZRXToken, AssetProxies and DutchAuction contract from abi-gen-wrappers and contract-wrappers packages 2019-11-11 17:50:01 +00:00
fabioberger
86b76a3e75 Introduce publicFacingContracts config in all package.jsons, refactor all imports from src in contracts packages 2019-11-11 15:10:15 +00:00
fabioberger
bc1dca3f6f Fix contracts-gen so make sure all dirs are created 2019-11-11 12:39:36 +00:00
fabioberger
5db1820123 Only export non-test source Solidity source-code 2019-11-11 11:46:03 +00:00
Steve Klebanoff
657c35fb86 Adds CHANGELOG 2019-11-10 22:05:32 -08:00
Steve Klebanoff
9432a84468 Upgrade @types/ethereumjs-tx and add DebugSubprovider 2019-11-10 21:58:50 -08:00
fabioberger
15a5bc02ef Fix remaining build issues 2019-11-11 00:13:44 +00:00
fabioberger
f011be9347 Update all contracts-*is package.json, tsconfig.json, compiler.json, artifacts/ts and wrappers.js 2019-11-10 23:41:56 +00:00
fabioberger
b6094fdb34 Add gitignore for new generted artifacts/wrappers dirs 2019-11-10 17:23:05 +00:00
fabioberger
9e6ab9f585 First pass contracts-* separation of test and publish artifacts/wrappers 2019-11-10 17:22:29 +00:00
F. Eugene Aumson
869d2c02fa CI/test-python: give launch-kit-backend CHAIN_ID, not NETWORK_ID (#2327)
* CI/test-python: give LK ID of chain, not network

For CircleCI job test-python, change docker config for
launch-kit-backend to set an environment variable for the chain ID,
not for the network ID.  This was failing on all branches after a recent
update to the `0xorg/launch-kit-backend:v3` tag.

* Update docker config used for local testing

* Update documentation of test environment
2019-11-09 20:25:14 -05:00
fragosti
3b1dca0e70 Add asset-buyer hack 2019-11-08 17:51:25 -08:00
fragosti
595358fa69 Remove chainId when using connect from asset-swapper 2019-11-08 17:41:26 -08:00
fragosti
8a8ec79c6c Remove chainId from the orderbook pacakge 2019-11-08 16:32:22 -08:00
fragosti
6252446bd3 Update error example in SRA 2019-11-08 16:29:28 -08:00
fragosti
403ceebff9 Remove chainId from json-schemas and connect 2019-11-08 16:09:53 -08:00
fabioberger
4767882ed3 Add .npmignore to all contracts-* packages so we only publish the Solidity source and lib dir (minus tests) 2019-11-08 18:20:47 +00:00
fabioberger
3b9d84fa58 Publish
- @0x/contracts-asset-proxy@2.3.0-beta.1
 - @0x/contracts-coordinator@2.1.0-beta.1
 - @0x/contracts-dev-utils@0.1.0-beta.1
 - @0x/contracts-erc1155@1.2.0-beta.1
 - @0x/contracts-erc20@2.3.0-beta.1
 - @0x/contracts-erc721@2.2.0-beta.1
 - @0x/contracts-exchange-forwarder@3.1.0-beta.1
 - @0x/contracts-exchange-libs@3.1.0-beta.1
 - @0x/contracts-exchange@2.2.0-beta.1
 - @0x/contracts-extensions@4.1.0-beta.1
 - @0x/contracts-integrations@1.0.1
 - @0x/contracts-multisig@3.2.0-beta.1
 - @0x/contracts-staking@1.1.0-beta.1
 - @0x/contracts-test-utils@3.2.0-beta.1
 - @0x/contracts-tests@0.0.2
 - @0x/contracts-utils@3.3.0-beta.1
 - 0x.js@8.0.0-beta.0
 - @0x/abi-gen-wrappers@5.4.0-beta.1
 - @0x/abi-gen@4.4.0-beta.1
 - @0x/assert@2.2.0-beta.1
 - @0x/asset-buyer@6.2.0-beta.1
 - @0x/asset-swapper@2.1.0-beta.1
 - @0x/base-contract@5.5.0-beta.1
 - @0x/connect@5.1.0-beta.1
 - @0x/contract-addresses@3.3.0-beta.2
 - @0x/contract-artifacts@2.3.0-beta.2
 - @0x/contract-wrappers@12.2.0-beta.1
 - @0x/contracts-gen@1.1.0-beta.1
 - @0x/dev-utils@2.4.0-beta.1
 - ethereum-types@2.2.0-beta.1
 - @0x/instant@1.0.33
 - @0x/json-schemas@4.1.0-beta.1
 - @0x/migrations@4.4.0-beta.1
 - @0x/monorepo-scripts@1.0.39
 - @0x/order-utils@8.5.0-beta.1
 - @0x/orderbook@0.1.0-beta.1
 - @0x/sol-compiler@3.2.0-beta.1
 - @0x/sol-coverage@3.1.0-beta.1
 - @0x/sol-doc@2.1.0-beta.1
 - @0x/sol-profiler@3.2.0-beta.1
 - @0x/sol-resolver@2.1.0-beta.1
 - @0x/sol-trace@2.1.0-beta.1
 - @0x/sol-tracing-utils@6.1.0-beta.1
 - @0x/sra-spec@2.1.0-beta.1
 - @0x/subproviders@5.1.0-beta.1
 - @0x/testnet-faucets@1.0.89
 - @0x/tslint-config@3.1.0-beta.1
 - @0x/types@2.5.0-beta.1
 - @0x/typescript-typings@4.4.0-beta.1
 - @0x/utils@4.6.0-beta.1
 - @0x/web3-wrapper@6.1.0-beta.1
2019-11-07 20:43:12 +00:00
fabioberger
6fd96a6fd7 Updated CHANGELOGS & MD docs 2019-11-07 20:42:58 +00:00
fabioberger
c93b02d55e Update DevUtils artifacts in contract-artifacts 2019-11-07 19:33:12 +00:00
fabioberger
568f87d5eb Add CHANGELOG entry about the updated DevUtils contract addresses 2019-11-07 19:24:07 +00:00
fabioberger
49ad0f0d54 Update devUtils contract addresses 2019-11-07 19:22:28 +00:00
fabioberger
0e642f59e1 Fix contract-addresses version in 0x.js 2019-11-07 19:00:26 +00:00
fabioberger
7c5730fb03 Update dep versions that were accidentally published 2019-11-07 18:11:40 +00:00
fabioberger
45f0f755ab Merge branch 'development' of github.com:0xProject/0x-monorepo into development 2019-11-07 18:07:23 +00:00
fabioberger
1ef2913c5b Update all CHANGELOGs to prep for publish 2019-11-07 18:07:15 +00:00
F. Eugene Aumson
fecbf220b6 Remove --serial from monorepo test:contracts (#2320) 2019-11-07 13:03:55 -05:00
fabioberger
17a5f05cf3 Make contract-test package private 2019-11-07 18:02:38 +00:00
Xianny
6a852ab0ed Replace assetDataUtils with DevUtilsContract wherever possible (#2304)
* Replace assetDataUtils with DevUtilsContract wherever possible

Does not replace from @0x/instant and some @0x/order-utils uses

* Add revertIfInvalidAssetData to LibAssetData

This is needed to replace `assetDataUtils.decodeAssetDataOrThrow`.
Because it's used in packages and not only contracts, we should wait
to deploy the updated contract so we can update `@0x/contract-artifacts`,
`@0x/abi-gen-wrappers`, and `@0x/contract-wrappers` first.

* remove usages of signatureUtils

* fix test for  optimised encoding

* refactor @0x/contracts-integrations

* update changelogs

* Move @0x/contracts-dev-utils from devDependencies to dependencies
It is exported as part of the package
2019-11-06 19:40:20 -08:00
Jacob Evans
ec26cff656 Fix contract-addresses CHANGELOG (prettier) 2019-11-07 08:48:48 +11:00
xianny
cdd34a1214 Updated CHANGELOGS & MD docs ONLY for pkgs that made it to npmjs (partial publish) 2019-11-06 12:50:58 -08:00
F. Eugene Aumson
857a4042ef abi-gen: Include templates in published tarball (#2315)
* abi-gen: Include templates in published tarball

* abi-gen: update CHANGELOG

* abi-gen/package.json: explicitly include code

Apparently when you include a "files" section, it by default only
includes the code directly referenced by the package.json.  (For this
package, it was including the lib/src/index.js referenced by "main", and
the bin/abi-gen.js referenced by "bin", but no other *.js files, nor any
*.d.ts files.)
2019-11-06 02:39:35 -05:00
F. Eugene Aumson
f51c80adb2 Change all instances of networkId to chainId (#2313)
* abi-gen/test: recompile contract fixtures for 3.0

It seems this hadn't been done since the merge with the 3.0 branch.

* Sync `monorepo$ yarn test` exclusions to CI config

* sra-spec: correct typo

* contract-wrappers: TODO after coord.-server update

* utils: fix typo in comment

* Refactor networkId to chainId everywhere

* Update CHANGELOGs
2019-11-06 01:18:55 -05:00
F. Eugene Aumson
e61f23d001 Migrate Python libraries to v3 (#2284)
* .gitignore migrations/0x_ganache_snapshot

* .gitignore new-ish Python contract wrappers

These should have been added back when we started generating these
wrappers.

* rm superfluous contract artifact in Python package

All of the contract artifacts were removed from the Python package
recently, because now they're copied from the monorepo/packages area as
an automated build step.  Somehow this one artifact slipped through the
cracks.

* Eliminate circular dependency

This was preventing the Exchange wrapper from ever importing its
validator!

* Improve output of monorepo-level parallel script

- Capture stderr (and have it included in stdout) so that it doesn't
leak onto the console for commands that didn't actually fail.

- Include all error output in the Exception object (eliminate print
statement).

* Silence new versions of linters

Newer versions care about this stuff.  Old versions didn't, and we don't
either.

* Support Rich Reverts via Web3.py middleware

* Fix bug in generated wrappers' bytes handling

`bytes.fromhex(bytes.decode('utf-8')` is just plain wrong.  It would
work for some cases, but is not working when trying to fill orders with
the latest Exchange contract.

* Migrate to Exchange v3

* Fix typo in DevUtils documentation

* Include new contracts in docs

* Re-enable Python checks in CI

* Accept strings for bytes

* Fix CircleCI build artifacts for gen'd python

I swear the previous way was working before, but it wasn't working now,
so this fixes it.

* Accept a provider OR a Web3 object

In various places.  This allows the caller to install middleware (which
in web3.py is installed on a Web3 object, not on a provider) before
executing any RPC calls, which is important for the case where one wants
to produce signatures locally before submitting to a remote node.

* wrapper base: don't assume there are accounts

* Eliminate some inline linter directives

* make CHANGELOGs be REVERSE chronological

* Update CHANGELOG entries and bump version numbers

* @0x/contract-addresses: Put addr's in JSON, not TS

This allows easier consumption by other languages.  (Specifically, it
eliminates the overhead of keeping the Python addresses package in sync
with the TypeScript one.)

* sra_client.py: incl. docker in `./setup.py clean`

* sra_client.py: Migrate to protocol v3

Removed script that existed only to exclude runs of sra_client builds
(parallel_without_sra_client).  Now `parallel` is used by CI,
re-including sra_client in CI checks.

* abi-gen/templates/Py: clarify if/else logic

In response to
https://github.com/0xProject/0x-monorepo/pull/2284#discussion_r342200906

* sra_client.py: Update CHANGELOG and bump version

* contract_addresses/setup.py: rm unnecessary rm

* json_schemas.py: corrections to dev dependencies

* In tests against deployment, also run doctests

* contract_wrappers example: rm xtra Order attribute

Thanks to @steveklebanoff for catching this.
https://github.com/0xProject/0x-monorepo/pull/2284#pullrequestreview-312065368
2019-11-05 23:04:29 -05:00
Greg Hysz
cbe4c4fbf9 Merge pull request #2319 from 0xProject/fix/development/blockTimestampTooLowNonDeterministicBug
Fix development
2019-11-05 17:23:18 -08:00
xianny
deffdabc30 Revert "Updated CHANGELOGS & MD docs"
This reverts commit f65d8cc325.
2019-11-05 17:06:05 -08:00
xianny
8811a5387a Revert "Publish"
This reverts commit 9336d4e545.
2019-11-05 17:05:58 -08:00
xianny
9336d4e545 Publish
- @0x/contracts-asset-proxy@2.3.0-beta.1
 - @0x/contracts-coordinator@2.1.0-beta.1
 - @0x/contracts-dev-utils@0.1.0-beta.1
 - @0x/contracts-erc1155@1.2.0-beta.1
 - @0x/contracts-erc20@2.3.0-beta.1
 - @0x/contracts-erc721@2.2.0-beta.1
 - @0x/contracts-exchange-forwarder@3.1.0-beta.1
 - @0x/contracts-exchange-libs@3.1.0-beta.1
 - @0x/contracts-exchange@2.2.0-beta.1
 - @0x/contracts-extensions@4.1.0-beta.1
 - @0x/contracts-integrations@1.0.1
 - @0x/contracts-multisig@3.2.0-beta.1
 - @0x/contracts-staking@1.1.0-beta.1
 - @0x/contracts-test-utils@3.2.0-beta.1
 - @0x/contracts-tests@0.0.2
 - @0x/contracts-utils@3.3.0-beta.1
 - 0x.js@7.1.0-beta.1
 - @0x/abi-gen-wrappers@5.4.0-beta.1
 - @0x/abi-gen@4.4.0-beta.1
 - @0x/assert@2.2.0-beta.1
 - @0x/asset-buyer@6.2.0-beta.1
 - @0x/asset-swapper@2.1.0-beta.1
 - @0x/base-contract@5.5.0-beta.1
 - @0x/connect@5.1.0-beta.1
 - @0x/contract-addresses@3.3.0-beta.1
 - @0x/contract-artifacts@2.3.0-beta.1
 - @0x/contract-wrappers@12.2.0-beta.1
 - @0x/contracts-gen@1.1.0-beta.1
 - @0x/dev-utils@2.4.0-beta.1
 - ethereum-types@2.2.0-beta.1
 - @0x/instant@1.0.33
 - @0x/json-schemas@4.1.0-beta.1
 - @0x/migrations@4.4.0-beta.1
 - @0x/monorepo-scripts@1.0.39
 - @0x/order-utils@8.5.0-beta.1
 - @0x/orderbook@0.1.0-beta.1
 - @0x/sol-compiler@3.2.0-beta.1
 - @0x/sol-coverage@3.1.0-beta.1
 - @0x/sol-doc@2.1.0-beta.1
 - @0x/sol-profiler@3.2.0-beta.1
 - @0x/sol-resolver@2.1.0-beta.1
 - @0x/sol-trace@2.1.0-beta.1
 - @0x/sol-tracing-utils@6.1.0-beta.1
 - @0x/sra-spec@2.1.0-beta.1
 - @0x/subproviders@5.1.0-beta.1
 - @0x/testnet-faucets@1.0.89
 - @0x/tslint-config@3.1.0-beta.0
 - @0x/types@2.5.0-beta.1
 - @0x/typescript-typings@4.4.0-beta.1
 - @0x/utils@4.6.0-beta.1
 - @0x/web3-wrapper@6.1.0-beta.1
2019-11-05 16:58:14 -08:00
xianny
f65d8cc325 Updated CHANGELOGS & MD docs 2019-11-05 16:58:00 -08:00
Greg Hysen
68656c4083 Fixes intermittent test failure by removing block timestamp contraints from staking scheduler tests 2019-11-05 16:57:37 -08:00
Greg Hysz
44793a9cf9 Merge pull request #2316 from 0xProject/tests/3.0/StakingMixinCumulativeRewardsUnitTEsts
Unit tests for MixinCumulativeRewards
2019-11-05 16:00:52 -08:00
Greg Hysen
2d0ad6f181 Updated staking changelog 2019-11-05 15:32:35 -08:00
Greg Hysen
a7f0717afb Unit tests for MixinCumulativeRewards 2019-11-05 15:32:04 -08:00
Greg Hysz
a9022352e7 Merge pull request #2314 from 0xProject/tests/3.0/MixinSchedulerUnitTests
Unit tests for MixinScheduler
2019-11-05 15:27:20 -08:00
Greg Hysen
9b2231ed24 Improved readability on some tests + updated staking changelog 2019-11-05 14:59:55 -08:00
Greg Hysen
c123200f38 Unit tests for MixinScheduler 2019-11-04 15:44:46 -08:00
James Towle
3c6c4128a6 Merge pull request #2294 from 0xProject/refactor/integration-tests/wrapper-functions
Refactor/integration tests/wrapper functions
2019-11-04 14:46:11 -08:00
Lawrence Forman
47e050cbaf Merge pull request #2312 from 0xProject/feat/contracts/staking/MixinStakingPoolRewards-unit-tests
MixinStakingPoolRewards unit tests
2019-11-04 17:19:03 -05:00
Alex Towle
62d15117c5 @0x:contracts-integrations Removed the dependency on number_utils from staking 2019-11-04 14:16:43 -08:00
Lawrence Forman
fb8360edfd Merge pull request #2311 from 0xProject/fix/contracts/staking/LibFixedMath-overflow-pt-2
Fix `LibFixedMath._mul()` overflow
2019-11-04 12:49:20 -05:00
Alex Towle
e557f2fb48 @0x:contracts-integrations Added decimal.js to dependencies so that number_utils can be used 2019-11-04 09:39:00 -08:00
Lawrence Forman
c957b48281 @0x/contracts-staking: Run prettier. 2019-11-04 11:10:07 -05:00
Lawrence Forman
c15c5e12b0 @0x/contracts-staking: Fix event name collision in MixinStakingPoolRewards unit tests. 2019-11-04 11:09:21 -05:00
Lawrence Forman
15c3c8074c @0x/contracts-staking: Add separate unit tests for withdrawDelegatorRewards() and _withdrawAndSyncDelegatorRewards(). 2019-11-04 10:43:37 -05:00
Lawrence Forman
cba72c811d @0x/contracts-staking: Add _computePoolRewardsSplit() tests to MixinStakingPoolRewards unit tests. 2019-11-04 10:43:37 -05:00
Lawrence Forman
28a2e56003 @0x/contracts-staking: Add more MixinStakingPoolRewards unit tests. 2019-11-04 10:43:37 -05:00
Lawrence Forman
8c4c3d56c6 @0x/contracts-staking: Create MixinStakingPoolRewards unit tests. 2019-11-04 10:43:37 -05:00
Alex Towle
911fcc0bed @0x:contracts-integrations Addressed review comments from @mzhu 2019-11-01 17:16:17 -07:00
Alex Towle
55fd16ccf1 @0x:contracts-integrations Addressed review comments from @dorothy-zbornak 2019-11-01 12:04:24 -07:00
Lawrence Forman
4e05e41f7f Merge pull request #2309 from 0xProject/feat/contracts/utils/LibERC20Token
LibERC20Token
2019-11-01 14:57:10 -04:00
Alex Towle
ebab80cff7 @0x:contracts-integrations Fixed test issues 2019-11-01 11:22:12 -07:00
Alex Towle
91cb162662 @0x:contracts-integrations Added tests for weth protocol fees 2019-11-01 11:22:12 -07:00
Alex Towle
fa26f8de51 @0x:contracts-integrations Refactored to reduce redundancy 2019-11-01 11:22:12 -07:00
Alex Towle
26602ac2db @0x:contracts-integrations Added assertions for events in all wrapper functions 2019-11-01 11:22:12 -07:00
Alex Towle
0b8af181d8 @0x:contracts-integrations Refactored the wrapper tests to use newer tools 2019-11-01 11:22:12 -07:00
Alex Towle
19d661d324 @0x:contracts-integrations Started to refactor the wrapper tests 2019-11-01 11:22:12 -07:00
Alex Towle
7d29b36246 @0x:contracts-integrations Moved the wrapper tests into the integrations package 2019-11-01 11:21:52 -07:00
Lawrence Forman
8ba7b95e86 @0x/contracts-utils: Move LibERC20Token out.
`@0x/contracts-erc20`: Move `LibERC20Token` in.
`@0x/contracts-erc20`: Use `LibBytes` and `LibRichErrors` in `LibERC20Token`.
`@0x/contracts-erc20`: Use `verifyEventsFromLogs` in `LibERC20Token` unit tests.
2019-11-01 13:58:22 -04:00
Lawrence Forman
30c72daed5 @0x/order-utils: Remove TransferFailedError from ForwarderRevertErrors (for real this time). 2019-11-01 13:36:07 -04:00
Lawrence Forman
575cb99839 @0x/contracts-utils: Update comments in LibERC20Token. 2019-11-01 13:36:07 -04:00
Lawrence Forman
0c064bf85b Update changelogs. 2019-11-01 13:36:07 -04:00
Lawrence Forman
0f3610c92a @0x/contracts-asset-proxy: Use LibERC20Token in UniswapBridge and Eth2DaiBridge. 2019-11-01 13:36:07 -04:00
Lawrence Forman
c8ef10baaf @0x/contracts-utils: Use simple assembly instead of abi.decode() in LibERC20Token._callWithOptionalBooleanResult().
`@0x/contracts-exchange-forwarder`: Use `LibERC20Token` in `MixinAssets`.
`@0x/order-utils`: Remove `TransferFailedError` from `ForwarderRevertErrors`.
2019-11-01 13:36:07 -04:00
Lawrence Forman
16dc73bd1e @0x/contracts-utils: Add LibERC20Token. 2019-11-01 13:36:07 -04:00
Lawrence Forman
4f56d68689 @0x/contracts-staking: Fix overflow w/ LibFixedMath._mul(-1, -2*255). 2019-11-01 13:35:23 -04:00
Greg Hysz
8e6d92cad5 Merge pull request #2310 from 0xProject/tests/3.0/StakingProxyUnitTests
Staking Proxy Unit Tests + Fallback Reverts if No Staking Contract
2019-11-01 10:26:54 -07:00
Greg Hysen
3a1c464543 Readability improvements to Staking Proxy unit tests + one extra case 2019-11-01 09:59:17 -07:00
Greg Hysen
a0c2f6b7b4 Updated Staking changelog 2019-10-31 18:25:33 -07:00
Greg Hysen
7bfbf0ad3a Staking Proxy unit tests + Staking Proxy fallback reverts if no staking contract is attached 2019-10-31 18:22:49 -07:00
mzhu25
82ee6750c7 Merge pull request #2307 from 0xProject/fix/integration-tests/tslint
`@0x/contracts-integrations`: Enable tslint and fix lint errors
2019-10-31 16:23:35 -07:00
mzhu25
c37fc30c55 Merge pull request #2302 from 0xProject/feature/integration-tests/fillOrder
`@0x/contracts-integrations`: fillOrder integration tests
2019-10-31 16:20:07 -07:00
Michael Zhu
09d13b2bfa default before/after in FunctionAssertion 2019-10-31 15:49:12 -07:00
Michael Zhu
af0de72bc3 address comments 2019-10-31 15:30:15 -07:00
Michael Zhu
43e32f6a1a fix other lint errors 2019-10-31 15:30:15 -07:00
Michael Zhu
e9e6452890 add tslint.json to package and update actor mixins 2019-10-31 15:28:02 -07:00
Michael Zhu
5f699b0c47 add test for weth protocol fees 2019-10-31 15:27:39 -07:00
Michael Zhu
bf18b86f9f address comments 2019-10-31 15:27:39 -07:00
Michael Zhu
56f7dd7538 fix deployment_manager_test 2019-10-31 15:27:39 -07:00
Michael Zhu
7aa88307f6 Flesh out fillOrder integration tests 2019-10-31 15:27:39 -07:00
James Towle
8aa69233e0 Merge pull request #2305 from 0xProject/sandstorm/framework/function_assertion_set
Function Assertion Sets
2019-10-31 14:07:57 -07:00
James Towle
e843333918 Merge pull request #2308 from 0xProject/fix/unblock-kroeger/add-contract-artifacts
`@0x:artifacts` Added the Staking and StakingProxy artifacts
2019-10-31 12:42:43 -07:00
Alex Towle
133a4dc4e1 @0x:contract-artifacts Trimmed artifacts and ran prettier 2019-10-31 10:21:40 -07:00
Alex Towle
c7945a542e @0x:abi-gen-wrappers Added exports 2019-10-31 10:18:41 -07:00
Alex Towle
b4e00baa07 @0x:artifacts Added the Staking and StakingProxy artifacts 2019-10-31 10:18:40 -07:00
Alex Towle
dde570706a @0x:contracts-integrations Put final cleaning touches on the function assertion set 2019-10-30 13:26:29 -07:00
Alex Towle
0b3e3ab990 @0x:contracts-integrations Addressed more review comments 2019-10-30 11:11:55 -07:00
Alex Towle
205c895d75 @0x:contracts-integrations Added better documentation to FunctionAssertions 2019-10-29 23:19:28 -07:00
Alex Towle
6402d29dd4 @0x:contracts-integrations Added collections of function assertions 2019-10-29 14:51:01 -07:00
mzhu25
dc18999931 Merge pull request #2293 from 0xProject/refactor/integrations/forwarder-tests
Refactor and move Forwarder tests to integrations package
2019-10-29 13:04:59 -07:00
Michael Zhu
43f8101d0b address comments 2019-10-29 11:26:56 -07:00
Michael Zhu
3d56c06ff3 Move Forwarder test to integrations; update to use new framework 2019-10-29 11:26:56 -07:00
Lawrence Forman
db9be73fec Merge pull request #2292 from 0xProject/feat/staking/MixinStakeBalances-unit-tests
Add MixinStakeBalances unit tests.
2019-10-29 08:11:59 -04:00
Lawrence Forman
a02892cbc8 @0x/contracts-staking: Remove duplicated test case in MixinStakeBalances unit tests. 2019-10-29 07:37:06 -04:00
Lawrence Forman
49c67fbb18 @0x/contracts-staking: Remove unused lodash import and only modifier from MixinStakeBalances unit tests. 2019-10-29 07:37:06 -04:00
Lawrence Forman
6f2e79208a @0x/contracts-staking: Add MixinStakeBalances unit tests. 2019-10-29 07:37:06 -04:00
Amir Bandeali
ceb3ba4116 Merge pull request #2296 from 0xProject/feat/3.0/testnet-migrations-2
Update 3.0 testnet migrations and addresses
2019-10-28 21:29:03 -07:00
Greg Hysz
08d4f1402f Merge pull request #2301 from 0xProject/fix/3.0/removeLibProxy
Removed LibProxy and inlined proxy call in StakingProxy.
2019-10-28 20:00:24 -07:00
Amir Bandeali
77fa97f259 Update DevUtils, Forwarder, and Coordinator addresses for each testnet 2019-10-28 17:40:50 -07:00
Amir Bandeali
3ac5d9add5 Add DevUtils, Forwarder, and Coordinator to testnet migrations 2019-10-28 17:40:45 -07:00
Amir Bandeali
cab89f312a Update CHANGELOG 2019-10-28 16:55:54 -07:00
Amir Bandeali
8972475389 Update testnet migrations and verifications 2019-10-28 16:55:54 -07:00
Amir Bandeali
330f2d54e2 Update contract-addresses with new testnet deployments 2019-10-28 16:55:54 -07:00
Greg Hysen
9c181f09ba Removed LibProxy and inlined proxy call in StakingProxy. 2019-10-28 16:42:52 -07:00
Amir Bandeali
011ecb8f4b Merge pull request #2297 from 0xProject/fix/multisig/allow-tx-to-be-over-confirmed
Allow transactions to be over confirmed without resetting the confirmation time
2019-10-28 12:49:19 -07:00
Amir Bandeali
bc2a9beb14 Merge pull request #2295 from 0xProject/feat/staking/remove-read-only-mode
Remove read-only mode and associated code
2019-10-28 12:02:10 -07:00
Amir Bandeali
091f5ed8b8 Allow transactions to be over confirmed without resetting the confirmation time 2019-10-28 10:45:17 -07:00
F. Eugene Aumson
ea9f535a7c contract_addresses.py: Add DevUtils contract (#2150)
* contract_addresses.py: Add DevUtils

* Update __init__.py

* Remove whitespace to satisfy linters
2019-10-28 13:32:24 -04:00
Amir Bandeali
f246314b1d Update default alpha from 1/2 to 2/3 2019-10-27 16:53:57 -07:00
Amir Bandeali
cdfd62a296 Fix reentrancy tests 2019-10-27 14:23:19 -07:00
Amir Bandeali
dcff7d511b Add tests for detachProtocolFeeCollector 2019-10-27 11:41:06 -07:00
Amir Bandeali
16a5475d24 Add detachProtocolFeeCollector function (in order to have a separate timelock for detaching) 2019-10-27 11:40:28 -07:00
Amir Bandeali
42468c3fa2 Remove read-only proxy from contract addresses and migrations 2019-10-27 11:12:22 -07:00
Amir Bandeali
9312d5d9f7 remove read-only mode related code from integrations 2019-10-27 11:12:22 -07:00
Amir Bandeali
33a0c22021 Remove tests related to read-only mode 2019-10-27 11:12:22 -07:00
Amir Bandeali
58e9c70203 Remove read-only mode related functions, storage variables, and contracts 2019-10-27 11:12:16 -07:00
F. Eugene Aumson
0067f10a6a @0x/utils: fix wrong RPC method in getChainIdAsync() (#2270)
It was using net_version, but it should be using the eth_chainId method
introduced in EIP-695.  I'm not sure whether/how the network ID differs
from the chain ID on mainnet and the testnets, but in Ganache in
particular, the network ID is 50 while the chain ID is 1337, and this
difference was causing problems for Python tests.  Specifically, the
Web3.py interface `Web3.eth.chainId` invokes the eth_chainId method, and
the result feeds into the order hash, which wasn't lining up with the
non-Python side of things.
2019-10-25 21:08:31 -04:00
Lawrence Forman
59210f5e5e Merge pull request #2287 from 0xProject/feat/staking/MixinStakingPool-unit-tests
Add MixinStakingPool unit tests.
2019-10-25 11:59:50 -04:00
Lawrence Forman
1c695b2759 Rebase onto 3.0 2019-10-25 10:56:03 -04:00
Lawrence Forman
c7222c17ae @0x/contracts-test-utils: prettier 2019-10-25 10:55:03 -04:00
Lawrence Forman
0f237d22f9 @0x/contracts-test-utils: Refactor verifyEvents() to just use verifyEventsFromLogs(). 2019-10-25 10:55:03 -04:00
Lawrence Forman
b1b1162b60 @0x/contracts-staking: Add MixinStakingPool unit tests. 2019-10-25 10:55:03 -04:00
Lawrence Forman
6ee1605a77 @0x/contracts-test-utils: Add verifyEventsFromLogs(). 2019-10-25 10:54:38 -04:00
Greg Hysz
a22b2e7a9f Merge pull request #2290 from 0xProject/fix/3.0/updatedInterfaces
Created IZrxVaultBackstop and updated IStaking.
2019-10-25 06:33:18 -07:00
Greg Hysz
86ed32a007 Merge pull request #2288 from 0xProject/fix/3.0/minorStakingReadability
Replaced `protocolFeePaid` -> `protocolFeeAmount`
2019-10-25 06:19:20 -07:00
Greg Hysen
8e8ea6a3ab Created IZrxVaultBackstop and updated IStaking. 2019-10-24 15:58:51 -07:00
Greg Hysen
cc7452da8f Replaced protocolFeePaid -> protocolFeeAmount. Changed some wording in comments. 2019-10-24 15:58:18 -07:00
Amir Bandeali
06715201a7 Merge pull request #2283 from 0xProject/fix/3.0/rename-bridge-withdraw-to
Rename `withdrawTo` to `bridgeTransferFrom`
2019-10-23 10:15:08 -07:00
Amir Bandeali
281658ba34 Rename withdrawTo to bridgeTransferFrom 2019-10-23 09:42:37 -07:00
Lawrence Forman
f192648c76 Merge pull request #2279 from 0xProject/fix/3.0-audit/staking/assert-valid-params-in-MixinParams
Assert storage params when calling `MixinParams.setParams()`.
2019-10-23 05:11:10 -04:00
Lawrence Forman
07e1d502e7 @0x/contracts-staking: Update changelog. 2019-10-23 04:40:47 -04:00
Lawrence Forman
703e890918 @0x/contracts-staking: Call StakingProxy.assertValidStorageParams() in MixinParams.setParams() 2019-10-23 04:40:47 -04:00
mzhu25
096950729e Merge pull request #2275 from 0xProject/refactor/integrations/coordinator-tests-part2
Coordinator test refactor [2/2]
2019-10-22 17:37:21 -07:00
Michael Zhu
8869d79c68 rebase 2019-10-22 17:05:08 -07:00
Michael Zhu
752dd04546 address comments 2019-10-22 17:05:08 -07:00
Michael Zhu
3e5d166ec4 moving away from extending DeploymentManager in case we want to deploy multiple extensions alongside one another 2019-10-22 17:05:08 -07:00
Michael Zhu
64bc1b0990 update coordinator tests to use deployment manager, balance stores, actor mixins 2019-10-22 17:05:08 -07:00
Michael Zhu
548b0db6ea coordinator deployment manager 2019-10-22 17:05:08 -07:00
Greg Hysz
c9607e8b2c Merge pull request #2280 from 0xProject/fix/3.0/handleNopInMoveStake
Force no-op when moving stake, in some scenarios
2019-10-22 16:51:46 -07:00
Greg Hysen
c676ecb8cf Force no-op when moving zero stake or moving from undelegated to undelegated. 2019-10-22 15:39:24 -07:00
James Towle
39804fdc83 Merge pull request #2281 from 0xProject/fix/ci/10-22-2019
`CI` Fix build failure
2019-10-22 15:20:24 -07:00
Alex Towle
1a1dc89454 CI Fix build failure 2019-10-22 14:53:13 -07:00
James Towle
e427698956 Merge pull request #2252 from 0xProject/feature/sandstorm/function-assertions
Initial Sandstorm Framework
2019-10-22 13:45:42 -07:00
Greg Hysz
575af6b6e8 Merge pull request #2278 from 0xProject/fix/3.0/removeProtocolFeeZeroAssertion
Remove assertion that protocol fee != zero
2019-10-22 13:24:59 -07:00
Alex Towle
3a1fc9ee5f @0x:contracts-integrations Fixed package after rebase 2019-10-22 13:15:01 -07:00
mzhu25
1237c7d479 Merge pull request #2277 from 0xProject/fix/3.0/rmeove-staking-fallback
Remove payable fallback from Staking.sol
2019-10-22 12:46:13 -07:00
Greg Hysen
c44e16a88f Removed assertion that protocol fee != 0 from staking contract. 2019-10-22 12:42:04 -07:00
Greg Hysz
06c180475e Merge pull request #2276 from 0xProject/cleanup/staking/finalizationDataStructures
Refactored finalization state.
2019-10-22 12:37:50 -07:00
Michael Zhu
74a2c3a199 Remove payable fallback from Staking.sol 2019-10-22 12:15:07 -07:00
Greg Hysen
9ac715f99d Protocol fee amount is not enforced by staking contract 2019-10-22 12:10:34 -07:00
Greg Hysen
22e39f782f Some (more) readability improvements and minor optimizations to staking finalization. 2019-10-22 12:09:18 -07:00
Alex Towle
f5a6b84fa3 CI: Added a seperate workflow for contracts/integrations 2019-10-22 12:07:50 -07:00
Alex Towle
718407ba6f @0x:contracts-integrations Switched to object destructuring in the function assertion unit test 2019-10-22 12:07:50 -07:00
Alex Towle
e603a81a46 @0x:contracts-integrations Simplified the tests 2019-10-22 12:07:50 -07:00
Alex Towle
03e35846fb @0x:contracts-integrations Removed the Cache 2019-10-22 12:07:50 -07:00
Alex Towle
c87364f86b @0x:contracts-integrations Addressed more review feedback 2019-10-22 12:07:50 -07:00
Alex Towle
a794a33551 @0x:contracts-integrations Addressed review comments 2019-10-22 12:06:38 -07:00
Alex Towle
494b437f1a @0x:contracts-integrations Renamed some functions in Address Manager 2019-10-22 12:04:47 -07:00
Alex Towle
92b80fc436 @0x:contracts-integrations Improved the caches 2019-10-22 12:04:47 -07:00
Alex Towle
d66101cd9d @0x:contracts-integrations Added unit tests for FunctionAssertion 2019-10-22 12:04:47 -07:00
Alex Towle
89ae04803f @0x:contract-integrations Added the integrations package to CI 2019-10-22 12:01:54 -07:00
Alex Towle
be95bce4cd @0x:contract-integrations Move caches to a new file 2019-10-22 12:01:30 -07:00
Alex Towle
01aee08c02 @0x:contracts-integrations Wrote a simple integration test and AddressManager 2019-10-22 12:01:30 -07:00
Alex Towle
6cba9fd77f @0x/contracts-integrations Created the FunctionAssertion class and examples 2019-10-22 11:59:17 -07:00
mzhu25
673d45361f Merge pull request #2273 from 0xProject/refactor/integrations/coordinator-tests
Coordinator test refactor [1/2] + actor mixin pattern
2019-10-22 11:37:02 -07:00
Greg Hysen
d91a7fc663 Some readability improvements and minor optimizations to staking finalization. 2019-10-22 11:02:25 -07:00
Greg Hysen
ce8fd44234 Removed lingering references to stale terminology ("active pools") 2019-10-22 11:02:25 -07:00
Greg Hysen
6617ad9531 Refactored finalization state.
1. Removes state variables:
   - totalWeightedStakeThisEpoch
   - totalFeesCollectedThisEpoch
   - numActivePoolsThisEpoch

2. No longer indexes by epoch % 2

3. Renamed event StakingPoolActivated → StakingPoolEarnedRewards.

4. Renamed structs:
   - ActivePool → PoolStats. This holds stats for a pool that earned rewards.
   - UnfinalizedState → AggregatedStats. This aggregates stats from the former struct.
2019-10-22 11:02:25 -07:00
Amir Bandeali
10f8051835 Merge pull request #2274 from 0xProject/feat/staking/separate-function-logic
Separate finalization from withdrawing rewards
2019-10-22 10:36:04 -07:00
Amir Bandeali
e7dc7167d0 Sync delegatedStakeToPoolByOwner whenever _withdrawAndSyncDelegatorRewards is called 2019-10-22 09:38:18 -07:00
Amir Bandeali
359b804001 Add test for withdrawing rewards before epoch is finalized 2019-10-21 22:27:06 -07:00
Amir Bandeali
fd9084b345 Add PoolNotFinalizedError rich revert 2019-10-21 22:27:06 -07:00
Amir Bandeali
44dac2cd80 Fix tests that assume touching stake will finalize pool 2019-10-21 22:27:06 -07:00
Amir Bandeali
a66ea2bf74 Assert that pool has been finalized in _withdrawAndSyncDelegatorRewards rather than calling finalizePool 2019-10-21 22:27:06 -07:00
Amir Bandeali
a362e9d2d8 Use safeMath where possible 2019-10-21 22:27:06 -07:00
Amir Bandeali
1885957bd3 Update tests to start at epoch 1 2019-10-21 22:27:06 -07:00
Amir Bandeali
1a409c3731 Initialize currentEpoch at 1 instead of 0 2019-10-21 22:27:06 -07:00
Amir Bandeali
7b7c64fc6a Add assertion function that checks if pool was finalized last epoch 2019-10-21 22:27:06 -07:00
Michael Zhu
102fcd3fb8 export actor classes 2019-10-21 11:17:53 -07:00
Michael Zhu
566e05aea4 typo 2019-10-21 11:17:53 -07:00
Michael Zhu
f014370531 document mixin constructor params 2019-10-21 11:17:53 -07:00
Michael Zhu
dfbbe9daa2 address comments 2019-10-21 11:17:53 -07:00
Michael Zhu
6b653fb00d prettier gdi 2019-10-21 11:17:53 -07:00
Michael Zhu
21cf2319d5 rename some stuff 2019-10-21 11:17:53 -07:00
Michael Zhu
4210477e71 Introduce actor mixin pattern 2019-10-21 11:17:53 -07:00
Michael Zhu
93b02e93b9 juggling some files around 2019-10-21 11:16:14 -07:00
Michael Zhu
f4cb8cfb7e Support arbitrary # of tokens in DeploymentManager 2019-10-21 11:16:14 -07:00
Xianny
ce9f051d42 Create @0x/contracts-tests (#2261)
* Create @0x/contracts-tests

* Move tests from @0x/contracts-dev-utils
2019-10-21 10:23:46 -07:00
Amir Bandeali
083216a0c6 Merge pull request #2271 from 0xProject/feat/3.0/zero-ex-governor
Rename AssetProxyOwner to ZeroExGovernor
2019-10-19 17:05:07 -07:00
Amir Bandeali
820b40e227 Import ZeroExGovernor instead of AssetProxyOwner in testnet migrations 2019-10-18 16:31:38 -07:00
mzhu25
59a38a8db0 Merge pull request #2269 from 0xProject/refactor/balance-stores
BalanceStore++
2019-10-18 09:01:33 -07:00
Lawrence Forman
d0884dcb4d Merge pull request #2267 from 0xProject/feat/3.0/staking/MixinStake-unit-tests
Create MixinStake unit tests
2019-10-18 11:41:18 -04:00
Lawrence Forman
c7ca625408 @0x/contracts-staking: Fix MixinStake unit tests typo. 2019-10-18 10:45:07 -04:00
Lawrence Forman
e46f51339a @0x/contracts-staking: Address review comments. 2019-10-18 10:42:47 -04:00
Michael Zhu
b45ec47eee address comments 2019-10-17 19:53:43 -07:00
Amir Bandeali
c50cbd7a75 Rename AssetProxyOwner to ZeroExGovernor throughout all contracts packages 2019-10-17 17:41:54 -07:00
Amir Bandeali
5ddc35fdf2 Rename AssetProxyOwner to ZeroExGovernor 2019-10-17 17:41:54 -07:00
Amir Bandeali
d6c064b9c3 Merge pull request #2224 from 0xProject/feat/3.0/testnet-migrations
3.0 testnet migrations
2019-10-17 17:38:09 -07:00
Amir Bandeali
caf6329bb3 Merge branch '3.0' into feat/3.0/testnet-migrations 2019-10-17 17:13:12 -07:00
Lawrence Forman
008938cf5b @0x/contracts-staking: Check order of increase and derease balance operations in MixinStake unit tests. 2019-10-17 14:09:46 +10:00
Fabio B
3fd29656cb Merge pull request #2268 from 0xProject/addERC1155MintableSupport
Add erc1155 mintable support
2019-10-17 11:50:02 +08:00
Michael Zhu
ffac52f42e lint 2019-10-16 20:19:04 -07:00
fabioberger
9114510c00 Add enum-naming linter ignore to wrappers to fix linter issue with URL in ERC1155Mintable 2019-10-17 12:16:42 +09:00
fabioberger
2dbda6fc42 Deploy ERC1155Mintable in migration 2019-10-17 12:16:08 +09:00
fabioberger
eae4001622 Update ganache-cli version in migration dockerfile 2019-10-17 12:16:08 +09:00
fabioberger
727d0498b6 Export ERC1155Mintable from abi-gen-wrapper 2019-10-17 12:16:08 +09:00
fabioberger
e43f2d39bf Add ERC1155Mintable to artifacts and abi-gen-wrappers packages 2019-10-17 12:16:08 +09:00
Michael Zhu
cde0169733 Update BlockchainBalanceStore to not rely on erc*_wrappers + better balance equality assertions 2019-10-16 18:46:55 -07:00
Xianny
0e90b0e7d0 Make wrappers small again (#2243)
* introduce --debug option to abi-gen and remove debug functions from @0x/abi-gen-wrappers
* make evmExecAsync protected; ignore deployedBytecode in doc comment
* trim deployedBytecode so it's undefined unless a contract has pure functions
* remove validateAndSendTransactionAsync
* Create `AwaitTransactionSuccessOpts` and `SendTransactionOpts` types 
* Remove duplicate types `IndexedFilterValues`, `DecodedLogEvent`, `EventCallback` from `@0x/base-contract`
2019-10-16 09:38:34 -07:00
Lawrence Forman
b793a31cdd @0x/contracts-staking: Create MixinStake unit tests. 2019-10-16 22:53:36 +10:00
James Towle
23198174f3 Merge pull request #2254 from 0xProject/fix/t14
Add SafeMath to Multisig
2019-10-15 15:40:48 -07:00
Alex Towle
523bc3f951 Updated Changelogs 2019-10-15 15:00:01 -07:00
Alex Towle
41d99e77c7 @0x:contracts-utils Removed SafeMath and the use of the contract throughout contracts/ 2019-10-15 14:31:48 -07:00
Alex Towle
90193c8197 @0x:contracts-multisig Changed SafeMath to LibSafeMath 2019-10-15 14:31:48 -07:00
Alex Towle
6f5c62914e @0x:contracts-multisig Switched to SafeMath in pastTimeLock 2019-10-15 14:31:48 -07:00
James Towle
17faeae47d Merge pull request #2265 from 0xProject/fix/3.0/c18
Fix/3.0/c18
2019-10-15 11:31:46 -07:00
Alex Towle
7283a16710 @0x:contracts-utils Updated changelog 2019-10-14 11:57:02 -07:00
Alex Towle
52c3dc4ad8 @0x:contracts-utils Fixed and improved the LibBytes tests 2019-10-14 11:54:02 -07:00
Alex Towle
1cf8ae5909 @0x:contracts-utils Removed several functions from LibBytes 2019-10-14 11:54:02 -07:00
Amir Bandeali
51282953bd Merge pull request #2263 from 0xProject/fix/3.0-audit/staking/cumulative-rewards-refactor
Staking: Refactor and slightly simplify rewards tracking
2019-10-14 18:28:03 +09:00
Lawrence Forman
a6603d6bd6 @0x/contracts-staking: Fix typo in MixinCumulativeRewards 2019-10-14 15:19:34 +10:00
Lawrence Forman
54a03eacd6 @0x/contracts-staking: Refactor MixinCumulativeRewards and MixinStakingPoolRewards to better encapsulate cumulative rewards.
`@0x/contracts-staking`: Make sure we don't overwrite an existing CR.
`@0x/contracts-staking`: Remove the need to initialize cumulative rewards when creating a pool.
`@0x/contracts-staking`: Just return an empty CR in `_getCumulativeRewardAtEpoch()` if one can't be found.
2019-10-14 12:36:26 +10:00
Amir Bandeali
43fa753a13 Merge pull request #2262 from 0xProject/fix/staking/simplify-finalization
Staking readability improvements
2019-10-14 10:45:55 +09:00
Amir Bandeali
9d9fe882b6 Remove unnecessary payable keywords 2019-10-14 09:58:31 +09:00
Amir Bandeali
4f6958b7b5 Do not import @0x/contracts-extensions to fix build 2019-10-14 09:46:06 +09:00
Amir Bandeali
9a5752fff9 Remove unused param in Pool struct 2019-10-14 09:45:37 +09:00
Amir Bandeali
c21932d149 Remove _creditRewardsToPool and remove return values from finalizePool 2019-10-13 17:31:55 +09:00
Amir Bandeali
ce6c05637f Update cumulative rewards tracking tests 2019-10-13 17:31:55 +09:00
Amir Bandeali
b0699fc238 Always set cumulative rewards when _withdrawAndSyncDelegatorRewards is called 2019-10-13 17:31:55 +09:00
Amir Bandeali
8bf7c4cf48 Remove unnecessary assert 2019-10-13 17:31:55 +09:00
Lawrence Forman
9f6d113fe8 Merge pull request #2255 from 0xProject/fix/3.0-audit/staking/LibFixedMath-arithmetic-overflows
Fix LibFixedMath arithmetic overflows
2019-10-12 07:38:05 +09:00
James Towle
646507c41a Merge pull request #2253 from 0xProject/fix/t8
Ownership Transferred Event
2019-10-10 16:58:08 -07:00
Alex Towle
65f2626544 @0x:contracts-utils Updated the OwnershipTransferred event to be closer to OpenZeppelin's event 2019-10-10 10:58:58 -07:00
Greg Hysz
7155d878b3 Merge pull request #2257 from 0xProject/cleanup/staking/loadSyncedUnsyncedBalance
Remove `loadSyncedBalance` and `loadUnsyncedBalance`
2019-10-10 16:15:17 +09:00
Greg Hysen
361576814c Removed loadSyncedBalance and loadUnsyncedBalance 2019-10-10 15:51:24 +09:00
Amir Bandeali
aa541d0cad Merge pull request #2256 from 0xProject/feat/staking/immutable
Separate immutable contracts, only inherit as needed
2019-10-10 15:19:37 +09:00
Amir Bandeali
7e58385a78 Separate immutable contracts, only inherit as needed 2019-10-10 15:00:35 +09:00
Amir Bandeali
b5545255d0 Merge pull request #2245 from 0xProject/fix/3.0/validate-assetdata
Enforce assetData is padded to 32 bytes
2019-10-10 10:55:22 +09:00
Lawrence Forman
a22ba8647c Update changelogs 2019-10-10 09:41:57 +09:00
Lawrence Forman
22fc0b4337 @0x/contracts-staking: Add another LibFixedMath.add() test. 2019-10-10 09:31:53 +09:00
Lawrence Forman
063d6ff24e @0x/contracts-staking: Add more overflow safeguards to LibFixedMath. 2019-10-10 09:16:01 +09:00
Lawrence Forman
09c0b83fe3 @0x/utils: Consolidated FixedMathRevertErrors 2019-10-10 09:16:01 +09:00
Lawrence Forman
a42f3d189c @0x/contracts-staking: Implement better overflow detection in LibFixedMath. 2019-10-10 09:16:01 +09:00
Alex Towle
7815da7257 @0x:contracts-utils Addressed review feedback 2019-10-09 10:49:38 -07:00
Amir Bandeali
8e2b971f5a Merge pull request #2249 from 0xProject/feat/staking/catastrophic-failure-backstop
Read-only mode backstop
2019-10-09 19:16:10 +09:00
Amir Bandeali
3fd7132a0d Merge pull request #2248 from 0xProject/fix/staking/cleanup-accounting
Simplify staking state
2019-10-09 18:00:06 +09:00
Amir Bandeali
93edb083fa Remove payable fallback from IStakingProxy, fix linting errors 2019-10-09 17:27:37 +09:00
Amir Bandeali
9e41c648dc Add backstop tests 2019-10-09 17:27:37 +09:00
Amir Bandeali
a7ef54dbff Implement ZrxVaultBackstop 2019-10-09 17:27:37 +09:00
Amir Bandeali
414084a7ad Track state of read-only mode in stakingProxy 2019-10-09 17:27:37 +09:00
Amir Bandeali
681e6eab7a Cleanup language used in comments and variable names 2019-10-09 17:15:25 +09:00
Amir Bandeali
701b203c58 Fix tests 2019-10-09 17:15:25 +09:00
Amir Bandeali
cbd0ca4b60 Make currentEpoch uint64 type, change INACTIVE => UNDELEGATED, and make global balances state a mapping from uin8 => StoredBalance 2019-10-09 17:15:25 +09:00
Amir Bandeali
1626566f93 Change getBalanceOfVault => getBalanceOfZrxVault 2019-10-09 17:15:25 +09:00
Amir Bandeali
ac75053f69 Remove unused rich revert 2019-10-09 17:15:25 +09:00
Amir Bandeali
13afc65b54 Do not store global inactive state 2019-10-09 17:15:25 +09:00
Amir Bandeali
aa0a1bb54d Fix tests to no longer utilize active stake 2019-10-09 17:15:25 +09:00
Amir Bandeali
2e36c7ef83 Remove ACTIVE state 2019-10-09 17:15:25 +09:00
Amir Bandeali
43399a9ad9 Refactor tests to use new getters 2019-10-09 17:15:25 +09:00
Amir Bandeali
2ef546210d Update tests to reflect new withdrawal logic 2019-10-09 17:15:25 +09:00
Amir Bandeali
7b379f3933 Simplify withdrawal flow and storage layout 2019-10-09 17:15:25 +09:00
Amir Bandeali
f8ac986a0f Remove unused struct field 2019-10-09 17:14:28 +09:00
Alex Towle
dc0a78434d @0x:contracts-utils Updated files 2019-10-08 19:27:39 -07:00
Alex Towle
d1b0384aef @0x:contracts-utils Added an event for ownership transfers 2019-10-08 19:22:27 -07:00
Greg Hysz
7ac7f45c4a Merge pull request #2250 from 0xProject/cleanup/staking/simplifyMakers
Simplify Makers Interactions with Staking Pools
2019-10-08 11:25:07 +09:00
Greg Hysen
b3c7ccec57 Changed nextPoolId to lastPoolId 2019-10-08 10:43:18 +09:00
Lawrence Forman
93725ecec0 Merge pull request #2233 from 0xProject/feat/erc20-bridge/uniswap
UniswapBridge
2019-10-08 10:31:47 +09:00
Amir Bandeali
3c31ef188a Merge pull request #2246 from 0xProject/fix/3.0/always-validate-signatures
Always validate order signatures
2019-10-08 10:25:28 +09:00
Lawrence Forman
53df2130ea @0x/contracts-asset-proxy: Remove only modifier on uniswap tests. 2019-10-08 09:27:53 +09:00
Amir Bandeali
8b695f9b98 Fix race condition in tests 2019-10-08 09:12:37 +09:00
Amir Bandeali
d914f6fce9 Test for failure with bad signature after partial fill 2019-10-08 09:12:37 +09:00
Amir Bandeali
e2e5152648 Always validate signatures for all types 2019-10-08 09:12:37 +09:00
Lawrence Forman
d3dcf7fb0c Merge pull request #2247 from 0xProject/fix/3.0-audit/staking/shadowed-variable
fix `_computeUnfinalizedDelegatorReward()` shadowed variable and function mutability
2019-10-07 18:50:32 -05:00
Greg Hysen
a0f5a8b64b Simplify Makers Interactions with Staking Pools.
- No longer an upper limit on how many makers can be in a pool.
- No longer a handshake for a maker to join a pool.
- No longer any special powers given to makers.
- Pool Id starts at 1 and increments by 1.
2019-10-08 06:00:24 +09:00
mzhu25
ee508f70bc Merge pull request #2228 from 0xProject/fix/3.0/refundFinalBalanceNoReentry
refundFinalBalanceNoReentry
2019-10-06 13:39:04 -07:00
mzhu25
200b3d450f Merge pull request #2229 from 0xProject/feature/3.0/update-coordinator
Update Coordinator for 3.0
2019-10-06 13:20:00 -07:00
Michael Zhu
52fc7517f9 Remove approval expirations, address other comments 2019-10-06 12:45:48 -07:00
Michael Zhu
cf517b1459 appease static tests 2019-10-06 12:44:58 -07:00
Michael Zhu
c17984b74f Refactor integration tests (CoordinatorTestFactory) 2019-10-06 12:44:58 -07:00
Michael Zhu
589d2212ee Test coordinator protocol fees 2019-10-06 12:44:58 -07:00
Michael Zhu
9b922f746b Update coordinator tests 2019-10-06 12:44:58 -07:00
Michael Zhu
0e7387550c Update contracts 2019-10-06 12:44:58 -07:00
Lawrence Forman
dbf22583b5 @0x/contracts-asset-proxy: Remove unecessary token allowance when coming from WETH. 2019-10-05 22:37:51 -05:00
Lawrence Forman
6825eb442b @0x/contracts-staking: Fix shadowed variable in MixinStakingPoolRewards._computeUnfinalizedDelegatorReward() and make the function pure. 2019-10-05 17:22:46 -05:00
James Towle
45f284973a Merge pull request #2240 from 0xProject/feature/integration-tests/deployment-manager
Deployment Manager
2019-10-05 15:14:12 -07:00
Lawrence Forman
ef6e691646 @0x/contracts-exchange-libs: Update generated source files after revase. 2019-10-05 16:29:06 -05:00
Lawrence Forman
e67888d65f @0x/contracs-asset-proxy: Pass in minimum buy amounts in the UniswapBridge.
`@0x/contracs-asset-proxy`: Slight refactors in `UniswapBridge`.
2019-10-05 16:27:24 -05:00
Lawrence Forman
584f8b13fe @0x/contracts-asset-proxy: Rebase and update Eth2DaiBridge to use IWallet from exchange-libs. 2019-10-05 13:57:51 -05:00
Lawrence Forman
f993b6d1ed @0x/contracts-exchange: Revert changes to IWallet. 2019-10-05 13:57:51 -05:00
Lawrence Forman
035dc607db @0x/contracts-asset-proxy: Use IWallet from exchange-libs.
`@0x/contracts-asset-proxy`: Fix some comment typos in `UniswapBridge`.
`@0x/contracts-asset-proxy`: Add more allowance tests to the `UniswapBridge` tests.
2019-10-05 13:57:51 -05:00
Lawrence Forman
cf2053ec77 @0x/contracts-exchange-libs: Move IWallet from asset-proxy and exchange packages into this package. 2019-10-05 13:57:51 -05:00
Lawrence Forman
3840ebf538 @0x/contracts-exchange: Move IWallet.sol to exchange-libs. 2019-10-05 13:57:51 -05:00
Lawrence Forman
80cb6b654b @0x/contracts-asset-proxy: Fix linter errors. 2019-10-05 13:57:51 -05:00
Lawrence Forman
ab70c4df74 @0x/contracts-asset-proxy: Remove only modifier on tests. 2019-10-05 13:57:51 -05:00
Lawrence Forman
95e461072f @0x/contracts-asset-proxy: Always set allowance. 2019-10-05 13:57:50 -05:00
Lawrence Forman
2593f1ff30 @0x/contracts-asset-proxy: Update CHANGELOG. 2019-10-05 13:57:50 -05:00
Lawrence Forman
c2261a6bbe @0x/contracts-asset-proxy: Finish off UniswapBridge tests. 2019-10-05 13:57:50 -05:00
Lawrence Forman
b383781870 @0x/contracts-asset-proxy: Getting around stack issues. 2019-10-05 13:57:50 -05:00
Lawrence Forman
7d121bafd0 @0x/contracts-asset-proxy: More work on UniswapBridge tests. 2019-10-05 13:57:50 -05:00
Lawrence Forman
6a2911d10f @0x/contracts-asset-proxy: Start work on UniswapBridge tests. 2019-10-05 13:57:50 -05:00
Lawrence Forman
17362bcf44 @0x/contracts-asset-proxy: Create UniswapBridge. 2019-10-05 13:57:50 -05:00
Amir Bandeali
87906a3af1 Add test for improperly padded assetData 2019-10-04 18:05:20 -07:00
Amir Bandeali
c0c27ed637 Enforce that assetData is padded to 32 bytes, excluding the id, before dispatching transfer 2019-10-04 18:04:44 -07:00
Amir Bandeali
6be5552944 fix static tests 2019-10-04 17:17:07 -07:00
Alex Towle
b4ae42cc9a @0x/contracts-integrations Added the integrations package to the top-level configuration 2019-10-04 16:32:39 -07:00
Alex Towle
3c6957095d @0x:contracts-integrations Addressed review feedback 2019-10-04 15:42:36 -07:00
fabioberger
2020d87824 Fix dist tag issue in publish script 2019-10-04 20:44:18 +08:00
Amir Bandeali
ac1063dd68 Merge branch '3.0' into feat/3.0/testnet-migrations 2019-10-03 23:04:07 -07:00
fabioberger
b8e01d7be5 Add beta version to next tslint-config release 2019-10-04 13:28:25 +08:00
Alex Towle
24e4567b25 @0x:contracts-integration-tests Added an integration-tests package and a deployment manager class 2019-10-03 19:41:51 -07:00
Jacob Evans
ccf40fd65e Merge pull request #2242 from 0xProject/fix-mesh-orderbook-types
HACK: Types as any until Mesh RPC client is published
2019-10-03 18:21:24 -07:00
Jacob Evans
d4729e2669 Increase HEAP space for Instant 2019-10-03 17:47:33 -07:00
Jacob Evans
52d38c63de HACK the types until Mesh RPC client is published 2019-10-03 16:40:42 -07:00
Jacob Evans
086c30831d Merge pull request #2241 from 0xProject/rm-dev-tools-pages
Remove dev tools pages
2019-10-03 16:31:44 -07:00
Jacob Evans
4be83de7e5 Remove dev tools pages 2019-10-03 16:25:46 -07:00
Amir Bandeali
650efb95e2 Add more contract configs tests 2019-10-01 22:18:09 -07:00
Michael Zhu
3948f8b66b Replace nonReentrant + refundFinalBalance with refundFinalBalanceNoReentry 2019-10-01 15:39:50 -07:00
Amir Bandeali
ffcd297e5b Rename old exchange address to exchangeV2 2019-09-30 21:03:27 -07:00
Amir Bandeali
cfb099c65c Fix linting errors 2019-09-30 19:00:17 -07:00
Amir Bandeali
ba5c702a9e Update CHANGELOGs 2019-09-30 19:00:17 -07:00
Amir Bandeali
9d4010299a Cleanup migration scripts 2019-09-30 19:00:17 -07:00
Amir Bandeali
b5492bb023 Add ZrxVault testnet addresses to deployment constants 2019-09-30 19:00:17 -07:00
Amir Bandeali
76724a6c73 Implement initial 3.0 migrations script 2019-09-30 19:00:17 -07:00
Amir Bandeali
57ec0858fe Fix migrations build 2019-09-30 19:00:17 -07:00
Amir Bandeali
b281b9aac8 Update 3.0 testnet addresses 2019-09-30 19:00:17 -07:00
Amir Bandeali
f4453c0966 Regenerate abi-gen-wrappers 2019-09-30 18:57:17 -07:00
Amir Bandeali
ebd328db06 Add getSelector helper function to Typescript templates 2019-09-30 18:57:17 -07:00
939 changed files with 75569 additions and 129014 deletions

View File

@@ -47,7 +47,7 @@ jobs:
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- run: yarn wsrun test:circleci @0x/contracts-multisig @0x/contracts-utils @0x/contracts-exchange-libs @0x/contracts-erc20 @0x/contracts-erc721 @0x/contracts-erc1155 @0x/contracts-extensions @0x/contracts-asset-proxy @0x/contracts-exchange @0x/contracts-exchange-forwarder @0x/contracts-coordinator @0x/contracts-dev-utils @0x/contracts-staking
- run: yarn wsrun test:circleci @0x/contracts-multisig @0x/contracts-utils @0x/contracts-exchange-libs @0x/contracts-erc20 @0x/contracts-erc721 @0x/contracts-erc1155 @0x/contracts-extensions @0x/contracts-asset-proxy @0x/contracts-exchange @0x/contracts-exchange-forwarder @0x/contracts-coordinator @0x/contracts-tests @0x/contracts-staking
test-exchange-ganache-3.0:
resource_class: medium+
docker:
@@ -58,6 +58,16 @@ jobs:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- run: yarn wsrun test:circleci @0x/contracts-exchange
test-integrations-ganache-3.0:
resource_class: medium+
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
working_directory: ~/repo
steps:
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- run: yarn wsrun test:circleci @0x/contracts-integrations
test-contracts-rest-ganache-3.0:
resource_class: medium+
docker:
@@ -67,11 +77,11 @@ jobs:
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- run: yarn wsrun test:circleci @0x/contracts-multisig @0x/contracts-utils @0x/contracts-exchange-libs @0x/contracts-erc20 @0x/contracts-erc721 @0x/contracts-erc1155 @0x/contracts-asset-proxy @0x/contracts-exchange-forwarder @0x/contracts-dev-utils @0x/contracts-staking
# TODO(dorothy-zbornak): Re-enable after updating this package for 3.0.
- run: yarn wsrun test:circleci @0x/contracts-multisig @0x/contracts-utils @0x/contracts-exchange-libs @0x/contracts-erc20 @0x/contracts-erc721 @0x/contracts-erc1155 @0x/contracts-asset-proxy @0x/contracts-exchange-forwarder @0x/contracts-tests @0x/contracts-staking @0x/contracts-coordinator
# TODO(dorothy-zbornak): Re-enable after updating this package for
# 3.0. At that time, also remove exclusion from monorepo
# package.json's test script.
# - run: yarn wsrun test:circleci @0x/contracts-extensions
# TODO(abandeali): Re-enable after this package is complete.
# - run: yarn wsrun test:circleci @0x/contracts-coordinator
test-publish:
resource_class: medium+
docker:
@@ -82,7 +92,7 @@ jobs:
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- run:
- run:
command: yarn test:publish:circleci
no_output_timeout: 1800
test-doc-generation:
@@ -108,6 +118,9 @@ jobs:
- run: yarn wsrun test:circleci @0x/abi-gen
# TODO (xianny): Needs to be updated for 3.0
# - run: yarn wsrun test:circleci @0x/asset-buyer
# TODO: Needs to be updated for 3.0. At that time, also remove
# exclusion from monorepo package.json's test script.
# - run: yarn wsrun test:circleci @0x/asset-swapper
- run: yarn wsrun test:circleci @0x/contract-artifacts
- run: yarn wsrun test:circleci @0x/assert
- run: yarn wsrun test:circleci @0x/base-contract
@@ -117,6 +130,9 @@ jobs:
- run: yarn wsrun test:circleci @0x/dev-utils
- run: yarn wsrun test:circleci @0x/json-schemas
- run: yarn wsrun test:circleci @0x/order-utils
# TODO: Needs to be updated for 3.0. At that time, also remove
# exclusion from monorepo package.json's test script.
# - run: yarn wsrun test:circleci @0x/orderbook
- run: yarn wsrun test:circleci @0x/sol-compiler
- run: yarn wsrun test:circleci @0x/sol-tracing-utils
- run: yarn wsrun test:circleci @0x/sol-doc
@@ -184,14 +200,33 @@ jobs:
working_directory: ~/repo
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
- image: 0xorg/ganache-cli:2.2.2
- image: 0xorg/launch-kit-backend:74bcc39
- image: 0xorg/ganache-cli:4.4.0-beta.1
environment:
RPC_URL: http://localhost:8545
NETWORK_ID: 50
WHITELIST_ALL_TOKENS: True
VERSION: 4.4.0-beta.1
SNAPSHOT_NAME: 0x_ganache_snapshot-v3-beta
- image: 0xorg/mesh:6.0.0-beta-0xv3
environment:
ETHEREUM_RPC_URL: 'http://localhost:8545'
ETHEREUM_NETWORK_ID: '50'
ETHEREUM_CHAIN_ID: '1337'
USE_BOOTSTRAP_LIST: 'true'
VERBOSITY: 3
PRIVATE_KEY_PATH: ''
BLOCK_POLLING_INTERVAL: '5s'
P2P_LISTEN_PORT: '60557'
command: |
sh -c "until printf 'POST /\r\nContent-Length: 26\r\n\r\n{\"method\":\"net_listening\"}' | nc localhost 8545 | grep true; do continue; done; node_modules/.bin/forever ts/lib/index.js"
sh -c "waitForGanache () { until printf 'POST /\r\nContent-Length: 26\r\n\r\n{\"method\":\"net_listening\"}' | nc localhost 8545 | grep true; do continue; done }; waitForGanache && ./mesh"
- image: 0xorg/launch-kit-backend:v3
environment:
RPC_URL: 'http://localhost:8545'
CHAIN_ID: 1337
WHITELIST_ALL_TOKENS: True
FEE_RECIPIENT: '0x0000000000000000000000000000000000000001'
MAKER_FEE_UNIT_AMOUNT: 0
TAKER_FEE_UNIT_AMOUNT: 0
MESH_ENDPOINT: 'ws://localhost:60557'
command: |
sh -c "waitForMesh () { sleep 5; }; waitForMesh && node_modules/.bin/forever ts/lib/index.js"
steps:
- checkout
- restore_cache:
@@ -213,8 +248,14 @@ jobs:
- run:
command: |
cd python-packages
./parallel_without_sra_client coverage run setup.py test
./parallel coverage run setup.py test
./build_docs
- run:
command: |
# copy generated wrappers into contract_wrappers/build,
# JUST so CircleCI will persist them as build artifacts.
cd python-packages/contract_wrappers/src/zero_ex
for i in contract_wrappers/[^__]*/; do mkdir -p ../../build/$i; cp $i/__init__.py ../../build/$i; done
- save_cache:
key: coverage-python-contract-addresses-{{ .Environment.CIRCLE_SHA1 }}
paths:
@@ -239,8 +280,6 @@ jobs:
key: coverage-python-sra-client-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/python-packages/sra_client/.coverage
- store_artifacts:
path: ~/repo/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/*/__init__.py
- store_artifacts:
path: ~/repo/python-packages/contract_addresses/build
- store_artifacts:
@@ -394,6 +433,9 @@ workflows:
- test-exchange-ganache-3.0:
requires:
- build
- test-integrations-ganache-3.0:
requires:
- build
- test-contracts-rest-ganache-3.0:
requires:
- build
@@ -415,12 +457,11 @@ workflows:
- test-exchange-ganache-3.0
- test-rest
- static-tests
# - test-python:
# requires:
# - build
# - test-rest
# - static-tests-python:
# requires:
# - test-python
- test-python:
requires:
- build
- static-tests-python:
requires:
- build
# skip python tox run for now, as we don't yet have multiple test environments to support.
# - test-rest-python

View File

@@ -32,5 +32,3 @@ contracts: ['contracts']
@0x/json-schemas: ['packages/json-schemas']
@0x/ethereum-types: ['ethereum-types']
@0x/connect: ['packages/connect']
@0x/testnet-faucets: ['packages/testnet-faucets']
@0x/monorepo-scripts: ['packages/monorepo-scripts']

46
.gitignore vendored
View File

@@ -78,23 +78,35 @@ TODO.md
# VSCode file
.vscode
# server cli
packages/testnet-faucets/server/
# generated contract artifacts/
contracts/integrations/generated-artifacts/
contracts/integrations/test/generated-artifacts/
contracts/staking/generated-artifacts/
contracts/staking/test/generated-artifacts/
contracts/coordinator/generated-artifacts/
contracts/coordinator/test/generated-artifacts/
contracts/exchange/generated-artifacts/
contracts/exchange/test/generated-artifacts/
contracts/asset-proxy/generated-artifacts/
contracts/asset-proxy/test/generated-artifacts/
contracts/multisig/generated-artifacts/
contracts/multisig/test/generated-artifacts/
contracts/utils/generated-artifacts/
contracts/utils/test/generated-artifacts/
contracts/exchange-libs/generated-artifacts/
contracts/exchange-libs/test/generated-artifacts/
contracts/erc20/generated-artifacts/
contracts/erc20/test/generated-artifacts/
contracts/erc721/generated-artifacts/
contracts/erc721/test/generated-artifacts/
contracts/erc1155/generated-artifacts/
contracts/erc1155/test/generated-artifacts/
contracts/extensions/generated-artifacts/
contracts/extensions/test/generated-artifacts/
contracts/exchange-forwarder/generated-artifacts/
contracts/exchange-forwarder/test/generated-artifacts/
contracts/dev-utils/generated-artifacts/
contracts/dev-utils/test/generated-artifacts/
packages/sol-tracing-utils/test/fixtures/artifacts/
python-packages/contract_artifacts/src/zero_ex/contract_artifacts/artifacts/
@@ -115,19 +127,35 @@ contracts/dev-utils/build/
# generated contract wrappers
packages/python-contract-wrappers/generated/
contracts/integrations/generated-wrappers/
contracts/integrations/test/generated-wrappers/
contracts/staking/generated-wrappers/
contracts/staking/test/generated-wrappers/
contracts/coordinator/generated-wrappers/
contracts/coordinator/test/generated-wrappers/
contracts/exchange/generated-wrappers/
contracts/exchange/test/generated-wrappers/
contracts/asset-proxy/generated-wrappers/
contracts/asset-proxy/test/generated-wrappers/
contracts/multisig/generated-wrappers/
contracts/multisig/test/generated-wrappers/
contracts/utils/generated-wrappers/
contracts/utils/test/generated-wrappers/
contracts/exchange-libs/generated-wrappers/
contracts/exchange-libs/test/generated-wrappers/
contracts/erc20/generated-wrappers/
contracts/erc20/test/generated-wrappers/
contracts/erc721/generated-wrappers/
contracts/erc721/test/generated-wrappers/
contracts/erc1155/generated-wrappers/
contracts/erc1155/test/generated-wrappers/
contracts/extensions/generated-wrappers/
contracts/extensions/test/generated-wrappers/
contracts/exchange-forwarder/generated-wrappers/
contracts/exchange-forwarder/test/generated-wrappers/
contracts/dev-utils/generated-wrappers/
contracts/dev-utils/test/generated-wrappers/
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dev_utils/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc20_token/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/asset_proxy_owner/__init__.py
@@ -136,16 +164,20 @@ python-packages/contract_wrappers/src/zero_ex/contract_wrappers/coordinator_regi
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dummy_erc20_token/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dummy_erc721_token/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dutch_auction/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc1155_mintable/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc1155_proxy/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc20_proxy/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc721_proxy/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc721_token/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/eth_balance_checker/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/forwarder/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/i_asset_proxy/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/i_validator/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/i_wallet/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/multi_asset_proxy/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/order_validator/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/staking/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/staking_proxy/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/static_call_proxy/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/weth9/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/zrx_token/__init__.py
@@ -162,10 +194,14 @@ __pycache__
python-packages/*/src/*.egg-info
python-packages/*/.coverage
# python keeps package-local copies of json schemas
# python keeps package-local copies of json schemas and contract addresses
python-packages/json_schemas/src/zero_ex/json_schemas/schemas
python-packages/contract_addresses/src/zero_ex/contract_addresses/addresses.json
# Doc README copy
packages/*/docs/README.md
.DS_Store
# the snapshot that gets built for migrations sure does have a ton of files
packages/migrations/0x_ganache_snapshot*

View File

@@ -1,31 +1,61 @@
lib
.nyc_output
/contracts/integrations/generated-wrappers
/contracts/integrations/test/generated-wrappers
/contracts/integrations/generated-artifacts
/contracts/integrations/test/generated-artifacts
/contracts/staking/generated-wrappers
/contracts/staking/test/generated-wrappers
/contracts/staking/generated-artifacts
/contracts/staking/test/generated-artifacts
/contracts/coordinator/generated-wrappers
/contracts/coordinator/test/generated-wrappers
/contracts/coordinator/generated-artifacts
/contracts/coordinator/test/generated-artifacts
/contracts/exchange/generated-wrappers
/contracts/exchange/test/generated-wrappers
/contracts/exchange/generated-artifacts
/contracts/exchange/test/generated-artifacts
/contracts/asset-proxy/generated-wrappers
/contracts/asset-proxy/test/generated-wrappers
/contracts/asset-proxy/generated-artifacts
/contracts/asset-proxy/test/generated-artifacts
/contracts/multisig/generated-wrappers
/contracts/multisig/test/generated-wrappers
/contracts/multisig/generated-artifacts
/contracts/multisig/test/generated-artifacts
/contracts/utils/generated-wrappers
/contracts/utils/test/generated-wrappers
/contracts/utils/generated-artifacts
/contracts/utils/test/generated-artifacts
/contracts/exchange-libs/generated-wrappers
/contracts/exchange-libs/test/generated-wrappers
/contracts/exchange-libs/generated-artifacts
/contracts/exchange-libs/test/generated-artifacts
/contracts/erc20/generated-wrappers
/contracts/erc20/test/generated-wrappers
/contracts/erc20/generated-artifacts
/contracts/erc20/test/generated-artifacts
/contracts/erc721/generated-wrappers
/contracts/erc721/test/generated-wrappers
/contracts/erc721/generated-artifacts
/contracts/erc721/test/generated-artifacts
/contracts/erc1155/generated-wrappers
/contracts/erc1155/test/generated-wrappers
/contracts/erc1155/generated-artifacts
/contracts/erc1155/test/generated-artifacts
/contracts/extensions/generated-wrappers
/contracts/extensions/test/generated-wrappers
/contracts/extensions/generated-artifacts
/contracts/extensions/test/generated-artifacts
/contracts/exchange-forwarder/generated-wrappers
/contracts/exchange-forwarder/test/generated-wrappers
/contracts/exchange-forwarder/generated-artifacts
/contracts/exchange-forwarder/test/generated-artifacts
/contracts/dev-utils/generated-wrappers
/contracts/dev-utils/test/generated-wrappers
/contracts/dev-utils/generated-artifacts
/contracts/dev-utils/test/generated-artifacts
/contracts/staking/build/
/contracts/coordinator/build/
/contracts/exchange/build/

View File

@@ -1,6 +1,6 @@
{
"tabWidth": 4,
"printWidth": 120,
"trailingComma": all,
"singleQuote": true
"tabWidth": 4,
"singleQuote": true,
"trailingComma": "all"
}

View File

@@ -96,10 +96,9 @@ These packages are all under development. See [/contracts/README.md](/contracts/
#### Private Packages
| Package | Description |
| -------------------------------------------------- | -------------------------------------------------------------------------------- |
| [`@0x/instant`](/packages/instant) | A free and flexible way to offer simple crypto purchasing in any app or website. |
| [`@0x/testnet-faucets`](/packages/testnet-faucets) | A faucet micro-service that dispenses test ERC20 tokens or Ether |
| Package | Description |
| ---------------------------------- | -------------------------------------------------------------------------------- |
| [`@0x/instant`](/packages/instant) | A free and flexible way to offer simple crypto purchasing in any app or website. |
## Usage

View File

@@ -0,0 +1,10 @@
# Blacklist all files
.*
*
# Whitelist lib
!lib/**/*
# Whitelist Solidity contracts
!contracts/src/**/*
# Blacklist tests in lib
/lib/test/*
# Package specific ignore

View File

@@ -1,4 +1,33 @@
[
{
"version": "2.3.0-beta.3",
"changes": [
{
"note": "Dependencies updated"
}
],
"timestamp": 1574238768
},
{
"version": "2.3.0-beta.2",
"changes": [
{
"note": "Drastically reduced bundle size by adding .npmignore, only exporting specific artifacts/wrappers/utils",
"pr": 2330
}
],
"timestamp": 1574030254
},
{
"version": "2.3.0-beta.1",
"changes": [
{
"note": "ERC20Wrapper and ERC1155ProxyWrapper constructors now require an instance of DevUtilsContract",
"pr": 2034
}
],
"timestamp": 1573159180
},
{
"version": "2.3.0-beta.0",
"changes": [
@@ -25,6 +54,14 @@
{
"note": "Add `Eth2DaiBridge`",
"pr": 2221
},
{
"note": "Add `UniswapBridge`",
"pr": 2233
},
{
"note": "Replaced `SafeMath` with `LibSafeMath`",
"pr": 2254
}
],
"timestamp": 1570135330

View File

@@ -5,6 +5,18 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
## v2.3.0-beta.3 - _November 20, 2019_
* Dependencies updated
## v2.3.0-beta.2 - _November 17, 2019_
* Drastically reduced bundle size by adding .npmignore, only exporting specific artifacts/wrappers/utils (#2330)
## v2.3.0-beta.1 - _November 7, 2019_
* ERC20Wrapper and ERC1155ProxyWrapper constructors now require an instance of DevUtilsContract (#2034)
## v2.3.0-beta.0 - _October 3, 2019_
* Disallow the zero address from being made an authorized address in MixinAuthorizable, and created an archive directory that includes an old version of Ownable (#2019)
@@ -13,6 +25,8 @@ CHANGELOG
* Remove unused dependency on IAuthorizable in IAssetProxy (#1910)
* Add `ERC20BridgeProxy` (#2220)
* Add `Eth2DaiBridge` (#2221)
* Add `UniswapBridge` (#2233)
* Replaced `SafeMath` with `LibSafeMath` (#2254)
## v2.2.8 - _September 17, 2019_

View File

@@ -1,5 +1,5 @@
{
"artifactsDir": "./generated-artifacts",
"artifactsDir": "./test/generated-artifacts",
"contractsDir": "./contracts",
"useDockerisedSolc": false,
"isOfflineMode": false,

View File

@@ -19,7 +19,7 @@
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/SafeMath.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "@0x/contracts-erc1155/contracts/src/interfaces/IERC1155.sol";
import "../archive/MixinAuthorizable.sol";
import "./interfaces/IAssetProxy.sol";
@@ -27,10 +27,10 @@ import "./interfaces/IAssetProxy.sol";
contract ERC1155Proxy is
MixinAuthorizable,
SafeMath,
IAssetProxy
{
using LibBytes for bytes;
using LibSafeMath for uint256;
// Id of this proxy.
bytes4 constant internal PROXY_ID = bytes4(keccak256("ERC1155Assets(address,uint256[],uint256[],bytes)"));
@@ -71,7 +71,7 @@ contract ERC1155Proxy is
// to avoid copying over `ids` or `data`. This is possible if they are
// identical to `values` and the offsets for each are pointing to the
// same location in the ABI encoded calldata.
scaledValues[i] = _safeMul(values[i], amount);
scaledValues[i] = values[i].safeMul(amount);
}
// Execute `safeBatchTransferFrom` call

View File

@@ -73,7 +73,7 @@ contract ERC20BridgeProxy is
uint256 balanceBefore = balanceOf(tokenAddress, to);
// Call the bridge, who should transfer `amount` of `tokenAddress` to
// `to`.
bytes4 success = IERC20Bridge(bridgeAddress).withdrawTo(
bytes4 success = IERC20Bridge(bridgeAddress).bridgeTransferFrom(
tokenAddress,
from,
to,

View File

@@ -20,9 +20,10 @@ pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/interfaces/IERC20Token.sol";
import "@0x/contracts-erc20/contracts/src/LibERC20Token.sol";
import "@0x/contracts-exchange-libs/contracts/src/IWallet.sol";
import "../interfaces/IERC20Bridge.sol";
import "../interfaces/IEth2Dai.sol";
import "../interfaces/IWallet.sol";
// solhint-disable space-after-comma
@@ -42,7 +43,7 @@ contract Eth2DaiBridge is
/// @param amount Minimum amount of `toTokenAddress` tokens to buy.
/// @param bridgeData The abi-encoeded "from" token address.
/// @return success The magic bytes if successful.
function withdrawTo(
function bridgeTransferFrom(
address toTokenAddress,
address /* from */,
address to,
@@ -57,7 +58,7 @@ contract Eth2DaiBridge is
IEth2Dai exchange = _getEth2DaiContract();
// Grant an allowance to the exchange to spend `fromTokenAddress` token.
IERC20Token(fromTokenAddress).approve(address(exchange), uint256(-1));
LibERC20Token.approve(fromTokenAddress, address(exchange), uint256(-1));
// Try to sell all of this contract's `fromTokenAddress` token balance.
uint256 boughtAmount = _getEth2DaiContract().sellAllAmount(
@@ -67,7 +68,7 @@ contract Eth2DaiBridge is
amount
);
// Transfer the converted `toToken`s to `to`.
_transferERC20Token(toTokenAddress, to, boughtAmount);
LibERC20Token.transfer(toTokenAddress, to, boughtAmount);
return BRIDGE_SUCCESS;
}
@@ -94,49 +95,4 @@ contract Eth2DaiBridge is
{
return IEth2Dai(ETH2DAI_ADDRESS);
}
/// @dev Permissively transfers an ERC20 token that may not adhere to
/// specs.
/// @param tokenAddress The token contract address.
/// @param to The token recipient.
/// @param amount The amount of tokens to transfer.
function _transferERC20Token(
address tokenAddress,
address to,
uint256 amount
)
private
{
// Transfer tokens.
// We do a raw call so we can check the success separate
// from the return data.
(bool didSucceed, bytes memory returnData) = tokenAddress.call(
abi.encodeWithSelector(
IERC20Token(0).transfer.selector,
to,
amount
)
);
if (!didSucceed) {
assembly { revert(add(returnData, 0x20), mload(returnData)) }
}
// 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 {
didSucceed := 0
if eq(returndatasize, 32) {
// First 64 bytes of memory are reserved scratch space
returndatacopy(0, 0, 32)
didSucceed := mload(0)
}
}
}
require(didSucceed, "ERC20_TRANSFER_FAILED");
}
}

View File

@@ -0,0 +1,219 @@
/*
Copyright 2019 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.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/interfaces/IERC20Token.sol";
import "@0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol";
import "@0x/contracts-erc20/contracts/src/LibERC20Token.sol";
import "@0x/contracts-exchange-libs/contracts/src/IWallet.sol";
import "../interfaces/IUniswapExchangeFactory.sol";
import "../interfaces/IUniswapExchange.sol";
import "../interfaces/IERC20Bridge.sol";
// solhint-disable space-after-comma
// solhint-disable not-rely-on-time
contract UniswapBridge is
IERC20Bridge,
IWallet
{
/* Mainnet addresses */
address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95;
address constant private WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// Struct to hold `bridgeTransferFrom()` local variables in memory and to avoid
// stack overflows.
struct WithdrawToState {
IUniswapExchange exchange;
uint256 fromTokenBalance;
IEtherToken weth;
}
// solhint-disable no-empty-blocks
/// @dev Payable fallback to receive ETH from uniswap.
function ()
external
payable
{}
/// @dev Callback for `IERC20Bridge`. Tries to buy `amount` of
/// `toTokenAddress` tokens by selling the entirety of the `fromTokenAddress`
/// token encoded in the bridge data.
/// @param toTokenAddress The token to buy and transfer to `to`.
/// @param to The recipient of the bought tokens.
/// @param amount Minimum amount of `toTokenAddress` tokens to buy.
/// @param bridgeData The abi-encoded "from" token address.
/// @return success The magic bytes if successful.
function bridgeTransferFrom(
address toTokenAddress,
address /* from */,
address to,
uint256 amount,
bytes calldata bridgeData
)
external
returns (bytes4 success)
{
// State memory object to avoid stack overflows.
WithdrawToState memory state;
// Decode the bridge data to get the `fromTokenAddress`.
(address fromTokenAddress) = abi.decode(bridgeData, (address));
// Just transfer the tokens if they're the same.
if (fromTokenAddress == toTokenAddress) {
LibERC20Token.transfer(fromTokenAddress, to, amount);
return BRIDGE_SUCCESS;
}
// Get the exchange for the token pair.
state.exchange = _getUniswapExchangeForTokenPair(
fromTokenAddress,
toTokenAddress
);
// Get our balance of `fromTokenAddress` token.
state.fromTokenBalance = IERC20Token(fromTokenAddress).balanceOf(address(this));
// Get the weth contract.
state.weth = getWethContract();
// Convert from WETH to a token.
if (fromTokenAddress == address(state.weth)) {
// Unwrap the WETH.
state.weth.withdraw(state.fromTokenBalance);
// Buy as much of `toTokenAddress` token with ETH as possible and
// transfer it to `to`.
state.exchange.ethToTokenTransferInput.value(state.fromTokenBalance)(
// Minimum buy amount.
amount,
// Expires after this block.
block.timestamp,
// Recipient is `to`.
to
);
// Convert from a token to WETH.
} else if (toTokenAddress == address(state.weth)) {
// Grant the exchange an allowance.
_grantExchangeAllowance(state.exchange, fromTokenAddress);
// Buy as much ETH with `fromTokenAddress` token as possible.
uint256 ethBought = state.exchange.tokenToEthSwapInput(
// Sell all tokens we hold.
state.fromTokenBalance,
// Minimum buy amount.
amount,
// Expires after this block.
block.timestamp
);
// Wrap the ETH.
state.weth.deposit.value(ethBought)();
// Transfer the WETH to `to`.
IEtherToken(toTokenAddress).transfer(to, ethBought);
// Convert from one token to another.
} else {
// Grant the exchange an allowance.
_grantExchangeAllowance(state.exchange, fromTokenAddress);
// Buy as much `toTokenAddress` token with `fromTokenAddress` token
// and transfer it to `to`.
state.exchange.tokenToTokenTransferInput(
// Sell all tokens we hold.
state.fromTokenBalance,
// Minimum buy amount.
amount,
// No minimum intermediate ETH buy amount.
0,
// Expires after this block.
block.timestamp,
// Recipient is `to`.
to,
// Convert to `toTokenAddress`.
toTokenAddress
);
}
return BRIDGE_SUCCESS;
}
/// @dev `SignatureType.Wallet` callback, so that this bridge can be the maker
/// and sign for itself in orders. Always succeeds.
/// @return magicValue Success bytes, always.
function isValidSignature(
bytes32,
bytes calldata
)
external
view
returns (bytes4 magicValue)
{
return LEGACY_WALLET_MAGIC_VALUE;
}
/// @dev Overridable way to get the weth contract.
/// @return token The WETH contract.
function getWethContract()
public
view
returns (IEtherToken token)
{
return IEtherToken(WETH_ADDRESS);
}
/// @dev Overridable way to get the uniswap exchange factory contract.
/// @return factory The exchange factory contract.
function getUniswapExchangeFactoryContract()
public
view
returns (IUniswapExchangeFactory factory)
{
return IUniswapExchangeFactory(UNISWAP_EXCHANGE_FACTORY_ADDRESS);
}
/// @dev Grants an unlimited allowance to the exchange for its token
/// on behalf of this contract.
/// @param exchange The Uniswap token exchange.
/// @param tokenAddress The token address for the exchange.
function _grantExchangeAllowance(IUniswapExchange exchange, address tokenAddress)
private
{
LibERC20Token.approve(tokenAddress, address(exchange), uint256(-1));
}
/// @dev Retrieves the uniswap exchange for a given token pair.
/// In the case of a WETH-token exchange, this will be the non-WETH token.
/// In th ecase of a token-token exchange, this will be the first token.
/// @param fromTokenAddress The address of the token we are converting from.
/// @param toTokenAddress The address of the token we are converting to.
/// @return exchange The uniswap exchange.
function _getUniswapExchangeForTokenPair(
address fromTokenAddress,
address toTokenAddress
)
private
view
returns (IUniswapExchange exchange)
{
address exchangeTokenAddress = fromTokenAddress;
// Whichever isn't WETH is the exchange token.
if (fromTokenAddress == address(getWethContract())) {
exchangeTokenAddress = toTokenAddress;
}
exchange = getUniswapExchangeFactoryContract().getExchange(exchangeTokenAddress);
require(address(exchange) != address(0), "NO_UNISWAP_EXCHANGE_FOR_TOKEN");
return exchange;
}
}

View File

@@ -31,7 +31,7 @@ contract IERC20Bridge {
/// @param amount Amount of asset to transfer.
/// @param bridgeData Arbitrary asset data needed by the bridge contract.
/// @return success The magic bytes `0x37708e9b` if successful.
function withdrawTo(
function bridgeTransferFrom(
address tokenAddress,
address from,
address to,

View File

@@ -0,0 +1,77 @@
/*
Copyright 2019 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.5.9;
interface IUniswapExchange {
/// @dev Buys at least `minTokensBought` tokens with ETH and transfer them
/// to `recipient`.
/// @param minTokensBought The minimum number of tokens to buy.
/// @param deadline Time when this order expires.
/// @param recipient Who to transfer the tokens to.
/// @return tokensBought Amount of tokens bought.
function ethToTokenTransferInput(
uint256 minTokensBought,
uint256 deadline,
address recipient
)
external
payable
returns (uint256 tokensBought);
/// @dev Buys at least `minEthBought` ETH with tokens.
/// @param tokensSold Amount of tokens to sell.
/// @param minEthBought The minimum amount of ETH to buy.
/// @param deadline Time when this order expires.
/// @return ethBought Amount of tokens bought.
function tokenToEthSwapInput(
uint256 tokensSold,
uint256 minEthBought,
uint256 deadline
)
external
returns (uint256 ethBought);
/// @dev Buys at least `minTokensBought` tokens with the exchange token
/// and transfer them to `recipient`.
/// @param minTokensBought The minimum number of tokens to buy.
/// @param minEthBought The minimum amount of intermediate ETH to buy.
/// @param deadline Time when this order expires.
/// @param recipient Who to transfer the tokens to.
/// @param toTokenAddress The token being bought.
/// @return tokensBought Amount of tokens bought.
function tokenToTokenTransferInput(
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address recipient,
address toTokenAddress
)
external
returns (uint256 tokensBought);
/// @dev Retrieves the token that is associated with this exchange.
/// @return tokenAddress The token address.
function toTokenAddress()
external
view
returns (address tokenAddress);
}

View File

@@ -16,22 +16,17 @@
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
pragma solidity ^0.5.9;
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "../src/MixinSignatureValidator.sol";
import "../src/MixinTransactions.sol";
import "./IUniswapExchange.sol";
contract TestSignatureValidator is
LibEIP712ExchangeDomain,
MixinSignatureValidator
{
interface IUniswapExchangeFactory {
// solhint-disable no-empty-blocks
constructor (uint256 chainId)
public
LibEIP712ExchangeDomain(chainId, address(0))
{}
/// @dev Get the exchange for a token.
/// @param tokenAddress The address of the token contract.
function getExchange(address tokenAddress)
external
view
returns (IUniswapExchange);
}

View File

@@ -72,7 +72,7 @@ contract TestERC20Bridge is
testToken.setBalance(owner, balance);
}
function withdrawTo(
function bridgeTransferFrom(
address tokenAddress,
address from,
address to,

View File

@@ -0,0 +1,432 @@
/*
Copyright 2019 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.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/interfaces/IERC20Token.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "../src/bridges/UniswapBridge.sol";
import "../src/interfaces/IUniswapExchangeFactory.sol";
import "../src/interfaces/IUniswapExchange.sol";
// solhint-disable no-simple-event-func-name
contract TestEventsRaiser {
event TokenTransfer(
address token,
address from,
address to,
uint256 amount
);
event TokenApprove(
address spender,
uint256 allowance
);
event WethDeposit(
uint256 amount
);
event WethWithdraw(
uint256 amount
);
event EthToTokenTransferInput(
address exchange,
uint256 minTokensBought,
uint256 deadline,
address recipient
);
event TokenToEthSwapInput(
address exchange,
uint256 tokensSold,
uint256 minEthBought,
uint256 deadline
);
event TokenToTokenTransferInput(
address exchange,
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address recipient,
address toTokenAddress
);
function raiseEthToTokenTransferInput(
uint256 minTokensBought,
uint256 deadline,
address recipient
)
external
{
emit EthToTokenTransferInput(
msg.sender,
minTokensBought,
deadline,
recipient
);
}
function raiseTokenToEthSwapInput(
uint256 tokensSold,
uint256 minEthBought,
uint256 deadline
)
external
{
emit TokenToEthSwapInput(
msg.sender,
tokensSold,
minEthBought,
deadline
);
}
function raiseTokenToTokenTransferInput(
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address recipient,
address toTokenAddress
)
external
{
emit TokenToTokenTransferInput(
msg.sender,
tokensSold,
minTokensBought,
minEthBought,
deadline,
recipient,
toTokenAddress
);
}
function raiseTokenTransfer(
address from,
address to,
uint256 amount
)
external
{
emit TokenTransfer(
msg.sender,
from,
to,
amount
);
}
function raiseTokenApprove(address spender, uint256 allowance)
external
{
emit TokenApprove(spender, allowance);
}
function raiseWethDeposit(uint256 amount)
external
{
emit WethDeposit(amount);
}
function raiseWethWithdraw(uint256 amount)
external
{
emit WethWithdraw(amount);
}
}
/// @dev A minimalist ERC20/WETH token.
contract TestToken {
using LibSafeMath for uint256;
mapping (address => uint256) public balances;
string private _nextRevertReason;
/// @dev Set the balance for `owner`.
function setBalance(address owner)
external
payable
{
balances[owner] = msg.value;
}
/// @dev Set the revert reason for `transfer()`,
/// `deposit()`, and `withdraw()`.
function setRevertReason(string calldata reason)
external
{
_nextRevertReason = reason;
}
/// @dev Just calls `raiseTokenTransfer()` on the caller.
function transfer(address to, uint256 amount)
external
returns (bool)
{
_revertIfReasonExists();
TestEventsRaiser(msg.sender).raiseTokenTransfer(msg.sender, to, amount);
return true;
}
/// @dev Just calls `raiseTokenApprove()` on the caller.
function approve(address spender, uint256 allowance)
external
returns (bool)
{
TestEventsRaiser(msg.sender).raiseTokenApprove(spender, allowance);
return true;
}
/// @dev `IWETH.deposit()` that increases balances and calls
/// `raiseWethDeposit()` on the caller.
function deposit()
external
payable
{
_revertIfReasonExists();
balances[msg.sender] += balances[msg.sender].safeAdd(msg.value);
TestEventsRaiser(msg.sender).raiseWethDeposit(msg.value);
}
/// @dev `IWETH.withdraw()` that just reduces balances and calls
/// `raiseWethWithdraw()` on the caller.
function withdraw(uint256 amount)
external
{
_revertIfReasonExists();
balances[msg.sender] = balances[msg.sender].safeSub(amount);
msg.sender.transfer(amount);
TestEventsRaiser(msg.sender).raiseWethWithdraw(amount);
}
/// @dev Retrieve the balance for `owner`.
function balanceOf(address owner)
external
view
returns (uint256)
{
return balances[owner];
}
function _revertIfReasonExists()
private
view
{
if (bytes(_nextRevertReason).length != 0) {
revert(_nextRevertReason);
}
}
}
contract TestExchange is
IUniswapExchange
{
address public tokenAddress;
string private _nextRevertReason;
constructor(address _tokenAddress) public {
tokenAddress = _tokenAddress;
}
function setFillBehavior(
string calldata revertReason
)
external
payable
{
_nextRevertReason = revertReason;
}
function ethToTokenTransferInput(
uint256 minTokensBought,
uint256 deadline,
address recipient
)
external
payable
returns (uint256 tokensBought)
{
TestEventsRaiser(msg.sender).raiseEthToTokenTransferInput(
minTokensBought,
deadline,
recipient
);
_revertIfReasonExists();
return address(this).balance;
}
function tokenToEthSwapInput(
uint256 tokensSold,
uint256 minEthBought,
uint256 deadline
)
external
returns (uint256 ethBought)
{
TestEventsRaiser(msg.sender).raiseTokenToEthSwapInput(
tokensSold,
minEthBought,
deadline
);
_revertIfReasonExists();
uint256 fillAmount = address(this).balance;
msg.sender.transfer(fillAmount);
return fillAmount;
}
function tokenToTokenTransferInput(
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address recipient,
address toTokenAddress
)
external
returns (uint256 tokensBought)
{
TestEventsRaiser(msg.sender).raiseTokenToTokenTransferInput(
tokensSold,
minTokensBought,
minEthBought,
deadline,
recipient,
toTokenAddress
);
_revertIfReasonExists();
return address(this).balance;
}
function toTokenAddress()
external
view
returns (address _tokenAddress)
{
return tokenAddress;
}
function _revertIfReasonExists()
private
view
{
if (bytes(_nextRevertReason).length != 0) {
revert(_nextRevertReason);
}
}
}
/// @dev UniswapBridge overridden to mock tokens and implement IUniswapExchangeFactory.
contract TestUniswapBridge is
IUniswapExchangeFactory,
TestEventsRaiser,
UniswapBridge
{
TestToken public wethToken;
// Token address to TestToken instance.
mapping (address => TestToken) private _testTokens;
// Token address to TestExchange instance.
mapping (address => TestExchange) private _testExchanges;
constructor() public {
wethToken = new TestToken();
_testTokens[address(wethToken)] = wethToken;
}
/// @dev Sets the balance of this contract for an existing token.
/// The wei attached will be the balance.
function setTokenBalance(address tokenAddress)
external
payable
{
TestToken token = _testTokens[tokenAddress];
token.deposit.value(msg.value)();
}
/// @dev Sets the revert reason for an existing token.
function setTokenRevertReason(address tokenAddress, string calldata revertReason)
external
{
TestToken token = _testTokens[tokenAddress];
token.setRevertReason(revertReason);
}
/// @dev Create a token and exchange (if they don't exist) for a new token
/// and sets the exchange revert and fill behavior. The wei attached
/// will be the fill amount for the exchange.
/// @param tokenAddress The token address. If zero, one will be created.
/// @param revertReason The revert reason for exchange operations.
function createTokenAndExchange(
address tokenAddress,
string calldata revertReason
)
external
payable
returns (TestToken token, TestExchange exchange)
{
token = TestToken(tokenAddress);
if (tokenAddress == address(0)) {
token = new TestToken();
}
_testTokens[address(token)] = token;
exchange = _testExchanges[address(token)];
if (address(exchange) == address(0)) {
_testExchanges[address(token)] = exchange = new TestExchange(address(token));
}
exchange.setFillBehavior.value(msg.value)(revertReason);
return (token, exchange);
}
/// @dev `IUniswapExchangeFactory.getExchange`
function getExchange(address tokenAddress)
external
view
returns (IUniswapExchange)
{
return IUniswapExchange(_testExchanges[tokenAddress]);
}
// @dev Use `wethToken`.
function getWethContract()
public
view
returns (IEtherToken)
{
return IEtherToken(address(wethToken));
}
// @dev This contract will double as the Uniswap contract.
function getUniswapExchangeFactoryContract()
public
view
returns (IUniswapExchangeFactory)
{
return IUniswapExchangeFactory(address(this));
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@0x/contracts-asset-proxy",
"version": "2.3.0-beta.0",
"version": "2.3.0-beta.3",
"engines": {
"node": ">=6.12"
},
@@ -12,7 +12,7 @@
"scripts": {
"build": "yarn pre_build && tsc -b",
"build:ci": "yarn build",
"pre_build": "run-s compile contracts:gen generate_contract_wrappers",
"pre_build": "run-s compile contracts:gen generate_contract_wrappers contracts:copy",
"test": "yarn run_mocha",
"rebuild_and_test": "run-s build test",
"test:coverage": "SOLIDITY_COVERAGE=true run-s build run_mocha coverage:report:text coverage:report:lcov",
@@ -21,21 +21,25 @@
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe 'lib/test/**/*.js' --timeout 100000 --bail --exit",
"compile": "sol-compiler",
"watch": "sol-compiler -w",
"clean": "shx rm -rf lib generated-artifacts generated-wrappers",
"generate_contract_wrappers": "abi-gen --abis ${npm_package_config_abis} --output generated-wrappers --backend ethers",
"lint": "tslint --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"fix": "tslint --fix --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"clean": "shx rm -rf lib test/generated-artifacts test/generated-wrappers generated-artifacts generated-wrappers",
"generate_contract_wrappers": "abi-gen --debug --abis ${npm_package_config_abis} --output test/generated-wrappers --backend ethers",
"lint": "tslint --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./test/generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude ./test/generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"fix": "tslint --fix --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./test/generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude ./test/generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"coverage:report:text": "istanbul report text",
"coverage:report:html": "istanbul report html && open coverage/index.html",
"profiler:report:html": "istanbul report html && open coverage/index.html",
"coverage:report:lcov": "istanbul report lcov",
"test:circleci": "yarn test",
"contracts:gen": "contracts-gen",
"contracts:gen": "contracts-gen generate",
"contracts:copy": "contracts-gen copy",
"lint-contracts": "solhint -c ../.solhint.json contracts/**/**/**/**/*.sol",
"compile:truffle": "truffle compile"
"compile:truffle": "truffle compile",
"docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json",
"docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES"
},
"config": {
"abis": "./generated-artifacts/@(ERC1155Proxy|ERC20BridgeProxy|ERC20Proxy|ERC721Proxy|Eth2DaiBridge|IAssetData|IAssetProxy|IAssetProxyDispatcher|IAuthorizable|IERC20Bridge|IEth2Dai|IWallet|MixinAssetProxyDispatcher|MixinAuthorizable|MultiAssetProxy|Ownable|StaticCallProxy|TestERC20Bridge|TestEth2DaiBridge|TestStaticCallTarget).json",
"publicInterfaceContracts": "ERC1155Proxy,ERC20Proxy,ERC721Proxy,MultiAssetProxy,StaticCallProxy,ERC20BridgeProxy,Eth2DaiBridge,IAssetData,IAssetProxy,UniswapBridge,TestStaticCallTarget",
"abis": "./test/generated-artifacts/@(ERC1155Proxy|ERC20BridgeProxy|ERC20Proxy|ERC721Proxy|Eth2DaiBridge|IAssetData|IAssetProxy|IAssetProxyDispatcher|IAuthorizable|IERC20Bridge|IEth2Dai|IUniswapExchange|IUniswapExchangeFactory|MixinAssetProxyDispatcher|MixinAuthorizable|MultiAssetProxy|Ownable|StaticCallProxy|TestERC20Bridge|TestEth2DaiBridge|TestStaticCallTarget|TestUniswapBridge|UniswapBridge).json",
"abis:comment": "This list is auto-generated by contracts-gen. Don't edit manually."
},
"repository": {
@@ -48,12 +52,15 @@
},
"homepage": "https://github.com/0xProject/0x-monorepo/contracts/protocol/README.md",
"devDependencies": {
"@0x/abi-gen": "^4.3.0-beta.0",
"@0x/contracts-gen": "^1.1.0-beta.0",
"@0x/contracts-test-utils": "^3.2.0-beta.0",
"@0x/dev-utils": "^2.4.0-beta.0",
"@0x/sol-compiler": "^3.2.0-beta.0",
"@0x/tslint-config": "^3.0.1",
"@0x/abi-gen": "^4.4.0-beta.3",
"@0x/contracts-gen": "^1.1.0-beta.3",
"@0x/contracts-test-utils": "^3.2.0-beta.3",
"@0x/contracts-utils": "^3.3.0-beta.3",
"@0x/dev-utils": "^2.4.0-beta.3",
"@0x/sol-compiler": "^3.2.0-beta.3",
"@0x/ts-doc-gen": "^0.0.22",
"@0x/tslint-config": "^3.1.0-beta.2",
"@0x/types": "^2.5.0-beta.2",
"@types/lodash": "4.14.104",
"@types/mocha": "^5.2.7",
"@types/node": "*",
@@ -61,6 +68,7 @@
"chai-as-promised": "^7.1.0",
"chai-bignumber": "^3.0.0",
"dirty-chai": "^2.0.1",
"ethereumjs-util": "^5.1.1",
"make-promises-safe": "^1.1.0",
"mocha": "^6.2.0",
"npm-run-all": "^4.1.2",
@@ -68,21 +76,20 @@
"solhint": "^1.4.1",
"truffle": "^5.0.32",
"tslint": "5.11.0",
"typedoc": "^0.15.0",
"typescript": "3.0.1"
},
"dependencies": {
"@0x/base-contract": "^5.5.0-beta.0",
"@0x/contracts-erc1155": "^1.2.0-beta.0",
"@0x/contracts-erc20": "^2.3.0-beta.0",
"@0x/contracts-erc721": "^2.2.0-beta.0",
"@0x/contracts-utils": "^3.3.0-beta.0",
"@0x/order-utils": "^8.5.0-beta.0",
"@0x/types": "^2.5.0-beta.0",
"@0x/typescript-typings": "^4.4.0-beta.0",
"@0x/utils": "^4.6.0-beta.0",
"@0x/web3-wrapper": "^6.1.0-beta.0",
"ethereum-types": "^2.2.0-beta.0",
"ethereumjs-util": "^5.1.1",
"@0x/base-contract": "^5.5.0-beta.3",
"@0x/contracts-dev-utils": "^0.1.0-beta.3",
"@0x/contracts-erc1155": "^1.2.0-beta.3",
"@0x/contracts-erc20": "^2.3.0-beta.3",
"@0x/contracts-erc721": "^2.2.0-beta.3",
"@0x/order-utils": "^8.5.0-beta.3",
"@0x/typescript-typings": "^4.4.0-beta.2",
"@0x/utils": "^4.6.0-beta.2",
"@0x/web3-wrapper": "^6.1.0-beta.2",
"ethereum-types": "^2.2.0-beta.2",
"lodash": "^4.17.11"
},
"publishConfig": {

View File

@@ -12,38 +12,20 @@ import * as ERC721Proxy from '../generated-artifacts/ERC721Proxy.json';
import * as Eth2DaiBridge from '../generated-artifacts/Eth2DaiBridge.json';
import * as IAssetData from '../generated-artifacts/IAssetData.json';
import * as IAssetProxy from '../generated-artifacts/IAssetProxy.json';
import * as IAssetProxyDispatcher from '../generated-artifacts/IAssetProxyDispatcher.json';
import * as IAuthorizable from '../generated-artifacts/IAuthorizable.json';
import * as IERC20Bridge from '../generated-artifacts/IERC20Bridge.json';
import * as IEth2Dai from '../generated-artifacts/IEth2Dai.json';
import * as IWallet from '../generated-artifacts/IWallet.json';
import * as MixinAssetProxyDispatcher from '../generated-artifacts/MixinAssetProxyDispatcher.json';
import * as MixinAuthorizable from '../generated-artifacts/MixinAuthorizable.json';
import * as MultiAssetProxy from '../generated-artifacts/MultiAssetProxy.json';
import * as Ownable from '../generated-artifacts/Ownable.json';
import * as StaticCallProxy from '../generated-artifacts/StaticCallProxy.json';
import * as TestERC20Bridge from '../generated-artifacts/TestERC20Bridge.json';
import * as TestEth2DaiBridge from '../generated-artifacts/TestEth2DaiBridge.json';
import * as TestStaticCallTarget from '../generated-artifacts/TestStaticCallTarget.json';
import * as UniswapBridge from '../generated-artifacts/UniswapBridge.json';
export const artifacts = {
MixinAssetProxyDispatcher: MixinAssetProxyDispatcher as ContractArtifact,
MixinAuthorizable: MixinAuthorizable as ContractArtifact,
Ownable: Ownable as ContractArtifact,
ERC1155Proxy: ERC1155Proxy as ContractArtifact,
ERC20BridgeProxy: ERC20BridgeProxy as ContractArtifact,
ERC20Proxy: ERC20Proxy as ContractArtifact,
ERC721Proxy: ERC721Proxy as ContractArtifact,
MultiAssetProxy: MultiAssetProxy as ContractArtifact,
StaticCallProxy: StaticCallProxy as ContractArtifact,
ERC20BridgeProxy: ERC20BridgeProxy as ContractArtifact,
Eth2DaiBridge: Eth2DaiBridge as ContractArtifact,
IAssetData: IAssetData as ContractArtifact,
IAssetProxy: IAssetProxy as ContractArtifact,
IAssetProxyDispatcher: IAssetProxyDispatcher as ContractArtifact,
IAuthorizable: IAuthorizable as ContractArtifact,
IERC20Bridge: IERC20Bridge as ContractArtifact,
IEth2Dai: IEth2Dai as ContractArtifact,
IWallet: IWallet as ContractArtifact,
TestERC20Bridge: TestERC20Bridge as ContractArtifact,
TestEth2DaiBridge: TestEth2DaiBridge as ContractArtifact,
UniswapBridge: UniswapBridge as ContractArtifact,
TestStaticCallTarget: TestStaticCallTarget as ContractArtifact,
};

View File

@@ -1,3 +1,4 @@
import { DevUtilsContract } from '@0x/contracts-dev-utils';
import { artifacts as erc1155Artifacts, ERC1155MintableContract, Erc1155Wrapper } from '@0x/contracts-erc1155';
import {
constants,
@@ -7,13 +8,14 @@ import {
LogDecoder,
txDefaults,
} from '@0x/contracts-test-utils';
import { assetDataUtils } from '@0x/order-utils';
import { BigNumber } from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wrapper';
import { Provider, TransactionReceiptWithDecodedLogs } from 'ethereum-types';
import * as _ from 'lodash';
import { artifacts, ERC1155ProxyContract, IAssetProxyContract } from '../../src';
import { artifacts } from './artifacts';
import { ERC1155ProxyContract, IAssetProxyContract } from './wrappers';
export class ERC1155ProxyWrapper {
private readonly _tokenOwnerAddresses: string[];
@@ -26,6 +28,7 @@ export class ERC1155ProxyWrapper {
private readonly _logDecoder: LogDecoder;
private readonly _dummyTokenWrappers: Erc1155Wrapper[];
private readonly _assetProxyInterface: IAssetProxyContract;
private readonly _devUtils: DevUtilsContract;
private _proxyContract?: ERC1155ProxyContract;
private _proxyIdIfExists?: string;
private _initialTokenIdsByOwner: ERC1155HoldingsByOwner = { fungible: {}, nonFungible: {} };
@@ -37,6 +40,7 @@ export class ERC1155ProxyWrapper {
this._logDecoder = new LogDecoder(this._web3Wrapper, allArtifacts);
this._dummyTokenWrappers = [];
this._assetProxyInterface = new IAssetProxyContract(constants.NULL_ADDRESS, provider);
this._devUtils = new DevUtilsContract(constants.NULL_ADDRESS, provider);
this._tokenOwnerAddresses = tokenOwnerAddresses;
this._contractOwnerAddress = contractOwnerAddress;
this._fungibleTokenIds = [];
@@ -72,7 +76,7 @@ export class ERC1155ProxyWrapper {
txDefaults,
artifacts,
);
this._proxyIdIfExists = await this._proxyContract.getProxyId.callAsync();
this._proxyIdIfExists = await this._proxyContract.getProxyId().callAsync();
return this._proxyContract;
}
/**
@@ -95,7 +99,7 @@ export class ERC1155ProxyWrapper {
* @param extraData extra data to append to `transferFrom` transaction. Optional.
* @return abi encoded tx data.
*/
public getTransferFromAbiEncodedTxData(
public async getTransferFromAbiEncodedTxDataAsync(
from: string,
to: string,
contractAddress: string,
@@ -105,23 +109,17 @@ export class ERC1155ProxyWrapper {
receiverCallbackData: string,
authorizedSender: string,
assetData_?: string,
): string {
): Promise<string> {
this._validateProxyContractExistsOrThrow();
const assetData =
assetData_ === undefined
? assetDataUtils.encodeERC1155AssetData(
contractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
? await this._devUtils
.encodeERC1155AssetData(contractAddress, tokensToTransfer, valuesToTransfer, receiverCallbackData)
.callAsync()
: assetData_;
const data = this._assetProxyInterface.transferFrom.getABIEncodedTransactionData(
assetData,
from,
to,
valueMultiplier,
);
const data = this._assetProxyInterface
.transferFrom(assetData, from, to, valueMultiplier)
.getABIEncodedTransactionData();
return data;
}
/**
@@ -169,19 +167,13 @@ export class ERC1155ProxyWrapper {
this._validateProxyContractExistsOrThrow();
const assetData =
assetData_ === undefined
? assetDataUtils.encodeERC1155AssetData(
contractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
? await this._devUtils
.encodeERC1155AssetData(contractAddress, tokensToTransfer, valuesToTransfer, receiverCallbackData)
.callAsync()
: assetData_;
const data = this._assetProxyInterface.transferFrom.getABIEncodedTransactionData(
assetData,
from,
to,
valueMultiplier,
);
const data = this._assetProxyInterface
.transferFrom(assetData, from, to, valueMultiplier)
.getABIEncodedTransactionData();
const txHash = await this._web3Wrapper.sendTransactionAsync({
to: (this._proxyContract as ERC1155ProxyContract).address,
data,
@@ -362,7 +354,7 @@ export class ERC1155ProxyWrapper {
this._validateProxyContractExistsOrThrow();
const tokenContract = this._getContractFromAddress(contractAddress);
const operator = (this._proxyContract as ERC1155ProxyContract).address;
const didApproveAll = await tokenContract.isApprovedForAll.callAsync(userAddress, operator);
const didApproveAll = await tokenContract.isApprovedForAll(userAddress, operator).callAsync();
return didApproveAll;
}
public getFungibleTokenIds(): BigNumber[] {

View File

@@ -1,17 +1,20 @@
import { DevUtilsContract } from '@0x/contracts-dev-utils';
import { artifacts as erc20Artifacts, DummyERC20TokenContract } from '@0x/contracts-erc20';
import { constants, ERC20BalancesByOwner, txDefaults } from '@0x/contracts-test-utils';
import { assetDataUtils } from '@0x/order-utils';
import { BigNumber } from '@0x/utils';
import { ZeroExProvider } from 'ethereum-types';
import * as _ from 'lodash';
import { artifacts, ERC20ProxyContract } from '../../src';
import { artifacts } from './artifacts';
import { ERC20ProxyContract } from './wrappers';
export class ERC20Wrapper {
private readonly _tokenOwnerAddresses: string[];
private readonly _contractOwnerAddress: string;
private readonly _provider: ZeroExProvider;
private readonly _dummyTokenContracts: DummyERC20TokenContract[];
private readonly _devUtils: DevUtilsContract;
private _proxyContract?: ERC20ProxyContract;
private _proxyIdIfExists?: string;
/**
@@ -26,6 +29,7 @@ export class ERC20Wrapper {
this._provider = provider;
this._tokenOwnerAddresses = tokenOwnerAddresses;
this._contractOwnerAddress = contractOwnerAddress;
this._devUtils = new DevUtilsContract(constants.NULL_ADDRESS, provider);
}
public async deployDummyTokensAsync(
numberToDeploy: number,
@@ -54,7 +58,7 @@ export class ERC20Wrapper {
txDefaults,
artifacts,
);
this._proxyIdIfExists = await this._proxyContract.getProxyId.callAsync();
this._proxyIdIfExists = await this._proxyContract.getProxyId().callAsync();
return this._proxyContract;
}
public getProxyId(): string {
@@ -66,50 +70,39 @@ export class ERC20Wrapper {
this._validateProxyContractExistsOrThrow();
for (const dummyTokenContract of this._dummyTokenContracts) {
for (const tokenOwnerAddress of this._tokenOwnerAddresses) {
await dummyTokenContract.setBalance.awaitTransactionSuccessAsync(
tokenOwnerAddress,
constants.INITIAL_ERC20_BALANCE,
{ from: this._contractOwnerAddress },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await dummyTokenContract.approve.awaitTransactionSuccessAsync(
(this._proxyContract as ERC20ProxyContract).address,
constants.INITIAL_ERC20_ALLOWANCE,
{ from: tokenOwnerAddress },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await dummyTokenContract
.setBalance(tokenOwnerAddress, constants.INITIAL_ERC20_BALANCE)
.awaitTransactionSuccessAsync({ from: this._contractOwnerAddress });
await dummyTokenContract
.approve((this._proxyContract as ERC20ProxyContract).address, constants.INITIAL_ERC20_ALLOWANCE)
.awaitTransactionSuccessAsync({ from: tokenOwnerAddress });
}
}
}
public async getBalanceAsync(userAddress: string, assetData: string): Promise<BigNumber> {
const tokenContract = this._getTokenContractFromAssetData(assetData);
const balance = new BigNumber(await tokenContract.balanceOf.callAsync(userAddress));
const tokenContract = await this._getTokenContractFromAssetDataAsync(assetData);
const balance = new BigNumber(await tokenContract.balanceOf(userAddress).callAsync());
return balance;
}
public async setBalanceAsync(userAddress: string, assetData: string, amount: BigNumber): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(assetData);
await tokenContract.setBalance.awaitTransactionSuccessAsync(
userAddress,
amount,
{ from: this._contractOwnerAddress },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const tokenContract = await this._getTokenContractFromAssetDataAsync(assetData);
await tokenContract
.setBalance(userAddress, amount)
.awaitTransactionSuccessAsync(
{ from: this._contractOwnerAddress },
{ pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS },
);
}
public async getProxyAllowanceAsync(userAddress: string, assetData: string): Promise<BigNumber> {
const tokenContract = this._getTokenContractFromAssetData(assetData);
const tokenContract = await this._getTokenContractFromAssetDataAsync(assetData);
const proxyAddress = (this._proxyContract as ERC20ProxyContract).address;
const allowance = new BigNumber(await tokenContract.allowance.callAsync(userAddress, proxyAddress));
const allowance = new BigNumber(await tokenContract.allowance(userAddress, proxyAddress).callAsync());
return allowance;
}
public async setAllowanceAsync(userAddress: string, assetData: string, amount: BigNumber): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(assetData);
const tokenContract = await this._getTokenContractFromAssetDataAsync(assetData);
const proxyAddress = (this._proxyContract as ERC20ProxyContract).address;
await tokenContract.approve.awaitTransactionSuccessAsync(
proxyAddress,
amount,
{ from: userAddress },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await tokenContract.approve(proxyAddress, amount).awaitTransactionSuccessAsync({ from: userAddress });
}
public async getBalancesAsync(): Promise<ERC20BalancesByOwner> {
this._validateDummyTokenContractsExistOrThrow();
@@ -118,7 +111,7 @@ export class ERC20Wrapper {
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));
balances.push(await dummyTokenContract.balanceOf(tokenOwnerAddress).callAsync());
balanceInfo.push({
tokenOwnerAddress,
tokenAddress: dummyTokenContract.address,
@@ -151,9 +144,8 @@ export class ERC20Wrapper {
const tokenAddresses = _.map(this._dummyTokenContracts, dummyTokenContract => dummyTokenContract.address);
return tokenAddresses;
}
private _getTokenContractFromAssetData(assetData: string): DummyERC20TokenContract {
const erc20ProxyData = assetDataUtils.decodeERC20AssetData(assetData);
const tokenAddress = erc20ProxyData.tokenAddress;
private async _getTokenContractFromAssetDataAsync(assetData: string): Promise<DummyERC20TokenContract> {
const [proxyId, tokenAddress] = await this._devUtils.decodeERC20AssetData(assetData).callAsync(); // tslint:disable-line:no-unused-variable
const tokenContractIfExists = _.find(this._dummyTokenContracts, c => c.address === tokenAddress);
if (tokenContractIfExists === undefined) {
throw new Error(`Token: ${tokenAddress} was not deployed through ERC20Wrapper`);

View File

@@ -5,7 +5,9 @@ import { BigNumber } from '@0x/utils';
import { ZeroExProvider } from 'ethereum-types';
import * as _ from 'lodash';
import { artifacts, ERC721ProxyContract } from '../../src';
import { artifacts } from './artifacts';
import { ERC721ProxyContract } from './wrappers';
export class ERC721Wrapper {
private readonly _tokenOwnerAddresses: string[];
@@ -44,7 +46,7 @@ export class ERC721Wrapper {
txDefaults,
artifacts,
);
this._proxyIdIfExists = await this._proxyContract.getProxyId.callAsync();
this._proxyIdIfExists = await this._proxyContract.getProxyId().callAsync();
return this._proxyContract;
}
public getProxyId(): string {
@@ -78,7 +80,7 @@ export class ERC721Wrapper {
}
public async doesTokenExistAsync(tokenAddress: string, tokenId: BigNumber): Promise<boolean> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const owner = await tokenContract.ownerOf.callAsync(tokenId);
const owner = await tokenContract.ownerOf(tokenId).callAsync();
const doesExist = owner !== constants.NULL_ADDRESS;
return doesExist;
}
@@ -93,22 +95,14 @@ export class ERC721Wrapper {
): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const proxyAddress = (this._proxyContract as ERC721ProxyContract).address;
await tokenContract.setApprovalForAll.awaitTransactionSuccessAsync(
proxyAddress,
isApproved,
{ from: ownerAddress },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await tokenContract.setApprovalForAll(proxyAddress, isApproved).awaitTransactionSuccessAsync({
from: ownerAddress,
});
}
public async approveAsync(to: string, tokenAddress: string, tokenId: BigNumber): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const tokenOwner = await this.ownerOfAsync(tokenAddress, tokenId);
await tokenContract.approve.awaitTransactionSuccessAsync(
to,
tokenId,
{ from: tokenOwner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await tokenContract.approve(to, tokenId).awaitTransactionSuccessAsync({ from: tokenOwner });
}
public async transferFromAsync(
tokenAddress: string,
@@ -117,40 +111,28 @@ export class ERC721Wrapper {
userAddress: string,
): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
await tokenContract.transferFrom.awaitTransactionSuccessAsync(
currentOwner,
userAddress,
tokenId,
{ from: currentOwner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await tokenContract.transferFrom(currentOwner, userAddress, tokenId).awaitTransactionSuccessAsync({
from: currentOwner,
});
}
public async mintAsync(tokenAddress: string, tokenId: BigNumber, userAddress: string): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
await tokenContract.mint.awaitTransactionSuccessAsync(
userAddress,
tokenId,
{ from: this._contractOwnerAddress },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await tokenContract.mint(userAddress, tokenId).awaitTransactionSuccessAsync({
from: this._contractOwnerAddress,
});
}
public async burnAsync(tokenAddress: string, tokenId: BigNumber, owner: string): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
await tokenContract.burn.awaitTransactionSuccessAsync(
owner,
tokenId,
{ from: this._contractOwnerAddress },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await tokenContract.burn(owner, tokenId).awaitTransactionSuccessAsync({ from: this._contractOwnerAddress });
}
public async ownerOfAsync(tokenAddress: string, tokenId: BigNumber): Promise<string> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const owner = await tokenContract.ownerOf.callAsync(tokenId);
const owner = await tokenContract.ownerOf(tokenId).callAsync();
return owner;
}
public async isOwnerAsync(userAddress: string, tokenAddress: string, tokenId: BigNumber): Promise<boolean> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const tokenOwner = await tokenContract.ownerOf.callAsync(tokenId);
const tokenOwner = await tokenContract.ownerOf(tokenId).callAsync();
const isOwner = tokenOwner === userAddress;
return isOwner;
}
@@ -158,13 +140,13 @@ export class ERC721Wrapper {
this._validateProxyContractExistsOrThrow();
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const operator = (this._proxyContract as ERC721ProxyContract).address;
const didApproveAll = await tokenContract.isApprovedForAll.callAsync(userAddress, operator);
const didApproveAll = await tokenContract.isApprovedForAll(userAddress, operator).callAsync();
return didApproveAll;
}
public async isProxyApprovedAsync(tokenAddress: string, tokenId: BigNumber): Promise<boolean> {
this._validateProxyContractExistsOrThrow();
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const approvedAddress = await tokenContract.getApproved.callAsync(tokenId);
const approvedAddress = await tokenContract.getApproved(tokenId).callAsync();
const proxyAddress = (this._proxyContract as ERC721ProxyContract).address;
const isProxyAnApprovedOperator = approvedAddress === proxyAddress;
return isProxyAnApprovedOperator;
@@ -181,7 +163,7 @@ export class ERC721Wrapper {
dummyTokenContract.address
];
for (const tokenId of initialTokenOwnerIds) {
tokenOwnerAddresses.push(await dummyTokenContract.ownerOf.callAsync(tokenId));
tokenOwnerAddresses.push(await dummyTokenContract.ownerOf(tokenId).callAsync());
tokenInfo.push({
tokenId,
tokenAddress: dummyTokenContract.address,

View File

@@ -1,3 +1,64 @@
export * from './artifacts';
export * from './wrappers';
export * from '../test/utils';
export { artifacts } from './artifacts';
export {
ERC1155ProxyContract,
ERC20BridgeProxyContract,
ERC20ProxyContract,
ERC721ProxyContract,
Eth2DaiBridgeContract,
IAssetDataContract,
IAssetProxyContract,
MultiAssetProxyContract,
StaticCallProxyContract,
TestStaticCallTargetContract,
UniswapBridgeContract,
} from './wrappers';
export { ERC20Wrapper } from './erc20_wrapper';
export { ERC721Wrapper } from './erc721_wrapper';
export { ERC1155ProxyWrapper } from './erc1155_proxy_wrapper';
export { Erc1155Wrapper, ERC1155MintableContract } from '@0x/contracts-erc1155';
export { DummyERC20TokenContract } from '@0x/contracts-erc20';
export { DummyERC721TokenContract } from '@0x/contracts-erc721';
export {
ERC1155HoldingsByOwner,
ERC20BalancesByOwner,
ERC721TokenIdsByOwner,
ERC1155FungibleHoldingsByOwner,
ERC1155NonFungibleHoldingsByOwner,
} from '@0x/contracts-test-utils';
export {
TransactionReceiptWithDecodedLogs,
Provider,
ZeroExProvider,
JSONRPCRequestPayload,
JSONRPCErrorCallback,
TransactionReceiptStatus,
JSONRPCResponsePayload,
JSONRPCResponseError,
ContractArtifact,
ContractChains,
CompilerOpts,
StandardContractOutput,
CompilerSettings,
ContractChainData,
ContractAbi,
DevdocOutput,
EvmOutput,
CompilerSettingsMetadata,
OptimizerSettings,
OutputField,
ParamDescription,
EvmBytecodeOutput,
AbiDefinition,
FunctionAbi,
EventAbi,
RevertErrorAbi,
EventParameter,
DataItem,
MethodAbi,
ConstructorAbi,
FallbackAbi,
ConstructorStateMutability,
TupleDataItem,
StateMutability,
} from 'ethereum-types';

View File

@@ -10,16 +10,7 @@ export * from '../generated-wrappers/erc721_proxy';
export * from '../generated-wrappers/eth2_dai_bridge';
export * from '../generated-wrappers/i_asset_data';
export * from '../generated-wrappers/i_asset_proxy';
export * from '../generated-wrappers/i_asset_proxy_dispatcher';
export * from '../generated-wrappers/i_authorizable';
export * from '../generated-wrappers/i_erc20_bridge';
export * from '../generated-wrappers/i_eth2_dai';
export * from '../generated-wrappers/i_wallet';
export * from '../generated-wrappers/mixin_asset_proxy_dispatcher';
export * from '../generated-wrappers/mixin_authorizable';
export * from '../generated-wrappers/multi_asset_proxy';
export * from '../generated-wrappers/ownable';
export * from '../generated-wrappers/static_call_proxy';
export * from '../generated-wrappers/test_erc20_bridge';
export * from '../generated-wrappers/test_eth2_dai_bridge';
export * from '../generated-wrappers/test_static_call_target';
export * from '../generated-wrappers/uniswap_bridge';

View File

@@ -0,0 +1,55 @@
/*
* -----------------------------------------------------------------------------
* Warning: This file is auto-generated by contracts-gen. Don't edit manually.
* -----------------------------------------------------------------------------
*/
import { ContractArtifact } from 'ethereum-types';
import * as ERC1155Proxy from '../test/generated-artifacts/ERC1155Proxy.json';
import * as ERC20BridgeProxy from '../test/generated-artifacts/ERC20BridgeProxy.json';
import * as ERC20Proxy from '../test/generated-artifacts/ERC20Proxy.json';
import * as ERC721Proxy from '../test/generated-artifacts/ERC721Proxy.json';
import * as Eth2DaiBridge from '../test/generated-artifacts/Eth2DaiBridge.json';
import * as IAssetData from '../test/generated-artifacts/IAssetData.json';
import * as IAssetProxy from '../test/generated-artifacts/IAssetProxy.json';
import * as IAssetProxyDispatcher from '../test/generated-artifacts/IAssetProxyDispatcher.json';
import * as IAuthorizable from '../test/generated-artifacts/IAuthorizable.json';
import * as IERC20Bridge from '../test/generated-artifacts/IERC20Bridge.json';
import * as IEth2Dai from '../test/generated-artifacts/IEth2Dai.json';
import * as IUniswapExchange from '../test/generated-artifacts/IUniswapExchange.json';
import * as IUniswapExchangeFactory from '../test/generated-artifacts/IUniswapExchangeFactory.json';
import * as MixinAssetProxyDispatcher from '../test/generated-artifacts/MixinAssetProxyDispatcher.json';
import * as MixinAuthorizable from '../test/generated-artifacts/MixinAuthorizable.json';
import * as MultiAssetProxy from '../test/generated-artifacts/MultiAssetProxy.json';
import * as Ownable from '../test/generated-artifacts/Ownable.json';
import * as StaticCallProxy from '../test/generated-artifacts/StaticCallProxy.json';
import * as TestERC20Bridge from '../test/generated-artifacts/TestERC20Bridge.json';
import * as TestEth2DaiBridge from '../test/generated-artifacts/TestEth2DaiBridge.json';
import * as TestStaticCallTarget from '../test/generated-artifacts/TestStaticCallTarget.json';
import * as TestUniswapBridge from '../test/generated-artifacts/TestUniswapBridge.json';
import * as UniswapBridge from '../test/generated-artifacts/UniswapBridge.json';
export const artifacts = {
MixinAssetProxyDispatcher: MixinAssetProxyDispatcher as ContractArtifact,
MixinAuthorizable: MixinAuthorizable as ContractArtifact,
Ownable: Ownable as ContractArtifact,
ERC1155Proxy: ERC1155Proxy as ContractArtifact,
ERC20BridgeProxy: ERC20BridgeProxy as ContractArtifact,
ERC20Proxy: ERC20Proxy as ContractArtifact,
ERC721Proxy: ERC721Proxy as ContractArtifact,
MultiAssetProxy: MultiAssetProxy as ContractArtifact,
StaticCallProxy: StaticCallProxy as ContractArtifact,
Eth2DaiBridge: Eth2DaiBridge as ContractArtifact,
UniswapBridge: UniswapBridge as ContractArtifact,
IAssetData: IAssetData as ContractArtifact,
IAssetProxy: IAssetProxy as ContractArtifact,
IAssetProxyDispatcher: IAssetProxyDispatcher as ContractArtifact,
IAuthorizable: IAuthorizable as ContractArtifact,
IERC20Bridge: IERC20Bridge as ContractArtifact,
IEth2Dai: IEth2Dai as ContractArtifact,
IUniswapExchange: IUniswapExchange as ContractArtifact,
IUniswapExchangeFactory: IUniswapExchangeFactory as ContractArtifact,
TestERC20Bridge: TestERC20Bridge as ContractArtifact,
TestEth2DaiBridge: TestEth2DaiBridge as ContractArtifact,
TestStaticCallTarget: TestStaticCallTarget as ContractArtifact,
TestUniswapBridge: TestUniswapBridge as ContractArtifact,
};

View File

@@ -1,18 +1,13 @@
import {
chaiSetup,
constants,
expectTransactionFailedAsync,
provider,
txDefaults,
web3Wrapper,
} from '@0x/contracts-test-utils';
import { chaiSetup, expectTransactionFailedAsync, provider, txDefaults, web3Wrapper } from '@0x/contracts-test-utils';
import { BlockchainLifecycle } from '@0x/dev-utils';
import { RevertReason } from '@0x/types';
import { BigNumber } from '@0x/utils';
import * as chai from 'chai';
import * as _ from 'lodash';
import { artifacts, MixinAuthorizableContract } from '../src';
import { artifacts } from './artifacts';
import { MixinAuthorizableContract } from './wrappers';
chaiSetup.configure();
const expect = chai.expect;
@@ -54,29 +49,21 @@ describe('Authorizable', () => {
describe('addAuthorizedAddress', () => {
it('should revert if not called by owner', async () => {
await expectTransactionFailedAsync(
authorizable.addAuthorizedAddress.sendTransactionAsync(notOwner, { from: notOwner }),
authorizable.addAuthorizedAddress(notOwner).sendTransactionAsync({ from: notOwner }),
RevertReason.OnlyContractOwner,
);
});
it('should allow owner to add an authorized address', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const isAuthorized = await authorizable.authorized.callAsync(address);
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const isAuthorized = await authorizable.authorized(address).callAsync();
expect(isAuthorized).to.be.true();
});
it('should revert if owner attempts to authorize a duplicate address', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
return expectTransactionFailedAsync(
authorizable.addAuthorizedAddress.sendTransactionAsync(address, { from: owner }),
authorizable.addAuthorizedAddress(address).sendTransactionAsync({ from: owner }),
RevertReason.TargetAlreadyAuthorized,
);
});
@@ -84,35 +71,23 @@ describe('Authorizable', () => {
describe('removeAuthorizedAddress', () => {
it('should revert if not called by owner', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
await expectTransactionFailedAsync(
authorizable.removeAuthorizedAddress.sendTransactionAsync(address, { from: notOwner }),
authorizable.removeAuthorizedAddress(address).sendTransactionAsync({ from: notOwner }),
RevertReason.OnlyContractOwner,
);
});
it('should allow owner to remove an authorized address', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await authorizable.removeAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const isAuthorized = await authorizable.authorized.callAsync(address);
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
await authorizable.removeAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const isAuthorized = await authorizable.authorized(address).callAsync();
expect(isAuthorized).to.be.false();
});
it('should revert if owner attempts to remove an address that is not authorized', async () => {
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddress.sendTransactionAsync(address, {
authorizable.removeAuthorizedAddress(address).sendTransactionAsync({
from: owner,
}),
RevertReason.TargetNotAuthorized,
@@ -122,14 +97,10 @@ describe('Authorizable', () => {
describe('removeAuthorizedAddressAtIndex', () => {
it('should revert if not called by owner', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const index = new BigNumber(0);
await expectTransactionFailedAsync(
authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, {
authorizable.removeAuthorizedAddressAtIndex(address, index).sendTransactionAsync({
from: notOwner,
}),
RevertReason.OnlyContractOwner,
@@ -137,14 +108,10 @@ describe('Authorizable', () => {
});
it('should revert if index is >= authorities.length', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const index = new BigNumber(1);
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, {
authorizable.removeAuthorizedAddressAtIndex(address, index).sendTransactionAsync({
from: owner,
}),
RevertReason.IndexOutOfBounds,
@@ -154,7 +121,7 @@ describe('Authorizable', () => {
it('should revert if owner attempts to remove an address that is not authorized', async () => {
const index = new BigNumber(0);
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, {
authorizable.removeAuthorizedAddressAtIndex(address, index).sendTransactionAsync({
from: owner,
}),
RevertReason.TargetNotAuthorized,
@@ -164,19 +131,11 @@ describe('Authorizable', () => {
it('should revert if address at index does not match target', async () => {
const address1 = address;
const address2 = notOwner;
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address1,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address2,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await authorizable.addAuthorizedAddress(address1).awaitTransactionSuccessAsync({ from: owner });
await authorizable.addAuthorizedAddress(address2).awaitTransactionSuccessAsync({ from: owner });
const address1Index = new BigNumber(0);
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address2, address1Index, {
authorizable.removeAuthorizedAddressAtIndex(address2, address1Index).sendTransactionAsync({
from: owner,
}),
RevertReason.AuthorizedAddressMismatch,
@@ -184,41 +143,26 @@ describe('Authorizable', () => {
});
it('should allow owner to remove an authorized address', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const index = new BigNumber(0);
await authorizable.removeAuthorizedAddressAtIndex.awaitTransactionSuccessAsync(
address,
index,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const isAuthorized = await authorizable.authorized.callAsync(address);
await authorizable.removeAuthorizedAddressAtIndex(address, index).awaitTransactionSuccessAsync({
from: owner,
});
const isAuthorized = await authorizable.authorized(address).callAsync();
expect(isAuthorized).to.be.false();
});
});
describe('getAuthorizedAddresses', () => {
it('should return all authorized addresses', async () => {
const initial = await authorizable.getAuthorizedAddresses.callAsync();
const initial = await authorizable.getAuthorizedAddresses().callAsync();
expect(initial).to.have.length(0);
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const afterAdd = await authorizable.getAuthorizedAddresses.callAsync();
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const afterAdd = await authorizable.getAuthorizedAddresses().callAsync();
expect(afterAdd).to.have.length(1);
expect(afterAdd).to.include(address);
await authorizable.removeAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const afterRemove = await authorizable.getAuthorizedAddresses.callAsync();
await authorizable.removeAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const afterRemove = await authorizable.getAuthorizedAddresses().callAsync();
expect(afterRemove).to.have.length(0);
});
});

View File

@@ -1,3 +1,4 @@
import { DevUtilsContract } from '@0x/contracts-dev-utils';
import {
artifacts as erc1155Artifacts,
DummyERC1155ReceiverBatchTokenReceivedEventArgs,
@@ -14,16 +15,19 @@ import {
txDefaults,
web3Wrapper,
} from '@0x/contracts-test-utils';
import { SafeMathRevertErrors } from '@0x/contracts-utils';
import { BlockchainLifecycle } from '@0x/dev-utils';
import { assetDataUtils } from '@0x/order-utils';
import { AssetProxyId, RevertReason } from '@0x/types';
import { BigNumber, SafeMathRevertErrors } from '@0x/utils';
import { BigNumber } from '@0x/utils';
import * as chai from 'chai';
import { LogWithDecodedArgs } from 'ethereum-types';
import * as ethUtil from 'ethereumjs-util';
import * as _ from 'lodash';
import { artifacts, ERC1155ProxyContract, ERC1155ProxyWrapper } from '../src';
import { ERC1155ProxyWrapper } from '../src/erc1155_proxy_wrapper';
import { ERC1155ProxyContract, IAssetDataContract } from '../src/wrappers';
import { artifacts } from './artifacts';
chaiSetup.configure();
const expect = chai.expect;
@@ -59,6 +63,8 @@ describe('ERC1155Proxy', () => {
// tokens
let fungibleTokens: BigNumber[];
let nonFungibleTokensOwnedBySpender: BigNumber[];
// devUtils for encoding and decoding assetData
let devUtils: DevUtilsContract;
// tests
before(async () => {
await blockchainLifecycle.startAsync();
@@ -72,16 +78,8 @@ describe('ERC1155Proxy', () => {
const usedAddresses = ([owner, notAuthorized, authorized, spender, receiver] = _.slice(accounts, 0, 5));
erc1155ProxyWrapper = new ERC1155ProxyWrapper(provider, usedAddresses, owner);
erc1155Proxy = await erc1155ProxyWrapper.deployProxyAsync();
await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(
authorized,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(
erc1155Proxy.address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await erc1155Proxy.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner });
await erc1155Proxy.addAuthorizedAddress(erc1155Proxy.address).awaitTransactionSuccessAsync({ from: owner });
// deploy & configure ERC1155 tokens and receiver
[erc1155Wrapper] = await erc1155ProxyWrapper.deployDummyContractsAsync();
erc1155Contract = erc1155Wrapper.getContract();
@@ -103,6 +101,8 @@ describe('ERC1155Proxy', () => {
tokenBalances.nonFungible[spender][erc1155Contract.address][nonFungibleTokenAsString][0];
nonFungibleTokensOwnedBySpender.push(nonFungibleTokenHeldBySpender);
});
// set up devUtils
devUtils = new DevUtilsContract(constants.NULL_ADDRESS, provider, { from: owner });
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
@@ -123,7 +123,7 @@ describe('ERC1155Proxy', () => {
);
});
it('should have an id of 0xa7cb5fb7', async () => {
const proxyId = await erc1155Proxy.getProxyId.callAsync();
const proxyId = await erc1155Proxy.getProxyId().callAsync();
const expectedProxyId = AssetProxyId.ERC1155;
expect(proxyId).to.equal(expectedProxyId);
});
@@ -638,12 +638,14 @@ describe('ERC1155Proxy', () => {
return value.times(valueMultiplier);
});
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
const extraData = '0102030405060708091001020304050607080910010203040506070809100102';
const assetDataWithExtraData = `${assetData}${extraData}`;
// check balances before transfer
@@ -696,25 +698,20 @@ describe('ERC1155Proxy', () => {
const tokenUri = '';
for (const tokenToCreate of tokensToCreate) {
// create token
await erc1155Wrapper.getContract().createWithType.awaitTransactionSuccessAsync(
tokenToCreate,
tokenUri,
{
await erc1155Wrapper
.getContract()
.createWithType(tokenToCreate, tokenUri)
.awaitTransactionSuccessAsync({
from: owner,
},
constants.AWAIT_TRANSACTION_MINED_MS,
);
});
// mint balance for spender
await erc1155Wrapper.getContract().mintFungible.awaitTransactionSuccessAsync(
tokenToCreate,
[spender],
[spenderInitialBalance],
{
await erc1155Wrapper
.getContract()
.mintFungible(tokenToCreate, [spender], [spenderInitialBalance])
.awaitTransactionSuccessAsync({
from: owner,
},
constants.AWAIT_TRANSACTION_MINED_MS,
);
});
}
///// Step 2/5 /////
// Check balances before transfer
@@ -747,18 +744,16 @@ describe('ERC1155Proxy', () => {
const tokensToTransfer = [new BigNumber(1), new BigNumber(2)];
const valuesToTransfer = tokensToTransfer;
const valueMultiplier = new BigNumber(2);
const assetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
// remove the function selector and contract address from check, as these change on each test
const offsetToTokenIds = 74;
const assetDataWithoutContractAddress = assetData.substr(offsetToTokenIds);
const expectedAssetDataWithoutContractAddress =
// hand encode optimized assetData because our tooling (based on LibAssetData.sol/encodeERC1155AssetData) does not use optimized encoding
const assetDataContract = new IAssetDataContract(constants.NULL_ADDRESS, provider);
const selector = assetDataContract.getSelector('ERC1155Assets');
const assetDataWithoutContractAddress =
'0000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000040102030400000000000000000000000000000000000000000000000000000000';
expect(assetDataWithoutContractAddress).to.be.equal(expectedAssetDataWithoutContractAddress);
const assetData = `${selector}000000000000000000000000${erc1155ContractAddress.substr(
2,
)}${assetDataWithoutContractAddress}`;
///// Step 4/5 /////
// Transfer token IDs [1, 2] and amounts [1, 2] with a multiplier of 2;
// the expected trade will be token IDs [1, 2] and amounts [2, 4]
@@ -805,25 +800,20 @@ describe('ERC1155Proxy', () => {
const tokenUri = '';
for (const tokenToCreate of tokensToCreate) {
// create token
await erc1155Wrapper.getContract().createWithType.awaitTransactionSuccessAsync(
tokenToCreate,
tokenUri,
{
await erc1155Wrapper
.getContract()
.createWithType(tokenToCreate, tokenUri)
.awaitTransactionSuccessAsync({
from: owner,
},
constants.AWAIT_TRANSACTION_MINED_MS,
);
});
// mint balance for spender
await erc1155Wrapper.getContract().mintFungible.awaitTransactionSuccessAsync(
tokenToCreate,
[spender],
[spenderInitialBalance],
{
await erc1155Wrapper
.getContract()
.mintFungible(tokenToCreate, [spender], [spenderInitialBalance])
.awaitTransactionSuccessAsync({
from: owner,
},
constants.AWAIT_TRANSACTION_MINED_MS,
);
});
}
///// Step 2/5 /////
// Check balances before transfer
@@ -867,12 +857,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [new BigNumber(2), new BigNumber(2)];
const valueMultiplier = new BigNumber(2);
// create callback data that is the encoded version of `valuesToTransfer`
const generatedAssetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const generatedAssetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
// remove the function selector and contract address from check, as these change on each test
const offsetToTokenIds = 74;
const assetDataSelectorAndContractAddress = generatedAssetData.substr(0, offsetToTokenIds);
@@ -937,25 +929,20 @@ describe('ERC1155Proxy', () => {
const tokenUri = '';
for (const tokenToCreate of tokensToCreate) {
// create token
await erc1155Wrapper.getContract().createWithType.awaitTransactionSuccessAsync(
tokenToCreate,
tokenUri,
{
await erc1155Wrapper
.getContract()
.createWithType(tokenToCreate, tokenUri)
.awaitTransactionSuccessAsync({
from: owner,
},
constants.AWAIT_TRANSACTION_MINED_MS,
);
});
// mint balance for spender
await erc1155Wrapper.getContract().mintFungible.awaitTransactionSuccessAsync(
tokenToCreate,
[spender],
[spenderInitialBalance],
{
await erc1155Wrapper
.getContract()
.mintFungible(tokenToCreate, [spender], [spenderInitialBalance])
.awaitTransactionSuccessAsync({
from: owner,
},
constants.AWAIT_TRANSACTION_MINED_MS,
);
});
}
///// Step 2/5 /////
// Check balances before transfer
@@ -996,12 +983,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [new BigNumber(1), new BigNumber(2)];
const valueMultiplier = new BigNumber(2);
// create callback data that is the encoded version of `valuesToTransfer`
const generatedAssetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const generatedAssetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
// remove the function selector and contract address from check, as these change on each test
const offsetToTokenIds = 74;
const assetDataSelectorAndContractAddress = generatedAssetData.substr(0, offsetToTokenIds);
@@ -1059,12 +1048,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@@ -1106,12 +1097,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@@ -1157,12 +1150,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@@ -1208,12 +1203,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@@ -1259,12 +1256,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@@ -1311,12 +1310,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@@ -1358,12 +1359,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@@ -1409,12 +1412,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@@ -1456,12 +1461,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@@ -1507,13 +1514,15 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const txData = erc1155ProxyWrapper.getTransferFromAbiEncodedTxData(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
const txData = await erc1155ProxyWrapper.getTransferFromAbiEncodedTxDataAsync(
spender,
receiverContract,
erc1155Contract.address,
@@ -1538,13 +1547,15 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = assetDataUtils.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
const txData = erc1155ProxyWrapper.getTransferFromAbiEncodedTxData(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
.callAsync();
const txData = await erc1155ProxyWrapper.getTransferFromAbiEncodedTxDataAsync(
spender,
receiverContract,
erc1155Contract.address,
@@ -1667,13 +1678,9 @@ describe('ERC1155Proxy', () => {
it('should propagate revert reason from erc1155 contract failure', async () => {
// disable transfers
const shouldRejectTransfer = true;
await erc1155Receiver.setRejectTransferFlag.awaitTransactionSuccessAsync(
shouldRejectTransfer,
{
from: owner,
},
constants.AWAIT_TRANSACTION_MINED_MS,
);
await erc1155Receiver.setRejectTransferFlag(shouldRejectTransfer).awaitTransactionSuccessAsync({
from: owner,
});
// setup test parameters
const tokenHolders = [spender, receiverContract];
const tokensToTransfer = fungibleTokens.slice(0, 1);

View File

@@ -9,17 +9,15 @@ import {
Numberish,
randomAddress,
} from '@0x/contracts-test-utils';
import { AuthorizableRevertErrors } from '@0x/contracts-utils';
import { AssetProxyId } from '@0x/types';
import { AbiEncoder, AuthorizableRevertErrors, BigNumber, StringRevertError } from '@0x/utils';
import { AbiEncoder, BigNumber, StringRevertError } from '@0x/utils';
import { DecodedLogs } from 'ethereum-types';
import * as _ from 'lodash';
import {
artifacts,
ERC20BridgeProxyContract,
TestERC20BridgeBridgeWithdrawToEventArgs,
TestERC20BridgeContract,
} from '../src';
import { artifacts } from './artifacts';
import { ERC20BridgeProxyContract, TestERC20BridgeContract } from './wrappers';
blockchainTests.resets('ERC20BridgeProxy unit tests', env => {
const PROXY_ID = AssetProxyId.ERC20Bridge;
@@ -44,8 +42,8 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => {
env.txDefaults,
artifacts,
);
testTokenAddress = await bridgeContract.testToken.callAsync();
await assetProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(owner);
testTokenAddress = await bridgeContract.testToken().callAsync();
await assetProxy.addAuthorizedAddress(owner).awaitTransactionSuccessAsync();
});
interface AssetDataOpts {
@@ -102,7 +100,7 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => {
}
async function setTestTokenBalanceAsync(_owner: string, balance: Numberish): Promise<void> {
await bridgeContract.setTestTokenBalance.awaitTransactionSuccessAsync(_owner, new BigNumber(balance));
await bridgeContract.setTestTokenBalance(_owner, new BigNumber(balance)).awaitTransactionSuccessAsync();
}
describe('transferFrom()', () => {
@@ -132,13 +130,9 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => {
async function transferFromAsync(opts?: Partial<TransferFromOpts>, caller?: string): Promise<DecodedLogs> {
const _opts = createTransferFromOpts(opts);
const { logs } = await assetProxy.transferFrom.awaitTransactionSuccessAsync(
encodeAssetData(_opts.assetData),
_opts.from,
_opts.to,
new BigNumber(_opts.amount),
{ from: caller },
);
const { logs } = await assetProxy
.transferFrom(encodeAssetData(_opts.assetData), _opts.from, _opts.to, new BigNumber(_opts.amount))
.awaitTransactionSuccessAsync({ from: caller });
return (logs as any) as DecodedLogs;
}
@@ -164,7 +158,7 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => {
const opts = createTransferFromOpts();
const logs = await transferFromAsync(opts);
expect(logs.length).to.eq(1);
const args = logs[0].args as TestERC20BridgeBridgeWithdrawToEventArgs;
const args = logs[0].args;
expect(args.tokenAddress).to.eq(opts.assetData.tokenAddress);
expect(args.from).to.eq(opts.from);
expect(args.to).to.eq(opts.to);
@@ -180,12 +174,9 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => {
it('fails if asset data is truncated', async () => {
const opts = createTransferFromOpts();
const truncatedAssetData = hexSlice(encodeAssetData(opts.assetData), 0, -1);
const tx = assetProxy.transferFrom.awaitTransactionSuccessAsync(
truncatedAssetData,
opts.from,
opts.to,
new BigNumber(opts.amount),
);
const tx = assetProxy
.transferFrom(truncatedAssetData, opts.from, opts.to, new BigNumber(opts.amount))
.awaitTransactionSuccessAsync();
return expect(tx).to.be.rejected();
});
@@ -281,18 +272,18 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => {
it('retrieves the balance of the encoded token', async () => {
const _owner = randomAddress();
const balance = getRandomInteger(1, 100e18);
await bridgeContract.setTestTokenBalance.awaitTransactionSuccessAsync(_owner, balance);
await bridgeContract.setTestTokenBalance(_owner, balance).awaitTransactionSuccessAsync();
const assetData = createAssetData({
tokenAddress: testTokenAddress,
});
const actualBalance = await assetProxy.balanceOf.callAsync(encodeAssetData(assetData), _owner);
const actualBalance = await assetProxy.balanceOf(encodeAssetData(assetData), _owner).callAsync();
expect(actualBalance).to.bignumber.eq(balance);
});
});
describe('getProxyId()', () => {
it('returns the correct proxy ID', async () => {
const proxyId = await assetProxy.getProxyId.callAsync();
const proxyId = await assetProxy.getProxyId().callAsync();
expect(proxyId).to.eq(PROXY_ID);
});
});

View File

@@ -8,24 +8,23 @@ import {
hexRandom,
Numberish,
randomAddress,
TransactionHelper,
} from '@0x/contracts-test-utils';
import { AssetProxyId } from '@0x/types';
import { BigNumber } from '@0x/utils';
import { BigNumber, RawRevertError } from '@0x/utils';
import { DecodedLogs } from 'ethereum-types';
import * as _ from 'lodash';
import { artifacts } from './artifacts';
import {
artifacts,
TestEth2DaiBridgeContract,
TestEth2DaiBridgeEvents,
TestEth2DaiBridgeSellAllAmountEventArgs,
TestEth2DaiBridgeTokenApproveEventArgs,
TestEth2DaiBridgeTokenTransferEventArgs,
} from '../src';
} from './wrappers';
blockchainTests.resets('Eth2DaiBridge unit tests', env => {
const txHelper = new TransactionHelper(env.web3Wrapper, artifacts);
let testContract: TestEth2DaiBridgeContract;
before(async () => {
@@ -40,12 +39,12 @@ blockchainTests.resets('Eth2DaiBridge unit tests', env => {
describe('isValidSignature()', () => {
it('returns success bytes', async () => {
const LEGACY_WALLET_MAGIC_VALUE = '0xb0671381';
const result = await testContract.isValidSignature.callAsync(hexRandom(), hexRandom(_.random(0, 32)));
const result = await testContract.isValidSignature(hexRandom(), hexRandom(_.random(0, 32))).callAsync();
expect(result).to.eq(LEGACY_WALLET_MAGIC_VALUE);
});
});
describe('withdrawTo()', () => {
describe('bridgeTransferFrom()', () => {
interface WithdrawToOpts {
toTokenAddress?: string;
fromTokenAddress?: string;
@@ -80,32 +79,30 @@ blockchainTests.resets('Eth2DaiBridge unit tests', env => {
async function withdrawToAsync(opts?: Partial<WithdrawToOpts>): Promise<WithdrawToResult> {
const _opts = createWithdrawToOpts(opts);
// Set the fill behavior.
await testContract.setFillBehavior.awaitTransactionSuccessAsync(
_opts.revertReason,
new BigNumber(_opts.fillAmount),
);
await testContract
.setFillBehavior(_opts.revertReason, new BigNumber(_opts.fillAmount))
.awaitTransactionSuccessAsync();
// Create tokens and balances.
if (_opts.fromTokenAddress === undefined) {
[_opts.fromTokenAddress] = await txHelper.getResultAndReceiptAsync(
testContract.createToken,
new BigNumber(_opts.fromTokenBalance),
);
const createTokenFn = testContract.createToken(new BigNumber(_opts.fromTokenBalance));
_opts.fromTokenAddress = await createTokenFn.callAsync();
await createTokenFn.awaitTransactionSuccessAsync();
}
if (_opts.toTokenAddress === undefined) {
[_opts.toTokenAddress] = await txHelper.getResultAndReceiptAsync(
testContract.createToken,
constants.ZERO_AMOUNT,
);
const createTokenFn = testContract.createToken(constants.ZERO_AMOUNT);
_opts.toTokenAddress = await createTokenFn.callAsync();
await createTokenFn.awaitTransactionSuccessAsync();
}
// Set the transfer behavior of `toTokenAddress`.
await testContract.setTransferBehavior.awaitTransactionSuccessAsync(
_opts.toTokenAddress,
_opts.toTokentransferRevertReason,
_opts.toTokenTransferReturnData,
);
// Call withdrawTo().
const [result, { logs }] = await txHelper.getResultAndReceiptAsync(
testContract.withdrawTo,
await testContract
.setTransferBehavior(
_opts.toTokenAddress,
_opts.toTokentransferRevertReason,
_opts.toTokenTransferReturnData,
)
.awaitTransactionSuccessAsync();
// Call bridgeTransferFrom().
const bridgeTransferFromFn = testContract.bridgeTransferFrom(
// "to" token address
_opts.toTokenAddress,
// Random from address.
@@ -116,6 +113,8 @@ blockchainTests.resets('Eth2DaiBridge unit tests', env => {
// ABI-encode the "from" token address as the bridge data.
hexLeftPad(_opts.fromTokenAddress as string),
);
const result = await bridgeTransferFromFn.callAsync();
const { logs } = await bridgeTransferFromFn.awaitTransactionSuccessAsync();
return {
opts: _opts,
result,
@@ -179,14 +178,14 @@ blockchainTests.resets('Eth2DaiBridge unit tests', env => {
return expect(tx).to.revertWith(opts.toTokentransferRevertReason);
});
it('fails if `toTokenAddress.transfer()` returns falsey', async () => {
it('fails if `toTokenAddress.transfer()` returns false', async () => {
const opts = createWithdrawToOpts({ toTokenTransferReturnData: hexLeftPad(0) });
const tx = withdrawToAsync(opts);
return expect(tx).to.revertWith('ERC20_TRANSFER_FAILED');
return expect(tx).to.revertWith(new RawRevertError(hexLeftPad(0)));
});
it('succeeds if `toTokenAddress.transfer()` returns truthy', async () => {
await withdrawToAsync({ toTokenTransferReturnData: hexLeftPad(100) });
it('succeeds if `toTokenAddress.transfer()` returns true', async () => {
await withdrawToAsync({ toTokenTransferReturnData: hexLeftPad(1) });
});
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,4 @@
import { DevUtilsContract } from '@0x/contracts-dev-utils';
import {
chaiSetup,
constants,
@@ -8,13 +9,14 @@ import {
web3Wrapper,
} from '@0x/contracts-test-utils';
import { BlockchainLifecycle } from '@0x/dev-utils';
import { assetDataUtils } from '@0x/order-utils';
import { AssetProxyId, RevertReason } from '@0x/types';
import { AbiEncoder, BigNumber } from '@0x/utils';
import * as chai from 'chai';
import * as ethUtil from 'ethereumjs-util';
import { artifacts, IAssetProxyContract, StaticCallProxyContract, TestStaticCallTargetContract } from '../src';
import { artifacts } from './artifacts';
import { IAssetProxyContract, StaticCallProxyContract, TestStaticCallTargetContract } from './wrappers';
chaiSetup.configure();
const expect = chai.expect;
@@ -25,6 +27,7 @@ describe('StaticCallProxy', () => {
let fromAddress: string;
let toAddress: string;
let devUtils: DevUtilsContract;
let staticCallProxy: IAssetProxyContract;
let staticCallTarget: TestStaticCallTargetContract;
@@ -43,6 +46,7 @@ describe('StaticCallProxy', () => {
txDefaults,
artifacts,
);
devUtils = new DevUtilsContract(constants.NULL_ADDRESS, provider);
staticCallProxy = new IAssetProxyContract(
staticCallProxyWithoutTransferFrom.address,
provider,
@@ -77,26 +81,21 @@ describe('StaticCallProxy', () => {
);
});
it('should have an id of 0xc339d10a', async () => {
const proxyId = await staticCallProxy.getProxyId.callAsync();
const proxyId = await staticCallProxy.getProxyId().callAsync();
const expectedProxyId = AssetProxyId.StaticCall;
expect(proxyId).to.equal(expectedProxyId);
});
});
describe('transferFrom', () => {
it('should revert if assetData lies outside the bounds of calldata', async () => {
const staticCallData = staticCallTarget.noInputFunction.getABIEncodedTransactionData();
const staticCallData = staticCallTarget.noInputFunction().getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
const txData = staticCallProxy.transferFrom.getABIEncodedTransactionData(
assetData,
fromAddress,
toAddress,
amount,
);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
const txData = staticCallProxy
.transferFrom(assetData, fromAddress, toAddress, amount)
.getABIEncodedTransactionData();
const offsetToAssetData = '0000000000000000000000000000000000000000000000000000000000000080';
const txDataEndBuffer = ethUtil.toBuffer((txData.length - 2) / 2 - 4);
const paddedTxDataEndBuffer = ethUtil.setLengthLeft(txDataEndBuffer, 32);
@@ -114,23 +113,21 @@ describe('StaticCallProxy', () => {
it('should revert if the length of assetData is less than 100 bytes', async () => {
const staticCallData = constants.NULL_BYTES;
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils
const assetData = (await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.slice(0, -128);
.callAsync()).slice(0, -128);
const assetDataByteLen = (assetData.length - 2) / 2;
expect((assetDataByteLen - 4) % 32).to.equal(0);
await expectTransactionFailedWithoutReasonAsync(
staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount),
staticCallProxy.transferFrom(assetData, fromAddress, toAddress, amount).sendTransactionAsync(),
);
});
it('should revert if the offset to `staticCallData` points to outside of assetData', async () => {
const staticCallData = staticCallTarget.noInputFunction.getABIEncodedTransactionData();
const staticCallData = staticCallTarget.noInputFunction().getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
const offsetToStaticCallData = '0000000000000000000000000000000000000000000000000000000000000060';
const assetDataEndBuffer = ethUtil.toBuffer((assetData.length - 2) / 2 - 4);
const paddedAssetDataEndBuffer = ethUtil.setLengthLeft(assetDataEndBuffer, 32);
@@ -141,90 +138,88 @@ describe('StaticCallProxy', () => {
invalidOffsetToStaticCallData,
)}${newStaticCallData}`;
await expectTransactionFailedWithoutReasonAsync(
staticCallProxy.transferFrom.sendTransactionAsync(badAssetData, fromAddress, toAddress, amount),
staticCallProxy.transferFrom(badAssetData, fromAddress, toAddress, amount).sendTransactionAsync(),
);
});
it('should revert if the callTarget attempts to write to state', async () => {
const staticCallData = staticCallTarget.updateState.getABIEncodedTransactionData();
const staticCallData = staticCallTarget.updateState().getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await expectTransactionFailedWithoutReasonAsync(
staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount),
staticCallProxy.transferFrom(assetData, fromAddress, toAddress, amount).sendTransactionAsync(),
);
});
it('should revert with data provided by the callTarget if the staticcall reverts', async () => {
const staticCallData = staticCallTarget.assertEvenNumber.getABIEncodedTransactionData(new BigNumber(1));
const staticCallData = staticCallTarget.assertEvenNumber(new BigNumber(1)).getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await expectTransactionFailedAsync(
staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount),
staticCallProxy.transferFrom(assetData, fromAddress, toAddress, amount).sendTransactionAsync(),
RevertReason.TargetNotEven,
);
});
it('should revert if the hash of the output is different than expected expected', async () => {
const staticCallData = staticCallTarget.isOddNumber.getABIEncodedTransactionData(new BigNumber(0));
const staticCallData = staticCallTarget.isOddNumber(new BigNumber(0)).getABIEncodedTransactionData();
const trueAsBuffer = ethUtil.toBuffer('0x0000000000000000000000000000000000000000000000000000000000000001');
const expectedResultHash = ethUtil.bufferToHex(ethUtil.sha3(trueAsBuffer));
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await expectTransactionFailedAsync(
staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount),
staticCallProxy.transferFrom(assetData, fromAddress, toAddress, amount).sendTransactionAsync(),
RevertReason.UnexpectedStaticCallResult,
);
});
it('should be successful if a function call with no inputs and no outputs is successful', async () => {
const staticCallData = staticCallTarget.noInputFunction.getABIEncodedTransactionData();
const staticCallData = staticCallTarget.noInputFunction().getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await staticCallProxy
.transferFrom(assetData, fromAddress, toAddress, amount)
.awaitTransactionSuccessAsync();
});
it('should be successful if the staticCallTarget is not a contract and no return value is expected', async () => {
const staticCallData = '0x0102030405060708';
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(toAddress, staticCallData, expectedResultHash);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
const assetData = await devUtils
.encodeStaticCallAssetData(toAddress, staticCallData, expectedResultHash)
.callAsync();
await staticCallProxy
.transferFrom(assetData, fromAddress, toAddress, amount)
.awaitTransactionSuccessAsync();
});
it('should be successful if a function call with one static input returns the correct value', async () => {
const staticCallData = staticCallTarget.isOddNumber.getABIEncodedTransactionData(new BigNumber(1));
const staticCallData = staticCallTarget.isOddNumber(new BigNumber(1)).getABIEncodedTransactionData();
const trueAsBuffer = ethUtil.toBuffer('0x0000000000000000000000000000000000000000000000000000000000000001');
const expectedResultHash = ethUtil.bufferToHex(ethUtil.sha3(trueAsBuffer));
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await staticCallProxy
.transferFrom(assetData, fromAddress, toAddress, amount)
.awaitTransactionSuccessAsync();
});
it('should be successful if a function with one dynamic input is successful', async () => {
const dynamicInput = '0x0102030405060708';
const staticCallData = staticCallTarget.dynamicInputFunction.getABIEncodedTransactionData(dynamicInput);
const staticCallData = staticCallTarget.dynamicInputFunction(dynamicInput).getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await staticCallProxy
.transferFrom(assetData, fromAddress, toAddress, amount)
.awaitTransactionSuccessAsync();
});
it('should be successful if a function call returns a complex type', async () => {
const a = new BigNumber(1);
const b = new BigNumber(2);
const staticCallData = staticCallTarget.returnComplexType.getABIEncodedTransactionData(a, b);
const staticCallData = staticCallTarget.returnComplexType(a, b).getABIEncodedTransactionData();
const abiEncoder = new AbiEncoder.DynamicBytes({
name: '',
type: 'bytes',
@@ -237,12 +232,12 @@ describe('StaticCallProxy', () => {
const expectedResultHash = ethUtil.bufferToHex(
ethUtil.sha3(ethUtil.toBuffer(encodedExpectedResultWithOffset)),
);
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await staticCallProxy
.transferFrom(assetData, fromAddress, toAddress, amount)
.awaitTransactionSuccessAsync();
});
});
});

View File

@@ -0,0 +1,370 @@
import {
blockchainTests,
constants,
expect,
filterLogs,
filterLogsToArguments,
getRandomInteger,
hexLeftPad,
hexRandom,
Numberish,
randomAddress,
} from '@0x/contracts-test-utils';
import { AssetProxyId } from '@0x/types';
import { BigNumber } from '@0x/utils';
import { DecodedLogs } from 'ethereum-types';
import * as _ from 'lodash';
import { artifacts } from './artifacts';
import {
TestUniswapBridgeContract,
TestUniswapBridgeEthToTokenTransferInputEventArgs as EthToTokenTransferInputArgs,
TestUniswapBridgeEvents as ContractEvents,
TestUniswapBridgeTokenApproveEventArgs as TokenApproveArgs,
TestUniswapBridgeTokenToEthSwapInputEventArgs as TokenToEthSwapInputArgs,
TestUniswapBridgeTokenToTokenTransferInputEventArgs as TokenToTokenTransferInputArgs,
TestUniswapBridgeTokenTransferEventArgs as TokenTransferArgs,
TestUniswapBridgeWethDepositEventArgs as WethDepositArgs,
TestUniswapBridgeWethWithdrawEventArgs as WethWithdrawArgs,
} from './wrappers';
blockchainTests.resets('UniswapBridge unit tests', env => {
let testContract: TestUniswapBridgeContract;
let wethTokenAddress: string;
before(async () => {
testContract = await TestUniswapBridgeContract.deployFrom0xArtifactAsync(
artifacts.TestUniswapBridge,
env.provider,
env.txDefaults,
artifacts,
);
wethTokenAddress = await testContract.wethToken().callAsync();
});
describe('isValidSignature()', () => {
it('returns success bytes', async () => {
const LEGACY_WALLET_MAGIC_VALUE = '0xb0671381';
const result = await testContract.isValidSignature(hexRandom(), hexRandom(_.random(0, 32))).callAsync();
expect(result).to.eq(LEGACY_WALLET_MAGIC_VALUE);
});
});
describe('bridgeTransferFrom()', () => {
interface WithdrawToOpts {
fromTokenAddress: string;
toTokenAddress: string;
fromTokenBalance: Numberish;
toAddress: string;
amount: Numberish;
exchangeRevertReason: string;
exchangeFillAmount: Numberish;
toTokenRevertReason: string;
fromTokenRevertReason: string;
}
function createWithdrawToOpts(opts?: Partial<WithdrawToOpts>): WithdrawToOpts {
return {
fromTokenAddress: constants.NULL_ADDRESS,
toTokenAddress: constants.NULL_ADDRESS,
fromTokenBalance: getRandomInteger(1, 1e18),
toAddress: randomAddress(),
amount: getRandomInteger(1, 1e18),
exchangeRevertReason: '',
exchangeFillAmount: getRandomInteger(1, 1e18),
toTokenRevertReason: '',
fromTokenRevertReason: '',
...opts,
};
}
interface WithdrawToResult {
opts: WithdrawToOpts;
result: string;
logs: DecodedLogs;
blockTime: number;
}
async function withdrawToAsync(opts?: Partial<WithdrawToOpts>): Promise<WithdrawToResult> {
const _opts = createWithdrawToOpts(opts);
const callData = { value: new BigNumber(_opts.exchangeFillAmount) };
// Create the "from" token and exchange.
const createFromTokenFn = testContract.createTokenAndExchange(
_opts.fromTokenAddress,
_opts.exchangeRevertReason,
);
[_opts.fromTokenAddress] = await createFromTokenFn.callAsync(callData);
await createFromTokenFn.awaitTransactionSuccessAsync(callData);
// Create the "to" token and exchange.
const createToTokenFn = testContract.createTokenAndExchange(
_opts.toTokenAddress,
_opts.exchangeRevertReason,
);
[_opts.toTokenAddress] = await createToTokenFn.callAsync(callData);
await createToTokenFn.awaitTransactionSuccessAsync(callData);
await testContract
.setTokenRevertReason(_opts.toTokenAddress, _opts.toTokenRevertReason)
.awaitTransactionSuccessAsync();
await testContract
.setTokenRevertReason(_opts.fromTokenAddress, _opts.fromTokenRevertReason)
.awaitTransactionSuccessAsync();
// Set the token balance for the token we're converting from.
await testContract.setTokenBalance(_opts.fromTokenAddress).awaitTransactionSuccessAsync({
value: new BigNumber(_opts.fromTokenBalance),
});
// Call bridgeTransferFrom().
const bridgeTransferFromFn = testContract.bridgeTransferFrom(
// The "to" token address.
_opts.toTokenAddress,
// The "from" address.
randomAddress(),
// The "to" address.
_opts.toAddress,
// The amount to transfer to "to"
new BigNumber(_opts.amount),
// ABI-encoded "from" token address.
hexLeftPad(_opts.fromTokenAddress),
);
const result = await bridgeTransferFromFn.callAsync();
const receipt = await bridgeTransferFromFn.awaitTransactionSuccessAsync();
return {
opts: _opts,
result,
logs: (receipt.logs as any) as DecodedLogs,
blockTime: await env.web3Wrapper.getBlockTimestampAsync(receipt.blockNumber),
};
}
async function getExchangeForTokenAsync(tokenAddress: string): Promise<string> {
return testContract.getExchange(tokenAddress).callAsync();
}
it('returns magic bytes on success', async () => {
const { result } = await withdrawToAsync();
expect(result).to.eq(AssetProxyId.ERC20Bridge);
});
it('just transfers tokens to `to` if the same tokens are in play', async () => {
const createTokenFn = await testContract.createTokenAndExchange(constants.NULL_ADDRESS, '');
const [tokenAddress] = await createTokenFn.callAsync();
await createTokenFn.awaitTransactionSuccessAsync();
const { opts, result, logs } = await withdrawToAsync({
fromTokenAddress: tokenAddress,
toTokenAddress: tokenAddress,
});
expect(result).to.eq(AssetProxyId.ERC20Bridge);
const transfers = filterLogsToArguments<TokenTransferArgs>(logs, ContractEvents.TokenTransfer);
expect(transfers.length).to.eq(1);
expect(transfers[0].token).to.eq(tokenAddress);
expect(transfers[0].from).to.eq(testContract.address);
expect(transfers[0].to).to.eq(opts.toAddress);
expect(transfers[0].amount).to.bignumber.eq(opts.amount);
});
describe('token -> token', () => {
it('calls `IUniswapExchange.tokenToTokenTransferInput()', async () => {
const { opts, logs, blockTime } = await withdrawToAsync();
const exchangeAddress = await getExchangeForTokenAsync(opts.fromTokenAddress);
const calls = filterLogsToArguments<TokenToTokenTransferInputArgs>(
logs,
ContractEvents.TokenToTokenTransferInput,
);
expect(calls.length).to.eq(1);
expect(calls[0].exchange).to.eq(exchangeAddress);
expect(calls[0].tokensSold).to.bignumber.eq(opts.fromTokenBalance);
expect(calls[0].minTokensBought).to.bignumber.eq(opts.amount);
expect(calls[0].minEthBought).to.bignumber.eq(0);
expect(calls[0].deadline).to.bignumber.eq(blockTime);
expect(calls[0].recipient).to.eq(opts.toAddress);
expect(calls[0].toTokenAddress).to.eq(opts.toTokenAddress);
});
it('sets allowance for "from" token', async () => {
const { opts, logs } = await withdrawToAsync();
const approvals = filterLogsToArguments<TokenApproveArgs>(logs, ContractEvents.TokenApprove);
const exchangeAddress = await getExchangeForTokenAsync(opts.fromTokenAddress);
expect(approvals.length).to.eq(1);
expect(approvals[0].spender).to.eq(exchangeAddress);
expect(approvals[0].allowance).to.bignumber.eq(constants.MAX_UINT256);
});
it('sets allowance for "from" token on subsequent calls', async () => {
const { opts } = await withdrawToAsync();
const { logs } = await withdrawToAsync(opts);
const approvals = filterLogsToArguments<TokenApproveArgs>(logs, ContractEvents.TokenApprove);
const exchangeAddress = await getExchangeForTokenAsync(opts.fromTokenAddress);
expect(approvals.length).to.eq(1);
expect(approvals[0].spender).to.eq(exchangeAddress);
expect(approvals[0].allowance).to.bignumber.eq(constants.MAX_UINT256);
});
it('fails if "from" token does not exist', async () => {
const tx = testContract
.bridgeTransferFrom(
randomAddress(),
randomAddress(),
randomAddress(),
getRandomInteger(1, 1e18),
hexLeftPad(randomAddress()),
)
.awaitTransactionSuccessAsync();
return expect(tx).to.eventually.be.rejectedWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN');
});
it('fails if the exchange fails', async () => {
const revertReason = 'FOOBAR';
const tx = withdrawToAsync({
exchangeRevertReason: revertReason,
});
return expect(tx).to.eventually.be.rejectedWith(revertReason);
});
});
describe('token -> ETH', () => {
it('calls `IUniswapExchange.tokenToEthSwapInput()`, `WETH.deposit()`, then `transfer()`', async () => {
const { opts, logs, blockTime } = await withdrawToAsync({
toTokenAddress: wethTokenAddress,
});
const exchangeAddress = await getExchangeForTokenAsync(opts.fromTokenAddress);
let calls: any = filterLogs<TokenToEthSwapInputArgs>(logs, ContractEvents.TokenToEthSwapInput);
expect(calls.length).to.eq(1);
expect(calls[0].args.exchange).to.eq(exchangeAddress);
expect(calls[0].args.tokensSold).to.bignumber.eq(opts.fromTokenBalance);
expect(calls[0].args.minEthBought).to.bignumber.eq(opts.amount);
expect(calls[0].args.deadline).to.bignumber.eq(blockTime);
calls = filterLogs<WethDepositArgs>(
logs.slice(calls[0].logIndex as number),
ContractEvents.WethDeposit,
);
expect(calls.length).to.eq(1);
expect(calls[0].args.amount).to.bignumber.eq(opts.exchangeFillAmount);
calls = filterLogs<TokenTransferArgs>(
logs.slice(calls[0].logIndex as number),
ContractEvents.TokenTransfer,
);
expect(calls.length).to.eq(1);
expect(calls[0].args.token).to.eq(opts.toTokenAddress);
expect(calls[0].args.from).to.eq(testContract.address);
expect(calls[0].args.to).to.eq(opts.toAddress);
expect(calls[0].args.amount).to.bignumber.eq(opts.exchangeFillAmount);
});
it('sets allowance for "from" token', async () => {
const { opts, logs } = await withdrawToAsync({
toTokenAddress: wethTokenAddress,
});
const transfers = filterLogsToArguments<TokenApproveArgs>(logs, ContractEvents.TokenApprove);
const exchangeAddress = await getExchangeForTokenAsync(opts.fromTokenAddress);
expect(transfers.length).to.eq(1);
expect(transfers[0].spender).to.eq(exchangeAddress);
expect(transfers[0].allowance).to.bignumber.eq(constants.MAX_UINT256);
});
it('sets allowance for "from" token on subsequent calls', async () => {
const { opts } = await withdrawToAsync({
toTokenAddress: wethTokenAddress,
});
const { logs } = await withdrawToAsync(opts);
const approvals = filterLogsToArguments<TokenApproveArgs>(logs, ContractEvents.TokenApprove);
const exchangeAddress = await getExchangeForTokenAsync(opts.fromTokenAddress);
expect(approvals.length).to.eq(1);
expect(approvals[0].spender).to.eq(exchangeAddress);
expect(approvals[0].allowance).to.bignumber.eq(constants.MAX_UINT256);
});
it('fails if "from" token does not exist', async () => {
const tx = testContract
.bridgeTransferFrom(
randomAddress(),
randomAddress(),
randomAddress(),
getRandomInteger(1, 1e18),
hexLeftPad(wethTokenAddress),
)
.awaitTransactionSuccessAsync();
return expect(tx).to.eventually.be.rejectedWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN');
});
it('fails if `WETH.deposit()` fails', async () => {
const revertReason = 'FOOBAR';
const tx = withdrawToAsync({
toTokenAddress: wethTokenAddress,
toTokenRevertReason: revertReason,
});
return expect(tx).to.eventually.be.rejectedWith(revertReason);
});
it('fails if the exchange fails', async () => {
const revertReason = 'FOOBAR';
const tx = withdrawToAsync({
toTokenAddress: wethTokenAddress,
exchangeRevertReason: revertReason,
});
return expect(tx).to.eventually.be.rejectedWith(revertReason);
});
});
describe('ETH -> token', () => {
it('calls `WETH.withdraw()`, then `IUniswapExchange.ethToTokenTransferInput()`', async () => {
const { opts, logs, blockTime } = await withdrawToAsync({
fromTokenAddress: wethTokenAddress,
});
const exchangeAddress = await getExchangeForTokenAsync(opts.toTokenAddress);
let calls: any = filterLogs<WethWithdrawArgs>(logs, ContractEvents.WethWithdraw);
expect(calls.length).to.eq(1);
expect(calls[0].args.amount).to.bignumber.eq(opts.fromTokenBalance);
calls = filterLogs<EthToTokenTransferInputArgs>(
logs.slice(calls[0].logIndex as number),
ContractEvents.EthToTokenTransferInput,
);
expect(calls.length).to.eq(1);
expect(calls[0].args.exchange).to.eq(exchangeAddress);
expect(calls[0].args.minTokensBought).to.bignumber.eq(opts.amount);
expect(calls[0].args.deadline).to.bignumber.eq(blockTime);
expect(calls[0].args.recipient).to.eq(opts.toAddress);
});
it('does not set any allowance', async () => {
const { logs } = await withdrawToAsync({
fromTokenAddress: wethTokenAddress,
});
const approvals = filterLogsToArguments<TokenApproveArgs>(logs, ContractEvents.TokenApprove);
expect(approvals).to.be.empty('');
});
it('fails if "to" token does not exist', async () => {
const tx = testContract
.bridgeTransferFrom(
wethTokenAddress,
randomAddress(),
randomAddress(),
getRandomInteger(1, 1e18),
hexLeftPad(randomAddress()),
)
.awaitTransactionSuccessAsync();
return expect(tx).to.eventually.be.rejectedWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN');
});
it('fails if the `WETH.withdraw()` fails', async () => {
const revertReason = 'FOOBAR';
const tx = withdrawToAsync({
fromTokenAddress: wethTokenAddress,
fromTokenRevertReason: revertReason,
});
return expect(tx).to.eventually.be.rejectedWith(revertReason);
});
it('fails if the exchange fails', async () => {
const revertReason = 'FOOBAR';
const tx = withdrawToAsync({
fromTokenAddress: wethTokenAddress,
exchangeRevertReason: revertReason,
});
return expect(tx).to.eventually.be.rejectedWith(revertReason);
});
});
});
});

View File

@@ -1,3 +0,0 @@
export * from './erc20_wrapper';
export * from './erc721_wrapper';
export * from './erc1155_proxy_wrapper';

View File

@@ -0,0 +1,28 @@
/*
* -----------------------------------------------------------------------------
* Warning: This file is auto-generated by contracts-gen. Don't edit manually.
* -----------------------------------------------------------------------------
*/
export * from '../test/generated-wrappers/erc1155_proxy';
export * from '../test/generated-wrappers/erc20_bridge_proxy';
export * from '../test/generated-wrappers/erc20_proxy';
export * from '../test/generated-wrappers/erc721_proxy';
export * from '../test/generated-wrappers/eth2_dai_bridge';
export * from '../test/generated-wrappers/i_asset_data';
export * from '../test/generated-wrappers/i_asset_proxy';
export * from '../test/generated-wrappers/i_asset_proxy_dispatcher';
export * from '../test/generated-wrappers/i_authorizable';
export * from '../test/generated-wrappers/i_erc20_bridge';
export * from '../test/generated-wrappers/i_eth2_dai';
export * from '../test/generated-wrappers/i_uniswap_exchange';
export * from '../test/generated-wrappers/i_uniswap_exchange_factory';
export * from '../test/generated-wrappers/mixin_asset_proxy_dispatcher';
export * from '../test/generated-wrappers/mixin_authorizable';
export * from '../test/generated-wrappers/multi_asset_proxy';
export * from '../test/generated-wrappers/ownable';
export * from '../test/generated-wrappers/static_call_proxy';
export * from '../test/generated-wrappers/test_erc20_bridge';
export * from '../test/generated-wrappers/test_eth2_dai_bridge';
export * from '../test/generated-wrappers/test_static_call_target';
export * from '../test/generated-wrappers/test_uniswap_bridge';
export * from '../test/generated-wrappers/uniswap_bridge';

View File

@@ -10,19 +10,33 @@
"generated-artifacts/Eth2DaiBridge.json",
"generated-artifacts/IAssetData.json",
"generated-artifacts/IAssetProxy.json",
"generated-artifacts/IAssetProxyDispatcher.json",
"generated-artifacts/IAuthorizable.json",
"generated-artifacts/IERC20Bridge.json",
"generated-artifacts/IEth2Dai.json",
"generated-artifacts/IWallet.json",
"generated-artifacts/MixinAssetProxyDispatcher.json",
"generated-artifacts/MixinAuthorizable.json",
"generated-artifacts/MultiAssetProxy.json",
"generated-artifacts/Ownable.json",
"generated-artifacts/StaticCallProxy.json",
"generated-artifacts/TestERC20Bridge.json",
"generated-artifacts/TestEth2DaiBridge.json",
"generated-artifacts/TestStaticCallTarget.json"
"generated-artifacts/TestStaticCallTarget.json",
"generated-artifacts/UniswapBridge.json",
"test/generated-artifacts/ERC1155Proxy.json",
"test/generated-artifacts/ERC20BridgeProxy.json",
"test/generated-artifacts/ERC20Proxy.json",
"test/generated-artifacts/ERC721Proxy.json",
"test/generated-artifacts/Eth2DaiBridge.json",
"test/generated-artifacts/IAssetData.json",
"test/generated-artifacts/IAssetProxy.json",
"test/generated-artifacts/IAssetProxyDispatcher.json",
"test/generated-artifacts/IAuthorizable.json",
"test/generated-artifacts/IERC20Bridge.json",
"test/generated-artifacts/IEth2Dai.json",
"test/generated-artifacts/IUniswapExchange.json",
"test/generated-artifacts/IUniswapExchangeFactory.json",
"test/generated-artifacts/MixinAssetProxyDispatcher.json",
"test/generated-artifacts/MixinAuthorizable.json",
"test/generated-artifacts/MultiAssetProxy.json",
"test/generated-artifacts/Ownable.json",
"test/generated-artifacts/StaticCallProxy.json",
"test/generated-artifacts/TestERC20Bridge.json",
"test/generated-artifacts/TestEth2DaiBridge.json",
"test/generated-artifacts/TestStaticCallTarget.json",
"test/generated-artifacts/TestUniswapBridge.json",
"test/generated-artifacts/UniswapBridge.json"
],
"exclude": ["./deploy/solc/solc_bin"]
}

View File

@@ -0,0 +1,7 @@
{
"extends": "../../typedoc-tsconfig",
"compilerOptions": {
"outDir": "lib"
},
"include": ["./src/**/*", "./test/**/*"]
}

View File

@@ -0,0 +1,10 @@
# Blacklist all files
.*
*
# Whitelist lib
!lib/**/*
# Whitelist Solidity contracts
!contracts/src/**/*
# Blacklist tests in lib
/lib/test/*
# Package specific ignore

View File

@@ -1,4 +1,40 @@
[
{
"version": "2.1.0-beta.3",
"changes": [
{
"note": "Dependencies updated"
}
],
"timestamp": 1574238768
},
{
"version": "2.1.0-beta.2",
"changes": [
{
"note": "Drastically reduced bundle size by adding .npmignore, only exporting specific artifacts/wrappers/utils",
"pr": 2330
},
{
"note": "Introduced new export CoordinatorRevertErrors",
"pr": 2321
},
{
"note": "Added dependency on @0x/contracts-utils",
"pr": 2321
}
],
"timestamp": 1574030254
},
{
"version": "2.1.0-beta.1",
"changes": [
{
"note": "Dependencies updated"
}
],
"timestamp": 1573159180
},
{
"version": "2.1.0-beta.0",
"changes": [

View File

@@ -5,6 +5,20 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
## v2.1.0-beta.3 - _November 20, 2019_
* Dependencies updated
## v2.1.0-beta.2 - _November 17, 2019_
* Drastically reduced bundle size by adding .npmignore, only exporting specific artifacts/wrappers/utils (#2330)
* Introduced new export CoordinatorRevertErrors (#2321)
* Added dependency on @0x/contracts-utils (#2321)
## v2.1.0-beta.1 - _November 7, 2019_
* Dependencies updated
## v2.1.0-beta.0 - _October 3, 2019_
* Add chainId to domain separator (#1742)

View File

@@ -1,5 +1,5 @@
{
"artifactsDir": "./generated-artifacts",
"artifactsDir": "./test/generated-artifacts",
"contractsDir": "./contracts",
"useDockerisedSolc": false,
"compilerSettings": {

View File

@@ -19,12 +19,15 @@
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibAddressArray.sol";
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-exchange/contracts/src/interfaces/IExchange.sol";
import "./libs/LibCoordinatorApproval.sol";
import "./libs/LibCoordinatorRichErrors.sol";
import "./interfaces/ICoordinatorSignatureValidator.sol";
import "./interfaces/ICoordinatorApprovalVerifier.sol";
@@ -32,7 +35,7 @@ import "./interfaces/ICoordinatorApprovalVerifier.sol";
// solhint-disable avoid-tx-origin
contract MixinCoordinatorApprovalVerifier is
LibCoordinatorApproval,
LibZeroExTransaction,
LibEIP712ExchangeDomain,
ICoordinatorSignatureValidator,
ICoordinatorApprovalVerifier
{
@@ -44,13 +47,12 @@ contract MixinCoordinatorApprovalVerifier is
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param txOrigin Required signer of Ethereum transaction calling this function.
/// @param transactionSignature Proof that the transaction has been signed by the signer.
/// @param approvalExpirationTimeSeconds Array of expiration times in seconds for which each corresponding approval signature expires.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each order in the transaction's Exchange calldata.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each
/// order in the transaction's Exchange calldata.
function assertValidCoordinatorApprovals(
LibZeroExTransaction.ZeroExTransaction memory transaction,
address txOrigin,
bytes memory transactionSignature,
uint256[] memory approvalExpirationTimeSeconds,
bytes[] memory approvalSignatures
)
public
@@ -67,7 +69,6 @@ contract MixinCoordinatorApprovalVerifier is
orders,
txOrigin,
transactionSignature,
approvalExpirationTimeSeconds,
approvalSignatures
);
}
@@ -75,7 +76,7 @@ contract MixinCoordinatorApprovalVerifier is
/// @dev Decodes the orders from Exchange calldata representing any fill method.
/// @param data Exchange calldata representing a fill method.
/// @return The orders from the Exchange calldata.
/// @return orders The orders from the Exchange calldata.
function decodeOrdersFromFillData(bytes memory data)
public
pure
@@ -84,7 +85,6 @@ contract MixinCoordinatorApprovalVerifier is
bytes4 selector = data.readBytes4(0);
if (
selector == IExchange(address(0)).fillOrder.selector ||
selector == IExchange(address(0)).fillOrderNoThrow.selector ||
selector == IExchange(address(0)).fillOrKillOrder.selector
) {
// Decode single order
@@ -98,8 +98,10 @@ contract MixinCoordinatorApprovalVerifier is
selector == IExchange(address(0)).batchFillOrders.selector ||
selector == IExchange(address(0)).batchFillOrdersNoThrow.selector ||
selector == IExchange(address(0)).batchFillOrKillOrders.selector ||
selector == IExchange(address(0)).marketBuyOrders.selector ||
selector == IExchange(address(0)).marketSellOrders.selector
selector == IExchange(address(0)).marketBuyOrdersNoThrow.selector ||
selector == IExchange(address(0)).marketBuyOrdersFillOrKill.selector ||
selector == IExchange(address(0)).marketSellOrdersNoThrow.selector ||
selector == IExchange(address(0)).marketSellOrdersFillOrKill.selector
) {
// Decode all orders
// solhint-disable indent
@@ -107,7 +109,10 @@ contract MixinCoordinatorApprovalVerifier is
data.slice(4, data.length),
(LibOrder.Order[])
);
} else if (selector == IExchange(address(0)).matchOrders.selector) {
} else if (
selector == IExchange(address(0)).matchOrders.selector ||
selector == IExchange(address(0)).matchOrdersWithMaximalFill.selector
) {
// Decode left and right orders
(LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder) = abi.decode(
data.slice(4, data.length),
@@ -127,27 +132,24 @@ contract MixinCoordinatorApprovalVerifier is
/// @param orders Array of order structs containing order specifications.
/// @param txOrigin Required signer of Ethereum transaction calling this function.
/// @param transactionSignature Proof that the transaction has been signed by the signer.
/// @param approvalExpirationTimeSeconds Array of expiration times in seconds for which each corresponding approval signature expires.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each order.
function _assertValidTransactionOrdersApproval(
LibZeroExTransaction.ZeroExTransaction memory transaction,
LibOrder.Order[] memory orders,
address txOrigin,
bytes memory transactionSignature,
uint256[] memory approvalExpirationTimeSeconds,
bytes[] memory approvalSignatures
)
internal
view
{
// Verify that Ethereum tx signer is the same as the approved txOrigin
require(
tx.origin == txOrigin,
"INVALID_ORIGIN"
);
if (tx.origin != txOrigin) {
LibRichErrors.rrevert(LibCoordinatorRichErrors.InvalidOriginError(txOrigin));
}
// Hash 0x transaction
bytes32 transactionHash = getTransactionHash(transaction);
bytes32 transactionHash = LibZeroExTransaction.getTypedDataHash(transaction, EIP712_EXCHANGE_DOMAIN_HASH);
// Create empty list of approval signers
address[] memory approvalSignerAddresses = new address[](0);
@@ -155,21 +157,12 @@ contract MixinCoordinatorApprovalVerifier is
uint256 signaturesLength = approvalSignatures.length;
for (uint256 i = 0; i != signaturesLength; i++) {
// Create approval message
uint256 currentApprovalExpirationTimeSeconds = approvalExpirationTimeSeconds[i];
CoordinatorApproval memory approval = CoordinatorApproval({
txOrigin: txOrigin,
transactionHash: transactionHash,
transactionSignature: transactionSignature,
approvalExpirationTimeSeconds: currentApprovalExpirationTimeSeconds
transactionSignature: transactionSignature
});
// Ensure approval has not expired
require(
// solhint-disable-next-line not-rely-on-time
currentApprovalExpirationTimeSeconds > block.timestamp,
"APPROVAL_EXPIRED"
);
// Hash approval message and recover signer address
bytes32 approvalHash = getCoordinatorApprovalHash(approval);
address approvalSignerAddress = getSignerAddress(approvalHash, approvalSignatures[i]);
@@ -191,10 +184,12 @@ contract MixinCoordinatorApprovalVerifier is
// Ensure feeRecipient of order has approved this 0x transaction
address approverAddress = orders[i].feeRecipientAddress;
bool isOrderApproved = approvalSignerAddresses.contains(approverAddress);
require(
isOrderApproved,
"INVALID_APPROVAL_SIGNATURE"
);
if (!isOrderApproved) {
LibRichErrors.rrevert(LibCoordinatorRichErrors.InvalidApprovalSignatureError(
transactionHash,
approverAddress
));
}
}
}
}

View File

@@ -20,41 +20,53 @@ pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "@0x/contracts-utils/contracts/src/Refundable.sol";
import "./libs/LibConstants.sol";
import "./interfaces/ICoordinatorCore.sol";
import "./interfaces/ICoordinatorApprovalVerifier.sol";
// solhint-disable no-empty-blocks
contract MixinCoordinatorCore is
Refundable,
LibConstants,
ICoordinatorApprovalVerifier,
ICoordinatorCore
{
/// @dev Executes a 0x transaction that has been signed by the feeRecipients that correspond to each order in the transaction's Exchange calldata.
/// @dev A payable fallback function that makes this contract "payable". This is necessary to allow
/// this contract to gracefully handle refunds from the Exchange.
function ()
external
payable
{}
/// @dev Executes a 0x transaction that has been signed by the feeRecipients that correspond to
/// each order in the transaction's Exchange calldata.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param txOrigin Required signer of Ethereum transaction calling this function.
/// @param transactionSignature Proof that the transaction has been signed by the signer.
/// @param approvalExpirationTimeSeconds Array of expiration times in seconds for which each corresponding approval signature expires.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each order in the transaction's Exchange calldata.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each
/// order in the transaction's Exchange calldata.
function executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
address txOrigin,
bytes memory transactionSignature,
uint256[] memory approvalExpirationTimeSeconds,
bytes[] memory approvalSignatures
)
public
payable
refundFinalBalance
{
// Validate that the 0x transaction has been approves by each feeRecipient
assertValidCoordinatorApprovals(
transaction,
txOrigin,
transactionSignature,
approvalExpirationTimeSeconds,
approvalSignatures
);
// Execute the transaction
EXCHANGE.executeTransaction(transaction, transactionSignature);
EXCHANGE.executeTransaction.value(msg.value)(transaction, transactionSignature);
}
}

View File

@@ -19,7 +19,9 @@
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "./interfaces/ICoordinatorSignatureValidator.sol";
import "./libs/LibCoordinatorRichErrors.sol";
contract MixinSignatureValidator is
@@ -30,24 +32,32 @@ contract MixinSignatureValidator is
/// @dev Recovers the address of a signer given a hash and signature.
/// @param hash Any 32 byte hash.
/// @param signature Proof that the hash has been signed by signer.
/// @return signerAddress Address of the signer.
function getSignerAddress(bytes32 hash, bytes memory signature)
public
pure
returns (address signerAddress)
{
require(
signature.length > 0,
"LENGTH_GREATER_THAN_0_REQUIRED"
);
uint256 signatureLength = signature.length;
if (signatureLength == 0) {
LibRichErrors.rrevert(LibCoordinatorRichErrors.SignatureError(
LibCoordinatorRichErrors.SignatureErrorCodes.INVALID_LENGTH,
hash,
signature
));
}
// Pop last byte off of signature byte array.
uint8 signatureTypeRaw = uint8(signature.popLastByte());
uint8 signatureTypeRaw = uint8(signature[signature.length - 1]);
// Ensure signature is supported
require(
signatureTypeRaw < uint8(SignatureType.NSignatureTypes),
"SIGNATURE_UNSUPPORTED"
);
if (signatureTypeRaw >= uint8(SignatureType.NSignatureTypes)) {
LibRichErrors.rrevert(LibCoordinatorRichErrors.SignatureError(
LibCoordinatorRichErrors.SignatureErrorCodes.UNSUPPORTED,
hash,
signature
));
}
SignatureType signatureType = SignatureType(signatureTypeRaw);
@@ -57,25 +67,32 @@ 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");
LibRichErrors.rrevert(LibCoordinatorRichErrors.SignatureError(
LibCoordinatorRichErrors.SignatureErrorCodes.ILLEGAL,
hash,
signature
));
// Always invalid signature.
// Like Illegal, this is always implicitly available and therefore
// offered explicitly. It can be implicitly created by providing
// a correctly formatted but incorrect signature.
} else if (signatureType == SignatureType.Invalid) {
require(
signature.length == 0,
"LENGTH_0_REQUIRED"
);
revert("SIGNATURE_INVALID");
LibRichErrors.rrevert(LibCoordinatorRichErrors.SignatureError(
LibCoordinatorRichErrors.SignatureErrorCodes.INVALID,
hash,
signature
));
// Signature using EIP712
} else if (signatureType == SignatureType.EIP712) {
require(
signature.length == 65,
"LENGTH_65_REQUIRED"
);
if (signatureLength != 66) {
LibRichErrors.rrevert(LibCoordinatorRichErrors.SignatureError(
LibCoordinatorRichErrors.SignatureErrorCodes.INVALID_LENGTH,
hash,
signature
));
}
uint8 v = uint8(signature[0]);
bytes32 r = signature.readBytes32(1);
bytes32 s = signature.readBytes32(33);
@@ -89,10 +106,13 @@ contract MixinSignatureValidator is
// Signed using web3.eth_sign
} else if (signatureType == SignatureType.EthSign) {
require(
signature.length == 65,
"LENGTH_65_REQUIRED"
);
if (signatureLength != 66) {
LibRichErrors.rrevert(LibCoordinatorRichErrors.SignatureError(
LibCoordinatorRichErrors.SignatureErrorCodes.INVALID_LENGTH,
hash,
signature
));
}
uint8 v = uint8(signature[0]);
bytes32 r = signature.readBytes32(1);
bytes32 s = signature.readBytes32(33);
@@ -113,6 +133,10 @@ 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");
LibRichErrors.rrevert(LibCoordinatorRichErrors.SignatureError(
LibCoordinatorRichErrors.SignatureErrorCodes.UNSUPPORTED,
hash,
signature
));
}
}

View File

@@ -30,13 +30,12 @@ contract ICoordinatorApprovalVerifier {
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param txOrigin Required signer of Ethereum transaction calling this function.
/// @param transactionSignature Proof that the transaction has been signed by the signer.
/// @param approvalExpirationTimeSeconds Array of expiration times in seconds for which each corresponding approval signature expires.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each order in the transaction's Exchange calldata.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each
/// order in the transaction's Exchange calldata.
function assertValidCoordinatorApprovals(
LibZeroExTransaction.ZeroExTransaction memory transaction,
address txOrigin,
bytes memory transactionSignature,
uint256[] memory approvalExpirationTimeSeconds,
bytes[] memory approvalSignatures
)
public
@@ -44,7 +43,7 @@ contract ICoordinatorApprovalVerifier {
/// @dev Decodes the orders from Exchange calldata representing any fill method.
/// @param data Exchange calldata representing a fill method.
/// @return The orders from the Exchange calldata.
/// @return orders The orders from the Exchange calldata.
function decodeOrdersFromFillData(bytes memory data)
public
pure

View File

@@ -24,18 +24,19 @@ import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
contract ICoordinatorCore {
/// @dev Executes a 0x transaction that has been signed by the feeRecipients that correspond to each order in the transaction's Exchange calldata.
/// @dev Executes a 0x transaction that has been signed by the feeRecipients that correspond to
/// each order in the transaction's Exchange calldata.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param txOrigin Required signer of Ethereum transaction calling this function.
/// @param transactionSignature Proof that the transaction has been signed by the signer.
/// @param approvalExpirationTimeSeconds Array of expiration times in seconds for which each corresponding approval signature expires.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each order in the transaction's Exchange calldata.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each
/// order in the transaction's Exchange calldata.
function executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
address txOrigin,
bytes memory transactionSignature,
uint256[] memory approvalExpirationTimeSeconds,
bytes[] memory approvalSignatures
)
public;
public
payable;
}

View File

@@ -30,14 +30,14 @@ contract ICoordinatorSignatureValidator {
Wallet, // 0x04
Validator, // 0x05
PreSigned, // 0x06
OrderValidator, // 0x07
WalletOrderValidator, // 0x08
NSignatureTypes // 0x09, number of signature types. Always leave at end.
EIP1271Wallet, // 0x07
NSignatureTypes // 0x08, number of signature types. Always leave at end.
}
/// @dev Recovers the address of a signer given a hash and signature.
/// @param hash Any 32 byte hash.
/// @param signature Proof that the hash has been signed by signer.
/// @return signerAddress Address of the signer.
function getSignerAddress(bytes32 hash, bytes memory signature)
public
pure

View File

@@ -30,22 +30,24 @@ contract LibCoordinatorApproval is
// "CoordinatorApproval(",
// "address txOrigin,",
// "bytes32 transactionHash,",
// "bytes transactionSignature,",
// "uint256 approvalExpirationTimeSeconds",
// "bytes transactionSignature",
// ")"
// ));
bytes32 constant public EIP712_COORDINATOR_APPROVAL_SCHEMA_HASH = 0x2fbcdbaa76bc7589916958ae919dfbef04d23f6bbf26de6ff317b32c6cc01e05;
bytes32 constant public EIP712_COORDINATOR_APPROVAL_SCHEMA_HASH =
0xa6511c04ca44625d50986f8c36bedc09366207a17b96e347094053a9f8507168;
struct CoordinatorApproval {
address txOrigin; // Required signer of Ethereum transaction that is submitting approval.
bytes32 transactionHash; // EIP712 hash of the transaction.
bytes transactionSignature; // Signature of the 0x transaction.
uint256 approvalExpirationTimeSeconds; // Timestamp in seconds for which the approval expires.
}
/// @dev Calculated the EIP712 hash of the Coordinator approval mesasage using the domain separator of this contract.
/// @param approval Coordinator approval message containing the transaction hash, transaction signature, and expiration of the approval.
/// @return EIP712 hash of the Coordinator approval message with the domain separator of this contract.
/// @dev Calculates the EIP712 hash of the Coordinator approval mesasage using the domain
/// separator of this contract.
/// @param approval Coordinator approval message containing the transaction hash, and transaction
/// signature.
/// @return approvalHash EIP712 hash of the Coordinator approval message with the domain
/// separator of this contract.
function getCoordinatorApprovalHash(CoordinatorApproval memory approval)
public
view
@@ -55,9 +57,10 @@ contract LibCoordinatorApproval is
return approvalHash;
}
/// @dev Calculated the EIP712 hash of the Coordinator approval mesasage with no domain separator.
/// @param approval Coordinator approval message containing the transaction hash, transaction signature, and expiration of the approval.
/// @return EIP712 hash of the Coordinator approval message with no domain separator.
/// @dev Calculates the EIP712 hash of the Coordinator approval mesasage with no domain separator.
/// @param approval Coordinator approval message containing the transaction hash, and transaction
// signature.
/// @return result EIP712 hash of the Coordinator approval message with no domain separator.
function _hashCoordinatorApproval(CoordinatorApproval memory approval)
internal
pure
@@ -67,7 +70,6 @@ contract LibCoordinatorApproval is
bytes memory transactionSignature = approval.transactionSignature;
address txOrigin = approval.txOrigin;
bytes32 transactionHash = approval.transactionHash;
uint256 approvalExpirationTimeSeconds = approval.approvalExpirationTimeSeconds;
// Assembly for more efficiently computing:
// keccak256(abi.encodePacked(
@@ -75,7 +77,6 @@ contract LibCoordinatorApproval is
// approval.txOrigin,
// approval.transactionHash,
// keccak256(approval.transactionSignature)
// approval.approvalExpirationTimeSeconds,
// ));
assembly {
@@ -89,9 +90,8 @@ contract LibCoordinatorApproval is
mstore(add(memPtr, 32), txOrigin) // txOrigin
mstore(add(memPtr, 64), transactionHash) // transactionHash
mstore(add(memPtr, 96), transactionSignatureHash) // transactionSignatureHash
mstore(add(memPtr, 128), approvalExpirationTimeSeconds) // approvalExpirationTimeSeconds
// Compute hash
result := keccak256(memPtr, 160)
result := keccak256(memPtr, 128)
}
return result;
}

View File

@@ -0,0 +1,87 @@
/*
Copyright 2019 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.5.9;
library LibCoordinatorRichErrors {
enum SignatureErrorCodes {
INVALID_LENGTH,
UNSUPPORTED,
ILLEGAL,
INVALID
}
// bytes4(keccak256("SignatureError(uint8,bytes32,bytes)"))
bytes4 internal constant SIGNATURE_ERROR_SELECTOR =
0x779c5223;
// bytes4(keccak256("InvalidOriginError(address)"))
bytes4 internal constant INVALID_ORIGIN_ERROR_SELECTOR =
0xa458d7ff;
// bytes4(keccak256("InvalidApprovalSignatureError(bytes32,address)"))
bytes4 internal constant INVALID_APPROVAL_SIGNATURE_ERROR_SELECTOR =
0xd789b640;
// solhint-disable func-name-mixedcase
function SignatureError(
SignatureErrorCodes errorCode,
bytes32 hash,
bytes memory signature
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
SIGNATURE_ERROR_SELECTOR,
errorCode,
hash,
signature
);
}
function InvalidOriginError(
address expectedOrigin
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_ORIGIN_ERROR_SELECTOR,
expectedOrigin
);
}
function InvalidApprovalSignatureError(
bytes32 transactionHash,
address approverAddress
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_APPROVAL_SIGNATURE_ERROR_SELECTOR,
transactionHash,
approverAddress
);
}
}

View File

@@ -21,15 +21,13 @@ pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibEIP712.sol";
contract LibEIP712CoordinatorDomain is
LibEIP712
{
contract LibEIP712CoordinatorDomain {
// EIP712 Domain Name value for the Coordinator
string constant public EIP712_COORDINATOR_DOMAIN_NAME = "0x Protocol Coordinator";
// EIP712 Domain Version value for the Coordinator
string constant public EIP712_COORDINATOR_DOMAIN_VERSION = "2.0.0";
string constant public EIP712_COORDINATOR_DOMAIN_VERSION = "3.0.0";
// Hash of the EIP712 Domain Separator data for the Coordinator
// solhint-disable-next-line var-name-mixedcase
@@ -43,7 +41,9 @@ contract LibEIP712CoordinatorDomain is
)
public
{
address verifyingContractAddress = verifyingContractAddressIfExists == address(0) ? address(this) : verifyingContractAddressIfExists;
address verifyingContractAddress = verifyingContractAddressIfExists == address(0)
? address(this)
: verifyingContractAddressIfExists;
EIP712_COORDINATOR_DOMAIN_HASH = LibEIP712.hashEIP712Domain(
EIP712_COORDINATOR_DOMAIN_NAME,
EIP712_COORDINATOR_DOMAIN_VERSION,
@@ -55,7 +55,7 @@ contract LibEIP712CoordinatorDomain is
/// @dev Calculates EIP712 encoding for a hash struct in the EIP712 domain
/// of this contract.
/// @param hashStruct The EIP712 hash struct.
/// @return EIP712 hash applied to this EIP712 Domain.
/// @return result EIP712 hash applied to this EIP712 Domain.
function _hashEIP712CoordinatorMessage(bytes32 hashStruct)
internal
view

View File

@@ -29,7 +29,7 @@ contract MixinCoordinatorRegistryCore is
mapping (address => string) internal coordinatorEndpoints;
/// @dev Called by a Coordinator operator to set the endpoint of their Coordinator.
/// @param coordinatorEndpoint endpoint of the Coordinator.
/// @param coordinatorEndpoint Endpoint of the Coordinator as a string.
function setCoordinatorEndpoint(string calldata coordinatorEndpoint) external {
address coordinatorOperator = msg.sender;
coordinatorEndpoints[coordinatorOperator] = coordinatorEndpoint;
@@ -37,7 +37,8 @@ contract MixinCoordinatorRegistryCore is
}
/// @dev Gets the endpoint for a Coordinator.
/// @param coordinatorOperator operator of the Coordinator endpoint.
/// @param coordinatorOperator Operator of the Coordinator endpoint.
/// @return coordinatorEndpoint Endpoint of the Coordinator as a string.
function getCoordinatorEndpoint(address coordinatorOperator)
external
view

View File

@@ -29,11 +29,12 @@ contract ICoordinatorRegistryCore
);
/// @dev Called by a Coordinator operator to set the endpoint of their Coordinator.
/// @param coordinatorEndpoint endpoint of the Coordinator.
/// @param coordinatorEndpoint Endpoint of the Coordinator as a string.
function setCoordinatorEndpoint(string calldata coordinatorEndpoint) external;
/// @dev Gets the endpoint for a Coordinator.
/// @param coordinatorOperator operator of the Coordinator endpoint.
/// @param coordinatorOperator Operator of the Coordinator endpoint.
/// @return coordinatorEndpoint Endpoint of the Coordinator as a string.
function getCoordinatorEndpoint(address coordinatorOperator)
external
view

View File

@@ -1,6 +1,6 @@
{
"name": "@0x/contracts-coordinator",
"version": "2.1.0-beta.0",
"version": "2.1.0-beta.3",
"engines": {
"node": ">=6.12"
},
@@ -12,7 +12,7 @@
"scripts": {
"build": "yarn pre_build && tsc -b",
"build:ci": "yarn build",
"pre_build": "run-s compile contracts:gen generate_contract_wrappers",
"pre_build": "run-s compile contracts:gen generate_contract_wrappers contracts:copy",
"test": "yarn run_mocha",
"rebuild_and_test": "run-s build test",
"test:coverage": "SOLIDITY_COVERAGE=true run-s build run_mocha coverage:report:text coverage:report:lcov",
@@ -21,21 +21,25 @@
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe 'lib/test/**/*.js' --timeout 100000 --bail --exit",
"compile": "sol-compiler",
"watch": "sol-compiler -w",
"clean": "shx rm -rf lib generated-artifacts generated-wrappers",
"generate_contract_wrappers": "abi-gen --abis ${npm_package_config_abis} --output generated-wrappers --backend ethers",
"lint": "tslint --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"fix": "tslint --fix --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"clean": "shx rm -rf lib test/generated-artifacts test/generated-wrappers generated-artifacts generated-wrappers",
"generate_contract_wrappers": "abi-gen --debug --abis ${npm_package_config_abis} --output test/generated-wrappers --backend ethers",
"lint": "tslint --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./test/generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude ./test/generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"fix": "tslint --fix --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./test/generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude ./test/generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"coverage:report:text": "istanbul report text",
"coverage:report:html": "istanbul report html && open coverage/index.html",
"profiler:report:html": "istanbul report html && open coverage/index.html",
"coverage:report:lcov": "istanbul report lcov",
"test:circleci": "yarn test",
"contracts:gen": "contracts-gen",
"contracts:gen": "contracts-gen generate",
"contracts:copy": "contracts-gen copy",
"lint-contracts": "solhint -c ../.solhint.json contracts/**/**/**/**/*.sol",
"compile:truffle": "truffle compile"
"compile:truffle": "truffle compile",
"docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json",
"docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES"
},
"config": {
"abis": "./generated-artifacts/@(Coordinator|CoordinatorRegistry).json",
"publicInterfaceContracts": "Coordinator,CoordinatorRegistry,LibCoordinatorApproval,LibCoordinatorRichErrors,LibEIP712CoordinatorDomain,LibConstants",
"abis": "./test/generated-artifacts/@(Coordinator|CoordinatorRegistry|ICoordinatorApprovalVerifier|ICoordinatorCore|ICoordinatorRegistryCore|ICoordinatorSignatureValidator|LibConstants|LibCoordinatorApproval|LibCoordinatorRichErrors|LibEIP712CoordinatorDomain|MixinCoordinatorApprovalVerifier|MixinCoordinatorCore|MixinCoordinatorRegistryCore|MixinSignatureValidator).json",
"abis:comment": "This list is auto-generated by contracts-gen. Don't edit manually."
},
"repository": {
@@ -48,12 +52,19 @@
},
"homepage": "https://github.com/0xProject/0x-monorepo/contracts/extensions/README.md",
"devDependencies": {
"@0x/abi-gen": "^4.3.0-beta.0",
"@0x/contracts-gen": "^1.1.0-beta.0",
"@0x/contracts-test-utils": "^3.2.0-beta.0",
"@0x/dev-utils": "^2.4.0-beta.0",
"@0x/sol-compiler": "^3.2.0-beta.0",
"@0x/tslint-config": "^3.0.1",
"@0x/abi-gen": "^4.4.0-beta.3",
"@0x/contracts-asset-proxy": "^2.3.0-beta.3",
"@0x/contracts-dev-utils": "^0.1.0-beta.3",
"@0x/contracts-erc20": "^2.3.0-beta.3",
"@0x/contracts-exchange": "^2.2.0-beta.3",
"@0x/contracts-gen": "^1.1.0-beta.3",
"@0x/contracts-test-utils": "^3.2.0-beta.3",
"@0x/dev-utils": "^2.4.0-beta.3",
"@0x/order-utils": "^8.5.0-beta.3",
"@0x/sol-compiler": "^3.2.0-beta.3",
"@0x/ts-doc-gen": "^0.0.22",
"@0x/tslint-config": "^3.1.0-beta.2",
"@0x/web3-wrapper": "^6.1.0-beta.2",
"@types/lodash": "4.14.104",
"@types/mocha": "^5.2.7",
"@types/node": "*",
@@ -61,6 +72,7 @@
"chai-as-promised": "^7.1.0",
"chai-bignumber": "^3.0.0",
"dirty-chai": "^2.0.1",
"lodash": "^4.17.11",
"make-promises-safe": "^1.1.0",
"mocha": "^6.2.0",
"npm-run-all": "^4.1.2",
@@ -68,23 +80,16 @@
"solhint": "^1.4.1",
"truffle": "^5.0.32",
"tslint": "5.11.0",
"typedoc": "^0.15.0",
"typescript": "3.0.1"
},
"dependencies": {
"@0x/base-contract": "^5.5.0-beta.0",
"@0x/contracts-asset-proxy": "^2.3.0-beta.0",
"@0x/contracts-erc20": "^2.3.0-beta.0",
"@0x/contracts-exchange": "^2.2.0-beta.0",
"@0x/contracts-exchange-libs": "^3.1.0-beta.0",
"@0x/contracts-utils": "^3.3.0-beta.0",
"@0x/order-utils": "^8.5.0-beta.0",
"@0x/types": "^2.5.0-beta.0",
"@0x/typescript-typings": "^4.4.0-beta.0",
"@0x/utils": "^4.6.0-beta.0",
"@0x/web3-wrapper": "^6.1.0-beta.0",
"ethereum-types": "^2.2.0-beta.0",
"ethereumjs-util": "^5.1.1",
"lodash": "^4.17.11"
"@0x/base-contract": "^5.5.0-beta.3",
"@0x/contracts-utils": "^3.3.0-beta.3",
"@0x/types": "^2.5.0-beta.2",
"@0x/typescript-typings": "^4.4.0-beta.2",
"@0x/utils": "^4.6.0-beta.2",
"ethereum-types": "^2.2.0-beta.2"
},
"publishConfig": {
"access": "public"

View File

@@ -1,9 +1,8 @@
import { signingUtils } from '@0x/contracts-test-utils';
import { hexConcat, signingUtils } from '@0x/contracts-test-utils';
import { SignatureType, SignedZeroExTransaction } from '@0x/types';
import { BigNumber } from '@0x/utils';
import * as ethUtil from 'ethereumjs-util';
import { hashUtils, SignedCoordinatorApproval } from './index';
import { hashUtils } from './hash_utils';
import { SignedCoordinatorApproval } from './types';
export class ApprovalFactory {
private readonly _privateKey: Buffer;
@@ -14,24 +13,21 @@ export class ApprovalFactory {
this._verifyingContractAddress = verifyingContract;
}
public newSignedApproval(
public async newSignedApprovalAsync(
transaction: SignedZeroExTransaction,
txOrigin: string,
approvalExpirationTimeSeconds: BigNumber,
signatureType: SignatureType = SignatureType.EthSign,
): SignedCoordinatorApproval {
const approvalHashBuff = hashUtils.getApprovalHashBuffer(
): Promise<SignedCoordinatorApproval> {
const approvalHashBuff = await hashUtils.getApprovalHashBufferAsync(
transaction,
this._verifyingContractAddress,
txOrigin,
approvalExpirationTimeSeconds,
);
const signatureBuff = signingUtils.signMessage(approvalHashBuff, this._privateKey, signatureType);
const signedApproval = {
txOrigin,
transaction,
approvalExpirationTimeSeconds,
signature: ethUtil.addHexPrefix(signatureBuff.toString('hex')),
signature: hexConcat(signatureBuff),
};
return signedApproval;
}

View File

@@ -7,7 +7,15 @@ import { ContractArtifact } from 'ethereum-types';
import * as Coordinator from '../generated-artifacts/Coordinator.json';
import * as CoordinatorRegistry from '../generated-artifacts/CoordinatorRegistry.json';
import * as LibConstants from '../generated-artifacts/LibConstants.json';
import * as LibCoordinatorApproval from '../generated-artifacts/LibCoordinatorApproval.json';
import * as LibCoordinatorRichErrors from '../generated-artifacts/LibCoordinatorRichErrors.json';
import * as LibEIP712CoordinatorDomain from '../generated-artifacts/LibEIP712CoordinatorDomain.json';
export const artifacts = {
Coordinator: Coordinator as ContractArtifact,
CoordinatorRegistry: CoordinatorRegistry as ContractArtifact,
LibCoordinatorApproval: LibCoordinatorApproval as ContractArtifact,
LibCoordinatorRichErrors: LibCoordinatorRichErrors as ContractArtifact,
LibEIP712CoordinatorDomain: LibEIP712CoordinatorDomain as ContractArtifact,
LibConstants: LibConstants as ContractArtifact,
};

View File

@@ -1,33 +1,28 @@
import { hexConcat } from '@0x/contracts-test-utils';
import { eip712Utils } from '@0x/order-utils';
import { SignedZeroExTransaction } from '@0x/types';
import { BigNumber, signTypedDataUtils } from '@0x/utils';
import * as _ from 'lodash';
import { signTypedDataUtils } from '@0x/utils';
export const hashUtils = {
getApprovalHashBuffer(
async getApprovalHashBufferAsync(
transaction: SignedZeroExTransaction,
verifyingContract: string,
txOrigin: string,
approvalExpirationTimeSeconds: BigNumber,
): Buffer {
const typedData = eip712Utils.createCoordinatorApprovalTypedData(
): Promise<Buffer> {
const typedData = await eip712Utils.createCoordinatorApprovalTypedDataAsync(
transaction,
verifyingContract,
txOrigin,
approvalExpirationTimeSeconds,
);
const hashBuffer = signTypedDataUtils.generateTypedDataHash(typedData);
return hashBuffer;
},
getApprovalHashHex(
async getApprovalHashHexAsync(
transaction: SignedZeroExTransaction,
verifyingContract: string,
txOrigin: string,
approvalExpirationTimeSeconds: BigNumber,
): string {
const hashHex = `0x${hashUtils
.getApprovalHashBuffer(transaction, verifyingContract, txOrigin, approvalExpirationTimeSeconds)
.toString('hex')}`;
): Promise<string> {
const hashHex = hexConcat(await hashUtils.getApprovalHashBufferAsync(transaction, verifyingContract, txOrigin));
return hashHex;
},
};

View File

@@ -1,3 +1,41 @@
export * from './artifacts';
export * from './wrappers';
export * from '../test/utils';
export { artifacts } from './artifacts';
export {
CoordinatorContract,
CoordinatorRegistryContract,
LibConstantsContract,
LibCoordinatorApprovalContract,
LibCoordinatorRichErrorsContract,
LibEIP712CoordinatorDomainContract,
} from './wrappers';
export import CoordinatorRevertErrors = require('./revert_errors');
export { ApprovalFactory } from './approval_factory';
export { SignedCoordinatorApproval } from './types';
export { SignatureType, SignedZeroExTransaction, EIP712DomainWithDefaultSchema } from '@0x/types';
export {
ContractArtifact,
ContractChains,
CompilerOpts,
StandardContractOutput,
CompilerSettings,
ContractChainData,
ContractAbi,
DevdocOutput,
EvmOutput,
CompilerSettingsMetadata,
OptimizerSettings,
OutputField,
ParamDescription,
EvmBytecodeOutput,
AbiDefinition,
FunctionAbi,
EventAbi,
RevertErrorAbi,
EventParameter,
DataItem,
MethodAbi,
ConstructorAbi,
FallbackAbi,
ConstructorStateMutability,
TupleDataItem,
StateMutability,
} from 'ethereum-types';

View File

@@ -0,0 +1,52 @@
import { BigNumber, RevertError } from '@0x/utils';
// tslint:disable:max-classes-per-file
export enum SignatureErrorCodes {
InvalidLength,
Unsupported,
Illegal,
Invalid,
}
export class SignatureError extends RevertError {
constructor(errorCode?: SignatureErrorCodes, hash?: string, signature?: string) {
super('SignatureError', 'SignatureError(uint8 errorCode, bytes32 hash, bytes signature)', {
errorCode,
hash,
signature,
});
}
}
export class InvalidOriginError extends RevertError {
constructor(expectedOrigin?: string) {
super('InvalidOriginError', 'InvalidOriginError(address expectedOrigin)', { expectedOrigin });
}
}
export class ApprovalExpiredError extends RevertError {
constructor(transactionHash?: string, approvalExpirationTime?: BigNumber | number | string) {
super('ApprovalExpiredError', 'ApprovalExpiredError(bytes32 transactionHash, uint256 approvalExpirationTime)', {
transactionHash,
approvalExpirationTime,
});
}
}
export class InvalidApprovalSignatureError extends RevertError {
constructor(transactionHash?: string, approverAddress?: string) {
super(
'InvalidApprovalSignatureError',
'InvalidApprovalSignatureError(bytes32 transactionHash, address approverAddress)',
{ transactionHash, approverAddress },
);
}
}
const types = [SignatureError, InvalidOriginError, ApprovalExpiredError, InvalidApprovalSignatureError];
// Register the types we've defined.
for (const type of types) {
RevertError.registerType(type);
}

View File

@@ -1,10 +1,8 @@
import { SignedZeroExTransaction } from '@0x/types';
import { BigNumber } from '@0x/utils';
export interface CoordinatorApproval {
transaction: SignedZeroExTransaction;
txOrigin: string;
approvalExpirationTimeSeconds: BigNumber;
}
export interface SignedCoordinatorApproval extends CoordinatorApproval {

View File

@@ -5,3 +5,7 @@
*/
export * from '../generated-wrappers/coordinator';
export * from '../generated-wrappers/coordinator_registry';
export * from '../generated-wrappers/lib_constants';
export * from '../generated-wrappers/lib_coordinator_approval';
export * from '../generated-wrappers/lib_coordinator_rich_errors';
export * from '../generated-wrappers/lib_e_i_p712_coordinator_domain';

View File

@@ -0,0 +1,37 @@
/*
* -----------------------------------------------------------------------------
* Warning: This file is auto-generated by contracts-gen. Don't edit manually.
* -----------------------------------------------------------------------------
*/
import { ContractArtifact } from 'ethereum-types';
import * as Coordinator from '../test/generated-artifacts/Coordinator.json';
import * as CoordinatorRegistry from '../test/generated-artifacts/CoordinatorRegistry.json';
import * as ICoordinatorApprovalVerifier from '../test/generated-artifacts/ICoordinatorApprovalVerifier.json';
import * as ICoordinatorCore from '../test/generated-artifacts/ICoordinatorCore.json';
import * as ICoordinatorRegistryCore from '../test/generated-artifacts/ICoordinatorRegistryCore.json';
import * as ICoordinatorSignatureValidator from '../test/generated-artifacts/ICoordinatorSignatureValidator.json';
import * as LibConstants from '../test/generated-artifacts/LibConstants.json';
import * as LibCoordinatorApproval from '../test/generated-artifacts/LibCoordinatorApproval.json';
import * as LibCoordinatorRichErrors from '../test/generated-artifacts/LibCoordinatorRichErrors.json';
import * as LibEIP712CoordinatorDomain from '../test/generated-artifacts/LibEIP712CoordinatorDomain.json';
import * as MixinCoordinatorApprovalVerifier from '../test/generated-artifacts/MixinCoordinatorApprovalVerifier.json';
import * as MixinCoordinatorCore from '../test/generated-artifacts/MixinCoordinatorCore.json';
import * as MixinCoordinatorRegistryCore from '../test/generated-artifacts/MixinCoordinatorRegistryCore.json';
import * as MixinSignatureValidator from '../test/generated-artifacts/MixinSignatureValidator.json';
export const artifacts = {
Coordinator: Coordinator as ContractArtifact,
MixinCoordinatorApprovalVerifier: MixinCoordinatorApprovalVerifier as ContractArtifact,
MixinCoordinatorCore: MixinCoordinatorCore as ContractArtifact,
MixinSignatureValidator: MixinSignatureValidator as ContractArtifact,
ICoordinatorApprovalVerifier: ICoordinatorApprovalVerifier as ContractArtifact,
ICoordinatorCore: ICoordinatorCore as ContractArtifact,
ICoordinatorSignatureValidator: ICoordinatorSignatureValidator as ContractArtifact,
LibConstants: LibConstants as ContractArtifact,
LibCoordinatorApproval: LibCoordinatorApproval as ContractArtifact,
LibCoordinatorRichErrors: LibCoordinatorRichErrors as ContractArtifact,
LibEIP712CoordinatorDomain: LibEIP712CoordinatorDomain as ContractArtifact,
CoordinatorRegistry: CoordinatorRegistry as ContractArtifact,
MixinCoordinatorRegistryCore: MixinCoordinatorRegistryCore as ContractArtifact,
ICoordinatorRegistryCore: ICoordinatorRegistryCore as ContractArtifact,
};

View File

@@ -1,531 +0,0 @@
import { ERC20ProxyContract, ERC20Wrapper } from '@0x/contracts-asset-proxy';
import { DummyERC20TokenContract } from '@0x/contracts-erc20';
import {
artifacts as exchangeArtifacts,
constants as exchangeConstants,
ExchangeCancelEventArgs,
ExchangeCancelUpToEventArgs,
ExchangeContract,
exchangeDataEncoder,
ExchangeFillEventArgs,
ExchangeFunctionName,
} from '@0x/contracts-exchange';
import {
chaiSetup,
constants,
expectTransactionFailedAsync,
getLatestBlockTimestampAsync,
OrderFactory,
provider,
TransactionFactory,
txDefaults,
web3Wrapper,
} from '@0x/contracts-test-utils';
import { BlockchainLifecycle } from '@0x/dev-utils';
import { assetDataUtils, orderHashUtils } from '@0x/order-utils';
import { RevertReason } from '@0x/types';
import { BigNumber, providerUtils } from '@0x/utils';
import * as chai from 'chai';
import { LogWithDecodedArgs } from 'ethereum-types';
import { ApprovalFactory, artifacts, CoordinatorContract } from '../src';
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
web3Wrapper.abiDecoder.addABI(exchangeArtifacts.Exchange.compilerOutput.abi);
// tslint:disable:no-unnecessary-type-assertion
describe('Coordinator tests', () => {
let chainId: number;
let makerAddress: string;
let owner: string;
let takerAddress: string;
let feeRecipientAddress: string;
let erc20Proxy: ERC20ProxyContract;
let erc20TokenA: DummyERC20TokenContract;
let erc20TokenB: DummyERC20TokenContract;
let makerFeeToken: DummyERC20TokenContract;
let coordinatorContract: CoordinatorContract;
let exchange: ExchangeContract;
let erc20Wrapper: ERC20Wrapper;
let orderFactory: OrderFactory;
let takerTransactionFactory: TransactionFactory;
let makerTransactionFactory: TransactionFactory;
let approvalFactory: ApprovalFactory;
before(async () => {
await blockchainLifecycle.startAsync();
});
after(async () => {
await blockchainLifecycle.revertAsync();
});
before(async () => {
chainId = await providerUtils.getChainIdAsync(provider);
const accounts = await web3Wrapper.getAvailableAddressesAsync();
const usedAddresses = ([owner, makerAddress, takerAddress, feeRecipientAddress] = accounts.slice(0, 4));
erc20Wrapper = new ERC20Wrapper(provider, usedAddresses, owner);
erc20Proxy = await erc20Wrapper.deployProxyAsync();
const numDummyErc20ToDeploy = 3;
[erc20TokenA, erc20TokenB, makerFeeToken] = await erc20Wrapper.deployDummyTokensAsync(
numDummyErc20ToDeploy,
constants.DUMMY_TOKEN_DECIMALS,
);
await erc20Wrapper.setBalancesAndAllowancesAsync();
exchange = await ExchangeContract.deployFrom0xArtifactAsync(
exchangeArtifacts.Exchange,
provider,
txDefaults,
new BigNumber(chainId),
);
await web3Wrapper.awaitTransactionSuccessAsync(
await erc20Proxy.addAuthorizedAddress.sendTransactionAsync(exchange.address, { from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
await web3Wrapper.awaitTransactionSuccessAsync(
await exchange.registerAssetProxy.sendTransactionAsync(erc20Proxy.address, { from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
coordinatorContract = await CoordinatorContract.deployFrom0xArtifactAsync(
artifacts.Coordinator,
provider,
txDefaults,
artifacts,
exchange.address,
new BigNumber(chainId),
);
// Configure order defaults
const defaultOrderParams = {
...constants.STATIC_ORDER_PARAMS,
senderAddress: coordinatorContract.address,
makerAddress,
feeRecipientAddress,
makerAssetData: assetDataUtils.encodeERC20AssetData(erc20TokenA.address),
takerAssetData: assetDataUtils.encodeERC20AssetData(erc20TokenB.address),
makerFeeAssetData: assetDataUtils.encodeERC20AssetData(makerFeeToken.address),
takerFeeAssetData: assetDataUtils.encodeERC20AssetData(makerFeeToken.address),
exchangeAddress: exchange.address,
chainId,
};
const makerPrivateKey = constants.TESTRPC_PRIVATE_KEYS[accounts.indexOf(makerAddress)];
const takerPrivateKey = constants.TESTRPC_PRIVATE_KEYS[accounts.indexOf(takerAddress)];
const feeRecipientPrivateKey = constants.TESTRPC_PRIVATE_KEYS[accounts.indexOf(feeRecipientAddress)];
orderFactory = new OrderFactory(makerPrivateKey, defaultOrderParams);
makerTransactionFactory = new TransactionFactory(makerPrivateKey, exchange.address, chainId);
takerTransactionFactory = new TransactionFactory(takerPrivateKey, exchange.address, chainId);
approvalFactory = new ApprovalFactory(feeRecipientPrivateKey, coordinatorContract.address);
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('single order fills', () => {
for (const fnName of exchangeConstants.SINGLE_FILL_FN_NAMES) {
it(`${fnName} should fill the order with a signed approval`, async () => {
const orders = [await orderFactory.newSignedOrderAsync()];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory.newSignedApproval(
transaction,
takerAddress,
approvalExpirationTimeSeconds,
);
const transactionReceipt = await web3Wrapper.awaitTransactionSuccessAsync(
await coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
takerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: takerAddress },
),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const fillLogs = transactionReceipt.logs.filter(
log => (log as LogWithDecodedArgs<ExchangeFillEventArgs>).event === 'Fill',
);
expect(fillLogs.length).to.eq(1);
const fillLogArgs = (fillLogs[0] as LogWithDecodedArgs<ExchangeFillEventArgs>).args;
expect(fillLogArgs.makerAddress).to.eq(makerAddress);
expect(fillLogArgs.takerAddress).to.eq(takerAddress);
expect(fillLogArgs.senderAddress).to.eq(coordinatorContract.address);
expect(fillLogArgs.feeRecipientAddress).to.eq(feeRecipientAddress);
expect(fillLogArgs.makerAssetData).to.eq(orders[0].makerAssetData);
expect(fillLogArgs.takerAssetData).to.eq(orders[0].takerAssetData);
expect(fillLogArgs.makerAssetFilledAmount).to.bignumber.eq(orders[0].makerAssetAmount);
expect(fillLogArgs.takerAssetFilledAmount).to.bignumber.eq(orders[0].takerAssetAmount);
expect(fillLogArgs.makerFeePaid).to.bignumber.eq(orders[0].makerFee);
expect(fillLogArgs.takerFeePaid).to.bignumber.eq(orders[0].takerFee);
expect(fillLogArgs.orderHash).to.eq(orderHashUtils.getOrderHashHex(orders[0]));
});
it(`${fnName} should fill the order if called by approver`, async () => {
const orders = [await orderFactory.newSignedOrderAsync()];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data });
const transactionReceipt = await web3Wrapper.awaitTransactionSuccessAsync(
await coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
feeRecipientAddress,
transaction.signature,
[],
[],
{ from: feeRecipientAddress },
),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const fillLogs = transactionReceipt.logs.filter(
log => (log as LogWithDecodedArgs<ExchangeFillEventArgs>).event === 'Fill',
);
expect(fillLogs.length).to.eq(1);
const fillLogArgs = (fillLogs[0] as LogWithDecodedArgs<ExchangeFillEventArgs>).args;
expect(fillLogArgs.makerAddress).to.eq(makerAddress);
expect(fillLogArgs.takerAddress).to.eq(takerAddress);
expect(fillLogArgs.senderAddress).to.eq(coordinatorContract.address);
expect(fillLogArgs.feeRecipientAddress).to.eq(feeRecipientAddress);
expect(fillLogArgs.makerAssetData).to.eq(orders[0].makerAssetData);
expect(fillLogArgs.takerAssetData).to.eq(orders[0].takerAssetData);
expect(fillLogArgs.makerAssetFilledAmount).to.bignumber.eq(orders[0].makerAssetAmount);
expect(fillLogArgs.takerAssetFilledAmount).to.bignumber.eq(orders[0].takerAssetAmount);
expect(fillLogArgs.makerFeePaid).to.bignumber.eq(orders[0].makerFee);
expect(fillLogArgs.takerFeePaid).to.bignumber.eq(orders[0].takerFee);
expect(fillLogArgs.orderHash).to.eq(orderHashUtils.getOrderHashHex(orders[0]));
});
it(`${fnName} should revert with no approval signature`, async () => {
const orders = [await orderFactory.newSignedOrderAsync()];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data });
await expectTransactionFailedAsync(
coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
takerAddress,
transaction.signature,
[],
[],
{
from: takerAddress,
gas: constants.MAX_EXECUTE_TRANSACTION_GAS,
},
),
RevertReason.InvalidApprovalSignature,
);
});
it(`${fnName} should revert with an invalid approval signature`, async () => {
const orders = [await orderFactory.newSignedOrderAsync()];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory.newSignedApproval(
transaction,
takerAddress,
approvalExpirationTimeSeconds,
);
const signature = `${approval.signature.slice(0, 4)}FFFFFFFF${approval.signature.slice(12)}`;
await expectTransactionFailedAsync(
coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
takerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[signature],
{ from: takerAddress },
),
RevertReason.InvalidApprovalSignature,
);
});
it(`${fnName} should revert with an expired approval`, async () => {
const orders = [await orderFactory.newSignedOrderAsync()];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).minus(constants.TIME_BUFFER);
const approval = approvalFactory.newSignedApproval(
transaction,
takerAddress,
approvalExpirationTimeSeconds,
);
await expectTransactionFailedAsync(
coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
takerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: takerAddress },
),
RevertReason.ApprovalExpired,
);
});
it(`${fnName} should revert if not called by tx signer or approver`, async () => {
const orders = [await orderFactory.newSignedOrderAsync()];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory.newSignedApproval(
transaction,
takerAddress,
approvalExpirationTimeSeconds,
);
await expectTransactionFailedAsync(
coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
takerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: owner },
),
RevertReason.InvalidOrigin,
);
});
}
});
describe('batch order fills', () => {
for (const fnName of [...exchangeConstants.MARKET_FILL_FN_NAMES, ...exchangeConstants.BATCH_FILL_FN_NAMES]) {
it(`${fnName} should fill the orders with a signed approval`, async () => {
const orders = [await orderFactory.newSignedOrderAsync(), await orderFactory.newSignedOrderAsync()];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory.newSignedApproval(
transaction,
takerAddress,
approvalExpirationTimeSeconds,
);
const transactionReceipt = await web3Wrapper.awaitTransactionSuccessAsync(
await coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
takerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: takerAddress, gas: constants.MAX_EXECUTE_TRANSACTION_GAS },
),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const fillLogs = transactionReceipt.logs.filter(
log => (log as LogWithDecodedArgs<ExchangeFillEventArgs>).event === 'Fill',
);
expect(fillLogs.length).to.eq(orders.length);
orders.forEach((order, index) => {
const fillLogArgs = (fillLogs[index] as LogWithDecodedArgs<ExchangeFillEventArgs>).args;
expect(fillLogArgs.makerAddress).to.eq(makerAddress);
expect(fillLogArgs.takerAddress).to.eq(takerAddress);
expect(fillLogArgs.senderAddress).to.eq(coordinatorContract.address);
expect(fillLogArgs.feeRecipientAddress).to.eq(feeRecipientAddress);
expect(fillLogArgs.makerAssetData).to.eq(order.makerAssetData);
expect(fillLogArgs.takerAssetData).to.eq(order.takerAssetData);
expect(fillLogArgs.makerAssetFilledAmount).to.bignumber.eq(order.makerAssetAmount);
expect(fillLogArgs.takerAssetFilledAmount).to.bignumber.eq(order.takerAssetAmount);
expect(fillLogArgs.makerFeePaid).to.bignumber.eq(order.makerFee);
expect(fillLogArgs.takerFeePaid).to.bignumber.eq(order.takerFee);
expect(fillLogArgs.orderHash).to.eq(orderHashUtils.getOrderHashHex(order));
});
});
it(`${fnName} should fill the orders if called by approver`, async () => {
const orders = [await orderFactory.newSignedOrderAsync(), await orderFactory.newSignedOrderAsync()];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data });
const transactionReceipt = await web3Wrapper.awaitTransactionSuccessAsync(
await coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
feeRecipientAddress,
transaction.signature,
[],
[],
{ from: feeRecipientAddress, gas: constants.MAX_EXECUTE_TRANSACTION_GAS },
),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const fillLogs = transactionReceipt.logs.filter(
log => (log as LogWithDecodedArgs<ExchangeFillEventArgs>).event === 'Fill',
);
expect(fillLogs.length).to.eq(orders.length);
orders.forEach((order, index) => {
const fillLogArgs = (fillLogs[index] as LogWithDecodedArgs<ExchangeFillEventArgs>).args;
expect(fillLogArgs.makerAddress).to.eq(makerAddress);
expect(fillLogArgs.takerAddress).to.eq(takerAddress);
expect(fillLogArgs.senderAddress).to.eq(coordinatorContract.address);
expect(fillLogArgs.feeRecipientAddress).to.eq(feeRecipientAddress);
expect(fillLogArgs.makerAssetData).to.eq(order.makerAssetData);
expect(fillLogArgs.takerAssetData).to.eq(order.takerAssetData);
expect(fillLogArgs.makerAssetFilledAmount).to.bignumber.eq(order.makerAssetAmount);
expect(fillLogArgs.takerAssetFilledAmount).to.bignumber.eq(order.takerAssetAmount);
expect(fillLogArgs.makerFeePaid).to.bignumber.eq(order.makerFee);
expect(fillLogArgs.takerFeePaid).to.bignumber.eq(order.takerFee);
expect(fillLogArgs.orderHash).to.eq(orderHashUtils.getOrderHashHex(order));
});
});
it(`${fnName} should revert with an invalid approval signature`, async () => {
const orders = [await orderFactory.newSignedOrderAsync(), await orderFactory.newSignedOrderAsync()];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory.newSignedApproval(
transaction,
takerAddress,
approvalExpirationTimeSeconds,
);
const signature = `${approval.signature.slice(0, 4)}FFFFFFFF${approval.signature.slice(12)}`;
await expectTransactionFailedAsync(
coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
takerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[signature],
{ from: takerAddress },
),
RevertReason.InvalidApprovalSignature,
);
});
it(`${fnName} should revert with an expired approval`, async () => {
const orders = [await orderFactory.newSignedOrderAsync(), await orderFactory.newSignedOrderAsync()];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).minus(constants.TIME_BUFFER);
const approval = approvalFactory.newSignedApproval(
transaction,
takerAddress,
approvalExpirationTimeSeconds,
);
await expectTransactionFailedAsync(
coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
takerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: takerAddress },
),
RevertReason.ApprovalExpired,
);
});
it(`${fnName} should revert if not called by tx signer or approver`, async () => {
const orders = [await orderFactory.newSignedOrderAsync(), await orderFactory.newSignedOrderAsync()];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory.newSignedApproval(
transaction,
takerAddress,
approvalExpirationTimeSeconds,
);
await expectTransactionFailedAsync(
coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
takerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: owner },
),
RevertReason.InvalidOrigin,
);
});
}
});
describe('cancels', () => {
it('cancelOrder call should be successful without an approval', async () => {
const orders = [await orderFactory.newSignedOrderAsync()];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(ExchangeFunctionName.CancelOrder, orders);
const transaction = await makerTransactionFactory.newSignedTransactionAsync({ data });
const transactionReceipt = await web3Wrapper.awaitTransactionSuccessAsync(
await coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
makerAddress,
transaction.signature,
[],
[],
{
from: makerAddress,
},
),
);
const cancelLogs = transactionReceipt.logs.filter(
log => (log as LogWithDecodedArgs<ExchangeCancelEventArgs>).event === 'Cancel',
);
expect(cancelLogs.length).to.eq(1);
const cancelLogArgs = (cancelLogs[0] as LogWithDecodedArgs<ExchangeCancelEventArgs>).args;
expect(cancelLogArgs.makerAddress).to.eq(makerAddress);
expect(cancelLogArgs.senderAddress).to.eq(coordinatorContract.address);
expect(cancelLogArgs.feeRecipientAddress).to.eq(feeRecipientAddress);
expect(cancelLogArgs.makerAssetData).to.eq(orders[0].makerAssetData);
expect(cancelLogArgs.takerAssetData).to.eq(orders[0].takerAssetData);
expect(cancelLogArgs.orderHash).to.eq(orderHashUtils.getOrderHashHex(orders[0]));
});
it('batchCancelOrders call should be successful without an approval', async () => {
const orders = [await orderFactory.newSignedOrderAsync(), await orderFactory.newSignedOrderAsync()];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(ExchangeFunctionName.BatchCancelOrders, orders);
const transaction = await makerTransactionFactory.newSignedTransactionAsync({ data });
const transactionReceipt = await web3Wrapper.awaitTransactionSuccessAsync(
await coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
makerAddress,
transaction.signature,
[],
[],
{
from: makerAddress,
},
),
);
const cancelLogs = transactionReceipt.logs.filter(
log => (log as LogWithDecodedArgs<ExchangeCancelEventArgs>).event === 'Cancel',
);
expect(cancelLogs.length).to.eq(orders.length);
orders.forEach((order, index) => {
const cancelLogArgs = (cancelLogs[index] as LogWithDecodedArgs<ExchangeCancelEventArgs>).args;
expect(cancelLogArgs.makerAddress).to.eq(makerAddress);
expect(cancelLogArgs.senderAddress).to.eq(coordinatorContract.address);
expect(cancelLogArgs.feeRecipientAddress).to.eq(feeRecipientAddress);
expect(cancelLogArgs.makerAssetData).to.eq(order.makerAssetData);
expect(cancelLogArgs.takerAssetData).to.eq(order.takerAssetData);
expect(cancelLogArgs.orderHash).to.eq(orderHashUtils.getOrderHashHex(order));
});
});
it('cancelOrdersUpTo call should be successful without an approval', async () => {
const targetEpoch = constants.ZERO_AMOUNT;
const data = exchange.cancelOrdersUpTo.getABIEncodedTransactionData(targetEpoch);
const transaction = await makerTransactionFactory.newSignedTransactionAsync({ data });
const transactionReceipt = await web3Wrapper.awaitTransactionSuccessAsync(
await coordinatorContract.executeTransaction.sendTransactionAsync(
transaction,
makerAddress,
transaction.signature,
[],
[],
{
from: makerAddress,
},
),
);
const cancelLogs = transactionReceipt.logs.filter(
log => (log as LogWithDecodedArgs<ExchangeCancelUpToEventArgs>).event === 'CancelUpTo',
);
expect(cancelLogs.length).to.eq(1);
const cancelLogArgs = (cancelLogs[0] as LogWithDecodedArgs<ExchangeCancelUpToEventArgs>).args;
expect(cancelLogArgs.makerAddress).to.eq(makerAddress);
expect(cancelLogArgs.orderSenderAddress).to.eq(coordinatorContract.address);
expect(cancelLogArgs.orderEpoch).to.bignumber.eq(targetEpoch.plus(1));
});
});
});
// tslint:disable:max-file-line-count

View File

@@ -1,81 +1,73 @@
import { artifacts as exchangeArtifacts } from '@0x/contracts-exchange';
import { chaiSetup, provider, web3Wrapper } from '@0x/contracts-test-utils';
import { BlockchainLifecycle } from '@0x/dev-utils';
import * as chai from 'chai';
import { LogWithDecodedArgs } from 'ethereum-types';
import { blockchainTests, expect, verifyEvents } from '@0x/contracts-test-utils';
import { CoordinatorRegistryCoordinatorEndpointSetEventArgs } from '../src';
import { artifacts } from './artifacts';
import { CoordinatorRegistryWrapper } from './utils/coordinator_registry_wrapper';
import { CoordinatorRegistryContract, CoordinatorRegistryCoordinatorEndpointSetEventArgs } from './wrappers';
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
web3Wrapper.abiDecoder.addABI(exchangeArtifacts.Exchange.compilerOutput.abi);
// tslint:disable:no-unnecessary-type-assertion
describe('Coordinator Registry tests', () => {
blockchainTests.resets('Coordinator Registry tests', env => {
let coordinatorRegistry: CoordinatorRegistryContract;
let coordinatorOperator: string;
const coordinatorEndpoint = 'http://sometec.0x.org';
const nilCoordinatorEndpoint = '';
let coordinatorRegistryWrapper: CoordinatorRegistryWrapper;
// tests
before(async () => {
await blockchainLifecycle.startAsync();
});
after(async () => {
await blockchainLifecycle.revertAsync();
});
before(async () => {
// setup accounts (skip owner)
const accounts = await web3Wrapper.getAvailableAddressesAsync();
const accounts = await env.getAccountAddressesAsync();
[, coordinatorOperator] = accounts;
// deploy coordinator registry
coordinatorRegistryWrapper = new CoordinatorRegistryWrapper(provider);
await coordinatorRegistryWrapper.deployCoordinatorRegistryAsync();
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
coordinatorRegistry = await CoordinatorRegistryContract.deployFrom0xArtifactAsync(
artifacts.CoordinatorRegistry,
env.provider,
env.txDefaults,
artifacts,
);
});
describe('core', () => {
it('Should successfully set a Coordinator endpoint', async () => {
await coordinatorRegistryWrapper.setCoordinatorEndpointAsync(coordinatorOperator, coordinatorEndpoint);
const recordedCoordinatorEndpoint = await coordinatorRegistryWrapper.getCoordinatorEndpointAsync(
coordinatorOperator,
);
await coordinatorRegistry.setCoordinatorEndpoint(coordinatorEndpoint).awaitTransactionSuccessAsync({
from: coordinatorOperator,
});
const recordedCoordinatorEndpoint = await coordinatorRegistry
.getCoordinatorEndpoint(coordinatorOperator)
.callAsync();
expect(recordedCoordinatorEndpoint).to.be.equal(coordinatorEndpoint);
});
it('Should successfully unset a Coordinator endpoint', async () => {
// set Coordinator endpoint
await coordinatorRegistryWrapper.setCoordinatorEndpointAsync(coordinatorOperator, coordinatorEndpoint);
let recordedCoordinatorEndpoint = await coordinatorRegistryWrapper.getCoordinatorEndpointAsync(
coordinatorOperator,
);
await coordinatorRegistry.setCoordinatorEndpoint(coordinatorEndpoint).awaitTransactionSuccessAsync({
from: coordinatorOperator,
});
let recordedCoordinatorEndpoint = await coordinatorRegistry
.getCoordinatorEndpoint(coordinatorOperator)
.callAsync();
expect(recordedCoordinatorEndpoint).to.be.equal(coordinatorEndpoint);
// unset Coordinator endpoint
await coordinatorRegistryWrapper.setCoordinatorEndpointAsync(coordinatorOperator, nilCoordinatorEndpoint);
recordedCoordinatorEndpoint = await coordinatorRegistryWrapper.getCoordinatorEndpointAsync(
coordinatorOperator,
);
await coordinatorRegistry.setCoordinatorEndpoint(nilCoordinatorEndpoint).awaitTransactionSuccessAsync({
from: coordinatorOperator,
});
recordedCoordinatorEndpoint = await coordinatorRegistry
.getCoordinatorEndpoint(coordinatorOperator)
.callAsync();
expect(recordedCoordinatorEndpoint).to.be.equal(nilCoordinatorEndpoint);
});
it('Should emit an event when setting Coordinator endpoint', async () => {
// set Coordinator endpoint
const txReceipt = await coordinatorRegistryWrapper.setCoordinatorEndpointAsync(
coordinatorOperator,
coordinatorEndpoint,
);
const recordedCoordinatorEndpoint = await coordinatorRegistryWrapper.getCoordinatorEndpointAsync(
coordinatorOperator,
);
const txReceipt = await coordinatorRegistry
.setCoordinatorEndpoint(coordinatorEndpoint)
.awaitTransactionSuccessAsync({
from: coordinatorOperator,
});
const recordedCoordinatorEndpoint = await coordinatorRegistry
.getCoordinatorEndpoint(coordinatorOperator)
.callAsync();
expect(recordedCoordinatorEndpoint).to.be.equal(coordinatorEndpoint);
// validate event
expect(txReceipt.logs.length).to.be.equal(1);
const log = txReceipt.logs[0] as LogWithDecodedArgs<CoordinatorRegistryCoordinatorEndpointSetEventArgs>;
expect(log.args.coordinatorOperator).to.be.equal(coordinatorOperator);
expect(log.args.coordinatorEndpoint).to.be.equal(coordinatorEndpoint);
const expectedEvent: CoordinatorRegistryCoordinatorEndpointSetEventArgs = {
coordinatorOperator,
coordinatorEndpoint,
};
verifyEvents(txReceipt, [expectedEvent], 'CoordinatorEndpointSet');
});
});
});

View File

@@ -1,67 +1,35 @@
import { chaiSetup, constants, provider, randomAddress, txDefaults, web3Wrapper } from '@0x/contracts-test-utils';
import { BlockchainLifecycle } from '@0x/dev-utils';
import { transactionHashUtils } from '@0x/order-utils';
import { BigNumber, providerUtils } from '@0x/utils';
import * as chai from 'chai';
import { blockchainTests, constants, expect, randomAddress, transactionHashUtils } from '@0x/contracts-test-utils';
import { BigNumber } from '@0x/utils';
import { artifacts, CoordinatorContract, hashUtils } from '../src';
import { hashUtils } from '../src/hash_utils';
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
import { artifacts } from './artifacts';
describe('Libs tests', () => {
import { CoordinatorContract } from './wrappers';
blockchainTests.resets('Libs tests', env => {
let coordinatorContract: CoordinatorContract;
let chainId: number;
const exchangeAddress = randomAddress();
before(async () => {
await blockchainLifecycle.startAsync();
});
after(async () => {
await blockchainLifecycle.revertAsync();
});
before(async () => {
chainId = await providerUtils.getChainIdAsync(provider);
chainId = await env.getChainIdAsync();
coordinatorContract = await CoordinatorContract.deployFrom0xArtifactAsync(
artifacts.Coordinator,
provider,
txDefaults,
env.provider,
env.txDefaults,
artifacts,
exchangeAddress,
new BigNumber(chainId),
);
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('getTransactionHash', () => {
it('should return the correct transaction hash', async () => {
const tx = {
salt: new BigNumber(0),
expirationTimeSeconds: new BigNumber(0),
signerAddress: constants.NULL_ADDRESS,
data: '0x1234',
domain: {
verifyingContract: exchangeAddress,
chainId,
},
};
const expectedTxHash = transactionHashUtils.getTransactionHashHex(tx);
const txHash = await coordinatorContract.getTransactionHash.callAsync(tx);
expect(expectedTxHash).to.eq(txHash);
});
});
describe('getApprovalHash', () => {
it('should return the correct approval hash', async () => {
const signedTx = {
salt: new BigNumber(0),
expirationTimeSeconds: new BigNumber(0),
salt: constants.ZERO_AMOUNT,
gasPrice: constants.ZERO_AMOUNT,
expirationTimeSeconds: constants.ZERO_AMOUNT,
signerAddress: constants.NULL_ADDRESS,
data: '0x1234',
signature: '0x5678',
@@ -70,21 +38,18 @@ describe('Libs tests', () => {
chainId,
},
};
const approvalExpirationTimeSeconds = new BigNumber(0);
const txOrigin = constants.NULL_ADDRESS;
const approval = {
txOrigin,
transactionHash: transactionHashUtils.getTransactionHashHex(signedTx),
transactionSignature: signedTx.signature,
approvalExpirationTimeSeconds,
};
const expectedApprovalHash = hashUtils.getApprovalHashHex(
const expectedApprovalHash = await hashUtils.getApprovalHashHexAsync(
signedTx,
coordinatorContract.address,
txOrigin,
approvalExpirationTimeSeconds,
);
const approvalHash = await coordinatorContract.getCoordinatorApprovalHash.callAsync(approval);
const approvalHash = await coordinatorContract.getCoordinatorApprovalHash(approval).callAsync();
expect(expectedApprovalHash).to.eq(approvalHash);
});
});

View File

@@ -1,29 +1,28 @@
import { constants as exchangeConstants, exchangeDataEncoder, ExchangeFunctionName } from '@0x/contracts-exchange';
import { exchangeDataEncoder } from '@0x/contracts-exchange';
import {
chaiSetup,
blockchainTests,
constants,
expectContractCallFailedAsync,
getLatestBlockTimestampAsync,
provider,
ExchangeFunctionName,
expect,
hexConcat,
hexSlice,
randomAddress,
TransactionFactory,
txDefaults,
web3Wrapper,
transactionHashUtils,
} from '@0x/contracts-test-utils';
import { BlockchainLifecycle } from '@0x/dev-utils';
import { transactionHashUtils } from '@0x/order-utils';
import { RevertReason, SignatureType, SignedOrder } from '@0x/types';
import { BigNumber, LibBytesRevertErrors, providerUtils } from '@0x/utils';
import * as chai from 'chai';
import * as ethUtil from 'ethereumjs-util';
import { LibBytesRevertErrors } from '@0x/contracts-utils';
import { SignatureType, SignedOrder } from '@0x/types';
import { BigNumber } from '@0x/utils';
import { ApprovalFactory, artifacts, CoordinatorContract } from '../src';
import CoordinatorRevertErrors = require('../src/revert_errors');
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
import { ApprovalFactory } from '../src/approval_factory';
describe('Mixins tests', () => {
import { artifacts } from './artifacts';
import { CoordinatorContract } from './wrappers';
blockchainTests.resets('Mixins tests', env => {
let chainId: number;
let transactionSignerAddress: string;
let approvalSignerAddress1: string;
@@ -36,23 +35,17 @@ describe('Mixins tests', () => {
const exchangeAddress = randomAddress();
before(async () => {
await blockchainLifecycle.startAsync();
});
after(async () => {
await blockchainLifecycle.revertAsync();
});
before(async () => {
chainId = await providerUtils.getChainIdAsync(provider);
chainId = await env.getChainIdAsync();
mixins = await CoordinatorContract.deployFrom0xArtifactAsync(
artifacts.Coordinator,
provider,
txDefaults,
env.provider,
env.txDefaults,
artifacts,
exchangeAddress,
new BigNumber(chainId),
);
const accounts = await web3Wrapper.getAvailableAddressesAsync();
[transactionSignerAddress, approvalSignerAddress1, approvalSignerAddress2] = accounts.slice(0, 3);
const accounts = await env.getAccountAddressesAsync();
[transactionSignerAddress, approvalSignerAddress1, approvalSignerAddress2] = accounts;
defaultOrder = {
makerAddress: constants.NULL_ADDRESS,
takerAddress: constants.NULL_ADDRESS,
@@ -79,72 +72,91 @@ describe('Mixins tests', () => {
approvalFactory1 = new ApprovalFactory(approvalSignerPrivateKey1, mixins.address);
approvalFactory2 = new ApprovalFactory(approvalSignerPrivateKey2, mixins.address);
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('getSignerAddress', () => {
it('should return the correct address using the EthSign signature type', async () => {
const data = constants.NULL_BYTES;
const transaction = await transactionFactory.newSignedTransactionAsync({ data }, SignatureType.EthSign);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
const signerAddress = await mixins.getSignerAddress.callAsync(transactionHash, transaction.signature);
const signerAddress = await mixins.getSignerAddress(transactionHash, transaction.signature).callAsync();
expect(transaction.signerAddress).to.eq(signerAddress);
});
it('should return the correct address using the EIP712 signature type', async () => {
const data = constants.NULL_BYTES;
const transaction = await transactionFactory.newSignedTransactionAsync({ data }, SignatureType.EIP712);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
const signerAddress = await mixins.getSignerAddress.callAsync(transactionHash, transaction.signature);
const signerAddress = await mixins.getSignerAddress(transactionHash, transaction.signature).callAsync();
expect(transaction.signerAddress).to.eq(signerAddress);
});
it('should revert with with the Illegal signature type', async () => {
const data = constants.NULL_BYTES;
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const illegalSignatureByte = ethUtil.toBuffer(SignatureType.Illegal).toString('hex');
transaction.signature = `${transaction.signature.slice(
0,
transaction.signature.length - 2,
)}${illegalSignatureByte}`;
transaction.signature = hexConcat(
hexSlice(transaction.signature, 0, transaction.signature.length - 1),
SignatureType.Illegal,
);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(mixins.getSignerAddress.callAsync(transactionHash, transaction.signature)).to.be.rejectedWith(
RevertReason.SignatureIllegal,
expect(mixins.getSignerAddress(transactionHash, transaction.signature).callAsync()).to.revertWith(
new CoordinatorRevertErrors.SignatureError(
CoordinatorRevertErrors.SignatureErrorCodes.Illegal,
transactionHash,
transaction.signature,
),
);
});
it('should revert with with the Invalid signature type', async () => {
const data = constants.NULL_BYTES;
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const invalidSignatureByte = ethUtil.toBuffer(SignatureType.Invalid).toString('hex');
transaction.signature = `0x${invalidSignatureByte}`;
transaction.signature = hexConcat(SignatureType.Invalid);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(mixins.getSignerAddress.callAsync(transactionHash, transaction.signature)).to.be.rejectedWith(
RevertReason.SignatureInvalid,
expect(mixins.getSignerAddress(transactionHash, transaction.signature).callAsync()).to.revertWith(
new CoordinatorRevertErrors.SignatureError(
CoordinatorRevertErrors.SignatureErrorCodes.Invalid,
transactionHash,
transaction.signature,
),
);
});
it("should revert with with a signature type that doesn't exist", async () => {
it('should revert with with a signature type that equals `NSignatureTypes`', async () => {
const data = constants.NULL_BYTES;
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const invalidSignatureByte = '04';
transaction.signature = `${transaction.signature.slice(
0,
transaction.signature.length - 2,
)}${invalidSignatureByte}`;
transaction.signature = hexConcat(
hexSlice(transaction.signature, 0, transaction.signature.length - 1),
SignatureType.NSignatureTypes,
);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(mixins.getSignerAddress.callAsync(transactionHash, transaction.signature)).to.be.rejectedWith(
RevertReason.SignatureUnsupported,
expect(mixins.getSignerAddress(transactionHash, transaction.signature).callAsync()).to.revertWith(
new CoordinatorRevertErrors.SignatureError(
CoordinatorRevertErrors.SignatureErrorCodes.Unsupported,
transactionHash,
transaction.signature,
),
);
});
it("should revert with with a signature type that isn't supported", async () => {
const data = constants.NULL_BYTES;
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
transaction.signature = hexConcat(
hexSlice(transaction.signature, 0, transaction.signature.length - 1),
SignatureType.Wallet,
);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(mixins.getSignerAddress(transactionHash, transaction.signature).callAsync()).to.revertWith(
new CoordinatorRevertErrors.SignatureError(
CoordinatorRevertErrors.SignatureErrorCodes.Unsupported,
transactionHash,
transaction.signature,
),
);
});
});
describe('decodeOrdersFromFillData', () => {
for (const fnName of exchangeConstants.SINGLE_FILL_FN_NAMES) {
for (const fnName of constants.SINGLE_FILL_FN_NAMES) {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync();
const decodedSignedOrders = decodedOrders.map(order => ({
...order,
signature: constants.NULL_BYTES,
@@ -154,11 +166,11 @@ describe('Mixins tests', () => {
expect(orders).to.deep.eq(decodedSignedOrders);
});
}
for (const fnName of exchangeConstants.BATCH_FILL_FN_NAMES) {
for (const fnName of constants.BATCH_FILL_FN_NAMES) {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync();
const decodedSignedOrders = decodedOrders.map(order => ({
...order,
signature: constants.NULL_BYTES,
@@ -168,11 +180,11 @@ describe('Mixins tests', () => {
expect(orders).to.deep.eq(decodedSignedOrders);
});
}
for (const fnName of exchangeConstants.MARKET_FILL_FN_NAMES) {
for (const fnName of constants.MARKET_FILL_FN_NAMES) {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync();
const decodedSignedOrders = decodedOrders.map(order => ({
...order,
signature: constants.NULL_BYTES,
@@ -182,22 +194,32 @@ describe('Mixins tests', () => {
expect(orders).to.deep.eq(decodedSignedOrders);
});
}
for (const fnName of [
ExchangeFunctionName.CancelOrder,
ExchangeFunctionName.BatchCancelOrders,
ExchangeFunctionName.CancelOrdersUpTo,
]) {
for (const fnName of constants.MATCH_ORDER_FN_NAMES) {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync();
const decodedSignedOrders = decodedOrders.map(order => ({
...order,
signature: constants.NULL_BYTES,
exchangeAddress: constants.NULL_ADDRESS,
chainId,
}));
expect(orders).to.deep.eq(decodedSignedOrders);
});
}
for (const fnName of constants.CANCEL_ORDER_FN_NAMES) {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync();
const emptyArray: any[] = [];
expect(emptyArray).to.deep.eq(decodedOrders);
});
}
it('should decode an empty array for invalid data', async () => {
const data = '0x0123456789';
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync();
const emptyArray: any[] = [];
expect(emptyArray).to.deep.eq(decodedOrders);
});
@@ -208,33 +230,24 @@ describe('Mixins tests', () => {
new BigNumber(3), // the length of data
new BigNumber(4),
);
return expect(mixins.decodeOrdersFromFillData.callAsync(data)).to.revertWith(expectedError);
return expect(mixins.decodeOrdersFromFillData(data).callAsync()).to.revertWith(expectedError);
});
});
describe('Single order approvals', () => {
for (const fnName of exchangeConstants.SINGLE_FILL_FN_NAMES) {
it(`Should be successful: function=${fnName}, caller=tx_signer, senderAddress=[verifier], approval_sig=[approver1], expiration=[valid]`, async () => {
for (const fnName of constants.SINGLE_FILL_FN_NAMES) {
it(`Should be successful: function=${fnName}, caller=tx_signer, senderAddress=[verifier], approval_sig=[approver1]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: transactionSignerAddress },
);
const approval = await approvalFactory1.newSignedApprovalAsync(transaction, transactionSignerAddress);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval.signature,
])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName}, caller=tx_signer, senderAddress=[null], approval_sig=[approver1], expiration=[valid]`, async () => {
it(`Should be successful: function=${fnName}, caller=tx_signer, senderAddress=[null], approval_sig=[approver1]`, async () => {
const order = {
...defaultOrder,
senderAddress: constants.NULL_ADDRESS,
@@ -242,457 +255,257 @@ describe('Mixins tests', () => {
const orders = [order];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: transactionSignerAddress },
);
const approval = await approvalFactory1.newSignedApprovalAsync(transaction, transactionSignerAddress);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval.signature,
])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[], expiration=[]`, async () => {
it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[],
[],
{
await mixins
.assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, [])
.callAsync({
from: approvalSignerAddress1,
},
);
});
});
it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[approver1], expiration=[invalid]`, async () => {
it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[approver1]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: approvalSignerAddress1 },
);
const approval = await approvalFactory1.newSignedApprovalAsync(transaction, transactionSignerAddress);
await mixins
.assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, [
approval.signature,
])
.callAsync({ from: approvalSignerAddress1 });
});
it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[], expiration=[]`, async () => {
it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[],
[],
{
await mixins
.assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, [])
.callAsync({
from: approvalSignerAddress1,
},
);
});
});
it(`Should revert: function=${fnName}, caller=tx_signer, senderAddress=[verifier], approval_sig=[invalid], expiration=[valid]`, async () => {
it(`Should revert: function=${fnName}, caller=tx_signer, senderAddress=[verifier], approval_sig=[invalid]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
const approval = await approvalFactory1.newSignedApprovalAsync(transaction, transactionSignerAddress);
const signature = hexConcat(
hexSlice(approval.signature, 0, 2),
'0xFFFFFFFF',
hexSlice(approval.signature, 6),
);
const signature = `${approval.signature.slice(0, 4)}FFFFFFFF${approval.signature.slice(12)}`;
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[signature],
{ from: transactionSignerAddress },
),
RevertReason.InvalidApprovalSignature,
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
signature,
])
.callAsync({ from: transactionSignerAddress });
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(tx).to.revertWith(
new CoordinatorRevertErrors.InvalidApprovalSignatureError(transactionHash, approvalSignerAddress1),
);
});
it(`Should revert: function=${fnName}, caller=tx_signer, senderAddress=[verifier], approval_sig=[approver1], expiration=[invalid]`, async () => {
it(`Should revert: function=${fnName}, caller=approver2, senderAddress=[verifier], approval_sig=[approver1]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).minus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: transactionSignerAddress },
),
RevertReason.ApprovalExpired,
);
});
it(`Should revert: function=${fnName}, caller=approver2, senderAddress=[verifier], approval_sig=[approver1], expiration=[valid]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: approvalSignerAddress2 },
),
RevertReason.InvalidOrigin,
);
const approval = await approvalFactory1.newSignedApprovalAsync(transaction, transactionSignerAddress);
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval.signature,
])
.callAsync({ from: approvalSignerAddress2 });
expect(tx).to.revertWith(new CoordinatorRevertErrors.InvalidOriginError(transactionSignerAddress));
});
}
});
describe('Batch order approvals', () => {
for (const fnName of [
...exchangeConstants.BATCH_FILL_FN_NAMES,
...exchangeConstants.MARKET_FILL_FN_NAMES,
ExchangeFunctionName.MatchOrders,
...constants.BATCH_FILL_FN_NAMES,
...constants.MARKET_FILL_FN_NAMES,
...constants.MATCH_ORDER_FN_NAMES,
]) {
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver1], approval_sig=[approver1], expiration=[valid]`, async () => {
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver1], approval_sig=[approver1]`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: transactionSignerAddress },
);
const approval = await approvalFactory1.newSignedApprovalAsync(transaction, transactionSignerAddress);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval.signature,
])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[null,null], feeRecipient=[approver1,approver1], approval_sig=[approver1], expiration=[valid]`, async () => {
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[null,null], feeRecipient=[approver1,approver1], approval_sig=[approver1]`, async () => {
const orders = [defaultOrder, defaultOrder].map(order => ({
...order,
senderAddress: constants.NULL_ADDRESS,
}));
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: transactionSignerAddress },
);
const approval = await approvalFactory1.newSignedApprovalAsync(transaction, transactionSignerAddress);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval.signature,
])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[null,null], feeRecipient=[approver1,approver1], approval_sig=[], expiration=[]`, async () => {
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[null,null], feeRecipient=[approver1,approver1], approval_sig=[]`, async () => {
const orders = [defaultOrder, defaultOrder].map(order => ({
...order,
senderAddress: constants.NULL_ADDRESS,
}));
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
[],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[verifier,null], feeRecipient=[approver1,approver1], approval_sig=[approver1], expiration=[valid]`, async () => {
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[verifier,null], feeRecipient=[approver1,approver1], approval_sig=[approver1]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, senderAddress: constants.NULL_ADDRESS }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: transactionSignerAddress },
);
const approval = await approvalFactory1.newSignedApprovalAsync(transaction, transactionSignerAddress);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval.signature,
])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver2], approval_sig=[approver1,approver2], expiration=[valid,valid]`, async () => {
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver2], approval_sig=[approver1,approver2]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval1 = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
const approval2 = approvalFactory2.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds, approvalExpirationTimeSeconds],
[approval1.signature, approval2.signature],
{ from: transactionSignerAddress },
);
const approval1 = await approvalFactory1.newSignedApprovalAsync(transaction, transactionSignerAddress);
const approval2 = await approvalFactory2.newSignedApprovalAsync(transaction, transactionSignerAddress);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval1.signature,
approval2.signature,
])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver1], approval_sig=[], expiration=[]`, async () => {
it(`Should be successful: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver1], approval_sig=[]`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[],
[],
{ from: approvalSignerAddress1 },
);
await mixins
.assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, [])
.callAsync({ from: approvalSignerAddress1 });
});
it(`Should revert: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver2], approval_sig=[approver2], expiration=[valid]`, async () => {
it(`Should revert: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver2], approval_sig=[approver2]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval2 = approvalFactory2.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval2.signature],
{ from: approvalSignerAddress1 },
),
RevertReason.InvalidOrigin,
);
const approval2 = await approvalFactory2.newSignedApprovalAsync(transaction, transactionSignerAddress);
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval2.signature,
])
.callAsync({ from: approvalSignerAddress1 });
expect(tx).to.revertWith(new CoordinatorRevertErrors.InvalidOriginError(transactionSignerAddress));
});
it(`Should revert: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver1], approval_sig=[], expiration=[]`, async () => {
it(`Should revert: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver1], approval_sig=[]`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
[],
{ from: transactionSignerAddress },
),
RevertReason.InvalidApprovalSignature,
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [])
.callAsync({ from: transactionSignerAddress });
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(tx).to.revertWith(
new CoordinatorRevertErrors.InvalidApprovalSignatureError(transactionHash, approvalSignerAddress1),
);
});
it(`Should revert: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver1], approval_sig=[invalid], expiration=[valid]`, async () => {
it(`Should revert: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver1], approval_sig=[invalid]`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
const approval = await approvalFactory1.newSignedApprovalAsync(transaction, transactionSignerAddress);
const signature = hexConcat(
hexSlice(approval.signature, 0, 2),
'0xFFFFFFFF',
hexSlice(approval.signature, 6),
);
const signature = `${approval.signature.slice(0, 4)}FFFFFFFF${approval.signature.slice(12)}`;
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[signature],
{ from: transactionSignerAddress },
),
RevertReason.InvalidApprovalSignature,
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
signature,
])
.callAsync({ from: transactionSignerAddress });
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(tx).to.revertWith(
new CoordinatorRevertErrors.InvalidApprovalSignatureError(transactionHash, approvalSignerAddress1),
);
});
it(`Should revert: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver2], approval_sig=[valid,invalid], expiration=[valid,valid]`, async () => {
it(`Should revert: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver2], approval_sig=[valid,invalid]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval1 = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
const approval1 = await approvalFactory1.newSignedApprovalAsync(transaction, transactionSignerAddress);
const approval2 = await approvalFactory2.newSignedApprovalAsync(transaction, transactionSignerAddress);
const approvalSignature2 = hexConcat(
hexSlice(approval2.signature, 0, 2),
'0xFFFFFFFF',
hexSlice(approval2.signature, 6),
);
const approval2 = approvalFactory2.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
const approvalSignature2 = `${approval2.signature.slice(0, 4)}FFFFFFFF${approval2.signature.slice(12)}`;
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds, approvalExpirationTimeSeconds],
[approval1.signature, approvalSignature2],
{ from: transactionSignerAddress },
),
RevertReason.InvalidApprovalSignature,
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval1.signature,
approvalSignature2,
])
.callAsync({ from: transactionSignerAddress });
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(tx).to.revertWith(
new CoordinatorRevertErrors.InvalidApprovalSignatureError(transactionHash, approvalSignerAddress2),
);
});
it(`Should revert: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver2], approval_sig=[invalid], expiration=[valid]`, async () => {
it(`Should revert: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver2], approval_sig=[invalid]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval2 = approvalFactory2.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
const approval2 = await approvalFactory2.newSignedApprovalAsync(transaction, transactionSignerAddress);
const approvalSignature2 = hexConcat(
hexSlice(approval2.signature, 0, 2),
'0xFFFFFFFF',
hexSlice(approval2.signature, 6),
);
const approvalSignature2 = `${approval2.signature.slice(0, 4)}FFFFFFFF${approval2.signature.slice(12)}`;
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[approvalExpirationTimeSeconds],
[approvalSignature2],
{ from: approvalSignerAddress1 },
),
RevertReason.InvalidApprovalSignature,
const tx = mixins
.assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, [
approvalSignature2,
])
.callAsync({ from: approvalSignerAddress1 });
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(tx).to.revertWith(
new CoordinatorRevertErrors.InvalidApprovalSignatureError(transactionHash, approvalSignerAddress2),
);
});
it(`Should revert: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver2], approval_sig=[valid,valid], expiration=[valid,invalid]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds1 = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approvalExpirationTimeSeconds2 = new BigNumber(currentTimestamp).minus(constants.TIME_BUFFER);
const approval1 = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds1,
);
const approval2 = approvalFactory2.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds2,
);
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds1, approvalExpirationTimeSeconds2],
[approval1.signature, approval2.signature],
{ from: transactionSignerAddress },
),
RevertReason.ApprovalExpired,
);
});
it(`Should revert: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver2], approval_sig=[valid], expiration=[invalid]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).minus(constants.TIME_BUFFER);
const approval2 = approvalFactory2.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval2.signature],
{ from: approvalSignerAddress1 },
),
RevertReason.ApprovalExpired,
);
});
it(`Should revert: function=${fnName} caller=approver2, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver1], approval_sig=[valid], expiration=[valid]`, async () => {
it(`Should revert: function=${fnName} caller=approver2, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver1], approval_sig=[valid]`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval1 = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval1.signature],
{ from: approvalSignerAddress2 },
),
RevertReason.InvalidOrigin,
);
const approval1 = await approvalFactory1.newSignedApprovalAsync(transaction, transactionSignerAddress);
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval1.signature,
])
.callAsync({ from: approvalSignerAddress2 });
expect(tx).to.revertWith(new CoordinatorRevertErrors.InvalidOriginError(transactionSignerAddress));
});
}
});
@@ -701,39 +514,24 @@ describe('Mixins tests', () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(ExchangeFunctionName.CancelOrder, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
[],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [])
.callAsync({ from: transactionSignerAddress });
});
it('should allow the tx signer to call `batchCancelOrders` without approval', async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(ExchangeFunctionName.BatchCancelOrders, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
[],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [])
.callAsync({ from: transactionSignerAddress });
});
it('should allow the tx signer to call `cancelOrdersUpTo` without approval', async () => {
const data = exchangeDataEncoder.encodeOrdersToExchangeData(ExchangeFunctionName.CancelOrdersUpTo);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
[],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [])
.callAsync({ from: transactionSignerAddress });
});
});
});

View File

@@ -1,65 +0,0 @@
import { LogDecoder, txDefaults } from '@0x/contracts-test-utils';
import { Web3Wrapper } from '@0x/web3-wrapper';
import { TransactionReceiptWithDecodedLogs, ZeroExProvider } from 'ethereum-types';
import { artifacts, CoordinatorRegistryContract } from '../../src';
export class CoordinatorRegistryWrapper {
private readonly _web3Wrapper: Web3Wrapper;
private readonly _provider: ZeroExProvider;
private readonly _logDecoder: LogDecoder;
private _coordinatorRegistryContract?: CoordinatorRegistryContract;
/**
* Instanitates an CoordinatorRegistryWrapper
* @param provider Web3 provider to use for all JSON RPC requests
* Instance of CoordinatorRegistryWrapper
*/
constructor(provider: ZeroExProvider) {
this._web3Wrapper = new Web3Wrapper(provider);
this._provider = provider;
this._logDecoder = new LogDecoder(this._web3Wrapper, artifacts);
}
public async deployCoordinatorRegistryAsync(): Promise<CoordinatorRegistryContract> {
this._coordinatorRegistryContract = await CoordinatorRegistryContract.deployFrom0xArtifactAsync(
artifacts.CoordinatorRegistry,
this._provider,
txDefaults,
artifacts,
);
if (this._coordinatorRegistryContract === undefined) {
throw new Error(`Failed to deploy Coordinator Registry contract.`);
}
return this._coordinatorRegistryContract;
}
public async setCoordinatorEndpointAsync(
coordinatorOperator: string,
coordinatorEndpoint: string,
): Promise<TransactionReceiptWithDecodedLogs> {
this._assertCoordinatorRegistryDeployed();
const txReceipt = await this._logDecoder.getTxWithDecodedLogsAsync(
await (this
._coordinatorRegistryContract as CoordinatorRegistryContract).setCoordinatorEndpoint.sendTransactionAsync(
coordinatorEndpoint,
{
from: coordinatorOperator,
},
),
);
return txReceipt;
}
public async getCoordinatorEndpointAsync(coordinatorOperator: string): Promise<string> {
this._assertCoordinatorRegistryDeployed();
const coordinatorEndpoint = await (this
._coordinatorRegistryContract as CoordinatorRegistryContract).getCoordinatorEndpoint.callAsync(
coordinatorOperator,
);
return coordinatorEndpoint;
}
private _assertCoordinatorRegistryDeployed(): void {
if (this._coordinatorRegistryContract === undefined) {
throw new Error(
'The Coordinator Registry contract was not deployed through the CoordinatorRegistryWrapper. Call `deployCoordinatorRegistryAsync` to deploy.',
);
}
}
}

View File

@@ -1,3 +0,0 @@
export { hashUtils } from './hash_utils';
export { ApprovalFactory } from './approval_factory';
export * from './types';

View File

@@ -0,0 +1,19 @@
/*
* -----------------------------------------------------------------------------
* Warning: This file is auto-generated by contracts-gen. Don't edit manually.
* -----------------------------------------------------------------------------
*/
export * from '../test/generated-wrappers/coordinator';
export * from '../test/generated-wrappers/coordinator_registry';
export * from '../test/generated-wrappers/i_coordinator_approval_verifier';
export * from '../test/generated-wrappers/i_coordinator_core';
export * from '../test/generated-wrappers/i_coordinator_registry_core';
export * from '../test/generated-wrappers/i_coordinator_signature_validator';
export * from '../test/generated-wrappers/lib_constants';
export * from '../test/generated-wrappers/lib_coordinator_approval';
export * from '../test/generated-wrappers/lib_coordinator_rich_errors';
export * from '../test/generated-wrappers/lib_e_i_p712_coordinator_domain';
export * from '../test/generated-wrappers/mixin_coordinator_approval_verifier';
export * from '../test/generated-wrappers/mixin_coordinator_core';
export * from '../test/generated-wrappers/mixin_coordinator_registry_core';
export * from '../test/generated-wrappers/mixin_signature_validator';

View File

@@ -2,6 +2,27 @@
"extends": "../../tsconfig",
"compilerOptions": { "outDir": "lib", "rootDir": ".", "resolveJsonModule": true },
"include": ["./src/**/*", "./test/**/*", "./generated-wrappers/**/*"],
"files": ["generated-artifacts/Coordinator.json", "generated-artifacts/CoordinatorRegistry.json"],
"files": [
"generated-artifacts/Coordinator.json",
"generated-artifacts/CoordinatorRegistry.json",
"generated-artifacts/LibConstants.json",
"generated-artifacts/LibCoordinatorApproval.json",
"generated-artifacts/LibCoordinatorRichErrors.json",
"generated-artifacts/LibEIP712CoordinatorDomain.json",
"test/generated-artifacts/Coordinator.json",
"test/generated-artifacts/CoordinatorRegistry.json",
"test/generated-artifacts/ICoordinatorApprovalVerifier.json",
"test/generated-artifacts/ICoordinatorCore.json",
"test/generated-artifacts/ICoordinatorRegistryCore.json",
"test/generated-artifacts/ICoordinatorSignatureValidator.json",
"test/generated-artifacts/LibConstants.json",
"test/generated-artifacts/LibCoordinatorApproval.json",
"test/generated-artifacts/LibCoordinatorRichErrors.json",
"test/generated-artifacts/LibEIP712CoordinatorDomain.json",
"test/generated-artifacts/MixinCoordinatorApprovalVerifier.json",
"test/generated-artifacts/MixinCoordinatorCore.json",
"test/generated-artifacts/MixinCoordinatorRegistryCore.json",
"test/generated-artifacts/MixinSignatureValidator.json"
],
"exclude": ["./deploy/solc/solc_bin"]
}

View File

@@ -0,0 +1,7 @@
{
"extends": "../../typedoc-tsconfig",
"compilerOptions": {
"outDir": "lib"
},
"include": ["./src/**/*", "./test/**/*"]
}

View File

@@ -0,0 +1,10 @@
# Blacklist all files
.*
*
# Whitelist lib
!lib/**/*
# Whitelist Solidity contracts
!contracts/src/**/*
# Blacklist tests in lib
/lib/test/*
# Package specific ignore

View File

@@ -1,4 +1,45 @@
[
{
"version": "0.1.0-beta.3",
"changes": [
{
"note": "Dependencies updated"
}
],
"timestamp": 1574238768
},
{
"version": "0.1.0-beta.2",
"changes": [
{
"note": "Drastically reduced bundle size by adding .npmignore, only exporting specific artifacts/wrappers/utils",
"pr": 2330
},
{
"note": "Add new method getOrderHash() to DevUtils contract",
"pr": 2321
},
{
"note": "Add new method getTransactionHash() to DevUtils contract",
"pr": 2321
}
],
"timestamp": 1574030254
},
{
"version": "0.1.0-beta.1",
"changes": [
{
"note": "Add `encodeStaticCallAssetData` and `decodeStaticCallAssetData` in LibAssetData",
"pr": 2034
},
{
"note": "Add `revertIfInvalidAssetData` in LibAssetData",
"pr": 2034
}
],
"timestamp": 1573159180
},
{
"version": "0.1.0-beta.0",
"changes": [

View File

@@ -5,6 +5,21 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
## v0.1.0-beta.3 - _November 20, 2019_
* Dependencies updated
## v0.1.0-beta.2 - _November 17, 2019_
* Drastically reduced bundle size by adding .npmignore, only exporting specific artifacts/wrappers/utils (#2330)
* Add new method getOrderHash() to DevUtils contract (#2321)
* Add new method getTransactionHash() to DevUtils contract (#2321)
## v0.1.0-beta.1 - _November 7, 2019_
* Add `encodeStaticCallAssetData` and `decodeStaticCallAssetData` in LibAssetData (#2034)
* Add `revertIfInvalidAssetData` in LibAssetData (#2034)
## v0.1.0-beta.0 - _October 3, 2019_
* Use built in selectors instead of hard coded constants (#2055)

View File

@@ -1,5 +1,5 @@
{
"artifactsDir": "./generated-artifacts",
"artifactsDir": "./test/generated-artifacts",
"contractsDir": "./contracts",
"useDockerisedSolc": false,
"isOfflineMode": false,
@@ -7,7 +7,7 @@
"evmVersion": "constantinople",
"optimizer": {
"enabled": true,
"runs": 10000,
"runs": 1666,
"details": { "yul": true, "deduplicate": true, "cse": true, "constantOptimizer": true }
},
"outputSelection": {

View File

@@ -19,6 +19,11 @@
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "@0x/contracts-utils/contracts/src/LibEIP712.sol";
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "./OrderValidationUtils.sol";
import "./OrderTransferSimulationUtils.sol";
import "./LibTransactionDecoder.sol";
@@ -29,6 +34,7 @@ import "./EthBalanceChecker.sol";
contract DevUtils is
OrderValidationUtils,
LibTransactionDecoder,
LibEIP712ExchangeDomain,
EthBalanceChecker,
OrderTransferSimulationUtils
{
@@ -36,5 +42,32 @@ contract DevUtils is
public
OrderValidationUtils(_exchange)
OrderTransferSimulationUtils(_exchange)
LibEIP712ExchangeDomain(uint256(0), address(0)) // null args because because we only use constants
{}
function getOrderHash(LibOrder.Order memory order, uint256 chainId, address exchange)
public
pure
returns (bytes32 orderHash)
{
return LibOrder.getTypedDataHash(
order,
LibEIP712.hashEIP712Domain(_EIP712_EXCHANGE_DOMAIN_NAME, _EIP712_EXCHANGE_DOMAIN_VERSION, chainId, exchange)
);
}
function getTransactionHash(
LibZeroExTransaction.ZeroExTransaction memory transaction,
uint256 chainId,
address exchange
)
public
pure
returns (bytes32 transactionHash)
{
return LibZeroExTransaction.getTypedDataHash(
transaction,
LibEIP712.hashEIP712Domain(_EIP712_EXCHANGE_DOMAIN_NAME, _EIP712_EXCHANGE_DOMAIN_VERSION, chainId, exchange)
);
}
}

View File

@@ -316,6 +316,29 @@ contract LibAssetData {
return (balances, allowances);
}
/// @dev Decode AssetProxy identifier
/// @param assetData AssetProxy-compliant asset data describing an ERC-20, ERC-721, ERC1155, or MultiAsset asset.
/// @return The AssetProxy identifier
function decodeAssetProxyId(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId
)
{
assetProxyId = assetData.readBytes4(0);
require(
assetProxyId == IAssetData(address(0)).ERC20Token.selector ||
assetProxyId == IAssetData(address(0)).ERC721Token.selector ||
assetProxyId == IAssetData(address(0)).ERC1155Assets.selector ||
assetProxyId == IAssetData(address(0)).MultiAsset.selector ||
assetProxyId == IAssetData(address(0)).StaticCall.selector,
"WRONG_PROXY_ID"
);
return assetProxyId;
}
/// @dev Encode ERC-20 asset data into the format described in the AssetProxy contract specification.
/// @param tokenAddress The address of the ERC-20 contract hosting the asset to be traded.
/// @return AssetProxy-compliant data describing the asset.
@@ -330,7 +353,7 @@ contract LibAssetData {
/// @dev Decode ERC-20 asset data from the format described in the AssetProxy contract specification.
/// @param assetData AssetProxy-compliant asset data describing an ERC-20 asset.
/// @return The ERC-20 AssetProxy identifier, and the address of the ERC-20
/// @return The AssetProxy identifier, and the address of the ERC-20
/// contract hosting this asset.
function decodeERC20AssetData(bytes memory assetData)
public
@@ -515,4 +538,75 @@ contract LibAssetData {
);
// solhint-enable indent
}
/// @dev Encode StaticCall asset data into the format described in the AssetProxy contract specification.
/// @param staticCallTargetAddress Target address of StaticCall.
/// @param staticCallData Data that will be passed to staticCallTargetAddress in the StaticCall.
/// @param expectedReturnDataHash Expected Keccak-256 hash of the StaticCall return data.
/// @return AssetProxy-compliant asset data describing the set of assets.
function encodeStaticCallAssetData(
address staticCallTargetAddress,
bytes memory staticCallData,
bytes32 expectedReturnDataHash
)
public
pure
returns (bytes memory assetData)
{
assetData = abi.encodeWithSelector(
IAssetData(address(0)).StaticCall.selector,
staticCallTargetAddress,
staticCallData,
expectedReturnDataHash
);
return assetData;
}
/// @dev Decode StaticCall asset data from the format described in the AssetProxy contract specification.
/// @param assetData AssetProxy-compliant asset data describing a StaticCall asset
/// @return The StaticCall AssetProxy identifier, the target address of the StaticCAll, the data to be
/// passed to the target address, and the expected Keccak-256 hash of the static call return data.
function decodeStaticCallAssetData(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId,
address staticCallTargetAddress,
bytes memory staticCallData,
bytes32 expectedReturnDataHash
)
{
assetProxyId = assetData.readBytes4(0);
require(
assetProxyId == IAssetData(address(0)).StaticCall.selector,
"WRONG_PROXY_ID"
);
(staticCallTargetAddress, staticCallData, expectedReturnDataHash) = abi.decode(
assetData.slice(4, assetData.length),
(address, bytes, bytes32)
);
}
function revertIfInvalidAssetData(bytes memory assetData)
public
pure
{
bytes4 assetProxyId = assetData.readBytes4(0);
if (assetProxyId == IAssetData(address(0)).ERC20Token.selector) {
decodeERC20AssetData(assetData);
} else if (assetProxyId == IAssetData(address(0)).ERC721Token.selector) {
decodeERC721AssetData(assetData);
} else if (assetProxyId == IAssetData(address(0)).ERC1155Assets.selector) {
decodeERC1155AssetData(assetData);
} else if (assetProxyId == IAssetData(address(0)).MultiAsset.selector) {
decodeMultiAssetData(assetData);
} else if (assetProxyId == IAssetData(address(0)).StaticCall.selector) {
decodeStaticCallAssetData(assetData);
} else {
revert("WRONG_PROXY_ID");
}
}
}

View File

@@ -1,42 +1,34 @@
{
"name": "@0x/contracts-dev-utils",
"version": "0.1.0-beta.0",
"version": "0.1.0-beta.3",
"engines": {
"node": ">=6.12"
},
"description": "0x protocol specific utility contracts",
"main": "lib/src/index.js",
"directories": {
"test": "test"
},
"scripts": {
"build": "yarn pre_build && tsc -b",
"test": "yarn assert_deployable && echo !!! Tests are run via @0x/contracts-tests !!!",
"assert_deployable": "node -e \"const bytecodeLen = (require('./generated-artifacts/DevUtils.json').compilerOutput.evm.bytecode.object.length-2)/2; assert(bytecodeLen<=0x6000,'DevUtils contract is too big to deploy, per EIP-170. '+bytecodeLen+'>'+0x6000)\"",
"build:ci": "yarn build",
"pre_build": "run-s compile quantify_bytecode contracts:gen generate_contract_wrappers",
"test": "yarn run_mocha",
"rebuild_and_test": "run-s build test",
"test:coverage": "SOLIDITY_COVERAGE=true run-s build run_mocha coverage:report:text coverage:report:lcov",
"test:profiler": "SOLIDITY_PROFILER=true run-s build run_mocha profiler:report:html",
"test:trace": "SOLIDITY_REVERT_TRACE=true run-s build run_mocha",
"run_mocha": "UNLIMITED_CONTRACT_SIZE=true mocha --require source-map-support/register --require make-promises-safe 'lib/test/**/*.js' --timeout 100000 --bail --exit",
"pre_build": "run-s compile quantify_bytecode contracts:gen generate_contract_wrappers contracts:copy",
"compile": "sol-compiler",
"watch": "sol-compiler -w",
"clean": "shx rm -rf lib generated-artifacts generated-wrappers",
"generate_contract_wrappers": "abi-gen --abis ${npm_package_config_abis} --output generated-wrappers --backend ethers",
"lint": "tslint --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"fix": "tslint --fix --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"coverage:report:text": "istanbul report text",
"coverage:report:html": "istanbul report html && open coverage/index.html",
"profiler:report:html": "istanbul report html && open coverage/index.html",
"coverage:report:lcov": "istanbul report lcov",
"test:circleci": "yarn test",
"contracts:gen": "contracts-gen",
"clean": "shx rm -rf lib test/generated-artifacts test/generated-wrappers generated-artifacts generated-wrappers",
"generate_contract_wrappers": "abi-gen --debug --abis ${npm_package_config_abis} --output test/generated-wrappers --backend ethers",
"lint": "tslint --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./test/generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude ./test/generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"fix": "tslint --fix --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./test/generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude ./test/generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"contracts:gen": "contracts-gen generate",
"contracts:copy": "contracts-gen copy",
"lint-contracts": "solhint -c ../.solhint.json contracts/**/**/**/**/*.sol",
"quantify_bytecode": "echo EVM bytecode object lengths:;for i in ./generated-artifacts/*.json; do node -e \"console.log('$i\t' + (require('$i').compilerOutput.evm.bytecode.object.length - 2) / 2)\"; done",
"compile:truffle": "truffle compile"
"quantify_bytecode": "echo EVM bytecode object lengths:;for i in ./test/generated-artifacts/*.json; do node -e \"console.log('$i\t' + (require('$i').compilerOutput.evm.bytecode.object.length - 2) / 2)\"; done",
"compile:truffle": "truffle compile",
"docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json",
"docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES"
},
"config": {
"abis": "./generated-artifacts/@(DevUtils|EthBalanceChecker|LibAssetData|LibTransactionDecoder|OrderTransferSimulationUtils|OrderValidationUtils).json",
"publicInterfaceContracts": "DevUtils,LibAssetData,LibTransactionDecoder",
"abis": "./test/generated-artifacts/@(DevUtils|EthBalanceChecker|LibAssetData|LibTransactionDecoder|OrderTransferSimulationUtils|OrderValidationUtils).json",
"abis:comment": "This list is auto-generated by contracts-gen. Don't edit manually."
},
"repository": {
@@ -49,44 +41,25 @@
},
"homepage": "https://github.com/0xProject/0x-monorepo/contracts/dev-utils/README.md",
"devDependencies": {
"@0x/abi-gen": "^4.3.0-beta.0",
"@0x/contracts-gen": "^1.1.0-beta.0",
"@0x/contracts-test-utils": "^3.2.0-beta.0",
"@0x/dev-utils": "^2.4.0-beta.0",
"@0x/sol-compiler": "^3.2.0-beta.0",
"@0x/tslint-config": "^3.0.1",
"@types/lodash": "4.14.104",
"@types/mocha": "^5.2.7",
"@0x/abi-gen": "^4.4.0-beta.3",
"@0x/assert": "^2.2.0-beta.2",
"@0x/contracts-gen": "^1.1.0-beta.3",
"@0x/sol-compiler": "^3.2.0-beta.3",
"@0x/ts-doc-gen": "^0.0.22",
"@0x/tslint-config": "^3.1.0-beta.2",
"@types/node": "*",
"chai": "^4.0.1",
"chai-as-promised": "^7.1.0",
"chai-bignumber": "^3.0.0",
"dirty-chai": "^2.0.1",
"make-promises-safe": "^1.1.0",
"mocha": "^6.2.0",
"ethers": "~4.0.4",
"npm-run-all": "^4.1.2",
"shx": "^0.2.2",
"solhint": "^1.4.1",
"truffle": "^5.0.32",
"tslint": "5.11.0",
"typedoc": "^0.15.0",
"typescript": "3.0.1"
},
"dependencies": {
"@0x/base-contract": "^5.5.0-beta.0",
"@0x/contracts-asset-proxy": "^2.3.0-beta.0",
"@0x/contracts-erc1155": "^1.2.0-beta.0",
"@0x/contracts-erc20": "^2.3.0-beta.0",
"@0x/contracts-erc721": "^2.2.0-beta.0",
"@0x/contracts-exchange": "^2.2.0-beta.0",
"@0x/contracts-exchange-libs": "^3.1.0-beta.0",
"@0x/contracts-utils": "^3.3.0-beta.0",
"@0x/order-utils": "^8.5.0-beta.0",
"@0x/types": "^2.5.0-beta.0",
"@0x/typescript-typings": "^4.4.0-beta.0",
"@0x/utils": "^4.6.0-beta.0",
"@0x/web3-wrapper": "^6.1.0-beta.0",
"ethereum-types": "^2.2.0-beta.0",
"ethereumjs-util": "^5.1.1"
"@0x/base-contract": "^5.5.0-beta.3",
"ethereum-types": "^2.2.0-beta.2"
},
"publishConfig": {
"access": "public"

View File

@@ -6,16 +6,10 @@
import { ContractArtifact } from 'ethereum-types';
import * as DevUtils from '../generated-artifacts/DevUtils.json';
import * as EthBalanceChecker from '../generated-artifacts/EthBalanceChecker.json';
import * as LibAssetData from '../generated-artifacts/LibAssetData.json';
import * as LibTransactionDecoder from '../generated-artifacts/LibTransactionDecoder.json';
import * as OrderTransferSimulationUtils from '../generated-artifacts/OrderTransferSimulationUtils.json';
import * as OrderValidationUtils from '../generated-artifacts/OrderValidationUtils.json';
export const artifacts = {
DevUtils: DevUtils as ContractArtifact,
EthBalanceChecker: EthBalanceChecker as ContractArtifact,
LibAssetData: LibAssetData as ContractArtifact,
LibTransactionDecoder: LibTransactionDecoder as ContractArtifact,
OrderTransferSimulationUtils: OrderTransferSimulationUtils as ContractArtifact,
OrderValidationUtils: OrderValidationUtils as ContractArtifact,
};

View File

@@ -1,2 +1,30 @@
export * from './artifacts';
export * from './wrappers';
export { artifacts } from './artifacts';
export { DevUtilsContract, LibAssetDataContract, LibTransactionDecoderContract } from './wrappers';
export {
ContractArtifact,
ContractChains,
CompilerOpts,
StandardContractOutput,
CompilerSettings,
ContractChainData,
ContractAbi,
DevdocOutput,
EvmOutput,
CompilerSettingsMetadata,
OptimizerSettings,
OutputField,
ParamDescription,
EvmBytecodeOutput,
AbiDefinition,
FunctionAbi,
EventAbi,
RevertErrorAbi,
EventParameter,
DataItem,
MethodAbi,
ConstructorAbi,
FallbackAbi,
ConstructorStateMutability,
TupleDataItem,
StateMutability,
} from 'ethereum-types';

View File

@@ -4,8 +4,5 @@
* -----------------------------------------------------------------------------
*/
export * from '../generated-wrappers/dev_utils';
export * from '../generated-wrappers/eth_balance_checker';
export * from '../generated-wrappers/lib_asset_data';
export * from '../generated-wrappers/lib_transaction_decoder';
export * from '../generated-wrappers/order_transfer_simulation_utils';
export * from '../generated-wrappers/order_validation_utils';

View File

@@ -0,0 +1,21 @@
/*
* -----------------------------------------------------------------------------
* Warning: This file is auto-generated by contracts-gen. Don't edit manually.
* -----------------------------------------------------------------------------
*/
import { ContractArtifact } from 'ethereum-types';
import * as DevUtils from '../test/generated-artifacts/DevUtils.json';
import * as EthBalanceChecker from '../test/generated-artifacts/EthBalanceChecker.json';
import * as LibAssetData from '../test/generated-artifacts/LibAssetData.json';
import * as LibTransactionDecoder from '../test/generated-artifacts/LibTransactionDecoder.json';
import * as OrderTransferSimulationUtils from '../test/generated-artifacts/OrderTransferSimulationUtils.json';
import * as OrderValidationUtils from '../test/generated-artifacts/OrderValidationUtils.json';
export const artifacts = {
DevUtils: DevUtils as ContractArtifact,
EthBalanceChecker: EthBalanceChecker as ContractArtifact,
LibAssetData: LibAssetData as ContractArtifact,
LibTransactionDecoder: LibTransactionDecoder as ContractArtifact,
OrderTransferSimulationUtils: OrderTransferSimulationUtils as ContractArtifact,
OrderValidationUtils: OrderValidationUtils as ContractArtifact,
};

View File

@@ -1,651 +0,0 @@
import {
artifacts as proxyArtifacts,
ERC20ProxyContract,
ERC20Wrapper,
ERC721ProxyContract,
ERC721Wrapper,
MultiAssetProxyContract,
} from '@0x/contracts-asset-proxy';
import { DummyERC20TokenContract } from '@0x/contracts-erc20';
import { DummyERC721TokenContract } from '@0x/contracts-erc721';
import { artifacts as exchangeArtifacts, ExchangeContract, ExchangeWrapper } from '@0x/contracts-exchange';
import {
chaiSetup,
constants,
OrderFactory,
OrderStatus,
provider,
txDefaults,
web3Wrapper,
} from '@0x/contracts-test-utils';
import { BlockchainLifecycle } from '@0x/dev-utils';
import { assetDataUtils, orderHashUtils } from '@0x/order-utils';
import { OrderTransferResults, SignedOrder } from '@0x/types';
import { BigNumber, providerUtils } from '@0x/utils';
import * as chai from 'chai';
import { artifacts, DevUtilsContract } from '../src';
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
describe('OrderValidationUtils/OrderTransferSimulatorUtils', () => {
let makerAddress: string;
let takerAddress: string;
let owner: string;
let erc20AssetData: string;
let erc20AssetData2: string;
let erc721AssetData: string;
let feeAssetData: string;
let erc20Token: DummyERC20TokenContract;
let erc20Token2: DummyERC20TokenContract;
let feeErc20Token: DummyERC20TokenContract;
let erc721Token: DummyERC721TokenContract;
let exchange: ExchangeContract;
let devUtils: DevUtilsContract;
let erc20Proxy: ERC20ProxyContract;
let erc721Proxy: ERC721ProxyContract;
let multiAssetProxy: MultiAssetProxyContract;
let signedOrder: SignedOrder;
let orderFactory: OrderFactory;
const tokenId = new BigNumber(123456789);
before(async () => {
await blockchainLifecycle.startAsync();
});
after(async () => {
await blockchainLifecycle.revertAsync();
});
before(async () => {
const accounts = await web3Wrapper.getAvailableAddressesAsync();
const usedAddresses = ([owner, makerAddress, takerAddress] = accounts.slice(0, 3));
const chainId = await providerUtils.getChainIdAsync(provider);
const erc20Wrapper = new ERC20Wrapper(provider, usedAddresses, owner);
const erc721Wrapper = new ERC721Wrapper(provider, usedAddresses, owner);
const numDummyErc20ToDeploy = 3;
[erc20Token, erc20Token2, feeErc20Token] = await erc20Wrapper.deployDummyTokensAsync(
numDummyErc20ToDeploy,
constants.DUMMY_TOKEN_DECIMALS,
);
erc20Proxy = await erc20Wrapper.deployProxyAsync();
[erc721Token] = await erc721Wrapper.deployDummyTokensAsync();
erc721Proxy = await erc721Wrapper.deployProxyAsync();
feeAssetData = assetDataUtils.encodeERC20AssetData(feeErc20Token.address);
exchange = await ExchangeContract.deployFrom0xArtifactAsync(
exchangeArtifacts.Exchange,
provider,
txDefaults,
{},
new BigNumber(chainId),
);
multiAssetProxy = await MultiAssetProxyContract.deployFrom0xArtifactAsync(
proxyArtifacts.MultiAssetProxy,
provider,
txDefaults,
artifacts,
);
const exchangeWrapper = new ExchangeWrapper(exchange);
await exchangeWrapper.registerAssetProxyAsync(erc20Proxy.address, owner);
await exchangeWrapper.registerAssetProxyAsync(erc721Proxy.address, owner);
await exchangeWrapper.registerAssetProxyAsync(multiAssetProxy.address, owner);
await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner });
await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner });
devUtils = await DevUtilsContract.deployFrom0xArtifactAsync(
artifacts.DevUtils,
provider,
txDefaults,
artifacts,
exchange.address,
);
erc20AssetData = assetDataUtils.encodeERC20AssetData(erc20Token.address);
erc20AssetData2 = assetDataUtils.encodeERC20AssetData(erc20Token2.address);
erc721AssetData = assetDataUtils.encodeERC721AssetData(erc721Token.address, tokenId);
const defaultOrderParams = {
...constants.STATIC_ORDER_PARAMS,
makerAddress,
feeRecipientAddress: constants.NULL_ADDRESS,
makerAssetData: erc20AssetData,
takerAssetData: erc20AssetData2,
makerFeeAssetData: feeAssetData,
takerFeeAssetData: feeAssetData,
exchangeAddress: exchange.address,
chainId,
};
const privateKey = constants.TESTRPC_PRIVATE_KEYS[accounts.indexOf(makerAddress)];
orderFactory = new OrderFactory(privateKey, defaultOrderParams);
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('getTransferableAssetAmount', () => {
it('should return the balance when balance < allowance', async () => {
const balance = new BigNumber(123);
const allowance = new BigNumber(456);
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, balance);
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, allowance, {
from: makerAddress,
});
const transferableAmount = await devUtils.getTransferableAssetAmount.callAsync(
makerAddress,
erc20AssetData,
);
expect(transferableAmount).to.bignumber.equal(balance);
});
it('should return the allowance when allowance < balance', async () => {
const balance = new BigNumber(456);
const allowance = new BigNumber(123);
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, balance);
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, allowance, {
from: makerAddress,
});
const transferableAmount = await devUtils.getTransferableAssetAmount.callAsync(
makerAddress,
erc20AssetData,
);
expect(transferableAmount).to.bignumber.equal(allowance);
});
it('should return the correct transferable amount for multiAssetData', async () => {
const multiAssetData = assetDataUtils.encodeMultiAssetData(
[new BigNumber(1), new BigNumber(1)],
[erc20AssetData, erc20AssetData2],
);
const transferableAmount1 = new BigNumber(10);
const transferableAmount2 = new BigNumber(5);
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, transferableAmount1);
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, transferableAmount1, {
from: makerAddress,
});
await erc20Token2.setBalance.awaitTransactionSuccessAsync(makerAddress, transferableAmount2);
await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, transferableAmount2, {
from: makerAddress,
});
const transferableAmount = await devUtils.getTransferableAssetAmount.callAsync(
makerAddress,
multiAssetData,
);
expect(transferableAmount).to.bignumber.equal(transferableAmount2);
});
});
describe('getOrderRelevantState', () => {
beforeEach(async () => {
signedOrder = await orderFactory.newSignedOrderAsync();
});
it('should return the correct orderInfo when the order is valid', async () => {
const [orderInfo] = await devUtils.getOrderRelevantState.callAsync(signedOrder, signedOrder.signature);
expect(orderInfo.orderHash).to.equal(orderHashUtils.getOrderHashHex(signedOrder));
expect(orderInfo.orderStatus).to.equal(OrderStatus.Fillable);
expect(orderInfo.orderTakerAssetFilledAmount).to.bignumber.equal(constants.ZERO_AMOUNT);
});
it('should return isValidSignature=true when the signature is valid', async () => {
const [, , isValidSignature] = await devUtils.getOrderRelevantState.callAsync(
signedOrder,
signedOrder.signature,
);
expect(isValidSignature).to.equal(true);
});
it('should return isValidSignature=false when the signature is invalid', async () => {
const invalidSignature = '0x01';
const [, , isValidSignature] = await devUtils.getOrderRelevantState.callAsync(
signedOrder,
invalidSignature,
);
expect(isValidSignature).to.equal(false);
});
it('should return a fillableTakerAssetAmount of 0 when balances or allowances are insufficient', async () => {
const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync(
signedOrder,
signedOrder.signature,
);
expect(fillableTakerAssetAmount).to.bignumber.equal(constants.ZERO_AMOUNT);
});
it('should return a fillableTakerAssetAmount of 0 when fee balances/allowances are insufficient', async () => {
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount);
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync(
signedOrder,
signedOrder.signature,
);
expect(fillableTakerAssetAmount).to.bignumber.equal(constants.ZERO_AMOUNT);
});
it('should return a fillableTakerAssetAmount of 0 when balances/allowances of one asset within a multiAssetData are insufficient', async () => {
const multiAssetData = assetDataUtils.encodeMultiAssetData(
[new BigNumber(1), new BigNumber(1)],
[erc20AssetData, erc20AssetData2],
);
signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData: multiAssetData });
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount);
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync(
signedOrder,
signedOrder.signature,
);
expect(fillableTakerAssetAmount).to.bignumber.equal(constants.ZERO_AMOUNT);
});
it('should return the correct fillableTakerAssetAmount when fee balances/allowances are partially sufficient', async () => {
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount);
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
const divisor = 4;
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(
makerAddress,
signedOrder.makerFee.dividedToIntegerBy(divisor),
);
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, {
from: makerAddress,
});
const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync(
signedOrder,
signedOrder.signature,
);
expect(fillableTakerAssetAmount).to.bignumber.equal(
signedOrder.takerAssetAmount.dividedToIntegerBy(divisor),
);
});
it('should return the correct fillableTakerAssetAmount when non-fee balances/allowances are partially sufficient', async () => {
const divisor = 4;
await erc20Token.setBalance.awaitTransactionSuccessAsync(
makerAddress,
signedOrder.makerAssetAmount.dividedToIntegerBy(divisor),
);
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee);
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, {
from: makerAddress,
});
const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync(
signedOrder,
signedOrder.signature,
);
expect(fillableTakerAssetAmount).to.bignumber.equal(
signedOrder.takerAssetAmount.dividedToIntegerBy(divisor),
);
});
it('should return the correct fillableTakerAssetAmount when balances/allowances of one asset within a multiAssetData are partially sufficient', async () => {
const multiAssetData = assetDataUtils.encodeMultiAssetData(
[new BigNumber(1), new BigNumber(1)],
[erc20AssetData, erc20AssetData2],
);
signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData: multiAssetData });
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount);
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee);
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, {
from: makerAddress,
});
const divisor = 4;
await erc20Token2.setBalance.awaitTransactionSuccessAsync(
makerAddress,
signedOrder.makerAssetAmount.dividedToIntegerBy(divisor),
);
await erc20Token2.approve.awaitTransactionSuccessAsync(
erc20Proxy.address,
signedOrder.makerAssetAmount.dividedToIntegerBy(divisor),
{
from: makerAddress,
},
);
const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync(
signedOrder,
signedOrder.signature,
);
expect(fillableTakerAssetAmount).to.bignumber.equal(
signedOrder.takerAssetAmount.dividedToIntegerBy(divisor),
);
});
it('should return a fillableTakerAssetAmount of 0 when non-fee balances/allowances are insufficient', async () => {
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee);
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, {
from: makerAddress,
});
const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync(
signedOrder,
signedOrder.signature,
);
expect(fillableTakerAssetAmount).to.bignumber.equal(constants.ZERO_AMOUNT);
});
it('should return a fillableTakerAssetAmount equal to the takerAssetAmount when the order is unfilled and balances/allowances are sufficient', async () => {
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount);
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee);
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, {
from: makerAddress,
});
const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync(
signedOrder,
signedOrder.signature,
);
expect(fillableTakerAssetAmount).to.bignumber.equal(signedOrder.takerAssetAmount);
});
it('should return the correct fillableTakerAssetAmount when balances/allowances are partially sufficient and makerAsset=makerFeeAsset', async () => {
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData: feeAssetData,
makerAssetAmount: new BigNumber(10),
takerAssetAmount: new BigNumber(20),
makerFee: new BigNumber(40),
});
const transferableMakerAssetAmount = new BigNumber(10);
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, transferableMakerAssetAmount);
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, transferableMakerAssetAmount, {
from: makerAddress,
});
const expectedFillableTakerAssetAmount = transferableMakerAssetAmount
.times(signedOrder.takerAssetAmount)
.dividedToIntegerBy(signedOrder.makerAssetAmount.plus(signedOrder.makerFee));
const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync(
signedOrder,
signedOrder.signature,
);
expect(fillableTakerAssetAmount).to.bignumber.equal(expectedFillableTakerAssetAmount);
});
it('should return the correct fillabeTakerassetAmount when makerAsset balances/allowances are sufficient and there are no maker fees', async () => {
signedOrder = await orderFactory.newSignedOrderAsync({ makerFee: constants.ZERO_AMOUNT });
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount);
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync(
signedOrder,
signedOrder.signature,
);
expect(fillableTakerAssetAmount).to.bignumber.equal(signedOrder.takerAssetAmount);
});
it('should return a fillableTakerAssetAmount when the remaining takerAssetAmount is less than the transferable amount', async () => {
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount);
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee);
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, {
from: makerAddress,
});
await erc20Token2.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerAssetAmount);
await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, {
from: takerAddress,
});
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerFee);
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerFee, {
from: takerAddress,
});
const takerAssetFillAmount = signedOrder.takerAssetAmount.dividedToIntegerBy(4);
await exchange.fillOrder.awaitTransactionSuccessAsync(
signedOrder,
takerAssetFillAmount,
signedOrder.signature,
{ from: takerAddress },
);
const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync(
signedOrder,
signedOrder.signature,
);
expect(fillableTakerAssetAmount).to.bignumber.equal(
signedOrder.takerAssetAmount.minus(takerAssetFillAmount),
);
});
it('should return correct info even when there are no fees specified', async () => {
signedOrder = await orderFactory.newSignedOrderAsync({
makerFee: new BigNumber(0),
takerFee: new BigNumber(0),
makerFeeAssetData: '0x',
takerFeeAssetData: '0x',
});
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount);
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
const [
orderInfo,
fillableTakerAssetAmount,
isValidSignature,
] = await devUtils.getOrderRelevantState.callAsync(signedOrder, signedOrder.signature);
expect(orderInfo.orderHash).to.equal(orderHashUtils.getOrderHashHex(signedOrder));
expect(orderInfo.orderStatus).to.equal(OrderStatus.Fillable);
expect(orderInfo.orderTakerAssetFilledAmount).to.bignumber.equal(constants.ZERO_AMOUNT);
expect(fillableTakerAssetAmount).to.bignumber.equal(signedOrder.takerAssetAmount);
expect(isValidSignature).to.equal(true);
});
});
describe('getOrderRelevantStates', async () => {
it('should return the correct information for multiple orders', async () => {
signedOrder = await orderFactory.newSignedOrderAsync();
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount);
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee);
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, {
from: makerAddress,
});
const signedOrder2 = await orderFactory.newSignedOrderAsync({ makerAssetData: erc721AssetData });
const invalidSignature = '0x01';
await exchange.cancelOrder.awaitTransactionSuccessAsync(signedOrder2, { from: makerAddress });
const [
ordersInfo,
fillableTakerAssetAmounts,
isValidSignature,
] = await devUtils.getOrderRelevantStates.callAsync(
[signedOrder, signedOrder2],
[signedOrder.signature, invalidSignature],
);
expect(ordersInfo[0].orderHash).to.equal(orderHashUtils.getOrderHashHex(signedOrder));
expect(ordersInfo[1].orderHash).to.equal(orderHashUtils.getOrderHashHex(signedOrder2));
expect(ordersInfo[0].orderStatus).to.equal(OrderStatus.Fillable);
expect(ordersInfo[1].orderStatus).to.equal(OrderStatus.Cancelled);
expect(ordersInfo[0].orderTakerAssetFilledAmount).to.bignumber.equal(constants.ZERO_AMOUNT);
expect(ordersInfo[1].orderTakerAssetFilledAmount).to.bignumber.equal(constants.ZERO_AMOUNT);
expect(fillableTakerAssetAmounts[0]).to.bignumber.equal(signedOrder.takerAssetAmount);
expect(fillableTakerAssetAmounts[1]).to.bignumber.equal(constants.ZERO_AMOUNT);
expect(isValidSignature[0]).to.equal(true);
expect(isValidSignature[1]).to.equal(false);
});
});
describe('getSimulatedOrderTransferResults', () => {
beforeEach(async () => {
signedOrder = await orderFactory.newSignedOrderAsync();
});
it('should return TakerAssetDataFailed if the takerAsset transfer fails', async () => {
const orderTransferResults = await devUtils.getSimulatedOrderTransferResults.callAsync(
signedOrder,
takerAddress,
signedOrder.takerAssetAmount,
);
expect(orderTransferResults).to.equal(OrderTransferResults.TakerAssetDataFailed);
});
it('should return MakerAssetDataFailed if the makerAsset transfer fails', async () => {
await erc20Token2.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerAssetAmount, {
from: owner,
});
await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, {
from: takerAddress,
});
const orderTransferResults = await devUtils.getSimulatedOrderTransferResults.callAsync(
signedOrder,
takerAddress,
signedOrder.takerAssetAmount,
);
expect(orderTransferResults).to.equal(OrderTransferResults.MakerAssetDataFailed);
});
it('should return TakerFeeAssetDataFailed if the takerFeeAsset transfer fails', async () => {
await erc20Token2.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerAssetAmount, {
from: owner,
});
await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, {
from: takerAddress,
});
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount, {
from: owner,
});
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
const orderTransferResults = await devUtils.getSimulatedOrderTransferResults.callAsync(
signedOrder,
takerAddress,
signedOrder.takerAssetAmount,
);
expect(orderTransferResults).to.equal(OrderTransferResults.TakerFeeAssetDataFailed);
});
it('should return MakerFeeAssetDataFailed if the makerFeeAsset transfer fails', async () => {
await erc20Token2.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerAssetAmount, {
from: owner,
});
await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, {
from: takerAddress,
});
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount, {
from: owner,
});
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerFee, {
from: owner,
});
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerFee, {
from: takerAddress,
});
const orderTransferResults = await devUtils.getSimulatedOrderTransferResults.callAsync(
signedOrder,
takerAddress,
signedOrder.takerAssetAmount,
);
expect(orderTransferResults).to.equal(OrderTransferResults.MakerFeeAssetDataFailed);
});
it('should return TransfersSuccessful if all transfers succeed', async () => {
await erc20Token2.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerAssetAmount, {
from: owner,
});
await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, {
from: takerAddress,
});
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount, {
from: owner,
});
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerFee, {
from: owner,
});
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerFee, {
from: takerAddress,
});
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee, {
from: owner,
});
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, {
from: makerAddress,
});
const orderTransferResults = await devUtils.getSimulatedOrderTransferResults.callAsync(
signedOrder,
takerAddress,
signedOrder.takerAssetAmount,
);
expect(orderTransferResults).to.equal(OrderTransferResults.TransfersSuccessful);
});
it('should return TransfersSuccessful for a partial fill when taker has ample assets for the fill but not for the whole order', async () => {
await erc20Token2.setBalance.awaitTransactionSuccessAsync(
takerAddress,
signedOrder.takerAssetAmount.dividedBy(2),
{
from: owner,
},
);
await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, {
from: takerAddress,
});
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount, {
from: owner,
});
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerFee, {
from: owner,
});
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerFee, {
from: takerAddress,
});
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee, {
from: owner,
});
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, {
from: makerAddress,
});
const orderTransferResults = await devUtils.getSimulatedOrderTransferResults.callAsync(
signedOrder,
takerAddress,
signedOrder.takerAssetAmount.dividedBy(2),
);
expect(orderTransferResults).to.equal(OrderTransferResults.TransfersSuccessful);
});
});
describe('getSimulatedOrdersTransferResults', async () => {
it('should simulate the transfers of each order independently from one another', async () => {
// Set balances and allowances to exactly enough to fill a single order
await erc20Token2.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerAssetAmount, {
from: owner,
});
await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, {
from: takerAddress,
});
await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount, {
from: owner,
});
await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, {
from: makerAddress,
});
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerFee, {
from: owner,
});
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerFee, {
from: takerAddress,
});
await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee, {
from: owner,
});
await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, {
from: makerAddress,
});
const [
orderTransferResults1,
orderTransferResults2,
] = await devUtils.getSimulatedOrdersTransferResults.callAsync(
[signedOrder, signedOrder],
[takerAddress, takerAddress],
[signedOrder.takerAssetAmount, signedOrder.takerAssetAmount],
);
expect(orderTransferResults1).to.equal(OrderTransferResults.TransfersSuccessful);
expect(orderTransferResults2).to.equal(OrderTransferResults.TransfersSuccessful);
});
});
});
// tslint:disable:max-file-line-count

View File

@@ -0,0 +1,11 @@
/*
* -----------------------------------------------------------------------------
* Warning: This file is auto-generated by contracts-gen. Don't edit manually.
* -----------------------------------------------------------------------------
*/
export * from '../test/generated-wrappers/dev_utils';
export * from '../test/generated-wrappers/eth_balance_checker';
export * from '../test/generated-wrappers/lib_asset_data';
export * from '../test/generated-wrappers/lib_transaction_decoder';
export * from '../test/generated-wrappers/order_transfer_simulation_utils';
export * from '../test/generated-wrappers/order_validation_utils';

View File

@@ -4,11 +4,14 @@
"include": ["./src/**/*", "./test/**/*", "./generated-wrappers/**/*"],
"files": [
"generated-artifacts/DevUtils.json",
"generated-artifacts/EthBalanceChecker.json",
"generated-artifacts/LibAssetData.json",
"generated-artifacts/LibTransactionDecoder.json",
"generated-artifacts/OrderTransferSimulationUtils.json",
"generated-artifacts/OrderValidationUtils.json"
"test/generated-artifacts/DevUtils.json",
"test/generated-artifacts/EthBalanceChecker.json",
"test/generated-artifacts/LibAssetData.json",
"test/generated-artifacts/LibTransactionDecoder.json",
"test/generated-artifacts/OrderTransferSimulationUtils.json",
"test/generated-artifacts/OrderValidationUtils.json"
],
"exclude": ["./deploy/solc/solc_bin"]
}

View File

@@ -0,0 +1,7 @@
{
"extends": "../../typedoc-tsconfig",
"compilerOptions": {
"outDir": "lib"
},
"include": ["./src/**/*", "./test/**/*"]
}

View File

@@ -0,0 +1,10 @@
# Blacklist all files
.*
*
# Whitelist lib
!lib/**/*
# Whitelist Solidity contracts
!contracts/src/**/*
# Blacklist tests in lib
/lib/test/*
# Package specific ignore

View File

@@ -1,10 +1,42 @@
[
{
"version": "1.2.0-beta.3",
"changes": [
{
"note": "Dependencies updated"
}
],
"timestamp": 1574238768
},
{
"version": "1.2.0-beta.2",
"changes": [
{
"note": "Drastically reduced bundle size by adding .npmignore, only exporting specific artifacts/wrappers/utils",
"pr": 2330
}
],
"timestamp": 1574030254
},
{
"version": "1.2.0-beta.1",
"changes": [
{
"note": "Dependencies updated"
}
],
"timestamp": 1573159180
},
{
"version": "1.2.0-beta.0",
"changes": [
{
"note": "Add `mintKnownFungibleTokensAsync()`, `isNonFungibleItemAsync()`, `isFungibleItemAsync()`, `getOwnerOfAsync()`, `getBalanceAsync()` to `Erc1155Wrapper`.",
"pr": 1819
},
{
"note": "Replaced `SafeMath` with `LibSafeMath`",
"pr": 2254
}
],
"timestamp": 1570135330

View File

@@ -5,9 +5,22 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
## v1.2.0-beta.3 - _November 20, 2019_
* Dependencies updated
## v1.2.0-beta.2 - _November 17, 2019_
* Drastically reduced bundle size by adding .npmignore, only exporting specific artifacts/wrappers/utils (#2330)
## v1.2.0-beta.1 - _November 7, 2019_
* Dependencies updated
## v1.2.0-beta.0 - _October 3, 2019_
* Add `mintKnownFungibleTokensAsync()`, `isNonFungibleItemAsync()`, `isFungibleItemAsync()`, `getOwnerOfAsync()`, `getBalanceAsync()` to `Erc1155Wrapper`. (#1819)
* Replaced `SafeMath` with `LibSafeMath` (#2254)
## v1.1.15 - _September 17, 2019_

View File

@@ -1,5 +1,5 @@
{
"artifactsDir": "./generated-artifacts",
"artifactsDir": "./test/generated-artifacts",
"contractsDir": "./contracts",
"useDockerisedSolc": false,
"isOfflineMode": false,

View File

@@ -18,7 +18,7 @@
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/SafeMath.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "@0x/contracts-utils/contracts/src/LibAddress.sol";
import "./interfaces/IERC1155.sol";
import "./interfaces/IERC1155Receiver.sol";
@@ -26,11 +26,11 @@ import "./MixinNonFungibleToken.sol";
contract ERC1155 is
SafeMath,
IERC1155,
MixinNonFungibleToken
{
using LibAddress for address;
using LibSafeMath for uint256;
// selectors for receiver callbacks
bytes4 constant public ERC1155_RECEIVED = 0xf23a6e61;
@@ -88,11 +88,11 @@ contract ERC1155 is
nfOwners[id] = to;
// You could keep balance of NF type in base type id like so:
// uint256 baseType = getNonFungibleBaseType(_id);
// balances[baseType][_from] = balances[baseType][_from]._safeSub(_value);
// balances[baseType][_to] = balances[baseType][_to]._safeAdd(_value);
// balances[baseType][_from] = balances[baseType][_from].safeSub(_value);
// balances[baseType][_to] = balances[baseType][_to].safeAdd(_value);
} else {
balances[id][from] = _safeSub(balances[id][from], value);
balances[id][to] = _safeAdd(balances[id][to], value);
balances[id][from] = balances[id][from].safeSub(value);
balances[id][to] = balances[id][to].safeAdd(value);
}
emit TransferSingle(msg.sender, from, to, id, value);
@@ -170,8 +170,8 @@ contract ERC1155 is
);
nfOwners[id] = to;
} else {
balances[id][from] = _safeSub(balances[id][from], value);
balances[id][to] = _safeAdd(balances[id][to], value);
balances[id][from] = balances[id][from].safeSub(value);
balances[id][to] = balances[id][to].safeAdd(value);
}
}
emit TransferBatch(msg.sender, from, to, ids, values);

View File

@@ -1,6 +1,6 @@
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/SafeMath.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "./ERC1155.sol";
import "./interfaces/IERC1155Mintable.sol";
@@ -11,6 +11,7 @@ contract ERC1155Mintable is
IERC1155Mintable,
ERC1155
{
using LibSafeMath for uint256;
/// token nonce
uint256 internal nonce;
@@ -37,7 +38,7 @@ contract ERC1155Mintable is
)
external
returns (uint256 type_)
{
{
// Store the type in the upper 128 bits
type_ = (++nonce << 128);
@@ -114,7 +115,7 @@ contract ERC1155Mintable is
uint256 quantity = quantities[i];
// Grant the items to the caller
balances[id][dst] = _safeAdd(quantity, balances[id][dst]);
balances[id][dst] = quantity.safeAdd(balances[id][dst]);
// Emit the Transfer/Mint event.
// the 0x0 source address implies a mint
@@ -172,7 +173,7 @@ contract ERC1155Mintable is
nfOwners[id] = dst;
// You could use base-type id to store NF type balances if you wish.
// balances[_type][dst] = quantity._safeAdd(balances[_type][dst]);
// balances[_type][dst] = quantity.safeAdd(balances[_type][dst]);
emit TransferSingle(msg.sender, address(0x0), dst, id, 1);
@@ -194,6 +195,6 @@ contract ERC1155Mintable is
// record the `maxIndex` of this nft type
// this allows us to mint more nft's of this type in a subsequent call.
maxIndex[type_] = _safeAdd(to.length, maxIndex[type_]);
maxIndex[type_] = to.length.safeAdd(maxIndex[type_]);
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@0x/contracts-erc1155",
"version": "1.2.0-beta.0",
"version": "1.2.0-beta.3",
"engines": {
"node": ">=6.12"
},
@@ -12,7 +12,7 @@
"scripts": {
"build": "yarn pre_build && tsc -b",
"build:ci": "yarn build",
"pre_build": "run-s compile contracts:gen generate_contract_wrappers",
"pre_build": "run-s compile contracts:gen generate_contract_wrappers contracts:copy",
"test": "yarn run_mocha",
"rebuild_and_test": "run-s build test",
"test:coverage": "SOLIDITY_COVERAGE=true run-s build run_mocha coverage:report:text coverage:report:lcov",
@@ -21,21 +21,25 @@
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe 'lib/test/**/*.js' --timeout 100000 --bail --exit",
"compile": "sol-compiler",
"watch": "sol-compiler -w",
"clean": "shx rm -rf lib generated-artifacts generated-wrappers",
"generate_contract_wrappers": "abi-gen --abis ${npm_package_config_abis} --output generated-wrappers --backend ethers",
"lint": "tslint --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"fix": "tslint --fix --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"clean": "shx rm -rf lib test/generated-artifacts test/generated-wrappers generated-artifacts generated-wrappers",
"generate_contract_wrappers": "abi-gen --debug --abis ${npm_package_config_abis} --output test/generated-wrappers --backend ethers",
"lint": "tslint --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./test/generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude ./test/generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"fix": "tslint --fix --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./test/generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude ./test/generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"coverage:report:text": "istanbul report text",
"coverage:report:html": "istanbul report html && open coverage/index.html",
"profiler:report:html": "istanbul report html && open coverage/index.html",
"coverage:report:lcov": "istanbul report lcov",
"test:circleci": "yarn test",
"contracts:gen": "contracts-gen",
"contracts:gen": "contracts-gen generate",
"contracts:copy": "contracts-gen copy",
"lint-contracts": "solhint -c ../.solhint.json contracts/**/**/**/**/*.sol",
"compile:truffle": "truffle compile"
"compile:truffle": "truffle compile",
"docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json",
"docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES"
},
"config": {
"abis": "./generated-artifacts/@(DummyERC1155Receiver|ERC1155|ERC1155Mintable|IERC1155|IERC1155Mintable|IERC1155Receiver|MixinNonFungibleToken).json",
"publicInterfaceContracts": "ERC1155,ERC1155Mintable,IERC1155Receiver,DummyERC1155Receiver",
"abis": "./test/generated-artifacts/@(DummyERC1155Receiver|ERC1155|ERC1155Mintable|IERC1155|IERC1155Mintable|IERC1155Receiver|MixinNonFungibleToken).json",
"abis:comment": "This list is auto-generated by contracts-gen. Don't edit manually."
},
"repository": {
@@ -48,11 +52,14 @@
},
"homepage": "https://github.com/0xProject/0x-monorepo/contracts/tokens/README.md",
"devDependencies": {
"@0x/abi-gen": "^4.3.0-beta.0",
"@0x/contracts-gen": "^1.1.0-beta.0",
"@0x/dev-utils": "^2.4.0-beta.0",
"@0x/sol-compiler": "^3.2.0-beta.0",
"@0x/tslint-config": "^3.0.1",
"@0x/abi-gen": "^4.4.0-beta.3",
"@0x/contracts-gen": "^1.1.0-beta.3",
"@0x/contracts-utils": "^3.3.0-beta.3",
"@0x/dev-utils": "^2.4.0-beta.3",
"@0x/sol-compiler": "^3.2.0-beta.3",
"@0x/ts-doc-gen": "^0.0.22",
"@0x/tslint-config": "^3.1.0-beta.2",
"@0x/types": "^2.5.0-beta.2",
"@types/lodash": "4.14.104",
"@types/mocha": "^5.2.7",
"@types/node": "*",
@@ -67,17 +74,16 @@
"solhint": "^1.4.1",
"truffle": "^5.0.32",
"tslint": "5.11.0",
"typedoc": "^0.15.0",
"typescript": "3.0.1"
},
"dependencies": {
"@0x/base-contract": "^5.5.0-beta.0",
"@0x/contracts-test-utils": "^3.2.0-beta.0",
"@0x/contracts-utils": "^3.3.0-beta.0",
"@0x/types": "^2.5.0-beta.0",
"@0x/typescript-typings": "^4.4.0-beta.0",
"@0x/utils": "^4.6.0-beta.0",
"@0x/web3-wrapper": "^6.1.0-beta.0",
"ethereum-types": "^2.2.0-beta.0",
"@0x/base-contract": "^5.5.0-beta.3",
"@0x/contracts-test-utils": "^3.2.0-beta.3",
"@0x/typescript-typings": "^4.4.0-beta.2",
"@0x/utils": "^4.6.0-beta.2",
"@0x/web3-wrapper": "^6.1.0-beta.2",
"ethereum-types": "^2.2.0-beta.2",
"lodash": "^4.17.11"
},
"publishConfig": {

View File

@@ -8,16 +8,10 @@ import { ContractArtifact } from 'ethereum-types';
import * as DummyERC1155Receiver from '../generated-artifacts/DummyERC1155Receiver.json';
import * as ERC1155 from '../generated-artifacts/ERC1155.json';
import * as ERC1155Mintable from '../generated-artifacts/ERC1155Mintable.json';
import * as IERC1155 from '../generated-artifacts/IERC1155.json';
import * as IERC1155Mintable from '../generated-artifacts/IERC1155Mintable.json';
import * as IERC1155Receiver from '../generated-artifacts/IERC1155Receiver.json';
import * as MixinNonFungibleToken from '../generated-artifacts/MixinNonFungibleToken.json';
export const artifacts = {
ERC1155: ERC1155 as ContractArtifact,
ERC1155Mintable: ERC1155Mintable as ContractArtifact,
MixinNonFungibleToken: MixinNonFungibleToken as ContractArtifact,
IERC1155: IERC1155 as ContractArtifact,
IERC1155Mintable: IERC1155Mintable as ContractArtifact,
IERC1155Receiver: IERC1155Receiver as ContractArtifact,
DummyERC1155Receiver: DummyERC1155Receiver as ContractArtifact,
};

View File

@@ -1,11 +1,13 @@
import { constants, LogDecoder } from '@0x/contracts-test-utils';
import { LogDecoder } from '@0x/contracts-test-utils';
import { BigNumber } from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wrapper';
import * as chai from 'chai';
import { LogWithDecodedArgs, Provider, TransactionReceiptWithDecodedLogs } from 'ethereum-types';
import * as _ from 'lodash';
import { artifacts, ERC1155MintableContract, ERC1155TransferSingleEventArgs } from '../../src';
import { ERC1155MintableContract, ERC1155TransferSingleEventArgs } from './wrappers';
import { artifacts } from './artifacts';
const expect = chai.expect;
@@ -25,7 +27,7 @@ export class Erc1155Wrapper {
return this._erc1155Contract;
}
public async getBalancesAsync(owners: string[], tokens: BigNumber[]): Promise<BigNumber[]> {
const balances = await this._erc1155Contract.balanceOfBatch.callAsync(owners, tokens);
const balances = await this._erc1155Contract.balanceOfBatch(owners, tokens).callAsync();
return balances;
}
public async safeTransferFromAsync(
@@ -39,7 +41,7 @@ export class Erc1155Wrapper {
const spender = delegatedSpender === undefined ? from : delegatedSpender;
const callbackDataHex = callbackData === undefined ? '0x' : callbackData;
const tx = await this._logDecoder.getTxWithDecodedLogsAsync(
await this._erc1155Contract.safeTransferFrom.sendTransactionAsync(from, to, token, value, callbackDataHex, {
await this._erc1155Contract.safeTransferFrom(from, to, token, value, callbackDataHex).sendTransactionAsync({
from: spender,
}),
);
@@ -56,14 +58,9 @@ export class Erc1155Wrapper {
const spender = delegatedSpender === undefined ? from : delegatedSpender;
const callbackDataHex = callbackData === undefined ? '0x' : callbackData;
const tx = await this._logDecoder.getTxWithDecodedLogsAsync(
await this._erc1155Contract.safeBatchTransferFrom.sendTransactionAsync(
from,
to,
tokens,
values,
callbackDataHex,
{ from: spender },
),
await this._erc1155Contract
.safeBatchTransferFrom(from, to, tokens, values, callbackDataHex)
.sendTransactionAsync({ from: spender }),
);
return tx;
}
@@ -74,7 +71,7 @@ export class Erc1155Wrapper {
const tokenUri = 'dummyFungibleToken';
const tokenIsNonFungible = false;
const tx = await this._logDecoder.getTxWithDecodedLogsAsync(
await this._erc1155Contract.create.sendTransactionAsync(tokenUri, tokenIsNonFungible, {
await this._erc1155Contract.create(tokenUri, tokenIsNonFungible).sendTransactionAsync({
from: this._contractOwner,
}),
);
@@ -95,31 +92,24 @@ export class Erc1155Wrapper {
tokenAmountsAsArray.push(tokenAmounts);
});
}
await this._erc1155Contract.mintFungible.awaitTransactionSuccessAsync(
tokenId,
beneficiaries,
tokenAmountsAsArray,
{ from: this._contractOwner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await this._erc1155Contract
.mintFungible(tokenId, beneficiaries, tokenAmountsAsArray)
.awaitTransactionSuccessAsync({ from: this._contractOwner });
}
public async mintNonFungibleTokensAsync(beneficiaries: string[]): Promise<[BigNumber, BigNumber[]]> {
const tokenUri = 'dummyNonFungibleToken';
const tokenIsNonFungible = true;
const tx = await this._logDecoder.getTxWithDecodedLogsAsync(
await this._erc1155Contract.create.sendTransactionAsync(tokenUri, tokenIsNonFungible, {
await this._erc1155Contract.create(tokenUri, tokenIsNonFungible).sendTransactionAsync({
from: this._contractOwner,
}),
);
// tslint:disable-next-line no-unnecessary-type-assertion
const createFungibleTokenLog = tx.logs[0] as LogWithDecodedArgs<ERC1155TransferSingleEventArgs>;
const token = createFungibleTokenLog.args.id;
await this._erc1155Contract.mintNonFungible.awaitTransactionSuccessAsync(
token,
beneficiaries,
{ from: this._contractOwner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await this._erc1155Contract.mintNonFungible(token, beneficiaries).awaitTransactionSuccessAsync({
from: this._contractOwner,
});
const encodedNftIds: BigNumber[] = [];
const nftIdBegin = 1;
const nftIdEnd = beneficiaries.length + 1;
@@ -136,14 +126,14 @@ export class Erc1155Wrapper {
isApproved: boolean,
): Promise<TransactionReceiptWithDecodedLogs> {
const tx = await this._logDecoder.getTxWithDecodedLogsAsync(
await this._erc1155Contract.setApprovalForAll.sendTransactionAsync(beneficiary, isApproved, {
await this._erc1155Contract.setApprovalForAll(beneficiary, isApproved).sendTransactionAsync({
from: owner,
}),
);
return tx;
}
public async isApprovedForAllAsync(owner: string, beneficiary: string): Promise<boolean> {
const isApprovedForAll = await this._erc1155Contract.isApprovedForAll.callAsync(owner, beneficiary);
const isApprovedForAll = await this._erc1155Contract.isApprovedForAll(owner, beneficiary).callAsync();
return isApprovedForAll;
}
public async assertBalancesAsync(
@@ -165,18 +155,18 @@ export class Erc1155Wrapper {
});
}
public async isNonFungibleItemAsync(tokenId: BigNumber): Promise<boolean> {
return this._erc1155Contract.isNonFungibleItem.callAsync(tokenId);
return this._erc1155Contract.isNonFungibleItem(tokenId).callAsync();
}
public async isFungibleItemAsync(tokenId: BigNumber): Promise<boolean> {
return !(await this.isNonFungibleItemAsync(tokenId));
}
public async getOwnerOfAsync(tokenId: BigNumber): Promise<string> {
return this._erc1155Contract.ownerOf.callAsync(tokenId);
return this._erc1155Contract.ownerOf(tokenId).callAsync();
}
/**
* @dev Get the balance of an ERC1155 token for a given owner and token ID.
*/
public async getBalanceAsync(ownerAddress: string, tokenId: BigNumber): Promise<BigNumber> {
return this._erc1155Contract.balanceOf.callAsync(ownerAddress, tokenId);
return this._erc1155Contract.balanceOf(ownerAddress, tokenId).callAsync();
}
}

View File

@@ -1,3 +1,45 @@
export * from './wrappers';
export * from './artifacts';
export { Erc1155Wrapper } from '../test/utils/erc1155_wrapper';
export {
DummyERC1155ReceiverContract,
ERC1155Contract,
ERC1155MintableContract,
IERC1155ReceiverContract,
DummyERC1155ReceiverBatchTokenReceivedEventArgs,
ERC1155TransferSingleEventArgs,
} from './wrappers';
export { artifacts } from './artifacts';
export { Erc1155Wrapper } from './erc1155_wrapper';
export {
Provider,
TransactionReceiptWithDecodedLogs,
JSONRPCRequestPayload,
JSONRPCResponsePayload,
JSONRPCResponseError,
JSONRPCErrorCallback,
TransactionReceiptStatus,
ContractArtifact,
ContractChains,
CompilerOpts,
StandardContractOutput,
CompilerSettings,
ContractChainData,
ContractAbi,
DevdocOutput,
EvmOutput,
CompilerSettingsMetadata,
OptimizerSettings,
OutputField,
ParamDescription,
EvmBytecodeOutput,
AbiDefinition,
FunctionAbi,
EventAbi,
RevertErrorAbi,
EventParameter,
DataItem,
MethodAbi,
ConstructorAbi,
FallbackAbi,
ConstructorStateMutability,
TupleDataItem,
StateMutability,
} from 'ethereum-types';

View File

@@ -6,7 +6,4 @@
export * from '../generated-wrappers/dummy_erc1155_receiver';
export * from '../generated-wrappers/erc1155';
export * from '../generated-wrappers/erc1155_mintable';
export * from '../generated-wrappers/i_erc1155_mintable';
export * from '../generated-wrappers/i_erc1155_receiver';
export * from '../generated-wrappers/ierc1155';
export * from '../generated-wrappers/mixin_non_fungible_token';

View File

@@ -0,0 +1,23 @@
/*
* -----------------------------------------------------------------------------
* Warning: This file is auto-generated by contracts-gen. Don't edit manually.
* -----------------------------------------------------------------------------
*/
import { ContractArtifact } from 'ethereum-types';
import * as DummyERC1155Receiver from '../test/generated-artifacts/DummyERC1155Receiver.json';
import * as ERC1155 from '../test/generated-artifacts/ERC1155.json';
import * as ERC1155Mintable from '../test/generated-artifacts/ERC1155Mintable.json';
import * as IERC1155 from '../test/generated-artifacts/IERC1155.json';
import * as IERC1155Mintable from '../test/generated-artifacts/IERC1155Mintable.json';
import * as IERC1155Receiver from '../test/generated-artifacts/IERC1155Receiver.json';
import * as MixinNonFungibleToken from '../test/generated-artifacts/MixinNonFungibleToken.json';
export const artifacts = {
ERC1155: ERC1155 as ContractArtifact,
ERC1155Mintable: ERC1155Mintable as ContractArtifact,
MixinNonFungibleToken: MixinNonFungibleToken as ContractArtifact,
IERC1155: IERC1155 as ContractArtifact,
IERC1155Mintable: IERC1155Mintable as ContractArtifact,
IERC1155Receiver: IERC1155Receiver as ContractArtifact,
DummyERC1155Receiver: DummyERC1155Receiver as ContractArtifact,
};

View File

@@ -6,21 +6,19 @@ import {
txDefaults,
web3Wrapper,
} from '@0x/contracts-test-utils';
import { SafeMathRevertErrors } from '@0x/contracts-utils';
import { BlockchainLifecycle } from '@0x/dev-utils';
import { RevertReason } from '@0x/types';
import { BigNumber, SafeMathRevertErrors } from '@0x/utils';
import { BigNumber } from '@0x/utils';
import * as chai from 'chai';
import { LogWithDecodedArgs } from 'ethereum-types';
import * as _ from 'lodash';
import {
artifacts,
DummyERC1155ReceiverBatchTokenReceivedEventArgs,
DummyERC1155ReceiverContract,
ERC1155MintableContract,
} from '../src';
import { Erc1155Wrapper } from '../src/erc1155_wrapper';
import { ERC1155MintableContract } from '../src/wrappers';
import { Erc1155Wrapper } from './utils/erc1155_wrapper';
import { artifacts } from './artifacts';
import { DummyERC1155ReceiverBatchTokenReceivedEventArgs, DummyERC1155ReceiverContract } from './wrappers';
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
@@ -179,14 +177,9 @@ describe('ERC1155Token', () => {
valueToTransfer,
);
// execute transfer
const tx = erc1155Contract.safeTransferFrom.sendTransactionAsync(
spender,
receiver,
tokenToTransfer,
valueToTransfer,
receiverCallbackData,
{ from: spender },
);
const tx = erc1155Contract
.safeTransferFrom(spender, receiver, tokenToTransfer, valueToTransfer, receiverCallbackData)
.sendTransactionAsync({ from: spender });
return expect(tx).to.revertWith(expectedError);
});
it('should revert if callback reverts', async () => {
@@ -196,19 +189,14 @@ describe('ERC1155Token', () => {
// set receiver to reject balances
const shouldRejectTransfer = true;
await web3Wrapper.awaitTransactionSuccessAsync(
await erc1155Receiver.setRejectTransferFlag.sendTransactionAsync(shouldRejectTransfer),
await erc1155Receiver.setRejectTransferFlag(shouldRejectTransfer).sendTransactionAsync(),
constants.AWAIT_TRANSACTION_MINED_MS,
);
// execute transfer
await expectTransactionFailedAsync(
erc1155Contract.safeTransferFrom.sendTransactionAsync(
spender,
receiver,
tokenToTransfer,
valueToTransfer,
receiverCallbackData,
{ from: spender },
),
erc1155Contract
.safeTransferFrom(spender, receiver, tokenToTransfer, valueToTransfer, receiverCallbackData)
.sendTransactionAsync({ from: spender }),
RevertReason.TransferRejected,
);
});
@@ -355,14 +343,9 @@ describe('ERC1155Token', () => {
valuesToTransfer[0],
);
// execute transfer
const tx = erc1155Contract.safeBatchTransferFrom.sendTransactionAsync(
spender,
receiver,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
{ from: spender },
);
const tx = erc1155Contract
.safeBatchTransferFrom(spender, receiver, tokensToTransfer, valuesToTransfer, receiverCallbackData)
.sendTransactionAsync({ from: spender });
return expect(tx).to.revertWith(expectedError);
});
it('should revert if callback reverts', async () => {
@@ -372,19 +355,14 @@ describe('ERC1155Token', () => {
// set receiver to reject balances
const shouldRejectTransfer = true;
await web3Wrapper.awaitTransactionSuccessAsync(
await erc1155Receiver.setRejectTransferFlag.sendTransactionAsync(shouldRejectTransfer),
await erc1155Receiver.setRejectTransferFlag(shouldRejectTransfer).sendTransactionAsync(),
constants.AWAIT_TRANSACTION_MINED_MS,
);
// execute transfer
await expectTransactionFailedAsync(
erc1155Contract.safeBatchTransferFrom.sendTransactionAsync(
spender,
receiver,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
{ from: spender },
),
erc1155Contract
.safeBatchTransferFrom(spender, receiver, tokensToTransfer, valuesToTransfer, receiverCallbackData)
.sendTransactionAsync({ from: spender }),
RevertReason.TransferRejected,
);
});
@@ -432,14 +410,9 @@ describe('ERC1155Token', () => {
await erc1155Wrapper.assertBalancesAsync(tokenHolders, [tokenToTransfer], expectedInitialBalances);
// execute transfer
await expectTransactionFailedAsync(
erc1155Contract.safeTransferFrom.sendTransactionAsync(
spender,
receiver,
tokenToTransfer,
valueToTransfer,
receiverCallbackData,
{ from: delegatedSpender },
),
erc1155Contract
.safeTransferFrom(spender, receiver, tokenToTransfer, valueToTransfer, receiverCallbackData)
.sendTransactionAsync({ from: delegatedSpender }),
RevertReason.InsufficientAllowance,
);
});
@@ -485,14 +458,9 @@ describe('ERC1155Token', () => {
await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedInitialBalances);
// execute transfer
await expectTransactionFailedAsync(
erc1155Contract.safeBatchTransferFrom.sendTransactionAsync(
spender,
receiver,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
{ from: delegatedSpender },
),
erc1155Contract
.safeBatchTransferFrom(spender, receiver, tokensToTransfer, valuesToTransfer, receiverCallbackData)
.sendTransactionAsync({ from: delegatedSpender }),
RevertReason.InsufficientAllowance,
);
});

View File

@@ -0,0 +1,12 @@
/*
* -----------------------------------------------------------------------------
* Warning: This file is auto-generated by contracts-gen. Don't edit manually.
* -----------------------------------------------------------------------------
*/
export * from '../test/generated-wrappers/dummy_erc1155_receiver';
export * from '../test/generated-wrappers/erc1155';
export * from '../test/generated-wrappers/erc1155_mintable';
export * from '../test/generated-wrappers/i_erc1155_mintable';
export * from '../test/generated-wrappers/i_erc1155_receiver';
export * from '../test/generated-wrappers/ierc1155';
export * from '../test/generated-wrappers/mixin_non_fungible_token';

Some files were not shown because too many files have changed in this diff Show More