Compare commits

...

651 Commits

Author SHA1 Message Date
Leonid Logvinov
ff334b0e53 Update CHANGELOG 2017-11-28 14:42:55 -06:00
Leonid
a98d6bf496 Merge pull request #235 from 0xProject/feature/gasPriceGasLimit
Add optional config for gasPrice and gasLimit for every transaction sending method
2017-11-28 14:37:33 -06:00
Leonid
bbcf669bd9 Merge pull request #242 from 0xProject/feature/orderWatcherCleanup
Add a cleanup job to an order watcher
2017-11-28 14:37:15 -06:00
Leonid Logvinov
328ecd0533 Change interval to 1h 2017-11-28 14:33:08 -06:00
Leonid Logvinov
ab91717199 Rename 2017-11-28 14:27:39 -06:00
Leonid Logvinov
e4dfdc6b5c Add ifExists to cleanupJobInterval 2017-11-28 14:27:16 -06:00
Leonid Logvinov
9e673f0073 Add a cleanup job to an order watcher 2017-11-28 14:11:00 -06:00
Leonid Logvinov
353abffba9 Improve the comment 2017-11-28 12:23:41 -06:00
Leonid Logvinov
bead76a5b7 Add CHANGELOG comment 2017-11-28 12:16:02 -06:00
Leonid Logvinov
9f5e724aec Add a HACK comment 2017-11-28 12:13:50 -06:00
Leonid Logvinov
50bf6a991d Normalise subprovider names 2017-11-28 12:12:25 -06:00
Leonid Logvinov
1d584b1329 Remove a comment 2017-11-28 12:10:06 -06:00
Leonid Logvinov
0c5a9fbc2c Fix a typo 2017-11-28 12:06:11 -06:00
Leonid Logvinov
d5e58ecdd8 Pin testrpc version 2017-11-28 12:05:32 -06:00
Leonid Logvinov
d6a9e7520d Remove gas params from tests 2017-11-28 11:51:10 -06:00
Leonid Logvinov
36b21e6e7b Add fake gas estimate suprovider for tests 2017-11-28 11:44:10 -06:00
Leonid Logvinov
977a6b2794 Revert "Fix website linter errors"
This reverts commit 6e2a69976b.
2017-11-28 11:43:42 -06:00
Fabio Berger
78f0ab3682 Last remaining website fixes 2017-11-27 22:23:51 -06:00
Fabio Berger
5a59ac4c6b fix remaining tslint errors 2017-11-27 22:08:08 -06:00
Fabio Berger
0a19ba3014 Fix tslint issues 2017-11-27 21:38:09 -06:00
Fabio Berger
88bd0f5328 Add lint command to website sub-package 2017-11-27 19:58:53 -06:00
Leonid Logvinov
6e2a69976b Fix website linter errors 2017-11-27 18:06:15 -06:00
Leonid Logvinov
0500602ac3 Fix tests 2017-11-27 17:38:38 -06:00
Leonid Logvinov
e6887dc9d4 Fix a comment 2017-11-27 17:37:55 -06:00
Leonid Logvinov
082c5c375e Fix tests 2017-11-27 17:37:55 -06:00
Leonid Logvinov
5977fa881e Increase gas margin 2017-11-27 17:37:23 -06:00
Leonid Logvinov
128fccb763 Fix defaults for shouldValidate 2017-11-27 17:37:23 -06:00
Leonid Logvinov
65697f5896 Update MAX_REASONABLE_GAS_COST_IN_WEI 2017-11-27 17:37:23 -06:00
Leonid Logvinov
ee93f091ea Add gas margin and remove undefined values 2017-11-27 17:37:22 -06:00
Leonid Logvinov
33a8c7a9fb Update testrpc 2017-11-27 17:37:22 -06:00
Leonid Logvinov
d1065cd266 Add an initializer for txOpts in etherToken 2017-11-27 17:36:27 -06:00
Leonid Logvinov
0e44a630f0 Add CHANGELOG entry 2017-11-27 17:36:27 -06:00
Leonid Logvinov
7a21c6854b Add option config for gasPrice and gasLimit for every transaction sending method 2017-11-27 17:35:55 -06:00
Fabio Berger
54ef916b93 Merge pull request #233 from 0xProject/feature/passNetworkId
Forces the users of 0x.js to pass the network id
2017-11-27 17:15:18 -06:00
Brandon Millman
4a770dee84 Merge pull request #241 from 0xProject/fix/moveConnectTypes
Move all connect types into types.ts
2017-11-27 14:42:26 -08:00
Brandon Millman
426a412ba1 Move all connect types into types.ts 2017-11-27 14:34:34 -08:00
Leonid Logvinov
f862a2af6d Fix tests 2017-11-27 16:32:33 -06:00
Leonid Logvinov
32867c9a07 Fix merge conflicts 2017-11-27 16:03:57 -06:00
Leonid
cf0a8b2d05 Merge branch 'development' into feature/passNetworkId 2017-11-27 15:53:21 -06:00
Brandon Millman
4a17f5e820 Merge pull request #240 from 0xProject/fix/websiteMdDirectory
Add md directory to website package and change generated docs directory
2017-11-27 13:02:08 -08:00
Fabio Berger
694c37150c Merge pull request #239 from 0xProject/fix/docs
Fix 0x.js Doc Issues
2017-11-27 14:44:32 -06:00
Brandon Millman
b04d07815f Add md directory to website package and change generated docs directory 2017-11-27 12:12:19 -08:00
Fabio Berger
e7b523074a remove comment 2017-11-27 12:24:11 -06:00
Fabio Berger
4e03155588 Add link to Provider explanation 2017-11-27 12:06:03 -06:00
Fabio Berger
3e5abc60d3 Add "Web3" prefix to web3 alias types and link to the correct line in the web3 typings 2017-11-27 12:05:39 -06:00
Fabio Berger
edf80aba1a Fix overlapping arg names 2017-11-27 10:56:33 -06:00
Fabio Berger
25ec4cf7b0 Fix source links in 0x.js docs 2017-11-27 10:25:53 -06:00
Fabio Berger
48b3d85265 Merge pull request #237 from 0xProject/addWebsite
Add Website to Mono Repo
2017-11-27 10:05:47 -06:00
Fabio Berger
ecfee00fec Fix subscriptions given latest changes to 0x.js 2017-11-23 18:21:48 -06:00
Fabio Berger
b5ce876327 Update CHANGELOG.md 2017-11-23 17:35:53 -06:00
Fabio Berger
d1342c6326 Merge branch 'development' into addWebsite
* development: (41 commits)
  Add validation fix to changelog
  Fix tests now that we no longer fire duplicate orderWatcher events
  Add comment about BlockParamLiteral explaining the omission of Earliest
  Add missing type
  Pass 'latest' to ExchangeTransferSimulator when used for validating orders, and pass 'pending' when used in the order watcher.
  Remove `Earliest` from blockParamLiterals since specifying block 0 is trivial and this type can be reused in situations where the options are pending or latest
  Rename removed to isRemoved
  Add CHANGELOG entry
  Make DecodedLogEvent contain web3 log under a log subkey
  Update to Async call
  Fix nits
  Add @0xproject/connect to the main README
  Fix connect CHANGELOG version
  Publish
  Fix npm auth issues
  Perform the division last to not compound any errors
  add a test constant for ZRX decimals
  Add a test for when the ratio is < 1
  Remove only
  calculatedFillableAmountPlusFees
  ...
2017-11-23 17:08:20 -06:00
Fabio Berger
d3dcb2fd40 Add validation fix to changelog 2017-11-23 17:05:12 -06:00
Fabio Berger
c448d048fd Merge pull request #236 from 0xProject/fix/validateOrdersAgainstLatestBlock
Fix/validate orders against latest block
2017-11-23 17:02:57 -06:00
Fabio Berger
f0b3ee84b4 Fix tests now that we no longer fire duplicate orderWatcher events 2017-11-23 15:56:42 -06:00
Fabio Berger
ab78c54d6a Add comment about BlockParamLiteral explaining the omission of Earliest 2017-11-23 15:36:46 -06:00
Fabio Berger
cee0d2706f Add missing type 2017-11-23 15:32:00 -06:00
Fabio Berger
8dea47f038 Merge branch 'development' into validateOrdersAgainstLatestBlock
* development:
  Rename removed to isRemoved
  Add CHANGELOG entry
  Make DecodedLogEvent contain web3 log under a log subkey
2017-11-23 15:24:32 -06:00
Fabio Berger
b7b1721145 Pass 'latest' to ExchangeTransferSimulator when used for validating orders, and pass 'pending' when used in the order watcher. 2017-11-23 15:21:45 -06:00
Fabio Berger
5068f1666a Remove Earliest from blockParamLiterals since specifying block 0 is trivial and this type can be reused in situations where the options are pending or latest 2017-11-23 15:20:20 -06:00
Leonid Logvinov
37f0051d83 Update CHANGELOG.md 2017-11-23 15:16:04 -06:00
Leonid Logvinov
c780d04cee Remove ContractDoesNotExist error and replace it with more specific errors 2017-11-23 15:15:47 -06:00
Leonid Logvinov
8c54e9a873 Add a regression test 2017-11-23 15:15:47 -06:00
Leonid Logvinov
062f85e506 Pass networkId on provider update 2017-11-23 15:15:47 -06:00
Leonid Logvinov
b3c0d54acd Fix linter issue 2017-11-23 15:15:47 -06:00
Leonid Logvinov
3d11afd872 Remove outdated comment 2017-11-23 15:15:47 -06:00
Leonid Logvinov
96d15a8931 Improve a comment 2017-11-23 15:15:47 -06:00
Leonid Logvinov
50915e6007 Add a comment 2017-11-23 15:15:47 -06:00
Leonid Logvinov
52007e5864 Reuse the protected function to get contract address 2017-11-23 15:15:47 -06:00
Leonid Logvinov
0c74d5ba01 Move variable declaration inside the if 2017-11-23 15:15:47 -06:00
Leonid Logvinov
0cd1959706 Update CHANGELOG.md 2017-11-23 15:15:17 -06:00
Leonid Logvinov
55ddf62df2 Fix rebasing issues 2017-11-23 15:15:17 -06:00
Leonid Logvinov
7f69d26247 Add CHANGELOG entry 2017-11-23 15:15:17 -06:00
Leonid Logvinov
b3c01f6750 Revert "Remove redundant async"
This reverts commit 8d11ababd62d947e338757f57c41179510b11338.
2017-11-23 15:15:00 -06:00
Leonid Logvinov
34beee1edc Refactor getContractAddress to contractWrapper 2017-11-23 15:15:00 -06:00
Leonid Logvinov
7bc6a7b23f Remove redundant async 2017-11-23 15:13:38 -06:00
Leonid Logvinov
4a19655fb0 Fix the artifacts 2017-11-23 15:13:38 -06:00
Leonid Logvinov
e32c453bc3 Remove unused asyncs 2017-11-23 15:13:38 -06:00
Leonid Logvinov
7b8d9193e2 Auto-fix linter errors in other mono-repo packages 2017-11-23 15:13:37 -06:00
Leonid Logvinov
74633126ce Add type information for the linter 2017-11-23 15:13:37 -06:00
Leonid Logvinov
2fa5bb2028 Autofix json-schemas linter errors 2017-11-23 15:13:37 -06:00
Leonid Logvinov
010e6f8d7f Fix the imports order 2017-11-23 15:13:37 -06:00
Leonid Logvinov
3d5b6ec110 Enforce comments on public methods 2017-11-23 15:13:37 -06:00
Leonid Logvinov
db2917b01c Enable some new linter rules and fix the issues 2017-11-23 15:13:37 -06:00
Leonid Logvinov
87d34f9c7f Auto-fix linter errors 2017-11-23 15:13:37 -06:00
Leonid Logvinov
d20926e150 Don't reassign the parameter 2017-11-23 15:13:37 -06:00
Leonid Logvinov
c453099f6b Fix linter issues 2017-11-23 15:13:37 -06:00
Leonid Logvinov
08569dbe6c Await block reconcilation 2017-11-23 15:13:37 -06:00
Leonid Logvinov
a38ef3655b Remove even more asyncs 2017-11-23 15:13:37 -06:00
Leonid Logvinov
c586d3e81d Add project config to tslint which enables some type-dependent rules 2017-11-23 15:13:37 -06:00
Leonid Logvinov
c72745b0b2 Make zeroEx.tokenRegistry.getContractAddress non-async 2017-11-23 15:13:37 -06:00
Leonid Logvinov
8935146240 Make exchange subscriptions non-async 2017-11-23 15:13:37 -06:00
Leonid Logvinov
66aaceea91 Cleanup order watcher from redundant asyncs 2017-11-23 15:13:36 -06:00
Leonid Logvinov
4fe28ec53c Make zeroEx.exchange.getContractAddress non-async 2017-11-23 15:13:36 -06:00
Leonid Logvinov
efe8e07854 Add ZRX artifacts 2017-11-23 15:13:36 -06:00
Leonid Logvinov
63dc606a9c Make getZRXTokenAddress non async 2017-11-23 15:13:36 -06:00
Leonid Logvinov
131236305b Store networkId in web3Wrapper 2017-11-23 15:13:36 -06:00
Leonid Logvinov
45c9171a2c Add networkId to zeroExConfig schema 2017-11-23 15:13:36 -06:00
Leonid Logvinov
311d42626a Adjust the tests 2017-11-23 15:13:36 -06:00
Leonid Logvinov
cbf35de4c1 Fix CI tests 2017-11-23 15:13:36 -06:00
Leonid Logvinov
92efc65847 Add networkId to ZeroExConfig and make it required 2017-11-23 15:13:36 -06:00
Leonid
17e41f2391 Merge pull request #234 from 0xProject/feature/eventTypes
Make DecodedLogEvent contain web3 log under a log subkey
2017-11-23 15:13:07 -06:00
Leonid Logvinov
fcd37808d4 Rename removed to isRemoved 2017-11-23 15:12:34 -06:00
Leonid Logvinov
6323badc19 Add CHANGELOG entry 2017-11-23 15:12:34 -06:00
Leonid Logvinov
e01468b492 Make DecodedLogEvent contain web3 log under a log subkey 2017-11-23 15:12:34 -06:00
Fabio Berger
f7f2390ce1 Add exit code 0 because it is expected that uglifying the code throws an error 2017-11-23 14:01:23 -06:00
Fabio Berger
6118561bb5 update tokenByAddress after tokenStateByAddress to avoid race-condition 2017-11-23 13:58:27 -06:00
Fabio Berger
6a9f10cd36 Add error when unexpected condition hit 2017-11-23 13:57:01 -06:00
Fabio Berger
e7a4e03194 Fix alignment 2017-11-23 13:56:42 -06:00
Fabio Berger
a42e8ae873 Add missing keys 2017-11-23 13:56:34 -06:00
Fabio Berger
bcc5d63516 Fix bug 2017-11-23 13:56:16 -06:00
Fabio Berger
f97074dc84 Merge pull request #230 from 0xProject/feature/removeDuplicateEvents
Add an order state cache to filter out duplicate events
2017-11-23 12:35:18 -06:00
Fabio Berger
bd81124b5a Merge pull request #226 from dekz/feature/calculate-remaining-proportions
Calculate remaining proportions from fee to ratio proportions
2017-11-23 12:33:06 -06:00
Jacob Evans
5a18f43b51 Update to Async call 2017-11-23 15:17:11 +11:00
Jacob Evans
924b96ce2a Fix nits 2017-11-23 15:14:33 +11:00
Jacob Evans
47236dbaec Merge branch 'development' into feature/calculate-remaining-proportions 2017-11-23 14:38:10 +11:00
Jacob Evans
437ac301db Merge branch 'development' into feature/calculate-remaining-proportions 2017-11-23 14:37:34 +11:00
Brandon Millman
215740fab2 Add @0xproject/connect to the main README 2017-11-22 15:39:05 -08:00
Fabio Berger
c66fc63452 Merge branch 'development' into addWebsite
* development:
  Revert "Publish"
  Publish
  Add actual version to CHANGELOG
  Add blockchainLifecycle management to the ExpirationWatcher test
  Update connect CHANGELOG.md in preperation for publishing
  Add TODO comment before BigNumber.config() call
  Prepare connect package for publishing
2017-11-22 17:26:48 -06:00
Brandon Millman
02aefc40f3 Fix connect CHANGELOG version 2017-11-22 15:10:50 -08:00
Brandon Millman
cd42ca1bbd Publish
- 0x.js@0.26.1
     - @0xproject/connect@0.1.0
2017-11-22 15:07:34 -08:00
Brandon Millman
05bfd764b6 Fix npm auth issues
Related lerna issue: https://github.com/lerna/lerna/issues/896
2017-11-22 15:05:03 -08:00
Fabio Berger
99f2026ce2 Revert "Publish"
This reverts commit 6a8717b294.
2017-11-22 16:51:09 -06:00
Fabio Berger
6a8717b294 Publish
- 0x.js@0.26.1
 - @0xproject/connect@0.1.0
2017-11-22 16:50:16 -06:00
Fabio Berger
c3f24a9cea Add actual version to CHANGELOG 2017-11-22 16:47:24 -06:00
Fabio Berger
805a055946 Force the clearance of tradeHistory 2017-11-22 16:43:17 -06:00
Brandon Millman
c0e17f6136 Add blockchainLifecycle management to the ExpirationWatcher test 2017-11-22 14:20:45 -08:00
Brandon Millman
b38142ddb1 Update connect CHANGELOG.md in preperation for publishing 2017-11-22 13:54:07 -08:00
Brandon Millman
0b29514836 Merge pull request #232 from 0xProject/feature/prepareConnectForPublish
Prepare connect package for publishing
2017-11-22 13:31:16 -08:00
Brandon Millman
27ce87f652 Add TODO comment before BigNumber.config() call 2017-11-22 13:26:15 -08:00
Brandon Millman
a61a7b688a Prepare connect package for publishing 2017-11-22 13:12:17 -08:00
Fabio Berger
f74408f390 Merge branch 'development' into addWebsite
* development: (33 commits)
  Last renames
  Refactor while condition
  Fix tests
  Fix tests
  Fix a typo
  Fix test:circleci command
  Check if transactionReceipt exists before normalizing it
  Address nits
  Remove old comment
  Fix async callbacks
  Check if callback exists
  Rename
  Pass callback down
  Remove custom heap and use bintrees
  Add expirationMarginMs
  Add defaults
  Fix typos
  Rename orderLifetime to orderLifetimeS
  Reference types directly
  Add ifExists suffix
  ...
2017-11-22 14:22:22 -06:00
Fabio Berger
f5e0fd8de5 Upgrade to latest 0x.js version and refactor subscriptions to use latest interface 2017-11-22 14:21:07 -06:00
Fabio Berger
353b6f3d6d add bundles to gitignore 2017-11-22 14:20:35 -06:00
Fabio Berger
cb377f29c2 Fix build bug 2017-11-22 14:20:24 -06:00
Leonid
0e03ef385b Merge pull request #227 from 0xProject/feature/orderExpired
Add expirationWatcher
2017-11-22 12:02:31 -06:00
Leonid Logvinov
ac2c723ec9 Last renames 2017-11-22 11:56:34 -06:00
Leonid Logvinov
3fc0eae4c0 Refactor while condition 2017-11-22 11:44:34 -06:00
Leonid
beed223281 Merge branch 'development' into feature/orderExpired 2017-11-22 11:24:59 -06:00
Jacob Evans
9c9ce97525 Perform the division last to not compound any errors 2017-11-22 11:08:39 +11:00
Jacob Evans
4bfb1fcc71 add a test constant for ZRX decimals 2017-11-22 10:54:09 +11:00
Jacob Evans
15628a1206 Add a test for when the ratio is < 1 2017-11-22 10:43:38 +11:00
Jacob Evans
a1411e3d52 Remove only 2017-11-22 08:05:47 +11:00
Leonid Logvinov
66750f7349 Fix tests 2017-11-21 14:03:32 -06:00
Fabio Berger
f7f1397e52 Merge branch 'development' into addWebsite
* development:
  Fix a typo in  postpublish utils tags -> tag
  Publish
  Revert "Publish"
  Publish
  Add instanceOf assertion
  Rename toDecimal to hexToDecimal
  Add PR numbers
  Add postFormatter for logs
2017-11-21 14:03:26 -06:00
Fabio Berger
3660ba28d7 Add website to mono repo, update packages to align with existing sub-packages, use new subscribeAsync 0x.js method 2017-11-21 14:03:08 -06:00
Leonid Logvinov
e3cc283478 Fix a typo in postpublish utils tags -> tag 2017-11-21 13:43:39 -06:00
Leonid Logvinov
9a2735d035 Publish
- 0x.js@0.26.0
 - @0xproject/assert@0.0.5
 - @0xproject/connect@0.0.1
 - @0xproject/json-schemas@0.6.8
 - @0xproject/tslint-config@0.1.1
2017-11-21 13:34:33 -06:00
Leonid Logvinov
06cd2f1eb3 Revert "Publish"
This reverts commit 41315827c1.
2017-11-21 13:31:47 -06:00
Leonid Logvinov
41315827c1 Publish
- 0x.js@0.26.0
 - @0xproject/assert@0.0.5
 - @0xproject/connect@0.0.1
 - @0xproject/json-schemas@0.6.8
 - @0xproject/tslint-config@0.1.1
2017-11-21 13:27:42 -06:00
Leonid
415fd101d3 Merge pull request #231 from 0xProject/fix/logsPostFormatting
Add postFormatter for logs
2017-11-21 13:24:47 -06:00
Leonid Logvinov
0747e162fa Add instanceOf assertion 2017-11-21 13:18:29 -06:00
Leonid Logvinov
8d6ba6ee7a Rename toDecimal to hexToDecimal 2017-11-21 13:16:55 -06:00
Leonid Logvinov
173a707a2e Add PR numbers 2017-11-21 13:15:05 -06:00
Leonid Logvinov
c8c95b4bd2 Add postFormatter for logs 2017-11-21 13:09:23 -06:00
Leonid Logvinov
351b7557b6 Fix tests 2017-11-21 12:21:49 -06:00
Leonid Logvinov
4dc1962f9e Fix a typo 2017-11-21 11:59:34 -06:00
Jacob Evans
335b9629b8 calculatedFillableAmountPlusFees 2017-11-21 15:00:09 +11:00
Jacob Evans
d16f0508bd totalZRXTransferAmount -> totalZRXTransferAmountRequired 2017-11-21 14:57:08 +11:00
Jacob Evans
da03331015 Unit test edge case for ZRX and ZRX partial fill 2017-11-21 14:51:19 +11:00
Jacob Evans
43128234bb setting a failed test 2017-11-21 14:00:21 +11:00
Jacob Evans
bbcee8dfa7 Move to base units 2017-11-21 13:04:36 +11:00
Jacob Evans
5b8f84f59a Added unit test for calculator 2017-11-21 12:58:17 +11:00
Leonid Logvinov
cfcbf34305 Fix test:circleci command 2017-11-20 17:46:53 -06:00
Jacob Evans
4bd5789203 Refactor into a calculator class 2017-11-21 10:30:29 +11:00
Leonid Logvinov
c4669013ab Check if transactionReceipt exists before normalizing it 2017-11-20 17:24:30 -06:00
Leonid Logvinov
3ad6020e19 Address nits 2017-11-20 16:55:53 -06:00
Leonid Logvinov
3fc8645d92 Remove old comment 2017-11-20 16:52:53 -06:00
Jacob Evans
fb812d59b0 Fixes before refactor 2017-11-21 09:50:37 +11:00
Leonid Logvinov
3e0371685f Fix async callbacks 2017-11-20 16:39:34 -06:00
Leonid Logvinov
3bc3666215 Check if callback exists 2017-11-20 16:25:51 -06:00
Leonid Logvinov
b01a4af99e Rename 2017-11-20 16:17:23 -06:00
Leonid Logvinov
9745d5348c Pass callback down 2017-11-20 16:14:40 -06:00
Leonid Logvinov
c858ff61f7 Add an order state cache to filter out duplicate events 2017-11-20 16:07:16 -06:00
Leonid
d39c0bee39 Merge branch 'development' into feature/orderExpired 2017-11-20 14:46:53 -06:00
Leonid Logvinov
5788b90c52 Remove custom heap and use bintrees 2017-11-20 14:40:53 -06:00
Fabio Berger
037f466e1f Merge pull request #225 from dekz/feature/track-zrx-movements
Track ZRX Approval and Balance events
2017-11-20 13:54:07 -06:00
Leonid Logvinov
71475d3cea Add expirationMarginMs 2017-11-20 13:47:09 -06:00
Leonid Logvinov
a613c3b7e7 Add defaults 2017-11-20 13:02:24 -06:00
Leonid Logvinov
35668fe225 Fix typos 2017-11-20 12:54:22 -06:00
Leonid Logvinov
83a2abeee4 Rename orderLifetime to orderLifetimeS 2017-11-20 12:53:49 -06:00
Leonid Logvinov
49d926013c Reference types directly 2017-11-20 12:53:16 -06:00
Leonid Logvinov
c068ec5231 Add ifExists suffix 2017-11-20 12:49:55 -06:00
Leonid Logvinov
86d19657b1 Improve the comment 2017-11-20 11:17:53 -06:00
Leonid Logvinov
67ad07020d Remove comment 2017-11-20 11:16:40 -06:00
Leonid Logvinov
fa2c4160b5 Remove new line 2017-11-20 11:15:48 -06:00
Leonid Logvinov
a37f019806 Delete orderExpirationCheckingIntervalIdIfExists 2017-11-20 11:15:01 -06:00
Leonid Logvinov
20449a0cb2 Throw when subscription is already removed 2017-11-20 11:13:54 -06:00
Leonid Logvinov
856a5c3369 Throw when subscription is already present 2017-11-20 11:10:25 -06:00
Leonid Logvinov
2c193a1244 Remove redundant bind 2017-11-20 11:06:32 -06:00
Leonid Logvinov
c4d10a6f2d Do simple inits inline 2017-11-20 11:05:37 -06:00
Jacob Evans
d6589004c7 fix bug when fees and partial asymmetric 2017-11-20 11:10:50 +11:00
Jacob Evans
519f1318c6 remove import 2017-11-20 11:02:16 +11:00
Jacob Evans
7460a36ce2 calculate remaining maker token amount 2017-11-20 10:55:28 +11:00
Jacob Evans
c8f6e3f923 Remove only 2017-11-20 10:45:40 +11:00
Jacob Evans
7b373e29ea Split into Pooled and non-pooled 2017-11-20 10:45:01 +11:00
Jacob Evans
94ce7a54c3 Incorrect amount when is zero or non-zrx fee 2017-11-20 09:20:37 +11:00
Jacob Evans
3bb6d8871b Readability variable names 2017-11-20 09:04:26 +11:00
Fabio Berger
98394c6e37 Merge pull request #228 from 0xProject/feature/publishLifecycleScripts
Add postpublish scripts for sub-packages
2017-11-17 19:30:51 -05:00
Leonid Logvinov
e755ed927c Remove order on expiration 2017-11-17 17:25:58 -06:00
Fabio Berger
37a9b64503 Small fixes 2017-11-17 17:00:15 -06:00
Fabio Berger
0de00da753 Merge branch 'development' into feature/publishLifecycleScripts
* development:
  Remove clean step from test_umd.sh
  Update CHANGELOG.md
  vx.x.x
  Add CHANGELOG files to each sub-package
  Fix 0x.js CHANGELOG
  separate assignment and call
  Remove Async subscribe callbacks from OrderWatcher
  Update changelog
  Callback for subscribe no longer supports an Async Callback
2017-11-17 16:54:57 -06:00
Fabio Berger
a4ae3c1e14 Updated yarn.lock 2017-11-17 16:50:14 -06:00
Fabio Berger
7f595169c1 Put release name generation into postpublish_utils 2017-11-17 16:44:56 -06:00
Fabio Berger
abee7d25a4 Add back promisify 2017-11-17 16:43:15 -06:00
Fabio Berger
49ba456189 Set S3 bucket path to variable 2017-11-17 14:49:46 -06:00
Fabio Berger
6a83687f45 reset all sub-package versions to latest actually published 2017-11-17 14:44:44 -06:00
Fabio Berger
70f4453e3e Get package name from package.json 2017-11-17 14:33:43 -06:00
Fabio Berger
cd0f6716e8 remove unused imports 2017-11-17 14:33:28 -06:00
Brandon Millman
5042b85d21 Remove clean step from test_umd.sh 2017-11-17 12:32:58 -08:00
Fabio Berger
5015f2d7d7 Add postpublish scripts for all the subpackages so that they each publish a release to github 2017-11-17 14:10:18 -06:00
Fabio Berger
5277d4a266 Move most of code for getting latest tag/version and calling publish_release to postpublish_utils script in top-level dir 2017-11-17 14:09:48 -06:00
Fabio Berger
f25b2d9ab9 Set prerelease to true so that non of the releases are marked as "latest" 2017-11-17 13:19:33 -06:00
Fabio Berger
0402d3de80 Move upload_docs_json back to npm script and pass in vars properly. 2017-11-17 13:19:12 -06:00
Leonid Logvinov
d3e03744cd Improve the comment 2017-11-17 13:06:10 -06:00
Leonid Logvinov
34926eb66a Add tests for expirationWatcher 2017-11-17 13:02:37 -06:00
Leonid Logvinov
b7585318c7 Fix heap implementation 2017-11-17 13:02:17 -06:00
Fabio Berger
e70c3976db Use yarn docs:json command 2017-11-17 13:30:26 -05:00
Fabio Berger
2c055db0d7 update yarn.lock 2017-11-17 13:24:49 -05:00
Fabio Berger
50dc1d3db3 specify the current working directory in which to run the yarn command 2017-11-17 13:24:36 -05:00
Fabio Berger
2e368b50eb print out file name in console 2017-11-17 13:24:15 -05:00
Fabio Berger
7b61ad639b small fixes 2017-11-17 12:23:27 -05:00
Fabio Berger
741774c4a7 Update CHANGELOG.md 2017-11-17 12:13:40 -05:00
Jacob Evans
33c1259fa2 Merge branch 'development' into feature/track-zrx-movements 2017-11-15 19:31:45 -05:00
Jacob Evans
9ee04fb14c Merge branch 'development' into feature/track-zrx-movements 2017-11-15 19:31:08 -05:00
Jacob Evans
e9a5ae21e0 Fix nits 2017-11-15 19:30:18 -05:00
Jacob Evans
0bcf7e56c2 Change to Async suffix convention 2017-11-15 19:10:44 -05:00
Fabio Berger
141f185c72 Merge pull request #222 from dekz/syncSubscribe
Remove support for Async callback types when used in Subscribe functions
2017-11-15 18:57:17 -05:00
Jacob Evans
e1b2c64654 Merge branch 'development' into syncSubscribe 2017-11-15 18:25:41 -05:00
Jacob Evans
d7e5c6f9b5 Merge branch 'development' into syncSubscribe 2017-11-15 18:25:09 -05:00
Brandon Millman
1e5cc3b0e5 experiment with calling typedoc programatically 2017-11-15 18:17:41 -05:00
Jacob Evans
85c3b2996d vx.x.x 2017-11-15 16:48:30 -05:00
Fabio Berger
9a57f71ee6 improve script 2017-11-15 16:47:35 -05:00
Jacob Evans
cf7727debc refactor up 2017-11-15 16:37:02 -05:00
Jacob Evans
9133e764a5 Use 18 decimal place units 2017-11-15 16:22:35 -05:00
Jacob Evans
c32938fa43 Shortcut if everything satisfies in the non dependent use case 2017-11-15 16:20:39 -05:00
Fabio Berger
827c245777 postpublish script fixes 2017-11-15 16:19:33 -05:00
Leonid Logvinov
88d020f9f2 Add initial implementation of expiration watcher 2017-11-15 14:54:56 -06:00
Jacob Evans
54c891a447 Fix test 2017-11-15 15:52:23 -05:00
Brandon Millman
6096fe75d3 WIP 2017-11-15 15:46:58 -05:00
Jacob Evans
a2e1d28efc Remove comments 2017-11-15 15:26:22 -05:00
Brandon Millman
a9fbe921a0 WIP 2017-11-15 15:14:20 -05:00
Jacob Evans
ee8042b458 Add return type 2017-11-15 14:40:43 -05:00
Jacob Evans
1e1b14edc5 test wording 2017-11-15 12:12:01 -05:00
Jacob Evans
4c505b6470 Add a pending changelog 2017-11-15 12:09:27 -05:00
Jacob Evans
471abfa760 Add and Remove Fee Token with Maker Token 2017-11-15 12:08:12 -05:00
Jacob Evans
590552d3e0 Initial tests 2017-11-15 11:12:40 -05:00
Fabio Berger
557faba31b Add CHANGELOG files to each sub-package 2017-11-15 10:11:04 -05:00
Fabio Berger
2411749594 Fix 0x.js CHANGELOG 2017-11-15 10:10:45 -05:00
Fabio Berger
4e39a957c7 Merge branch 'development' of github.com:0xProject/0x.js into development
* 'development' of github.com:0xProject/0x.js:
  Add lodash noop to emptyOrderbookChannelHandler
  Fix lint error
  Add connect to monorepo
2017-11-14 22:50:10 -05:00
Fabio Berger
0cf719a744 Add title and install instructions to all sub-package READMEs 2017-11-14 22:46:10 -05:00
Brandon Millman
fe7ad22cc1 Merge pull request #224 from 0xProject/feature/addConnect
Add connect to monorepo
2017-11-14 22:43:29 -05:00
Fabio Berger
59f82c5bfb Add rocket.chat badge and remove 0x.js npm badge 2017-11-14 22:41:42 -05:00
Brandon Millman
a2b8933129 Add lodash noop to emptyOrderbookChannelHandler 2017-11-14 22:37:20 -05:00
Fabio Berger
031b07264a Merge branch 'development' of github.com:0xProject/0x.js into development
* 'development' of github.com:0xProject/0x.js:
  Change the way 0x.js assert extends the @0xproject/assert module
2017-11-14 22:31:42 -05:00
Fabio Berger
87f8e93e12 Add core packes to README 2017-11-14 22:31:37 -05:00
Brandon Millman
5b5c31861a Change the way 0x.js assert extends the @0xproject/assert module 2017-11-14 22:23:41 -05:00
Brandon Millman
c315ca6c0c Fix lint error 2017-11-14 22:10:43 -05:00
Brandon Millman
655b0636fa Add connect to monorepo 2017-11-14 21:55:29 -05:00
Fabio Berger
5bd8e172c9 Merge pull request #223 from dekz/bug/fix-readme-links
Fix README links
2017-11-14 21:42:15 -05:00
Jacob Evans
ebb35fd65e Doubled up 2017-11-14 21:41:36 -05:00
Jacob Evans
df7195bda4 Change Slack to Rocket 2017-11-14 21:40:20 -05:00
Jacob Evans
4bd950bb6f Fix README links 2017-11-14 21:31:41 -05:00
Jacob Evans
3f39b22a68 separate assignment and call 2017-11-14 21:20:31 -05:00
Brandon Millman
c019280e85 Merge pull request #219 from 0xProject/feature/rounding-validation
Rounding validation
2017-11-14 18:15:54 -05:00
Fabio Berger
ff0b0ae1ab re-add commonjs build 2017-11-14 18:04:29 -05:00
Fabio Berger
823015435d Publish
- 0x.js@0.25.1
2017-11-14 16:27:34 -05:00
Fabio Berger
99854d7ecf Publish
- 0x.js@0.25.0
2017-11-14 15:59:13 -05:00
Fabio Berger
bb7d9656a5 Publish
- 0x.js@0.24.0
2017-11-14 15:56:14 -05:00
Fabio Berger
e41994a064 revert 0x.js version and change name so matches existing npm package name 2017-11-14 15:51:59 -05:00
Fabio Berger
79df9ef8e6 Publish
- @0xproject/0x.js@0.24.0
 - @0xproject/assert@0.0.4
 - @0xproject/json-schemas@0.6.7
 - @0xproject/tslint-config@0.1.0
2017-11-14 15:43:59 -05:00
Fabio Berger
3b52686125 Remove private flag because we need it published to npm 2017-11-14 15:43:32 -05:00
Fabio Berger
af7c03212d Revert version 2017-11-14 15:38:24 -05:00
Fabio Berger
bdeedb6c91 Update package name and version in package.json 2017-11-14 15:00:40 -05:00
Brandon Millman
4d61d56639 Merge pull request #221 from 0xProject/feature/addJsonSchemas
Add json-schemas package to mono repo
2017-11-14 13:02:17 -05:00
Fabio Berger
430154d543 Update CHANGELOG 2017-11-14 12:57:34 -05:00
Brandon Millman
bb6631c7c6 Update tslint rules for assert and json-schemas 2017-11-14 12:56:22 -05:00
Brandon Millman
9bb5e6f5ce Merge branch 'development' into feature/addJsonSchemas
* development:
  Improve description
  Alphabetize
  Add exit 0 to 0x.js build command
  Add snapshot save and revert to order_state_watcher_test.ts
  Fix changelog
  Use tslint v5.8.0 everywhere and use the tslint-config sub-package instead of the old repo as a dep. in the rest of the sub-packages.
  Add tslint-config sub-package
  Fix tslint issue
  Public interface has changed, moved to minor version
  Update changelog
  Renamed canceled to cancelled
2017-11-14 12:29:46 -05:00
Fabio Berger
05de07496f Merge pull request #220 from 0xProject/feature/addTsLintPackage
Add TSLint Config package
2017-11-14 12:25:44 -05:00
Fabio Berger
ab9dc66b8f Improve description 2017-11-14 12:25:29 -05:00
Fabio Berger
f98042a7f8 Alphabetize 2017-11-14 12:25:20 -05:00
Brandon Millman
247b4686fa Add exit 0 to 0x.js build command 2017-11-14 12:14:08 -05:00
Brandon Millman
c78cb27175 Add snapshot save and revert to order_state_watcher_test.ts 2017-11-14 11:58:35 -05:00
Jacob Evans
752603284d Remove Async subscribe callbacks from OrderWatcher 2017-11-14 11:21:00 -05:00
Leonid Logvinov
dcfe8bae1c Name a constant 2017-11-14 11:11:09 -05:00
Jacob Evans
8f4be963b2 Update changelog 2017-11-14 11:09:37 -05:00
Leonid Logvinov
61496d77a5 Fix namings 2017-11-14 11:03:01 -05:00
Jacob Evans
a12069f03f Callback for subscribe no longer supports an Async Callback 2017-11-14 10:56:57 -05:00
Brandon Millman
56b5619d24 Add json-schemas package to mono repo 2017-11-14 09:42:50 -05:00
Fabio Berger
bc61b92070 Fix changelog 2017-11-13 21:31:40 -05:00
Fabio Berger
682fbd3b76 Merge pull request #217 from dekz/fixCancelledNaming2
Standardise on Cancelled over canceled
2017-11-13 21:12:31 -05:00
Fabio Berger
574ea453b0 Use tslint v5.8.0 everywhere and use the tslint-config sub-package instead of the old repo as a dep. in the rest of the sub-packages. 2017-11-13 21:08:23 -05:00
Fabio Berger
2b806455a5 Add tslint-config sub-package 2017-11-13 20:57:26 -05:00
Fabio Berger
49898525af Fix tslint issue 2017-11-13 20:56:01 -05:00
Leonid Logvinov
24493a4556 Fix tests 2017-11-13 20:32:39 -05:00
Jacob Evans
8de64c9495 Public interface has changed, moved to minor version 2017-11-13 19:25:50 -05:00
Leonid Logvinov
02bbcf6b0e Add a test for rounding error 2017-11-13 18:57:38 -05:00
Fabio Berger
08963f269b Merge pull request #218 from 0xProject/bmillman_add_assert
Add assert sub-package
2017-11-13 18:50:49 -05:00
Fabio Berger
2d0fd14d3c remove new line 2017-11-13 18:50:09 -05:00
Fabio Berger
a15f78652f Update urls 2017-11-13 18:50:00 -05:00
Fabio Berger
3d62312657 Missing @ 2017-11-13 18:45:30 -05:00
Fabio Berger
9b083eebd7 Remove unused circle.yml 2017-11-13 18:42:14 -05:00
Fabio Berger
c7e57a4124 Move conditional running of umd test to 0x.js's package.json 2017-11-13 18:42:02 -05:00
Fabio Berger
ee1a44ebeb Add preliminary instructions to top-level README 2017-11-13 18:20:20 -05:00
Fabio Berger
5b70383ce6 remove image from sub-readme 2017-11-13 18:20:04 -05:00
Fabio Berger
abb2ad45ce fix orderings 2017-11-13 18:12:01 -05:00
Fabio Berger
087ea1f068 Standardize around a test:circleci command that any sub-package can implement in order to have their tests run on CircleCi 2017-11-13 18:11:31 -05:00
Leonid Logvinov
33f479c271 Add assertions for fillableTakerAmount 2017-11-13 18:10:00 -05:00
Leonid Logvinov
f936363440 Add validation for rounding error 2017-11-13 18:09:18 -05:00
Leonid Logvinov
315e4015de Return remainingFillableTakerAmount 2017-11-13 17:59:18 -05:00
Leonid Logvinov
0c91b66f45 Add remainingFillableMakerAmount to types 2017-11-13 17:58:41 -05:00
Fabio Berger
4354d3f121 Rename back 2017-11-13 17:57:02 -05:00
Fabio Berger
3e8e3478a3 Rename assert sub-package and removed duplicate methods from 0x.js's assert module 2017-11-13 17:42:42 -05:00
Fabio Berger
cf29530dd0 fix merge 2017-11-13 17:14:07 -05:00
Brandon Millman
b0f13c17e2 Add assert package to the monorepo 2017-11-13 17:11:39 -05:00
Brandon Millman
1147cb56ba Add assert package to the monorepo 2017-11-13 17:07:33 -05:00
Jacob Evans
e29c3e4c70 Update changelog 2017-11-13 16:39:33 -05:00
Jacob Evans
b1b473d3cb Renamed canceled to cancelled 2017-11-13 16:35:37 -05:00
Fabio Berger
c088d9ddd9 Re-add changelog for 0x.js 2017-11-13 16:28:36 -05:00
Fabio Berger
2b26981e3d Merge pull request #215 from 0xProject/monoRepo
Mono repo Final Steps
2017-11-13 13:05:06 -05:00
Fabio Berger
f3e4576625 Upgrade to Typescript 2.6.1 and fix major & minor versions 2017-11-13 13:03:53 -05:00
Fabio Berger
5dae2b8d2b Don't remove files before UMD test run 2017-11-13 13:03:31 -05:00
Fabio Berger
62da364e5d Only run umd tests on development 2017-11-13 13:02:44 -05:00
Fabio Berger
58a318b754 Merge pull request #214 from 0xProject/monoRepo
Switch over to Lerna + Yarn Workspaces setup for a mono-repo approach
2017-11-13 12:52:08 -05:00
Fabio Berger
ff07f49002 Remove unused var 2017-11-13 12:47:54 -05:00
Fabio Berger
8d69d8553c Add interface type 2017-11-13 12:43:22 -05:00
Fabio Berger
a072954176 Replace _.get for type safety 2017-11-13 12:39:36 -05:00
Fabio Berger
23de8185c6 Declare as string 2017-11-13 12:39:20 -05:00
Fabio Berger
d9c80e9b6a Merge branch 'monoRepo' of github.com:0xProject/0x.js into monoRepo
* 'monoRepo' of github.com:0xProject/0x.js:
  Fail the tests on tsc error
2017-11-13 12:31:34 -05:00
Fabio Berger
dcc4272c4e move tslint.json to 0x.js sub-package 2017-11-13 12:31:29 -05:00
Fabio Berger
2060940ecc Fix lint and ts issues 2017-11-13 12:30:01 -05:00
Leonid Logvinov
14274ef67b Fail the tests on tsc error 2017-11-13 12:27:20 -05:00
Fabio Berger
70661c179f point to top-level node_modules 2017-11-13 12:21:25 -05:00
Fabio Berger
8a0ae68f27 remove unnecessary -- 2017-11-13 12:20:58 -05:00
Fabio Berger
06ada87370 Add missing key 2017-11-13 12:14:01 -05:00
Fabio Berger
a5d9b71eb6 Simply lerna command and run bootstrap to install dependencies 2017-11-13 12:13:11 -05:00
Fabio Berger
aa3385d516 Fix lerna command 2017-11-13 12:02:37 -05:00
Fabio Berger
af60b41c89 Fix package.json 2017-11-13 11:59:31 -05:00
Fabio Berger
506bf45272 Add checkout 2017-11-13 11:57:22 -05:00
Fabio Berger
2655daa2f4 Merge branch 'monoRepo' of github.com:0xProject/0x.js into monoRepo
* 'monoRepo' of github.com:0xProject/0x.js:
  Fix package.json
2017-11-13 11:54:29 -05:00
Fabio Berger
0b095ce5ce Upgrade circleci to version 2.0 2017-11-13 11:54:19 -05:00
Leonid Logvinov
ae461b77f8 Fix package.json 2017-11-13 11:26:39 -05:00
Fabio Berger
4f3b9dc61a leave out yarn version peg 2017-11-13 11:22:31 -05:00
Fabio Berger
a246702511 Use lerna 2017-11-13 11:20:07 -05:00
Fabio Berger
2ae47d64b7 use yarn instead of lerna 2017-11-13 11:09:56 -05:00
Fabio Berger
6a76349730 Install older version of yarn 2017-11-13 11:09:46 -05:00
Fabio Berger
e6482554f5 Add circle.yml and move testrpc command to top-level repo 2017-11-13 10:56:22 -05:00
Fabio Berger
c4ee2d7386 Switch over to Lerna + Yarn Workspaces setup for a mono-repo approach 2017-11-12 22:17:18 -05:00
Fabio Berger
a74ec0effa Merge pull request #200 from 0xProject/feature/receipt-status
Normalize the way we return the transaction status
2017-11-12 21:24:00 -05:00
Fabio Berger
e33027c624 Merge branch 'development' into feature/receipt-status
* development: (164 commits)
  Remove old tests
  Remove unused code
  Fix tests
  Remove redundant spaces
  Don't store empty objects
  Fix a typo
  Remove duplicate operations
  Remove redundant instance variables
  Fix tests
  Remove blockStore and default to numConfirmations === 0
  Add a comment
  Store number of confirmations in a blockStore
  Remove tautology check
  Pass blockStore to eventWatcher
  Fix last merge conflicts
  Clear cache on unsubscribe
  Clear store cache on events
  Add more configs for order watcher
  Make subscribe function async and make blockStore operational
  Adjust tests to new interface
  ...

# Conflicts:
#	package.json
#	src/types.ts
#	yarn.lock
2017-11-12 21:12:37 -05:00
Fabio Berger
b0be323e89 Merge pull request #205 from 0xProject/orderWatcher
Order watcher
2017-11-12 20:50:42 -05:00
Fabio Berger
a22661670f Merge branch 'orderWatcher' of github.com:0xProject/0x.js into orderWatcher
* 'orderWatcher' of github.com:0xProject/0x.js: (33 commits)
  Remove old tests
  Remove unused code
  Fix tests
  Remove redundant spaces
  Don't store empty objects
  Fix a typo
  Remove duplicate operations
  Remove redundant instance variables
  Fix tests
  Remove blockStore and default to numConfirmations === 0
  Add a comment
  Store number of confirmations in a blockStore
  Remove tautology check
  Pass blockStore to eventWatcher
  Fix last merge conflicts
  Clear cache on unsubscribe
  Clear store cache on events
  Add more configs for order watcher
  Make subscribe function async and make blockStore operational
  Adjust tests to new interface
  ...
2017-11-12 20:49:56 -05:00
Fabio Berger
442f35a1fd Merge branch 'development' into orderWatcher
* development:
  0.23.0
  Update CHANGELOG
  Fix amounts in tests one last time. Now that we updated the testRPC snapshot, this should no longer be mismatched between CI and locally
  Update testRPC snapshot used by CircleCi
  Push unsubscribe to the base class rather than super
  Check for null rather than undefined
  Removed nits
  Test case was error then unsubscribe
  Clean up subscription state.
  Fix unhandled promise rejection error on subscriptions

# Conflicts:
#	src/types.ts
#	test/exchange_wrapper_test.ts
#	test/token_wrapper_test.ts
2017-11-12 20:49:48 -05:00
Fabio Berger
5aef16c2aa Merge pull request #211 from 0xProject/feature/orderWatcherLocalStateStore
Order watcher local state store
2017-11-12 20:26:21 -05:00
Leonid Logvinov
e512e38efb Remove old tests 2017-11-12 20:21:24 -05:00
Leonid Logvinov
7ea0b138bc Remove unused code 2017-11-12 20:06:14 -05:00
Leonid Logvinov
d73fb5a23c Fix tests 2017-11-12 20:06:14 -05:00
Leonid Logvinov
610298a25d Remove redundant spaces 2017-11-12 20:06:14 -05:00
Leonid Logvinov
7b50a6490d Don't store empty objects 2017-11-12 20:06:14 -05:00
Leonid Logvinov
fdb82d5dd4 Fix a typo 2017-11-12 20:06:13 -05:00
Leonid Logvinov
a587697883 Remove duplicate operations 2017-11-12 20:06:13 -05:00
Leonid Logvinov
3204c077d1 Remove redundant instance variables 2017-11-12 20:06:13 -05:00
Leonid Logvinov
d52825a5b1 Fix tests 2017-11-12 20:06:13 -05:00
Leonid Logvinov
84c965d459 Remove blockStore and default to numConfirmations === 0 2017-11-12 20:06:13 -05:00
Leonid Logvinov
22cd6989a0 Add a comment 2017-11-12 20:06:13 -05:00
Leonid Logvinov
a9ae555b88 Store number of confirmations in a blockStore 2017-11-12 20:06:13 -05:00
Leonid Logvinov
d4dc428124 Remove tautology check 2017-11-12 20:06:13 -05:00
Leonid Logvinov
f5608d2c94 Pass blockStore to eventWatcher 2017-11-12 20:06:13 -05:00
Leonid Logvinov
bcad937003 Fix last merge conflicts 2017-11-12 20:06:13 -05:00
Leonid Logvinov
53c918cc78 Clear cache on unsubscribe 2017-11-12 20:06:13 -05:00
Leonid Logvinov
009f81fe4f Clear store cache on events 2017-11-12 20:06:13 -05:00
Leonid Logvinov
81ce4a0229 Add more configs for order watcher 2017-11-12 20:06:13 -05:00
Leonid Logvinov
6bcd9adb9e Make subscribe function async and make blockStore operational 2017-11-12 20:06:13 -05:00
Leonid Logvinov
61e7b735dc Adjust tests to new interface 2017-11-12 20:06:13 -05:00
Leonid Logvinov
44c15fc1ef Add more errors 2017-11-12 20:06:12 -05:00
Leonid Logvinov
9d3fe1258a Create stores in orderStateWatcher 2017-11-12 20:06:12 -05:00
Leonid Logvinov
e72ba39c41 Make orderStateUtils operate on stores 2017-11-12 20:05:46 -05:00
Leonid Logvinov
ffcc487763 Create fake blockStore for exchange transfer simulator 2017-11-12 20:03:18 -05:00
Leonid Logvinov
473ce8b617 Add initial incomplete BlockStore implementation 2017-11-12 20:03:18 -05:00
Leonid Logvinov
70436fa535 Make stores accept numConfirmations and blockStore instead of defaultBlock 2017-11-12 20:03:18 -05:00
Leonid Logvinov
4921f61e76 Add LatestBlockNumberNotSet internal error 2017-11-12 20:03:18 -05:00
Leonid Logvinov
75b390cf93 Add functions to clear stores cache 2017-11-12 20:03:18 -05:00
Leonid Logvinov
dcda8fe538 Add store for order filled/cancelled state 2017-11-12 20:03:18 -05:00
Leonid Logvinov
6edae86516 Make store configurable by blockParam 2017-11-12 20:03:18 -05:00
Leonid Logvinov
f163e6d8cc Fix tests 2017-11-12 20:03:18 -05:00
Leonid Logvinov
742660591f Make a store an instance variable of exchange transfer simulator and stop inheriting it 2017-11-12 20:03:18 -05:00
Leonid Logvinov
ddbcf5f470 Refactor out BalanceAndProxyAllowanceLazyStore 2017-11-12 20:03:17 -05:00
Fabio Berger
6becf22a2f Merge pull request #210 from dekz/orderWatcherRemaining
Calculate the remaining order amount in maker units
2017-11-12 19:39:24 -05:00
Jacob Evans
32246fd26b remove comments 2017-11-12 19:37:03 -05:00
Jacob Evans
42e3ab91a7 Perform the division after multiplication to reduce compounding the rounding errors 2017-11-12 19:17:27 -05:00
Fabio Berger
6daf70b745 Merge pull request #207 from 0xProject/orderWatcherTests
Additional order watcher tests
2017-11-12 18:11:45 -05:00
Fabio Berger
12298ea392 Don't return anything 2017-11-12 18:11:30 -05:00
Jacob Evans
5e77e8809a Update comment 2017-11-12 17:30:57 -05:00
Jacob Evans
1b3f84c9ad text description update 2017-11-12 17:28:34 -05:00
Jacob Evans
e06539e76d remove only 2017-11-12 17:25:42 -05:00
Jacob Evans
fdb3fa6801 Added specs for allowance and balance changes 2017-11-12 17:24:31 -05:00
Brandon Millman
1392a855bb 0.23.0 2017-11-12 17:01:58 -05:00
Brandon Millman
d4cab6e62f Update CHANGELOG 2017-11-12 17:01:43 -05:00
Leonid Logvinov
5d2b6585c6 Fix tslint issue 2017-11-12 15:19:10 -05:00
Leonid Logvinov
a2f89347a9 Fix tests 2017-11-12 15:05:06 -05:00
Leonid Logvinov
50ee23ebfa Normalize the way we return the transaction status 2017-11-12 15:05:06 -05:00
Brandon Millman
719c51f61a Merge pull request #209 from 0xProject/fixUnhandledPromiseBug
Fix unhandled promise rejection error on subscriptions
2017-11-12 14:06:39 -05:00
Jacob Evans
3e2a614eb9 Calculate the remaining order amount in maker units 2017-11-12 11:28:01 -05:00
Fabio Berger
abb23631df Update testRPC snapshot used by CircleCi 2017-11-12 10:53:29 -05:00
Fabio Berger
dae5a063cf Fix amounts in tests one last time. Now that we updated the testRPC snapshot, this should no longer be mismatched between CI and locally 2017-11-12 10:43:24 -05:00
Fabio Berger
e57a507ba0 Update testRPC snapshot used by CircleCi 2017-11-12 10:39:09 -05:00
Fabio Berger
4e194d7766 Merge pull request #208 from dekz/fixUnhandledPromiseBug
Clean up subscription state.
2017-11-12 09:40:47 -05:00
Jacob Evans
d34ea79d93 Push unsubscribe to the base class rather than super 2017-11-11 13:42:42 -05:00
Jacob Evans
ee73659f16 Check for null rather than undefined 2017-11-11 12:33:05 -05:00
Jacob Evans
394417ff07 Removed nits 2017-11-11 12:15:24 -05:00
Jacob Evans
a85b1f016d Test case was error then unsubscribe 2017-11-11 12:01:27 -05:00
Fabio Berger
c6f97f20fb Merge branch 'development' into orderWatcher
* development:
  0.22.6
  Add new changes to CHANGELOG
  use util fn
  no race, reject from interval cb and clear
  allow timeout for await transaction mined

# Conflicts:
#	src/types.ts
2017-11-11 11:14:09 -05:00
Fabio Berger
b66600338e Add comment 2017-11-11 11:05:52 -05:00
Jacob Evans
4ae9482d50 Clean up subscription state.
In the case of an exception, keep the state correct between contract wrapper, exchange wrapper and token wrapper.
2017-11-11 11:01:59 -05:00
Fabio Berger
72fcf7b2ab rename isDecodedLog to isLogDecoded 2017-11-11 10:57:39 -05:00
Fabio Berger
a8b6bbd6bc Improve comment 2017-11-11 10:57:27 -05:00
Fabio Berger
e5d04f4467 Fix test given that we now do delete the keys in dependentOrderHashes 2017-11-11 10:50:08 -05:00
Fabio Berger
62ac8e1952 Fix missing renames 2017-11-11 10:22:09 -05:00
Fabio Berger
d61f34ec12 Declare OnOrderStateChangeCallback as either sync or async 2017-11-11 10:21:59 -05:00
Fabio Berger
252fdd03d7 Fix comment 2017-11-11 10:21:40 -05:00
Fabio Berger
0fe5c5dac3 Remove keys from dependentOrderHashes if empty 2017-11-11 10:13:42 -05:00
Fabio Berger
037e992de4 establish convention of initializing empty instances in instance declaration 2017-11-11 09:57:45 -05:00
Fabio Berger
12023073f4 Use enum instead of boolean to avoid potential bugs from isRemoved incorrectly being set to true 2017-11-11 09:54:27 -05:00
Fabio Berger
0db0694aad rename _orders to _orderByOrderhash for clarity 2017-11-11 09:47:32 -05:00
Fabio Berger
d4f763aa68 Add comment above orderStateWatcher class 2017-11-11 09:45:50 -05:00
Fabio Berger
4e708c81ca Fix expected balance 2017-11-11 09:19:51 -05:00
Fabio Berger
041d00301c Fix type declaration in test 2017-11-11 08:58:01 -05:00
Fabio Berger
0ec51b124b Feather the callback down to _emitDifferencesAsync and don't store it as a class instance. This will make supporting multiple subscriptions easier later on and reduces the amount of unsubscription cleanup 2017-11-11 08:57:49 -05:00
Fabio Berger
6012926e82 Throw if trying to subscribe multiple times 2017-11-10 18:07:11 -05:00
Fabio Berger
ca9c1bca4a Fix alignment 2017-11-10 18:06:57 -05:00
Fabio Berger
0d957ea71d Add comment above the eventWatcher class 2017-11-10 17:47:41 -05:00
Fabio Berger
697926641f Rename method since it's not more then just mempool 2017-11-10 17:47:30 -05:00
Fabio Berger
2bf65fda1f Add tests for the numConfirmations config to ensure that the events are being emitted for the confirmation depth specified 2017-11-10 16:34:21 -05:00
Fabio Berger
4262ac3c89 Fix unhandled promise rejection error on subscriptions 2017-11-10 14:13:15 -05:00
Leonid Logvinov
76b66872d8 0.22.6 2017-11-10 11:41:31 -05:00
Leonid Logvinov
2f92aaea0c Add new changes to CHANGELOG 2017-11-10 11:40:31 -05:00
Leonid
c5b347bb15 Merge pull request #206 from lukeautry/await_transaction_timeout
Allow timeout for await transaction mined
2017-11-10 11:38:02 -05:00
Luke Autry
d11087c28f use util fn 2017-11-10 11:35:40 -05:00
Luke Autry
e6139e02b8 no race, reject from interval cb and clear 2017-11-10 11:34:17 -05:00
Luke Autry
583b92e672 allow timeout for await transaction mined 2017-11-10 10:43:52 -05:00
Fabio Berger
d90756e8ef Test that the orderStateWatcher doesn't emit an event when an irrelevant blockchain event is received. 2017-11-10 10:07:29 -05:00
Fabio Berger
9b9ab983d6 Fix test description 2017-11-10 09:04:25 -05:00
Fabio Berger
d5746652a2 Fix test description 2017-11-09 23:37:01 -05:00
Fabio Berger
47f9e171fc Move numConfirmations to constructor call 2017-11-09 23:32:22 -05:00
Fabio Berger
a1bc18e5cf Improve comment 2017-11-09 23:32:04 -05:00
Fabio Berger
0cd5bf7967 Make sure to set the defaultBlock to the blockNumber rather then the number of confirmations 2017-11-09 23:24:46 -05:00
Fabio Berger
0205f9ede3 Simplify to/from block code 2017-11-09 23:16:26 -05:00
Fabio Berger
960c83315b Add assertion 2017-11-09 23:05:46 -05:00
Fabio Berger
f9c84fb6f4 Merge branch 'orderWatcher' of github.com:0xProject/0x.js into orderWatcher
* 'orderWatcher' of github.com:0xProject/0x.js:
  Add forgotten file
2017-11-09 22:58:10 -05:00
Fabio Berger
1b14561748 remove no longer needed arg 2017-11-09 22:58:06 -05:00
Fabio Berger
27519e1dfa rename intervalId to intervalIdIfExists 2017-11-09 22:57:38 -05:00
Leonid Logvinov
46e2da24a4 Add forgotten file 2017-11-09 22:12:29 -05:00
Fabio Berger
dbbcbed344 Merge branch 'orderWatcher' of github.com:0xProject/0x.js into orderWatcher
* 'orderWatcher' of github.com:0xProject/0x.js:
  Add order state watcher tests for LogCancel

# Conflicts:
#	test/order_state_watcher_test.ts
2017-11-09 18:30:20 -05:00
Fabio Berger
c0db88168b Fix bug where we hard-coded using pendingBlock for fetching the orderState. Moved numConfirmations to become a global orderStateWatcher config 2017-11-09 18:29:13 -05:00
Leonid Logvinov
d98435b4dc Add order state watcher tests for LogCancel 2017-11-09 18:28:33 -05:00
Fabio Berger
595dc6de03 Fix comments 2017-11-09 18:04:24 -05:00
Fabio Berger
322e054f1a comment improvements 2017-11-09 17:57:41 -05:00
Fabio Berger
7f606e1e64 Closing paren on same level as open 2017-11-09 17:50:48 -05:00
Fabio Berger
b0491b0ee2 Rename _callbackAsync to _callbackIfExistsAsync for clarity 2017-11-09 17:48:05 -05:00
Fabio Berger
0e69356ca9 Merge branches 'orderWatcher' and 'orderWatcher' of github.com:0xProject/0x.js into orderWatcher
* 'orderWatcher' of github.com:0xProject/0x.js:
  Fix getting events from non-mempool

* 'orderWatcher' of github.com:0xProject/0x.js:
  Fix getting events from non-mempool
2017-11-09 17:45:37 -05:00
Fabio Berger
90348e08c1 use explicit import 2017-11-09 17:45:30 -05:00
Leonid Logvinov
c60d7e2db8 Fix getting events from non-mempool 2017-11-09 17:44:45 -05:00
Fabio Berger
50d3a14825 Remove finished TODOs 2017-11-09 17:39:03 -05:00
Fabio Berger
0ff3ba5250 Merge branch 'orderWatcher' of github.com:0xProject/0x.js into orderWatcher
* 'orderWatcher' of github.com:0xProject/0x.js:
  Revert test amount changes
2017-11-09 17:20:49 -05:00
Fabio Berger
02cc3f9116 Create assert.isValidSignature method and use it in addOrder 2017-11-09 17:18:30 -05:00
Fabio Berger
62861d1e13 Move isValidSignature implementation into signatureUtils 2017-11-09 17:18:03 -05:00
Leonid Logvinov
cd3c7f1b97 Revert test amount changes 2017-11-09 17:14:10 -05:00
Fabio Berger
0c8886ad0c Fix comment 2017-11-09 17:03:54 -05:00
Fabio Berger
9d24325207 Merge branch 'orderWatcher' of github.com:0xProject/0x.js into orderWatcher
* 'orderWatcher' of github.com:0xProject/0x.js:
  Revert "Use _.get for optional configs"

# Conflicts:
#	src/0x.ts
2017-11-09 17:01:30 -05:00
Fabio Berger
126a165f55 Add nested config for orderWatcher 2017-11-09 16:59:41 -05:00
Leonid Logvinov
1c6e6842c6 Revert "Use _.get for optional configs"
This reverts commit ecc54b07c7.
2017-11-09 16:48:45 -05:00
Fabio Berger
6f5a55b5fe Rename MempoolEventCallback to EventWatcherCallback 2017-11-09 16:43:19 -05:00
Fabio Berger
530f5a700e Merge branch 'orderWatcher' of github.com:0xProject/0x.js into orderWatcher
* 'orderWatcher' of github.com:0xProject/0x.js:
  Fix namings
2017-11-09 16:42:06 -05:00
Fabio Berger
441c1f9ab7 rename folder to order_watcher 2017-11-09 16:41:57 -05:00
Leonid Logvinov
d98d885924 Fix namings 2017-11-09 16:37:00 -05:00
Leonid Logvinov
6aa91d89e0 Remove redundant assertions 2017-11-09 16:30:40 -05:00
Fabio Berger
ecc54b07c7 Use _.get for optional configs 2017-11-09 16:30:14 -05:00
Fabio Berger
ce11a38d70 Improve comment 2017-11-09 16:23:39 -05:00
Leonid Logvinov
c9e0b29878 Add SubscriptionAlreadyPresent error 2017-11-09 16:20:31 -05:00
Leonid Logvinov
3a96fec03b Pass numConfirmations 2017-11-09 15:38:23 -05:00
Leonid Logvinov
7a231b3166 Removed unused order adding in tests 2017-11-09 15:30:41 -05:00
Leonid Logvinov
31f6934787 Add a test that a second subscription fails 2017-11-09 15:30:22 -05:00
Fabio Berger
c5dc89886d fix merge conflicts 2017-11-09 15:13:56 -05:00
Fabio Berger
545cc0b026 Add comments to public methods 2017-11-09 15:02:44 -05:00
Fabio Berger
9ff42053c3 Add numConfirmations arg so that caller can decide on numConfirmations at which they want to watch orders 2017-11-09 15:02:28 -05:00
Leonid Logvinov
41a0ce146d Add tests for order removals 2017-11-09 14:54:55 -05:00
Leonid Logvinov
709fa06af6 Pass orderHash instead of an order to removeOrder and adjust the tests 2017-11-09 14:23:53 -05:00
Fabio Berger
5623400557 Merge branch 'orderWatcher' of github.com:0xProject/0x.js into orderWatcher
* 'orderWatcher' of github.com:0xProject/0x.js: (32 commits)
  Remove check for now, we need a more robust check
  Rename test file and add test for a partial fill
  Fix tests by making the expected balance be 2^27 not 2^26
  Add assert.isValidBaseUnitAmount that checks for decimals in amounts that should be in baseUnits. This can sometimes alert developers whenever they accidentally pass in unitAmounts.
  Look for relevant events in the decodedLogs and emit orderState events for orders impacted by the blockchain state changes
  Remove unused import
  Fix typo
  Add todo comments
  fix styling
  remove unused type
  Add naive order state watcher implementation
  Change fields in OrderState to represent taker side values
  Introduce OrderState interface
  Fix config schema
  Add empty implementation of order state watcher
  Add new public types
  Move mempoolPollingIntervalMs to OrderWatcherConfig
  Adjust tests for mempool event watcher
  Clear event cache on unsubscribe
  Remove mempool event watcher config
  ...
2017-11-09 14:12:17 -05:00
Fabio Berger
1351e02065 Remove check for now, we need a more robust check 2017-11-09 14:11:46 -05:00
Fabio Berger
4f030ac45c Rename test file and add test for a partial fill 2017-11-09 14:11:46 -05:00
Fabio Berger
c7c81a1f7e Fix tests by making the expected balance be 2^27 not 2^26 2017-11-09 14:11:46 -05:00
Fabio Berger
ae74965774 Add assert.isValidBaseUnitAmount that checks for decimals in amounts that should be in baseUnits. This can sometimes alert developers whenever they accidentally pass in unitAmounts. 2017-11-09 14:11:46 -05:00
Fabio Berger
e952c98ca8 Look for relevant events in the decodedLogs and emit orderState events for orders impacted by the blockchain state changes 2017-11-09 14:11:46 -05:00
Fabio Berger
6f00c422c7 Remove unused import 2017-11-09 14:11:46 -05:00
Fabio Berger
e592cedbb4 Fix typo 2017-11-09 14:11:46 -05:00
Fabio Berger
a10bb4b2fa Add todo comments 2017-11-09 14:11:46 -05:00
Fabio Berger
c89eec4261 fix styling 2017-11-09 14:11:46 -05:00
Fabio Berger
edc0fec808 remove unused type 2017-11-09 14:11:46 -05:00
Leonid Logvinov
bb5474660c Add naive order state watcher implementation
Revalidate all orders upon event received and emit order states even if
not changed
2017-11-09 14:11:46 -05:00
Leonid Logvinov
63f16b5f99 Change fields in OrderState to represent taker side values 2017-11-09 14:11:46 -05:00
Leonid Logvinov
0b84c469d3 Introduce OrderState interface 2017-11-09 14:11:45 -05:00
Leonid Logvinov
ff5d18d327 Fix config schema 2017-11-09 14:11:45 -05:00
Leonid Logvinov
1980b3fae4 Add empty implementation of order state watcher 2017-11-09 14:11:45 -05:00
Leonid Logvinov
6714b8958b Add new public types 2017-11-09 14:11:45 -05:00
Leonid Logvinov
f601a5d356 Move mempoolPollingIntervalMs to OrderWatcherConfig 2017-11-09 14:11:45 -05:00
Leonid Logvinov
e7f60032bc Adjust tests for mempool event watcher 2017-11-09 14:11:45 -05:00
Leonid Logvinov
589bd8694f Clear event cache on unsubscribe 2017-11-09 14:11:45 -05:00
Leonid Logvinov
eace1a9840 Remove mempool event watcher config 2017-11-09 14:11:45 -05:00
Leonid Logvinov
3ddb203317 Move provider altering logic to Web3Wrapper 2017-11-09 14:11:45 -05:00
Leonid Logvinov
84b8e77aaa Add types for order state watcher 2017-11-09 14:11:45 -05:00
Leonid Logvinov
247eefc33a Add initial interface of an OrderWatcher 2017-11-09 14:11:45 -05:00
Leonid Logvinov
fd54a6a3ad Rename MempoolWatcher to EventWatcher and remove from public interface 2017-11-09 14:11:45 -05:00
Leonid Logvinov
a2ffd7de2e Fix namings 2017-11-09 14:11:45 -05:00
Leonid Logvinov
cea2fb0fe6 Add mempool tests 2017-11-09 14:11:45 -05:00
Leonid Logvinov
23d7d7d140 Don't emit new events if already unsubscribed 2017-11-09 14:11:45 -05:00
Leonid Logvinov
f8179bc5a9 Compare logs by string representation 2017-11-09 14:11:45 -05:00
Leonid Logvinov
a4e93558aa Upgrade web3-typescript-typings 2017-11-09 14:11:45 -05:00
Leonid Logvinov
cb3cae0f30 Add initial mempool watching implememtation 2017-11-09 14:11:45 -05:00
Fabio Berger
04e0199790 Remove check for now, we need a more robust check 2017-11-09 10:22:29 -05:00
Fabio Berger
453f3405a7 Rename test file and add test for a partial fill 2017-11-09 10:21:54 -05:00
Fabio Berger
a8585df81b Fix tests by making the expected balance be 2^27 not 2^26 2017-11-09 10:21:38 -05:00
Fabio Berger
c96c681758 Add assert.isValidBaseUnitAmount that checks for decimals in amounts that should be in baseUnits. This can sometimes alert developers whenever they accidentally pass in unitAmounts. 2017-11-09 10:09:20 -05:00
Fabio Berger
6007609f71 Look for relevant events in the decodedLogs and emit orderState events for orders impacted by the blockchain state changes 2017-11-08 19:01:57 -05:00
Fabio Berger
5a6ed252c4 Remove unused import 2017-11-08 19:00:38 -05:00
Fabio Berger
641dff8991 Fix typo 2017-11-08 19:00:14 -05:00
Fabio Berger
ee3115550e Add todo comments 2017-11-08 18:59:59 -05:00
Fabio Berger
d39852c0cf fix styling 2017-11-08 18:59:40 -05:00
Fabio Berger
c57894633f remove unused type 2017-11-08 18:59:28 -05:00
Fabio Berger
a7bedad9f0 0.22.5 2017-11-07 18:02:57 -05:00
Fabio Berger
92df3d953f Update changelog 2017-11-07 18:02:40 -05:00
Leonid Logvinov
a896904ae7 Add naive order state watcher implementation
Revalidate all orders upon event received and emit order states even if
not changed
2017-10-30 18:49:16 +02:00
Leonid Logvinov
6bfcd253f8 Change fields in OrderState to represent taker side values 2017-10-30 18:49:16 +02:00
Leonid Logvinov
456f7e7304 Introduce OrderState interface 2017-10-30 18:49:16 +02:00
Leonid Logvinov
ed7917f9df Fix config schema 2017-10-30 18:49:16 +02:00
Leonid Logvinov
2a25ece363 Add empty implementation of order state watcher 2017-10-30 18:49:16 +02:00
Leonid Logvinov
1c90c3af42 Add new public types 2017-10-30 18:49:16 +02:00
Leonid Logvinov
6ca6290f6a Move mempoolPollingIntervalMs to OrderWatcherConfig 2017-10-30 18:49:16 +02:00
Leonid Logvinov
fd2c5d46ad Adjust tests for mempool event watcher 2017-10-30 18:49:16 +02:00
Leonid Logvinov
a6c110f558 Clear event cache on unsubscribe 2017-10-30 18:49:16 +02:00
Leonid Logvinov
02b33f988f Remove mempool event watcher config 2017-10-30 18:49:16 +02:00
Leonid Logvinov
7bf6e6188a Move provider altering logic to Web3Wrapper 2017-10-30 18:49:16 +02:00
Leonid Logvinov
26394813f4 Add types for order state watcher 2017-10-30 18:49:16 +02:00
Leonid Logvinov
f21f42f11e Add initial interface of an OrderWatcher 2017-10-30 18:49:16 +02:00
Leonid Logvinov
68a8556cd2 Rename MempoolWatcher to EventWatcher and remove from public interface 2017-10-30 18:49:16 +02:00
Leonid Logvinov
e4d8b1c4d2 Fix namings 2017-10-30 18:49:16 +02:00
Leonid Logvinov
eac467fe9a Add mempool tests 2017-10-30 18:49:16 +02:00
Leonid Logvinov
1bb9c912cd Don't emit new events if already unsubscribed 2017-10-30 18:49:16 +02:00
Leonid Logvinov
02d470892f Compare logs by string representation 2017-10-30 18:49:16 +02:00
Leonid Logvinov
161f62dc27 Upgrade web3-typescript-typings 2017-10-30 18:49:16 +02:00
Leonid Logvinov
f53472e717 Add initial mempool watching implememtation 2017-10-30 18:49:16 +02:00
Fabio Berger
7fa5d34c45 Remove unnecessary dep 2017-10-30 18:48:16 +02:00
Fabio Berger
b49d1dae7d Merge branch 'development' of github.com:0xProject/0x.js into development
* 'development' of github.com:0xProject/0x.js:
  Update CHANGELOG
  0.22.4
  Add HACK comments
  Add a forgotten augmentation file
  Upgrade bignumber to the version with native typings and remove typings
  Downgrade typedoc
  Upgrade bignumber to the version with native typings and remove typings
2017-10-30 16:17:39 +02:00
Fabio Berger
9b0496b049 Fix comment 2017-10-30 16:08:44 +02:00
Leonid Logvinov
fec8f8a881 Update CHANGELOG 2017-10-25 23:05:49 +03:00
Leonid Logvinov
e08c54878c 0.22.4 2017-10-25 23:04:49 +03:00
Leonid
e78398862b Merge pull request #202 from 0xProject/fix/bignumber-types
Bignumber types
2017-10-25 23:04:31 +03:00
Leonid Logvinov
122a5e9b63 Add HACK comments 2017-10-25 23:04:17 +03:00
Leonid Logvinov
5d759d82ed Add a forgotten augmentation file 2017-10-25 22:30:22 +03:00
Leonid Logvinov
744a9b8931 Upgrade bignumber to the version with native typings and remove typings 2017-10-25 22:22:23 +03:00
Leonid Logvinov
45c4042e2b Downgrade typedoc 2017-10-25 22:11:09 +03:00
Leonid Logvinov
bba7704732 Upgrade bignumber to the version with native typings and remove typings 2017-10-25 22:10:09 +03:00
Leonid Logvinov
fa3e88c454 0.22.3 2017-10-25 12:20:47 +03:00
Leonid Logvinov
e0ff550e19 Update CHANGELOG 2017-10-25 12:16:20 +03:00
Leonid
48dbee2e10 Merge pull request #199 from NoteGio/raise-allowance-gas
Increase ALLOWANCE_TO_ZERO_GAS_AMOUNT
2017-10-25 10:22:35 +03:00
Austin Roberts
1ba2df8024 Increase ALLOWANCE_TO_ZERO_GAS_AMOUNT
On TestRPC, I'm seeing a particular transaction that is taking 47275
gas instead of the predefined 47155. It's not at all obvious to me
why this transaction is taking an extra 120 gas, and I've been unable
to reproduce the issue in the 0x.js test suite, but bumping the gas
allowance has resolved the issue for me.

The transactions in question are trying to set an unlimited proxy
allowance on either the WETH or ZRX tokens in the testrpc snapshot,
but run out of gas.
2017-10-24 17:14:35 -05:00
Leonid Logvinov
e17f6979c3 0.22.2 2017-10-24 18:58:40 +03:00
Leonid
8330dabda8 Merge pull request #197 from 0xProject/fix/rounding
Fix rounding of maker fill amount and correctly validate partial fees
2017-10-24 18:54:50 +03:00
Leonid Logvinov
1fd8c2a6e2 Update CHANGELOG 2017-10-24 18:47:22 +03:00
Leonid Logvinov
0c6be94222 Fix index 2017-10-24 18:31:59 +03:00
Leonid Logvinov
89103c40fb Use more meaningful variable names 2017-10-24 18:31:59 +03:00
Leonid Logvinov
fbe34663da Fix the rounding of makerFillAmount and correctly validate partial fees 2017-10-24 18:31:59 +03:00
Leonid Logvinov
9d0ccdfdcc Add tests testing that rounding or makerFillAmount is correct and that we only validate partial fees 2017-10-24 18:31:59 +03:00
Leonid Logvinov
cd1f0c74c1 Revert CHANGELOG 2017-10-24 16:42:50 +03:00
Leonid
3deac0f100 Merge pull request #198 from 0xProject/revert-195-minification
Revert "Reduce final bundle size by 11% (82kB)"
2017-10-24 16:40:50 +03:00
Leonid
641d3b75ea Revert "Reduce final bundle size by 11% (82kB)" 2017-10-24 16:40:38 +03:00
Brandon Millman
fab2fa9adf Merge pull request #196 from 0xProject/bmillman_fix_tslint
Fix lint script to analyze nested files
2017-10-23 10:20:42 -07:00
Brandon Millman
b3d8cefbe6 Fix lint script to analyze nested files 2017-10-19 12:03:49 -07:00
Leonid Logvinov
32e8e52ad7 0.22.1 2017-10-19 17:09:30 +03:00
Leonid Logvinov
77b3a43e17 Update CHANGELOG 2017-10-19 17:09:23 +03:00
Leonid
ddec91ba52 Merge pull request #195 from 0xProject/minification
Reduce final bundle size by 11% (82kB)
2017-10-19 16:31:06 +03:00
Leonid Logvinov
0329b36430 Fix linter errors 2017-10-19 12:55:14 +03:00
Leonid Logvinov
f62dc0f46c Update 0x-json-schemas 2017-10-19 12:44:00 +03:00
Leonid Logvinov
f64638173a Transform lodash-es to commonjs module format 2017-10-19 00:31:10 +03:00
Leonid Logvinov
14a0dcecf5 Fix tests 2017-10-18 23:38:28 +03:00
Leonid Logvinov
e17cca9834 Remove unused parts from artifacts 2017-10-18 17:46:37 +03:00
Leonid Logvinov
9b0f68f9a9 Include only used lodash functions 2017-10-18 17:45:39 +03:00
Leonid Logvinov
f4eb73ca7c Upgrade 0x-json-schemas to the version that doesn't depend on lodash 2017-10-18 17:19:56 +03:00
Leonid Logvinov
4ea6ebb0ae Uprade ethereumjs-blockstream, cause new version doesn't include source maps and is significantly smaller 2017-10-18 17:18:44 +03:00
Leonid Logvinov
8931f2e736 0.22.0 2017-10-16 12:03:31 +03:00
Leonid Logvinov
7ae78ca3c8 Update CHANGELOG 2017-10-16 12:03:20 +03:00
Leonid
d24eeec1a1 Merge pull request #187 from apackin/setFillOrKillToUseRequestInterface
[WIP] Use OrderFillRequest interface for batchFillOrKill
2017-10-16 11:41:04 +03:00
Leonid
a798f32cc8 Merge branch 'development' into setFillOrKillToUseRequestInterface 2017-10-16 11:40:20 +03:00
Leonid Logvinov
df5fe4a84f 0.21.4 2017-10-13 19:00:06 +03:00
Leonid Logvinov
9aef222f79 Add changes to CHANGELOG 2017-10-13 18:59:52 +03:00
Leonid
5591378245 Merge pull request #194 from 0xProject/feature/type-safe-subscriptions
Make logs fetching and subscriptions more type-safe
2017-10-13 17:16:11 +03:00
Leonid Logvinov
dde2268f9f Remove unused code 2017-10-13 13:03:00 +03:00
Leonid Logvinov
0eaca6c691 Make logs fetching and sunscriptions more type-safe 2017-10-13 12:52:59 +03:00
Leonid Logvinov
ba654c04a0 0.21.3 2017-10-12 17:56:13 +03:00
Leonid
f4fbac2694 Merge pull request #193 from 0xProject/fix/allowance-error
Fix an issue causing fills to throw `INSUFFICIENT_TAKER_ALLOWANCE`
2017-10-12 17:51:37 +03:00
Leonid Logvinov
b86f6322e1 Update CHANGELOG 2017-10-12 17:08:46 +03:00
Leonid Logvinov
74c6be3698 Pass correct parameters to validation simulation 2017-10-12 17:02:18 +03:00
Leonid Logvinov
d114613384 Add a regression test 2017-10-12 17:01:55 +03:00
Leonid Logvinov
c23ea1e688 0.21.2 2017-10-11 18:49:26 +03:00
Leonid
f9d4799ebe Merge pull request #190 from 0xProject/fix/export-contract-event-arg
Export ContractEventArg
2017-10-11 18:37:48 +03:00
Leonid Logvinov
9ec4f6dcab Update CHANGELOG 2017-10-11 18:09:10 +03:00
Leonid Logvinov
bcdd063d70 Export ContractEventArg 2017-10-11 18:03:25 +03:00
Leonid Logvinov
22bc7cd692 0.21.1 2017-10-11 15:12:02 +03:00
Leonid
080fe38d1c Merge pull request #189 from 0xProject/fix/getLogsParamsSerialization
Fix a bug in logs fetching
2017-10-11 15:11:40 +03:00
Leonid Logvinov
df32756556 Update CHANGELOG 2017-10-11 14:58:58 +03:00
Leonid Logvinov
d02b7c5fdf Fix a bug in logs fetching 2017-10-11 14:54:49 +03:00
Assaf
c8b54f3bac Use OrderFillRequest interface for batchFillOrKill 2017-10-10 19:52:43 -04:00
Leonid Logvinov
233f97891c 0.21.0 2017-10-10 15:26:46 +03:00
Leonid
056e0f26ab Merge pull request #185 from 0xProject/fix/batch-validation
Fix batch validation
2017-10-10 14:15:57 +03:00
Leonid Logvinov
bda979a6c7 Change tests to test that allowance is checked first 2017-10-10 11:58:18 +03:00
Leonid Logvinov
cfae1a8dfd Throw allowance errors first 2017-10-10 11:48:42 +03:00
Leonid Logvinov
468a20c9ea Remove unused check 2017-10-10 11:48:05 +03:00
Leonid Logvinov
f24c94f1a8 Fix the comment 2017-10-10 11:47:39 +03:00
Leonid Logvinov
ac27937a9c Fix the comment 2017-10-10 11:47:01 +03:00
Leonid Logvinov
2b82354617 Remove redundant constructor 2017-10-10 11:46:33 +03:00
Leonid Logvinov
3fa98ec00e Assign to a variable before assigning 2017-10-10 11:45:57 +03:00
Leonid Logvinov
052fd5783f Change string enum value 2017-10-10 11:44:27 +03:00
Leonid Logvinov
63aa3d0659 Fix CHANGELOG comments 2017-10-10 11:43:55 +03:00
Leonid Logvinov
a4af1065ed Update CHANGELOG 2017-10-09 13:23:51 +03:00
Leonid Logvinov
ef8b2875cf Fix the comment 2017-10-09 13:20:19 +03:00
Leonid Logvinov
1424a7302a Implement transfer Emulator and rewrite tests 2017-10-09 13:07:48 +03:00
Leonid Logvinov
54ac354809 Add types for TradeSide and TransferType 2017-10-06 15:54:17 +03:00
Leonid
f38d2f80a6 Merge pull request #182 from 0xProject/feature/ethereumjs-blockstream
Rewrite subscriptions
2017-10-06 15:24:42 +03:00
Leonid Logvinov
0c112a2a1c Add a hex prefix 2017-10-06 15:13:31 +03:00
Leonid Logvinov
81297b44c6 Add undefined check 2017-10-06 13:15:11 +03:00
Leonid Logvinov
a2cc127ea9 Fix comments 2017-10-06 13:10:45 +03:00
Leonid Logvinov
cfa75ed36c Add a comment 2017-10-06 13:09:14 +03:00
Leonid Logvinov
498cf5333d Fix a typo 2017-10-06 13:08:07 +03:00
Leonid Logvinov
292aab9b18 Use BlockParamLiteral types 2017-10-06 13:07:01 +03:00
Leonid Logvinov
637183e4b2 introduce BlockParamLiteral 2017-10-06 13:04:51 +03:00
Leonid Logvinov
44e2929a4c Check for blockAndLogStreamer to be undefined instead of th filters object to be empty 2017-10-06 13:01:08 +03:00
Leonid Logvinov
1043def46c Install js-sha3 and use it for keccak256 2017-10-06 12:58:17 +03:00
Leonid Logvinov
6af2ba5cff Remove _activeFilters 2017-10-06 12:30:27 +03:00
Leonid
cd5327bc31 Merge pull request #184 from 0xProject/greenkeeper/typedoc-0.9.0
Update typedoc to the latest version 🚀
2017-10-06 12:11:05 +03:00
greenkeeper[bot]
977fe0f8ef chore(package): update typedoc to version 0.9.0 2017-10-06 04:16:50 +00:00
Leonid Logvinov
a406b4d134 Remove unused imports 2017-10-05 17:34:30 +03:00
Leonid Logvinov
1414b8ee8b Add type assertions for callback parameters 2017-10-05 16:32:01 +03:00
Leonid Logvinov
209c31f361 Remove TODOs 2017-10-05 16:28:20 +03:00
Leonid Logvinov
721d969a85 Make it possible to have multiple layers of snapshots 2017-10-05 15:56:28 +03:00
Leonid Logvinov
7bcedc27b8 Update CHANGELOG 2017-10-05 15:43:46 +03:00
Leonid Logvinov
553cbb25f4 Fix comments 2017-10-05 15:35:38 +03:00
Leonid Logvinov
118381c1d1 Move more logic into _stopBlockAndLogStream and _startBlockAndLogStream 2017-10-05 15:35:38 +03:00
Leonid Logvinov
f2100fa36d Remove missing comment 2017-10-05 15:35:38 +03:00
Leonid Logvinov
a537b2e40c Add missing comment 2017-10-05 15:35:37 +03:00
Leonid Logvinov
1b6d3b0f0b Add missing comments 2017-10-05 15:35:37 +03:00
Leonid Logvinov
7dd6352393 Implement subscriptions based on ethereumjs-blockstream 2017-10-05 15:35:37 +03:00
Leonid Logvinov
e37a3155cd Instantiate logAndBlockStreamer 2017-10-05 15:35:37 +03:00
Leonid Logvinov
542cf7b1cb Fix CHANGELOG formatting 2017-10-05 14:55:32 +03:00
472 changed files with 37780 additions and 16015 deletions

28
.circleci/config.yml Normal file
View File

@@ -0,0 +1,28 @@
version: 2
jobs:
build:
docker:
- image: circleci/node:6.12
environment:
CONTRACTS_COMMIT_HASH: '78fe8dd'
steps:
- checkout
- run: echo 'export PATH=$HOME/CIRCLE_PROJECT_REPONAME/node_modules/.bin:$PATH' >> $BASH_ENV
- run:
name: yarn
command: yarn
- save_cache:
key: dependency-cache-{{ checksum "package.json" }}
paths:
- ~/.cache/yarn
- run: wget https://s3.amazonaws.com/testrpc-shapshots/${CONTRACTS_COMMIT_HASH}.zip
- run: unzip ${CONTRACTS_COMMIT_HASH}.zip -d testrpc_snapshot
- run: node ./node_modules/lerna/bin/lerna.js bootstrap
- run: yarn lerna:run bootstrap
- run:
name: testrpc
command: npm run testrpc -- --db testrpc_snapshot
background: true
- run: yarn lerna:run test:circleci
- run: yarn lerna:run lint

8
.gitignore vendored
View File

@@ -58,9 +58,13 @@ typings/
.env
# built library using in commonjs module syntax
lib
lib/
# UMD bundles that export the global variable
_bundles
# generated documentation
docs
generated_docs/
TODO.md
packages/website/public/bundle*

View File

@@ -4,50 +4,25 @@
[0x][website-url] is an open protocol that facilitates trustless, low friction exchange of Ethereum-based assets. A full description of the protocol may be found in our [whitepaper][whitepaper-url].
This repository contains a Javascript library that makes it easy to build Relayers and other DApps that use the 0x protocol.
This repository contains all the 0x developer tools written in TypeScript. Our hope is that these tools make it easy to build Relayers and other DApps that use the 0x protocol.
[website-url]: https://0xproject.com/
[whitepaper-url]: https://0xproject.com/pdfs/0x_white_paper.pdf
[![CircleCI](https://circleci.com/gh/0xProject/0x.js.svg?style=svg&circle-token=61bf7cd8c9b4e11b132089dfcffdd1be277d1e0c)](https://circleci.com/gh/0xProject/0x.js)
[![npm version](https://badge.fury.io/js/0x.js.svg)](https://badge.fury.io/js/0x.js)
[![Coverage Status](https://coveralls.io/repos/github/0xProject/0x.js/badge.svg?branch=master&t=fp0cXD)](https://coveralls.io/github/0xProject/0x.js?branch=master)
[![Slack Status](http://slack.0xProject.com/badge.svg)](http://slack.0xProject.com)
[![Discord](https://img.shields.io/badge/chat-rocket.chat-yellow.svg?style=flat
)](https://chat.0xproject.com)
[![Join the chat at https://gitter.im/0xProject/Lobby](https://badges.gitter.im/0xProject/Lobby.svg)](https://gitter.im/0xProject/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![Greenkeeper badge](https://badges.greenkeeper.io/0xProject/0x.js.svg?token=7c22e5c72acf39d3ead8d29c5d9bb38f9096df3e643024dcedd53ab732847be1&ts=1496426342666)](https://greenkeeper.io/)
## Installation
### Core Packages
0x.js ships as both a [UMD](https://github.com/umdjs/umd) module and a [CommonJS](https://en.wikipedia.org/wiki/CommonJS) package.
#### CommonJS *(recommended)*:
**Install**
```bash
npm install 0x.js --save
```
**Import**
```javascript
import {ZeroEx} from '0x.js';
```
#### UMD:
**Install**
Download the UMD module from our [releases page](https://github.com/0xProject/0x.js/releases) and add it to your project.
**Import**
```html
<script type="text/javascript" src="0x.js"></script>
```
## Documentation
Extensive documentation of 0x.js can be found on [our website][docs-url].
[website-url]: https://0xproject.com/
[whitepaper-url]: https://0xproject.com/pdfs/0x_white_paper.pdf
[docs-url]: https://0xproject.com/docs/0xjs
| Package | Version | Description |
|--------|-------|------------|
| [`0x.js`](/packages/0x.js) | [![npm](https://img.shields.io/npm/v/0x.js.svg?maxAge=2592000)](https://www.npmjs.com/package/0x.js) | A Javascript library for interacting with the 0x protocol |
| [`@0xproject/assert`](/packages/assert) | [![npm](https://img.shields.io/npm/v/@0xproject/assert.svg?maxAge=2592000)](https://www.npmjs.com/package/@0xproject/assert) | Standard type and schema assertions |
| [`@0xproject/connect`](/packages/connect) | [![npm](https://img.shields.io/npm/v/@0xproject/connect.svg?maxAge=2592000)](https://www.npmjs.com/package/@0xproject/connect) | A Javascript library for interacting with the standard relayer api |
| [`@0xproject/json-schemas`](/packages/json-schemas) | [![npm](https://img.shields.io/npm/v/@0xproject/json-schemas.svg?maxAge=2592000)](https://www.npmjs.com/package/@0xproject/json-schemas) | 0x-related json schemas |
| [`@0xproject/tslint-config`](/packages/tslint-config) | [![npm](https://img.shields.io/npm/v/@0xproject/tslint-config.svg?maxAge=2592000)](https://www.npmjs.com/package/@0xproject/tslint-config) | Custom 0x project TSLint rules |

View File

@@ -1,23 +0,0 @@
machine:
node:
version: 6.5.0
environment:
CONTRACTS_COMMIT_HASH: '35053f9'
PATH: "${PATH}:${HOME}/${CIRCLE_PROJECT_REPONAME}/node_modules/.bin"
dependencies:
override:
- yarn
cache_directories:
- ~/.cache/yarn
test:
override:
- wget https://s3.amazonaws.com/testrpc-shapshots/${CONTRACTS_COMMIT_HASH}.zip
- unzip ${CONTRACTS_COMMIT_HASH}.zip -d testrpc_snapshot
- npm run testrpc -- --db testrpc_snapshot:
background: true
- yarn test:coverage
- yarn report_test_coverage
- if [ $CIRCLE_BRANCH = "master" ]; then yarn test:umd; fi
- yarn lint

9
lerna.json Normal file
View File

@@ -0,0 +1,9 @@
{
"lerna": "2.5.1",
"packages": [
"packages/*"
],
"version": "independent",
"npmClient": "yarn",
"useWorkspaces": true
}

10156
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,104 +1,22 @@
{
"name": "0x.js",
"version": "0.20.0",
"description": "A javascript library for interacting with the 0x protocol",
"keywords": [
"0x.js",
"0xproject",
"ethereum",
"tokens",
"exchange"
],
"main": "lib/src/index.js",
"types": "lib/src/index.d.ts",
"scripts": {
"prebuild": "npm run clean",
"build": "run-p build:umd:prod build:commonjs",
"prepublishOnly": "run-p build",
"postpublish": "run-s release docs:json upload_docs_json",
"release": "publish-release --assets _bundles/index.js,_bundles/index.min.js --tag $(git describe --tags) --owner 0xProject --repo 0x.js",
"upload_docs_json": "aws s3 cp docs/index.json s3://0xjs-docs-jsons/$(git describe --tags).json --profile 0xproject --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --content-type aplication/json",
"lint": "tslint src/*.ts test/*.ts",
"test": "run-s clean test:commonjs",
"test:umd": "./scripts/test_umd.sh",
"test:coverage": "nyc npm run test --all",
"report_test_coverage": "nyc report --reporter=text-lcov | coveralls",
"update_contracts": "for i in ${npm_package_config_artifacts}; do copyfiles -u 4 ../contracts/build/contracts/$i.json ../0x.js/src/artifacts; done;",
"testrpc": "testrpc -p 8545 --networkId 50 -m \"${npm_package_config_mnemonic}\"",
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json docs/index.json .",
"docs:generate": "typedoc --out docs .",
"docs:open": "opn docs/index.html",
"clean": "shx rm -rf _bundles lib test_temp",
"build:umd:dev": "webpack",
"build:umd:prod": "NODE_ENV=production webpack",
"build:commonjs": "tsc; copyfiles -u 2 './src/artifacts/**/*.json' ./lib/src/artifacts;",
"test:commonjs": "run-s build:commonjs run_mocha",
"pretest:umd": "run-s clean build:umd:dev build:commonjs",
"substitute_umd_bundle": "npm run remove_src_files_not_used_by_tests; shx mv _bundles/* lib/src",
"remove_src_files_not_used_by_tests": "find ./lib/src \\( -path ./lib/src/utils -o -path ./lib/src/subproviders -o -path ./lib/src/schemas -o -path \"./lib/src/types.*\" \\) -prune -o -type f -print | xargs rm",
"run_mocha": "mocha lib/test/**/*_test.js --timeout 5000 --bail --exit"
},
"config": {
"artifacts": "TokenTransferProxy Exchange TokenRegistry Token EtherToken",
"mnemonic": "concert load couple harbor equip island argue ramp clarify fence smart topic"
},
"repository": {
"type": "git",
"url": "https://github.com/0xProject/0x.js"
},
"license": "Apache-2.0",
"engines": {
"node": ">=6.0.0"
},
"devDependencies": {
"@types/jsonschema": "^1.1.1",
"@types/lodash": "^4.14.64",
"@types/mocha": "^2.2.41",
"@types/node": "^8.0.1",
"@types/sinon": "^2.2.2",
"awesome-typescript-loader": "^3.1.3",
"bignumber.js": "^4.0.2",
"chai": "^4.0.1",
"chai-as-promised": "^7.1.0",
"chai-as-promised-typescript-typings": "0.0.3",
"chai-bignumber": "^2.0.1",
"chai-typescript-typings": "^0.0.0",
"copyfiles": "^1.2.0",
"coveralls": "^3.0.0",
"dirty-chai": "^2.0.1",
"ethereumjs-testrpc": "4.0.1",
"json-loader": "^0.5.4",
"mocha": "^4.0.0",
"npm-run-all": "^4.0.2",
"nyc": "^11.0.1",
"opn-cli": "^3.1.0",
"request": "^2.81.0",
"request-promise-native": "^1.0.4",
"shx": "^0.2.2",
"sinon": "^4.0.0",
"source-map-support": "^0.5.0",
"truffle-hdwallet-provider": "^0.0.3",
"tslint": "^5.3.2",
"tslint-config-0xproject": "^0.0.2",
"typedoc": "^0.8.0",
"types-bn": "^0.0.1",
"types-ethereumjs-util": "0xProject/types-ethereumjs-util",
"typescript": "^2.4.1",
"web3-provider-engine": "^13.0.1",
"web3-typescript-typings": "^0.6.2",
"webpack": "^3.1.0"
},
"dependencies": {
"@types/bignumber.js": "^4.0.2",
"0x-json-schemas": "^0.6.1",
"bignumber.js": "^4.0.2",
"compare-versions": "^3.0.1",
"es6-promisify": "^5.0.0",
"ethereumjs-abi": "^0.6.4",
"ethereumjs-util": "^5.1.1",
"find-versions": "^2.0.0",
"lodash": "^4.17.4",
"publish-release": "^1.3.3",
"web3": "^0.20.0"
}
"private": true,
"name": "0x.js",
"workspaces": [
"packages/*"
],
"scripts": {
"testrpc": "testrpc -p 8545 --networkId 50 -m \"${npm_package_config_mnemonic}\"",
"lerna:run": "lerna run",
"lerna:publish": "lerna run clean; lerna run build; lerna publish --registry=https://registry.npmjs.org/"
},
"config": {
"mnemonic": "concert load couple harbor equip island argue ramp clarify fence smart topic"
},
"devDependencies": {
"lerna": "^2.5.1",
"async-child-process": "^1.1.1",
"semver-sort": "^0.0.4",
"publish-release": "0xproject/publish-release",
"es6-promisify": "^5.0.0"
}
}

View File

@@ -1,19 +1,108 @@
# CHANGELOG
v0.20.0 - _October 3, 2017_
v0.27.0 - _November 28, 2017_
------------------------
* Make `ZeroExConfig` required parameter of `ZeroEx` constructor (#233)
* Add a required property `networkId` to `ZeroExConfig` (#233)
* Make all `getContractAddress` functions, `zeroEx.exchange.subscribe`, `zeroEx.exchange.getZRXTokenAddress` sync (#233)
* Remove `ZeroExError.ContractNotFound` and replace it with contract-specific errors (#233)
* Make `DecodedLogEvent<A>` contain `LogWithDecodedArgs<A>` under log key instead of merging it in like web3 does (#234)
* Rename `removed` to `isRemoved` in `DecodedLogEvent<A>` (#234)
* Add config allowing to specify gasPrice and gasLimit for every transaction sending method (#235)
* All transaction sending methods now call `estimateGas` if no gas amount was supplied (#235)
* Modify order validation methods to validate against the `latest` block, not against the `pending` block (#236)
v0.26.0 - _November 21, 2017_
------------------------
* Add post-formatter for logs converting `blockNumber`, `logIndex`, `transactionIndex` from hexes to numbers (#231)
* Remove support for Async callback types when used in Subscribe functions (#222)
* In OrderWatcher subscribe to ZRX Token Transfer and Approval events when maker token is different (#225)
v0.25.1 - _November 13, 2017_
------------------------
* Standardise on Cancelled over Canceled (#217)
* Add missing `DecodedLogEvent` type to exported types (#205)
* Normalized the transactionReceipt status to be `null|0|1`, 1 meaning transaction execution successful, 0 unsuccessful and `null` if it is a pre-byzantinium transaction. (#200)
v0.23.0 - _November 12, 2017_
------------------------
* Fixed unhandled promise rejection error in subscribe methods (#209)
* Subscribe callbacks now receive an error object as their first argument
v0.22.6 - _November 10, 2017_
------------------------
* Add a timeout parameter to transaction awaiting (#206)
v0.22.5 - _November 7, 2017_
------------------------
* Re-publish v0.22.4 to fix publishing issue
v0.22.4 - _October 25, 2017_
------------------------
* Upgraded bignumber.js to a new version that ships with native typings
v0.22.3 - _October 25, 2017_
------------------------
* Fixed an issue with new version of testrpc and unlimited proxy allowance (#199)
v0.22.2 - _October 24, 2017_
------------------------
* Fixed rounding of maker fill amount and incorrect validation of partial fees (#197)
v0.22.0 - _October 16, 2017_
------------------------
* Started using `OrderFillRequest` interface instead of `OrderFillOrKillRequest` interface for `zeroEx.exchange.batchFillOrKill` (#187)
* Removed `OrderFillOrKillRequest` (#187)
v0.21.4 - _October 13, 2017_
------------------------
* Made 0x.js more type-safe by making `getLogsAsync` and `subscribe/subscribeAsync` generics parametrized with arg type (#194)
v0.21.3 - _October 12, 2017_
------------------------
* Fixed a bug causing order fills to throw `INSUFFICIENT_TAKER_ALLOWANCE` (#193)
v0.21.2 - _October 11, 2017_
------------------------
* Exported `ContractEventArg` as a public type (#190)
v0.21.1 - _October 11, 2017_
------------------------
* Fixed a bug in subscriptions (#189)
v0.21.0 - _October 10, 2017_
------------------------
* Complete rewrite of subscription logic (#182)
* Subscriptions no longer return historical logs. If you want them - use `getLogsAsync`
* Subscriptions now use [ethereumjs-blockstream](https://github.com/ethereumjs/ethereumjs-blockstream) under the hood
* Subscriptions correctly handle block re-orgs (forks)
* Subscriptions correctly backfill logs (connection problems)
* They no longer setup filters on the underlying nodes, so you can use them with infura without a filter Subprovider
* Removed `ContractEventEmitter` and added `LogEvent`
* Renamed `zeroEx.token.subscribeAsync` to `zeroEx.token.subscribe`
* Added `zeroEx.token.unsubscribe` and `zeroEx.exchange.unsubscribe`
* Renamed `zeroEx.exchange.stopWatchingAllEventsAsync` to `zeroEx.exhange.unsubscribeAll`
* Renamed `zeroEx.token.stopWatchingAllEventsAsync` to `zeroEx.token.unsubscribeAll`
* Fixed the batch fills validation by emulating all balance & proxy allowance changes (#185)
v0.20.0 - _October 5, 2017_
------------------------
* Add `zeroEx.token.getLogsAsync` (#178)
* Add `zeroEx.exchange.getLogsAsync` (#178)
* Fixed fees validation when one of the tokens transferred is ZRX (#181)
v0.19.0 - _September 29, 2017_
------------------------
* Made order validation optional (#172)
* Added Ropsten testnet support (#173)
* Fixed a bug causing awaitTransactionMinedAsync to DDos backend nodes (#175)
v0.18.0 - _September 26, 2017_
------------------------
* Added `zeroEx.exchange.validateOrderFillableOrThrowAsync` to simplify orderbook pruning (#170)
v0.17.0 - _September 26, 2017_
------------------------
* Made `zeroEx.exchange.getZRXTokenAddressAsync` public (#171)
v0.16.0 - _September 20, 2017_

40
packages/0x.js/README.md Normal file
View File

@@ -0,0 +1,40 @@
0x.js
-----
## Installation
0x.js ships as both a [UMD](https://github.com/umdjs/umd) module and a [CommonJS](https://en.wikipedia.org/wiki/CommonJS) package.
#### CommonJS *(recommended)*:
**Install**
```bash
npm install 0x.js --save
```
**Import**
```javascript
import {ZeroEx} from '0x.js';
```
#### UMD:
**Install**
Download the UMD module from our [releases page](https://github.com/0xProject/0x.js/releases) and add it to your project.
**Import**
```html
<script type="text/javascript" src="0x.js"></script>
```
## Documentation
Extensive documentation of 0x.js can be found on [our website][docs-url].
[website-url]: https://0xproject.com/
[whitepaper-url]: https://0xproject.com/pdfs/0x_white_paper.pdf
[docs-url]: https://0xproject.com/docs/0xjs

102
packages/0x.js/package.json Normal file
View File

@@ -0,0 +1,102 @@
{
"name": "0x.js",
"version": "0.26.1",
"description": "A javascript library for interacting with the 0x protocol",
"keywords": [
"0x.js",
"0xproject",
"ethereum",
"tokens",
"exchange"
],
"main": "lib/src/index.js",
"types": "lib/src/index.d.ts",
"scripts": {
"prebuild": "npm run clean",
"build": "run-p build:umd:prod build:commonjs; exit 0;",
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_DIR",
"upload_docs_json": "aws s3 cp generated_docs/index.json $S3_URL --profile 0xproject --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --content-type application/json",
"lint": "tslint --project . 'src/**/*.ts' 'test/**/*.ts'",
"test:circleci": "run-s test:coverage report_test_coverage && if [ $CIRCLE_BRANCH = \"development\" ]; then yarn test:umd; fi",
"test": "run-s clean test:commonjs",
"test:umd": "./scripts/test_umd.sh",
"test:coverage": "nyc npm run test --all",
"report_test_coverage": "nyc report --reporter=text-lcov | coveralls",
"update_contracts": "for i in ${npm_package_config_artifacts}; do copyfiles -u 4 ../contracts/build/contracts/$i.json ../0x.js/src/artifacts; done;",
"clean": "shx rm -rf _bundles lib test_temp",
"build:umd:dev": "webpack",
"build:umd:prod": "NODE_ENV=production webpack",
"build:commonjs": "tsc && copyfiles -u 2 './src/artifacts/**/*.json' ./lib/src/artifacts;",
"test:commonjs": "run-s build:commonjs run_mocha",
"pretest:umd": "run-s clean build:umd:dev build:commonjs",
"substitute_umd_bundle": "shx mv _bundles/* lib/src",
"run_mocha": "mocha lib/test/**/*_test.js --timeout 5000 --bail --exit"
},
"config": {
"artifacts": "TokenTransferProxy Exchange TokenRegistry Token EtherToken"
},
"repository": {
"type": "git",
"url": "https://github.com/0xProject/0x.js"
},
"license": "Apache-2.0",
"engines": {
"node": ">=6.0.0"
},
"devDependencies": {
"@0xproject/tslint-config": "^0.1.1",
"@types/bintrees": "^1.0.2",
"@types/jsonschema": "^1.1.1",
"@types/lodash": "^4.14.64",
"@types/mocha": "^2.2.41",
"@types/node": "^8.0.1",
"@types/sinon": "^2.2.2",
"@types/uuid": "^3.4.2",
"awesome-typescript-loader": "^3.1.3",
"chai": "^4.0.1",
"chai-as-promised": "^7.1.0",
"chai-as-promised-typescript-typings": "0.0.3",
"chai-bignumber": "^2.0.1",
"chai-typescript-typings": "^0.0.1",
"copyfiles": "^1.2.0",
"coveralls": "^3.0.0",
"dirty-chai": "^2.0.1",
"ethereumjs-testrpc": "6.0.3",
"json-loader": "^0.5.4",
"mocha": "^4.0.0",
"npm-run-all": "^4.0.2",
"nyc": "^11.0.1",
"opn-cli": "^3.1.0",
"request": "^2.81.0",
"request-promise-native": "^1.0.4",
"shx": "^0.2.2",
"sinon": "^4.0.0",
"source-map-support": "^0.5.0",
"truffle-hdwallet-provider": "^0.0.3",
"tslint": "5.8.0",
"typedoc": "~0.8.0",
"types-bn": "^0.0.1",
"types-ethereumjs-util": "0xProject/types-ethereumjs-util",
"typescript": "~2.6.1",
"web3-provider-engine": "^13.0.1",
"web3-typescript-typings": "^0.7.1",
"webpack": "^3.1.0"
},
"dependencies": {
"@0xproject/assert": "^0.0.5",
"@0xproject/json-schemas": "^0.6.8",
"bignumber.js": "~4.1.0",
"bintrees": "^1.0.2",
"bn.js": "4.11.8",
"compare-versions": "^3.0.1",
"es6-promisify": "^5.0.0",
"ethereumjs-abi": "^0.6.4",
"ethereumjs-blockstream": "^2.0.6",
"ethereumjs-util": "^5.1.1",
"find-versions": "^2.0.0",
"js-sha3": "^0.6.1",
"lodash": "^4.17.4",
"uuid": "^3.1.0",
"web3": "^0.20.0"
}
}

View File

@@ -0,0 +1,44 @@
const execAsync = require('async-child-process').execAsync;
const postpublish_utils = require('../../../scripts/postpublish_utils');
const packageJSON = require('../package.json');
const cwd = __dirname + '/..';
const subPackageName = packageJSON.name;
const S3BucketPath = 's3://0xjs-docs-jsons/';
let tag;
let version;
postpublish_utils.getLatestTagAndVersionAsync(subPackageName)
.then(function(result) {
tag = result.tag;
version = result.version;
const releaseName = postpublish_utils.getReleaseName(subPackageName, version);
const assets = [
__dirname + '/../_bundles/index.js',
__dirname + '/../_bundles/index.min.js',
];
return postpublish_utils.publishReleaseNotes(tag, releaseName, assets);
})
.then(function(release) {
console.log('POSTPUBLISH: Release successful, generating docs...');
const jsonFilePath = __dirname + '/../' + postpublish_utils.generatedDocsDirectoryName + '/index.json';
return execAsync(
'JSON_FILE_PATH=' + jsonFilePath + ' PROJECT_DIR=' + __dirname + '/.. yarn docs:json',
{
cwd,
}
);
})
.then(function(result) {
if (result.stderr !== '') {
throw new Error(result.stderr);
}
const fileName = 'v' + version + '.json';
console.log('POSTPUBLISH: Doc generation successful, uploading docs... as ', fileName);
const s3Url = S3BucketPath + fileName;
return execAsync('S3_URL=' + s3Url + ' yarn upload_docs_json', {
cwd,
});
}).catch (function(err) {
throw err;
});

View File

@@ -3,5 +3,4 @@
# UMD tests should only be run after building the commonjs because they reuse some of the commonjs build artifacts
run-s substitute_umd_bundle run_mocha
return_code=$?
npm run clean
exit $return_code

View File

@@ -1,40 +1,35 @@
import * as _ from 'lodash';
import * as BigNumber from 'bignumber.js';
import * as Web3 from 'web3';
import * as abiDecoder from 'abi-decoder';
import {SchemaValidator, schemas} from '0x-json-schemas';
import {bigNumberConfigs} from './bignumber_config';
import {schemas, SchemaValidator} from '@0xproject/json-schemas';
import BigNumber from 'bignumber.js';
import * as ethUtil from 'ethereumjs-util';
import findVersions = require('find-versions');
import compareVersions = require('compare-versions');
import {Web3Wrapper} from './web3_wrapper';
import {constants} from './utils/constants';
import {utils} from './utils/utils';
import {signatureUtils} from './utils/signature_utils';
import {assert} from './utils/assert';
import {AbiDecoder} from './utils/abi_decoder';
import {intervalUtils} from './utils/interval_utils';
import * as _ from 'lodash';
import {artifacts} from './artifacts';
import {bigNumberConfigs} from './bignumber_config';
import {EtherTokenWrapper} from './contract_wrappers/ether_token_wrapper';
import {ExchangeWrapper} from './contract_wrappers/exchange_wrapper';
import {TokenRegistryWrapper} from './contract_wrappers/token_registry_wrapper';
import {EtherTokenWrapper} from './contract_wrappers/ether_token_wrapper';
import {TokenWrapper} from './contract_wrappers/token_wrapper';
import {TokenTransferProxyWrapper} from './contract_wrappers/token_transfer_proxy_wrapper';
import {TokenWrapper} from './contract_wrappers/token_wrapper';
import {OrderStateWatcher} from './order_watcher/order_state_watcher';
import {zeroExConfigSchema} from './schemas/zero_ex_config_schema';
import {
ECSignature,
ZeroExError,
Order,
OrderStateWatcherConfig,
SignedOrder,
TransactionReceiptWithDecodedLogs,
Web3Provider,
ZeroExConfig,
TransactionReceipt,
DecodedLogArgs,
TransactionReceiptWithDecodedLogs,
LogWithDecodedArgs,
FilterObject,
RawLog,
ZeroExError,
} from './types';
import {zeroExConfigSchema} from './schemas/zero_ex_config_schema';
import {AbiDecoder} from './utils/abi_decoder';
import {assert} from './utils/assert';
import {constants} from './utils/constants';
import {intervalUtils} from './utils/interval_utils';
import {OrderStateUtils} from './utils/order_state_utils';
import {signatureUtils} from './utils/signature_utils';
import {utils} from './utils/utils';
import {Web3Wrapper} from './web3_wrapper';
// Customize our BigNumber instances
bigNumberConfigs.configure();
@@ -74,6 +69,11 @@ export class ZeroEx {
* tokenTransferProxy smart contract.
*/
public proxy: TokenTransferProxyWrapper;
/**
* An instance of the OrderStateWatcher class containing methods for watching a set of orders for relevant
* blockchain state changes.
*/
public orderStateWatcher: OrderStateWatcher;
private _web3Wrapper: Web3Wrapper;
private _abiDecoder: AbiDecoder;
/**
@@ -89,19 +89,8 @@ export class ZeroEx {
assert.doesConformToSchema('signature', signature, schemas.ecSignatureSchema);
assert.isETHAddressHex('signerAddress', signerAddress);
const dataBuff = ethUtil.toBuffer(data);
const msgHashBuff = ethUtil.hashPersonalMessage(dataBuff);
try {
const pubKey = ethUtil.ecrecover(
msgHashBuff,
signature.v,
ethUtil.toBuffer(signature.r),
ethUtil.toBuffer(signature.s));
const retrievedAddress = ethUtil.bufferToHex(ethUtil.pubToAddress(pubKey));
return retrievedAddress === signerAddress;
} catch (err) {
return false;
}
const isValidSignature = signatureUtils.isValidSignature(data, signature, signerAddress);
return isValidSignature;
}
/**
* Generates a pseudo-random 256-bit salt.
@@ -109,7 +98,7 @@ export class ZeroEx {
* and will not collide with other outstanding orders that are identical in all other parameters.
* @return A pseudo-random 256-bit number that can be used as a salt.
*/
public static generatePseudoRandomSalt(): BigNumber.BigNumber {
public static generatePseudoRandomSalt(): BigNumber {
// BigNumber.random returns a pseudo-random number between 0 & 1 with a passed in number of decimal places.
// Source: https://mikemcl.github.io/bignumber.js/#random
const randomNumber = BigNumber.random(constants.MAX_DIGITS_IN_UNSIGNED_256_INT);
@@ -140,7 +129,7 @@ export class ZeroEx {
* @param decimals The number of decimal places the unit amount has.
* @return The amount in units.
*/
public static toUnitAmount(amount: BigNumber.BigNumber, decimals: number): BigNumber.BigNumber {
public static toUnitAmount(amount: BigNumber, decimals: number): BigNumber {
assert.isBigNumber('amount', amount);
assert.isNumber('decimals', decimals);
@@ -156,7 +145,7 @@ export class ZeroEx {
* @param decimals The number of decimal places the unit amount has.
* @return The amount in baseUnits.
*/
public static toBaseUnitAmount(amount: BigNumber.BigNumber, decimals: number): BigNumber.BigNumber {
public static toBaseUnitAmount(amount: BigNumber, decimals: number): BigNumber {
assert.isBigNumber('amount', amount);
assert.isNumber('decimals', decimals);
@@ -181,58 +170,48 @@ export class ZeroEx {
* @param config The configuration object. Look up the type for the description.
* @return An instance of the 0x.js ZeroEx class.
*/
constructor(provider: Web3Provider, config?: ZeroExConfig) {
constructor(provider: Web3Provider, config: ZeroExConfig) {
assert.isWeb3Provider('provider', provider);
if (!_.isUndefined(config)) {
assert.doesConformToSchema('config', config, zeroExConfigSchema);
}
if (_.isUndefined((provider as any).sendAsync)) {
// Web3@1.0 provider doesn't support synchronous http requests,
// so it only has an async `send` method, instead of a `send` and `sendAsync` in web3@0.x.x`
// We re-assign the send method so that Web3@1.0 providers work with 0x.js
(provider as any).sendAsync = (provider as any).send;
}
assert.doesConformToSchema('config', config, zeroExConfigSchema);
const artifactJSONs = _.values(artifacts);
const abiArrays = _.map(artifactJSONs, artifact => artifact.abi);
this._abiDecoder = new AbiDecoder(abiArrays);
const gasPrice = _.isUndefined(config) ? undefined : config.gasPrice;
const defaults = {
gasPrice,
gasPrice: config.gasPrice,
};
this._web3Wrapper = new Web3Wrapper(provider, defaults);
this._web3Wrapper = new Web3Wrapper(provider, config.networkId, defaults);
this.proxy = new TokenTransferProxyWrapper(
this._web3Wrapper,
config.tokenTransferProxyContractAddress,
);
this.token = new TokenWrapper(
this._web3Wrapper,
this._abiDecoder,
this._getTokenTransferProxyAddressAsync.bind(this),
this.proxy,
);
const exchageContractAddressIfExists = _.isUndefined(config) ? undefined : config.exchangeContractAddress;
this.exchange = new ExchangeWrapper(
this._web3Wrapper,
this._abiDecoder,
this.token,
exchageContractAddressIfExists,
config.exchangeContractAddress,
);
this.proxy = new TokenTransferProxyWrapper(
this._web3Wrapper,
this._getTokenTransferProxyAddressAsync.bind(this),
this.tokenRegistry = new TokenRegistryWrapper(this._web3Wrapper, config.tokenRegistryContractAddress);
this.etherToken = new EtherTokenWrapper(this._web3Wrapper, this.token, config.etherTokenContractAddress);
this.orderStateWatcher = new OrderStateWatcher(
this._web3Wrapper, this._abiDecoder, this.token, this.exchange, config.orderWatcherConfig,
);
const tokenRegistryContractAddressIfExists = _.isUndefined(config) ?
undefined :
config.tokenRegistryContractAddress;
this.tokenRegistry = new TokenRegistryWrapper(this._web3Wrapper, tokenRegistryContractAddressIfExists);
const etherTokenContractAddressIfExists = _.isUndefined(config) ? undefined : config.etherTokenContractAddress;
this.etherToken = new EtherTokenWrapper(this._web3Wrapper, this.token, etherTokenContractAddressIfExists);
}
/**
* Sets a new web3 provider for 0x.js. Updating the provider will stop all
* subscriptions so you will need to re-subscribe to all events relevant to your app after this call.
* @param provider The Web3Provider you would like the 0x.js library to use from now on.
* @param networkId The id of the network your provider is connected to
*/
public async setProviderAsync(provider: Web3Provider) {
this._web3Wrapper.setProvider(provider);
await (this.exchange as any)._invalidateContractInstancesAsync();
public setProvider(provider: Web3Provider, networkId: number): void {
this._web3Wrapper.setProvider(provider, networkId);
(this.exchange as any)._invalidateContractInstances();
(this.tokenRegistry as any)._invalidateContractInstance();
await (this.token as any)._invalidateContractInstancesAsync();
(this.token as any)._invalidateContractInstances();
(this.proxy as any)._invalidateContractInstance();
(this.etherToken as any)._invalidateContractInstance();
}
@@ -298,13 +277,24 @@ export class ZeroEx {
* Waits for a transaction to be mined and returns the transaction receipt.
* @param txHash Transaction hash
* @param pollingIntervalMs How often (in ms) should we check if the transaction is mined.
* @param timeoutMs How long (in ms) to poll for transaction mined until aborting.
* @return Transaction receipt with decoded log args.
*/
public async awaitTransactionMinedAsync(
txHash: string, pollingIntervalMs: number = 1000): Promise<TransactionReceiptWithDecodedLogs> {
txHash: string, pollingIntervalMs = 1000, timeoutMs?: number): Promise<TransactionReceiptWithDecodedLogs> {
let timeoutExceeded = false;
if (timeoutMs) {
setTimeout(() => timeoutExceeded = true, timeoutMs);
}
const txReceiptPromise = new Promise(
(resolve: (receipt: TransactionReceiptWithDecodedLogs) => void, reject) => {
const intervalId = intervalUtils.setAsyncExcludingInterval(async () => {
if (timeoutExceeded) {
intervalUtils.clearAsyncExcludingInterval(intervalId);
return reject(ZeroExError.TransactionMiningTimeout);
}
const transactionReceipt = await this._web3Wrapper.getTransactionReceiptAsync(txHash);
if (!_.isNull(transactionReceipt)) {
intervalUtils.clearAsyncExcludingInterval(intervalId);
@@ -320,6 +310,7 @@ export class ZeroEx {
}
}, pollingIntervalMs);
});
return txReceiptPromise;
}
/*

View File

@@ -1,11 +1,13 @@
import {Artifact} from './types';
import * as TokenArtifact from './artifacts/Token.json';
import * as ExchangeArtifact from './artifacts/Exchange.json';
import * as EtherTokenArtifact from './artifacts/EtherToken.json';
import * as ExchangeArtifact from './artifacts/Exchange.json';
import * as TokenArtifact from './artifacts/Token.json';
import * as TokenRegistryArtifact from './artifacts/TokenRegistry.json';
import * as TokenTransferProxyArtifact from './artifacts/TokenTransferProxy.json';
import * as ZRXArtifact from './artifacts/ZRX.json';
import {Artifact} from './types';
export const artifacts = {
ZRXArtifact: ZRXArtifact as any as Artifact,
TokenArtifact: TokenArtifact as any as Artifact,
ExchangeArtifact: ExchangeArtifact as any as Artifact,
EtherTokenArtifact: EtherTokenArtifact as any as Artifact,

View File

@@ -0,0 +1,250 @@
{
"contract_name": "EtherToken",
"abi": [
{
"constant": true,
"inputs": [],
"name": "name",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_spender",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_from",
"type": "address"
},
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "amount",
"type": "uint256"
}
],
"name": "withdraw",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "decimals",
"outputs": [
{
"name": "",
"type": "uint8"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "symbol",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [],
"name": "deposit",
"outputs": [],
"payable": true,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
},
{
"name": "_spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"payable": true,
"type": "fallback"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_from",
"type": "address"
},
{
"indexed": true,
"name": "_to",
"type": "address"
},
{
"indexed": false,
"name": "_value",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_owner",
"type": "address"
},
{
"indexed": true,
"name": "_spender",
"type": "address"
},
{
"indexed": false,
"name": "_value",
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
}
],
"networks": {
"1": {
"address": "0x2956356cd2a2bf3202f771f50d3d14a367b48070"
},
"3": {
"address": "0xc00fd9820cd2898cc4c054b7bf142de637ad129a"
},
"42": {
"address": "0x05d090b51c40b020eab3bfcb6a2dff130df22e9c"
},
"50": {
"address": "0x48bacb9266a570d521063ef5dd96e61686dbe788"
}
}
}

View File

@@ -0,0 +1,607 @@
{
"contract_name": "Exchange",
"abi": [
{
"constant": true,
"inputs": [
{
"name": "numerator",
"type": "uint256"
},
{
"name": "denominator",
"type": "uint256"
},
{
"name": "target",
"type": "uint256"
}
],
"name": "isRoundingError",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "",
"type": "bytes32"
}
],
"name": "filled",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "",
"type": "bytes32"
}
],
"name": "cancelled",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5][]"
},
{
"name": "orderValues",
"type": "uint256[6][]"
},
{
"name": "fillTakerTokenAmount",
"type": "uint256"
},
{
"name": "shouldThrowOnInsufficientBalanceOrAllowance",
"type": "bool"
},
{
"name": "v",
"type": "uint8[]"
},
{
"name": "r",
"type": "bytes32[]"
},
{
"name": "s",
"type": "bytes32[]"
}
],
"name": "fillOrdersUpTo",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5]"
},
{
"name": "orderValues",
"type": "uint256[6]"
},
{
"name": "cancelTakerTokenAmount",
"type": "uint256"
}
],
"name": "cancelOrder",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "ZRX_TOKEN_CONTRACT",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5][]"
},
{
"name": "orderValues",
"type": "uint256[6][]"
},
{
"name": "fillTakerTokenAmounts",
"type": "uint256[]"
},
{
"name": "v",
"type": "uint8[]"
},
{
"name": "r",
"type": "bytes32[]"
},
{
"name": "s",
"type": "bytes32[]"
}
],
"name": "batchFillOrKillOrders",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5]"
},
{
"name": "orderValues",
"type": "uint256[6]"
},
{
"name": "fillTakerTokenAmount",
"type": "uint256"
},
{
"name": "v",
"type": "uint8"
},
{
"name": "r",
"type": "bytes32"
},
{
"name": "s",
"type": "bytes32"
}
],
"name": "fillOrKillOrder",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "orderHash",
"type": "bytes32"
}
],
"name": "getUnavailableTakerTokenAmount",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "signer",
"type": "address"
},
{
"name": "hash",
"type": "bytes32"
},
{
"name": "v",
"type": "uint8"
},
{
"name": "r",
"type": "bytes32"
},
{
"name": "s",
"type": "bytes32"
}
],
"name": "isValidSignature",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "numerator",
"type": "uint256"
},
{
"name": "denominator",
"type": "uint256"
},
{
"name": "target",
"type": "uint256"
}
],
"name": "getPartialAmount",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "TOKEN_TRANSFER_PROXY_CONTRACT",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5][]"
},
{
"name": "orderValues",
"type": "uint256[6][]"
},
{
"name": "fillTakerTokenAmounts",
"type": "uint256[]"
},
{
"name": "shouldThrowOnInsufficientBalanceOrAllowance",
"type": "bool"
},
{
"name": "v",
"type": "uint8[]"
},
{
"name": "r",
"type": "bytes32[]"
},
{
"name": "s",
"type": "bytes32[]"
}
],
"name": "batchFillOrders",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5][]"
},
{
"name": "orderValues",
"type": "uint256[6][]"
},
{
"name": "cancelTakerTokenAmounts",
"type": "uint256[]"
}
],
"name": "batchCancelOrders",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5]"
},
{
"name": "orderValues",
"type": "uint256[6]"
},
{
"name": "fillTakerTokenAmount",
"type": "uint256"
},
{
"name": "shouldThrowOnInsufficientBalanceOrAllowance",
"type": "bool"
},
{
"name": "v",
"type": "uint8"
},
{
"name": "r",
"type": "bytes32"
},
{
"name": "s",
"type": "bytes32"
}
],
"name": "fillOrder",
"outputs": [
{
"name": "filledTakerTokenAmount",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "orderAddresses",
"type": "address[5]"
},
{
"name": "orderValues",
"type": "uint256[6]"
}
],
"name": "getOrderHash",
"outputs": [
{
"name": "",
"type": "bytes32"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "EXTERNAL_QUERY_GAS_LIMIT",
"outputs": [
{
"name": "",
"type": "uint16"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "VERSION",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"type": "function"
},
{
"inputs": [
{
"name": "_zrxToken",
"type": "address"
},
{
"name": "_tokenTransferProxy",
"type": "address"
}
],
"payable": false,
"type": "constructor"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "maker",
"type": "address"
},
{
"indexed": false,
"name": "taker",
"type": "address"
},
{
"indexed": true,
"name": "feeRecipient",
"type": "address"
},
{
"indexed": false,
"name": "makerToken",
"type": "address"
},
{
"indexed": false,
"name": "takerToken",
"type": "address"
},
{
"indexed": false,
"name": "filledMakerTokenAmount",
"type": "uint256"
},
{
"indexed": false,
"name": "filledTakerTokenAmount",
"type": "uint256"
},
{
"indexed": false,
"name": "paidMakerFee",
"type": "uint256"
},
{
"indexed": false,
"name": "paidTakerFee",
"type": "uint256"
},
{
"indexed": true,
"name": "tokens",
"type": "bytes32"
},
{
"indexed": false,
"name": "orderHash",
"type": "bytes32"
}
],
"name": "LogFill",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "maker",
"type": "address"
},
{
"indexed": true,
"name": "feeRecipient",
"type": "address"
},
{
"indexed": false,
"name": "makerToken",
"type": "address"
},
{
"indexed": false,
"name": "takerToken",
"type": "address"
},
{
"indexed": false,
"name": "cancelledMakerTokenAmount",
"type": "uint256"
},
{
"indexed": false,
"name": "cancelledTakerTokenAmount",
"type": "uint256"
},
{
"indexed": true,
"name": "tokens",
"type": "bytes32"
},
{
"indexed": false,
"name": "orderHash",
"type": "bytes32"
}
],
"name": "LogCancel",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "errorId",
"type": "uint8"
},
{
"indexed": true,
"name": "orderHash",
"type": "bytes32"
}
],
"name": "LogError",
"type": "event"
}
],
"networks": {
"1": {
"address": "0x12459c951127e0c374ff9105dda097662a027093"
},
"3": {
"address": "0x479cc461fecd078f766ecc58533d6f69580cf3ac"
},
"42": {
"address": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364"
},
"50": {
"address": "0xb69e673309512a9d726f87304c6984054f87a93b"
}
}
}

View File

@@ -168,9 +168,5 @@
"name": "Approval",
"type": "event"
}
],
"unlinked_binary": "0x6060604052341561000c57fe5b5b6101e08061001c6000396000f3006060604052361561005c5763ffffffff60e060020a600035041663095ea7b3811461005e57806318160ddd1461009157806323b872dd146100b357806370a08231146100ec578063a9059cbb1461005e578063dd62ed3e1461014d575bfe5b341561006657fe5b61007d600160a060020a0360043516602435610181565b604080519115158252519081900360200190f35b341561009957fe5b6100a161018a565b60408051918252519081900360200190f35b34156100bb57fe5b61007d600160a060020a0360043581169060243516604435610190565b604080519115158252519081900360200190f35b34156100f457fe5b6100a1600160a060020a036004351661019a565b60408051918252519081900360200190f35b341561006657fe5b61007d600160a060020a0360043516602435610181565b604080519115158252519081900360200190f35b341561015557fe5b6100a1600160a060020a0360043581169060243516610181565b60408051918252519081900360200190f35b60005b92915050565b60005b90565b60005b9392505050565b60005b919050565b60005b92915050565b60005b929150505600a165627a7a723058202e3f7ac17048343c0d0ea24fccb64620577374eeeed61539e543df4025d7d0db0029",
"networks": {},
"schema_version": "0.0.5",
"updated_at": 1503317882695
}
]
}

View File

@@ -0,0 +1,544 @@
{
"contract_name": "TokenRegistry",
"abi": [
{
"constant": false,
"inputs": [
{
"name": "_token",
"type": "address"
},
{
"name": "_index",
"type": "uint256"
}
],
"name": "removeToken",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_name",
"type": "string"
}
],
"name": "getTokenAddressByName",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_symbol",
"type": "string"
}
],
"name": "getTokenAddressBySymbol",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_token",
"type": "address"
},
{
"name": "_swarmHash",
"type": "bytes"
}
],
"name": "setTokenSwarmHash",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_token",
"type": "address"
}
],
"name": "getTokenMetaData",
"outputs": [
{
"name": "",
"type": "address"
},
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "uint8"
},
{
"name": "",
"type": "bytes"
},
{
"name": "",
"type": "bytes"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "owner",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_token",
"type": "address"
},
{
"name": "_name",
"type": "string"
},
{
"name": "_symbol",
"type": "string"
},
{
"name": "_decimals",
"type": "uint8"
},
{
"name": "_ipfsHash",
"type": "bytes"
},
{
"name": "_swarmHash",
"type": "bytes"
}
],
"name": "addToken",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_token",
"type": "address"
},
{
"name": "_name",
"type": "string"
}
],
"name": "setTokenName",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "",
"type": "address"
}
],
"name": "tokens",
"outputs": [
{
"name": "token",
"type": "address"
},
{
"name": "name",
"type": "string"
},
{
"name": "symbol",
"type": "string"
},
{
"name": "decimals",
"type": "uint8"
},
{
"name": "ipfsHash",
"type": "bytes"
},
{
"name": "swarmHash",
"type": "bytes"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "",
"type": "uint256"
}
],
"name": "tokenAddresses",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_name",
"type": "string"
}
],
"name": "getTokenByName",
"outputs": [
{
"name": "",
"type": "address"
},
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "uint8"
},
{
"name": "",
"type": "bytes"
},
{
"name": "",
"type": "bytes"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "getTokenAddresses",
"outputs": [
{
"name": "",
"type": "address[]"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_token",
"type": "address"
},
{
"name": "_ipfsHash",
"type": "bytes"
}
],
"name": "setTokenIpfsHash",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_symbol",
"type": "string"
}
],
"name": "getTokenBySymbol",
"outputs": [
{
"name": "",
"type": "address"
},
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "uint8"
},
{
"name": "",
"type": "bytes"
},
{
"name": "",
"type": "bytes"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_token",
"type": "address"
},
{
"name": "_symbol",
"type": "string"
}
],
"name": "setTokenSymbol",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "newOwner",
"type": "address"
}
],
"name": "transferOwnership",
"outputs": [],
"payable": false,
"type": "function"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "token",
"type": "address"
},
{
"indexed": false,
"name": "name",
"type": "string"
},
{
"indexed": false,
"name": "symbol",
"type": "string"
},
{
"indexed": false,
"name": "decimals",
"type": "uint8"
},
{
"indexed": false,
"name": "ipfsHash",
"type": "bytes"
},
{
"indexed": false,
"name": "swarmHash",
"type": "bytes"
}
],
"name": "LogAddToken",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "token",
"type": "address"
},
{
"indexed": false,
"name": "name",
"type": "string"
},
{
"indexed": false,
"name": "symbol",
"type": "string"
},
{
"indexed": false,
"name": "decimals",
"type": "uint8"
},
{
"indexed": false,
"name": "ipfsHash",
"type": "bytes"
},
{
"indexed": false,
"name": "swarmHash",
"type": "bytes"
}
],
"name": "LogRemoveToken",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "token",
"type": "address"
},
{
"indexed": false,
"name": "oldName",
"type": "string"
},
{
"indexed": false,
"name": "newName",
"type": "string"
}
],
"name": "LogTokenNameChange",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "token",
"type": "address"
},
{
"indexed": false,
"name": "oldSymbol",
"type": "string"
},
{
"indexed": false,
"name": "newSymbol",
"type": "string"
}
],
"name": "LogTokenSymbolChange",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "token",
"type": "address"
},
{
"indexed": false,
"name": "oldIpfsHash",
"type": "bytes"
},
{
"indexed": false,
"name": "newIpfsHash",
"type": "bytes"
}
],
"name": "LogTokenIpfsHashChange",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "token",
"type": "address"
},
{
"indexed": false,
"name": "oldSwarmHash",
"type": "bytes"
},
{
"indexed": false,
"name": "newSwarmHash",
"type": "bytes"
}
],
"name": "LogTokenSwarmHashChange",
"type": "event"
}
],
"networks": {
"1": {
"address": "0x926a74c5c36adf004c87399e65f75628b0f98d2c"
},
"3": {
"address": "0x6b1a50f0bb5a7995444bd3877b22dc89c62843ed"
},
"42": {
"address": "0xf18e504561f4347bea557f3d4558f559dddbae7f"
},
"50": {
"address": "0x0b1ba0af832d7c05fd64161e0db78e85978e8082"
}
}
}

View File

@@ -0,0 +1,184 @@
{
"contract_name": "TokenTransferProxy",
"abi": [
{
"constant": false,
"inputs": [
{
"name": "token",
"type": "address"
},
{
"name": "from",
"type": "address"
},
{
"name": "to",
"type": "address"
},
{
"name": "value",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "target",
"type": "address"
}
],
"name": "addAuthorizedAddress",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "",
"type": "uint256"
}
],
"name": "authorities",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "target",
"type": "address"
}
],
"name": "removeAuthorizedAddress",
"outputs": [],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "owner",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "",
"type": "address"
}
],
"name": "authorized",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "getAuthorizedAddresses",
"outputs": [
{
"name": "",
"type": "address[]"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "newOwner",
"type": "address"
}
],
"name": "transferOwnership",
"outputs": [],
"payable": false,
"type": "function"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "target",
"type": "address"
},
{
"indexed": true,
"name": "caller",
"type": "address"
}
],
"name": "LogAuthorizedAddressAdded",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "target",
"type": "address"
},
{
"indexed": true,
"name": "caller",
"type": "address"
}
],
"name": "LogAuthorizedAddressRemoved",
"type": "event"
}
],
"networks": {
"1": {
"address": "0x8da0d80f5007ef1e431dd2127178d224e32c2ef4"
},
"3": {
"address": "0x4e9aad8184de8833365fea970cd9149372fdf1e6"
},
"42": {
"address": "0x087eed4bc1ee3de49befbd66c662b434b15d49d4"
},
"50": {
"address": "0x871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c"
}
}
}

View File

@@ -0,0 +1,17 @@
{
"contract_name": "ZRX",
"networks": {
"1": {
"address": "0xe41d2489571d322189246dafa5ebde1f4699f498"
},
"3": {
"address": "0xa8e9fa8f91e5ae138c74648c9c304f1c75003a8d"
},
"42": {
"address": "0x6ff6c0ff1d68b964901f986d4c9fa3ac68346570"
},
"50": {
"address": "0x25b8fe1de9daf8ba351890744ff28cf7dfa8f5e3"
}
}
}

View File

@@ -1,4 +1,4 @@
import * as BigNumber from 'bignumber.js';
import BigNumber from 'bignumber.js';
export const bigNumberConfigs = {
configure() {

View File

@@ -1,9 +1,14 @@
import * as Web3 from 'web3';
import * as _ from 'lodash';
import {schemas, SchemaValidator} from '@0xproject/json-schemas';
import promisify = require('es6-promisify');
import {SchemaValidator, schemas} from '0x-json-schemas';
import * as _ from 'lodash';
import * as Web3 from 'web3';
import {AbiType} from './types';
// HACK: Gas estimates on testrpc don't take into account gas refunds.
// Our calls can trigger max 8 gas refunds for SSTORE per transaction for 15k gas each which gives 120k.
const GAS_MARGIN = 120000;
export class Contract implements Web3.ContractInstance {
public address: string;
public abi: Web3.ContractAbi;
@@ -33,9 +38,10 @@ export class Contract implements Web3.ContractInstance {
} else {
const cbStyleFunction = this.contract[functionAbi.name];
const cbStyleEstimateGasFunction = this.contract[functionAbi.name].estimateGas;
const estimateGasAsync = promisify(cbStyleEstimateGasFunction, this.contract);
this[functionAbi.name] = {
estimateGasAsync: promisify(cbStyleEstimateGasFunction, this.contract),
sendTransactionAsync: this.promisifyWithDefaultParams(cbStyleFunction),
estimateGasAsync,
sendTransactionAsync: this.promisifyWithDefaultParams(cbStyleFunction, estimateGasAsync),
};
}
});
@@ -46,28 +52,40 @@ export class Contract implements Web3.ContractInstance {
this[eventAbi.name] = this.contract[eventAbi.name];
});
}
private promisifyWithDefaultParams(fn: (...args: any[]) => void): (...args: any[]) => Promise<any> {
const promisifiedWithDefaultParams = (...args: any[]) => {
const promise = new Promise((resolve, reject) => {
private promisifyWithDefaultParams(
web3CbStyleFunction: (...args: any[]) => void,
estimateGasAsync: (...args: any[]) => Promise<number>,
): (...args: any[]) => Promise<any> {
const promisifiedWithDefaultParams = async (...args: any[]) => {
const promise = new Promise(async (resolve, reject) => {
const lastArg = args[args.length - 1];
let txData: Partial<Web3.TxData> = {};
if (this.isTxData(lastArg)) {
if (!_.isUndefined(lastArg) && this.isTxData(lastArg)) {
txData = args.pop();
}
// Gas amount sourced with the following priorities:
// 1. Optional param passed in to public method call
// 2. Global config passed in at library instantiation
// 3. Gas estimate calculation + safety margin
const removeUndefinedProperties = _.pickBy;
txData = {
...this.defaults,
...txData,
...removeUndefinedProperties(this.defaults),
...removeUndefinedProperties(txData),
};
const callback = (err: Error, data: any) => {
if (_.isNull(err)) {
resolve(data);
} else {
if (_.isUndefined(txData.gas)) {
try {
const estimatedGas = await estimateGasAsync.apply(this.contract, [...args, txData]);
const gas = estimatedGas + GAS_MARGIN;
txData.gas = gas;
} catch (err) {
reject(err);
return;
}
};
}
const callback = (err: Error, data: any) => _.isNull(err) ? resolve(data) : reject(err);
args.push(txData);
args.push(callback);
fn.apply(this.contract, args);
web3CbStyleFunction.apply(this.contract, args);
});
return promise;
};

View File

@@ -0,0 +1,165 @@
import {Block, BlockAndLogStreamer} from 'ethereumjs-blockstream';
import * as _ from 'lodash';
import * as Web3 from 'web3';
import {
Artifact,
BlockParamLiteral,
ContractEventArgs,
ContractEvents,
EventCallback,
IndexedFilterValues,
InternalZeroExError,
LogWithDecodedArgs,
RawLog,
SubscriptionOpts,
ZeroExError,
} from '../types';
import {AbiDecoder} from '../utils/abi_decoder';
import {constants} from '../utils/constants';
import {filterUtils} from '../utils/filter_utils';
import {intervalUtils} from '../utils/interval_utils';
import {Web3Wrapper} from '../web3_wrapper';
export class ContractWrapper {
protected _web3Wrapper: Web3Wrapper;
private _abiDecoder?: AbiDecoder;
private _blockAndLogStreamer: BlockAndLogStreamer|undefined;
private _blockAndLogStreamInterval: NodeJS.Timer;
private _filters: {[filterToken: string]: Web3.FilterObject};
private _filterCallbacks: {[filterToken: string]: EventCallback<ContractEventArgs>};
private _onLogAddedSubscriptionToken: string|undefined;
private _onLogRemovedSubscriptionToken: string|undefined;
constructor(web3Wrapper: Web3Wrapper, abiDecoder?: AbiDecoder) {
this._web3Wrapper = web3Wrapper;
this._abiDecoder = abiDecoder;
this._filters = {};
this._filterCallbacks = {};
this._blockAndLogStreamer = undefined;
this._onLogAddedSubscriptionToken = undefined;
this._onLogRemovedSubscriptionToken = undefined;
}
/**
* Cancels all existing subscriptions
*/
public unsubscribeAll(): void {
const filterTokens = _.keys(this._filterCallbacks);
_.each(filterTokens, filterToken => {
this._unsubscribe(filterToken);
});
}
protected _unsubscribe(filterToken: string, err?: Error): void {
if (_.isUndefined(this._filters[filterToken])) {
throw new Error(ZeroExError.SubscriptionNotFound);
}
if (!_.isUndefined(err)) {
const callback = this._filterCallbacks[filterToken];
callback(err, undefined);
}
delete this._filters[filterToken];
delete this._filterCallbacks[filterToken];
if (_.isEmpty(this._filters)) {
this._stopBlockAndLogStream();
}
}
protected _subscribe<ArgsType extends ContractEventArgs>(
address: string, eventName: ContractEvents, indexFilterValues: IndexedFilterValues, abi: Web3.ContractAbi,
callback: EventCallback<ArgsType>): string {
const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi);
if (_.isUndefined(this._blockAndLogStreamer)) {
this._startBlockAndLogStream();
}
const filterToken = filterUtils.generateUUID();
this._filters[filterToken] = filter;
this._filterCallbacks[filterToken] = callback;
return filterToken;
}
protected async _getLogsAsync<ArgsType extends ContractEventArgs>(
address: string, eventName: ContractEvents, subscriptionOpts: SubscriptionOpts,
indexFilterValues: IndexedFilterValues, abi: Web3.ContractAbi): Promise<Array<LogWithDecodedArgs<ArgsType>>> {
const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi, subscriptionOpts);
const logs = await this._web3Wrapper.getLogsAsync(filter);
const logsWithDecodedArguments = _.map(logs, this._tryToDecodeLogOrNoop.bind(this));
return logsWithDecodedArguments;
}
protected _tryToDecodeLogOrNoop<ArgsType extends ContractEventArgs>(
log: Web3.LogEntry): LogWithDecodedArgs<ArgsType>|RawLog {
if (_.isUndefined(this._abiDecoder)) {
throw new Error(InternalZeroExError.NoAbiDecoder);
}
const logWithDecodedArgs = this._abiDecoder.tryToDecodeLogOrNoop(log);
return logWithDecodedArgs;
}
protected async _instantiateContractIfExistsAsync<ContractType extends Web3.ContractInstance>(
artifact: Artifact, addressIfExists?: string): Promise<ContractType> {
const contractInstance =
await this._web3Wrapper.getContractInstanceFromArtifactAsync<ContractType>(artifact, addressIfExists);
return contractInstance;
}
protected _getContractAddress(artifact: Artifact, addressIfExists?: string): string {
if (_.isUndefined(addressIfExists)) {
const networkId = this._web3Wrapper.getNetworkId();
const contractAddress = artifact.networks[networkId].address;
if (_.isUndefined(contractAddress)) {
throw new Error(ZeroExError.ExchangeContractDoesNotExist);
}
return contractAddress;
} else {
return addressIfExists;
}
}
private _onLogStateChanged<ArgsType extends ContractEventArgs>(isRemoved: boolean, log: Web3.LogEntry): void {
_.forEach(this._filters, (filter: Web3.FilterObject, filterToken: string) => {
if (filterUtils.matchesFilter(log, filter)) {
const decodedLog = this._tryToDecodeLogOrNoop(log) as LogWithDecodedArgs<ArgsType>;
const logEvent = {
log: decodedLog,
isRemoved,
};
this._filterCallbacks[filterToken](null, logEvent);
}
});
}
private _startBlockAndLogStream(): void {
this._blockAndLogStreamer = new BlockAndLogStreamer(
this._web3Wrapper.getBlockAsync.bind(this._web3Wrapper),
this._web3Wrapper.getLogsAsync.bind(this._web3Wrapper),
);
const catchAllLogFilter = {};
this._blockAndLogStreamer.addLogFilter(catchAllLogFilter);
this._blockAndLogStreamInterval = intervalUtils.setAsyncExcludingInterval(
this._reconcileBlockAsync.bind(this), constants.DEFAULT_BLOCK_POLLING_INTERVAL,
);
let isRemoved = false;
this._onLogAddedSubscriptionToken = this._blockAndLogStreamer.subscribeToOnLogAdded(
this._onLogStateChanged.bind(this, isRemoved),
);
isRemoved = true;
this._onLogRemovedSubscriptionToken = this._blockAndLogStreamer.subscribeToOnLogRemoved(
this._onLogStateChanged.bind(this, isRemoved),
);
}
private _stopBlockAndLogStream(): void {
(this._blockAndLogStreamer as BlockAndLogStreamer).unsubscribeFromOnLogAdded(
this._onLogAddedSubscriptionToken as string);
(this._blockAndLogStreamer as BlockAndLogStreamer).unsubscribeFromOnLogRemoved(
this._onLogRemovedSubscriptionToken as string);
intervalUtils.clearAsyncExcludingInterval(this._blockAndLogStreamInterval);
delete this._blockAndLogStreamer;
}
private async _reconcileBlockAsync(): Promise<void> {
try {
const latestBlock = await this._web3Wrapper.getBlockAsync(BlockParamLiteral.Latest);
// We need to coerce to Block type cause Web3.Block includes types for mempool blocks
if (!_.isUndefined(this._blockAndLogStreamer)) {
// If we clear the interval while fetching the block - this._blockAndLogStreamer will be undefined
await this._blockAndLogStreamer.reconcileNewBlock(latestBlock as any as Block);
}
} catch (err) {
const filterTokens = _.keys(this._filterCallbacks);
_.each(filterTokens, filterToken => {
this._unsubscribe(filterToken, err);
});
}
}
}

View File

@@ -1,10 +1,13 @@
import BigNumber from 'bignumber.js';
import * as _ from 'lodash';
import {artifacts} from '../artifacts';
import {EtherTokenContract, TransactionOpts, ZeroExError} from '../types';
import {assert} from '../utils/assert';
import {Web3Wrapper} from '../web3_wrapper';
import {ContractWrapper} from './contract_wrapper';
import {TokenWrapper} from './token_wrapper';
import {EtherTokenContract, ZeroExError} from '../types';
import {assert} from '../utils/assert';
import {artifacts} from '../artifacts';
/**
* This class includes all the functionality related to interacting with a wrapped Ether ERC20 token contract.
@@ -24,11 +27,14 @@ export class EtherTokenWrapper extends ContractWrapper {
* to the depositor address. These wrapped ETH tokens can be used in 0x trades and are redeemable for 1-to-1
* for ETH.
* @param amountInWei Amount of ETH in Wei the caller wishes to deposit.
* @param depositor The hex encoded user Ethereum address that would like to make the deposit.
* @param depositor The hex encoded user Ethereum address that would like to make the deposit.
* @param txOpts Transaction parameters.
* @return Transaction hash.
*/
public async depositAsync(amountInWei: BigNumber.BigNumber, depositor: string): Promise<string> {
assert.isBigNumber('amountInWei', amountInWei);
public async depositAsync(
amountInWei: BigNumber, depositor: string, txOpts: TransactionOpts = {},
): Promise<string> {
assert.isValidBaseUnitAmount('amountInWei', amountInWei);
await assert.isSenderAddressAsync('depositor', depositor, this._web3Wrapper);
const ethBalanceInWei = await this._web3Wrapper.getBalanceInWeiAsync(depositor);
@@ -38,6 +44,8 @@ export class EtherTokenWrapper extends ContractWrapper {
const txHash = await wethContract.deposit.sendTransactionAsync({
from: depositor,
value: amountInWei,
gas: txOpts.gasLimit,
gasPrice: txOpts.gasPrice,
});
return txHash;
}
@@ -46,19 +54,24 @@ export class EtherTokenWrapper extends ContractWrapper {
* equivalent number of wrapped ETH tokens.
* @param amountInWei Amount of ETH in Wei the caller wishes to withdraw.
* @param withdrawer The hex encoded user Ethereum address that would like to make the withdrawl.
* @param txOpts Transaction parameters.
* @return Transaction hash.
*/
public async withdrawAsync(amountInWei: BigNumber.BigNumber, withdrawer: string): Promise<string> {
assert.isBigNumber('amountInWei', amountInWei);
public async withdrawAsync(
amountInWei: BigNumber, withdrawer: string, txOpts: TransactionOpts = {},
): Promise<string> {
assert.isValidBaseUnitAmount('amountInWei', amountInWei);
await assert.isSenderAddressAsync('withdrawer', withdrawer, this._web3Wrapper);
const wethContractAddress = await this.getContractAddressAsync();
const wethContractAddress = this.getContractAddress();
const WETHBalanceInBaseUnits = await this._tokenWrapper.getBalanceAsync(wethContractAddress, withdrawer);
assert.assert(WETHBalanceInBaseUnits.gte(amountInWei), ZeroExError.InsufficientWEthBalanceForWithdrawal);
const wethContract = await this._getEtherTokenContractAsync();
const txHash = await wethContract.withdraw.sendTransactionAsync(amountInWei, {
from: withdrawer,
gas: txOpts.gasLimit,
gasPrice: txOpts.gasPrice,
});
return txHash;
}
@@ -66,9 +79,11 @@ export class EtherTokenWrapper extends ContractWrapper {
* Retrieves the Wrapped Ether token contract address
* @return The Wrapped Ether token contract address
*/
public async getContractAddressAsync(): Promise<string> {
const wethContract = await this._getEtherTokenContractAsync();
return wethContract.address;
public getContractAddress(): string {
const contractAddress = this._getContractAddress(
artifacts.EtherTokenArtifact, this._contractAddressIfExists,
);
return contractAddress;
}
private _invalidateContractInstance(): void {
delete this._etherTokenContractIfExists;
@@ -80,7 +95,7 @@ export class EtherTokenWrapper extends ContractWrapper {
const contractInstance = await this._instantiateContractIfExistsAsync<EtherTokenContract>(
artifacts.EtherTokenArtifact, this._contractAddressIfExists,
);
this._etherTokenContractIfExists = contractInstance as EtherTokenContract;
this._etherTokenContractIfExists = contractInstance;
return this._etherTokenContractIfExists;
}
}

View File

@@ -1,60 +1,62 @@
import {schemas} from '@0xproject/json-schemas';
import BigNumber from 'bignumber.js';
import * as _ from 'lodash';
import * as BigNumber from 'bignumber.js';
import {SchemaValidator, schemas} from '0x-json-schemas';
import promisify = require('es6-promisify');
import {Web3Wrapper} from '../web3_wrapper';
import * as Web3 from 'web3';
import {artifacts} from '../artifacts';
import {
BlockParamLiteral,
DecodedLogArgs,
ECSignature,
EventCallback,
ExchangeContract,
ExchangeContractErrCodes,
ExchangeContractErrs,
ZeroExError,
OrderValues,
OrderAddresses,
Order,
OrderFillOrKillRequest,
SignedOrder,
ContractEvent,
ExchangeContractEventArgs,
ExchangeEvents,
ContractEventEmitter,
SubscriptionOpts,
IndexedFilterValues,
CreateContractEvent,
ContractEventObj,
OrderCancellationRequest,
OrderFillRequest,
LogCancelContractEventArgs,
LogErrorContractEventArgs,
LogFillContractEventArgs,
LogCancelContractEventArgs,
LogWithDecodedArgs,
MethodOpts,
ValidateOrderFillableOpts,
Order,
OrderAddresses,
OrderCancellationRequest,
OrderFillRequest,
OrderTransactionOpts,
OrderValues,
RawLog,
SignedOrder,
SubscriptionOpts,
ValidateOrderFillableOpts,
} from '../types';
import {assert} from '../utils/assert';
import {utils} from '../utils/utils';
import {eventUtils} from '../utils/event_utils';
import {OrderValidationUtils} from '../utils/order_validation_utils';
import {ContractWrapper} from './contract_wrapper';
import {constants} from '../utils/constants';
import {TokenWrapper} from './token_wrapper';
import {decorators} from '../utils/decorators';
import {AbiDecoder} from '../utils/abi_decoder';
import {artifacts} from '../artifacts';
import {assert} from '../utils/assert';
import {decorators} from '../utils/decorators';
import {ExchangeTransferSimulator} from '../utils/exchange_transfer_simulator';
import {OrderValidationUtils} from '../utils/order_validation_utils';
import {utils} from '../utils/utils';
import {Web3Wrapper} from '../web3_wrapper';
import {ContractWrapper} from './contract_wrapper';
import {TokenWrapper} from './token_wrapper';
const SHOULD_VALIDATE_BY_DEFAULT = true;
interface ExchangeContractErrCodesToMsgs {
[exchangeContractErrCodes: number]: string;
}
/**
* This class includes all the functionality related to calling methods and subscribing to
* events of the 0x Exchange smart contract.
*/
export class ExchangeWrapper extends ContractWrapper {
private _exchangeContractIfExists?: ExchangeContract;
private _exchangeLogEventEmitters: ContractEventEmitter[];
private _orderValidationUtils: OrderValidationUtils;
private _tokenWrapper: TokenWrapper;
private _exchangeContractErrCodesToMsg = {
private _exchangeContractErrCodesToMsg: ExchangeContractErrCodesToMsgs = {
[ExchangeContractErrCodes.ERROR_FILL_EXPIRED]: ExchangeContractErrs.OrderFillExpired,
[ExchangeContractErrCodes.ERROR_CANCEL_EXPIRED]: ExchangeContractErrs.OrderFillExpired,
[ExchangeContractErrCodes.ERROR_FILL_NO_VALUE]: ExchangeContractErrs.OrderRemainingFillAmountZero,
@@ -63,6 +65,7 @@ export class ExchangeWrapper extends ContractWrapper {
[ExchangeContractErrCodes.ERROR_FILL_BALANCE_ALLOWANCE]: ExchangeContractErrs.FillBalanceAllowanceError,
};
private _contractAddressIfExists?: string;
private _zrxContractAddressIfExists?: string;
private static _getOrderAddressesAndValues(order: Order): [OrderAddresses, OrderValues] {
const orderAddresses: OrderAddresses = [
order.maker,
@@ -86,7 +89,6 @@ export class ExchangeWrapper extends ContractWrapper {
super(web3Wrapper, abiDecoder);
this._tokenWrapper = tokenWrapper;
this._orderValidationUtils = new OrderValidationUtils(tokenWrapper, this);
this._exchangeLogEventEmitters = [];
this._contractAddressIfExists = contractAddressIfExists;
}
/**
@@ -96,10 +98,10 @@ export class ExchangeWrapper extends ContractWrapper {
* @param orderHash The hex encoded orderHash for which you would like to retrieve the
* unavailable takerAmount.
* @param methodOpts Optional arguments this method accepts.
* @return The amount of the order (in taker tokens) that has either been filled or canceled.
* @return The amount of the order (in taker tokens) that has either been filled or cancelled.
*/
public async getUnavailableTakerAmountAsync(orderHash: string,
methodOpts?: MethodOpts): Promise<BigNumber.BigNumber> {
methodOpts?: MethodOpts): Promise<BigNumber> {
assert.doesConformToSchema('orderHash', orderHash, schemas.orderHashSchema);
const exchangeContract = await this._getExchangeContractAsync();
@@ -117,7 +119,7 @@ export class ExchangeWrapper extends ContractWrapper {
* @param methodOpts Optional arguments this method accepts.
* @return The amount of the order (in taker tokens) that has already been filled.
*/
public async getFilledTakerAmountAsync(orderHash: string, methodOpts?: MethodOpts): Promise<BigNumber.BigNumber> {
public async getFilledTakerAmountAsync(orderHash: string, methodOpts?: MethodOpts): Promise<BigNumber> {
assert.doesConformToSchema('orderHash', orderHash, schemas.orderHashSchema);
const exchangeContract = await this._getExchangeContractAsync();
@@ -134,7 +136,7 @@ export class ExchangeWrapper extends ContractWrapper {
* @param methodOpts Optional arguments this method accepts.
* @return The amount of the order (in taker tokens) that has been cancelled.
*/
public async getCanceledTakerAmountAsync(orderHash: string, methodOpts?: MethodOpts): Promise<BigNumber.BigNumber> {
public async getCancelledTakerAmountAsync(orderHash: string, methodOpts?: MethodOpts): Promise<BigNumber> {
assert.doesConformToSchema('orderHash', orderHash, schemas.orderHashSchema);
const exchangeContract = await this._getExchangeContractAsync();
@@ -164,37 +166,28 @@ export class ExchangeWrapper extends ContractWrapper {
* @return Transaction hash.
*/
@decorators.contractCallErrorHandler
public async fillOrderAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber.BigNumber,
public async fillOrderAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber,
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
takerAddress: string,
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
assert.isBigNumber('fillTakerTokenAmount', fillTakerTokenAmount);
assert.isValidBaseUnitAmount('fillTakerTokenAmount', fillTakerTokenAmount);
assert.isBoolean('shouldThrowOnInsufficientBalanceOrAllowance', shouldThrowOnInsufficientBalanceOrAllowance);
await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper);
const exchangeInstance = await this._getExchangeContractAsync();
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
if (shouldValidate) {
await this.validateFillOrderThrowIfInvalidAsync(signedOrder, fillTakerTokenAmount, takerAddress);
const zrxTokenAddress = this.getZRXTokenAddress();
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
await this._orderValidationUtils.validateFillOrderThrowIfInvalidAsync(
exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress);
}
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(signedOrder);
const gas = await exchangeInstance.fillOrder.estimateGasAsync(
orderAddresses,
orderValues,
fillTakerTokenAmount,
shouldThrowOnInsufficientBalanceOrAllowance,
signedOrder.ecSignature.v,
signedOrder.ecSignature.r,
signedOrder.ecSignature.s,
{
from: takerAddress,
},
);
const txHash: string = await exchangeInstance.fillOrder.sendTransactionAsync(
orderAddresses,
orderValues,
@@ -205,7 +198,8 @@ export class ExchangeWrapper extends ContractWrapper {
signedOrder.ecSignature.s,
{
from: takerAddress,
gas,
gas: orderTransactionOpts.gasLimit,
gasPrice: orderTransactionOpts.gasPrice,
},
);
return txHash;
@@ -228,10 +222,10 @@ export class ExchangeWrapper extends ContractWrapper {
* @return Transaction hash.
*/
@decorators.contractCallErrorHandler
public async fillOrdersUpToAsync(signedOrders: SignedOrder[], fillTakerTokenAmount: BigNumber.BigNumber,
public async fillOrdersUpToAsync(signedOrders: SignedOrder[], fillTakerTokenAmount: BigNumber,
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
takerAddress: string,
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema);
const takerTokenAddresses = _.map(signedOrders, signedOrder => signedOrder.takerTokenAddress);
assert.hasAtMostOneUniqueValue(takerTokenAddresses,
@@ -239,16 +233,20 @@ export class ExchangeWrapper extends ContractWrapper {
const exchangeContractAddresses = _.map(signedOrders, signedOrder => signedOrder.exchangeContractAddress);
assert.hasAtMostOneUniqueValue(exchangeContractAddresses,
ExchangeContractErrs.BatchOrdersMustHaveSameExchangeAddress);
assert.isBigNumber('fillTakerTokenAmount', fillTakerTokenAmount);
assert.isValidBaseUnitAmount('fillTakerTokenAmount', fillTakerTokenAmount);
assert.isBoolean('shouldThrowOnInsufficientBalanceOrAllowance', shouldThrowOnInsufficientBalanceOrAllowance);
await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper);
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
if (shouldValidate) {
await Promise.all(signedOrders.map(signedOrder => this.validateFillOrderThrowIfInvalidAsync(
signedOrder, fillTakerTokenAmount, takerAddress)));
const zrxTokenAddress = this.getZRXTokenAddress();
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
for (const signedOrder of signedOrders) {
await this._orderValidationUtils.validateFillOrderThrowIfInvalidAsync(
exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress);
}
}
if (_.isEmpty(signedOrders)) {
@@ -269,18 +267,6 @@ export class ExchangeWrapper extends ContractWrapper {
);
const exchangeInstance = await this._getExchangeContractAsync();
const gas = await exchangeInstance.fillOrdersUpTo.estimateGasAsync(
orderAddressesArray,
orderValuesArray,
fillTakerTokenAmount,
shouldThrowOnInsufficientBalanceOrAllowance,
vArray,
rArray,
sArray,
{
from: takerAddress,
},
);
const txHash = await exchangeInstance.fillOrdersUpTo.sendTransactionAsync(
orderAddressesArray,
orderValuesArray,
@@ -291,7 +277,8 @@ export class ExchangeWrapper extends ContractWrapper {
sArray,
{
from: takerAddress,
gas,
gas: orderTransactionOpts.gasLimit,
gasPrice: orderTransactionOpts.gasPrice,
},
);
return txHash;
@@ -299,9 +286,9 @@ export class ExchangeWrapper extends ContractWrapper {
/**
* Batch version of fillOrderAsync.
* Executes multiple fills atomically in a single transaction.
* If shouldThrowOnInsufficientBalanceOrAllowance is set to true, it will continue filling subsequent orders even
* If shouldThrowOnInsufficientBalanceOrAllowance is set to false, it will continue filling subsequent orders even
* when earlier ones fail.
* When shouldThrowOnInsufficientBalanceOrAllowance is set to false, if any fill fails, the entire batch fails.
* When shouldThrowOnInsufficientBalanceOrAllowance is set to true, if any fill fails, the entire batch fails.
* @param orderFillRequests An array of objects that conform to the
* OrderFillRequest interface.
* @param shouldThrowOnInsufficientBalanceOrAllowance Whether or not you wish for the contract call to throw
@@ -319,7 +306,7 @@ export class ExchangeWrapper extends ContractWrapper {
public async batchFillOrdersAsync(orderFillRequests: OrderFillRequest[],
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
takerAddress: string,
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
assert.doesConformToSchema('orderFillRequests', orderFillRequests, schemas.orderFillRequestsSchema);
const exchangeContractAddresses = _.map(
orderFillRequests,
@@ -329,13 +316,18 @@ export class ExchangeWrapper extends ContractWrapper {
ExchangeContractErrs.BatchOrdersMustHaveSameExchangeAddress);
assert.isBoolean('shouldThrowOnInsufficientBalanceOrAllowance', shouldThrowOnInsufficientBalanceOrAllowance);
await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper);
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
if (shouldValidate) {
await Promise.all(orderFillRequests.map(orderFillRequest => this.validateFillOrderThrowIfInvalidAsync(
orderFillRequest.signedOrder, orderFillRequest.takerTokenFillAmount, takerAddress)),
);
const zrxTokenAddress = this.getZRXTokenAddress();
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
for (const orderFillRequest of orderFillRequests) {
await this._orderValidationUtils.validateFillOrderThrowIfInvalidAsync(
exchangeTradeEmulator, orderFillRequest.signedOrder, orderFillRequest.takerTokenFillAmount,
takerAddress, zrxTokenAddress,
);
}
}
if (_.isEmpty(orderFillRequests)) {
throw new Error(ExchangeContractErrs.BatchOrdersMustHaveAtLeastOneItem);
@@ -356,18 +348,6 @@ export class ExchangeWrapper extends ContractWrapper {
);
const exchangeInstance = await this._getExchangeContractAsync();
const gas = await exchangeInstance.batchFillOrders.estimateGasAsync(
orderAddressesArray,
orderValuesArray,
fillTakerTokenAmounts,
shouldThrowOnInsufficientBalanceOrAllowance,
vArray,
rArray,
sArray,
{
from: takerAddress,
},
);
const txHash = await exchangeInstance.batchFillOrders.sendTransactionAsync(
orderAddressesArray,
orderValuesArray,
@@ -378,7 +358,8 @@ export class ExchangeWrapper extends ContractWrapper {
sArray,
{
from: takerAddress,
gas,
gas: orderTransactionOpts.gasLimit,
gasPrice: orderTransactionOpts.gasPrice,
},
);
return txHash;
@@ -395,35 +376,26 @@ export class ExchangeWrapper extends ContractWrapper {
* @return Transaction hash.
*/
@decorators.contractCallErrorHandler
public async fillOrKillOrderAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber.BigNumber,
public async fillOrKillOrderAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber,
takerAddress: string,
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
assert.isBigNumber('fillTakerTokenAmount', fillTakerTokenAmount);
assert.isValidBaseUnitAmount('fillTakerTokenAmount', fillTakerTokenAmount);
await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper);
const exchangeInstance = await this._getExchangeContractAsync();
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
if (shouldValidate) {
await this.validateFillOrKillOrderThrowIfInvalidAsync(signedOrder, fillTakerTokenAmount, takerAddress);
const zrxTokenAddress = this.getZRXTokenAddress();
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
await this._orderValidationUtils.validateFillOrKillOrderThrowIfInvalidAsync(
exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress);
}
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(signedOrder);
const gas = await exchangeInstance.fillOrKillOrder.estimateGasAsync(
orderAddresses,
orderValues,
fillTakerTokenAmount,
signedOrder.ecSignature.v,
signedOrder.ecSignature.r,
signedOrder.ecSignature.s,
{
from: takerAddress,
},
);
const txHash = await exchangeInstance.fillOrKillOrder.sendTransactionAsync(
orderAddresses,
orderValues,
@@ -433,7 +405,8 @@ export class ExchangeWrapper extends ContractWrapper {
signedOrder.ecSignature.s,
{
from: takerAddress,
gas,
gas: orderTransactionOpts.gasLimit,
gasPrice: orderTransactionOpts.gasPrice,
},
);
return txHash;
@@ -441,43 +414,48 @@ export class ExchangeWrapper extends ContractWrapper {
/**
* Batch version of fillOrKill. Allows a taker to specify a batch of orders that will either be atomically
* filled (each to the specified fillAmount) or aborted.
* @param orderFillOrKillRequests An array of objects that conform to the OrderFillOrKillRequest interface.
* @param orderFillRequests An array of objects that conform to the OrderFillRequest interface.
* @param takerAddress The user Ethereum address who would like to fill there orders.
* Must be available via the supplied Web3.Provider passed to 0x.js.
* @param orderTransactionOpts Optional arguments this method accepts.
* @return Transaction hash.
*/
@decorators.contractCallErrorHandler
public async batchFillOrKillAsync(orderFillOrKillRequests: OrderFillOrKillRequest[],
public async batchFillOrKillAsync(orderFillRequests: OrderFillRequest[],
takerAddress: string,
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
assert.doesConformToSchema('orderFillOrKillRequests', orderFillOrKillRequests,
schemas.orderFillOrKillRequestsSchema);
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
assert.doesConformToSchema('orderFillRequests', orderFillRequests,
schemas.orderFillRequestsSchema);
const exchangeContractAddresses = _.map(
orderFillOrKillRequests,
orderFillOrKillRequest => orderFillOrKillRequest.signedOrder.exchangeContractAddress,
orderFillRequests,
orderFillRequest => orderFillRequest.signedOrder.exchangeContractAddress,
);
assert.hasAtMostOneUniqueValue(exchangeContractAddresses,
ExchangeContractErrs.BatchOrdersMustHaveSameExchangeAddress);
await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper);
if (_.isEmpty(orderFillOrKillRequests)) {
if (_.isEmpty(orderFillRequests)) {
throw new Error(ExchangeContractErrs.BatchOrdersMustHaveAtLeastOneItem);
}
const exchangeInstance = await this._getExchangeContractAsync();
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
if (shouldValidate) {
await Promise.all(orderFillOrKillRequests.map(request => this.validateFillOrKillOrderThrowIfInvalidAsync(
request.signedOrder, request.fillTakerAmount, takerAddress)),
);
const zrxTokenAddress = this.getZRXTokenAddress();
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
for (const orderFillRequest of orderFillRequests) {
await this._orderValidationUtils.validateFillOrKillOrderThrowIfInvalidAsync(
exchangeTradeEmulator, orderFillRequest.signedOrder, orderFillRequest.takerTokenFillAmount,
takerAddress, zrxTokenAddress,
);
}
}
const orderAddressesValuesAndTakerTokenFillAmounts = _.map(orderFillOrKillRequests, request => {
const orderAddressesValuesAndTakerTokenFillAmounts = _.map(orderFillRequests, request => {
return [
...ExchangeWrapper._getOrderAddressesAndValues(request.signedOrder),
request.fillTakerAmount,
request.takerTokenFillAmount,
request.signedOrder.ecSignature.v,
request.signedOrder.ecSignature.r,
request.signedOrder.ecSignature.s,
@@ -487,18 +465,6 @@ export class ExchangeWrapper extends ContractWrapper {
// We use _.unzip<any> because _.unzip doesn't type check if values have different types :'(
const [orderAddresses, orderValues, fillTakerTokenAmounts, vParams, rParams, sParams] =
_.unzip<any>(orderAddressesValuesAndTakerTokenFillAmounts);
const gas = await exchangeInstance.batchFillOrKillOrders.estimateGasAsync(
orderAddresses,
orderValues,
fillTakerTokenAmounts,
vParams,
rParams,
sParams,
{
from: takerAddress,
},
);
const txHash = await exchangeInstance.batchFillOrKillOrders.sendTransactionAsync(
orderAddresses,
orderValues,
@@ -508,7 +474,8 @@ export class ExchangeWrapper extends ContractWrapper {
sParams,
{
from: takerAddress,
gas,
gas: orderTransactionOpts.gasLimit,
gasPrice: orderTransactionOpts.gasPrice,
},
);
return txHash;
@@ -523,37 +490,33 @@ export class ExchangeWrapper extends ContractWrapper {
*/
@decorators.contractCallErrorHandler
public async cancelOrderAsync(order: Order|SignedOrder,
cancelTakerTokenAmount: BigNumber.BigNumber,
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
cancelTakerTokenAmount: BigNumber,
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
assert.doesConformToSchema('order', order, schemas.orderSchema);
assert.isBigNumber('takerTokenCancelAmount', cancelTakerTokenAmount);
assert.isValidBaseUnitAmount('takerTokenCancelAmount', cancelTakerTokenAmount);
await assert.isSenderAddressAsync('order.maker', order.maker, this._web3Wrapper);
const exchangeInstance = await this._getExchangeContractAsync();
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
if (shouldValidate) {
await this.validateCancelOrderThrowIfInvalidAsync(order, cancelTakerTokenAmount);
const orderHash = utils.getOrderHashHex(order);
const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash);
OrderValidationUtils.validateCancelOrderThrowIfInvalid(
order, cancelTakerTokenAmount, unavailableTakerTokenAmount);
}
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(order);
const gas = await exchangeInstance.cancelOrder.estimateGasAsync(
orderAddresses,
orderValues,
cancelTakerTokenAmount,
{
from: order.maker,
},
);
const txHash = await exchangeInstance.cancelOrder.sendTransactionAsync(
orderAddresses,
orderValues,
cancelTakerTokenAmount,
{
from: order.maker,
gas,
gas: orderTransactionOpts.gasLimit,
gasPrice: orderTransactionOpts.gasPrice,
},
);
return txHash;
@@ -568,7 +531,7 @@ export class ExchangeWrapper extends ContractWrapper {
*/
@decorators.contractCallErrorHandler
public async batchCancelOrdersAsync(orderCancellationRequests: OrderCancellationRequest[],
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
assert.doesConformToSchema('orderCancellationRequests', orderCancellationRequests,
schemas.orderCancellationRequestsSchema);
const exchangeContractAddresses = _.map(
@@ -581,13 +544,19 @@ export class ExchangeWrapper extends ContractWrapper {
assert.hasAtMostOneUniqueValue(makers, ExchangeContractErrs.MultipleMakersInSingleCancelBatchDisallowed);
const maker = makers[0];
await assert.isSenderAddressAsync('maker', maker, this._web3Wrapper);
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
SHOULD_VALIDATE_BY_DEFAULT :
orderTransactionOpts.shouldValidate;
if (shouldValidate) {
await Promise.all(orderCancellationRequests.map(cancellationRequest =>
this.validateCancelOrderThrowIfInvalidAsync(
cancellationRequest.order, cancellationRequest.takerTokenCancelAmount)));
for (const orderCancellationRequest of orderCancellationRequests) {
const orderHash = utils.getOrderHashHex(orderCancellationRequest.order);
const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash);
OrderValidationUtils.validateCancelOrderThrowIfInvalid(
orderCancellationRequest.order, orderCancellationRequest.takerTokenCancelAmount,
unavailableTakerTokenAmount,
);
}
}
if (_.isEmpty(orderCancellationRequests)) {
throw new Error(ExchangeContractErrs.BatchOrdersMustHaveAtLeastOneItem);
@@ -602,61 +571,44 @@ export class ExchangeWrapper extends ContractWrapper {
// We use _.unzip<any> because _.unzip doesn't type check if values have different types :'(
const [orderAddresses, orderValues, cancelTakerTokenAmounts] =
_.unzip<any>(orderAddressesValuesAndTakerTokenCancelAmounts);
const gas = await exchangeInstance.batchCancelOrders.estimateGasAsync(
orderAddresses,
orderValues,
cancelTakerTokenAmounts,
{
from: maker,
},
);
const txHash = await exchangeInstance.batchCancelOrders.sendTransactionAsync(
orderAddresses,
orderValues,
cancelTakerTokenAmounts,
{
from: maker,
gas,
gas: orderTransactionOpts.gasLimit,
gasPrice: orderTransactionOpts.gasPrice,
},
);
return txHash;
}
/**
* Subscribe to an event type emitted by the Exchange smart contract
* @param eventName The exchange contract event you would like to subscribe to.
* @param subscriptionOpts Subscriptions options that let you configure the subscription.
* @param indexFilterValues An object where the keys are indexed args returned by the event and
* the value is the value you are interested in. E.g `{maker: aUserAddressHex}`
* @param exchangeContractAddress The hex encoded address of the Exchange contract to call.
* @return ContractEventEmitter object
* Subscribe to an event type emitted by the Exchange contract.
* @param eventName The exchange contract event you would like to subscribe to.
* @param indexFilterValues An object where the keys are indexed args returned by the event and
* the value is the value you are interested in. E.g `{maker: aUserAddressHex}`
* @param callback Callback that gets called when a log is added/removed
* @return Subscription token used later to unsubscribe
*/
public async subscribeAsync(eventName: ExchangeEvents, subscriptionOpts: SubscriptionOpts,
indexFilterValues: IndexedFilterValues, exchangeContractAddress: string):
Promise<ContractEventEmitter> {
assert.isETHAddressHex('exchangeContractAddress', exchangeContractAddress);
public subscribe<ArgsType extends ExchangeContractEventArgs>(
eventName: ExchangeEvents, indexFilterValues: IndexedFilterValues,
callback: EventCallback<ArgsType>): string {
assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents);
assert.doesConformToSchema('subscriptionOpts', subscriptionOpts, schemas.subscriptionOptsSchema);
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
const exchangeContract = await this._getExchangeContractAsync();
let createLogEvent: CreateContractEvent;
switch (eventName) {
case ExchangeEvents.LogFill:
createLogEvent = exchangeContract.LogFill;
break;
case ExchangeEvents.LogError:
createLogEvent = exchangeContract.LogError;
break;
case ExchangeEvents.LogCancel:
createLogEvent = exchangeContract.LogCancel;
break;
default:
throw utils.spawnSwitchErr('ExchangeEvents', eventName);
}
const logEventObj: ContractEventObj = createLogEvent(indexFilterValues, subscriptionOpts);
const eventEmitter = eventUtils.wrapEventEmitter(logEventObj);
this._exchangeLogEventEmitters.push(eventEmitter);
return eventEmitter;
assert.isFunction('callback', callback);
const exchangeContractAddress = this.getContractAddress();
const subscriptionToken = this._subscribe<ArgsType>(
exchangeContractAddress, eventName, indexFilterValues, artifacts.ExchangeArtifact.abi, callback,
);
return subscriptionToken;
}
/**
* Cancel a subscription
* @param subscriptionToken Subscription token returned by `subscribe()`
*/
public unsubscribe(subscriptionToken: string): void {
this._unsubscribe(subscriptionToken);
}
/**
* Gets historical logs without creating a subscription
@@ -666,35 +618,26 @@ export class ExchangeWrapper extends ContractWrapper {
* the value is the value you are interested in. E.g `{_from: aUserAddressHex}`
* @return Array of logs that match the parameters
*/
public async getLogsAsync(eventName: ExchangeEvents, subscriptionOpts: SubscriptionOpts,
indexFilterValues: IndexedFilterValues): Promise<LogWithDecodedArgs[]> {
public async getLogsAsync<ArgsType extends ExchangeContractEventArgs>(
eventName: ExchangeEvents, subscriptionOpts: SubscriptionOpts, indexFilterValues: IndexedFilterValues,
): Promise<Array<LogWithDecodedArgs<ArgsType>>> {
assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents);
assert.doesConformToSchema('subscriptionOpts', subscriptionOpts, schemas.subscriptionOptsSchema);
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
const exchangeContractAddress = await this.getContractAddressAsync();
const logs = await this._getLogsAsync(
const exchangeContractAddress = this.getContractAddress();
const logs = await this._getLogsAsync<ArgsType>(
exchangeContractAddress, eventName, subscriptionOpts, indexFilterValues, artifacts.ExchangeArtifact.abi,
);
return logs;
}
/**
* Stops watching for all exchange events
*/
public async stopWatchingAllEventsAsync(): Promise<void> {
const stopWatchingPromises = _.map(this._exchangeLogEventEmitters,
logEventObj => logEventObj.stopWatchingAsync());
await Promise.all(stopWatchingPromises);
this._exchangeLogEventEmitters = [];
}
/**
* Retrieves the Ethereum address of the Exchange contract deployed on the network
* that the user-passed web3 provider is connected to.
* @returns The Ethereum address of the Exchange contract being used.
*/
public async getContractAddressAsync(): Promise<string> {
const exchangeInstance = await this._getExchangeContractAsync();
const exchangeAddress = exchangeInstance.address;
return exchangeAddress;
public getContractAddress(): string {
const contractAddress = this._getContractAddress(artifacts.ExchangeArtifact, this._contractAddressIfExists);
return contractAddress;
}
/**
* Checks if order is still fillable and throws an error otherwise. Useful for orderbook
@@ -709,10 +652,11 @@ export class ExchangeWrapper extends ContractWrapper {
signedOrder: SignedOrder, opts?: ValidateOrderFillableOpts,
): Promise<void> {
assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
const zrxTokenAddress = await this.getZRXTokenAddressAsync();
const zrxTokenAddress = this.getZRXTokenAddress();
const expectedFillTakerTokenAmount = !_.isUndefined(opts) ? opts.expectedFillTakerTokenAmount : undefined;
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
await this._orderValidationUtils.validateOrderFillableOrThrowAsync(
signedOrder, zrxTokenAddress, expectedFillTakerTokenAmount,
exchangeTradeEmulator, signedOrder, zrxTokenAddress, expectedFillTakerTokenAmount,
);
}
/**
@@ -724,14 +668,15 @@ export class ExchangeWrapper extends ContractWrapper {
* Must be available via the supplied Web3.Provider passed to 0x.js.
*/
public async validateFillOrderThrowIfInvalidAsync(signedOrder: SignedOrder,
fillTakerTokenAmount: BigNumber.BigNumber,
fillTakerTokenAmount: BigNumber,
takerAddress: string): Promise<void> {
assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
assert.isBigNumber('fillTakerTokenAmount', fillTakerTokenAmount);
assert.isValidBaseUnitAmount('fillTakerTokenAmount', fillTakerTokenAmount);
await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper);
const zrxTokenAddress = await this.getZRXTokenAddressAsync();
const zrxTokenAddress = this.getZRXTokenAddress();
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
await this._orderValidationUtils.validateFillOrderThrowIfInvalidAsync(
signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress);
exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress);
}
/**
* Checks if cancelling a given order will succeed and throws an informative error if it won't.
@@ -740,12 +685,12 @@ export class ExchangeWrapper extends ContractWrapper {
* @param cancelTakerTokenAmount The amount (specified in taker tokens) that you would like to cancel.
*/
public async validateCancelOrderThrowIfInvalidAsync(
order: Order, cancelTakerTokenAmount: BigNumber.BigNumber): Promise<void> {
order: Order, cancelTakerTokenAmount: BigNumber): Promise<void> {
assert.doesConformToSchema('order', order, schemas.orderSchema);
assert.isBigNumber('cancelTakerTokenAmount', cancelTakerTokenAmount);
assert.isValidBaseUnitAmount('cancelTakerTokenAmount', cancelTakerTokenAmount);
const orderHash = utils.getOrderHashHex(order);
const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash);
await this._orderValidationUtils.validateCancelOrderThrowIfInvalidAsync(
OrderValidationUtils.validateCancelOrderThrowIfInvalid(
order, cancelTakerTokenAmount, unavailableTakerTokenAmount);
}
/**
@@ -757,14 +702,15 @@ export class ExchangeWrapper extends ContractWrapper {
* Must be available via the supplied Web3.Provider passed to 0x.js.
*/
public async validateFillOrKillOrderThrowIfInvalidAsync(signedOrder: SignedOrder,
fillTakerTokenAmount: BigNumber.BigNumber,
fillTakerTokenAmount: BigNumber,
takerAddress: string): Promise<void> {
assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
assert.isBigNumber('fillTakerTokenAmount', fillTakerTokenAmount);
assert.isValidBaseUnitAmount('fillTakerTokenAmount', fillTakerTokenAmount);
await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper);
const zrxTokenAddress = await this.getZRXTokenAddressAsync();
const zrxTokenAddress = this.getZRXTokenAddress();
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
await this._orderValidationUtils.validateFillOrKillOrderThrowIfInvalidAsync(
signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress);
exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress);
}
/**
* Checks if rounding error will be > 0.1% when computing makerTokenAmount by doing:
@@ -775,12 +721,12 @@ export class ExchangeWrapper extends ContractWrapper {
* @param takerTokenAmount The order size on the taker side
* @param makerTokenAmount The order size on the maker side
*/
public async isRoundingErrorAsync(fillTakerTokenAmount: BigNumber.BigNumber,
takerTokenAmount: BigNumber.BigNumber,
makerTokenAmount: BigNumber.BigNumber): Promise<boolean> {
assert.isBigNumber('fillTakerTokenAmount', fillTakerTokenAmount);
assert.isBigNumber('takerTokenAmount', takerTokenAmount);
assert.isBigNumber('makerTokenAmount', makerTokenAmount);
public async isRoundingErrorAsync(fillTakerTokenAmount: BigNumber,
takerTokenAmount: BigNumber,
makerTokenAmount: BigNumber): Promise<boolean> {
assert.isValidBaseUnitAmount('fillTakerTokenAmount', fillTakerTokenAmount);
assert.isValidBaseUnitAmount('takerTokenAmount', takerTokenAmount);
assert.isValidBaseUnitAmount('makerTokenAmount', makerTokenAmount);
const exchangeInstance = await this._getExchangeContractAsync();
const isRoundingError = await exchangeInstance.isRoundingError.callAsync(
fillTakerTokenAmount, takerTokenAmount, makerTokenAmount,
@@ -789,12 +735,14 @@ export class ExchangeWrapper extends ContractWrapper {
}
/**
* Checks if logs contain LogError, which is emmited by Exchange contract on transaction failure.
* @param logsWithDecodedArgs Transaction logs as returned by `zeroEx.awaitTransactionMinedAsync`
* @param logs Transaction logs as returned by `zeroEx.awaitTransactionMinedAsync`
*/
public throwLogErrorsAsErrors(logsWithDecodedArgs: LogWithDecodedArgs[]): void {
const errLog = _.find(logsWithDecodedArgs, {event: ExchangeEvents.LogError});
public throwLogErrorsAsErrors(logs: Array<LogWithDecodedArgs<DecodedLogArgs>|Web3.LogEntry>): void {
const errLog = _.find(logs, {
event: ExchangeEvents.LogError,
}) as LogWithDecodedArgs<LogErrorContractEventArgs>|undefined;
if (!_.isUndefined(errLog)) {
const logArgs: LogErrorContractEventArgs = errLog.args as any;
const logArgs = errLog.args;
const errCode = logArgs.errorId.toNumber();
const errMessage = this._exchangeContractErrCodesToMsg[errCode];
throw new Error(errMessage);
@@ -804,13 +752,14 @@ export class ExchangeWrapper extends ContractWrapper {
* Returns the ZRX token address used by the exchange contract.
* @return Address of ZRX token
*/
public async getZRXTokenAddressAsync(): Promise<string> {
const exchangeInstance = await this._getExchangeContractAsync();
const ZRXtokenAddress = await exchangeInstance.ZRX_TOKEN_CONTRACT.callAsync();
return ZRXtokenAddress;
public getZRXTokenAddress(): string {
const contractAddress = this._getContractAddress(
artifacts.ZRXArtifact, this._zrxContractAddressIfExists,
);
return contractAddress;
}
private async _invalidateContractInstancesAsync(): Promise<void> {
await this.stopWatchingAllEventsAsync();
private _invalidateContractInstances(): void {
this.unsubscribeAll();
delete this._exchangeContractIfExists;
}
private async _isValidSignatureUsingContractCallAsync(dataHex: string, ecSignature: ECSignature,
@@ -843,7 +792,7 @@ export class ExchangeWrapper extends ContractWrapper {
const contractInstance = await this._instantiateContractIfExistsAsync<ExchangeContract>(
artifacts.ExchangeArtifact, this._contractAddressIfExists,
);
this._exchangeContractIfExists = contractInstance as ExchangeContract;
this._exchangeContractIfExists = contractInstance;
return this._exchangeContractIfExists;
}
private async _getTokenTransferProxyAddressAsync(): Promise<string> {
@@ -852,4 +801,4 @@ export class ExchangeWrapper extends ContractWrapper {
const tokenTransferProxyAddressLowerCase = tokenTransferProxyAddress.toLowerCase();
return tokenTransferProxyAddressLowerCase;
}
}
} // tslint:disable:max-file-line-count

View File

@@ -1,10 +1,12 @@
import * as _ from 'lodash';
import {Web3Wrapper} from '../web3_wrapper';
import {assert} from '../utils/assert';
import {Token, TokenRegistryContract, TokenMetadata} from '../types';
import {constants} from '../utils/constants';
import {ContractWrapper} from './contract_wrapper';
import {artifacts} from '../artifacts';
import {Token, TokenMetadata, TokenRegistryContract, ZeroExError} from '../types';
import {assert} from '../utils/assert';
import {constants} from '../utils/constants';
import {Web3Wrapper} from '../web3_wrapper';
import {ContractWrapper} from './contract_wrapper';
/**
* This class includes all the functionality related to interacting with the 0x Token Registry smart contract.
@@ -12,6 +14,18 @@ import {artifacts} from '../artifacts';
export class TokenRegistryWrapper extends ContractWrapper {
private _tokenRegistryContractIfExists?: TokenRegistryContract;
private _contractAddressIfExists?: string;
private static _createTokenFromMetadata(metadata: TokenMetadata): Token|undefined {
if (metadata[0] === constants.NULL_ADDRESS) {
return undefined;
}
const token = {
address: metadata[0],
name: metadata[1],
symbol: metadata[2],
decimals: metadata[3].toNumber(),
};
return token;
}
constructor(web3Wrapper: Web3Wrapper, contractAddressIfExists?: string) {
super(web3Wrapper);
this._contractAddressIfExists = contractAddressIfExists;
@@ -26,7 +40,7 @@ export class TokenRegistryWrapper extends ContractWrapper {
const addresses = await this.getTokenAddressesAsync();
const tokenPromises: Array<Promise<Token|undefined>> = _.map(
addresses,
(address: string) => (this.getTokenIfExistsAsync(address)),
async (address: string) => this.getTokenIfExistsAsync(address),
);
const tokens = await Promise.all(tokenPromises);
return tokens as Token[];
@@ -49,7 +63,7 @@ export class TokenRegistryWrapper extends ContractWrapper {
const tokenRegistryContract = await this._getTokenRegistryContractAsync();
const metadata = await tokenRegistryContract.getTokenMetaData.callAsync(address);
const token = this._createTokenFromMetadata(metadata);
const token = TokenRegistryWrapper._createTokenFromMetadata(metadata);
return token;
}
public async getTokenAddressBySymbolIfExistsAsync(symbol: string): Promise<string|undefined> {
@@ -74,14 +88,14 @@ export class TokenRegistryWrapper extends ContractWrapper {
assert.isString('symbol', symbol);
const tokenRegistryContract = await this._getTokenRegistryContractAsync();
const metadata = await tokenRegistryContract.getTokenBySymbol.callAsync(symbol);
const token = this._createTokenFromMetadata(metadata);
const token = TokenRegistryWrapper._createTokenFromMetadata(metadata);
return token;
}
public async getTokenByNameIfExistsAsync(name: string): Promise<Token|undefined> {
assert.isString('name', name);
const tokenRegistryContract = await this._getTokenRegistryContractAsync();
const metadata = await tokenRegistryContract.getTokenByName.callAsync(name);
const token = this._createTokenFromMetadata(metadata);
const token = TokenRegistryWrapper._createTokenFromMetadata(metadata);
return token;
}
/**
@@ -89,22 +103,11 @@ export class TokenRegistryWrapper extends ContractWrapper {
* that the user-passed web3 provider is connected to.
* @returns The Ethereum address of the TokenRegistry contract being used.
*/
public async getContractAddressAsync(): Promise<string> {
const tokenRegistryInstance = await this._getTokenRegistryContractAsync();
const tokenRegistryAddress = tokenRegistryInstance.address;
return tokenRegistryAddress;
}
private _createTokenFromMetadata(metadata: TokenMetadata): Token|undefined {
if (metadata[0] === constants.NULL_ADDRESS) {
return undefined;
}
const token = {
address: metadata[0],
name: metadata[1],
symbol: metadata[2],
decimals: metadata[3].toNumber(),
};
return token;
public getContractAddress(): string {
const contractAddress = this._getContractAddress(
artifacts.TokenRegistryArtifact, this._contractAddressIfExists,
);
return contractAddress;
}
private _invalidateContractInstance(): void {
delete this._tokenRegistryContractIfExists;
@@ -116,7 +119,7 @@ export class TokenRegistryWrapper extends ContractWrapper {
const contractInstance = await this._instantiateContractIfExistsAsync<TokenRegistryContract>(
artifacts.TokenRegistryArtifact, this._contractAddressIfExists,
);
this._tokenRegistryContractIfExists = contractInstance as TokenRegistryContract;
this._tokenRegistryContractIfExists = contractInstance;
return this._tokenRegistryContractIfExists;
}
}

View File

@@ -1,18 +1,20 @@
import * as _ from 'lodash';
import {Web3Wrapper} from '../web3_wrapper';
import {ContractWrapper} from './contract_wrapper';
import {artifacts} from '../artifacts';
import {TokenTransferProxyContract} from '../types';
import {TokenTransferProxyContract, ZeroExError} from '../types';
import {Web3Wrapper} from '../web3_wrapper';
import {ContractWrapper} from './contract_wrapper';
/**
* This class includes the functionality related to interacting with the TokenTransferProxy contract.
*/
export class TokenTransferProxyWrapper extends ContractWrapper {
private _tokenTransferProxyContractIfExists?: TokenTransferProxyContract;
private _tokenTransferProxyContractAddressFetcher: () => Promise<string>;
constructor(web3Wrapper: Web3Wrapper, tokenTransferProxyContractAddressFetcher: () => Promise<string>) {
private _contractAddressIfExists?: string;
constructor(web3Wrapper: Web3Wrapper, contractAddressIfExists?: string) {
super(web3Wrapper);
this._tokenTransferProxyContractAddressFetcher = tokenTransferProxyContractAddressFetcher;
this._contractAddressIfExists = contractAddressIfExists;
}
/**
* Check if the Exchange contract address is authorized by the TokenTransferProxy contract.
@@ -38,10 +40,11 @@ export class TokenTransferProxyWrapper extends ContractWrapper {
* that the user-passed web3 provider is connected to.
* @returns The Ethereum address of the TokenTransferProxy contract being used.
*/
public async getContractAddressAsync(): Promise<string> {
const proxyInstance = await this._getTokenTransferProxyContractAsync();
const proxyAddress = proxyInstance.address;
return proxyAddress;
public getContractAddress(): string {
const contractAddress = this._getContractAddress(
artifacts.TokenTransferProxyArtifact, this._contractAddressIfExists,
);
return contractAddress;
}
private _invalidateContractInstance(): void {
delete this._tokenTransferProxyContractIfExists;
@@ -50,11 +53,10 @@ export class TokenTransferProxyWrapper extends ContractWrapper {
if (!_.isUndefined(this._tokenTransferProxyContractIfExists)) {
return this._tokenTransferProxyContractIfExists;
}
const contractAddress = await this._tokenTransferProxyContractAddressFetcher();
const contractInstance = await this._instantiateContractIfExistsAsync<TokenTransferProxyContract>(
artifacts.TokenTransferProxyArtifact, contractAddress,
artifacts.TokenTransferProxyArtifact, this._contractAddressIfExists,
);
this._tokenTransferProxyContractIfExists = contractInstance as TokenTransferProxyContract;
this._tokenTransferProxyContractIfExists = contractInstance;
return this._tokenTransferProxyContractIfExists;
}
}

View File

@@ -1,29 +1,29 @@
import {schemas} from '@0xproject/json-schemas';
import BigNumber from 'bignumber.js';
import * as _ from 'lodash';
import * as BigNumber from 'bignumber.js';
import {SchemaValidator, schemas} from '0x-json-schemas';
import {Web3Wrapper} from '../web3_wrapper';
import {assert} from '../utils/assert';
import {utils} from '../utils/utils';
import {eventUtils} from '../utils/event_utils';
import {constants} from '../utils/constants';
import {ContractWrapper} from './contract_wrapper';
import {AbiDecoder} from '../utils/abi_decoder';
import {artifacts} from '../artifacts';
import {
TokenContract,
ZeroExError,
TokenEvents,
EventCallback,
IndexedFilterValues,
SubscriptionOpts,
CreateContractEvent,
ContractEventEmitter,
ContractEventObj,
MethodOpts,
LogWithDecodedArgs,
RawLog,
MethodOpts,
SubscriptionOpts,
TokenContract,
TokenContractEventArgs,
TokenEvents,
TransactionOpts,
ZeroExError,
} from '../types';
import {AbiDecoder} from '../utils/abi_decoder';
import {assert} from '../utils/assert';
import {constants} from '../utils/constants';
import {Web3Wrapper} from '../web3_wrapper';
const ALLOWANCE_TO_ZERO_GAS_AMOUNT = 47155;
import {ContractWrapper} from './contract_wrapper';
import {TokenTransferProxyWrapper} from './token_transfer_proxy_wrapper';
const ALLOWANCE_TO_ZERO_GAS_AMOUNT = 47275;
/**
* This class includes all the functionality related to interacting with ERC20 token contracts.
@@ -33,14 +33,12 @@ const ALLOWANCE_TO_ZERO_GAS_AMOUNT = 47155;
export class TokenWrapper extends ContractWrapper {
public UNLIMITED_ALLOWANCE_IN_BASE_UNITS = constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
private _tokenContractsByAddress: {[address: string]: TokenContract};
private _tokenLogEventEmitters: ContractEventEmitter[];
private _tokenTransferProxyContractAddressFetcher: () => Promise<string>;
private _tokenTransferProxyWrapper: TokenTransferProxyWrapper;
constructor(web3Wrapper: Web3Wrapper, abiDecoder: AbiDecoder,
tokenTransferProxyContractAddressFetcher: () => Promise<string>) {
tokenTransferProxyWrapper: TokenTransferProxyWrapper) {
super(web3Wrapper, abiDecoder);
this._tokenContractsByAddress = {};
this._tokenLogEventEmitters = [];
this._tokenTransferProxyContractAddressFetcher = tokenTransferProxyContractAddressFetcher;
this._tokenTransferProxyWrapper = tokenTransferProxyWrapper;
}
/**
* Retrieves an owner's ERC20 token balance.
@@ -50,7 +48,7 @@ export class TokenWrapper extends ContractWrapper {
* @return The owner's ERC20 token balance in base units.
*/
public async getBalanceAsync(tokenAddress: string, ownerAddress: string,
methodOpts?: MethodOpts): Promise<BigNumber.BigNumber> {
methodOpts?: MethodOpts): Promise<BigNumber> {
assert.isETHAddressHex('ownerAddress', ownerAddress);
assert.isETHAddressHex('tokenAddress', tokenAddress);
@@ -69,24 +67,21 @@ export class TokenWrapper extends ContractWrapper {
* for spenderAddress.
* @param spenderAddress The hex encoded user Ethereum address who will be able to spend the set allowance.
* @param amountInBaseUnits The allowance amount you would like to set.
* @param txOpts Transaction parameters.
* @return Transaction hash.
*/
public async setAllowanceAsync(tokenAddress: string, ownerAddress: string, spenderAddress: string,
amountInBaseUnits: BigNumber.BigNumber): Promise<string> {
amountInBaseUnits: BigNumber, txOpts: TransactionOpts = {}): Promise<string> {
await assert.isSenderAddressAsync('ownerAddress', ownerAddress, this._web3Wrapper);
assert.isETHAddressHex('spenderAddress', spenderAddress);
assert.isETHAddressHex('tokenAddress', tokenAddress);
assert.isBigNumber('amountInBaseUnits', amountInBaseUnits);
assert.isValidBaseUnitAmount('amountInBaseUnits', amountInBaseUnits);
const tokenContract = await this._getTokenContractAsync(tokenAddress);
// Hack: for some reason default estimated gas amount causes `base fee exceeds gas limit` exception
// on testrpc. Probably related to https://github.com/ethereumjs/testrpc/issues/294
// TODO: Debug issue in testrpc and submit a PR, then remove this hack
const networkIdIfExists = await this._web3Wrapper.getNetworkIdIfExistsAsync();
const gas = networkIdIfExists === constants.TESTRPC_NETWORK_ID ? ALLOWANCE_TO_ZERO_GAS_AMOUNT : undefined;
const txHash = await tokenContract.approve.sendTransactionAsync(spenderAddress, amountInBaseUnits, {
from: ownerAddress,
gas,
gas: txOpts.gasLimit,
gasPrice: txOpts.gasPrice,
});
return txHash;
}
@@ -99,12 +94,13 @@ export class TokenWrapper extends ContractWrapper {
* @param ownerAddress The hex encoded user Ethereum address who would like to set an allowance
* for spenderAddress.
* @param spenderAddress The hex encoded user Ethereum address who will be able to spend the set allowance.
* @param txOpts Transaction parameters.
* @return Transaction hash.
*/
public async setUnlimitedAllowanceAsync(tokenAddress: string, ownerAddress: string,
spenderAddress: string): Promise<string> {
spenderAddress: string, txOpts: TransactionOpts = {}): Promise<string> {
const txHash = await this.setAllowanceAsync(
tokenAddress, ownerAddress, spenderAddress, this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS,
tokenAddress, ownerAddress, spenderAddress, this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS, txOpts,
);
return txHash;
}
@@ -117,7 +113,7 @@ export class TokenWrapper extends ContractWrapper {
* @param methodOpts Optional arguments this method accepts.
*/
public async getAllowanceAsync(tokenAddress: string, ownerAddress: string,
spenderAddress: string, methodOpts?: MethodOpts): Promise<BigNumber.BigNumber> {
spenderAddress: string, methodOpts?: MethodOpts): Promise<BigNumber> {
assert.isETHAddressHex('ownerAddress', ownerAddress);
assert.isETHAddressHex('tokenAddress', tokenAddress);
@@ -135,11 +131,11 @@ export class TokenWrapper extends ContractWrapper {
* @param methodOpts Optional arguments this method accepts.
*/
public async getProxyAllowanceAsync(tokenAddress: string, ownerAddress: string,
methodOpts?: MethodOpts): Promise<BigNumber.BigNumber> {
methodOpts?: MethodOpts): Promise<BigNumber> {
assert.isETHAddressHex('ownerAddress', ownerAddress);
assert.isETHAddressHex('tokenAddress', tokenAddress);
const proxyAddress = await this._getTokenTransferProxyAddressAsync();
const proxyAddress = this._tokenTransferProxyWrapper.getContractAddress();
const allowanceInBaseUnits = await this.getAllowanceAsync(tokenAddress, ownerAddress, proxyAddress, methodOpts);
return allowanceInBaseUnits;
}
@@ -150,16 +146,19 @@ export class TokenWrapper extends ContractWrapper {
* @param ownerAddress The hex encoded user Ethereum address who is setting an allowance
* for the Proxy contract.
* @param amountInBaseUnits The allowance amount specified in baseUnits.
* @param txOpts Transaction parameters.
* @return Transaction hash.
*/
public async setProxyAllowanceAsync(tokenAddress: string, ownerAddress: string,
amountInBaseUnits: BigNumber.BigNumber): Promise<string> {
amountInBaseUnits: BigNumber, txOpts: TransactionOpts = {}): Promise<string> {
assert.isETHAddressHex('ownerAddress', ownerAddress);
assert.isETHAddressHex('tokenAddress', tokenAddress);
assert.isBigNumber('amountInBaseUnits', amountInBaseUnits);
assert.isValidBaseUnitAmount('amountInBaseUnits', amountInBaseUnits);
const proxyAddress = await this._getTokenTransferProxyAddressAsync();
const txHash = await this.setAllowanceAsync(tokenAddress, ownerAddress, proxyAddress, amountInBaseUnits);
const proxyAddress = this._tokenTransferProxyWrapper.getContractAddress();
const txHash = await this.setAllowanceAsync(
tokenAddress, ownerAddress, proxyAddress, amountInBaseUnits, txOpts,
);
return txHash;
}
/**
@@ -170,11 +169,14 @@ export class TokenWrapper extends ContractWrapper {
* @param tokenAddress The hex encoded contract Ethereum address where the ERC20 token is deployed.
* @param ownerAddress The hex encoded user Ethereum address who is setting an allowance
* for the Proxy contract.
* @param txOpts Transaction parameters.
* @return Transaction hash.
*/
public async setUnlimitedProxyAllowanceAsync(tokenAddress: string, ownerAddress: string): Promise<string> {
public async setUnlimitedProxyAllowanceAsync(
tokenAddress: string, ownerAddress: string, txOpts: TransactionOpts = {},
): Promise<string> {
const txHash = await this.setProxyAllowanceAsync(
tokenAddress, ownerAddress, this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS,
tokenAddress, ownerAddress, this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS, txOpts,
);
return txHash;
}
@@ -184,14 +186,15 @@ export class TokenWrapper extends ContractWrapper {
* @param fromAddress The hex encoded user Ethereum address that will send the funds.
* @param toAddress The hex encoded user Ethereum address that will receive the funds.
* @param amountInBaseUnits The amount (specified in baseUnits) of the token to transfer.
* @param txOpts Transaction parameters.
* @return Transaction hash.
*/
public async transferAsync(tokenAddress: string, fromAddress: string, toAddress: string,
amountInBaseUnits: BigNumber.BigNumber): Promise<string> {
amountInBaseUnits: BigNumber, txOpts: TransactionOpts = {}): Promise<string> {
assert.isETHAddressHex('tokenAddress', tokenAddress);
await assert.isSenderAddressAsync('fromAddress', fromAddress, this._web3Wrapper);
assert.isETHAddressHex('toAddress', toAddress);
assert.isBigNumber('amountInBaseUnits', amountInBaseUnits);
assert.isValidBaseUnitAmount('amountInBaseUnits', amountInBaseUnits);
const tokenContract = await this._getTokenContractAsync(tokenAddress);
@@ -202,6 +205,8 @@ export class TokenWrapper extends ContractWrapper {
const txHash = await tokenContract.transfer.sendTransactionAsync(toAddress, amountInBaseUnits, {
from: fromAddress,
gas: txOpts.gasLimit,
gasPrice: txOpts.gasPrice,
});
return txHash;
}
@@ -216,16 +221,17 @@ export class TokenWrapper extends ContractWrapper {
* `fromAddress` must have set an allowance to the `senderAddress`
* before this call.
* @param amountInBaseUnits The amount (specified in baseUnits) of the token to transfer.
* @param txOpts Transaction parameters.
* @return Transaction hash.
*/
public async transferFromAsync(tokenAddress: string, fromAddress: string, toAddress: string,
senderAddress: string, amountInBaseUnits: BigNumber.BigNumber):
senderAddress: string, amountInBaseUnits: BigNumber, txOpts: TransactionOpts = {}):
Promise<string> {
assert.isETHAddressHex('tokenAddress', tokenAddress);
assert.isETHAddressHex('fromAddress', fromAddress);
assert.isETHAddressHex('toAddress', toAddress);
await assert.isSenderAddressAsync('senderAddress', senderAddress, this._web3Wrapper);
assert.isBigNumber('amountInBaseUnits', amountInBaseUnits);
assert.isValidBaseUnitAmount('amountInBaseUnits', amountInBaseUnits);
const tokenContract = await this._getTokenContractAsync(tokenAddress);
@@ -243,6 +249,8 @@ export class TokenWrapper extends ContractWrapper {
fromAddress, toAddress, amountInBaseUnits,
{
from: senderAddress,
gas: txOpts.gasLimit,
gasPrice: txOpts.gasPrice,
},
);
return txHash;
@@ -251,34 +259,29 @@ export class TokenWrapper extends ContractWrapper {
* Subscribe to an event type emitted by the Token contract.
* @param tokenAddress The hex encoded address where the ERC20 token is deployed.
* @param eventName The token contract event you would like to subscribe to.
* @param subscriptionOpts Subscriptions options that let you configure the subscription.
* @param indexFilterValues An object where the keys are indexed args returned by the event and
* the value is the value you are interested in. E.g `{maker: aUserAddressHex}`
* @return ContractEventEmitter object
* @param callback Callback that gets called when a log is added/removed
* @return Subscription token used later to unsubscribe
*/
public async subscribeAsync(tokenAddress: string, eventName: TokenEvents, subscriptionOpts: SubscriptionOpts,
indexFilterValues: IndexedFilterValues): Promise<ContractEventEmitter> {
public subscribe<ArgsType extends TokenContractEventArgs>(
tokenAddress: string, eventName: TokenEvents, indexFilterValues: IndexedFilterValues,
callback: EventCallback<ArgsType>): string {
assert.isETHAddressHex('tokenAddress', tokenAddress);
assert.doesBelongToStringEnum('eventName', eventName, TokenEvents);
assert.doesConformToSchema('subscriptionOpts', subscriptionOpts, schemas.subscriptionOptsSchema);
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
const tokenContract = await this._getTokenContractAsync(tokenAddress);
let createLogEvent: CreateContractEvent;
switch (eventName) {
case TokenEvents.Approval:
createLogEvent = tokenContract.Approval;
break;
case TokenEvents.Transfer:
createLogEvent = tokenContract.Transfer;
break;
default:
throw utils.spawnSwitchErr('TokenEvents', eventName);
}
const logEventObj: ContractEventObj = createLogEvent(indexFilterValues, subscriptionOpts);
const eventEmitter = eventUtils.wrapEventEmitter(logEventObj);
this._tokenLogEventEmitters.push(eventEmitter);
return eventEmitter;
assert.isFunction('callback', callback);
const subscriptionToken = this._subscribe<ArgsType>(
tokenAddress, eventName, indexFilterValues, artifacts.TokenArtifact.abi, callback,
);
return subscriptionToken;
}
/**
* Cancel a subscription
* @param subscriptionToken Subscription token returned by `subscribe()`
*/
public unsubscribe(subscriptionToken: string): void {
this._unsubscribe(subscriptionToken);
}
/**
* Gets historical logs without creating a subscription
@@ -289,28 +292,20 @@ export class TokenWrapper extends ContractWrapper {
* the value is the value you are interested in. E.g `{_from: aUserAddressHex}`
* @return Array of logs that match the parameters
*/
public async getLogsAsync(tokenAddress: string, eventName: TokenEvents, subscriptionOpts: SubscriptionOpts,
indexFilterValues: IndexedFilterValues): Promise<LogWithDecodedArgs[]> {
public async getLogsAsync<ArgsType extends TokenContractEventArgs>(
tokenAddress: string, eventName: TokenEvents, subscriptionOpts: SubscriptionOpts,
indexFilterValues: IndexedFilterValues): Promise<Array<LogWithDecodedArgs<ArgsType>>> {
assert.isETHAddressHex('tokenAddress', tokenAddress);
assert.doesBelongToStringEnum('eventName', eventName, TokenEvents);
assert.doesConformToSchema('subscriptionOpts', subscriptionOpts, schemas.subscriptionOptsSchema);
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
const logs = await this._getLogsAsync(
const logs = await this._getLogsAsync<ArgsType>(
tokenAddress, eventName, subscriptionOpts, indexFilterValues, artifacts.TokenArtifact.abi,
);
return logs;
}
/**
* Stops watching for all token events
*/
public async stopWatchingAllEventsAsync(): Promise<void> {
const stopWatchingPromises = _.map(this._tokenLogEventEmitters,
logEventObj => logEventObj.stopWatchingAsync());
await Promise.all(stopWatchingPromises);
this._tokenLogEventEmitters = [];
}
private async _invalidateContractInstancesAsync(): Promise<void> {
await this.stopWatchingAllEventsAsync();
private _invalidateContractInstances(): void {
this.unsubscribeAll();
this._tokenContractsByAddress = {};
}
private async _getTokenContractAsync(tokenAddress: string): Promise<TokenContract> {
@@ -321,12 +316,8 @@ export class TokenWrapper extends ContractWrapper {
const contractInstance = await this._instantiateContractIfExistsAsync<TokenContract>(
artifacts.TokenArtifact, tokenAddress,
);
tokenContract = contractInstance as TokenContract;
tokenContract = contractInstance;
this._tokenContractsByAddress[tokenAddress] = tokenContract;
return tokenContract;
}
private async _getTokenTransferProxyAddressAsync(): Promise<string> {
const tokenTransferProxyContractAddress = await this._tokenTransferProxyContractAddressFetcher();
return tokenTransferProxyContractAddress;
}
}

View File

@@ -12,12 +12,6 @@ declare module 'web3-provider-engine/subproviders/rpc';
// disallow `namespace`, we disable tslint for the following.
/* tslint:disable */
declare namespace Chai {
interface NumberComparer {
(value: number|BigNumber.BigNumber, message?: string): Assertion;
}
interface NumericComparison {
greaterThan: NumberComparer;
}
interface Assertion {
bignumber: Assertion;
// HACK: In order to comply with chai-as-promised we make eventually a `PromisedAssertion` not an `Assertion`
@@ -70,8 +64,6 @@ declare module 'truffle-hdwallet-provider' {
// abi-decoder declarations
interface DecodedLogArg {
name: string;
value: string|BigNumber.BigNumber;
}
interface DecodedLog {
name: string;

23
packages/0x.js/src/globalsAugment.d.ts vendored Normal file
View File

@@ -0,0 +1,23 @@
import BigNumber from 'bignumber.js';
// HACK: This module overrides the Chai namespace so that we can use BigNumber types inside.
// Source: https://github.com/Microsoft/TypeScript/issues/7352#issuecomment-191547232
declare global {
// HACK: In order to merge the bignumber declaration added by chai-bignumber to the chai Assertion
// interface we must use `namespace` as the Chai definitelyTyped definition does. Since we otherwise
// disallow `namespace`, we disable tslint for the following.
/* tslint:disable */
namespace Chai {
interface NumberComparer {
(value: number|BigNumber, message?: string): Assertion;
}
interface NumericComparison {
greaterThan: NumberComparer;
}
}
/* tslint:enable */
interface DecodedLogArg {
name: string;
value: string|BigNumber;
}
}

View File

@@ -6,8 +6,6 @@ export {
ECSignature,
ZeroExError,
EventCallback,
EventCallbackAsync,
EventCallbackSync,
ExchangeContractErrs,
ContractEvent,
Token,
@@ -16,10 +14,8 @@ export {
IndexedFilterValues,
SubscriptionOpts,
BlockParam,
OrderFillOrKillRequest,
OrderCancellationRequest,
OrderFillRequest,
ContractEventEmitter,
LogErrorContractEventArgs,
LogCancelContractEventArgs,
LogFillContractEventArgs,
@@ -28,12 +24,20 @@ export {
ApprovalContractEventArgs,
TokenContractEventArgs,
ContractEventArgs,
ContractEventArg,
Web3Provider,
ZeroExConfig,
TransactionReceipt,
TransactionReceiptWithDecodedLogs,
LogWithDecodedArgs,
DecodedLogArgs,
MethodOpts,
OrderTransactionOpts,
FilterObject,
LogEvent,
DecodedLogEvent,
EventWatcherCallback,
OnOrderStateChangeCallback,
OrderStateValid,
OrderStateInvalid,
OrderState,
} from './types';

View File

@@ -0,0 +1,89 @@
import * as _ from 'lodash';
import * as Web3 from 'web3';
import {
BlockParamLiteral,
EventCallback,
EventWatcherCallback,
ZeroExError,
} from '../types';
import {AbiDecoder} from '../utils/abi_decoder';
import {assert} from '../utils/assert';
import {intervalUtils} from '../utils/interval_utils';
import {utils} from '../utils/utils';
import {Web3Wrapper} from '../web3_wrapper';
const DEFAULT_EVENT_POLLING_INTERVAL_MS = 200;
enum LogEventState {
Removed,
Added,
}
/*
* The EventWatcher watches for blockchain events at the specified block confirmation
* depth.
*/
export class EventWatcher {
private _web3Wrapper: Web3Wrapper;
private _pollingIntervalMs: number;
private _intervalIdIfExists?: NodeJS.Timer;
private _lastEvents: Web3.LogEntry[] = [];
constructor(web3Wrapper: Web3Wrapper, pollingIntervalIfExistsMs: undefined|number) {
this._web3Wrapper = web3Wrapper;
this._pollingIntervalMs = _.isUndefined(pollingIntervalIfExistsMs) ?
DEFAULT_EVENT_POLLING_INTERVAL_MS :
pollingIntervalIfExistsMs;
}
public subscribe(callback: EventWatcherCallback): void {
assert.isFunction('callback', callback);
if (!_.isUndefined(this._intervalIdIfExists)) {
throw new Error(ZeroExError.SubscriptionAlreadyPresent);
}
this._intervalIdIfExists = intervalUtils.setAsyncExcludingInterval(
this._pollForBlockchainEventsAsync.bind(this, callback), this._pollingIntervalMs,
);
}
public unsubscribe(): void {
this._lastEvents = [];
if (!_.isUndefined(this._intervalIdIfExists)) {
intervalUtils.clearAsyncExcludingInterval(this._intervalIdIfExists);
delete this._intervalIdIfExists;
}
}
private async _pollForBlockchainEventsAsync(callback: EventWatcherCallback): Promise<void> {
const pendingEvents = await this._getEventsAsync();
if (pendingEvents.length === 0) {
// HACK: Sometimes when node rebuilds the pending block we get back the empty result.
// We don't want to emit a lot of removal events and bring them back after a couple of miliseconds,
// that's why we just ignore those cases.
return;
}
const removedEvents = _.differenceBy(this._lastEvents, pendingEvents, JSON.stringify);
const newEvents = _.differenceBy(pendingEvents, this._lastEvents, JSON.stringify);
await this._emitDifferencesAsync(removedEvents, LogEventState.Removed, callback);
await this._emitDifferencesAsync(newEvents, LogEventState.Added, callback);
this._lastEvents = pendingEvents;
}
private async _getEventsAsync(): Promise<Web3.LogEntry[]> {
const eventFilter = {
fromBlock: BlockParamLiteral.Pending,
toBlock: BlockParamLiteral.Pending,
};
const events = await this._web3Wrapper.getLogsAsync(eventFilter);
return events;
}
private async _emitDifferencesAsync(
logs: Web3.LogEntry[], logEventState: LogEventState, callback: EventWatcherCallback,
): Promise<void> {
for (const log of logs) {
const logEvent = {
removed: logEventState === LogEventState.Removed,
...log,
};
if (!_.isUndefined(this._intervalIdIfExists)) {
callback(logEvent);
}
}
}
}

View File

@@ -0,0 +1,77 @@
import {BigNumber} from 'bignumber.js';
import {RBTree} from 'bintrees';
import * as _ from 'lodash';
import {ZeroEx} from '../0x';
import {SignedOrder, ZeroExError} from '../types';
import {intervalUtils} from '../utils/interval_utils';
import {utils} from '../utils/utils';
const DEFAULT_EXPIRATION_MARGIN_MS = 0;
const DEFAULT_ORDER_EXPIRATION_CHECKING_INTERVAL_MS = 50;
/**
* This class includes the functionality to detect expired orders.
* It stores them in a min heap by expiration time and checks for expired ones every `orderExpirationCheckingIntervalMs`
*/
export class ExpirationWatcher {
private orderHashByExpirationRBTree: RBTree<string>;
private expiration: {[orderHash: string]: BigNumber} = {};
private orderExpirationCheckingIntervalMs: number;
private expirationMarginMs: number;
private orderExpirationCheckingIntervalIdIfExists?: NodeJS.Timer;
constructor(expirationMarginIfExistsMs?: number,
orderExpirationCheckingIntervalIfExistsMs?: number) {
this.expirationMarginMs = expirationMarginIfExistsMs ||
DEFAULT_EXPIRATION_MARGIN_MS;
this.orderExpirationCheckingIntervalMs = expirationMarginIfExistsMs ||
DEFAULT_ORDER_EXPIRATION_CHECKING_INTERVAL_MS;
const scoreFunction = (orderHash: string) => this.expiration[orderHash].toNumber();
const comparator = (lhs: string, rhs: string) => scoreFunction(lhs) - scoreFunction(rhs);
this.orderHashByExpirationRBTree = new RBTree(comparator);
}
public subscribe(callback: (orderHash: string) => void): void {
if (!_.isUndefined(this.orderExpirationCheckingIntervalIdIfExists)) {
throw new Error(ZeroExError.SubscriptionAlreadyPresent);
}
this.orderExpirationCheckingIntervalIdIfExists = intervalUtils.setAsyncExcludingInterval(
this.pruneExpiredOrders.bind(this, callback), this.orderExpirationCheckingIntervalMs,
);
}
public unsubscribe(): void {
if (_.isUndefined(this.orderExpirationCheckingIntervalIdIfExists)) {
throw new Error(ZeroExError.SubscriptionNotFound);
}
intervalUtils.clearAsyncExcludingInterval(this.orderExpirationCheckingIntervalIdIfExists);
delete this.orderExpirationCheckingIntervalIdIfExists;
}
public addOrder(orderHash: string, expirationUnixTimestampMs: BigNumber): void {
this.expiration[orderHash] = expirationUnixTimestampMs;
this.orderHashByExpirationRBTree.insert(orderHash);
}
public removeOrder(orderHash: string): void {
this.orderHashByExpirationRBTree.remove(orderHash);
delete this.expiration[orderHash];
}
private pruneExpiredOrders(callback: (orderHash: string) => void): void {
const currentUnixTimestampMs = utils.getCurrentUnixTimestampMs();
while (true) {
const hasTrakedOrders = this.orderHashByExpirationRBTree.size === 0;
if (hasTrakedOrders) {
break;
}
const nextOrderHashToExpire = this.orderHashByExpirationRBTree.min();
const hasNoExpiredOrders = this.expiration[nextOrderHashToExpire].greaterThan(
currentUnixTimestampMs.plus(this.expirationMarginMs),
);
const isSubscriptionActive = _.isUndefined(this.orderExpirationCheckingIntervalIdIfExists);
if (hasNoExpiredOrders || isSubscriptionActive) {
break;
}
const orderHash = this.orderHashByExpirationRBTree.min();
this.orderHashByExpirationRBTree.remove(orderHash);
delete this.expiration[orderHash];
callback(orderHash);
}
}
}

View File

@@ -0,0 +1,327 @@
import {schemas} from '@0xproject/json-schemas';
import * as _ from 'lodash';
import {ZeroEx} from '../0x';
import {artifacts} from '../artifacts';
import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper';
import {TokenWrapper} from '../contract_wrappers/token_wrapper';
import {BalanceAndProxyAllowanceLazyStore} from '../stores/balance_proxy_allowance_lazy_store';
import {OrderFilledCancelledLazyStore} from '../stores/order_filled_cancelled_lazy_store';
import {
ApprovalContractEventArgs,
BlockParamLiteral,
ContractEventArgs,
ExchangeContractErrs,
ExchangeEvents,
LogCancelContractEventArgs,
LogEvent,
LogFillContractEventArgs,
LogWithDecodedArgs,
OnOrderStateChangeCallback,
OrderState,
OrderStateWatcherConfig,
SignedOrder,
TokenEvents,
TransferContractEventArgs,
Web3Provider,
ZeroExError,
} from '../types';
import {AbiDecoder} from '../utils/abi_decoder';
import {assert} from '../utils/assert';
import {intervalUtils} from '../utils/interval_utils';
import {OrderStateUtils} from '../utils/order_state_utils';
import {utils} from '../utils/utils';
import {Web3Wrapper} from '../web3_wrapper';
import {EventWatcher} from './event_watcher';
import {ExpirationWatcher} from './expiration_watcher';
interface DependentOrderHashes {
[makerAddress: string]: {
[makerToken: string]: Set<string>;
};
}
interface OrderByOrderHash {
[orderHash: string]: SignedOrder;
}
interface OrderStateByOrderHash {
[orderHash: string]: OrderState;
}
const DEFAULT_CLEANUP_JOB_INTERVAL_MS = 1000 * 60 * 60; // 1h
/**
* This class includes all the functionality related to watching a set of orders
* for potential changes in order validity/fillability. The orderWatcher notifies
* the subscriber of these changes so that a final decison can be made on whether
* the order should be deemed invalid.
*/
export class OrderStateWatcher {
private _orderStateByOrderHashCache: OrderStateByOrderHash = {};
private _orderByOrderHash: OrderByOrderHash = {};
private _dependentOrderHashes: DependentOrderHashes = {};
private _callbackIfExists?: OnOrderStateChangeCallback;
private _eventWatcher: EventWatcher;
private _web3Wrapper: Web3Wrapper;
private _abiDecoder: AbiDecoder;
private _expirationWatcher: ExpirationWatcher;
private _orderStateUtils: OrderStateUtils;
private _orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore;
private _balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore;
private _cleanupJobInterval: number;
private _cleanupJobIntervalIdIfExists?: NodeJS.Timer;
constructor(
web3Wrapper: Web3Wrapper, abiDecoder: AbiDecoder, token: TokenWrapper, exchange: ExchangeWrapper,
config?: OrderStateWatcherConfig,
) {
this._abiDecoder = abiDecoder;
this._web3Wrapper = web3Wrapper;
const pollingIntervalIfExistsMs = _.isUndefined(config) ? undefined : config.eventPollingIntervalMs;
this._eventWatcher = new EventWatcher(web3Wrapper, pollingIntervalIfExistsMs);
this._balanceAndProxyAllowanceLazyStore = new BalanceAndProxyAllowanceLazyStore(
token, BlockParamLiteral.Pending,
);
this._orderFilledCancelledLazyStore = new OrderFilledCancelledLazyStore(exchange);
this._orderStateUtils = new OrderStateUtils(
this._balanceAndProxyAllowanceLazyStore, this._orderFilledCancelledLazyStore,
);
const orderExpirationCheckingIntervalMsIfExists = _.isUndefined(config) ?
undefined :
config.orderExpirationCheckingIntervalMs;
const expirationMarginIfExistsMs = _.isUndefined(config) ?
undefined :
config.expirationMarginMs;
this._expirationWatcher = new ExpirationWatcher(
expirationMarginIfExistsMs, orderExpirationCheckingIntervalMsIfExists,
);
this._cleanupJobInterval = _.isUndefined(config) || _.isUndefined(config.cleanupJobIntervalMs) ?
DEFAULT_CLEANUP_JOB_INTERVAL_MS :
config.cleanupJobIntervalMs;
}
/**
* Add an order to the orderStateWatcher. Before the order is added, it's
* signature is verified.
* @param signedOrder The order you wish to start watching.
*/
public addOrder(signedOrder: SignedOrder): void {
assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
assert.isValidSignature(orderHash, signedOrder.ecSignature, signedOrder.maker);
this._orderByOrderHash[orderHash] = signedOrder;
this.addToDependentOrderHashes(signedOrder, orderHash);
const expirationUnixTimestampMs = signedOrder.expirationUnixTimestampSec.times(1000);
this._expirationWatcher.addOrder(orderHash, expirationUnixTimestampMs);
}
/**
* Removes an order from the orderStateWatcher
* @param orderHash The orderHash of the order you wish to stop watching.
*/
public removeOrder(orderHash: string): void {
assert.doesConformToSchema('orderHash', orderHash, schemas.orderHashSchema);
const signedOrder = this._orderByOrderHash[orderHash];
if (_.isUndefined(signedOrder)) {
return; // noop
}
delete this._orderByOrderHash[orderHash];
delete this._orderStateByOrderHashCache[orderHash];
const exchange = (this._orderFilledCancelledLazyStore as any).exchange as ExchangeWrapper;
const zrxTokenAddress = exchange.getZRXTokenAddress();
this.removeFromDependentOrderHashes(signedOrder.maker, zrxTokenAddress, orderHash);
this.removeFromDependentOrderHashes(signedOrder.maker, signedOrder.makerTokenAddress, orderHash);
this._expirationWatcher.removeOrder(orderHash);
}
/**
* Starts an orderStateWatcher subscription. The callback will be called every time a watched order's
* backing blockchain state has changed. This is a call-to-action for the caller to re-validate the order.
* @param callback Receives the orderHash of the order that should be re-validated, together
* with all the order-relevant blockchain state needed to re-validate the order.
*/
public subscribe(callback: OnOrderStateChangeCallback): void {
assert.isFunction('callback', callback);
if (!_.isUndefined(this._callbackIfExists)) {
throw new Error(ZeroExError.SubscriptionAlreadyPresent);
}
this._callbackIfExists = callback;
this._eventWatcher.subscribe(this._onEventWatcherCallbackAsync.bind(this));
this._expirationWatcher.subscribe(this._onOrderExpired.bind(this));
this._cleanupJobIntervalIdIfExists = intervalUtils.setAsyncExcludingInterval(
this._cleanupAsync.bind(this), this._cleanupJobInterval,
);
}
/**
* Ends an orderStateWatcher subscription.
*/
public unsubscribe(): void {
if (_.isUndefined(this._callbackIfExists) || _.isUndefined(this._cleanupJobIntervalIdIfExists)) {
throw new Error(ZeroExError.SubscriptionNotFound);
}
this._balanceAndProxyAllowanceLazyStore.deleteAll();
this._orderFilledCancelledLazyStore.deleteAll();
delete this._callbackIfExists;
this._eventWatcher.unsubscribe();
this._expirationWatcher.unsubscribe();
intervalUtils.clearAsyncExcludingInterval(this._cleanupJobIntervalIdIfExists);
}
private async _cleanupAsync(): Promise<void> {
for (const orderHash of _.keys(this._orderByOrderHash)) {
this._cleanupOrderRelatedState(orderHash);
await this._emitRevalidateOrdersAsync([orderHash]);
}
}
private _cleanupOrderRelatedState(orderHash: string): void {
const signedOrder = this._orderByOrderHash[orderHash];
this._orderFilledCancelledLazyStore.deleteFilledTakerAmount(orderHash);
this._orderFilledCancelledLazyStore.deleteCancelledTakerAmount(orderHash);
this._balanceAndProxyAllowanceLazyStore.deleteBalance(signedOrder.makerTokenAddress, signedOrder.maker);
this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(signedOrder.makerTokenAddress, signedOrder.maker);
this._balanceAndProxyAllowanceLazyStore.deleteBalance(signedOrder.takerTokenAddress, signedOrder.taker);
this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(signedOrder.takerTokenAddress, signedOrder.taker);
const zrxTokenAddress = this._getZRXTokenAddress();
if (!signedOrder.makerFee.isZero()) {
this._balanceAndProxyAllowanceLazyStore.deleteBalance(zrxTokenAddress, signedOrder.maker);
this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(zrxTokenAddress, signedOrder.maker);
}
if (!signedOrder.takerFee.isZero()) {
this._balanceAndProxyAllowanceLazyStore.deleteBalance(zrxTokenAddress, signedOrder.taker);
this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(zrxTokenAddress, signedOrder.taker);
}
}
private _onOrderExpired(orderHash: string): void {
const orderState: OrderState = {
isValid: false,
orderHash,
error: ExchangeContractErrs.OrderFillExpired,
};
if (!_.isUndefined(this._orderByOrderHash[orderHash])) {
this.removeOrder(orderHash);
if (!_.isUndefined(this._callbackIfExists)) {
this._callbackIfExists(orderState);
}
}
}
private async _onEventWatcherCallbackAsync(log: LogEvent): Promise<void> {
const maybeDecodedLog = this._abiDecoder.tryToDecodeLogOrNoop(log);
const isLogDecoded = !_.isUndefined((maybeDecodedLog as LogWithDecodedArgs<any>).event);
if (!isLogDecoded) {
return; // noop
}
const decodedLog = maybeDecodedLog as LogWithDecodedArgs<ContractEventArgs>;
let makerToken: string;
let makerAddress: string;
switch (decodedLog.event) {
case TokenEvents.Approval:
{
// Invalidate cache
const args = decodedLog.args as ApprovalContractEventArgs;
this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(decodedLog.address, args._owner);
// Revalidate orders
makerToken = decodedLog.address;
makerAddress = args._owner;
if (!_.isUndefined(this._dependentOrderHashes[makerAddress]) &&
!_.isUndefined(this._dependentOrderHashes[makerAddress][makerToken])) {
const orderHashes = Array.from(this._dependentOrderHashes[makerAddress][makerToken]);
await this._emitRevalidateOrdersAsync(orderHashes);
}
break;
}
case TokenEvents.Transfer:
{
// Invalidate cache
const args = decodedLog.args as TransferContractEventArgs;
this._balanceAndProxyAllowanceLazyStore.deleteBalance(decodedLog.address, args._from);
this._balanceAndProxyAllowanceLazyStore.deleteBalance(decodedLog.address, args._to);
// Revalidate orders
makerToken = decodedLog.address;
makerAddress = args._from;
if (!_.isUndefined(this._dependentOrderHashes[makerAddress]) &&
!_.isUndefined(this._dependentOrderHashes[makerAddress][makerToken])) {
const orderHashes = Array.from(this._dependentOrderHashes[makerAddress][makerToken]);
await this._emitRevalidateOrdersAsync(orderHashes);
}
break;
}
case ExchangeEvents.LogFill:
{
// Invalidate cache
const args = decodedLog.args as LogFillContractEventArgs;
this._orderFilledCancelledLazyStore.deleteFilledTakerAmount(args.orderHash);
// Revalidate orders
const orderHash = args.orderHash;
const isOrderWatched = !_.isUndefined(this._orderByOrderHash[orderHash]);
if (isOrderWatched) {
await this._emitRevalidateOrdersAsync([orderHash]);
}
break;
}
case ExchangeEvents.LogCancel:
{
// Invalidate cache
const args = decodedLog.args as LogCancelContractEventArgs;
this._orderFilledCancelledLazyStore.deleteCancelledTakerAmount(args.orderHash);
// Revalidate orders
const orderHash = args.orderHash;
const isOrderWatched = !_.isUndefined(this._orderByOrderHash[orderHash]);
if (isOrderWatched) {
await this._emitRevalidateOrdersAsync([orderHash]);
}
break;
}
case ExchangeEvents.LogError:
return; // noop
default:
throw utils.spawnSwitchErr('decodedLog.event', decodedLog.event);
}
}
private async _emitRevalidateOrdersAsync(orderHashes: string[]): Promise<void> {
for (const orderHash of orderHashes) {
const signedOrder = this._orderByOrderHash[orderHash];
// Most of these calls will never reach the network because the data is fetched from stores
// and only updated when cache is invalidated
const orderState = await this._orderStateUtils.getOrderStateAsync(signedOrder);
if (_.isUndefined(this._callbackIfExists)) {
break; // Unsubscribe was called
}
if (_.isEqual(orderState, this._orderStateByOrderHashCache[orderHash])) {
// Actual order state didn't change
continue;
} else {
this._orderStateByOrderHashCache[orderHash] = orderState;
}
this._callbackIfExists(orderState);
}
}
private addToDependentOrderHashes(signedOrder: SignedOrder, orderHash: string): void {
if (_.isUndefined(this._dependentOrderHashes[signedOrder.maker])) {
this._dependentOrderHashes[signedOrder.maker] = {};
}
if (_.isUndefined(this._dependentOrderHashes[signedOrder.maker][signedOrder.makerTokenAddress])) {
this._dependentOrderHashes[signedOrder.maker][signedOrder.makerTokenAddress] = new Set();
}
this._dependentOrderHashes[signedOrder.maker][signedOrder.makerTokenAddress].add(orderHash);
const zrxTokenAddress = this._getZRXTokenAddress();
if (_.isUndefined(this._dependentOrderHashes[signedOrder.maker][zrxTokenAddress])) {
this._dependentOrderHashes[signedOrder.maker][zrxTokenAddress] = new Set();
}
this._dependentOrderHashes[signedOrder.maker][zrxTokenAddress].add(orderHash);
}
private removeFromDependentOrderHashes(makerAddress: string, tokenAddress: string, orderHash: string) {
this._dependentOrderHashes[makerAddress][tokenAddress].delete(orderHash);
if (this._dependentOrderHashes[makerAddress][tokenAddress].size === 0) {
delete this._dependentOrderHashes[makerAddress][tokenAddress];
}
if (_.isEmpty(this._dependentOrderHashes[makerAddress])) {
delete this._dependentOrderHashes[makerAddress];
}
}
private _getZRXTokenAddress(): string {
const exchange = (this._orderFilledCancelledLazyStore as any).exchange as ExchangeWrapper;
const zrxTokenAddress = exchange.getZRXTokenAddress();
return zrxTokenAddress;
}
}

View File

@@ -0,0 +1,87 @@
import {BigNumber} from 'bignumber.js';
import {SignedOrder} from '../types';
export class RemainingFillableCalculator {
private signedOrder: SignedOrder;
private isMakerTokenZRX: boolean;
// Transferrable Amount is the minimum of Approval and Balance
private transferrableMakerTokenAmount: BigNumber;
private transferrableMakerFeeTokenAmount: BigNumber;
private remainingMakerTokenAmount: BigNumber;
private remainingMakerFeeAmount: BigNumber;
constructor(signedOrder: SignedOrder,
isMakerTokenZRX: boolean,
transferrableMakerTokenAmount: BigNumber,
transferrableMakerFeeTokenAmount: BigNumber,
remainingMakerTokenAmount: BigNumber) {
this.signedOrder = signedOrder;
this.isMakerTokenZRX = isMakerTokenZRX;
this.transferrableMakerTokenAmount = transferrableMakerTokenAmount;
this.transferrableMakerFeeTokenAmount = transferrableMakerFeeTokenAmount;
this.remainingMakerTokenAmount = remainingMakerTokenAmount;
this.remainingMakerFeeAmount = remainingMakerTokenAmount.times(signedOrder.makerFee)
.dividedToIntegerBy(signedOrder.makerTokenAmount);
}
public computeRemainingMakerFillable(): BigNumber {
if (this.hasSufficientFundsForFeeAndTransferAmount()) {
return this.remainingMakerTokenAmount;
}
if (this.signedOrder.makerFee.isZero()) {
return BigNumber.min(this.remainingMakerTokenAmount, this.transferrableMakerTokenAmount);
}
return this.calculatePartiallyFillableMakerTokenAmount();
}
public computeRemainingTakerFillable(): BigNumber {
return this.computeRemainingMakerFillable().times(this.signedOrder.takerTokenAmount)
.dividedToIntegerBy(this.signedOrder.makerTokenAmount);
}
private hasSufficientFundsForFeeAndTransferAmount(): boolean {
if (this.isMakerTokenZRX) {
const totalZRXTransferAmountRequired = this.remainingMakerTokenAmount.plus(this.remainingMakerFeeAmount);
const hasSufficientFunds = this.transferrableMakerTokenAmount.greaterThanOrEqualTo(
totalZRXTransferAmountRequired);
return hasSufficientFunds;
} else {
const hasSufficientFundsForTransferAmount = this.transferrableMakerTokenAmount.greaterThanOrEqualTo(
this.remainingMakerTokenAmount);
const hasSufficientFundsForFeeAmount = this.transferrableMakerFeeTokenAmount.greaterThanOrEqualTo(
this.remainingMakerFeeAmount);
const hasSufficientFunds = hasSufficientFundsForTransferAmount && hasSufficientFundsForFeeAmount;
return hasSufficientFunds;
}
}
private calculatePartiallyFillableMakerTokenAmount(): BigNumber {
// Given an order for 200 wei for 2 ZRXwei fee, find 100 wei for 1 ZRXwei. Order ratio is then 100:1
const orderToFeeRatio = this.signedOrder.makerTokenAmount.dividedBy(this.signedOrder.makerFee);
// The number of times the maker can fill the order, if each fill only required the transfer of a single
// baseUnit of fee tokens.
// Given 2 ZRXwei, the maximum amount of times Maker can fill this order, in terms of fees, is 2
const fillableTimesInFeeTokenBaseUnits = BigNumber.min(this.transferrableMakerFeeTokenAmount,
this.remainingMakerFeeAmount);
// The number of times the Maker can fill the order, given the Maker Token Balance
// Assuming a balance of 150 wei, and an orderToFeeRatio of 100:1, maker can fill this order 1 time.
let fillableTimesInMakerTokenUnits = this.transferrableMakerTokenAmount.dividedBy(orderToFeeRatio);
if (this.isMakerTokenZRX) {
// If ZRX is the maker token, the Fee and the Maker amount need to be removed from the same pool;
// 200 ZRXwei for 2ZRXwei fee can only be filled once (need 202 ZRXwei)
const totalZRXTokenPooled = this.transferrableMakerTokenAmount;
// The purchasing power here is less as the tokens are taken from the same Pool
// For every one number of fills, we have to take an extra ZRX out of the pool
fillableTimesInMakerTokenUnits = totalZRXTokenPooled.dividedBy(
orderToFeeRatio.plus(new BigNumber(1)));
}
// When Ratio is not fully divisible there can be remainders which cannot be represented, so they are floored.
// This can result in a RoundingError being thrown by the Exchange Contract.
const partiallyFillableMakerTokenAmount = fillableTimesInMakerTokenUnits
.times(this.signedOrder.makerTokenAmount)
.dividedToIntegerBy(this.signedOrder.makerFee);
const partiallyFillableFeeTokenAmount = fillableTimesInFeeTokenBaseUnits
.times(this.signedOrder.makerTokenAmount)
.dividedToIntegerBy(this.signedOrder.makerFee);
const partiallyFillableAmount = BigNumber.min(partiallyFillableMakerTokenAmount,
partiallyFillableFeeTokenAmount);
return partiallyFillableAmount;
}
}

View File

@@ -0,0 +1,28 @@
export const zeroExConfigSchema = {
id: '/ZeroExConfig',
properties: {
networkId: {
type: 'number',
minimum: 0,
},
gasPrice: {$ref: '/Number'},
exchangeContractAddress: {$ref: '/Address'},
tokenRegistryContractAddress: {$ref: '/Address'},
etherTokenContractAddress: {$ref: '/Address'},
orderWatcherConfig: {
type: 'object',
properties: {
pollingIntervalMs: {
type: 'number',
minimum: 0,
},
numConfirmations: {
type: 'number',
minimum: 0,
},
},
},
},
type: 'object',
required: ['networkId'],
};

View File

@@ -0,0 +1,85 @@
import {BigNumber} from 'bignumber.js';
import * as _ from 'lodash';
import * as Web3 from 'web3';
import {TokenWrapper} from '../contract_wrappers/token_wrapper';
import {BlockParamLiteral} from '../types';
/**
* Copy on read store for balances/proxyAllowances of tokens/accounts
*/
export class BalanceAndProxyAllowanceLazyStore {
private token: TokenWrapper;
private defaultBlock: BlockParamLiteral;
private balance: {
[tokenAddress: string]: {
[userAddress: string]: BigNumber;
};
};
private proxyAllowance: {
[tokenAddress: string]: {
[userAddress: string]: BigNumber;
};
};
constructor(token: TokenWrapper, defaultBlock: BlockParamLiteral) {
this.token = token;
this.defaultBlock = defaultBlock;
this.balance = {};
this.proxyAllowance = {};
}
public async getBalanceAsync(tokenAddress: string, userAddress: string): Promise<BigNumber> {
if (_.isUndefined(this.balance[tokenAddress]) || _.isUndefined(this.balance[tokenAddress][userAddress])) {
const methodOpts = {
defaultBlock: this.defaultBlock,
};
const balance = await this.token.getBalanceAsync(tokenAddress, userAddress, methodOpts);
this.setBalance(tokenAddress, userAddress, balance);
}
const cachedBalance = this.balance[tokenAddress][userAddress];
return cachedBalance;
}
public setBalance(tokenAddress: string, userAddress: string, balance: BigNumber): void {
if (_.isUndefined(this.balance[tokenAddress])) {
this.balance[tokenAddress] = {};
}
this.balance[tokenAddress][userAddress] = balance;
}
public deleteBalance(tokenAddress: string, userAddress: string): void {
if (!_.isUndefined(this.balance[tokenAddress])) {
delete this.balance[tokenAddress][userAddress];
if (_.isEmpty(this.balance[tokenAddress])) {
delete this.balance[tokenAddress];
}
}
}
public async getProxyAllowanceAsync(tokenAddress: string, userAddress: string): Promise<BigNumber> {
if (_.isUndefined(this.proxyAllowance[tokenAddress]) ||
_.isUndefined(this.proxyAllowance[tokenAddress][userAddress])) {
const methodOpts = {
defaultBlock: this.defaultBlock,
};
const proxyAllowance = await this.token.getProxyAllowanceAsync(tokenAddress, userAddress, methodOpts);
this.setProxyAllowance(tokenAddress, userAddress, proxyAllowance);
}
const cachedProxyAllowance = this.proxyAllowance[tokenAddress][userAddress];
return cachedProxyAllowance;
}
public setProxyAllowance(tokenAddress: string, userAddress: string, proxyAllowance: BigNumber): void {
if (_.isUndefined(this.proxyAllowance[tokenAddress])) {
this.proxyAllowance[tokenAddress] = {};
}
this.proxyAllowance[tokenAddress][userAddress] = proxyAllowance;
}
public deleteProxyAllowance(tokenAddress: string, userAddress: string): void {
if (!_.isUndefined(this.proxyAllowance[tokenAddress])) {
delete this.proxyAllowance[tokenAddress][userAddress];
if (_.isEmpty(this.proxyAllowance[tokenAddress])) {
delete this.proxyAllowance[tokenAddress];
}
}
}
public deleteAll(): void {
this.balance = {};
this.proxyAllowance = {};
}
}

View File

@@ -0,0 +1,62 @@
import {BigNumber} from 'bignumber.js';
import * as _ from 'lodash';
import * as Web3 from 'web3';
import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper';
import {BlockParamLiteral} from '../types';
/**
* Copy on read store for filled/cancelled taker amounts
*/
export class OrderFilledCancelledLazyStore {
private exchange: ExchangeWrapper;
private filledTakerAmount: {
[orderHash: string]: BigNumber;
};
private cancelledTakerAmount: {
[orderHash: string]: BigNumber;
};
constructor(exchange: ExchangeWrapper) {
this.exchange = exchange;
this.filledTakerAmount = {};
this.cancelledTakerAmount = {};
}
public async getFilledTakerAmountAsync(orderHash: string): Promise<BigNumber> {
if (_.isUndefined(this.filledTakerAmount[orderHash])) {
const methodOpts = {
defaultBlock: BlockParamLiteral.Pending,
};
const filledTakerAmount = await this.exchange.getFilledTakerAmountAsync(orderHash, methodOpts);
this.setFilledTakerAmount(orderHash, filledTakerAmount);
}
const cachedFilled = this.filledTakerAmount[orderHash];
return cachedFilled;
}
public setFilledTakerAmount(orderHash: string, filledTakerAmount: BigNumber): void {
this.filledTakerAmount[orderHash] = filledTakerAmount;
}
public deleteFilledTakerAmount(orderHash: string): void {
delete this.filledTakerAmount[orderHash];
}
public async getCancelledTakerAmountAsync(orderHash: string): Promise<BigNumber> {
if (_.isUndefined(this.cancelledTakerAmount[orderHash])) {
const methodOpts = {
defaultBlock: BlockParamLiteral.Pending,
};
const cancelledTakerAmount = await this.exchange.getCancelledTakerAmountAsync(orderHash, methodOpts);
this.setCancelledTakerAmount(orderHash, cancelledTakerAmount);
}
const cachedCancelled = this.cancelledTakerAmount[orderHash];
return cachedCancelled;
}
public setCancelledTakerAmount(orderHash: string, cancelledTakerAmount: BigNumber): void {
this.cancelledTakerAmount[orderHash] = cancelledTakerAmount;
}
public deleteCancelledTakerAmount(orderHash: string): void {
delete this.cancelledTakerAmount[orderHash];
}
public deleteAll(): void {
this.filledTakerAmount = {};
this.cancelledTakerAmount = {};
}
}

View File

@@ -1,8 +1,13 @@
import BigNumber from 'bignumber.js';
import * as Web3 from 'web3';
export enum ZeroExError {
ContractDoesNotExist = 'CONTRACT_DOES_NOT_EXIST',
ExchangeContractDoesNotExist = 'EXCHANGE_CONTRACT_DOES_NOT_EXIST',
ZRXContractDoesNotExist = 'ZRX_CONTRACT_DOES_NOT_EXIST',
EtherTokenContractDoesNotExist = 'ETHER_TOKEN_CONTRACT_DOES_NOT_EXIST',
TokenTransferProxyContractDoesNotExist = 'TOKEN_TRANSFER_PROXY_CONTRACT_DOES_NOT_EXIST',
TokenRegistryContractDoesNotExist = 'TOKEN_REGISTRY_CONTRACT_DOES_NOT_EXIST',
TokenContractDoesNotExist = 'TOKEN_CONTRACT_DOES_NOT_EXIST',
UnhandledError = 'UNHANDLED_ERROR',
UserHasNoAssociatedAddress = 'USER_HAS_NO_ASSOCIATED_ADDRESSES',
InvalidSignature = 'INVALID_SIGNATURE',
@@ -14,6 +19,9 @@ export enum ZeroExError {
InvalidJump = 'INVALID_JUMP',
OutOfGas = 'OUT_OF_GAS',
NoNetworkId = 'NO_NETWORK_ID',
SubscriptionNotFound = 'SUBSCRIPTION_NOT_FOUND',
SubscriptionAlreadyPresent = 'SUBSCRIPTION_ALREADY_PRESENT',
TransactionMiningTimeout = 'TRANSACTION_MINING_TIMEOUT',
}
export enum InternalZeroExError {
@@ -32,26 +40,23 @@ export interface ECSignature {
export type OrderAddresses = [string, string, string, string, string];
export type OrderValues = [BigNumber.BigNumber, BigNumber.BigNumber, BigNumber.BigNumber,
BigNumber.BigNumber, BigNumber.BigNumber, BigNumber.BigNumber];
export type OrderValues = [BigNumber, BigNumber, BigNumber,
BigNumber, BigNumber, BigNumber];
export type EventCallbackAsync = (err: Error, event: ContractEvent) => Promise<void>;
export type EventCallbackSync = (err: Error, event: ContractEvent) => void;
export type EventCallback = EventCallbackSync|EventCallbackAsync;
export interface ContractEventObj {
watch: (eventWatch: EventCallback) => void;
stopWatching: () => void;
export type LogEvent = Web3.LogEntryEvent;
export interface DecodedLogEvent<ArgsType> {
isRemoved: boolean;
log: LogWithDecodedArgs<ArgsType>;
}
export type CreateContractEvent = (indexFilterValues: IndexedFilterValues,
subscriptionOpts: SubscriptionOpts) => ContractEventObj;
export type EventCallback<ArgsType> = (err: null|Error, log?: DecodedLogEvent<ArgsType>) => void;
export type EventWatcherCallback = (log: LogEvent) => void;
export interface ExchangeContract extends Web3.ContractInstance {
isValidSignature: {
callAsync: (signerAddressHex: string, dataHex: string, v: number, r: string, s: string,
txOpts?: TxOpts) => Promise<boolean>;
};
LogFill: CreateContractEvent;
LogCancel: CreateContractEvent;
LogError: CreateContractEvent;
ZRX_TOKEN_CONTRACT: {
callAsync: () => Promise<string>;
};
@@ -59,77 +64,77 @@ export interface ExchangeContract extends Web3.ContractInstance {
callAsync: () => Promise<string>;
};
getUnavailableTakerTokenAmount: {
callAsync: (orderHash: string, defaultBlock?: Web3.BlockParam) => Promise<BigNumber.BigNumber>;
callAsync: (orderHash: string, defaultBlock?: Web3.BlockParam) => Promise<BigNumber>;
};
isRoundingError: {
callAsync: (fillTakerAmount: BigNumber.BigNumber, takerTokenAmount: BigNumber.BigNumber,
makerTokenAmount: BigNumber.BigNumber, txOpts?: TxOpts) => Promise<boolean>;
callAsync: (takerTokenFillAmount: BigNumber, takerTokenAmount: BigNumber,
makerTokenAmount: BigNumber, txOpts?: TxOpts) => Promise<boolean>;
};
fillOrder: {
sendTransactionAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues,
fillTakerTokenAmount: BigNumber.BigNumber,
fillTakerTokenAmount: BigNumber,
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
v: number, r: string, s: string, txOpts?: TxOpts) => Promise<string>;
estimateGasAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues,
fillTakerTokenAmount: BigNumber.BigNumber,
fillTakerTokenAmount: BigNumber,
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
v: number, r: string, s: string, txOpts?: TxOpts) => Promise<number>;
};
batchFillOrders: {
sendTransactionAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
fillTakerTokenAmounts: BigNumber.BigNumber[],
fillTakerTokenAmounts: BigNumber[],
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
v: number[], r: string[], s: string[], txOpts?: TxOpts) => Promise<string>;
estimateGasAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
fillTakerTokenAmounts: BigNumber.BigNumber[],
fillTakerTokenAmounts: BigNumber[],
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
v: number[], r: string[], s: string[], txOpts?: TxOpts) => Promise<number>;
};
fillOrdersUpTo: {
sendTransactionAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
fillTakerTokenAmount: BigNumber.BigNumber,
fillTakerTokenAmount: BigNumber,
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
v: number[], r: string[], s: string[], txOpts?: TxOpts) => Promise<string>;
estimateGasAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
fillTakerTokenAmount: BigNumber.BigNumber,
fillTakerTokenAmount: BigNumber,
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
v: number[], r: string[], s: string[], txOpts?: TxOpts) => Promise<number>;
};
cancelOrder: {
sendTransactionAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues,
cancelTakerTokenAmount: BigNumber.BigNumber, txOpts?: TxOpts) => Promise<string>;
cancelTakerTokenAmount: BigNumber, txOpts?: TxOpts) => Promise<string>;
estimateGasAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues,
cancelTakerTokenAmount: BigNumber.BigNumber,
cancelTakerTokenAmount: BigNumber,
txOpts?: TxOpts) => Promise<number>;
};
batchCancelOrders: {
sendTransactionAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
cancelTakerTokenAmounts: BigNumber.BigNumber[], txOpts?: TxOpts) => Promise<string>;
cancelTakerTokenAmounts: BigNumber[], txOpts?: TxOpts) => Promise<string>;
estimateGasAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
cancelTakerTokenAmounts: BigNumber.BigNumber[],
cancelTakerTokenAmounts: BigNumber[],
txOpts?: TxOpts) => Promise<number>;
};
fillOrKillOrder: {
sendTransactionAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues,
fillTakerTokenAmount: BigNumber.BigNumber,
fillTakerTokenAmount: BigNumber,
v: number, r: string, s: string, txOpts?: TxOpts) => Promise<string>;
estimateGasAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues,
fillTakerTokenAmount: BigNumber.BigNumber,
fillTakerTokenAmount: BigNumber,
v: number, r: string, s: string, txOpts?: TxOpts) => Promise<number>;
};
batchFillOrKillOrders: {
sendTransactionAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
fillTakerTokenAmounts: BigNumber.BigNumber[],
fillTakerTokenAmounts: BigNumber[],
v: number[], r: string[], s: string[], txOpts: TxOpts) => Promise<string>;
estimateGasAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
fillTakerTokenAmounts: BigNumber.BigNumber[],
fillTakerTokenAmounts: BigNumber[],
v: number[], r: string[], s: string[], txOpts?: TxOpts) => Promise<number>;
};
filled: {
callAsync: (orderHash: string, defaultBlock?: Web3.BlockParam) => Promise<BigNumber.BigNumber>;
callAsync: (orderHash: string, defaultBlock?: Web3.BlockParam) => Promise<BigNumber>;
};
cancelled: {
callAsync: (orderHash: string, defaultBlock?: Web3.BlockParam) => Promise<BigNumber.BigNumber>;
callAsync: (orderHash: string, defaultBlock?: Web3.BlockParam) => Promise<BigNumber>;
};
getOrderHash: {
callAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues) => Promise<string>;
@@ -137,25 +142,23 @@ export interface ExchangeContract extends Web3.ContractInstance {
}
export interface TokenContract extends Web3.ContractInstance {
Transfer: CreateContractEvent;
Approval: CreateContractEvent;
balanceOf: {
callAsync: (address: string, defaultBlock?: Web3.BlockParam) => Promise<BigNumber.BigNumber>;
callAsync: (address: string, defaultBlock?: Web3.BlockParam) => Promise<BigNumber>;
};
allowance: {
callAsync: (ownerAddress: string, allowedAddress: string,
defaultBlock?: Web3.BlockParam) => Promise<BigNumber.BigNumber>;
defaultBlock?: Web3.BlockParam) => Promise<BigNumber>;
};
transfer: {
sendTransactionAsync: (toAddress: string, amountInBaseUnits: BigNumber.BigNumber,
sendTransactionAsync: (toAddress: string, amountInBaseUnits: BigNumber,
txOpts?: TxOpts) => Promise<string>;
};
transferFrom: {
sendTransactionAsync: (fromAddress: string, toAddress: string, amountInBaseUnits: BigNumber.BigNumber,
sendTransactionAsync: (fromAddress: string, toAddress: string, amountInBaseUnits: BigNumber,
txOpts?: TxOpts) => Promise<string>;
};
approve: {
sendTransactionAsync: (proxyAddress: string, amountInBaseUnits: BigNumber.BigNumber,
sendTransactionAsync: (proxyAddress: string, amountInBaseUnits: BigNumber,
txOpts?: TxOpts) => Promise<string>;
};
}
@@ -186,7 +189,7 @@ export interface EtherTokenContract extends Web3.ContractInstance {
sendTransactionAsync: (txOpts: TxOpts) => Promise<string>;
};
withdraw: {
sendTransactionAsync: (amount: BigNumber.BigNumber, txOpts: TxOpts) => Promise<string>;
sendTransactionAsync: (amount: BigNumber, txOpts: TxOpts) => Promise<string>;
};
}
@@ -260,10 +263,10 @@ export interface LogFillContractEventArgs {
feeRecipient: string;
makerToken: string;
takerToken: string;
filledMakerTokenAmount: BigNumber.BigNumber;
filledTakerTokenAmount: BigNumber.BigNumber;
paidMakerFee: BigNumber.BigNumber;
paidTakerFee: BigNumber.BigNumber;
filledMakerTokenAmount: BigNumber;
filledTakerTokenAmount: BigNumber;
paidMakerFee: BigNumber;
paidTakerFee: BigNumber;
tokens: string;
orderHash: string;
}
@@ -272,43 +275,43 @@ export interface LogCancelContractEventArgs {
feeRecipient: string;
makerToken: string;
takerToken: string;
cancelledMakerTokenAmount: BigNumber.BigNumber;
cancelledTakerTokenAmount: BigNumber.BigNumber;
cancelledMakerTokenAmount: BigNumber;
cancelledTakerTokenAmount: BigNumber;
tokens: string;
orderHash: string;
}
export interface LogErrorContractEventArgs {
errorId: BigNumber.BigNumber;
errorId: BigNumber;
orderHash: string;
}
export type ExchangeContractEventArgs = LogFillContractEventArgs|LogCancelContractEventArgs|LogErrorContractEventArgs;
export interface TransferContractEventArgs {
_from: string;
_to: string;
_value: BigNumber.BigNumber;
_value: BigNumber;
}
export interface ApprovalContractEventArgs {
_owner: string;
_spender: string;
_value: BigNumber.BigNumber;
_value: BigNumber;
}
export type TokenContractEventArgs = TransferContractEventArgs|ApprovalContractEventArgs;
export type ContractEventArgs = ExchangeContractEventArgs|TokenContractEventArgs;
export type ContractEventArg = string|BigNumber.BigNumber;
export type ContractEventArg = string|BigNumber;
export interface Order {
maker: string;
taker: string;
makerFee: BigNumber.BigNumber;
takerFee: BigNumber.BigNumber;
makerTokenAmount: BigNumber.BigNumber;
takerTokenAmount: BigNumber.BigNumber;
makerFee: BigNumber;
takerFee: BigNumber;
makerTokenAmount: BigNumber;
takerTokenAmount: BigNumber;
makerTokenAddress: string;
takerTokenAddress: string;
salt: BigNumber.BigNumber;
salt: BigNumber;
exchangeContractAddress: string;
feeRecipient: string;
expirationUnixTimestampSec: BigNumber.BigNumber;
expirationUnixTimestampSec: BigNumber;
}
export interface SignedOrder extends Order {
@@ -316,7 +319,7 @@ export interface SignedOrder extends Order {
}
// [address, name, symbol, decimals, ipfsHash, swarmHash]
export type TokenMetadata = [string, string, string, BigNumber.BigNumber, string, string];
export type TokenMetadata = [string, string, string, BigNumber, string, string];
export interface Token {
name: string;
@@ -328,7 +331,8 @@ export interface Token {
export interface TxOpts {
from: string;
gas?: number;
value?: BigNumber.BigNumber;
value?: BigNumber;
gasPrice?: BigNumber;
}
export interface TokenAddressBySymbol {
@@ -352,7 +356,15 @@ export interface IndexedFilterValues {
[index: string]: ContractEventArg;
}
export type BlockParam = 'latest'|'earliest'|'pending'|number;
// Earliest is omitted by design. It is simply an alias for the `0` constant and
// is thus not very helpful. Moreover, this type is used in places that only accept
// `latest` or `pending`.
export enum BlockParamLiteral {
Latest = 'latest',
Pending = 'pending',
}
export type BlockParam = BlockParamLiteral|number;
export interface SubscriptionOpts {
fromBlock: BlockParam;
@@ -361,32 +373,23 @@ export interface SubscriptionOpts {
export type DoneCallback = (err?: Error) => void;
export interface OrderFillOrKillRequest {
signedOrder: SignedOrder;
fillTakerAmount: BigNumber.BigNumber;
}
export interface OrderCancellationRequest {
order: Order|SignedOrder;
takerTokenCancelAmount: BigNumber.BigNumber;
takerTokenCancelAmount: BigNumber;
}
export interface OrderFillRequest {
signedOrder: SignedOrder;
takerTokenFillAmount: BigNumber.BigNumber;
takerTokenFillAmount: BigNumber;
}
export type AsyncMethod = (...args: any[]) => Promise<any>;
export interface ContractEventEmitter {
watch: (eventCallback: EventCallback) => void;
stopWatchingAsync: () => Promise<void>;
}
/**
* We re-export the `Web3.Provider` type specified in the Web3 Typescript typings
* since it is the type of the `provider` argument to the `ZeroEx` constructor.
* It is however a `Web3` library type, not a native `0x.js` type.
* It is however a `Web3` library type, not a native `0x.js` type. To learn more
* about providers, visit https://0xproject.com/wiki#Web3-Provider-Explained
*/
export type Web3Provider = Web3.Provider;
@@ -400,20 +403,38 @@ export interface JSONRPCPayload {
}
/*
* orderExpirationCheckingIntervalMs: How often to check for expired orders. Default: 50
* eventPollingIntervalMs: How often to poll the Ethereum node for new events. Defaults: 200
* expirationMarginMs: Amount of time before order expiry that you'd like to be notified
* of an orders expiration. Defaults: 0
* cleanupJobIntervalMs: How often to run a cleanup job which revalidates all the orders. Defaults: 1h
*/
export interface OrderStateWatcherConfig {
orderExpirationCheckingIntervalMs?: number;
eventPollingIntervalMs?: number;
expirationMarginMs?: number;
cleanupJobIntervalMs?: number;
}
/*
* networkId: The id of the underlying ethereum network your provider is connected to. (1-mainnet, 42-kovan, 50-testrpc)
* gasPrice: Gas price to use with every transaction
* exchangeContractAddress: The address of an exchange contract to use
* tokenRegistryContractAddress: The address of a token registry contract to use
* etherTokenContractAddress: The address of an ether token contract to use
* tokenTransferProxyContractAddress: The address of the token transfer proxy contract to use
* orderWatcherConfig: All the configs related to the orderWatcher
*/
export interface ZeroExConfig {
gasPrice?: BigNumber.BigNumber; // Gas price to use with every transaction
networkId: number;
gasPrice?: BigNumber;
exchangeContractAddress?: string;
tokenRegistryContractAddress?: string;
etherTokenContractAddress?: string;
tokenTransferProxyContractAddress?: string;
orderWatcherConfig?: OrderStateWatcherConfig;
}
export type TransactionReceipt = Web3.TransactionReceipt;
export enum AbiType {
Function = 'function',
Constructor = 'constructor',
@@ -425,22 +446,22 @@ export interface DecodedLogArgs {
[argName: string]: ContractEventArg;
}
export interface DecodedArgs {
args: DecodedLogArgs;
event: string;
export interface LogWithDecodedArgs<ArgsType> extends Web3.DecodedLogEntry<ArgsType> {}
export interface TransactionReceiptWithDecodedLogs extends TransactionReceipt {
logs: Array<LogWithDecodedArgs<DecodedLogArgs>|Web3.LogEntry>;
}
export interface LogWithDecodedArgs extends Web3.LogEntry, DecodedArgs {}
export interface TransactionReceiptWithDecodedLogs extends Web3.TransactionReceipt {
logs: Array<LogWithDecodedArgs|Web3.LogEntry>;
}
export type ArtifactContractName = 'ZRX'|'TokenTransferProxy'|'TokenRegistry'|'Token'|'Exchange'|'EtherToken';
export interface Artifact {
abi: any;
networks: {[networkId: number]: {
address: string;
}};
contract_name: ArtifactContractName;
abi: Web3.ContractAbi;
networks: {
[networkId: number]: {
address: string;
};
};
}
/*
@@ -450,7 +471,7 @@ export interface Artifact {
* allowance/balance to fill the entire remaining order amount.
*/
export interface ValidateOrderFillableOpts {
expectedFillTakerTokenAmount?: BigNumber.BigNumber;
expectedFillTakerTokenAmount?: BigNumber;
}
/*
@@ -464,11 +485,71 @@ export interface MethodOpts {
}
/*
* shouldValidate: Flag indicating whether the library should make attempts to validate a transaction before
* broadcasting it. For example, order has a valid signature, maker has sufficient funds, etc.
* gasPrice: Gas price in Wei to use for a transaction
* gasLimit: The amount of gas to send with a transaction
*/
export interface OrderTransactionOpts {
shouldValidate: boolean;
export interface TransactionOpts {
gasPrice?: BigNumber;
gasLimit?: number;
}
/*
* shouldValidate: Flag indicating whether the library should make attempts to validate a transaction before
* broadcasting it. For example, order has a valid signature, maker has sufficient funds, etc. Default: true
*/
export interface OrderTransactionOpts extends TransactionOpts {
shouldValidate?: boolean;
}
export type FilterObject = Web3.FilterObject;
export enum TradeSide {
Maker = 'maker',
Taker = 'taker',
}
export enum TransferType {
Trade = 'trade',
Fee = 'fee',
}
export interface OrderRelevantState {
makerBalance: BigNumber;
makerProxyAllowance: BigNumber;
makerFeeBalance: BigNumber;
makerFeeProxyAllowance: BigNumber;
filledTakerTokenAmount: BigNumber;
cancelledTakerTokenAmount: BigNumber;
remainingFillableMakerTokenAmount: BigNumber;
remainingFillableTakerTokenAmount: BigNumber;
}
export interface OrderStateValid {
isValid: true;
orderHash: string;
orderRelevantState: OrderRelevantState;
}
export interface OrderStateInvalid {
isValid: false;
orderHash: string;
error: ExchangeContractErrs;
}
export type OrderState = OrderStateValid|OrderStateInvalid;
export type OnOrderStateChangeCallback = (orderState: OrderState) => void;
export interface TransactionReceipt {
blockHash: string;
blockNumber: number;
transactionHash: string;
transactionIndex: number;
from: string;
to: string;
status: null|0|1;
cumulativeGasUsed: number;
gasUsed: number;
contractAddress: string|null;
logs: Web3.LogEntry[];
} // tslint:disable:max-file-line-count

View File

@@ -1,17 +1,28 @@
import * as Web3 from 'web3';
import BigNumber from 'bignumber.js';
import * as _ from 'lodash';
import * as BigNumber from 'bignumber.js';
import {AbiType, DecodedLogArgs, DecodedArgs, LogWithDecodedArgs, RawLog, SolidityTypes} from '../types';
import * as Web3 from 'web3';
import * as SolidityCoder from 'web3/lib/solidity/coder';
import {AbiType, ContractEventArgs, DecodedLogArgs, LogWithDecodedArgs, RawLog, SolidityTypes} from '../types';
export class AbiDecoder {
private savedABIs: Web3.AbiDefinition[] = [];
private methodIds: {[signatureHash: string]: Web3.EventAbi} = {};
private static padZeros(address: string) {
let formatted = address;
if (_.startsWith(formatted, '0x')) {
formatted = formatted.slice(2);
}
formatted = _.padStart(formatted, 40, '0');
return `0x${formatted}`;
}
constructor(abiArrays: Web3.AbiDefinition[][]) {
_.map(abiArrays, this.addABI.bind(this));
}
// This method can only decode logs from the 0x smart contracts
public tryToDecodeLogOrNoop(log: Web3.LogEntry): LogWithDecodedArgs|RawLog {
// This method can only decode logs from the 0x & ERC20 smart contracts
public tryToDecodeLogOrNoop<ArgsType extends ContractEventArgs>(
log: Web3.LogEntry): LogWithDecodedArgs<ArgsType>|RawLog {
const methodId = log.topics[0];
const event = this.methodIds[methodId];
if (_.isUndefined(event)) {
@@ -30,10 +41,10 @@ export class AbiDecoder {
// Indexed parameters are stored in topics. Non-indexed ones in decodedData
let value = param.indexed ? log.topics[topicsIndex++] : decodedData[dataIndex++];
if (param.type === SolidityTypes.Address) {
value = this.padZeros(new BigNumber(value).toString(16));
value = AbiDecoder.padZeros(new BigNumber(value).toString(16));
} else if (param.type === SolidityTypes.Uint256 ||
param.type === SolidityTypes.Uint8 ||
param.type === SolidityTypes.Uint ) {
param.type === SolidityTypes.Uint) {
value = new BigNumber(value);
}
decodedParams[param.name] = value;
@@ -55,13 +66,4 @@ export class AbiDecoder {
});
this.savedABIs = this.savedABIs.concat(abiArray);
}
private padZeros(address: string) {
let formatted = address;
if (_.startsWith(formatted, '0x')) {
formatted = formatted.slice(2);
}
formatted = _.padStart(formatted, 40, '0');
return `0x${formatted}`;
}
}

View File

@@ -0,0 +1,31 @@
import {assert as sharedAssert} from '@0xproject/assert';
import {Schema, SchemaValidator} from '@0xproject/json-schemas';
import BigNumber from 'bignumber.js';
import * as _ from 'lodash';
import * as Web3 from 'web3';
import {ECSignature} from '../types';
import {signatureUtils} from '../utils/signature_utils';
import {Web3Wrapper} from '../web3_wrapper';
const HEX_REGEX = /^0x[0-9A-F]*$/i;
export const assert = {
...sharedAssert,
isValidSignature(orderHash: string, ecSignature: ECSignature, signerAddress: string) {
const isValidSignature = signatureUtils.isValidSignature(orderHash, ecSignature, signerAddress);
this.assert(isValidSignature, `Expected order with hash '${orderHash}' to have a valid signature`);
},
async isSenderAddressAsync(variableName: string, senderAddressHex: string,
web3Wrapper: Web3Wrapper): Promise<void> {
sharedAssert.isETHAddressHex(variableName, senderAddressHex);
const isSenderAddressAvailable = await web3Wrapper.isSenderAddressAvailableAsync(senderAddressHex);
sharedAssert.assert(isSenderAddressAvailable,
`Specified ${variableName} ${senderAddressHex} isn't available through the supplied web3 provider`,
);
},
async isUserAddressAvailableAsync(web3Wrapper: Web3Wrapper): Promise<void> {
const availableAddresses = await web3Wrapper.getAvailableAddressesAsync();
this.assert(!_.isEmpty(availableAddresses), 'No addresses were available on the provided web3 provider');
},
};

View File

@@ -1,4 +1,4 @@
import * as BigNumber from 'bignumber.js';
import BigNumber from 'bignumber.js';
export const constants = {
NULL_ADDRESS: '0x0000000000000000000000000000000000000000',
@@ -7,4 +7,5 @@ export const constants = {
INVALID_JUMP_PATTERN: 'invalid JUMP at',
OUT_OF_GAS_PATTERN: 'out of gas',
UNLIMITED_ALLOWANCE_IN_BASE_UNITS: new BigNumber(2).pow(256).minus(1),
DEFAULT_BLOCK_POLLING_INTERVAL: 1000,
};

View File

@@ -1,7 +1,9 @@
import * as _ from 'lodash';
import {constants} from './constants';
import {AsyncMethod, ZeroExError} from '../types';
import {constants} from './constants';
export const decorators = {
/**
* Source: https://stackoverflow.com/a/29837695/3546986

View File

@@ -0,0 +1,89 @@
import BigNumber from 'bignumber.js';
import * as _ from 'lodash';
import {TokenWrapper} from '../contract_wrappers/token_wrapper';
import {BalanceAndProxyAllowanceLazyStore} from '../stores/balance_proxy_allowance_lazy_store';
import {BlockParamLiteral, ExchangeContractErrs, TradeSide, TransferType} from '../types';
enum FailureReason {
Balance = 'balance',
ProxyAllowance = 'proxyAllowance',
}
const ERR_MSG_MAPPING = {
[FailureReason.Balance]: {
[TradeSide.Maker]: {
[TransferType.Trade]: ExchangeContractErrs.InsufficientMakerBalance,
[TransferType.Fee]: ExchangeContractErrs.InsufficientMakerFeeBalance,
},
[TradeSide.Taker]: {
[TransferType.Trade]: ExchangeContractErrs.InsufficientTakerBalance,
[TransferType.Fee]: ExchangeContractErrs.InsufficientTakerFeeBalance,
},
},
[FailureReason.ProxyAllowance]: {
[TradeSide.Maker]: {
[TransferType.Trade]: ExchangeContractErrs.InsufficientMakerAllowance,
[TransferType.Fee]: ExchangeContractErrs.InsufficientMakerFeeAllowance,
},
[TradeSide.Taker]: {
[TransferType.Trade]: ExchangeContractErrs.InsufficientTakerAllowance,
[TransferType.Fee]: ExchangeContractErrs.InsufficientTakerFeeAllowance,
},
},
};
export class ExchangeTransferSimulator {
private store: BalanceAndProxyAllowanceLazyStore;
private UNLIMITED_ALLOWANCE_IN_BASE_UNITS: BigNumber;
private static throwValidationError(failureReason: FailureReason, tradeSide: TradeSide,
transferType: TransferType): never {
const errMsg = ERR_MSG_MAPPING[failureReason][tradeSide][transferType];
throw new Error(errMsg);
}
constructor(token: TokenWrapper, defaultBlock: BlockParamLiteral) {
this.store = new BalanceAndProxyAllowanceLazyStore(token, defaultBlock);
this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS = token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
}
/**
* Simulates transferFrom call performed by a proxy
* @param tokenAddress Address of the token to be transferred
* @param from Owner of the transferred tokens
* @param to Recipient of the transferred tokens
* @param amountInBaseUnits The amount of tokens being transferred
* @param tradeSide Is Maker/Taker transferring
* @param transferType Is it a fee payment or a value transfer
*/
public async transferFromAsync(tokenAddress: string, from: string, to: string,
amountInBaseUnits: BigNumber, tradeSide: TradeSide,
transferType: TransferType): Promise<void> {
const balance = await this.store.getBalanceAsync(tokenAddress, from);
const proxyAllowance = await this.store.getProxyAllowanceAsync(tokenAddress, from);
if (proxyAllowance.lessThan(amountInBaseUnits)) {
ExchangeTransferSimulator.throwValidationError(FailureReason.ProxyAllowance, tradeSide, transferType);
}
if (balance.lessThan(amountInBaseUnits)) {
ExchangeTransferSimulator.throwValidationError(FailureReason.Balance, tradeSide, transferType);
}
await this.decreaseProxyAllowanceAsync(tokenAddress, from, amountInBaseUnits);
await this.decreaseBalanceAsync(tokenAddress, from, amountInBaseUnits);
await this.increaseBalanceAsync(tokenAddress, to, amountInBaseUnits);
}
private async decreaseProxyAllowanceAsync(tokenAddress: string, userAddress: string,
amountInBaseUnits: BigNumber): Promise<void> {
const proxyAllowance = await this.store.getProxyAllowanceAsync(tokenAddress, userAddress);
if (!proxyAllowance.eq(this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS)) {
this.store.setProxyAllowance(tokenAddress, userAddress, proxyAllowance.minus(amountInBaseUnits));
}
}
private async increaseBalanceAsync(tokenAddress: string, userAddress: string,
amountInBaseUnits: BigNumber): Promise<void> {
const balance = await this.store.getBalanceAsync(tokenAddress, userAddress);
this.store.setBalance(tokenAddress, userAddress, balance.plus(amountInBaseUnits));
}
private async decreaseBalanceAsync(tokenAddress: string, userAddress: string,
amountInBaseUnits: BigNumber): Promise<void> {
const balance = await this.store.getBalanceAsync(tokenAddress, userAddress);
this.store.setBalance(tokenAddress, userAddress, balance.minus(amountInBaseUnits));
}
}

View File

@@ -0,0 +1,83 @@
import * as ethUtil from 'ethereumjs-util';
import * as jsSHA3 from 'js-sha3';
import * as _ from 'lodash';
import * as uuid from 'uuid/v4';
import * as Web3 from 'web3';
import {ContractEvents, IndexedFilterValues, SubscriptionOpts} from '../types';
const TOPIC_LENGTH = 32;
export const filterUtils = {
generateUUID(): string {
return uuid();
},
getFilter(address: string, eventName: ContractEvents,
indexFilterValues: IndexedFilterValues, abi: Web3.ContractAbi,
subscriptionOpts?: SubscriptionOpts): Web3.FilterObject {
const eventAbi = _.find(abi, {name: eventName}) as Web3.EventAbi;
const eventSignature = filterUtils.getEventSignatureFromAbiByName(eventAbi, eventName);
const topicForEventSignature = ethUtil.addHexPrefix(jsSHA3.keccak256(eventSignature));
const topicsForIndexedArgs = filterUtils.getTopicsForIndexedArgs(eventAbi, indexFilterValues);
const topics = [topicForEventSignature, ...topicsForIndexedArgs];
let filter: Web3.FilterObject = {
address,
topics,
};
if (!_.isUndefined(subscriptionOpts)) {
filter = {
...subscriptionOpts,
...filter,
};
}
return filter;
},
getEventSignatureFromAbiByName(eventAbi: Web3.EventAbi, eventName: ContractEvents): string {
const types = _.map(eventAbi.inputs, 'type');
const signature = `${eventAbi.name}(${types.join(',')})`;
return signature;
},
getTopicsForIndexedArgs(abi: Web3.EventAbi, indexFilterValues: IndexedFilterValues): Array<string|null> {
const topics: Array<string|null> = [];
for (const eventInput of abi.inputs) {
if (!eventInput.indexed) {
continue;
}
if (_.isUndefined(indexFilterValues[eventInput.name])) {
// Null is a wildcard topic in a JSON-RPC call
topics.push(null);
} else {
const value = indexFilterValues[eventInput.name] as string;
const buffer = ethUtil.toBuffer(value);
const paddedBuffer = ethUtil.setLengthLeft(buffer, TOPIC_LENGTH);
const topic = ethUtil.bufferToHex(paddedBuffer);
topics.push(topic);
}
}
return topics;
},
matchesFilter(log: Web3.LogEntry, filter: Web3.FilterObject): boolean {
if (!_.isUndefined(filter.address) && log.address !== filter.address) {
return false;
}
if (!_.isUndefined(filter.topics)) {
return filterUtils.matchesTopics(log.topics, filter.topics);
}
return true;
},
matchesTopics(logTopics: string[], filterTopics: Array<string[]|string|null>): boolean {
const matchesTopic = _.zipWith(logTopics, filterTopics, filterUtils.matchesTopic.bind(filterUtils));
const matchesTopics = _.every(matchesTopic);
return matchesTopics;
},
matchesTopic(logTopic: string, filterTopic: string[]|string|null): boolean {
if (_.isArray(filterTopic)) {
return _.includes(filterTopic, logTopic);
}
if (_.isString(filterTopic)) {
return filterTopic === logTopic;
}
// null topic is a wildcard
return true;
},
};

View File

@@ -0,0 +1,137 @@
import BigNumber from 'bignumber.js';
import * as _ from 'lodash';
import * as Web3 from 'web3';
import {ZeroEx} from '../0x';
import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper';
import {TokenWrapper} from '../contract_wrappers/token_wrapper';
import {RemainingFillableCalculator} from '../order_watcher/remaining_fillable_calculator';
import {BalanceAndProxyAllowanceLazyStore} from '../stores/balance_proxy_allowance_lazy_store';
import {OrderFilledCancelledLazyStore} from '../stores/order_filled_cancelled_lazy_store';
import {
ExchangeContractErrs,
MethodOpts,
OrderRelevantState,
OrderState,
OrderStateInvalid,
OrderStateValid,
SignedOrder,
} from '../types';
import {constants} from '../utils/constants';
import {utils} from '../utils/utils';
const ACCEPTABLE_RELATIVE_ROUNDING_ERROR = 0.0001;
export class OrderStateUtils {
private balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore;
private orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore;
private static validateIfOrderIsValid(signedOrder: SignedOrder, orderRelevantState: OrderRelevantState): void {
const unavailableTakerTokenAmount = orderRelevantState.cancelledTakerTokenAmount.add(
orderRelevantState.filledTakerTokenAmount,
);
const availableTakerTokenAmount = signedOrder.takerTokenAmount.minus(unavailableTakerTokenAmount);
if (availableTakerTokenAmount.eq(0)) {
throw new Error(ExchangeContractErrs.OrderRemainingFillAmountZero);
}
if (orderRelevantState.makerBalance.eq(0)) {
throw new Error(ExchangeContractErrs.InsufficientMakerBalance);
}
if (orderRelevantState.makerProxyAllowance.eq(0)) {
throw new Error(ExchangeContractErrs.InsufficientMakerAllowance);
}
if (!signedOrder.makerFee.eq(0)) {
if (orderRelevantState.makerFeeBalance.eq(0)) {
throw new Error(ExchangeContractErrs.InsufficientMakerFeeBalance);
}
if (orderRelevantState.makerFeeProxyAllowance.eq(0)) {
throw new Error(ExchangeContractErrs.InsufficientMakerFeeAllowance);
}
}
const minFillableTakerTokenAmountWithinNoRoundingErrorRange = signedOrder.takerTokenAmount
.dividedBy(ACCEPTABLE_RELATIVE_ROUNDING_ERROR)
.dividedBy(signedOrder.makerTokenAmount);
if (orderRelevantState.remainingFillableTakerTokenAmount
.lessThan(minFillableTakerTokenAmountWithinNoRoundingErrorRange)) {
throw new Error(ExchangeContractErrs.OrderFillRoundingError);
}
}
constructor(balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore,
orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore) {
this.balanceAndProxyAllowanceLazyStore = balanceAndProxyAllowanceLazyStore;
this.orderFilledCancelledLazyStore = orderFilledCancelledLazyStore;
}
public async getOrderStateAsync(signedOrder: SignedOrder): Promise<OrderState> {
const orderRelevantState = await this.getOrderRelevantStateAsync(signedOrder);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
try {
OrderStateUtils.validateIfOrderIsValid(signedOrder, orderRelevantState);
const orderState: OrderStateValid = {
isValid: true,
orderHash,
orderRelevantState,
};
return orderState;
} catch (err) {
const orderState: OrderStateInvalid = {
isValid: false,
orderHash,
error: err.message,
};
return orderState;
}
}
public async getOrderRelevantStateAsync(signedOrder: SignedOrder): Promise<OrderRelevantState> {
// HACK: We access the private property here but otherwise the interface will be less nice.
// If we pass it from the instantiator - there is no opportunity to get it there
// because JS doesn't support async constructors.
// Moreover - it's cached under the hood so it's equivalent to an async constructor.
const exchange = (this.orderFilledCancelledLazyStore as any).exchange as ExchangeWrapper;
const zrxTokenAddress = exchange.getZRXTokenAddress();
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
const makerBalance = await this.balanceAndProxyAllowanceLazyStore.getBalanceAsync(
signedOrder.makerTokenAddress, signedOrder.maker,
);
const makerProxyAllowance = await this.balanceAndProxyAllowanceLazyStore.getProxyAllowanceAsync(
signedOrder.makerTokenAddress, signedOrder.maker,
);
const makerFeeBalance = await this.balanceAndProxyAllowanceLazyStore.getBalanceAsync(
zrxTokenAddress, signedOrder.maker,
);
const makerFeeProxyAllowance = await this.balanceAndProxyAllowanceLazyStore.getProxyAllowanceAsync(
zrxTokenAddress, signedOrder.maker,
);
const filledTakerTokenAmount = await this.orderFilledCancelledLazyStore.getFilledTakerAmountAsync(orderHash);
const cancelledTakerTokenAmount = await this.orderFilledCancelledLazyStore.getCancelledTakerAmountAsync(
orderHash,
);
const unavailableTakerTokenAmount = await exchange.getUnavailableTakerAmountAsync(orderHash);
const totalMakerTokenAmount = signedOrder.makerTokenAmount;
const totalTakerTokenAmount = signedOrder.takerTokenAmount;
const remainingTakerTokenAmount = totalTakerTokenAmount.minus(unavailableTakerTokenAmount);
const remainingMakerTokenAmount = remainingTakerTokenAmount.times(totalMakerTokenAmount)
.dividedToIntegerBy(totalTakerTokenAmount);
const transferrableMakerTokenAmount = BigNumber.min([makerProxyAllowance, makerBalance]);
const transferrableFeeTokenAmount = BigNumber.min([makerFeeProxyAllowance, makerFeeBalance]);
const isMakerTokenZRX = signedOrder.makerTokenAddress === zrxTokenAddress;
const remainingFillableCalculator = new RemainingFillableCalculator(signedOrder,
isMakerTokenZRX,
transferrableMakerTokenAmount,
transferrableFeeTokenAmount,
remainingMakerTokenAmount);
const remainingFillableMakerTokenAmount = remainingFillableCalculator.computeRemainingMakerFillable();
const remainingFillableTakerTokenAmount = remainingFillableCalculator.computeRemainingTakerFillable();
const orderRelevantState = {
makerBalance,
makerProxyAllowance,
makerFeeBalance,
makerFeeProxyAllowance,
filledTakerTokenAmount,
cancelledTakerTokenAmount,
remainingFillableMakerTokenAmount,
remainingFillableTakerTokenAmount,
};
return orderRelevantState;
}
}

View File

@@ -0,0 +1,168 @@
import BigNumber from 'bignumber.js';
import * as _ from 'lodash';
import {ZeroEx} from '../0x';
import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper';
import {TokenWrapper} from '../contract_wrappers/token_wrapper';
import {ExchangeContractErrs, Order, SignedOrder, TradeSide, TransferType, ZeroExError} from '../types';
import {constants} from '../utils/constants';
import {utils} from '../utils/utils';
import {ExchangeTransferSimulator} from './exchange_transfer_simulator';
export class OrderValidationUtils {
private tokenWrapper: TokenWrapper;
private exchangeWrapper: ExchangeWrapper;
public static validateCancelOrderThrowIfInvalid(
order: Order, cancelTakerTokenAmount: BigNumber, unavailableTakerTokenAmount: BigNumber,
): void {
if (cancelTakerTokenAmount.eq(0)) {
throw new Error(ExchangeContractErrs.OrderCancelAmountZero);
}
if (order.takerTokenAmount.eq(unavailableTakerTokenAmount)) {
throw new Error(ExchangeContractErrs.OrderAlreadyCancelledOrFilled);
}
const currentUnixTimestampSec = utils.getCurrentUnixTimestampSec();
if (order.expirationUnixTimestampSec.lessThan(currentUnixTimestampSec)) {
throw new Error(ExchangeContractErrs.OrderCancelExpired);
}
}
public static async validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
exchangeTradeEmulator: ExchangeTransferSimulator, signedOrder: SignedOrder,
fillTakerTokenAmount: BigNumber, senderAddress: string, zrxTokenAddress: string,
): Promise<void> {
const fillMakerTokenAmount = OrderValidationUtils.getPartialAmount(
fillTakerTokenAmount,
signedOrder.takerTokenAmount,
signedOrder.makerTokenAmount,
);
await exchangeTradeEmulator.transferFromAsync(
signedOrder.makerTokenAddress, signedOrder.maker, senderAddress, fillMakerTokenAmount,
TradeSide.Maker, TransferType.Trade,
);
await exchangeTradeEmulator.transferFromAsync(
signedOrder.takerTokenAddress, senderAddress, signedOrder.maker, fillTakerTokenAmount,
TradeSide.Taker, TransferType.Trade,
);
const makerFeeAmount = OrderValidationUtils.getPartialAmount(
fillTakerTokenAmount,
signedOrder.takerTokenAmount,
signedOrder.makerFee,
);
await exchangeTradeEmulator.transferFromAsync(
zrxTokenAddress, signedOrder.maker, signedOrder.feeRecipient, makerFeeAmount, TradeSide.Maker,
TransferType.Fee,
);
const takerFeeAmount = OrderValidationUtils.getPartialAmount(
fillTakerTokenAmount,
signedOrder.takerTokenAmount,
signedOrder.takerFee,
);
await exchangeTradeEmulator.transferFromAsync(
zrxTokenAddress, senderAddress, signedOrder.feeRecipient, takerFeeAmount, TradeSide.Taker,
TransferType.Fee,
);
}
private static validateRemainingFillAmountNotZeroOrThrow(
takerTokenAmount: BigNumber, unavailableTakerTokenAmount: BigNumber,
) {
if (takerTokenAmount.eq(unavailableTakerTokenAmount)) {
throw new Error(ExchangeContractErrs.OrderRemainingFillAmountZero);
}
}
private static validateOrderNotExpiredOrThrow(expirationUnixTimestampSec: BigNumber) {
const currentUnixTimestampSec = utils.getCurrentUnixTimestampSec();
if (expirationUnixTimestampSec.lessThan(currentUnixTimestampSec)) {
throw new Error(ExchangeContractErrs.OrderFillExpired);
}
}
private static getPartialAmount(numerator: BigNumber, denominator: BigNumber,
target: BigNumber): BigNumber {
const fillMakerTokenAmount = numerator
.mul(target)
.div(denominator)
.round(0);
return fillMakerTokenAmount;
}
constructor(tokenWrapper: TokenWrapper, exchangeWrapper: ExchangeWrapper) {
this.tokenWrapper = tokenWrapper;
this.exchangeWrapper = exchangeWrapper;
}
public async validateOrderFillableOrThrowAsync(
exchangeTradeEmulator: ExchangeTransferSimulator, signedOrder: SignedOrder, zrxTokenAddress: string,
expectedFillTakerTokenAmount?: BigNumber): Promise<void> {
const orderHash = utils.getOrderHashHex(signedOrder);
const unavailableTakerTokenAmount = await this.exchangeWrapper.getUnavailableTakerAmountAsync(orderHash);
OrderValidationUtils.validateRemainingFillAmountNotZeroOrThrow(
signedOrder.takerTokenAmount, unavailableTakerTokenAmount,
);
OrderValidationUtils.validateOrderNotExpiredOrThrow(signedOrder.expirationUnixTimestampSec);
let fillTakerTokenAmount = signedOrder.takerTokenAmount.minus(unavailableTakerTokenAmount);
if (!_.isUndefined(expectedFillTakerTokenAmount)) {
fillTakerTokenAmount = expectedFillTakerTokenAmount;
}
const fillMakerTokenAmount = OrderValidationUtils.getPartialAmount(
fillTakerTokenAmount,
signedOrder.takerTokenAmount,
signedOrder.makerTokenAmount,
);
await exchangeTradeEmulator.transferFromAsync(
signedOrder.makerTokenAddress, signedOrder.maker, signedOrder.taker, fillMakerTokenAmount,
TradeSide.Maker, TransferType.Trade,
);
const makerFeeAmount = OrderValidationUtils.getPartialAmount(
fillTakerTokenAmount,
signedOrder.takerTokenAmount,
signedOrder.makerFee,
);
await exchangeTradeEmulator.transferFromAsync(
zrxTokenAddress, signedOrder.maker, signedOrder.feeRecipient, makerFeeAmount,
TradeSide.Maker, TransferType.Fee,
);
}
public async validateFillOrderThrowIfInvalidAsync(
exchangeTradeEmulator: ExchangeTransferSimulator, signedOrder: SignedOrder,
fillTakerTokenAmount: BigNumber, takerAddress: string,
zrxTokenAddress: string): Promise<BigNumber> {
if (fillTakerTokenAmount.eq(0)) {
throw new Error(ExchangeContractErrs.OrderFillAmountZero);
}
const orderHash = utils.getOrderHashHex(signedOrder);
if (!ZeroEx.isValidSignature(orderHash, signedOrder.ecSignature, signedOrder.maker)) {
throw new Error(ZeroExError.InvalidSignature);
}
const unavailableTakerTokenAmount = await this.exchangeWrapper.getUnavailableTakerAmountAsync(orderHash);
OrderValidationUtils.validateRemainingFillAmountNotZeroOrThrow(
signedOrder.takerTokenAmount, unavailableTakerTokenAmount,
);
if (signedOrder.taker !== constants.NULL_ADDRESS && signedOrder.taker !== takerAddress) {
throw new Error(ExchangeContractErrs.TransactionSenderIsNotFillOrderTaker);
}
OrderValidationUtils.validateOrderNotExpiredOrThrow(signedOrder.expirationUnixTimestampSec);
const remainingTakerTokenAmount = signedOrder.takerTokenAmount.minus(unavailableTakerTokenAmount);
const filledTakerTokenAmount = remainingTakerTokenAmount.lessThan(fillTakerTokenAmount) ?
remainingTakerTokenAmount :
fillTakerTokenAmount;
await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
exchangeTradeEmulator, signedOrder, filledTakerTokenAmount, takerAddress, zrxTokenAddress,
);
const wouldRoundingErrorOccur = await this.exchangeWrapper.isRoundingErrorAsync(
filledTakerTokenAmount, signedOrder.takerTokenAmount, signedOrder.makerTokenAmount,
);
if (wouldRoundingErrorOccur) {
throw new Error(ExchangeContractErrs.OrderFillRoundingError);
}
return filledTakerTokenAmount;
}
public async validateFillOrKillOrderThrowIfInvalidAsync(
exchangeTradeEmulator: ExchangeTransferSimulator, signedOrder: SignedOrder,
fillTakerTokenAmount: BigNumber, takerAddress: string, zrxTokenAddress: string): Promise<void> {
const filledTakerTokenAmount = await this.validateFillOrderThrowIfInvalidAsync(
exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress,
);
if (filledTakerTokenAmount !== fillTakerTokenAmount) {
throw new Error(ExchangeContractErrs.InsufficientRemainingFillAmount);
}
}
}

View File

@@ -1,7 +1,23 @@
import * as ethUtil from 'ethereumjs-util';
import {ECSignature} from '../types';
export const signatureUtils = {
isValidSignature(data: string, signature: ECSignature, signerAddress: string): boolean {
const dataBuff = ethUtil.toBuffer(data);
const msgHashBuff = ethUtil.hashPersonalMessage(dataBuff);
try {
const pubKey = ethUtil.ecrecover(
msgHashBuff,
signature.v,
ethUtil.toBuffer(signature.r),
ethUtil.toBuffer(signature.s));
const retrievedAddress = ethUtil.bufferToHex(ethUtil.pubToAddress(pubKey));
return retrievedAddress === signerAddress;
} catch (err) {
return false;
}
},
parseSignatureHexAsVRS(signatureHex: string): ECSignature {
const signatureBuffer = ethUtil.toBuffer(signatureHex);
let v = signatureBuffer[0];

View File

@@ -1,9 +1,10 @@
import * as _ from 'lodash';
import BigNumber from 'bignumber.js';
import BN = require('bn.js');
import * as ethABI from 'ethereumjs-abi';
import * as ethUtil from 'ethereumjs-util';
import * as _ from 'lodash';
import {Order, SignedOrder, SolidityTypes} from '../types';
import * as BigNumber from 'bignumber.js';
import BN = require('bn.js');
export const utils = {
/**
@@ -12,7 +13,7 @@ export const utils = {
* expects values of Solidity type `uint` to be passed as type `BN`.
* We do not use BN anywhere else in the codebase.
*/
bigNumberToBN(value: BigNumber.BigNumber) {
bigNumberToBN(value: BigNumber) {
return new BN(value.toString(), 10);
},
consoleLog(message: string): void {
@@ -49,7 +50,10 @@ export const utils = {
const hashHex = ethUtil.bufferToHex(hashBuff);
return hashHex;
},
getCurrentUnixTimestamp(): BigNumber.BigNumber {
return new BigNumber(Date.now() / 1000);
getCurrentUnixTimestampSec(): BigNumber {
return new BigNumber(Date.now() / 1000).round();
},
getCurrentUnixTimestampMs(): BigNumber {
return new BigNumber(Date.now());
},
};

View File

@@ -0,0 +1,200 @@
import BigNumber from 'bignumber.js';
import promisify = require('es6-promisify');
import * as _ from 'lodash';
import * as Web3 from 'web3';
import {Contract} from './contract';
import {Artifact, ArtifactContractName, TransactionReceipt, ZeroExError} from './types';
interface RawLogEntry {
logIndex: string|null;
transactionIndex: string|null;
transactionHash: string;
blockHash: string|null;
blockNumber: string|null;
address: string;
data: string;
topics: string[];
}
const CONTRACT_NAME_TO_NOT_FOUND_ERROR: {[contractName: string]: ZeroExError} = {
ZRX: ZeroExError.ZRXContractDoesNotExist,
EtherToken: ZeroExError.EtherTokenContractDoesNotExist,
Token: ZeroExError.TokenContractDoesNotExist,
TokenRegistry: ZeroExError.TokenRegistryContractDoesNotExist,
TokenTransferProxy: ZeroExError.TokenTransferProxyContractDoesNotExist,
Exchange: ZeroExError.ExchangeContractDoesNotExist,
};
export class Web3Wrapper {
private web3: Web3;
private networkId: number;
private defaults: Partial<Web3.TxData>;
private jsonRpcRequestId: number;
constructor(provider: Web3.Provider, networkId: number, defaults?: Partial<Web3.TxData>) {
if (_.isUndefined((provider as any).sendAsync)) {
// Web3@1.0 provider doesn't support synchronous http requests,
// so it only has an async `send` method, instead of a `send` and `sendAsync` in web3@0.x.x`
// We re-assign the send method so that Web3@1.0 providers work with 0x.js
(provider as any).sendAsync = (provider as any).send;
}
this.web3 = new Web3();
this.networkId = networkId;
this.web3.setProvider(provider);
this.defaults = defaults || {};
this.jsonRpcRequestId = 0;
}
public setProvider(provider: Web3.Provider, networkId: number) {
this.networkId = networkId;
this.web3.setProvider(provider);
}
public isAddress(address: string): boolean {
return this.web3.isAddress(address);
}
public async isSenderAddressAvailableAsync(senderAddress: string): Promise<boolean> {
const addresses = await this.getAvailableAddressesAsync();
return _.includes(addresses, senderAddress);
}
public async getNodeVersionAsync(): Promise<string> {
const nodeVersion = await promisify(this.web3.version.getNode)();
return nodeVersion;
}
public async getTransactionReceiptAsync(txHash: string): Promise<TransactionReceipt> {
const transactionReceipt = await promisify(this.web3.eth.getTransactionReceipt)(txHash);
if (!_.isNull(transactionReceipt)) {
transactionReceipt.status = this.normalizeTxReceiptStatus(transactionReceipt.status);
}
return transactionReceipt;
}
public getCurrentProvider(): Web3.Provider {
return this.web3.currentProvider;
}
public getNetworkId(): number {
return this.networkId;
}
public async getContractInstanceFromArtifactAsync<A extends Web3.ContractInstance>(artifact: Artifact,
address?: string): Promise<A> {
let contractAddress: string;
if (_.isUndefined(address)) {
const networkId = this.getNetworkId();
if (_.isUndefined(artifact.networks[networkId])) {
throw new Error(ZeroExError.ContractNotDeployedOnNetwork);
}
contractAddress = artifact.networks[networkId].address.toLowerCase();
} else {
contractAddress = address;
}
const doesContractExist = await this.doesContractExistAtAddressAsync(contractAddress);
if (!doesContractExist) {
throw new Error(CONTRACT_NAME_TO_NOT_FOUND_ERROR[artifact.contract_name]);
}
const contractInstance = this.getContractInstance<A>(
artifact.abi, contractAddress,
);
return contractInstance;
}
public toWei(ethAmount: BigNumber): BigNumber {
const balanceWei = this.web3.toWei(ethAmount, 'ether');
return balanceWei;
}
public async getBalanceInWeiAsync(owner: string): Promise<BigNumber> {
let balanceInWei = await promisify(this.web3.eth.getBalance)(owner);
balanceInWei = new BigNumber(balanceInWei);
return balanceInWei;
}
public async doesContractExistAtAddressAsync(address: string): Promise<boolean> {
const code = await promisify(this.web3.eth.getCode)(address);
// Regex matches 0x0, 0x00, 0x in order to accommodate poorly implemented clients
const codeIsEmpty = /^0x0{0,40}$/i.test(code);
return !codeIsEmpty;
}
public async signTransactionAsync(address: string, message: string): Promise<string> {
const signData = await promisify(this.web3.eth.sign)(address, message);
return signData;
}
public async getBlockNumberAsync(): Promise<number> {
const blockNumber = await promisify(this.web3.eth.getBlockNumber)();
return blockNumber;
}
public async getBlockAsync(blockParam: string|Web3.BlockParam): Promise<Web3.BlockWithoutTransactionData> {
const block = await promisify(this.web3.eth.getBlock)(blockParam);
return block;
}
public async getBlockTimestampAsync(blockParam: string|Web3.BlockParam): Promise<number> {
const {timestamp} = await this.getBlockAsync(blockParam);
return timestamp;
}
public async getAvailableAddressesAsync(): Promise<string[]> {
const addresses: string[] = await promisify(this.web3.eth.getAccounts)();
return addresses;
}
public async getLogsAsync(filter: Web3.FilterObject): Promise<Web3.LogEntry[]> {
let fromBlock = filter.fromBlock;
if (_.isNumber(fromBlock)) {
fromBlock = this.web3.toHex(fromBlock);
}
let toBlock = filter.toBlock;
if (_.isNumber(toBlock)) {
toBlock = this.web3.toHex(toBlock);
}
const serializedFilter = {
...filter,
fromBlock,
toBlock,
};
const payload = {
jsonrpc: '2.0',
id: this.jsonRpcRequestId++,
method: 'eth_getLogs',
params: [serializedFilter],
};
const rawLogs = await this.sendRawPayloadAsync<RawLogEntry[]>(payload);
const formattedLogs = _.map(rawLogs, this.formatLog.bind(this));
return formattedLogs;
}
private getContractInstance<A extends Web3.ContractInstance>(abi: Web3.ContractAbi, address: string): A {
const web3ContractInstance = this.web3.eth.contract(abi).at(address);
const contractInstance = new Contract(web3ContractInstance, this.defaults) as any as A;
return contractInstance;
}
private async getNetworkAsync(): Promise<number> {
const networkId = await promisify(this.web3.version.getNetwork)();
return networkId;
}
private async sendRawPayloadAsync<A>(payload: Web3.JSONRPCRequestPayload): Promise<A> {
const sendAsync = this.web3.currentProvider.sendAsync.bind(this.web3.currentProvider);
const response = await promisify(sendAsync)(payload);
const result = response.result;
return result;
}
private normalizeTxReceiptStatus(status: undefined|null|string|0|1): null|0|1 {
// Transaction status might have four values
// undefined - Testrpc and other old clients
// null - New clients on old transactions
// number - Parity
// hex - Geth
if (_.isString(status)) {
return this.web3.toDecimal(status) as 0|1;
} else if (_.isUndefined(status)) {
return null;
} else {
return status;
}
}
private formatLog(rawLog: RawLogEntry): Web3.LogEntry {
const formattedLog = {
...rawLog,
logIndex: this.hexToDecimal(rawLog.logIndex),
blockNumber: this.hexToDecimal(rawLog.blockNumber),
transactionIndex: this.hexToDecimal(rawLog.transactionIndex),
};
return formattedLog;
}
private hexToDecimal(hex: string|null): number|null {
if (_.isNull(hex)) {
return null;
}
const decimal = this.web3.toDecimal(hex);
return decimal;
}
}

View File

@@ -1,14 +1,16 @@
import * as _ from 'lodash';
import BigNumber from 'bignumber.js';
import * as chai from 'chai';
import {chaiSetup} from './utils/chai_setup';
import * as _ from 'lodash';
import 'mocha';
import * as BigNumber from 'bignumber.js';
import * as Sinon from 'sinon';
import {ZeroEx, Order, ZeroExError, LogWithDecodedArgs} from '../src';
import {ApprovalContractEventArgs, LogWithDecodedArgs, Order, TokenEvents, ZeroEx, ZeroExError} from '../src';
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
import {chaiSetup} from './utils/chai_setup';
import {constants} from './utils/constants';
import {TokenUtils} from './utils/token_utils';
import {web3Factory} from './utils/web3_factory';
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
const blockchainLifecycle = new BlockchainLifecycle();
chaiSetup.configure();
@@ -16,7 +18,10 @@ const expect = chai.expect;
describe('ZeroEx library', () => {
const web3 = web3Factory.create();
const zeroEx = new ZeroEx(web3.currentProvider);
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
const zeroEx = new ZeroEx(web3.currentProvider, config);
describe('#setProvider', () => {
it('overrides provider in nested web3s and invalidates contractInstances', async () => {
// Instantiate the contract instances with the current provider
@@ -28,7 +33,7 @@ describe('ZeroEx library', () => {
const newProvider = web3Factory.getRpcProvider();
// Add property to newProvider so that we can differentiate it from old provider
(newProvider as any).zeroExTestId = 1;
await zeroEx.setProviderAsync(newProvider);
zeroEx.setProvider(newProvider, constants.TESTRPC_NETWORK_ID);
// Check that contractInstances with old provider are removed after provider update
expect((zeroEx.exchange as any)._exchangeContractIfExists).to.be.undefined();
@@ -36,11 +41,11 @@ describe('ZeroEx library', () => {
// Check that all nested web3 wrapper instances return the updated provider
const nestedWeb3WrapperProvider = (zeroEx as any)._web3Wrapper.getCurrentProvider();
expect((nestedWeb3WrapperProvider as any).zeroExTestId).to.be.a('number');
expect((nestedWeb3WrapperProvider).zeroExTestId).to.be.a('number');
const exchangeWeb3WrapperProvider = (zeroEx.exchange as any)._web3Wrapper.getCurrentProvider();
expect((exchangeWeb3WrapperProvider as any).zeroExTestId).to.be.a('number');
expect((exchangeWeb3WrapperProvider).zeroExTestId).to.be.a('number');
const tokenRegistryWeb3WrapperProvider = (zeroEx.tokenRegistry as any)._web3Wrapper.getCurrentProvider();
expect((tokenRegistryWeb3WrapperProvider as any).zeroExTestId).to.be.a('number');
expect((tokenRegistryWeb3WrapperProvider).zeroExTestId).to.be.a('number');
});
});
describe('#isValidSignature', () => {
@@ -220,11 +225,11 @@ describe('ZeroEx library', () => {
const tokens = await zeroEx.tokenRegistry.getTokensAsync();
const tokenUtils = new TokenUtils(tokens);
const zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address;
const proxyAddress = await zeroEx.proxy.getContractAddressAsync();
const proxyAddress = zeroEx.proxy.getContractAddress();
const txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(zrxTokenAddress, coinbase);
const txReceiptWithDecodedLogs = await zeroEx.awaitTransactionMinedAsync(txHash);
const log = txReceiptWithDecodedLogs.logs[0] as LogWithDecodedArgs;
expect(log.event).to.be.equal('Approval');
const log = txReceiptWithDecodedLogs.logs[0] as LogWithDecodedArgs<ApprovalContractEventArgs>;
expect(log.event).to.be.equal(TokenEvents.Approval);
expect(log.args._owner).to.be.equal(coinbase);
expect(log.args._spender).to.be.equal(proxyAddress);
expect(log.args._value).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
@@ -232,28 +237,29 @@ describe('ZeroEx library', () => {
});
describe('#config', () => {
it('allows to specify exchange contract address', async () => {
const config = {
const zeroExConfig = {
exchangeContractAddress: ZeroEx.NULL_ADDRESS,
networkId: constants.TESTRPC_NETWORK_ID,
};
const zeroExWithWrongExchangeAddress = new ZeroEx(web3.currentProvider, config);
return expect(zeroExWithWrongExchangeAddress.exchange.getContractAddressAsync())
.to.be.rejectedWith(ZeroExError.ContractDoesNotExist);
const zeroExWithWrongExchangeAddress = new ZeroEx(web3.currentProvider, zeroExConfig);
expect(zeroExWithWrongExchangeAddress.exchange.getContractAddress()).to.be.equal(ZeroEx.NULL_ADDRESS);
});
it('allows to specify ether token contract address', async () => {
const config = {
const zeroExConfig = {
etherTokenContractAddress: ZeroEx.NULL_ADDRESS,
networkId: constants.TESTRPC_NETWORK_ID,
};
const zeroExWithWrongEtherTokenAddress = new ZeroEx(web3.currentProvider, config);
return expect(zeroExWithWrongEtherTokenAddress.etherToken.getContractAddressAsync())
.to.be.rejectedWith(ZeroExError.ContractDoesNotExist);
const zeroExWithWrongEtherTokenAddress = new ZeroEx(web3.currentProvider, zeroExConfig);
expect(zeroExWithWrongEtherTokenAddress.etherToken.getContractAddress()).to.be.equal(ZeroEx.NULL_ADDRESS);
});
it('allows to specify token registry token contract address', async () => {
const config = {
const zeroExConfig = {
tokenRegistryContractAddress: ZeroEx.NULL_ADDRESS,
networkId: constants.TESTRPC_NETWORK_ID,
};
const zeroExWithWrongTokenRegistryAddress = new ZeroEx(web3.currentProvider, config);
return expect(zeroExWithWrongTokenRegistryAddress.tokenRegistry.getContractAddressAsync())
.to.be.rejectedWith(ZeroExError.ContractDoesNotExist);
const zeroExWithWrongTokenRegistryAddress = new ZeroEx(web3.currentProvider, zeroExConfig);
expect(zeroExWithWrongTokenRegistryAddress.tokenRegistry.getContractAddress())
.to.be.equal(ZeroEx.NULL_ADDRESS);
});
});
});

View File

@@ -1,8 +1,10 @@
import * as fs from 'fs';
import * as chai from 'chai';
import {chaiSetup} from './utils/chai_setup';
import * as fs from 'fs';
import HDWalletProvider = require('truffle-hdwallet-provider');
import {ZeroEx} from '../src';
import {chaiSetup} from './utils/chai_setup';
import {constants} from './utils/constants';
chaiSetup.configure();
@@ -18,15 +20,18 @@ describe('Artifacts', () => {
const packageJSON = JSON.parse(packageJSONContent);
const mnemonic = packageJSON.config.mnemonic;
const web3Provider = new HDWalletProvider(mnemonic, kovanRpcUrl);
const zeroEx = new ZeroEx(web3Provider);
const config = {
networkId: constants.KOVAN_NETWORK_ID,
};
const zeroEx = new ZeroEx(web3Provider, config);
it('token registry contract is deployed', async () => {
await (zeroEx.tokenRegistry as any)._getTokenRegistryContractAsync();
}).timeout(TIMEOUT);
it('proxy contract is deployed', async () => {
await (zeroEx.token as any)._getTokenTransferProxyAddressAsync();
await (zeroEx.proxy as any)._getTokenTransferProxyContractAsync();
}).timeout(TIMEOUT);
it('exchange contract is deployed', async () => {
await zeroEx.exchange.getContractAddressAsync();
await (zeroEx.exchange as any)._getExchangeContractAsync();
}).timeout(TIMEOUT);
});
describe('contracts are deployed on ropsten', () => {
@@ -35,15 +40,18 @@ describe('Artifacts', () => {
const packageJSON = JSON.parse(packageJSONContent);
const mnemonic = packageJSON.config.mnemonic;
const web3Provider = new HDWalletProvider(mnemonic, ropstenRpcUrl);
const zeroEx = new ZeroEx(web3Provider);
const config = {
networkId: constants.ROPSTEN_NETWORK_ID,
};
const zeroEx = new ZeroEx(web3Provider, config);
it('token registry contract is deployed', async () => {
await (zeroEx.tokenRegistry as any)._getTokenRegistryContractAsync();
}).timeout(TIMEOUT);
it('proxy contract is deployed', async () => {
await (zeroEx.token as any)._getTokenTransferProxyAddressAsync();
await (zeroEx.proxy as any)._getTokenTransferProxyContractAsync();
}).timeout(TIMEOUT);
it('exchange contract is deployed', async () => {
await zeroEx.exchange.getContractAddressAsync();
await (zeroEx.exchange as any)._getExchangeContractAsync();
}).timeout(TIMEOUT);
});
});

View File

@@ -1,14 +1,20 @@
import * as chai from 'chai';
import 'mocha';
import {ZeroEx} from '../src';
import {assert} from '../src/utils/assert';
import {constants} from './utils/constants';
import {web3Factory} from './utils/web3_factory';
const expect = chai.expect;
describe('Assertion library', () => {
const web3 = web3Factory.create();
const zeroEx = new ZeroEx(web3.currentProvider);
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
const zeroEx = new ZeroEx(web3.currentProvider, config);
describe('#isSenderAddressHexAsync', () => {
it('throws when address is invalid', async () => {
const address = '0xdeadbeef';

View File

@@ -1,12 +1,14 @@
import 'mocha';
import BigNumber from 'bignumber.js';
import * as chai from 'chai';
import {chaiSetup} from './utils/chai_setup';
import 'mocha';
import * as Web3 from 'web3';
import * as BigNumber from 'bignumber.js';
import promisify = require('es6-promisify');
import {web3Factory} from './utils/web3_factory';
import {ZeroEx, ZeroExError} from '../src';
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
import {chaiSetup} from './utils/chai_setup';
import {constants} from './utils/constants';
import {web3Factory} from './utils/web3_factory';
chaiSetup.configure();
const expect = chai.expect;
@@ -16,7 +18,7 @@ const blockchainLifecycle = new BlockchainLifecycle();
// a small amount of ETH will be used to pay this gas cost. We therefore check that the difference between
// the expected balance and actual balance (given the amount of ETH deposited), only deviates by the amount
// required to pay gas costs.
const MAX_REASONABLE_GAS_COST_IN_WEI = 62237;
const MAX_REASONABLE_GAS_COST_IN_WEI = 62517;
describe('EtherTokenWrapper', () => {
let web3: Web3;
@@ -24,18 +26,19 @@ describe('EtherTokenWrapper', () => {
let userAddresses: string[];
let addressWithETH: string;
let wethContractAddress: string;
let depositWeiAmount: BigNumber.BigNumber;
let depositWeiAmount: BigNumber;
let decimalPlaces: number;
const gasPrice = new BigNumber(1);
const zeroExConfig = {
gasPrice,
networkId: constants.TESTRPC_NETWORK_ID,
};
before(async () => {
web3 = web3Factory.create();
zeroEx = new ZeroEx(web3.currentProvider, zeroExConfig);
userAddresses = await zeroEx.getAvailableAddressesAsync();
addressWithETH = userAddresses[0];
wethContractAddress = await zeroEx.etherToken.getContractAddressAsync();
wethContractAddress = zeroEx.etherToken.getContractAddress();
depositWeiAmount = (zeroEx as any)._web3Wrapper.toWei(new BigNumber(5));
decimalPlaces = 7;
});

View File

@@ -0,0 +1,130 @@
import BigNumber from 'bignumber.js';
import * as chai from 'chai';
import * as _ from 'lodash';
import 'mocha';
import * as Sinon from 'sinon';
import * as Web3 from 'web3';
import {
DecodedLogEvent,
LogEvent,
ZeroEx,
} from '../src';
import {EventWatcher} from '../src/order_watcher/event_watcher';
import {DoneCallback} from '../src/types';
import {Web3Wrapper} from '../src/web3_wrapper';
import {chaiSetup} from './utils/chai_setup';
import {constants} from './utils/constants';
import {web3Factory} from './utils/web3_factory';
chaiSetup.configure();
const expect = chai.expect;
describe('EventWatcher', () => {
let web3: Web3;
let stubs: Sinon.SinonStub[] = [];
let eventWatcher: EventWatcher;
let web3Wrapper: Web3Wrapper;
const numConfirmations = 0;
const logA: Web3.LogEntry = {
address: '0x71d271f8b14adef568f8f28f1587ce7271ac4ca5',
blockHash: null,
blockNumber: null,
data: '',
logIndex: null,
topics: [],
transactionHash: '0x004881d38cd4a8f72f1a0d68c8b9b8124504706041ff37019c1d1ed6bfda8e17',
transactionIndex: 0,
};
const logB: Web3.LogEntry = {
address: '0x8d12a197cb00d4747a1fe03395095ce2a5cc6819',
blockHash: null,
blockNumber: null,
data: '',
logIndex: null,
topics: [ '0xf341246adaac6f497bc2a656f546ab9e182111d630394f0c57c710a59a2cb567' ],
transactionHash: '0x01ef3c048b18d9b09ea195b4ed94cf8dd5f3d857a1905ff886b152cfb1166f25',
transactionIndex: 0,
};
const logC: Web3.LogEntry = {
address: '0x1d271f8b174adef58f1587ce68f8f27271ac4ca5',
blockHash: null,
blockNumber: null,
data: '',
logIndex: null,
topics: [ '0xf341246adaac6f497bc2a656f546ab9e182111d630394f0c57c710a59a2cb567' ],
transactionHash: '0x01ef3c048b18d9b09ea195b4ed94cf8dd5f3d857a1905ff886b152cfb1166f25',
transactionIndex: 0,
};
before(async () => {
web3 = web3Factory.create();
const pollingIntervalMs = 10;
web3Wrapper = new Web3Wrapper(web3.currentProvider, constants.TESTRPC_NETWORK_ID);
eventWatcher = new EventWatcher(web3Wrapper, pollingIntervalMs);
});
afterEach(() => {
// clean up any stubs after the test has completed
_.each(stubs, s => s.restore());
stubs = [];
eventWatcher.unsubscribe();
});
it('correctly emits initial log events', (done: DoneCallback) => {
const logs: Web3.LogEntry[] = [logA, logB];
const expectedLogEvents = [
{
removed: false,
...logA,
},
{
removed: false,
...logB,
},
];
const getLogsStub = Sinon.stub(web3Wrapper, 'getLogsAsync');
getLogsStub.onCall(0).returns(logs);
stubs.push(getLogsStub);
const callback = (event: LogEvent) => {
const expectedLogEvent = expectedLogEvents.shift();
expect(event).to.be.deep.equal(expectedLogEvent);
if (_.isEmpty(expectedLogEvents)) {
done();
}
};
eventWatcher.subscribe(callback);
});
it('correctly computes the difference and emits only changes', (done: DoneCallback) => {
const initialLogs: Web3.LogEntry[] = [logA, logB];
const changedLogs: Web3.LogEntry[] = [logA, logC];
const expectedLogEvents = [
{
removed: false,
...logA,
},
{
removed: false,
...logB,
},
{
removed: true,
...logB,
},
{
removed: false,
...logC,
},
];
const getLogsStub = Sinon.stub(web3Wrapper, 'getLogsAsync');
getLogsStub.onCall(0).returns(initialLogs);
getLogsStub.onCall(1).returns(changedLogs);
stubs.push(getLogsStub);
const callback = (event: LogEvent) => {
const expectedLogEvent = expectedLogEvents.shift();
expect(event).to.be.deep.equal(expectedLogEvent);
if (_.isEmpty(expectedLogEvents)) {
done();
}
};
eventWatcher.subscribe(callback);
});
});

View File

@@ -0,0 +1,93 @@
import BigNumber from 'bignumber.js';
import * as chai from 'chai';
import {ExchangeContractErrs, Token, ZeroEx} from '../src';
import {BlockParamLiteral, TradeSide, TransferType} from '../src/types';
import {ExchangeTransferSimulator} from '../src/utils/exchange_transfer_simulator';
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
import {chaiSetup} from './utils/chai_setup';
import {constants} from './utils/constants';
import {web3Factory} from './utils/web3_factory';
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle();
describe('ExchangeTransferSimulator', () => {
const web3 = web3Factory.create();
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
const zeroEx = new ZeroEx(web3.currentProvider, config);
const transferAmount = new BigNumber(5);
let userAddresses: string[];
let tokens: Token[];
let coinbase: string;
let sender: string;
let recipient: string;
let exampleTokenAddress: string;
let exchangeTransferSimulator: ExchangeTransferSimulator;
let txHash: string;
before(async () => {
userAddresses = await zeroEx.getAvailableAddressesAsync();
[coinbase, sender, recipient] = userAddresses;
tokens = await zeroEx.tokenRegistry.getTokensAsync();
exampleTokenAddress = tokens[0].address;
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('#transferFromAsync', () => {
beforeEach(() => {
exchangeTransferSimulator = new ExchangeTransferSimulator(zeroEx.token, BlockParamLiteral.Latest);
});
it('throws if the user doesn\'t have enough allowance', async () => {
return expect(exchangeTransferSimulator.transferFromAsync(
exampleTokenAddress, sender, recipient, transferAmount, TradeSide.Taker, TransferType.Trade,
)).to.be.rejectedWith(ExchangeContractErrs.InsufficientTakerAllowance);
});
it('throws if the user doesn\'t have enough balance', async () => {
txHash = await zeroEx.token.setProxyAllowanceAsync(exampleTokenAddress, sender, transferAmount);
await zeroEx.awaitTransactionMinedAsync(txHash);
return expect(exchangeTransferSimulator.transferFromAsync(
exampleTokenAddress, sender, recipient, transferAmount, TradeSide.Maker, TransferType.Trade,
)).to.be.rejectedWith(ExchangeContractErrs.InsufficientMakerBalance);
});
it('updates balances and proxyAllowance after transfer', async () => {
txHash = await zeroEx.token.transferAsync(exampleTokenAddress, coinbase, sender, transferAmount);
await zeroEx.awaitTransactionMinedAsync(txHash);
txHash = await zeroEx.token.setProxyAllowanceAsync(exampleTokenAddress, sender, transferAmount);
await zeroEx.awaitTransactionMinedAsync(txHash);
await exchangeTransferSimulator.transferFromAsync(
exampleTokenAddress, sender, recipient, transferAmount, TradeSide.Taker, TransferType.Trade,
);
const store = (exchangeTransferSimulator as any).store;
const senderBalance = await store.getBalanceAsync(exampleTokenAddress, sender);
const recipientBalance = await store.getBalanceAsync(exampleTokenAddress, recipient);
const senderProxyAllowance = await store.getProxyAllowanceAsync(exampleTokenAddress, sender);
expect(senderBalance).to.be.bignumber.equal(0);
expect(recipientBalance).to.be.bignumber.equal(transferAmount);
expect(senderProxyAllowance).to.be.bignumber.equal(0);
});
it('doesn\'t update proxyAllowance after transfer if unlimited', async () => {
txHash = await zeroEx.token.transferAsync(exampleTokenAddress, coinbase, sender, transferAmount);
await zeroEx.awaitTransactionMinedAsync(txHash);
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(exampleTokenAddress, sender);
await zeroEx.awaitTransactionMinedAsync(txHash);
await exchangeTransferSimulator.transferFromAsync(
exampleTokenAddress, sender, recipient, transferAmount, TradeSide.Taker, TransferType.Trade,
);
const store = (exchangeTransferSimulator as any).store;
const senderBalance = await store.getBalanceAsync(exampleTokenAddress, sender);
const recipientBalance = await store.getBalanceAsync(exampleTokenAddress, recipient);
const senderProxyAllowance = await store.getProxyAllowanceAsync(exampleTokenAddress, sender);
expect(senderBalance).to.be.bignumber.equal(0);
expect(recipientBalance).to.be.bignumber.equal(transferAmount);
expect(senderProxyAllowance).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
});
});
});

View File

@@ -1,30 +1,30 @@
import 'mocha';
import BigNumber from 'bignumber.js';
import * as chai from 'chai';
import 'mocha';
import * as Web3 from 'web3';
import * as BigNumber from 'bignumber.js';
import {chaiSetup} from './utils/chai_setup';
import ChaiBigNumber = require('chai-bignumber');
import promisify = require('es6-promisify');
import {web3Factory} from './utils/web3_factory';
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
import {
ZeroEx,
Token,
SignedOrder,
SubscriptionOpts,
ExchangeEvents,
ContractEvent,
DecodedLogEvent,
ExchangeContractErrs,
ExchangeEvents,
LogCancelContractEventArgs,
LogEvent,
LogFillContractEventArgs,
OrderCancellationRequest,
OrderFillRequest,
LogFillContractEventArgs,
OrderFillOrKillRequest,
SignedOrder,
SubscriptionOpts,
Token,
ZeroEx,
} from '../src';
import {DoneCallback} from '../src/types';
import {BlockParamLiteral, DoneCallback} from '../src/types';
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
import {chaiSetup} from './utils/chai_setup';
import {constants} from './utils/constants';
import {FillScenarios} from './utils/fill_scenarios';
import {TokenUtils} from './utils/token_utils';
import {assert} from '../src/utils/assert';
import {TokenTransferProxyWrapper} from '../src/contract_wrappers/token_transfer_proxy_wrapper';
import {web3Factory} from './utils/web3_factory';
chaiSetup.configure();
const expect = chai.expect;
@@ -41,10 +41,13 @@ describe('ExchangeWrapper', () => {
let zrxTokenAddress: string;
let fillScenarios: FillScenarios;
let exchangeContractAddress: string;
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
before(async () => {
web3 = web3Factory.create();
zeroEx = new ZeroEx(web3.currentProvider);
exchangeContractAddress = await zeroEx.exchange.getContractAddressAsync();
zeroEx = new ZeroEx(web3.currentProvider, config);
exchangeContractAddress = zeroEx.exchange.getContractAddress();
userAddresses = await zeroEx.getAvailableAddressesAsync();
tokens = await zeroEx.tokenRegistry.getTokensAsync();
tokenUtils = new TokenUtils(tokens);
@@ -64,7 +67,7 @@ describe('ExchangeWrapper', () => {
let makerAddress: string;
let takerAddress: string;
let feeRecipient: string;
const fillTakerAmount = new BigNumber(5);
const takerTokenFillAmount = new BigNumber(5);
before(async () => {
[coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses;
tokens = await zeroEx.tokenRegistry.getTokensAsync();
@@ -73,7 +76,7 @@ describe('ExchangeWrapper', () => {
takerTokenAddress = takerToken.address;
});
describe('#batchFillOrKillAsync', () => {
it('successfuly batch fillOrKill', async () => {
it('successfully batch fillOrKill', async () => {
const fillableAmount = new BigNumber(5);
const partialFillTakerAmount = new BigNumber(2);
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
@@ -82,44 +85,44 @@ describe('ExchangeWrapper', () => {
const anotherSignedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
);
const orderFillOrKillRequests = [
const orderFillRequests = [
{
signedOrder,
fillTakerAmount: partialFillTakerAmount,
takerTokenFillAmount: partialFillTakerAmount,
},
{
signedOrder: anotherSignedOrder,
fillTakerAmount: partialFillTakerAmount,
takerTokenFillAmount: partialFillTakerAmount,
},
];
await zeroEx.exchange.batchFillOrKillAsync(orderFillOrKillRequests, takerAddress);
await zeroEx.exchange.batchFillOrKillAsync(orderFillRequests, takerAddress);
});
describe('order transaction options', () => {
let signedOrder: SignedOrder;
let orderFillOrKillRequests: OrderFillOrKillRequest[];
let orderFillRequests: OrderFillRequest[];
const fillableAmount = new BigNumber(5);
beforeEach(async () => {
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
);
orderFillOrKillRequests = [
orderFillRequests = [
{
signedOrder,
fillTakerAmount: new BigNumber(0),
takerTokenFillAmount: new BigNumber(0),
},
];
});
it('should validate when orderTransactionOptions are not present', async () => {
return expect(zeroEx.exchange.batchFillOrKillAsync(orderFillOrKillRequests, takerAddress))
return expect(zeroEx.exchange.batchFillOrKillAsync(orderFillRequests, takerAddress))
.to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero);
});
it('should validate when orderTransactionOptions specify to validate', async () => {
return expect(zeroEx.exchange.batchFillOrKillAsync(orderFillOrKillRequests, takerAddress, {
return expect(zeroEx.exchange.batchFillOrKillAsync(orderFillRequests, takerAddress, {
shouldValidate: true,
})).to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero);
});
it('should not validate when orderTransactionOptions specify not to validate', async () => {
return expect(zeroEx.exchange.batchFillOrKillAsync(orderFillOrKillRequests, takerAddress, {
return expect(zeroEx.exchange.batchFillOrKillAsync(orderFillRequests, takerAddress, {
shouldValidate: false,
})).to.not.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero);
});
@@ -143,15 +146,15 @@ describe('ExchangeWrapper', () => {
.to.be.bignumber.equal(0);
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, takerAddress))
.to.be.bignumber.equal(fillableAmount);
await zeroEx.exchange.fillOrKillOrderAsync(signedOrder, fillTakerAmount, takerAddress);
await zeroEx.exchange.fillOrKillOrderAsync(signedOrder, takerTokenFillAmount, takerAddress);
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, makerAddress))
.to.be.bignumber.equal(fillableAmount.minus(fillTakerAmount));
.to.be.bignumber.equal(fillableAmount.minus(takerTokenFillAmount));
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, makerAddress))
.to.be.bignumber.equal(fillTakerAmount);
.to.be.bignumber.equal(takerTokenFillAmount);
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, takerAddress))
.to.be.bignumber.equal(fillTakerAmount);
.to.be.bignumber.equal(takerTokenFillAmount);
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, takerAddress))
.to.be.bignumber.equal(fillableAmount.minus(fillTakerAmount));
.to.be.bignumber.equal(fillableAmount.minus(takerTokenFillAmount));
});
it('should partially fill a valid order', async () => {
const partialFillAmount = new BigNumber(3);
@@ -193,7 +196,7 @@ describe('ExchangeWrapper', () => {
let takerAddress: string;
let feeRecipient: string;
const fillableAmount = new BigNumber(5);
const fillTakerAmount = new BigNumber(5);
const takerTokenFillAmount = new BigNumber(5);
const shouldThrowOnInsufficientBalanceOrAllowance = true;
before(async () => {
[coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses;
@@ -217,16 +220,16 @@ describe('ExchangeWrapper', () => {
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, takerAddress))
.to.be.bignumber.equal(fillableAmount);
const txHash = await zeroEx.exchange.fillOrderAsync(
signedOrder, fillTakerAmount, shouldThrowOnInsufficientBalanceOrAllowance, takerAddress);
signedOrder, takerTokenFillAmount, shouldThrowOnInsufficientBalanceOrAllowance, takerAddress);
await zeroEx.awaitTransactionMinedAsync(txHash);
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, makerAddress))
.to.be.bignumber.equal(fillableAmount.minus(fillTakerAmount));
.to.be.bignumber.equal(fillableAmount.minus(takerTokenFillAmount));
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, makerAddress))
.to.be.bignumber.equal(fillTakerAmount);
.to.be.bignumber.equal(takerTokenFillAmount);
expect(await zeroEx.token.getBalanceAsync(makerTokenAddress, takerAddress))
.to.be.bignumber.equal(fillTakerAmount);
.to.be.bignumber.equal(takerTokenFillAmount);
expect(await zeroEx.token.getBalanceAsync(takerTokenAddress, takerAddress))
.to.be.bignumber.equal(fillableAmount.minus(fillTakerAmount));
.to.be.bignumber.equal(fillableAmount.minus(takerTokenFillAmount));
});
it('should partially fill the valid order', async () => {
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
@@ -253,7 +256,7 @@ describe('ExchangeWrapper', () => {
makerAddress, takerAddress, fillableAmount, feeRecipient,
);
const txHash = await zeroEx.exchange.fillOrderAsync(
signedOrder, fillTakerAmount, shouldThrowOnInsufficientBalanceOrAllowance, takerAddress);
signedOrder, takerTokenFillAmount, shouldThrowOnInsufficientBalanceOrAllowance, takerAddress);
await zeroEx.awaitTransactionMinedAsync(txHash);
expect(await zeroEx.token.getBalanceAsync(zrxTokenAddress, feeRecipient))
.to.be.bignumber.equal(makerFee.plus(takerFee));
@@ -307,11 +310,11 @@ describe('ExchangeWrapper', () => {
orderFillBatch = [
{
signedOrder,
takerTokenFillAmount: fillTakerAmount,
takerTokenFillAmount,
},
{
signedOrder: anotherSignedOrder,
takerTokenFillAmount: fillTakerAmount,
takerTokenFillAmount,
},
];
});
@@ -326,8 +329,8 @@ describe('ExchangeWrapper', () => {
await zeroEx.awaitTransactionMinedAsync(txHash);
const filledAmount = await zeroEx.exchange.getFilledTakerAmountAsync(signedOrderHashHex);
const anotherFilledAmount = await zeroEx.exchange.getFilledTakerAmountAsync(anotherOrderHashHex);
expect(filledAmount).to.be.bignumber.equal(fillTakerAmount);
expect(anotherFilledAmount).to.be.bignumber.equal(fillTakerAmount);
expect(filledAmount).to.be.bignumber.equal(takerTokenFillAmount);
expect(anotherFilledAmount).to.be.bignumber.equal(takerTokenFillAmount);
});
});
describe('order transaction options', () => {
@@ -446,7 +449,7 @@ describe('ExchangeWrapper', () => {
it('should cancel an order', async () => {
const txHash = await zeroEx.exchange.cancelOrderAsync(signedOrder, cancelAmount);
await zeroEx.awaitTransactionMinedAsync(txHash);
const cancelledAmount = await zeroEx.exchange.getCanceledTakerAmountAsync(orderHashHex);
const cancelledAmount = await zeroEx.exchange.getCancelledTakerAmountAsync(orderHashHex);
expect(cancelledAmount).to.be.bignumber.equal(cancelAmount);
});
});
@@ -505,8 +508,8 @@ describe('ExchangeWrapper', () => {
describe('successful batch cancels', () => {
it('should cancel a batch of orders', async () => {
await zeroEx.exchange.batchCancelOrdersAsync(cancelBatch);
const cancelledAmount = await zeroEx.exchange.getCanceledTakerAmountAsync(orderHashHex);
const anotherCancelledAmount = await zeroEx.exchange.getCanceledTakerAmountAsync(
const cancelledAmount = await zeroEx.exchange.getCancelledTakerAmountAsync(orderHashHex);
const anotherCancelledAmount = await zeroEx.exchange.getCancelledTakerAmountAsync(
anotherOrderHashHex,
);
expect(cancelledAmount).to.be.bignumber.equal(cancelAmount);
@@ -548,8 +551,8 @@ describe('ExchangeWrapper', () => {
let makerTokenAddress: string;
let takerTokenAddress: string;
let takerAddress: string;
let fillableAmount: BigNumber.BigNumber;
let partialFillAmount: BigNumber.BigNumber;
let fillableAmount: BigNumber;
let partialFillAmount: BigNumber;
let signedOrder: SignedOrder;
let orderHash: string;
before(() => {
@@ -595,28 +598,28 @@ describe('ExchangeWrapper', () => {
expect(filledValueT).to.be.bignumber.equal(partialFillAmount);
});
});
describe('#getCanceledTakerAmountAsync', () => {
describe('#getCancelledTakerAmountAsync', () => {
it('should throw if passed an invalid orderHash', async () => {
const invalidOrderHashHex = '0x123';
return expect(zeroEx.exchange.getCanceledTakerAmountAsync(invalidOrderHashHex)).to.be.rejected();
return expect(zeroEx.exchange.getCancelledTakerAmountAsync(invalidOrderHashHex)).to.be.rejected();
});
it('should return zero if passed a valid but non-existent orderHash', async () => {
const cancelledValueT = await zeroEx.exchange.getCanceledTakerAmountAsync(NON_EXISTENT_ORDER_HASH);
const cancelledValueT = await zeroEx.exchange.getCancelledTakerAmountAsync(NON_EXISTENT_ORDER_HASH);
expect(cancelledValueT).to.be.bignumber.equal(0);
});
it('should return the cancelledValueT for a valid and partially filled orderHash', async () => {
const cancelledValueT = await zeroEx.exchange.getCanceledTakerAmountAsync(orderHash);
const cancelledValueT = await zeroEx.exchange.getCancelledTakerAmountAsync(orderHash);
expect(cancelledValueT).to.be.bignumber.equal(0);
});
it('should return the cancelledValueT for a valid and cancelled orderHash', async () => {
const cancelAmount = fillableAmount.minus(partialFillAmount);
await zeroEx.exchange.cancelOrderAsync(signedOrder, cancelAmount);
const cancelledValueT = await zeroEx.exchange.getCanceledTakerAmountAsync(orderHash);
const cancelledValueT = await zeroEx.exchange.getCancelledTakerAmountAsync(orderHash);
expect(cancelledValueT).to.be.bignumber.equal(cancelAmount);
});
});
});
describe('#subscribeAsync', () => {
describe('#subscribe', () => {
const indexFilterValues = {};
const shouldThrowOnInsufficientBalanceOrAllowance = true;
let makerTokenAddress: string;
@@ -624,13 +627,9 @@ describe('ExchangeWrapper', () => {
let coinbase: string;
let takerAddress: string;
let makerAddress: string;
let fillableAmount: BigNumber.BigNumber;
let fillableAmount: BigNumber;
let signedOrder: SignedOrder;
const subscriptionOpts: SubscriptionOpts = {
fromBlock: 0,
toBlock: 'latest',
};
const fillTakerAmountInBaseUnits = new BigNumber(1);
const takerTokenFillAmountInBaseUnits = new BigNumber(1);
const cancelTakerAmountInBaseUnits = new BigNumber(1);
before(() => {
[coinbase, makerAddress, takerAddress] = userAddresses;
@@ -645,102 +644,84 @@ describe('ExchangeWrapper', () => {
);
});
afterEach(async () => {
await zeroEx.exchange.stopWatchingAllEventsAsync();
zeroEx.exchange.unsubscribeAll();
});
// Hack: Mocha does not allow a test to be both async and have a `done` callback
// Since we need to await the receipt of the event in the `subscribeAsync` callback,
// Since we need to await the receipt of the event in the `subscribe` callback,
// we do need both. A hack is to make the top-level a sync fn w/ a done callback and then
// wrap the rest of the test in an async block
// Source: https://github.com/mochajs/mocha/issues/2407
it('Should receive the LogFill event when an order is filled', (done: DoneCallback) => {
(async () => {
const zeroExEvent = await zeroEx.exchange.subscribeAsync(
ExchangeEvents.LogFill, subscriptionOpts, indexFilterValues, exchangeContractAddress,
);
zeroExEvent.watch((err: Error, event: ContractEvent) => {
expect(err).to.be.null();
expect(event).to.not.be.undefined();
expect(event.event).to.be.equal('LogFill');
const callback = (err: Error, logEvent: DecodedLogEvent<LogFillContractEventArgs>) => {
expect(logEvent.log.event).to.be.equal(ExchangeEvents.LogFill);
done();
});
};
zeroEx.exchange.subscribe(
ExchangeEvents.LogFill, indexFilterValues, callback,
);
await zeroEx.exchange.fillOrderAsync(
signedOrder, fillTakerAmountInBaseUnits, shouldThrowOnInsufficientBalanceOrAllowance, takerAddress,
signedOrder, takerTokenFillAmountInBaseUnits, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress,
);
})().catch(done);
});
it('Should receive the LogCancel event when an order is cancelled', (done: DoneCallback) => {
(async () => {
const zeroExEvent = await zeroEx.exchange.subscribeAsync(
ExchangeEvents.LogCancel, subscriptionOpts, indexFilterValues, exchangeContractAddress,
const callback = (err: Error, logEvent: DecodedLogEvent<LogCancelContractEventArgs>) => {
expect(logEvent.log.event).to.be.equal(ExchangeEvents.LogCancel);
done();
};
zeroEx.exchange.subscribe(
ExchangeEvents.LogCancel, indexFilterValues, callback,
);
zeroExEvent.watch((err: Error, event: ContractEvent) => {
expect(err).to.be.null();
expect(event).to.not.be.undefined();
expect(event.event).to.be.equal('LogCancel');
done();
});
await zeroEx.exchange.cancelOrderAsync(signedOrder, cancelTakerAmountInBaseUnits);
})().catch(done);
});
it('Outstanding subscriptions are cancelled when zeroEx.setProviderAsync called', (done: DoneCallback) => {
it('Outstanding subscriptions are cancelled when zeroEx.setProvider called', (done: DoneCallback) => {
(async () => {
const eventSubscriptionToBeCancelled = await zeroEx.exchange.subscribeAsync(
ExchangeEvents.LogFill, subscriptionOpts, indexFilterValues, exchangeContractAddress,
);
eventSubscriptionToBeCancelled.watch((err: Error, event: ContractEvent) => {
const callbackNeverToBeCalled = (err: Error, logEvent: DecodedLogEvent<LogFillContractEventArgs>) => {
done(new Error('Expected this subscription to have been cancelled'));
});
};
zeroEx.exchange.subscribe(
ExchangeEvents.LogFill, indexFilterValues, callbackNeverToBeCalled,
);
const newProvider = web3Factory.getRpcProvider();
await zeroEx.setProviderAsync(newProvider);
zeroEx.setProvider(newProvider, constants.TESTRPC_NETWORK_ID);
const eventSubscriptionToStay = await zeroEx.exchange.subscribeAsync(
ExchangeEvents.LogFill, subscriptionOpts, indexFilterValues, exchangeContractAddress,
);
eventSubscriptionToStay.watch((err: Error, event: ContractEvent) => {
expect(err).to.be.null();
expect(event).to.not.be.undefined();
expect(event.event).to.be.equal('LogFill');
const callback = (err: Error, logEvent: DecodedLogEvent<LogFillContractEventArgs>) => {
expect(logEvent.log.event).to.be.equal(ExchangeEvents.LogFill);
done();
});
};
zeroEx.exchange.subscribe(
ExchangeEvents.LogFill, indexFilterValues, callback,
);
await zeroEx.exchange.fillOrderAsync(
signedOrder, fillTakerAmountInBaseUnits, shouldThrowOnInsufficientBalanceOrAllowance, takerAddress,
signedOrder, takerTokenFillAmountInBaseUnits, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress,
);
})().catch(done);
});
it('Should stop watch for events when stopWatchingAsync called on the eventEmitter', (done: DoneCallback) => {
it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => {
(async () => {
const eventSubscriptionToBeStopped = await zeroEx.exchange.subscribeAsync(
ExchangeEvents.LogFill, subscriptionOpts, indexFilterValues, exchangeContractAddress,
const callbackNeverToBeCalled = (err: Error, logEvent: DecodedLogEvent<LogFillContractEventArgs>) => {
done(new Error('Expected this subscription to have been cancelled'));
};
const subscriptionToken = zeroEx.exchange.subscribe(
ExchangeEvents.LogFill, indexFilterValues, callbackNeverToBeCalled,
);
eventSubscriptionToBeStopped.watch((err: Error, event: ContractEvent) => {
done(new Error('Expected this subscription to have been stopped'));
});
await eventSubscriptionToBeStopped.stopWatchingAsync();
zeroEx.exchange.unsubscribe(subscriptionToken);
await zeroEx.exchange.fillOrderAsync(
signedOrder, fillTakerAmountInBaseUnits, shouldThrowOnInsufficientBalanceOrAllowance, takerAddress,
signedOrder, takerTokenFillAmountInBaseUnits, shouldThrowOnInsufficientBalanceOrAllowance,
takerAddress,
);
done();
})().catch(done);
});
it('Should wrap all event args BigNumber instances in a newer version of BigNumber', (done: DoneCallback) => {
(async () => {
const zeroExEvent = await zeroEx.exchange.subscribeAsync(
ExchangeEvents.LogFill, subscriptionOpts, indexFilterValues, exchangeContractAddress,
);
zeroExEvent.watch((err: Error, event: ContractEvent) => {
const args = event.args as LogFillContractEventArgs;
expect(args.filledMakerTokenAmount.isBigNumber).to.be.true();
expect(args.filledTakerTokenAmount.isBigNumber).to.be.true();
expect(args.paidMakerFee.isBigNumber).to.be.true();
expect(args.paidTakerFee.isBigNumber).to.be.true();
done();
});
await zeroEx.exchange.fillOrderAsync(
signedOrder, fillTakerAmountInBaseUnits, shouldThrowOnInsufficientBalanceOrAllowance, takerAddress,
);
})().catch(done);
});
});
describe('#getOrderHashHexUsingContractCallAsync', () => {
let makerTokenAddress: string;
@@ -765,8 +746,8 @@ describe('ExchangeWrapper', () => {
});
});
describe('#getZRXTokenAddressAsync', () => {
it('gets the same token as is in token registry', async () => {
const zrxAddress = await zeroEx.exchange.getZRXTokenAddressAsync();
it('gets the same token as is in token registry', () => {
const zrxAddress = zeroEx.exchange.getZRXTokenAddress();
const zrxToken = tokenUtils.getProtocolTokenOrThrow();
expect(zrxAddress).to.equal(zrxToken.address);
});
@@ -779,8 +760,8 @@ describe('ExchangeWrapper', () => {
const fillableAmount = new BigNumber(5);
const shouldThrowOnInsufficientBalanceOrAllowance = true;
const subscriptionOpts: SubscriptionOpts = {
fromBlock: 'earliest',
toBlock: 'latest',
fromBlock: 0,
toBlock: BlockParamLiteral.Latest,
};
let txHash: string;
before(async () => {
@@ -838,11 +819,12 @@ describe('ExchangeWrapper', () => {
const indexFilterValues = {
maker: differentMakerAddress,
};
const logs = await zeroEx.exchange.getLogsAsync(
const logs = await zeroEx.exchange.getLogsAsync<LogFillContractEventArgs>(
eventName, subscriptionOpts, indexFilterValues,
);
expect(logs).to.have.length(1);
expect(logs[0].args.maker).to.be.equal(differentMakerAddress);
const args = logs[0].args;
expect(args.maker).to.be.equal(differentMakerAddress);
});
});
});
}); // tslint:disable:max-file-line-count

View File

@@ -0,0 +1,144 @@
import BigNumber from 'bignumber.js';
import * as chai from 'chai';
import * as _ from 'lodash';
import 'mocha';
import * as Sinon from 'sinon';
import * as Web3 from 'web3';
import {ZeroEx} from '../src/0x';
import {ExpirationWatcher} from '../src/order_watcher/expiration_watcher';
import {DoneCallback, Token} from '../src/types';
import {constants} from '../src/utils/constants';
import {utils} from '../src/utils/utils';
import {Web3Wrapper} from '../src/web3_wrapper';
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
import {chaiSetup} from './utils/chai_setup';
import {FillScenarios} from './utils/fill_scenarios';
import {reportCallbackErrors} from './utils/report_callback_errors';
import {TokenUtils} from './utils/token_utils';
import {web3Factory} from './utils/web3_factory';
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle();
describe('ExpirationWatcher', () => {
let web3: Web3;
let zeroEx: ZeroEx;
let tokenUtils: TokenUtils;
let tokens: Token[];
let userAddresses: string[];
let zrxTokenAddress: string;
let fillScenarios: FillScenarios;
let exchangeContractAddress: string;
let makerTokenAddress: string;
let takerTokenAddress: string;
let coinbase: string;
let makerAddress: string;
let takerAddress: string;
let feeRecipient: string;
const fillableAmount = new BigNumber(5);
let currentUnixTimestampSec: BigNumber;
let timer: Sinon.SinonFakeTimers;
let expirationWatcher: ExpirationWatcher;
before(async () => {
web3 = web3Factory.create();
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
zeroEx = new ZeroEx(web3.currentProvider, config);
exchangeContractAddress = zeroEx.exchange.getContractAddress();
userAddresses = await zeroEx.getAvailableAddressesAsync();
tokens = await zeroEx.tokenRegistry.getTokensAsync();
tokenUtils = new TokenUtils(tokens);
zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address;
fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress);
[coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses;
tokens = await zeroEx.tokenRegistry.getTokensAsync();
const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens();
makerTokenAddress = makerToken.address;
takerTokenAddress = takerToken.address;
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
const sinonTimerConfig = {shouldAdvanceTime: true} as any;
// This constructor has incorrect types
timer = Sinon.useFakeTimers(sinonTimerConfig);
currentUnixTimestampSec = utils.getCurrentUnixTimestampSec();
expirationWatcher = new ExpirationWatcher();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
timer.restore();
expirationWatcher.unsubscribe();
});
it('correctly emits events when order expires', (done: DoneCallback) => {
(async () => {
const orderLifetimeSec = 60;
const expirationUnixTimestampSec = currentUnixTimestampSec.plus(orderLifetimeSec);
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
expirationUnixTimestampSec,
);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
expirationWatcher.addOrder(orderHash, signedOrder.expirationUnixTimestampSec.times(1000));
const callbackAsync = reportCallbackErrors(done)(async (hash: string) => {
expect(hash).to.be.equal(orderHash);
expect(utils.getCurrentUnixTimestampSec()).to.be.bignumber.gte(expirationUnixTimestampSec);
done();
});
expirationWatcher.subscribe(callbackAsync);
timer.tick(orderLifetimeSec * 1000);
})().catch(done);
});
it('doesn\'t emit events before order expires', (done: DoneCallback) => {
(async () => {
const orderLifetimeSec = 60;
const expirationUnixTimestampSec = currentUnixTimestampSec.plus(orderLifetimeSec);
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
expirationUnixTimestampSec,
);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
expirationWatcher.addOrder(orderHash, signedOrder.expirationUnixTimestampSec.times(1000));
const callbackAsync = reportCallbackErrors(done)(async (hash: string) => {
done(new Error('Emitted expiration went before the order actually expired'));
});
expirationWatcher.subscribe(callbackAsync);
const notEnoughTime = orderLifetimeSec - 1;
timer.tick(notEnoughTime * 1000);
done();
})().catch(done);
});
it('emits events in correct order', (done: DoneCallback) => {
(async () => {
const order1Lifetime = 60;
const order2Lifetime = 120;
const order1ExpirationUnixTimestampSec = currentUnixTimestampSec.plus(order1Lifetime);
const order2ExpirationUnixTimestampSec = currentUnixTimestampSec.plus(order2Lifetime);
const signedOrder1 = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
order1ExpirationUnixTimestampSec,
);
const signedOrder2 = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
order2ExpirationUnixTimestampSec,
);
const orderHash1 = ZeroEx.getOrderHashHex(signedOrder1);
const orderHash2 = ZeroEx.getOrderHashHex(signedOrder2);
expirationWatcher.addOrder(orderHash2, signedOrder2.expirationUnixTimestampSec.times(1000));
expirationWatcher.addOrder(orderHash1, signedOrder1.expirationUnixTimestampSec.times(1000));
const expirationOrder = [orderHash1, orderHash2];
const callbackAsync = reportCallbackErrors(done)(async (hash: string) => {
const orderHash = expirationOrder.shift();
expect(hash).to.be.equal(orderHash);
if (_.isEmpty(expirationOrder)) {
done();
}
});
expirationWatcher.subscribe(callbackAsync);
timer.tick(order2Lifetime * 1000);
})().catch(done);
});
});

View File

@@ -0,0 +1,488 @@
import BigNumber from 'bignumber.js';
import * as chai from 'chai';
import * as _ from 'lodash';
import 'mocha';
import * as Web3 from 'web3';
import {
DecodedLogEvent,
ExchangeContractErrs,
LogEvent,
OrderState,
OrderStateInvalid,
OrderStateValid,
SignedOrder,
Token,
ZeroEx,
ZeroExConfig,
ZeroExError,
} from '../src';
import {OrderStateWatcher} from '../src/order_watcher/order_state_watcher';
import {DoneCallback} from '../src/types';
import {Web3Wrapper} from '../src/web3_wrapper';
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
import {chaiSetup} from './utils/chai_setup';
import {constants} from './utils/constants';
import {FillScenarios} from './utils/fill_scenarios';
import {reportCallbackErrors} from './utils/report_callback_errors';
import {TokenUtils} from './utils/token_utils';
import {web3Factory} from './utils/web3_factory';
const TIMEOUT_MS = 150;
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle();
describe('OrderStateWatcher', () => {
let web3: Web3;
let zeroEx: ZeroEx;
let tokens: Token[];
let tokenUtils: TokenUtils;
let fillScenarios: FillScenarios;
let userAddresses: string[];
let zrxTokenAddress: string;
let exchangeContractAddress: string;
let makerToken: Token;
let takerToken: Token;
let maker: string;
let taker: string;
let web3Wrapper: Web3Wrapper;
let signedOrder: SignedOrder;
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
const decimals = constants.ZRX_DECIMALS;
const fillableAmount = ZeroEx.toBaseUnitAmount(new BigNumber(5), decimals);
before(async () => {
web3 = web3Factory.create();
zeroEx = new ZeroEx(web3.currentProvider, config);
exchangeContractAddress = zeroEx.exchange.getContractAddress();
userAddresses = await zeroEx.getAvailableAddressesAsync();
[, maker, taker] = userAddresses;
tokens = await zeroEx.tokenRegistry.getTokensAsync();
tokenUtils = new TokenUtils(tokens);
zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address;
fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress);
[makerToken, takerToken] = tokenUtils.getNonProtocolTokens();
web3Wrapper = (zeroEx as any)._web3Wrapper;
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('#removeOrder', async () => {
it('should successfully remove existing order', async () => {
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerToken.address, takerToken.address, maker, taker, fillableAmount,
);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
zeroEx.orderStateWatcher.addOrder(signedOrder);
expect((zeroEx.orderStateWatcher as any)._orderByOrderHash).to.include({
[orderHash]: signedOrder,
});
let dependentOrderHashes = (zeroEx.orderStateWatcher as any)._dependentOrderHashes;
expect(dependentOrderHashes[signedOrder.maker][signedOrder.makerTokenAddress]).to.have.keys(orderHash);
zeroEx.orderStateWatcher.removeOrder(orderHash);
expect((zeroEx.orderStateWatcher as any)._orderByOrderHash).to.not.include({
[orderHash]: signedOrder,
});
dependentOrderHashes = (zeroEx.orderStateWatcher as any)._dependentOrderHashes;
expect(dependentOrderHashes[signedOrder.maker]).to.be.undefined();
});
it('should no-op when removing a non-existing order', async () => {
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerToken.address, takerToken.address, maker, taker, fillableAmount,
);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
const nonExistentOrderHash = `0x${orderHash.substr(2).split('').reverse().join('')}`;
zeroEx.orderStateWatcher.removeOrder(nonExistentOrderHash);
});
});
describe('#subscribe', async () => {
afterEach(async () => {
zeroEx.orderStateWatcher.unsubscribe();
});
it('should fail when trying to subscribe twice', async () => {
zeroEx.orderStateWatcher.subscribe(_.noop);
expect(() => zeroEx.orderStateWatcher.subscribe(_.noop))
.to.throw(ZeroExError.SubscriptionAlreadyPresent);
});
});
describe('tests with cleanup', async () => {
afterEach(async () => {
zeroEx.orderStateWatcher.unsubscribe();
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
zeroEx.orderStateWatcher.removeOrder(orderHash);
});
it('should emit orderStateInvalid when maker allowance set to 0 for watched order', (done: DoneCallback) => {
(async () => {
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerToken.address, takerToken.address, maker, taker, fillableAmount,
);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
expect(orderState.isValid).to.be.false();
const invalidOrderState = orderState as OrderStateInvalid;
expect(invalidOrderState.orderHash).to.be.equal(orderHash);
expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerAllowance);
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
await zeroEx.token.setProxyAllowanceAsync(makerToken.address, maker, new BigNumber(0));
})().catch(done);
});
it('should not emit an orderState event when irrelevant Transfer event received', (done: DoneCallback) => {
(async () => {
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerToken.address, takerToken.address, maker, taker, fillableAmount,
);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
throw new Error('OrderState callback fired for irrelevant order');
});
zeroEx.orderStateWatcher.subscribe(callback);
const notTheMaker = userAddresses[0];
const anyRecipient = taker;
const transferAmount = new BigNumber(2);
const notTheMakerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, notTheMaker);
await zeroEx.token.transferAsync(makerToken.address, notTheMaker, anyRecipient, transferAmount);
setTimeout(() => {
done();
}, TIMEOUT_MS);
})().catch(done);
});
it('should emit orderStateInvalid when maker moves balance backing watched order', (done: DoneCallback) => {
(async () => {
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerToken.address, takerToken.address, maker, taker, fillableAmount,
);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
expect(orderState.isValid).to.be.false();
const invalidOrderState = orderState as OrderStateInvalid;
expect(invalidOrderState.orderHash).to.be.equal(orderHash);
expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerBalance);
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
const anyRecipient = taker;
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
await zeroEx.token.transferAsync(makerToken.address, maker, anyRecipient, makerBalance);
})().catch(done);
});
it('should emit orderStateInvalid when watched order fully filled', (done: DoneCallback) => {
(async () => {
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerToken.address, takerToken.address, maker, taker, fillableAmount,
);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
expect(orderState.isValid).to.be.false();
const invalidOrderState = orderState as OrderStateInvalid;
expect(invalidOrderState.orderHash).to.be.equal(orderHash);
expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.OrderRemainingFillAmountZero);
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
const shouldThrowOnInsufficientBalanceOrAllowance = true;
await zeroEx.exchange.fillOrderAsync(
signedOrder, fillableAmount, shouldThrowOnInsufficientBalanceOrAllowance, taker,
);
})().catch(done);
});
it('should emit orderStateValid when watched order partially filled', (done: DoneCallback) => {
(async () => {
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerToken.address, takerToken.address, maker, taker, fillableAmount,
);
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
const takerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, taker);
const fillAmountInBaseUnits = new BigNumber(2);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
expect(orderState.isValid).to.be.true();
const validOrderState = orderState as OrderStateValid;
expect(validOrderState.orderHash).to.be.equal(orderHash);
const orderRelevantState = validOrderState.orderRelevantState;
const remainingMakerBalance = makerBalance.sub(fillAmountInBaseUnits);
const remainingFillable = fillableAmount.minus(fillAmountInBaseUnits);
expect(orderRelevantState.remainingFillableMakerTokenAmount).to.be.bignumber.equal(
remainingFillable);
expect(orderRelevantState.remainingFillableTakerTokenAmount).to.be.bignumber.equal(
remainingFillable);
expect(orderRelevantState.makerBalance).to.be.bignumber.equal(remainingMakerBalance);
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
const shouldThrowOnInsufficientBalanceOrAllowance = true;
await zeroEx.exchange.fillOrderAsync(
signedOrder, fillAmountInBaseUnits, shouldThrowOnInsufficientBalanceOrAllowance, taker,
);
})().catch(done);
});
it('should trigger the callback when orders backing ZRX allowance changes', (done: DoneCallback) => {
(async () => {
const makerFee = ZeroEx.toBaseUnitAmount(new BigNumber(2), 18);
const takerFee = ZeroEx.toBaseUnitAmount(new BigNumber(0), 18);
signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
makerToken.address, takerToken.address, makerFee, takerFee, maker, taker, fillableAmount,
taker);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
await zeroEx.token.setProxyAllowanceAsync(zrxTokenAddress, maker, new BigNumber(0));
})().catch(done);
});
describe('remainingFillable(M|T)akerTokenAmount', () => {
it('should calculate correct remaining fillable', (done: DoneCallback) => {
(async () => {
const takerFillableAmount = ZeroEx.toBaseUnitAmount(new BigNumber(10), decimals);
const makerFillableAmount = ZeroEx.toBaseUnitAmount(new BigNumber(20), decimals);
signedOrder = await fillScenarios.createAsymmetricFillableSignedOrderAsync(
makerToken.address, takerToken.address, maker, taker, makerFillableAmount,
takerFillableAmount,
);
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
const takerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, taker);
const fillAmountInBaseUnits = ZeroEx.toBaseUnitAmount(new BigNumber(2), decimals);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
expect(orderState.isValid).to.be.true();
const validOrderState = orderState as OrderStateValid;
expect(validOrderState.orderHash).to.be.equal(orderHash);
const orderRelevantState = validOrderState.orderRelevantState;
expect(orderRelevantState.remainingFillableMakerTokenAmount).to.be.bignumber.equal(
ZeroEx.toBaseUnitAmount(new BigNumber(16), decimals));
expect(orderRelevantState.remainingFillableTakerTokenAmount).to.be.bignumber.equal(
ZeroEx.toBaseUnitAmount(new BigNumber(8), decimals));
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
const shouldThrowOnInsufficientBalanceOrAllowance = true;
await zeroEx.exchange.fillOrderAsync(
signedOrder, fillAmountInBaseUnits, shouldThrowOnInsufficientBalanceOrAllowance, taker,
);
})().catch(done);
});
it('should equal approved amount when approved amount is lowest', (done: DoneCallback) => {
(async () => {
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerToken.address, takerToken.address, maker, taker, fillableAmount,
);
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
const changedMakerApprovalAmount = ZeroEx.toBaseUnitAmount(new BigNumber(3), decimals);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
const validOrderState = orderState as OrderStateValid;
const orderRelevantState = validOrderState.orderRelevantState;
expect(orderRelevantState.remainingFillableMakerTokenAmount).to.be.bignumber.equal(
changedMakerApprovalAmount);
expect(orderRelevantState.remainingFillableTakerTokenAmount).to.be.bignumber.equal(
changedMakerApprovalAmount);
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
await zeroEx.token.setProxyAllowanceAsync(makerToken.address, maker, changedMakerApprovalAmount);
})().catch(done);
});
it('should equal balance amount when balance amount is lowest', (done: DoneCallback) => {
(async () => {
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerToken.address, takerToken.address, maker, taker, fillableAmount,
);
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
const remainingAmount = ZeroEx.toBaseUnitAmount(new BigNumber(1), decimals);
const transferAmount = makerBalance.sub(remainingAmount);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
expect(orderState.isValid).to.be.true();
const validOrderState = orderState as OrderStateValid;
const orderRelevantState = validOrderState.orderRelevantState;
expect(orderRelevantState.remainingFillableMakerTokenAmount).to.be.bignumber.equal(
remainingAmount);
expect(orderRelevantState.remainingFillableTakerTokenAmount).to.be.bignumber.equal(
remainingAmount);
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
await zeroEx.token.transferAsync(
makerToken.address, maker, ZeroEx.NULL_ADDRESS, transferAmount);
})().catch(done);
});
it('should equal remaining amount when partially cancelled and order has fees', (done: DoneCallback) => {
(async () => {
const takerFee = ZeroEx.toBaseUnitAmount(new BigNumber(0), decimals);
const makerFee = ZeroEx.toBaseUnitAmount(new BigNumber(5), decimals);
const feeRecipient = taker;
signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
makerToken.address, takerToken.address, makerFee, takerFee, maker,
taker, fillableAmount, feeRecipient);
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
const remainingTokenAmount = ZeroEx.toBaseUnitAmount(new BigNumber(4), decimals);
const transferTokenAmount = makerFee.sub(remainingTokenAmount);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
expect(orderState.isValid).to.be.true();
const validOrderState = orderState as OrderStateValid;
const orderRelevantState = validOrderState.orderRelevantState;
expect(orderRelevantState.remainingFillableMakerTokenAmount).to.be.bignumber.equal(
remainingTokenAmount);
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
await zeroEx.exchange.cancelOrderAsync(signedOrder, transferTokenAmount);
})().catch(done);
});
it('should equal ratio amount when fee balance is lowered', (done: DoneCallback) => {
(async () => {
const takerFee = ZeroEx.toBaseUnitAmount(new BigNumber(0), decimals);
const makerFee = ZeroEx.toBaseUnitAmount(new BigNumber(5), decimals);
const feeRecipient = taker;
signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
makerToken.address, takerToken.address, makerFee, takerFee, maker,
taker, fillableAmount, feeRecipient);
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
const remainingFeeAmount = ZeroEx.toBaseUnitAmount(new BigNumber(3), decimals);
const transferFeeAmount = makerFee.sub(remainingFeeAmount);
const remainingTokenAmount = ZeroEx.toBaseUnitAmount(new BigNumber(4), decimals);
const transferTokenAmount = makerFee.sub(remainingTokenAmount);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
const validOrderState = orderState as OrderStateValid;
const orderRelevantState = validOrderState.orderRelevantState;
expect(orderRelevantState.remainingFillableMakerTokenAmount).to.be.bignumber.equal(
remainingFeeAmount);
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
await zeroEx.token.setProxyAllowanceAsync(zrxTokenAddress, maker, remainingFeeAmount);
await zeroEx.token.transferAsync(
makerToken.address, maker, ZeroEx.NULL_ADDRESS, transferTokenAmount);
})().catch(done);
});
it('should calculate full amount when all available and non-divisible', (done: DoneCallback) => {
(async () => {
const takerFee = ZeroEx.toBaseUnitAmount(new BigNumber(0), decimals);
const makerFee = ZeroEx.toBaseUnitAmount(new BigNumber(2), decimals);
const feeRecipient = taker;
signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
makerToken.address, takerToken.address, makerFee, takerFee, maker,
taker, fillableAmount, feeRecipient);
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
const validOrderState = orderState as OrderStateValid;
const orderRelevantState = validOrderState.orderRelevantState;
expect(orderRelevantState.remainingFillableMakerTokenAmount).to.be.bignumber.equal(
fillableAmount);
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
await zeroEx.token.setProxyAllowanceAsync(
makerToken.address, maker, ZeroEx.toBaseUnitAmount(new BigNumber(100), decimals));
})().catch(done);
});
});
it('should emit orderStateInvalid when watched order cancelled', (done: DoneCallback) => {
(async () => {
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerToken.address, takerToken.address, maker, taker, fillableAmount,
);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
expect(orderState.isValid).to.be.false();
const invalidOrderState = orderState as OrderStateInvalid;
expect(invalidOrderState.orderHash).to.be.equal(orderHash);
expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.OrderRemainingFillAmountZero);
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
const shouldThrowOnInsufficientBalanceOrAllowance = true;
await zeroEx.exchange.cancelOrderAsync(signedOrder, fillableAmount);
})().catch(done);
});
it('should emit orderStateInvalid when within rounding error range', (done: DoneCallback) => {
(async () => {
const remainingFillableAmountInBaseUnits = new BigNumber(100);
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerToken.address, takerToken.address, maker, taker, fillableAmount,
);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
expect(orderState.isValid).to.be.false();
const invalidOrderState = orderState as OrderStateInvalid;
expect(invalidOrderState.orderHash).to.be.equal(orderHash);
expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.OrderFillRoundingError);
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
await zeroEx.exchange.cancelOrderAsync(
signedOrder, fillableAmount.minus(remainingFillableAmountInBaseUnits),
);
})().catch(done);
});
it('should emit orderStateValid when watched order partially cancelled', (done: DoneCallback) => {
(async () => {
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerToken.address, takerToken.address, maker, taker, fillableAmount,
);
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
const takerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, taker);
const cancelAmountInBaseUnits = new BigNumber(2);
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
zeroEx.orderStateWatcher.addOrder(signedOrder);
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
expect(orderState.isValid).to.be.true();
const validOrderState = orderState as OrderStateValid;
expect(validOrderState.orderHash).to.be.equal(orderHash);
const orderRelevantState = validOrderState.orderRelevantState;
expect(orderRelevantState.cancelledTakerTokenAmount).to.be.bignumber.equal(cancelAmountInBaseUnits);
done();
});
zeroEx.orderStateWatcher.subscribe(callback);
await zeroEx.exchange.cancelOrderAsync(signedOrder, cancelAmountInBaseUnits);
})().catch(done);
});
});
}); // tslint:disable:max-file-line-count

View File

@@ -0,0 +1,333 @@
import BigNumber from 'bignumber.js';
import * as chai from 'chai';
import * as Sinon from 'sinon';
import * as Web3 from 'web3';
import {ExchangeContractErrs, SignedOrder, Token, ZeroEx, ZeroExError} from '../src';
import {BlockParamLiteral, TradeSide, TransferType} from '../src/types';
import {ExchangeTransferSimulator} from '../src/utils/exchange_transfer_simulator';
import {OrderValidationUtils} from '../src/utils/order_validation_utils';
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
import {chaiSetup} from './utils/chai_setup';
import {constants} from './utils/constants';
import {FillScenarios} from './utils/fill_scenarios';
import {TokenUtils} from './utils/token_utils';
import {web3Factory} from './utils/web3_factory';
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle();
describe('OrderValidation', () => {
let web3: Web3;
let zeroEx: ZeroEx;
let userAddresses: string[];
let tokens: Token[];
let tokenUtils: TokenUtils;
let exchangeContractAddress: string;
let zrxTokenAddress: string;
let fillScenarios: FillScenarios;
let makerTokenAddress: string;
let takerTokenAddress: string;
let coinbase: string;
let makerAddress: string;
let takerAddress: string;
let feeRecipient: string;
let orderValidationUtils: OrderValidationUtils;
const fillableAmount = new BigNumber(5);
const fillTakerAmount = new BigNumber(5);
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
before(async () => {
web3 = web3Factory.create();
zeroEx = new ZeroEx(web3.currentProvider, config);
exchangeContractAddress = zeroEx.exchange.getContractAddress();
userAddresses = await zeroEx.getAvailableAddressesAsync();
[coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses;
tokens = await zeroEx.tokenRegistry.getTokensAsync();
tokenUtils = new TokenUtils(tokens);
zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address;
fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress);
const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens();
makerTokenAddress = makerToken.address;
takerTokenAddress = takerToken.address;
orderValidationUtils = new OrderValidationUtils(zeroEx.token, zeroEx.exchange);
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('validateOrderFillableOrThrowAsync', () => {
it('should succeed if the order is fillable', async () => {
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
);
await zeroEx.exchange.validateOrderFillableOrThrowAsync(
signedOrder,
);
});
it('should succeed if the order is asymmetric and fillable', async () => {
const makerFillableAmount = fillableAmount;
const takerFillableAmount = fillableAmount.minus(4);
const signedOrder = await fillScenarios.createAsymmetricFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress,
makerFillableAmount, takerFillableAmount,
);
await zeroEx.exchange.validateOrderFillableOrThrowAsync(
signedOrder,
);
});
it('should throw when the order is fully filled or cancelled', async () => {
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
);
await zeroEx.exchange.cancelOrderAsync(signedOrder, fillableAmount);
return expect(zeroEx.exchange.validateOrderFillableOrThrowAsync(
signedOrder,
)).to.be.rejectedWith(ExchangeContractErrs.OrderRemainingFillAmountZero);
});
it('should throw when order is expired', async () => {
const expirationInPast = new BigNumber(1496826058); // 7th Jun 2017
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress,
fillableAmount, expirationInPast,
);
return expect(zeroEx.exchange.validateOrderFillableOrThrowAsync(
signedOrder,
)).to.be.rejectedWith(ExchangeContractErrs.OrderFillExpired);
});
});
describe('validateFillOrderAndThrowIfInvalidAsync', () => {
it('should throw when the fill amount is zero', async () => {
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
);
const zeroFillAmount = new BigNumber(0);
return expect(zeroEx.exchange.validateFillOrderThrowIfInvalidAsync(
signedOrder, zeroFillAmount, takerAddress,
)).to.be.rejectedWith(ExchangeContractErrs.OrderFillAmountZero);
});
it('should throw when the signature is invalid', async () => {
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
);
// 27 <--> 28
signedOrder.ecSignature.v = (28 - signedOrder.ecSignature.v) + 27;
return expect(zeroEx.exchange.validateFillOrderThrowIfInvalidAsync(
signedOrder, fillableAmount, takerAddress,
)).to.be.rejectedWith(ZeroExError.InvalidSignature);
});
it('should throw when the order is fully filled or cancelled', async () => {
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
);
await zeroEx.exchange.cancelOrderAsync(signedOrder, fillableAmount);
return expect(zeroEx.exchange.validateFillOrderThrowIfInvalidAsync(
signedOrder, fillableAmount, takerAddress,
)).to.be.rejectedWith(ExchangeContractErrs.OrderRemainingFillAmountZero);
});
it('should throw when sender is not a taker', async () => {
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
);
const nonTakerAddress = userAddresses[6];
return expect(zeroEx.exchange.validateFillOrderThrowIfInvalidAsync(
signedOrder, fillTakerAmount, nonTakerAddress,
)).to.be.rejectedWith(ExchangeContractErrs.TransactionSenderIsNotFillOrderTaker);
});
it('should throw when order is expired', async () => {
const expirationInPast = new BigNumber(1496826058); // 7th Jun 2017
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress,
fillableAmount, expirationInPast,
);
return expect(zeroEx.exchange.validateFillOrderThrowIfInvalidAsync(
signedOrder, fillTakerAmount, takerAddress,
)).to.be.rejectedWith(ExchangeContractErrs.OrderFillExpired);
});
it('should throw when there a rounding error would have occurred', async () => {
const makerAmount = new BigNumber(3);
const takerAmount = new BigNumber(5);
const signedOrder = await fillScenarios.createAsymmetricFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress,
makerAmount, takerAmount,
);
const fillTakerAmountThatCausesRoundingError = new BigNumber(3);
return expect(zeroEx.exchange.validateFillOrderThrowIfInvalidAsync(
signedOrder, fillTakerAmountThatCausesRoundingError, takerAddress,
)).to.be.rejectedWith(ExchangeContractErrs.OrderFillRoundingError);
});
});
describe('#validateFillOrKillOrderAndThrowIfInvalidAsync', () => {
it('should throw if remaining fillAmount is less then the desired fillAmount', async () => {
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
);
const tooLargeFillAmount = new BigNumber(7);
const fillAmountDifference = tooLargeFillAmount.minus(fillableAmount);
await zeroEx.token.transferAsync(takerTokenAddress, coinbase, takerAddress, fillAmountDifference);
await zeroEx.token.setProxyAllowanceAsync(takerTokenAddress, takerAddress, tooLargeFillAmount);
await zeroEx.token.transferAsync(makerTokenAddress, coinbase, makerAddress, fillAmountDifference);
await zeroEx.token.setProxyAllowanceAsync(makerTokenAddress, makerAddress, tooLargeFillAmount);
return expect(zeroEx.exchange.validateFillOrKillOrderThrowIfInvalidAsync(
signedOrder, tooLargeFillAmount, takerAddress,
)).to.be.rejectedWith(ExchangeContractErrs.InsufficientRemainingFillAmount);
});
});
describe('validateCancelOrderAndThrowIfInvalidAsync', () => {
let signedOrder: SignedOrder;
let orderHashHex: string;
const cancelAmount = new BigNumber(3);
beforeEach(async () => {
[coinbase, makerAddress, takerAddress] = userAddresses;
const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens();
makerTokenAddress = makerToken.address;
takerTokenAddress = takerToken.address;
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
);
orderHashHex = ZeroEx.getOrderHashHex(signedOrder);
});
it('should throw when cancel amount is zero', async () => {
const zeroCancelAmount = new BigNumber(0);
return expect(zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync(signedOrder, zeroCancelAmount))
.to.be.rejectedWith(ExchangeContractErrs.OrderCancelAmountZero);
});
it('should throw when order is expired', async () => {
const expirationInPast = new BigNumber(1496826058); // 7th Jun 2017
const expiredSignedOrder = await fillScenarios.createFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress,
fillableAmount, expirationInPast,
);
orderHashHex = ZeroEx.getOrderHashHex(expiredSignedOrder);
return expect(zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync(expiredSignedOrder, cancelAmount))
.to.be.rejectedWith(ExchangeContractErrs.OrderCancelExpired);
});
it('should throw when order is already cancelled or filled', async () => {
await zeroEx.exchange.cancelOrderAsync(signedOrder, fillableAmount);
return expect(zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync(signedOrder, fillableAmount))
.to.be.rejectedWith(ExchangeContractErrs.OrderAlreadyCancelledOrFilled);
});
});
describe('#validateFillOrderBalancesAllowancesThrowIfInvalidAsync', () => {
let exchangeTransferSimulator: ExchangeTransferSimulator;
let transferFromAsync: Sinon.SinonSpy;
const bigNumberMatch = (expected: BigNumber) => {
return Sinon.match((value: BigNumber) => value.eq(expected));
};
beforeEach('create exchangeTransferSimulator', async () => {
exchangeTransferSimulator = new ExchangeTransferSimulator(zeroEx.token, BlockParamLiteral.Latest);
transferFromAsync = Sinon.spy();
exchangeTransferSimulator.transferFromAsync = transferFromAsync as any;
});
it('should call exchangeTransferSimulator.transferFrom in a correct order', async () => {
const makerFee = new BigNumber(2);
const takerFee = new BigNumber(2);
const signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
makerTokenAddress, takerTokenAddress, makerFee, takerFee,
makerAddress, takerAddress, fillableAmount, feeRecipient,
);
await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
exchangeTransferSimulator, signedOrder, fillableAmount, takerAddress, zrxTokenAddress,
);
expect(transferFromAsync.callCount).to.be.equal(4);
expect(
transferFromAsync.getCall(0).calledWith(
makerTokenAddress, makerAddress, takerAddress, bigNumberMatch(fillableAmount),
TradeSide.Maker, TransferType.Trade,
),
).to.be.true();
expect(
transferFromAsync.getCall(1).calledWith(
takerTokenAddress, takerAddress, makerAddress, bigNumberMatch(fillableAmount),
TradeSide.Taker, TransferType.Trade,
),
).to.be.true();
expect(
transferFromAsync.getCall(2).calledWith(
zrxTokenAddress, makerAddress, feeRecipient, bigNumberMatch(makerFee),
TradeSide.Maker, TransferType.Fee,
),
).to.be.true();
expect(
transferFromAsync.getCall(3).calledWith(
zrxTokenAddress, takerAddress, feeRecipient, bigNumberMatch(takerFee),
TradeSide.Taker, TransferType.Fee,
),
).to.be.true();
});
it('should call exchangeTransferSimulator.transferFrom with correct values for an open order', async () => {
const makerFee = new BigNumber(2);
const takerFee = new BigNumber(2);
const signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
makerTokenAddress, takerTokenAddress, makerFee, takerFee,
makerAddress, ZeroEx.NULL_ADDRESS, fillableAmount, feeRecipient,
);
await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
exchangeTransferSimulator, signedOrder, fillableAmount, takerAddress, zrxTokenAddress,
);
expect(transferFromAsync.callCount).to.be.equal(4);
expect(
transferFromAsync.getCall(0).calledWith(
makerTokenAddress, makerAddress, takerAddress, bigNumberMatch(fillableAmount),
TradeSide.Maker, TransferType.Trade,
),
).to.be.true();
expect(
transferFromAsync.getCall(1).calledWith(
takerTokenAddress, takerAddress, makerAddress, bigNumberMatch(fillableAmount),
TradeSide.Taker, TransferType.Trade,
),
).to.be.true();
expect(
transferFromAsync.getCall(2).calledWith(
zrxTokenAddress, makerAddress, feeRecipient, bigNumberMatch(makerFee),
TradeSide.Maker, TransferType.Fee,
),
).to.be.true();
expect(
transferFromAsync.getCall(3).calledWith(
zrxTokenAddress, takerAddress, feeRecipient, bigNumberMatch(takerFee),
TradeSide.Taker, TransferType.Fee,
),
).to.be.true();
});
it('should correctly round the fillMakerTokenAmount', async () => {
const makerTokenAmount = new BigNumber(3);
const takerTokenAmount = new BigNumber(1);
const signedOrder = await fillScenarios.createAsymmetricFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, makerTokenAmount, takerTokenAmount,
);
await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
exchangeTransferSimulator, signedOrder, takerTokenAmount, takerAddress, zrxTokenAddress,
);
expect(transferFromAsync.callCount).to.be.equal(4);
const makerFillAmount = transferFromAsync.getCall(0).args[3];
expect(makerFillAmount).to.be.bignumber.equal(makerTokenAmount);
});
it('should correctly round the makerFeeAmount', async () => {
const makerFee = new BigNumber(2);
const takerFee = new BigNumber(4);
const signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
makerTokenAddress, takerTokenAddress, makerFee, takerFee, makerAddress, takerAddress,
fillableAmount, ZeroEx.NULL_ADDRESS,
);
const fillTakerTokenAmount = fillableAmount.div(2).round(0);
await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
exchangeTransferSimulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress,
);
const makerPartialFee = makerFee.div(2);
const takerPartialFee = takerFee.div(2);
expect(transferFromAsync.callCount).to.be.equal(4);
const partialMakerFee = transferFromAsync.getCall(2).args[3];
expect(partialMakerFee).to.be.bignumber.equal(makerPartialFee);
const partialTakerFee = transferFromAsync.getCall(3).args[3];
expect(partialTakerFee).to.be.bignumber.equal(takerPartialFee);
});
});
});

View File

@@ -0,0 +1,178 @@
import BigNumber from 'bignumber.js';
import * as chai from 'chai';
import 'mocha';
import { ZeroEx } from '../src/0x';
import { RemainingFillableCalculator } from '../src/order_watcher/remaining_fillable_calculator';
import { ECSignature, SignedOrder } from '../src/types';
import { chaiSetup } from './utils/chai_setup';
import { TokenUtils } from './utils/token_utils';
chaiSetup.configure();
const expect = chai.expect;
describe('RemainingFillableCalculator', () => {
let calculator: RemainingFillableCalculator;
let signedOrder: SignedOrder;
let transferrableMakerTokenAmount: BigNumber;
let transferrableMakerFeeTokenAmount: BigNumber;
let remainingMakerTokenAmount: BigNumber;
let makerAmount: BigNumber;
let takerAmount: BigNumber;
let makerFeeAmount: BigNumber;
let isMakerTokenZRX: boolean;
const makerToken: string = '0x1';
const takerToken: string = '0x2';
const decimals: number = 4;
const zero: BigNumber = new BigNumber(0);
const zeroAddress = '0x0';
const signature: ECSignature = { v: 27, r: '', s: ''};
beforeEach(async () => {
[makerAmount, takerAmount, makerFeeAmount] = [ZeroEx.toBaseUnitAmount(new BigNumber(50), decimals),
ZeroEx.toBaseUnitAmount(new BigNumber(5), decimals),
ZeroEx.toBaseUnitAmount(new BigNumber(1), decimals)];
[transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount] = [
ZeroEx.toBaseUnitAmount(new BigNumber(50), decimals),
ZeroEx.toBaseUnitAmount(new BigNumber(5), decimals)];
});
function buildSignedOrder(): SignedOrder {
return { ecSignature: signature,
exchangeContractAddress: zeroAddress,
feeRecipient: zeroAddress,
maker: zeroAddress,
taker: zeroAddress,
makerFee: makerFeeAmount,
takerFee: zero,
makerTokenAmount: makerAmount,
takerTokenAmount: takerAmount,
makerTokenAddress: makerToken,
takerTokenAddress: takerToken,
salt: zero,
expirationUnixTimestampSec: zero };
}
describe('Maker token is NOT ZRX', () => {
before(async () => {
isMakerTokenZRX = false;
});
it('calculates the correct amount when unfilled and funds available', () => {
signedOrder = buildSignedOrder();
remainingMakerTokenAmount = signedOrder.makerTokenAmount;
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(remainingMakerTokenAmount);
});
it('calculates the correct amount when partially filled and funds available', () => {
signedOrder = buildSignedOrder();
remainingMakerTokenAmount = ZeroEx.toBaseUnitAmount(new BigNumber(1), decimals);
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(remainingMakerTokenAmount);
});
it('calculates the amount to be 0 when all fee funds are transferred', () => {
signedOrder = buildSignedOrder();
transferrableMakerFeeTokenAmount = zero;
remainingMakerTokenAmount = signedOrder.makerTokenAmount;
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(zero);
});
it('calculates the correct amount when balance is less than remaining fillable', () => {
signedOrder = buildSignedOrder();
const partiallyFilledAmount = ZeroEx.toBaseUnitAmount(new BigNumber(2), decimals);
remainingMakerTokenAmount = signedOrder.makerTokenAmount.minus(partiallyFilledAmount);
transferrableMakerTokenAmount = remainingMakerTokenAmount.minus(partiallyFilledAmount);
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(transferrableMakerTokenAmount);
});
describe('Order to Fee Ratio is < 1', () => {
beforeEach(async () => {
[makerAmount, takerAmount, makerFeeAmount] = [ZeroEx.toBaseUnitAmount(new BigNumber(3), decimals),
ZeroEx.toBaseUnitAmount(new BigNumber(6), decimals),
ZeroEx.toBaseUnitAmount(new BigNumber(6), decimals)];
});
it('calculates the correct amount when funds unavailable', () => {
signedOrder = buildSignedOrder();
remainingMakerTokenAmount = signedOrder.makerTokenAmount;
const transferredAmount = ZeroEx.toBaseUnitAmount(new BigNumber(2), decimals);
transferrableMakerTokenAmount = remainingMakerTokenAmount.minus(transferredAmount);
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount,
remainingMakerTokenAmount);
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(transferrableMakerTokenAmount);
});
});
describe('Ratio is not evenly divisble', () => {
beforeEach(async () => {
[makerAmount, takerAmount, makerFeeAmount] = [ZeroEx.toBaseUnitAmount(new BigNumber(3), decimals),
ZeroEx.toBaseUnitAmount(new BigNumber(7), decimals),
ZeroEx.toBaseUnitAmount(new BigNumber(7), decimals)];
});
it('calculates the correct amount when funds unavailable', () => {
signedOrder = buildSignedOrder();
remainingMakerTokenAmount = signedOrder.makerTokenAmount;
const transferredAmount = ZeroEx.toBaseUnitAmount(new BigNumber(2), decimals);
transferrableMakerTokenAmount = remainingMakerTokenAmount.minus(transferredAmount);
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount,
remainingMakerTokenAmount);
const calculatedFillableAmount = calculator.computeRemainingMakerFillable();
expect(calculatedFillableAmount.lessThanOrEqualTo(transferrableMakerTokenAmount)).to.be.true();
expect(calculatedFillableAmount).to.be.bignumber.greaterThan(new BigNumber(0));
const orderToFeeRatio = signedOrder.makerTokenAmount.dividedBy(signedOrder.makerFee);
const calculatedFeeAmount = calculatedFillableAmount.dividedBy(orderToFeeRatio);
expect(calculatedFeeAmount).to.be.bignumber.lessThan(transferrableMakerFeeTokenAmount);
});
});
});
describe('Maker Token is ZRX', () => {
before(async () => {
isMakerTokenZRX = true;
});
it('calculates the correct amount when unfilled and funds available', () => {
signedOrder = buildSignedOrder();
transferrableMakerTokenAmount = makerAmount.plus(makerFeeAmount);
transferrableMakerFeeTokenAmount = transferrableMakerTokenAmount;
remainingMakerTokenAmount = signedOrder.makerTokenAmount;
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(remainingMakerTokenAmount);
});
it('calculates the correct amount when partially filled and funds available', () => {
signedOrder = buildSignedOrder();
remainingMakerTokenAmount = ZeroEx.toBaseUnitAmount(new BigNumber(1), decimals);
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(remainingMakerTokenAmount);
});
it('calculates the amount to be 0 when all fee funds are transferred', () => {
signedOrder = buildSignedOrder();
transferrableMakerTokenAmount = zero;
transferrableMakerFeeTokenAmount = zero;
remainingMakerTokenAmount = signedOrder.makerTokenAmount;
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(zero);
});
it('calculates the correct amount when balance is less than remaining fillable', () => {
signedOrder = buildSignedOrder();
const partiallyFilledAmount = ZeroEx.toBaseUnitAmount(new BigNumber(2), decimals);
remainingMakerTokenAmount = signedOrder.makerTokenAmount.minus(partiallyFilledAmount);
transferrableMakerTokenAmount = remainingMakerTokenAmount.minus(partiallyFilledAmount);
transferrableMakerFeeTokenAmount = transferrableMakerTokenAmount;
const orderToFeeRatio = signedOrder.makerTokenAmount.dividedToIntegerBy(signedOrder.makerFee);
const expectedFillableAmount = new BigNumber(450980);
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
const calculatedFillableAmount = calculator.computeRemainingMakerFillable();
const numberOfFillsInRatio = calculatedFillableAmount.dividedToIntegerBy(orderToFeeRatio);
const calculatedFillableAmountPlusFees = calculatedFillableAmount.plus(numberOfFillsInRatio);
expect(calculatedFillableAmountPlusFees).to.be.bignumber.lessThan(transferrableMakerTokenAmount);
expect(calculatedFillableAmountPlusFees).to.be.bignumber.lessThan(remainingMakerTokenAmount);
expect(calculatedFillableAmount).to.be.bignumber.equal(expectedFillableAmount);
expect(numberOfFillsInRatio.decimalPlaces()).to.be.equal(0);
});
});
});

View File

@@ -0,0 +1,124 @@
import BigNumber from 'bignumber.js';
import * as chai from 'chai';
import promisify = require('es6-promisify');
import * as _ from 'lodash';
import 'mocha';
import * as Sinon from 'sinon';
import * as Web3 from 'web3';
import {
ApprovalContractEventArgs,
DecodedLogEvent,
Token,
TokenEvents,
ZeroEx,
ZeroExError,
} from '../src';
import {BlockParamLiteral, DoneCallback} from '../src/types';
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
import {chaiSetup} from './utils/chai_setup';
import {constants} from './utils/constants';
import {reportCallbackErrors} from './utils/report_callback_errors';
import {TokenUtils} from './utils/token_utils';
import {web3Factory} from './utils/web3_factory';
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle();
describe('SubscriptionTest', () => {
let web3: Web3;
let zeroEx: ZeroEx;
let userAddresses: string[];
let tokens: Token[];
let tokenUtils: TokenUtils;
let coinbase: string;
let addressWithoutFunds: string;
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
before(async () => {
web3 = web3Factory.create();
zeroEx = new ZeroEx(web3.currentProvider, config);
userAddresses = await zeroEx.getAvailableAddressesAsync();
tokens = await zeroEx.tokenRegistry.getTokensAsync();
tokenUtils = new TokenUtils(tokens);
coinbase = userAddresses[0];
addressWithoutFunds = userAddresses[1];
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('#subscribe', () => {
const indexFilterValues = {};
const shouldThrowOnInsufficientBalanceOrAllowance = true;
let tokenAddress: string;
const transferAmount = new BigNumber(42);
const allowanceAmount = new BigNumber(42);
let stubs: Sinon.SinonStub[] = [];
before(() => {
const token = tokens[0];
tokenAddress = token.address;
});
afterEach(() => {
zeroEx.token.unsubscribeAll();
_.each(stubs, s => s.restore());
stubs = [];
});
it('Should receive the Error when an error occurs while fetching the block', (done: DoneCallback) => {
(async () => {
const errMsg = 'Error fetching block';
const callback = reportCallbackErrors(done)(
(err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
expect(err.message).to.be.equal(errMsg);
expect(logEvent).to.be.undefined();
done();
},
);
stubs = [
Sinon.stub((zeroEx as any)._web3Wrapper, 'getBlockAsync')
.throws(new Error(errMsg)),
];
zeroEx.token.subscribe(
tokenAddress, TokenEvents.Approval, indexFilterValues, callback);
await zeroEx.token.setAllowanceAsync(tokenAddress, coinbase, addressWithoutFunds, allowanceAmount);
})().catch(done);
});
it('Should receive the Error when an error occurs while reconciling the new block', (done: DoneCallback) => {
(async () => {
const errMsg = 'Error fetching logs';
const callback = reportCallbackErrors(done)(
(err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
expect(err.message).to.be.equal(errMsg);
expect(logEvent).to.be.undefined();
done();
},
);
stubs = [
Sinon.stub((zeroEx as any)._web3Wrapper, 'getLogsAsync')
.throws(new Error(errMsg)),
];
zeroEx.token.subscribe(
tokenAddress, TokenEvents.Approval, indexFilterValues, callback);
await zeroEx.token.setAllowanceAsync(tokenAddress, coinbase, addressWithoutFunds, allowanceAmount);
})().catch(done);
});
it('Should allow unsubscribeAll to be called successfully after an error', (done: DoneCallback) => {
(async () => {
const callback = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => _.noop;
zeroEx.token.subscribe(
tokenAddress, TokenEvents.Approval, indexFilterValues, callback);
stubs = [
Sinon.stub((zeroEx as any)._web3Wrapper, 'getBlockAsync')
.throws(new Error('JSON RPC error')),
];
zeroEx.token.unsubscribeAll();
done();
})().catch(done);
});
});
});

View File

@@ -1,11 +1,14 @@
import {schemas, SchemaValidator} from '@0xproject/json-schemas';
import * as chai from 'chai';
import * as _ from 'lodash';
import 'mocha';
import * as chai from 'chai';
import {SchemaValidator, schemas} from '0x-json-schemas';
import {chaiSetup} from './utils/chai_setup';
import {web3Factory} from './utils/web3_factory';
import {ZeroEx, Token} from '../src';
import {Token, ZeroEx} from '../src';
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
import {chaiSetup} from './utils/chai_setup';
import {constants} from './utils/constants';
import {web3Factory} from './utils/web3_factory';
chaiSetup.configure();
const expect = chai.expect;
@@ -24,9 +27,12 @@ describe('TokenRegistryWrapper', () => {
const registeredName = '0x Protocol Token';
const unregisteredSymbol = 'MAL';
const unregisteredName = 'Malicious Token';
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
before(async () => {
const web3 = web3Factory.create();
zeroEx = new ZeroEx(web3.currentProvider);
zeroEx = new ZeroEx(web3.currentProvider, config);
tokens = await zeroEx.tokenRegistry.getTokensAsync();
_.map(tokens, token => {
tokenAddressBySymbol[token.symbol] = token.address;

View File

@@ -1,17 +1,23 @@
import * as chai from 'chai';
import {chaiSetup} from './utils/chai_setup';
import {web3Factory} from './utils/web3_factory';
import {ZeroEx} from '../src';
import {TokenTransferProxyWrapper} from '../src/contract_wrappers/token_transfer_proxy_wrapper';
import {chaiSetup} from './utils/chai_setup';
import {constants} from './utils/constants';
import {web3Factory} from './utils/web3_factory';
chaiSetup.configure();
const expect = chai.expect;
describe('TokenTransferProxyWrapper', () => {
let zeroEx: ZeroEx;
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
before(async () => {
const web3 = web3Factory.create();
zeroEx = new ZeroEx(web3.currentProvider);
zeroEx = new ZeroEx(web3.currentProvider, config);
});
describe('#isAuthorizedAsync', () => {
it('should return false if the address is not authorized', async () => {

View File

@@ -1,24 +1,30 @@
import 'mocha';
import BigNumber from 'bignumber.js';
import * as chai from 'chai';
import {chaiSetup} from './utils/chai_setup';
import * as Web3 from 'web3';
import * as BigNumber from 'bignumber.js';
import promisify = require('es6-promisify');
import {web3Factory} from './utils/web3_factory';
import 'mocha';
import * as Web3 from 'web3';
import {
ApprovalContractEventArgs,
ContractEvent,
DecodedLogEvent,
LogEvent,
LogWithDecodedArgs,
SubscriptionOpts,
Token,
TokenContractEventArgs,
TokenEvents,
TransferContractEventArgs,
ZeroEx,
ZeroExError,
Token,
SubscriptionOpts,
TokenEvents,
ContractEvent,
TransferContractEventArgs,
ApprovalContractEventArgs,
LogWithDecodedArgs,
} from '../src';
import {BlockParamLiteral, DoneCallback} from '../src/types';
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
import {chaiSetup} from './utils/chai_setup';
import {constants} from './utils/constants';
import {TokenUtils} from './utils/token_utils';
import {DoneCallback} from '../src/types';
import {web3Factory} from './utils/web3_factory';
chaiSetup.configure();
const expect = chai.expect;
@@ -32,9 +38,12 @@ describe('TokenWrapper', () => {
let tokenUtils: TokenUtils;
let coinbase: string;
let addressWithoutFunds: string;
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
before(async () => {
web3 = web3Factory.create();
zeroEx = new ZeroEx(web3.currentProvider);
zeroEx = new ZeroEx(web3.currentProvider, config);
userAddresses = await zeroEx.getAvailableAddressesAsync();
tokens = await zeroEx.tokenRegistry.getTokensAsync();
tokenUtils = new TokenUtils(tokens);
@@ -49,7 +58,7 @@ describe('TokenWrapper', () => {
});
describe('#transferAsync', () => {
let token: Token;
let transferAmount: BigNumber.BigNumber;
let transferAmount: BigNumber;
before(() => {
token = tokens[0];
transferAmount = new BigNumber(42);
@@ -60,7 +69,7 @@ describe('TokenWrapper', () => {
const preBalance = await zeroEx.token.getBalanceAsync(token.address, toAddress);
expect(preBalance).to.be.bignumber.equal(0);
const txHash = await zeroEx.token.transferAsync(token.address, fromAddress, toAddress, transferAmount);
await zeroEx.awaitTransactionMinedAsync(txHash);
const receipt = await zeroEx.awaitTransactionMinedAsync(txHash);
const postBalance = await zeroEx.token.getBalanceAsync(token.address, toAddress);
return expect(postBalance).to.be.bignumber.equal(transferAmount);
});
@@ -77,7 +86,7 @@ describe('TokenWrapper', () => {
const toAddress = coinbase;
return expect(zeroEx.token.transferAsync(
nonExistentTokenAddress, fromAddress, toAddress, transferAmount,
)).to.be.rejectedWith(ZeroExError.ContractDoesNotExist);
)).to.be.rejectedWith(ZeroExError.TokenContractDoesNotExist);
});
});
describe('#transferFromAsync', () => {
@@ -150,7 +159,7 @@ describe('TokenWrapper', () => {
const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065';
return expect(zeroEx.token.transferFromAsync(
nonExistentTokenAddress, fromAddress, toAddress, senderAddress, new BigNumber(42),
)).to.be.rejectedWith(ZeroExError.ContractDoesNotExist);
)).to.be.rejectedWith(ZeroExError.TokenContractDoesNotExist);
});
});
describe('#getBalanceAsync', () => {
@@ -159,14 +168,14 @@ describe('TokenWrapper', () => {
const token = tokens[0];
const ownerAddress = coinbase;
const balance = await zeroEx.token.getBalanceAsync(token.address, ownerAddress);
const expectedBalance = new BigNumber('100000000000000000000000000');
const expectedBalance = new BigNumber('1000000000000000000000000000');
return expect(balance).to.be.bignumber.equal(expectedBalance);
});
it('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => {
const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065';
const ownerAddress = coinbase;
return expect(zeroEx.token.getBalanceAsync(nonExistentTokenAddress, ownerAddress))
.to.be.rejectedWith(ZeroExError.ContractDoesNotExist);
.to.be.rejectedWith(ZeroExError.TokenContractDoesNotExist);
});
it('should return a balance of 0 for a non-existent owner address', async () => {
const token = tokens[0];
@@ -181,13 +190,13 @@ describe('TokenWrapper', () => {
before(async () => {
const hasAddresses = false;
const web3WithoutAccounts = web3Factory.create(hasAddresses);
zeroExWithoutAccounts = new ZeroEx(web3WithoutAccounts.currentProvider);
zeroExWithoutAccounts = new ZeroEx(web3WithoutAccounts.currentProvider, config);
});
it('should return balance even when called with Web3 provider instance without addresses', async () => {
const token = tokens[0];
const ownerAddress = coinbase;
const balance = await zeroExWithoutAccounts.token.getBalanceAsync(token.address, ownerAddress);
const expectedBalance = new BigNumber('100000000000000000000000000');
const expectedBalance = new BigNumber('1000000000000000000000000000');
return expect(balance).to.be.bignumber.equal(expectedBalance);
});
});
@@ -278,7 +287,7 @@ describe('TokenWrapper', () => {
before(async () => {
const hasAddresses = false;
const web3WithoutAccounts = web3Factory.create(hasAddresses);
zeroExWithoutAccounts = new ZeroEx(web3WithoutAccounts.currentProvider);
zeroExWithoutAccounts = new ZeroEx(web3WithoutAccounts.currentProvider, config);
});
it('should get the proxy allowance', async () => {
const token = tokens[0];
@@ -336,132 +345,118 @@ describe('TokenWrapper', () => {
return expect(allowance).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
});
});
describe('#subscribeAsync', () => {
describe('#subscribe', () => {
const indexFilterValues = {};
const shouldThrowOnInsufficientBalanceOrAllowance = true;
let tokenAddress: string;
const subscriptionOpts: SubscriptionOpts = {
fromBlock: 0,
toBlock: 'latest',
};
const transferAmount = new BigNumber(42);
const allowanceAmount = new BigNumber(42);
before(() => {
const token = tokens[0];
tokenAddress = token.address;
});
afterEach(async () => {
await zeroEx.token.stopWatchingAllEventsAsync();
afterEach(() => {
zeroEx.token.unsubscribeAll();
});
// Hack: Mocha does not allow a test to be both async and have a `done` callback
// Since we need to await the receipt of the event in the `subscribeAsync` callback,
// Since we need to await the receipt of the event in the `subscribe` callback,
// we do need both. A hack is to make the top-level a sync fn w/ a done callback and then
// wrap the rest of the test in an async block
// Source: https://github.com/mochajs/mocha/issues/2407
it('Should receive the Transfer event when tokens are transfered', (done: DoneCallback) => {
(async () => {
const zeroExEvent = await zeroEx.token.subscribeAsync(
tokenAddress, TokenEvents.Transfer, subscriptionOpts, indexFilterValues);
zeroExEvent.watch((err: Error, event: ContractEvent) => {
expect(err).to.be.null();
expect(event).to.not.be.undefined();
const args = event.args as TransferContractEventArgs;
const callback = (err: Error, logEvent: DecodedLogEvent<TransferContractEventArgs>) => {
expect(logEvent).to.not.be.undefined();
expect(logEvent.isRemoved).to.be.false();
expect(logEvent.log.logIndex).to.be.equal(0);
expect(logEvent.log.transactionIndex).to.be.equal(0);
expect(logEvent.log.blockNumber).to.be.a('number');
const args = logEvent.log.args;
expect(args._from).to.be.equal(coinbase);
expect(args._to).to.be.equal(addressWithoutFunds);
expect(args._value).to.be.bignumber.equal(transferAmount);
done();
});
};
zeroEx.token.subscribe(
tokenAddress, TokenEvents.Transfer, indexFilterValues, callback);
await zeroEx.token.transferAsync(tokenAddress, coinbase, addressWithoutFunds, transferAmount);
})().catch(done);
});
it('Should receive the Approval event when allowance is being set', (done: DoneCallback) => {
(async () => {
const zeroExEvent = await zeroEx.token.subscribeAsync(
tokenAddress, TokenEvents.Approval, subscriptionOpts, indexFilterValues);
zeroExEvent.watch((err: Error, event: ContractEvent) => {
expect(err).to.be.null();
expect(event).to.not.be.undefined();
const args = event.args as ApprovalContractEventArgs;
const callback = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
expect(logEvent).to.not.be.undefined();
expect(logEvent.isRemoved).to.be.false();
const args = logEvent.log.args;
expect(args._owner).to.be.equal(coinbase);
expect(args._spender).to.be.equal(addressWithoutFunds);
expect(args._value).to.be.bignumber.equal(allowanceAmount);
done();
});
};
zeroEx.token.subscribe(
tokenAddress, TokenEvents.Approval, indexFilterValues, callback);
await zeroEx.token.setAllowanceAsync(tokenAddress, coinbase, addressWithoutFunds, allowanceAmount);
})().catch(done);
});
it('Outstanding subscriptions are cancelled when zeroEx.setProviderAsync called', (done: DoneCallback) => {
it('Outstanding subscriptions are cancelled when zeroEx.setProvider called', (done: DoneCallback) => {
(async () => {
const eventSubscriptionToBeCancelled = await zeroEx.token.subscribeAsync(
tokenAddress, TokenEvents.Transfer, subscriptionOpts, indexFilterValues);
eventSubscriptionToBeCancelled.watch((err: Error, event: ContractEvent) => {
const callbackNeverToBeCalled = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
done(new Error('Expected this subscription to have been cancelled'));
});
const newProvider = web3Factory.getRpcProvider();
await zeroEx.setProviderAsync(newProvider);
const eventSubscriptionToStay = await zeroEx.token.subscribeAsync(
tokenAddress, TokenEvents.Transfer, subscriptionOpts, indexFilterValues);
eventSubscriptionToStay.watch((err: Error, event: ContractEvent) => {
expect(err).to.be.null();
expect(event).to.not.be.undefined();
};
zeroEx.token.subscribe(
tokenAddress, TokenEvents.Transfer, indexFilterValues, callbackNeverToBeCalled,
);
const callbackToBeCalled = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
done();
});
};
const newProvider = web3Factory.getRpcProvider();
zeroEx.setProvider(newProvider, constants.TESTRPC_NETWORK_ID);
zeroEx.token.subscribe(
tokenAddress, TokenEvents.Transfer, indexFilterValues, callbackToBeCalled,
);
await zeroEx.token.transferAsync(tokenAddress, coinbase, addressWithoutFunds, transferAmount);
})().catch(done);
});
it('Should stop watch for events when stopWatchingAsync called on the eventEmitter', (done: DoneCallback) => {
it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => {
(async () => {
const eventSubscriptionToBeStopped = await zeroEx.token.subscribeAsync(
tokenAddress, TokenEvents.Transfer, subscriptionOpts, indexFilterValues);
eventSubscriptionToBeStopped.watch((err: Error, event: ContractEvent) => {
done(new Error('Expected this subscription to have been stopped'));
});
await eventSubscriptionToBeStopped.stopWatchingAsync();
const callbackNeverToBeCalled = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
done(new Error('Expected this subscription to have been cancelled'));
};
const subscriptionToken = zeroEx.token.subscribe(
tokenAddress, TokenEvents.Transfer, indexFilterValues, callbackNeverToBeCalled);
zeroEx.token.unsubscribe(subscriptionToken);
await zeroEx.token.transferAsync(tokenAddress, coinbase, addressWithoutFunds, transferAmount);
done();
})().catch(done);
});
it('Should wrap all event args BigNumber instances in a newer version of BigNumber', (done: DoneCallback) => {
(async () => {
const zeroExEvent = await zeroEx.token.subscribeAsync(
tokenAddress, TokenEvents.Transfer, subscriptionOpts, indexFilterValues);
zeroExEvent.watch((err: Error, event: ContractEvent) => {
const args = event.args as TransferContractEventArgs;
expect(args._value.isBigNumber).to.be.true();
done();
});
await zeroEx.token.transferAsync(tokenAddress, coinbase, addressWithoutFunds, transferAmount);
})().catch(done);
});
});
describe('#getLogsAsync', () => {
let tokenAddress: string;
let tokenTransferProxyAddress: string;
const subscriptionOpts: SubscriptionOpts = {
fromBlock: 'earliest',
toBlock: 'latest',
fromBlock: 0,
toBlock: BlockParamLiteral.Latest,
};
let txHash: string;
before(async () => {
before(() => {
const token = tokens[0];
tokenAddress = token.address;
tokenTransferProxyAddress = await zeroEx.proxy.getContractAddressAsync();
tokenTransferProxyAddress = zeroEx.proxy.getContractAddress();
});
it('should get logs with decoded args emitted by Approval', async () => {
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(tokenAddress, coinbase);
await zeroEx.awaitTransactionMinedAsync(txHash);
const eventName = TokenEvents.Approval;
const indexFilterValues = {};
const logs = await zeroEx.token.getLogsAsync(
const logs = await zeroEx.token.getLogsAsync<ApprovalContractEventArgs>(
tokenAddress, eventName, subscriptionOpts, indexFilterValues,
);
expect(logs).to.have.length(1);
const args = logs[0].args;
expect(logs[0].event).to.be.equal(eventName);
expect(logs[0].args._owner).to.be.equal(coinbase);
expect(logs[0].args._spender).to.be.equal(tokenTransferProxyAddress);
expect(logs[0].args._value).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
expect(args._owner).to.be.equal(coinbase);
expect(args._spender).to.be.equal(tokenTransferProxyAddress);
expect(args._value).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
});
it('should only get the logs with the correct event name', async () => {
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(tokenAddress, coinbase);
@@ -482,11 +477,12 @@ describe('TokenWrapper', () => {
const indexFilterValues = {
_owner: coinbase,
};
const logs = await zeroEx.token.getLogsAsync(
const logs = await zeroEx.token.getLogsAsync<ApprovalContractEventArgs>(
tokenAddress, eventName, subscriptionOpts, indexFilterValues,
);
expect(logs).to.have.length(1);
expect(logs[0].args._owner).to.be.equal(coinbase);
const args = logs[0].args;
expect(args._owner).to.be.equal(coinbase);
});
});
});

View File

@@ -0,0 +1,26 @@
import {RPC} from './rpc';
export class BlockchainLifecycle {
private rpc: RPC;
private snapshotIdsStack: number[];
constructor() {
this.rpc = new RPC();
this.snapshotIdsStack = [];
}
// TODO: In order to run these tests on an actual node, we should check if we are running against
// TestRPC, if so, use snapshots, otherwise re-deploy contracts before every test
public async startAsync(): Promise<void> {
const snapshotId = await this.rpc.takeSnapshotAsync();
this.snapshotIdsStack.push(snapshotId);
}
public async revertAsync(): Promise<void> {
const snapshotId = this.snapshotIdsStack.pop() as number;
const didRevert = await this.rpc.revertSnapshotAsync(snapshotId);
if (!didRevert) {
throw new Error(`Snapshot with id #${snapshotId} failed to revert`);
}
}
public async mineABlock(): Promise<void> {
await this.rpc.mineBlockAsync();
}
}

View File

@@ -1,7 +1,7 @@
import * as chai from 'chai';
import * as dirtyChai from 'dirty-chai';
import ChaiBigNumber = require('chai-bignumber');
import chaiAsPromised = require('chai-as-promised');
import ChaiBigNumber = require('chai-bignumber');
import * as dirtyChai from 'dirty-chai';
export const chaiSetup = {
configure() {

View File

@@ -2,7 +2,11 @@ export const constants = {
NULL_ADDRESS: '0x0000000000000000000000000000000000000000',
RPC_HOST: 'localhost',
RPC_PORT: 8545,
ROPSTEN_NETWORK_ID: 3,
KOVAN_NETWORK_ID: 42,
TESTRPC_NETWORK_ID: 50,
KOVAN_RPC_URL: 'https://kovan.infura.io',
ROPSTEN_RPC_URL: 'https://ropsten.infura.io',
ZRX_DECIMALS: 18,
GAS_ESTIMATE: 500000,
};

View File

@@ -1,6 +1,8 @@
import * as BigNumber from 'bignumber.js';
import {ZeroEx, Token, SignedOrder} from '../../src';
import BigNumber from 'bignumber.js';
import {SignedOrder, Token, ZeroEx} from '../../src';
import {orderFactory} from '../utils/order_factory';
import {constants} from './constants';
export class FillScenarios {
@@ -21,8 +23,8 @@ export class FillScenarios {
}
public async createFillableSignedOrderAsync(makerTokenAddress: string, takerTokenAddress: string,
makerAddress: string, takerAddress: string,
fillableAmount: BigNumber.BigNumber,
expirationUnixTimestampSec?: BigNumber.BigNumber):
fillableAmount: BigNumber,
expirationUnixTimestampSec?: BigNumber):
Promise<SignedOrder> {
return this.createAsymmetricFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress,
@@ -31,10 +33,10 @@ export class FillScenarios {
}
public async createFillableSignedOrderWithFeesAsync(
makerTokenAddress: string, takerTokenAddress: string,
makerFee: BigNumber.BigNumber, takerFee: BigNumber.BigNumber,
makerFee: BigNumber, takerFee: BigNumber,
makerAddress: string, takerAddress: string,
fillableAmount: BigNumber.BigNumber,
feeRecepient: string, expirationUnixTimestampSec?: BigNumber.BigNumber,
fillableAmount: BigNumber,
feeRecepient: string, expirationUnixTimestampSec?: BigNumber,
): Promise<SignedOrder> {
return this.createAsymmetricFillableSignedOrderWithFeesAsync(
makerTokenAddress, takerTokenAddress, makerFee, takerFee, makerAddress, takerAddress,
@@ -43,8 +45,8 @@ export class FillScenarios {
}
public async createAsymmetricFillableSignedOrderAsync(
makerTokenAddress: string, takerTokenAddress: string, makerAddress: string, takerAddress: string,
makerFillableAmount: BigNumber.BigNumber, takerFillableAmount: BigNumber.BigNumber,
expirationUnixTimestampSec?: BigNumber.BigNumber): Promise<SignedOrder> {
makerFillableAmount: BigNumber, takerFillableAmount: BigNumber,
expirationUnixTimestampSec?: BigNumber): Promise<SignedOrder> {
const makerFee = new BigNumber(0);
const takerFee = new BigNumber(0);
const feeRecepient = constants.NULL_ADDRESS;
@@ -54,8 +56,8 @@ export class FillScenarios {
);
}
public async createPartiallyFilledSignedOrderAsync(makerTokenAddress: string, takerTokenAddress: string,
takerAddress: string, fillableAmount: BigNumber.BigNumber,
partialFillAmount: BigNumber.BigNumber) {
takerAddress: string, fillableAmount: BigNumber,
partialFillAmount: BigNumber) {
const [makerAddress] = this.userAddresses;
const signedOrder = await this.createAsymmetricFillableSignedOrderAsync(
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress,
@@ -69,10 +71,10 @@ export class FillScenarios {
}
private async createAsymmetricFillableSignedOrderWithFeesAsync(
makerTokenAddress: string, takerTokenAddress: string,
makerFee: BigNumber.BigNumber, takerFee: BigNumber.BigNumber,
makerFee: BigNumber, takerFee: BigNumber,
makerAddress: string, takerAddress: string,
makerFillableAmount: BigNumber.BigNumber, takerFillableAmount: BigNumber.BigNumber,
feeRecepient: string, expirationUnixTimestampSec?: BigNumber.BigNumber): Promise<SignedOrder> {
makerFillableAmount: BigNumber, takerFillableAmount: BigNumber,
feeRecepient: string, expirationUnixTimestampSec?: BigNumber): Promise<SignedOrder> {
await Promise.all([
this.increaseBalanceAndAllowanceAsync(makerTokenAddress, makerAddress, makerFillableAmount),
@@ -90,8 +92,8 @@ export class FillScenarios {
return signedOrder;
}
private async increaseBalanceAndAllowanceAsync(
tokenAddress: string, address: string, amount: BigNumber.BigNumber): Promise<void> {
if (amount.isZero()) {
tokenAddress: string, address: string, amount: BigNumber): Promise<void> {
if (amount.isZero() || address === ZeroEx.NULL_ADDRESS) {
return; // noop
}
await Promise.all([
@@ -100,11 +102,11 @@ export class FillScenarios {
]);
}
private async increaseBalanceAsync(
tokenAddress: string, address: string, amount: BigNumber.BigNumber): Promise<void> {
tokenAddress: string, address: string, amount: BigNumber): Promise<void> {
await this.zeroEx.token.transferAsync(tokenAddress, this.coinbase, address, amount);
}
private async increaseAllowanceAsync(
tokenAddress: string, address: string, amount: BigNumber.BigNumber): Promise<void> {
tokenAddress: string, address: string, amount: BigNumber): Promise<void> {
const oldMakerAllowance = await this.zeroEx.token.getProxyAllowanceAsync(tokenAddress, address);
const newMakerAllowance = oldMakerAllowance.plus(amount);
await this.zeroEx.token.setProxyAllowanceAsync(

View File

@@ -1,25 +1,26 @@
import BigNumber from 'bignumber.js';
import * as _ from 'lodash';
import * as BigNumber from 'bignumber.js';
import {ZeroEx, SignedOrder} from '../../src';
import {SignedOrder, ZeroEx} from '../../src';
export const orderFactory = {
async createSignedOrderAsync(
zeroEx: ZeroEx,
maker: string,
taker: string,
makerFee: BigNumber.BigNumber,
takerFee: BigNumber.BigNumber,
makerTokenAmount: BigNumber.BigNumber,
makerFee: BigNumber,
takerFee: BigNumber,
makerTokenAmount: BigNumber,
makerTokenAddress: string,
takerTokenAmount: BigNumber.BigNumber,
takerTokenAmount: BigNumber,
takerTokenAddress: string,
exchangeContractAddress: string,
feeRecipient: string,
expirationUnixTimestampSec?: BigNumber.BigNumber): Promise<SignedOrder> {
expirationUnixTimestampSecIfExists?: BigNumber): Promise<SignedOrder> {
const defaultExpirationUnixTimestampSec = new BigNumber(2524604400); // Close to infinite
expirationUnixTimestampSec = _.isUndefined(expirationUnixTimestampSec) ?
const expirationUnixTimestampSec = _.isUndefined(expirationUnixTimestampSecIfExists) ?
defaultExpirationUnixTimestampSec :
expirationUnixTimestampSec;
expirationUnixTimestampSecIfExists;
const order = {
maker,
taker,

View File

@@ -0,0 +1,14 @@
import { DoneCallback } from '../../src/types';
export const reportCallbackErrors = (done: DoneCallback) => {
return (f: (...args: any[]) => void) => {
const wrapped = async (...args: any[]) => {
try {
f(...args);
} catch (err) {
done(err);
}
};
return wrapped;
};
};

View File

@@ -1,5 +1,6 @@
import * as ethUtil from 'ethereumjs-util';
import * as request from 'request-promise-native';
import {constants} from './constants';
export class RPC {
@@ -26,6 +27,12 @@ export class RPC {
const didRevert = await this.sendAsync(payload);
return didRevert;
}
public async mineBlockAsync(): Promise<void> {
const method = 'evm_mine';
const params: any[] = [];
const payload = this.toPayload(method, params);
await this.sendAsync(payload);
}
private toPayload(method: string, params: any[] = []): string {
const payload = JSON.stringify({
id: this.id,
@@ -41,7 +48,7 @@ export class RPC {
uri: `http://${this.host}:${this.port}`,
body: payload,
headers: {
'content-type': 'application/json'
'content-type': 'application/json',
},
};
const bodyString = await request(opts);

View File

@@ -1,12 +1,13 @@
import * as Web3 from 'web3';
import {JSONRPCPayload} from '../types';
import {JSONRPCPayload} from '../../../src/types';
/*
* This class implements the web3-provider-engine subprovider interface and returns
* that the provider has no addresses when queried.
* Source: https://github.com/MetaMask/provider-engine/blob/master/subproviders/subprovider.js
*/
export class EmptyWalletSubProvider {
export class EmptyWalletSubprovider {
// This method needs to be here to satisfy the interface but linter wants it to be static.
// tslint:disable-next-line:prefer-function-over-method
public handleRequest(payload: JSONRPCPayload, next: () => void, end: (err: Error|null, result: any) => void) {
switch (payload.method) {
case 'eth_accounts':
@@ -19,6 +20,7 @@ export class EmptyWalletSubProvider {
}
}
// Required to implement this method despite not needing it for this subprovider
// tslint:disable-next-line:prefer-function-over-method
public setEngine(engine: any) {
// noop
}

View File

@@ -0,0 +1,34 @@
import {JSONRPCPayload} from '../../../src/types';
/*
* This class implements the web3-provider-engine subprovider interface and returns
* the constant gas estimate when queried.
* HACK: We need this so that our tests don't use testrpc gas estimation which sometimes kills the node.
* Source: https://github.com/trufflesuite/ganache-cli/issues/417
* Source: https://github.com/trufflesuite/ganache-cli/issues/437
* Source: https://github.com/MetaMask/provider-engine/blob/master/subproviders/subprovider.js
*/
export class FakeGasEstimateSubprovider {
private constantGasAmount: number;
constructor(constantGasAmount: number) {
this.constantGasAmount = constantGasAmount;
}
// This method needs to be here to satisfy the interface but linter wants it to be static.
// tslint:disable-next-line:prefer-function-over-method
public handleRequest(payload: JSONRPCPayload, next: () => void, end: (err: Error|null, result: any) => void) {
switch (payload.method) {
case 'eth_estimateGas':
end(null, this.constantGasAmount);
return;
default:
next();
return;
}
}
// Required to implement this method despite not needing it for this subprovider
// tslint:disable-next-line:prefer-function-over-method
public setEngine(engine: any) {
// noop
}
}

View File

@@ -1,5 +1,6 @@
import * as _ from 'lodash';
import {Token, InternalZeroExError} from '../../src/types';
import {InternalZeroExError, Token} from '../../src/types';
const PROTOCOL_TOKEN_SYMBOL = 'ZRX';

View File

@@ -3,11 +3,14 @@
// we are not running in a browser env.
// Filed issue: https://github.com/ethereum/web3.js/issues/844
(global as any).XMLHttpRequest = undefined;
import * as Web3 from 'web3';
import ProviderEngine = require('web3-provider-engine');
import RpcSubprovider = require('web3-provider-engine/subproviders/rpc');
import * as Web3 from 'web3';
import {EmptyWalletSubprovider} from './subproviders/empty_wallet_subprovider';
import {FakeGasEstimateSubprovider} from './subproviders/fake_gas_estimate_subprovider';
import {constants} from './constants';
import {EmptyWalletSubProvider} from '../../src/subproviders/empty_wallet_subprovider';
export const web3Factory = {
create(hasAddresses: boolean = true): Web3 {
@@ -20,8 +23,9 @@ export const web3Factory = {
const provider = new ProviderEngine();
const rpcUrl = `http://${constants.RPC_HOST}:${constants.RPC_PORT}`;
if (!hasAddresses) {
provider.addProvider(new EmptyWalletSubProvider());
provider.addProvider(new EmptyWalletSubprovider());
}
provider.addProvider(new FakeGasEstimateSubprovider(constants.GAS_ESTIMATE));
provider.addProvider(new RpcSubprovider({
rpcUrl,
}));

View File

@@ -13,10 +13,10 @@
"include": [
"./src/**/*",
"./test/**/*",
"./node_modules/types-bn/index.d.ts",
"./node_modules/types-ethereumjs-util/index.d.ts",
"./node_modules/web3-typescript-typings/index.d.ts",
"./node_modules/chai-typescript-typings/index.d.ts",
"./node_modules/chai-as-promised-typescript-typings/index.d.ts"
"../../node_modules/types-bn/index.d.ts",
"../../node_modules/types-ethereumjs-util/index.d.ts",
"../../node_modules/web3-typescript-typings/index.d.ts",
"../../node_modules/chai-typescript-typings/index.d.ts",
"../../node_modules/chai-as-promised-typescript-typings/index.d.ts"
]
}

View File

@@ -0,0 +1,5 @@
{
"extends": [
"@0xproject/tslint-config"
]
}

View File

@@ -0,0 +1,6 @@
# CHANGELOG
v0.0.4 - _Nov. 14, 2017_
------------------------
* Re-publish Assert previously published under NPM package @0xproject/0x-assert
* Added assertion isValidBaseUnitAmount which checks both that the value is a valid bigNumber and that it does not contain decimals.

10
packages/assert/README.md Normal file
View File

@@ -0,0 +1,10 @@
assert
------
Standard type and schema assertions to be used across all 0x projects and packages
## Install
```bash
npm install @0xproject/assert --save
```

View File

@@ -0,0 +1,46 @@
{
"name": "@0xproject/assert",
"version": "0.0.5",
"description": "Provides a standard way of performing type and schema validation across 0x projects",
"main": "lib/src/index.js",
"types": "lib/src/index.d.ts",
"scripts": {
"build": "tsc",
"clean": "shx rm -rf _bundles lib test_temp",
"lint": "tslint --project . 'src/**/*.ts' 'test/**/*.ts'",
"run_mocha": "mocha lib/test/**/*_test.js",
"prepublishOnly": "run-p build",
"test": "run-s clean build run_mocha",
"test:circleci": "yarn test"
},
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/0xProject/0x.js.git"
},
"bugs": {
"url": "https://github.com/0xProject/0x.js/issues"
},
"homepage": "https://github.com/0xProject/0x.js/packages/assert/README.md",
"devDependencies": {
"@0xproject/tslint-config": "^0.1.1",
"@types/lodash": "^4.14.78",
"@types/mocha": "^2.2.42",
"@types/valid-url": "^1.0.2",
"chai": "^4.0.1",
"chai-typescript-typings": "^0.0.1",
"dirty-chai": "^2.0.1",
"mocha": "^4.0.1",
"npm-run-all": "^4.1.1",
"shx": "^0.2.2",
"tslint": "5.8.0",
"typescript": "^2.4.2"
},
"dependencies": {
"@0xproject/json-schemas": "^0.6.8",
"bignumber.js": "~4.1.0",
"ethereum-address": "^0.0.4",
"lodash": "^4.17.4",
"valid-url": "^1.0.9"
}
}

View File

@@ -0,0 +1,14 @@
const postpublish_utils = require('../../../scripts/postpublish_utils');
const packageJSON = require('../package.json');
const subPackageName = packageJSON.name;
postpublish_utils.getLatestTagAndVersionAsync(subPackageName)
.then(function(result) {
const releaseName = postpublish_utils.getReleaseName(subPackageName, result.version);
const assets = [];
return postpublish_utils.publishReleaseNotes(result.tag, releaseName, assets);
})
.catch (function(err) {
throw err;
});

5
packages/assert/src/globals.d.ts vendored Normal file
View File

@@ -0,0 +1,5 @@
declare module 'dirty-chai';
declare module 'ethereum-address' {
const isAddress: (arg: any) => boolean;
}

View File

@@ -1,31 +1,43 @@
import {
Schema,
SchemaValidator,
} from '@0xproject/json-schemas';
import BigNumber from 'bignumber.js';
import * as ethereum_address from 'ethereum-address';
import * as _ from 'lodash';
import * as BigNumber from 'bignumber.js';
import * as Web3 from 'web3';
import {Web3Wrapper} from '../web3_wrapper';
import {SchemaValidator, Schema} from '0x-json-schemas';
import * as validUrl from 'valid-url';
const HEX_REGEX = /^0x[0-9A-F]*$/i;
export const assert = {
isBigNumber(variableName: string, value: BigNumber.BigNumber): void {
const isBigNumber = _.isObject(value) && value.isBigNumber;
isBigNumber(variableName: string, value: BigNumber): void {
const isBigNumber = _.isObject(value) && (value as any).isBigNumber;
this.assert(isBigNumber, this.typeAssertionMessage(variableName, 'BigNumber', value));
},
isValidBaseUnitAmount(variableName: string, value: BigNumber) {
assert.isBigNumber(variableName, value);
const hasDecimals = value.decimalPlaces() !== 0;
this.assert(
!hasDecimals, `${variableName} should be in baseUnits (no decimals), found value: ${value.toNumber()}`,
);
},
isUndefined(value: any, variableName?: string): void {
this.assert(_.isUndefined(value), this.typeAssertionMessage(variableName, 'undefined', value));
},
isString(variableName: string, value: string): void {
this.assert(_.isString(value), this.typeAssertionMessage(variableName, 'string', value));
},
isFunction(variableName: string, value: any): void {
this.assert(_.isFunction(value), this.typeAssertionMessage(variableName, 'function', value));
},
isHexString(variableName: string, value: string): void {
this.assert(_.isString(value) && HEX_REGEX.test(value),
this.typeAssertionMessage(variableName, 'HexString', value));
},
isETHAddressHex(variableName: string, value: string): void {
const web3 = new Web3();
this.assert(web3.isAddress(value), this.typeAssertionMessage(variableName, 'ETHAddressHex', value));
this.assert(ethereum_address.isAddress(value), this.typeAssertionMessage(variableName, 'ETHAddressHex', value));
this.assert(
web3.isAddress(value) && !web3.isChecksumAddress(value),
ethereum_address.isAddress(value) && value.toLowerCase() === value,
`Checksummed addresses are not supported. Convert ${variableName} to lower case before passing`,
);
},
@@ -40,18 +52,6 @@ export const assert = {
`Expected ${variableName} to be one of: ${enumValuesAsString}, encountered: ${value}`,
);
},
async isSenderAddressAsync(variableName: string, senderAddressHex: string,
web3Wrapper: Web3Wrapper): Promise<void> {
assert.isETHAddressHex(variableName, senderAddressHex);
const isSenderAddressAvailable = await web3Wrapper.isSenderAddressAvailableAsync(senderAddressHex);
assert.assert(isSenderAddressAvailable,
`Specified ${variableName} ${senderAddressHex} isn't available through the supplied web3 provider`,
);
},
async isUserAddressAvailableAsync(web3Wrapper: Web3Wrapper): Promise<void> {
const availableAddresses = await web3Wrapper.getAvailableAddressesAsync();
this.assert(!_.isEmpty(availableAddresses), 'No addresses were available on the provided web3 provider');
},
hasAtMostOneUniqueValue(value: any[], errMsg: string): void {
this.assert(_.uniq(value).length <= 1, errMsg);
},
@@ -61,8 +61,8 @@ export const assert = {
isBoolean(variableName: string, value: boolean): void {
this.assert(_.isBoolean(value), this.typeAssertionMessage(variableName, 'boolean', value));
},
isWeb3Provider(variableName: string, value: Web3.Provider): void {
const isWeb3Provider = _.isFunction((value as any).send) || _.isFunction((value as any).sendAsync);
isWeb3Provider(variableName: string, value: any): void {
const isWeb3Provider = _.isFunction((value).send) || _.isFunction((value).sendAsync);
this.assert(isWeb3Provider, this.typeAssertionMessage(variableName, 'Web3.Provider', value));
},
doesConformToSchema(variableName: string, value: any, schema: Schema): void {
@@ -74,6 +74,14 @@ Encountered: ${JSON.stringify(value, null, '\t')}
Validation errors: ${validationResult.errors.join(', ')}`;
this.assert(!hasValidationErrors, msg);
},
isHttpUrl(variableName: string, value: any): void {
const isValidUrl = validUrl.isWebUri(value);
this.assert(isValidUrl, this.typeAssertionMessage(variableName, 'http url', value));
},
isUri(variableName: string, value: any): void {
const isValidUri = validUrl.isUri(value);
this.assert(isValidUri, this.typeAssertionMessage(variableName, 'uri', value));
},
assert(condition: boolean, message: string): void {
if (!condition) {
throw new Error(message);

View File

@@ -0,0 +1,339 @@
import {schemas} from '@0xproject/json-schemas';
import {BigNumber} from 'bignumber.js';
import * as chai from 'chai';
import * as dirtyChai from 'dirty-chai';
import 'mocha';
import {assert} from '../src/index';
chai.config.includeStack = true;
chai.use(dirtyChai);
const expect = chai.expect;
describe('Assertions', () => {
const variableName = 'variable';
describe('#isBigNumber', () => {
it('should not throw for valid input', () => {
const validInputs = [
new BigNumber(23),
new BigNumber('45'),
];
validInputs.forEach(input => expect(assert.isBigNumber.bind(assert, variableName, input)).to.not.throw());
});
it('should throw for invalid input', () => {
const invalidInputs = [
'test',
42,
false,
{ random: 'test' },
undefined,
];
invalidInputs.forEach(input => expect(assert.isBigNumber.bind(assert, variableName, input)).to.throw());
});
});
describe('#isUndefined', () => {
it('should not throw for valid input', () => {
const validInputs = [
undefined,
];
validInputs.forEach(input => expect(assert.isUndefined.bind(assert, input, variableName)).to.not.throw());
});
it('should throw for invalid input', () => {
const invalidInputs = [
'test',
42,
false,
{ random: 'test' },
];
invalidInputs.forEach(input => expect(assert.isUndefined.bind(assert, input, variableName)).to.throw());
});
});
describe('#isString', () => {
it('should not throw for valid input', () => {
const validInputs = [
'hello',
'goodbye',
];
validInputs.forEach(input => expect(assert.isString.bind(assert, variableName, input)).to.not.throw());
});
it('should throw for invalid input', () => {
const invalidInputs = [
42,
false,
{ random: 'test' },
undefined,
new BigNumber(45),
];
invalidInputs.forEach(input => expect(assert.isString.bind(assert, variableName, input)).to.throw());
});
});
describe('#isFunction', () => {
it('should not throw for valid input', () => {
const validInputs = [
BigNumber,
assert.isString.bind(this),
];
validInputs.forEach(input => expect(assert.isFunction.bind(assert, variableName, input)).to.not.throw());
});
it('should throw for invalid input', () => {
const invalidInputs = [
42,
false,
{ random: 'test' },
undefined,
new BigNumber(45),
];
invalidInputs.forEach(input => expect(assert.isFunction.bind(assert, variableName, input)).to.throw());
});
});
describe('#isHexString', () => {
it('should not throw for valid input', () => {
const validInputs = [
'0x61a3ed31B43c8780e905a260a35faefEc527be7516aa11c0256729b5b351bc33',
'0x40349190569279751135161d22529dc25add4f6069af05be04cacbda2ace2254',
];
validInputs.forEach(input => expect(assert.isHexString.bind(assert, variableName, input)).to.not.throw());
});
it('should throw for invalid input', () => {
const invalidInputs = [
42,
false,
{ random: 'test' },
undefined,
new BigNumber(45),
'0x61a3ed31B43c8780e905a260a35faYfEc527be7516aa11c0256729b5b351bc33',
];
invalidInputs.forEach(input => expect(assert.isHexString.bind(assert, variableName, input)).to.throw());
});
});
describe('#isETHAddressHex', () => {
it('should not throw for valid input', () => {
const validInputs = [
'0x0000000000000000000000000000000000000000',
'0x6fffd0ae3f7d88c9b4925323f54c6e4b2918c5fd',
'0x12459c951127e0c374ff9105dda097662a027093',
];
validInputs.forEach(input =>
expect(assert.isETHAddressHex.bind(assert, variableName, input)).to.not.throw(),
);
});
it('should throw for invalid input', () => {
const invalidInputs = [
42,
false,
{ random: 'test' },
undefined,
new BigNumber(45),
'0x6FFFd0ae3f7d88c9b4925323f54c6e4b2918c5fd',
'0x6FFFd0ae3f7d88c9b4925323f54c6e4',
];
invalidInputs.forEach(input =>
expect(assert.isETHAddressHex.bind(assert, variableName, input)).to.throw(),
);
});
});
describe('#doesBelongToStringEnum', () => {
enum TestEnums {
Test1 = 'Test1',
Test2 = 'Test2',
}
it('should not throw for valid input', () => {
const validInputs = [
TestEnums.Test1,
TestEnums.Test2,
];
validInputs.forEach(input =>
expect(assert.doesBelongToStringEnum.bind(assert, variableName, input, TestEnums)).to.not.throw(),
);
});
it('should throw for invalid input', () => {
const invalidInputs = [
42,
false,
{ random: 'test' },
undefined,
new BigNumber(45),
];
invalidInputs.forEach(input =>
expect(assert.doesBelongToStringEnum.bind(assert, variableName, input, TestEnums)).to.throw(),
);
});
});
describe('#hasAtMostOneUniqueValue', () => {
const errorMsg = 'more than one unique value';
it('should not throw for valid input', () => {
const validInputs = [
['hello'],
['goodbye', 'goodbye', 'goodbye'],
];
validInputs.forEach(input =>
expect(assert.hasAtMostOneUniqueValue.bind(assert, input, errorMsg)).to.not.throw(),
);
});
it('should throw for invalid input', () => {
const invalidInputs = [
['hello', 'goodbye'],
['goodbye', 42, false, false],
];
invalidInputs.forEach(input =>
expect(assert.hasAtMostOneUniqueValue.bind(assert, input, errorMsg)).to.throw(),
);
});
});
describe('#isNumber', () => {
it('should not throw for valid input', () => {
const validInputs = [
42,
0,
21e+42,
];
validInputs.forEach(input => expect(assert.isNumber.bind(assert, variableName, input)).to.not.throw());
});
it('should throw for invalid input', () => {
const invalidInputs = [
false,
{ random: 'test' },
undefined,
new BigNumber(45),
];
invalidInputs.forEach(input => expect(assert.isNumber.bind(assert, variableName, input)).to.throw());
});
});
describe('#isBoolean', () => {
it('should not throw for valid input', () => {
const validInputs = [
true,
false,
];
validInputs.forEach(input => expect(assert.isBoolean.bind(assert, variableName, input)).to.not.throw());
});
it('should throw for invalid input', () => {
const invalidInputs = [
42,
{ random: 'test' },
undefined,
new BigNumber(45),
];
invalidInputs.forEach(input => expect(assert.isBoolean.bind(assert, variableName, input)).to.throw());
});
});
describe('#isWeb3Provider', () => {
it('should not throw for valid input', () => {
const validInputs = [
{ send: () => 45 },
{ sendAsync: () => 45 },
];
validInputs.forEach(input =>
expect(assert.isWeb3Provider.bind(assert, variableName, input)).to.not.throw(),
);
});
it('should throw for invalid input', () => {
const invalidInputs = [
42,
{ random: 'test' },
undefined,
new BigNumber(45),
];
invalidInputs.forEach(input =>
expect(assert.isWeb3Provider.bind(assert, variableName, input)).to.throw(),
);
});
});
describe('#doesConformToSchema', () => {
const schema = schemas.addressSchema;
it('should not throw for valid input', () => {
const validInputs = [
'0x6fffd0ae3f7d88c9b4925323f54c6e4b2918c5fd',
'0x12459c951127e0c374ff9105dda097662a027093',
];
validInputs.forEach(input =>
expect(assert.doesConformToSchema.bind(assert, variableName, input, schema)).to.not.throw(),
);
});
it('should throw for invalid input', () => {
const invalidInputs = [
42,
{ random: 'test' },
undefined,
new BigNumber(45),
];
invalidInputs.forEach(input =>
expect(assert.doesConformToSchema.bind(assert, variableName, input, schema)).to.throw(),
);
});
});
describe('#isHttpUrl', () => {
it('should not throw for valid input', () => {
const validInputs = [
'http://www.google.com',
'https://api.example-relayer.net',
'https://api.radarrelay.com/0x/v0/',
'https://zeroex.beta.radarrelay.com:8000/0x/v0/',
];
validInputs.forEach(input =>
expect(assert.isHttpUrl.bind(assert, variableName, input)).to.not.throw(),
);
});
it('should throw for invalid input', () => {
const invalidInputs = [
42,
{ random: 'test' },
undefined,
new BigNumber(45),
'ws://www.api.example-relayer.net',
'www.google.com',
'api.example-relayer.net',
'user:password@api.example-relayer.net',
'//api.example-relayer.net',
];
invalidInputs.forEach(input =>
expect(assert.isHttpUrl.bind(assert, variableName, input)).to.throw(),
);
});
});
describe('#isUri', () => {
it('should not throw for valid input', () => {
const validInputs = [
'http://www.google.com',
'https://api.example-relayer.net',
'https://api.radarrelay.com/0x/v0/',
'https://zeroex.beta.radarrelay.com:8000/0x/v0/',
'ws://www.api.example-relayer.net',
'wss://www.api.example-relayer.net',
'user:password@api.example-relayer.net',
];
validInputs.forEach(input =>
expect(assert.isUri.bind(assert, variableName, input)).to.not.throw(),
);
});
it('should throw for invalid input', () => {
const invalidInputs = [
42,
{ random: 'test' },
undefined,
new BigNumber(45),
'www.google.com',
'api.example-relayer.net',
'//api.example-relayer.net',
];
invalidInputs.forEach(input =>
expect(assert.isUri.bind(assert, variableName, input)).to.throw(),
);
});
});
describe('#assert', () => {
const assertMessage = 'assert not satisfied';
it('should not throw for valid input', () => {
expect(assert.assert.bind(assert, true, assertMessage)).to.not.throw();
});
it('should throw for invalid input', () => {
expect(assert.assert.bind(assert, false, assertMessage)).to.throw();
});
});
describe('#typeAssertionMessage', () => {
it('should render correct message', () => {
expect(assert.typeAssertionMessage('variable', 'string', 'number'))
.to.equal(`Expected variable to be of type string, encountered: number`);
});
});
});

View File

@@ -0,0 +1,18 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"lib": [ "es2017", "dom"],
"outDir": "lib",
"sourceMap": true,
"declaration": true,
"noImplicitAny": true,
"strictNullChecks": true
},
"include": [
"./src/**/*",
"./test/**/*",
"../../node_modules/chai-typescript-typings/index.d.ts",
"../../node_modules/web3-typescript-typings/index.d.ts"
]
}

View File

@@ -0,0 +1,5 @@
{
"extends": [
"@0xproject/tslint-config"
]
}

View File

@@ -0,0 +1,5 @@
# CHANGELOG
v0.1.0 - _November 22, 2017_
------------------------
* Provide a HttpClient class for interacting with standard relayer api compliant HTTP urls

View File

@@ -0,0 +1 @@
This repository contains a Javascript library that makes it easy to interact with Relayers that conform to the [Standard Relayer API](https://github.com/0xProject/standard-relayer-api)

View File

@@ -0,0 +1,70 @@
{
"name": "@0xproject/connect",
"version": "0.1.0",
"description": "A javascript library for interacting with the standard relayer api",
"keywords": [
"connect",
"0xproject",
"ethereum",
"tokens",
"exchange"
],
"main": "lib/src/index.js",
"types": "lib/src/index.d.ts",
"scripts": {
"build": "tsc",
"clean": "shx rm -rf _bundles lib test_temp",
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_DIR",
"upload_docs_json": "aws s3 cp generated_docs/index.json $S3_URL --profile 0xproject --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --content-type application/json",
"copy_test_fixtures": "copyfiles -u 2 './test/fixtures/**/*.json' ./lib/test/fixtures",
"lint": "tslint --project . 'src/**/*.ts' 'test/**/*.ts'",
"run_mocha": "mocha lib/test/**/*_test.js",
"test": "run-s clean build copy_test_fixtures run_mocha",
"test:circleci": "yarn test"
},
"repository": {
"type": "git",
"url": "https://github.com/0xProject/0x.js.git"
},
"author": "Brandon Millman",
"license": "Apache-2.0",
"engines": {
"node": ">=6.0.0"
},
"bugs": {
"url": "https://github.com/0xProject/0x.js/issues"
},
"homepage": "https://github.com/0xProject/0x.js/packages/connect/README.md",
"dependencies": {
"0x.js": "^0.26.1",
"@0xproject/assert": "^0.0.5",
"@0xproject/json-schemas": "^0.6.8",
"bignumber.js": "~4.1.0",
"isomorphic-fetch": "^2.2.1",
"lodash": "^4.17.4",
"query-string": "^5.0.1",
"websocket": "^1.0.25"
},
"devDependencies": {
"@0xproject/tslint-config": "^0.1.1",
"@types/fetch-mock": "^5.12.1",
"@types/lodash": "^4.14.77",
"@types/mocha": "^2.2.42",
"@types/query-string": "^5.0.1",
"@types/websocket": "^0.0.34",
"chai": "^4.0.1",
"chai-as-promised": "^7.1.0",
"chai-as-promised-typescript-typings": "0.0.3",
"chai-typescript-typings": "^0.0.1",
"copyfiles": "^1.2.0",
"dirty-chai": "^2.0.1",
"fetch-mock": "^5.13.1",
"mocha": "^4.0.0",
"npm-run-all": "^4.0.2",
"shx": "^0.2.2",
"tslint": "5.8.0",
"typedoc": "~0.8.0",
"typescript": "~2.6.1",
"web3-typescript-typings": "^0.7.1"
}
}

View File

@@ -0,0 +1,40 @@
const execAsync = require('async-child-process').execAsync;
const postpublish_utils = require('../../../scripts/postpublish_utils');
const packageJSON = require('../package.json');
const cwd = __dirname + '/..';
const subPackageName = packageJSON.name;
const S3BucketPath = 's3://connect-docs-jsons/';
let tag;
let version;
postpublish_utils.getLatestTagAndVersionAsync(subPackageName)
.then(function(result) {
tag = result.tag;
version = result.version;
const releaseName = postpublish_utils.getReleaseName(subPackageName, version);
return postpublish_utils.publishReleaseNotes(tag, releaseName);
})
.then(function(release) {
console.log('POSTPUBLISH: Release successful, generating docs...');
const jsonFilePath = __dirname + '/../' + postpublish_utils.generatedDocsDirectoryName + '/index.json';
return execAsync(
'JSON_FILE_PATH=' + jsonFilePath + ' PROJECT_DIR=' + __dirname + '/.. yarn docs:json',
{
cwd,
}
);
})
.then(function(result) {
if (result.stderr !== '') {
throw new Error(result.stderr);
}
const fileName = 'v' + version + '.json';
console.log('POSTPUBLISH: Doc generation successful, uploading docs... as ', fileName);
const s3Url = S3BucketPath + fileName;
return execAsync('S3_URL=' + s3Url + ' yarn upload_docs_json', {
cwd,
});
}).catch (function(err) {
throw err;
});

6
packages/connect/src/globals.d.ts vendored Normal file
View File

@@ -0,0 +1,6 @@
declare module 'dirty-chai';
declare module '*.json' {
const value: any;
export default value;
}

View File

@@ -0,0 +1,171 @@
import {SignedOrder} from '0x.js';
import {assert} from '@0xproject/assert';
import {schemas} from '@0xproject/json-schemas';
import {BigNumber} from 'bignumber.js';
import 'isomorphic-fetch';
import * as _ from 'lodash';
import * as queryString from 'query-string';
import {schemas as clientSchemas} from './schemas/schemas';
import {
Client,
FeesRequest,
FeesResponse,
HttpRequestOptions,
HttpRequestType,
OrderbookRequest,
OrderbookResponse,
OrdersRequest,
TokenPairsItem,
TokenPairsRequest,
} from './types';
import {typeConverters} from './utils/type_converters';
// TODO: move this and bigNumberConfigs in the 0x.js package into one place
BigNumber.config({
EXPONENTIAL_AT: 1000,
});
/**
* This class includes all the functionality related to interacting with a set of HTTP endpoints
* that implement the standard relayer API v0
*/
export class HttpClient implements Client {
private apiEndpointUrl: string;
/**
* Instantiates a new HttpClient instance
* @param url The base url for making API calls
* @return An instance of HttpClient
*/
constructor(url: string) {
assert.isHttpUrl('url', url);
this.apiEndpointUrl = url;
}
/**
* Retrieve token pair info from the API
* @param request A TokenPairsRequest instance describing specific token information
* to retrieve
* @return The resulting TokenPairsItems that match the request
*/
public async getTokenPairsAsync(request?: TokenPairsRequest): Promise<TokenPairsItem[]> {
if (!_.isUndefined(request)) {
assert.doesConformToSchema('request', request, clientSchemas.relayerTokenPairsRequestSchema);
}
const requestOpts = {
params: request,
};
const tokenPairs = await this._requestAsync('/token_pairs', HttpRequestType.Get, requestOpts);
assert.doesConformToSchema(
'tokenPairs', tokenPairs, schemas.relayerApiTokenPairsResponseSchema);
_.each(tokenPairs, (tokenPair: object) => {
typeConverters.convertStringsFieldsToBigNumbers(tokenPair, [
'tokenA.minAmount',
'tokenA.maxAmount',
'tokenB.minAmount',
'tokenB.maxAmount',
]);
});
return tokenPairs;
}
/**
* Retrieve orders from the API
* @param request An OrdersRequest instance describing specific orders to retrieve
* @return The resulting SignedOrders that match the request
*/
public async getOrdersAsync(request?: OrdersRequest): Promise<SignedOrder[]> {
if (!_.isUndefined(request)) {
assert.doesConformToSchema('request', request, clientSchemas.relayerOrdersRequestSchema);
}
const requestOpts = {
params: request,
};
const orders = await this._requestAsync(`/orders`, HttpRequestType.Get, requestOpts);
assert.doesConformToSchema('orders', orders, schemas.signedOrdersSchema);
_.each(orders, (order: object) => typeConverters.convertOrderStringFieldsToBigNumber(order));
return orders;
}
/**
* Retrieve a specific order from the API
* @param orderHash An orderHash generated from the desired order
* @return The SignedOrder that matches the supplied orderHash
*/
public async getOrderAsync(orderHash: string): Promise<SignedOrder> {
assert.doesConformToSchema('orderHash', orderHash, schemas.orderHashSchema);
const order = await this._requestAsync(`/order/${orderHash}`, HttpRequestType.Get);
assert.doesConformToSchema('order', order, schemas.signedOrderSchema);
typeConverters.convertOrderStringFieldsToBigNumber(order);
return order;
}
/**
* Retrieve an orderbook from the API
* @param request An OrderbookRequest instance describing the specific orderbook to retrieve
* @return The resulting OrderbookResponse that matches the request
*/
public async getOrderbookAsync(request: OrderbookRequest): Promise<OrderbookResponse> {
assert.doesConformToSchema('request', request, clientSchemas.relayerOrderBookRequestSchema);
const requestOpts = {
params: request,
};
const orderBook = await this._requestAsync('/orderbook', HttpRequestType.Get, requestOpts);
assert.doesConformToSchema('orderBook', orderBook, schemas.relayerApiOrderBookResponseSchema);
typeConverters.convertOrderbookStringFieldsToBigNumber(orderBook);
return orderBook;
}
/**
* Retrieve fee information from the API
* @param request A FeesRequest instance describing the specific fees to retrieve
* @return The resulting FeesResponse that matches the request
*/
public async getFeesAsync(request: FeesRequest): Promise<FeesResponse> {
assert.doesConformToSchema('request', request, schemas.relayerApiFeesPayloadSchema);
typeConverters.convertBigNumberFieldsToStrings(request, [
'makerTokenAmount',
'takerTokenAmount',
'expirationUnixTimestampSec',
'salt',
]);
const requestOpts = {
payload: request,
};
const fees = await this._requestAsync('/fees', HttpRequestType.Post, requestOpts);
assert.doesConformToSchema('fees', fees, schemas.relayerApiFeesResponseSchema);
typeConverters.convertStringsFieldsToBigNumbers(fees, ['makerFee', 'takerFee']);
return fees;
}
/**
* Submit a signed order to the API
* @param signedOrder A SignedOrder instance to submit
*/
public async submitOrderAsync(signedOrder: SignedOrder): Promise<void> {
assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
const requestOpts = {
payload: signedOrder,
};
await this._requestAsync('/order', HttpRequestType.Post, requestOpts);
}
private async _requestAsync(path: string, requestType: HttpRequestType,
requestOptions?: HttpRequestOptions): Promise<any> {
const params = _.get(requestOptions, 'params');
const payload = _.get(requestOptions, 'payload');
let query = '';
if (!_.isUndefined(params) && !_.isEmpty(params)) {
const stringifiedParams = queryString.stringify(params);
query = `?${stringifiedParams}`;
}
const url = `${this.apiEndpointUrl}/v0${path}${query}`;
const headers = new Headers({
'content-type': 'application/json',
});
const response = await fetch(url, {
method: requestType,
body: JSON.stringify(payload),
headers,
});
if (!response.ok) {
throw Error(response.statusText);
}
const json = await response.json();
return json;
}
}

View File

@@ -0,0 +1,11 @@
export {HttpClient} from './http_client';
export {
Client,
FeesRequest,
FeesResponse,
OrderbookRequest,
OrderbookResponse,
OrdersRequest,
TokenPairsItem,
TokenPairsRequest,
} from './types';

View File

@@ -0,0 +1,8 @@
export const relayerOrderBookRequestSchema = {
id: '/RelayerOrderBookRequest',
type: 'object',
properties: {
baseTokenAddress: {$ref: '/Address'},
quoteTokenAddress: {$ref: '/Address'},
},
};

View File

@@ -0,0 +1,8 @@
export const relayerOrderBookRequestSchema = {
id: '/RelayerOrderBookRequest',
type: 'object',
properties: {
baseTokenAddress: {$ref: '/Address'},
quoteTokenAddress: {$ref: '/Address'},
},
};

View File

@@ -0,0 +1,16 @@
export const relayerOrdersRequestSchema = {
id: '/RelayerOrdersRequest',
type: 'object',
properties: {
exchangeContractAddress: {$ref: '/Address'},
tokenAddress: {$ref: '/Address'},
makerTokenAddress: {$ref: '/Address'},
takerTokenAddress: {$ref: '/Address'},
tokenA: {$ref: '/Address'},
tokenB: {$ref: '/Address'},
maker: {$ref: '/Address'},
taker: {$ref: '/Address'},
trader: {$ref: '/Address'},
feeRecipient: {$ref: '/Address'},
},
};

View File

@@ -0,0 +1,8 @@
export const relayerTokenPairsRequestSchema = {
id: '/RelayerTokenPairsRequest',
type: 'object',
properties: {
tokenA: {$ref: '/Address'},
tokenB: {$ref: '/Address'},
},
};

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