Compare commits

..

366 Commits

Author SHA1 Message Date
Fabio Berger
dfeea78615 Publish
- 0x.js@0.38.6
 - @0xproject/abi-gen@0.3.4
 - @0xproject/assert@0.2.14
 - @0xproject/base-contract@0.3.6
 - @0xproject/connect@0.6.17
 - @0xproject/contract-wrappers@0.1.1
 - contracts@2.1.35
 - @0xproject/dev-utils@0.4.6
 - @0xproject/fill-scenarios@0.0.6
 - @0xproject/json-schemas@0.8.3
 - @0xproject/metacoin@0.0.10
 - @0xproject/migrations@0.0.10
 - @0xproject/order-utils@0.0.9
 - @0xproject/order-watcher@0.0.8
 - @0xproject/react-docs-example@0.0.15
 - @0xproject/react-docs@0.0.16
 - @0xproject/react-shared@0.2.3
 - @0xproject/sol-compiler@0.5.4
 - @0xproject/sol-cov@0.1.3
 - @0xproject/sra-report@0.1.6
 - @0xproject/subproviders@0.10.6
 - @0xproject/testnet-faucets@1.0.36
 - @0xproject/typescript-typings@0.4.3
 - @0xproject/utils@0.7.3
 - @0xproject/web3-wrapper@0.7.3
 - @0xproject/website@0.0.39
2018-07-18 15:10:58 +02:00
Fabio Berger
c8b93adcd0 Updated CHANGELOGS 2018-07-18 15:10:52 +02:00
Fabio Berger
2b02ddc588 Merge pull request #885 from 0xProject/bug-fixes
Development Bug Fixes
2018-07-18 14:21:21 +02:00
Fabio Berger
80c7c23151 Add missing dep 2018-07-18 12:55:49 +02:00
Fabio Berger
c068b574e5 Add PR nr. 2018-07-17 18:49:00 +02:00
Fabio Berger
9a20d4e1c9 Update comments 2018-07-17 18:48:53 +02:00
Fabio Berger
cca471a1ce Add back ethers-contracts types for Aquaduct 2018-07-17 17:05:37 +02:00
Fabio Berger
66d63e8f4f Add isVerbose flag to contract-wrappers subscribe methods 2018-07-17 16:55:55 +02:00
Fabio Berger
e678fed55b Fix bug where we accidentally force Blockstream to always call bound methods with latest param 2018-07-17 16:47:10 +02:00
Fabio Berger
9b10349b7c Remove stateLayer option from OrderWatcher 2018-07-17 16:46:06 +02:00
Fabio Berger
48838e1e98 Add .vscode to gitignore 2018-07-10 14:44:49 +02:00
Fabio Berger
eafd666ecd Move sol-compiler to deps to fix type error 2018-07-10 14:44:07 +02:00
Fabio Berger
599554b785 Publish
- 0x.js@0.38.5
 - @0xproject/abi-gen@0.3.3
 - @0xproject/assert@0.2.13
 - @0xproject/base-contract@0.3.5
 - @0xproject/connect@0.6.16
 - @0xproject/contract-wrappers@0.1.0
 - contracts@2.1.34
 - @0xproject/dev-utils@0.4.5
 - @0xproject/fill-scenarios@0.0.5
 - @0xproject/json-schemas@0.8.2
 - @0xproject/metacoin@0.0.9
 - @0xproject/migrations@0.0.9
 - @0xproject/monorepo-scripts@0.2.2
 - @0xproject/order-utils@0.0.8
 - @0xproject/order-watcher@0.0.7
 - @0xproject/react-docs-example@0.0.14
 - @0xproject/react-docs@0.0.15
 - @0xproject/react-shared@0.2.2
 - @0xproject/sol-compiler@0.5.3
 - @0xproject/sol-cov@0.1.2
 - @0xproject/sol-resolver@0.0.8
 - @0xproject/sra-report@0.1.5
 - @0xproject/subproviders@0.10.5
 - @0xproject/testnet-faucets@1.0.35
 - @0xproject/tslint-config@0.4.21
 - @0xproject/types@0.8.2
 - @0xproject/typescript-typings@0.4.2
 - @0xproject/utils@0.7.2
 - @0xproject/web3-wrapper@0.7.2
 - @0xproject/website@0.0.38
2018-07-09 17:24:22 +02:00
Fabio Berger
d57d282cab Updated CHANGELOGS 2018-07-09 17:24:12 +02:00
Fabio Berger
562bef98e2 reset dep cache 2018-07-09 16:57:40 +02:00
Fabio Berger
900f819be8 Use node v9 everywhere 2018-07-09 16:54:34 +02:00
Fabio Berger
e7337c2451 Update yarn.lock 2018-07-09 16:30:46 +02:00
Fabio Berger
dc81193132 Update package so works with node v9 2018-07-09 16:22:46 +02:00
Fabio Berger
fa868b4963 Bump up node version to v9 2018-07-09 16:09:31 +02:00
Fabio Berger
62945ad363 Updated contract-wrappers to use blockstream v5 and stop unsubscribing on blocksteam error 2018-07-09 15:35:08 +02:00
Fabio Berger
61c38d35be Update yarn.lock 2018-07-09 14:14:03 +02:00
Fabio Berger
4e0ec72896 Merge branch 'development' of github.com:0xProject/0x-monorepo into development
* 'development' of github.com:0xProject/0x-monorepo:
  Add missing import
  Extend from DecodedLogArgs and fix type names
  Update ethers typings & changelog
  Back-port order-watcher changes from v2-prototype
  Back-port over utils changes from v2-prototype
2018-07-09 14:10:29 +02:00
Fabio Berger
c28289e9a8 Back-port prePublish fixes 2018-07-09 14:05:29 +02:00
Fabio Berger
e7e9ddf232 remove excess new line 2018-07-09 14:03:17 +02:00
Fabio Berger
f03784ba37 update web3-provider-engine in subproviders 2018-07-09 14:01:47 +02:00
Fabio Berger
2445e23c0b Merge pull request #842 from 0xProject/back-port-v2-prototype
Back-port changes from v2-prototype in order to publish working Order-watcher
2018-07-09 13:53:15 +02:00
Fabio Berger
cd29483187 merge development 2018-07-09 13:52:21 +02:00
Fabio Berger
9bacbdab48 Add missing import 2018-07-09 13:47:33 +02:00
Fabio Berger
551d484fb7 Extend from DecodedLogArgs and fix type names 2018-07-09 13:03:53 +02:00
Fabio Berger
ff66432b83 Update ethers typings & changelog 2018-07-09 12:33:44 +02:00
Fabio Berger
a7ae82a2d1 Back-port order-watcher changes from v2-prototype 2018-07-09 12:31:06 +02:00
Fabio Berger
5f34b5a80e Back-port over utils changes from v2-prototype 2018-07-09 11:48:30 +02:00
Leonid Logvinov
8fca2a8116 Merge pull request #768 from galkin/development
Improve 'web3-provider-engine' typings
2018-06-27 09:24:33 +03:00
Nikita Galkin
5472500119 Improve 'web3-provider-engine' typings 2018-06-25 12:22:54 +03:00
Fabio Berger
8fb5c29b4b Publish
- 0x.js@0.38.4
 - @0xproject/abi-gen@0.3.2
 - @0xproject/assert@0.2.12
 - @0xproject/base-contract@0.3.4
 - @0xproject/connect@0.6.15
 - @0xproject/contract-wrappers@0.0.5
 - contracts@2.1.33
 - @0xproject/dev-utils@0.4.4
 - @0xproject/fill-scenarios@0.0.4
 - @0xproject/json-schemas@0.8.1
 - @0xproject/metacoin@0.0.8
 - @0xproject/migrations@0.0.8
 - @0xproject/monorepo-scripts@0.2.1
 - @0xproject/order-utils@0.0.7
 - @0xproject/order-watcher@0.0.6
 - @0xproject/react-docs-example@0.0.13
 - @0xproject/react-docs@0.0.14
 - @0xproject/react-shared@0.2.1
 - @0xproject/sol-compiler@0.5.2
 - @0xproject/sol-cov@0.1.1
 - @0xproject/sol-resolver@0.0.7
 - @0xproject/sra-report@0.1.4
 - @0xproject/subproviders@0.10.4
 - @0xproject/testnet-faucets@1.0.34
 - @0xproject/tslint-config@0.4.20
 - @0xproject/types@0.8.1
 - @0xproject/typescript-typings@0.4.1
 - @0xproject/utils@0.7.1
 - @0xproject/web3-wrapper@0.7.1
 - @0xproject/website@0.0.37
2018-06-19 10:48:07 +02:00
Fabio Berger
40a061a5ca Updated CHANGELOGS 2018-06-19 10:48:00 +02:00
Fabio Berger
2ef82592a3 Improve error message 2018-06-19 10:36:19 +02:00
Fabio Berger
14b5448d70 Add missing timestamp 2018-06-19 10:35:22 +02:00
Fabio Berger
e7d45e47bf Remove the hotfix for Ethersjs and instead update to the fixed version in all packages 2018-06-19 10:30:49 +02:00
Fabio Berger
28268d4355 Update versions and CHANGELOG's to account for unpublished versions on NPM 2018-06-18 23:18:42 +02:00
Fabio Berger
50fa02c1d1 Small fixes 2018-06-18 23:16:44 +02:00
Fabio Berger
b36ff9103d Merge pull request #718 from 0xProject/improvement/publishing-flow
Improve Pre-publishing flow
2018-06-18 23:01:36 +02:00
Fabio Berger
f032c2466c Use semver package instead of getNextPatchVersion 2018-06-18 19:22:31 +02:00
Fabio Berger
b63ddc9be4 Use semver external librarty instead of semverUtils 2018-06-18 19:00:39 +02:00
Fabio Berger
171430b617 small fixes 2018-06-18 17:58:17 +02:00
Fabio Berger
d561043774 Show all errors of a given kind at once rather then throwing after the first instance is encountered 2018-06-18 17:41:03 +02:00
Fabio Berger
b1871e9ddd fix package.json 2018-06-18 16:57:22 +02:00
Fabio Berger
b4a5e7258c Add the following prePublish checks:
- That package version matches latest NPM package version (including unpublished versions)
- That changelogs are properly formatted (lastEntry version >= currentVersion, no accidental timestamps)
- Checks for and removes any git tags locally and remotely that might be left-over from a previous failed publish

Moved changelog related helpers to changelogUtils and other small cleanup refactors.
2018-06-18 16:55:59 +02:00
Fabio Berger
3c75debdf9 Remove the remove_tags script 2018-06-18 16:46:54 +02:00
Fabio Berger
84d1053f73 Add missing timestamp to web3-wrapper changelog 2018-06-15 17:11:30 +02:00
Fabio Berger
f9df42f5d9 Fix incorrect merges 2018-06-15 16:58:36 +02:00
Leonid Logvinov
4414ef0a0f fix cherry-pick 2018-06-15 16:51:13 +02:00
Leonid Logvinov
b7729ada38 fix cherry-pick 2018-06-15 16:48:29 +02:00
Leonid Logvinov
3da67feeb2 Add prepublish_checks 2018-06-15 16:45:18 +02:00
Leonid Logvinov
8a0d563a32 Add CHANGELOG entry 2018-06-15 16:44:48 +02:00
Leonid Logvinov
612fc4a949 Fix cherry-pick 2018-06-15 16:44:35 +02:00
Fabio Berger
bf915ce403 Merge pull request #709 from 0xProject/feature/pin-deps
[DEVELOPMENT] Ethersjs Issue Hot Fix
2018-06-15 14:14:45 +02:00
Fabio Berger
0f9ea9773e Add lib/test and ganache.log to npmignore 2018-06-15 14:14:30 +02:00
Fabio Berger
447a3a6c26 Fix prettier 2018-06-15 13:53:26 +02:00
Fabio Berger
f1cc16c44d Export OrderWatcherConfig from 0x.js 2018-06-15 13:38:25 +02:00
Fabio Berger
aae16b6343 Add ganache.log to gitignore 2018-06-15 13:37:08 +02:00
Fabio Berger
834e1538d1 Fix typos, versions and other mistypings 2018-06-15 11:48:52 +02:00
Leonid Logvinov
afc489bc2c Pin all external dependencies 2018-06-14 21:25:36 -07:00
Leonid Logvinov
3e061e7364 Fix the is not a function bug caused by breaking patch version https://github.com/ethers-io/ethers.js/issues/201 2018-06-14 12:31:57 -07:00
Leonid Logvinov
6395c2a8b2 Update changelogs 2018-06-04 11:19:59 -07:00
Leonid Logvinov
c8225288cd v0.7.0 2018-06-04 11:15:00 -07:00
Leonid Logvinov
4a108aa67d Set default params and jsonrpc in Web3Wrapper._sendRawPayloadAsync 2018-06-04 11:11:18 -07:00
Leonid Logvinov
fd9b3e0dcf Add default jsonRpcId to raw payloads sent from web3Wrapper 2018-06-01 16:01:04 -07:00
Leonid Logvinov
f94b647e61 Publish
- 0x.js@0.38.3
 - contracts@2.1.32
 - @0xproject/order-watcher@0.0.5
 - @0xproject/sra-report@0.1.3
 - @0xproject/testnet-faucets@1.0.33
 - @0xproject/website@0.0.36
2018-05-29 11:29:07 -07:00
Leonid Logvinov
2eccc3efaf Updated CHANGELOGS 2018-05-29 11:29:01 -07:00
Leonid Logvinov
972341725e Remove UMD bundles from order-watcher 2018-05-29 11:13:50 -07:00
Leonid Logvinov
40b10fd29d Publish
- 0x.js@0.38.2
 - @0xproject/contract-wrappers@0.0.4
 - contracts@2.1.31
 - @0xproject/order-watcher@0.0.4
 - @0xproject/sra-report@0.1.2
 - @0xproject/testnet-faucets@1.0.32
 - @0xproject/website@0.0.35
2018-05-29 11:12:33 -07:00
Leonid Logvinov
b31fcffc76 Updated CHANGELOGS 2018-05-29 11:12:26 -07:00
Leonid Logvinov
ec222ea0cd Remove UMD bundles from contract-wrappers 2018-05-29 11:04:00 -07:00
Leonid Logvinov
5533220da0 Publish
- 0x.js@0.38.1
 - @0xproject/connect@0.6.14
 - @0xproject/contract-wrappers@0.0.3
 - contracts@2.1.30
 - @0xproject/fill-scenarios@0.0.3
 - @0xproject/order-utils@0.0.6
 - @0xproject/order-watcher@0.0.3
 - @0xproject/sra-report@0.1.1
 - @0xproject/testnet-faucets@1.0.31
 - @0xproject/website@0.0.34
2018-05-29 11:01:25 -07:00
Leonid Logvinov
6ee7024457 Updated CHANGELOGS 2018-05-29 11:01:18 -07:00
Fabio Berger
f839ac9c58 Merge branch 'development' of github.com:0xProject/0x-monorepo into development
* 'development' of github.com:0xProject/0x-monorepo:
  Correct documentation variable name
  Publish
  Updated CHANGELOGS
  Updated CHANGELOGS
  Change publish command name
2018-05-22 16:39:15 -07:00
Fabio Berger
1a8b1460a6 Fix signature verification test 2018-05-22 16:38:57 -07:00
Leonid Logvinov
feac0779a4 Merge pull request #608 from prettymuchbryce/docs-fix
Correct documentation variable name
2018-05-22 15:38:27 -07:00
Bryce Neal
d9eeb0421c Correct documentation variable name 2018-05-22 13:37:38 -07:00
Leonid Logvinov
031f97e97c Publish
- 0x.js@0.38.0
 - @0xproject/abi-gen@0.3.0
 - @0xproject/assert@0.2.10
 - @0xproject/base-contract@0.3.2
 - @0xproject/connect@0.6.13
 - @0xproject/contract-wrappers@0.0.2
 - contracts@2.1.29
 - @0xproject/dev-utils@0.4.2
 - @0xproject/fill-scenarios@0.0.2
 - @0xproject/json-schemas@0.7.24
 - @0xproject/metacoin@0.0.7
 - @0xproject/migrations@0.0.6
 - @0xproject/monorepo-scripts@0.1.20
 - @0xproject/order-utils@0.0.5
 - @0xproject/order-watcher@0.0.2
 - @0xproject/react-docs-example@0.0.12
 - @0xproject/react-docs@0.0.12
 - @0xproject/react-shared@0.1.7
 - @0xproject/sol-compiler@0.5.0
 - @0xproject/sol-cov@0.0.11
 - @0xproject/sol-resolver@0.0.5
 - @0xproject/sra-report@0.1.0
 - @0xproject/subproviders@0.10.2
 - @0xproject/testnet-faucets@1.0.30
 - @0xproject/tslint-config@0.4.18
 - @0xproject/types@0.7.0
 - @0xproject/typescript-typings@0.3.2
 - @0xproject/utils@0.6.2
 - @0xproject/web3-wrapper@0.6.4
 - @0xproject/website@0.0.33
2018-05-22 10:26:47 -07:00
Leonid Logvinov
b9e1c3c34f Updated CHANGELOGS 2018-05-22 10:26:39 -07:00
Leonid Logvinov
1a35107a1d Updated CHANGELOGS 2018-05-22 10:16:53 -07:00
Leonid Logvinov
d3e086c850 Change publish command name 2018-05-22 10:16:53 -07:00
Fabio Berger
ab9cfd293b remove generated contract_wrappers during clean 2018-05-22 09:21:20 -07:00
Fabio Berger
cc840a6911 Merge pull request #594 from 0xProject/improvement/addCustomTslintRules
Add more tslint rules
2018-05-22 18:04:50 +02:00
Fabio Berger
c4a2f70017 Make lint run in parallel 2018-05-21 18:36:06 -07:00
Alex Browne
a26cc7c14d Merge pull request #597 from 0xProject/make-promises-safe
Use make-promises-safe to catch unhandled rejections in tests
2018-05-17 11:58:31 -07:00
Fabio Berger
7fab782907 Improve naming 2018-05-17 14:07:55 +02:00
Fabio Berger
cf7967e629 Disable magic number rule in more places where it isn't helping code readability 2018-05-17 14:07:44 +02:00
Fabio Berger
0eacbac8f6 Merge branch 'development' into improvement/addCustomTslintRules
* development:
  Remove "Order utils" from menu for now
  Fix top tokens key
  Improve about page descriptions
  Do not remove artifacts when running `clean`
2018-05-17 13:57:51 +02:00
Fabio Berger
cec76c33b6 Remove "Order utils" from menu for now 2018-05-17 13:21:37 +02:00
Brandon Millman
18dcf98998 Fix top tokens key 2018-05-16 18:07:47 -07:00
Alex Browne
251218af8b Use make-promises-safe to catch unhandled rejections in tests 2018-05-16 17:36:37 -07:00
fragosti
c06ed58582 Improve about page descriptions 2018-05-16 10:15:04 -07:00
Fabio Berger
4de6221825 Do not remove artifacts when running clean 2018-05-16 16:08:15 +02:00
Fabio Berger
22f3f57f44 Merge branch 'development' into improvement/addCustomTslintRules
* development:
  fix style errors
  Fix circular dependency
  Add my profile image to images
  Add myself to about page
  Add dogfood configs to website
  Change minimum Node version to 6.12
  Document Node.js version requirement and add it to package.json
2018-05-16 15:15:23 +02:00
Fabio Berger
b2f362225c Fix comments 2018-05-16 15:14:31 +02:00
Fabio Berger
40ed59ce28 Improve name 2018-05-16 15:14:24 +02:00
Fabio Berger
839db68571 Fix TSLint rules 2018-05-16 14:59:10 +02:00
Fabio Berger
fec6ac3ff0 Enforce new rules, including no-switch-case-fall-through 2018-05-16 14:58:28 +02:00
Fabio Berger
45fa26dc6c Implement boolean variable naming custom TSLint rule 2018-05-16 14:58:01 +02:00
Fabio Berger
f49d432fdc Implement custom no-magic-numbers rule that doesn't include magic numbers passed into BigNumber instantiations (e.g const amount = new BigNumber(5); ) 2018-05-16 14:57:28 +02:00
Fabio Berger
1a31ceff8e Run linter sequentially 2018-05-16 14:56:11 +02:00
Francesco Agosti
cc486cb86d Merge pull request #593 from 0xProject/bug/website/fix-cirular-dependency
Fix circular dependency
2018-05-15 16:35:05 -07:00
Francesco Agosti
7a45a579c0 Merge pull request #592 from 0xProject/feature/website/add-francesco-about
Add myself to about page
2018-05-15 15:59:24 -07:00
fragosti
dc58d539c2 fix style errors 2018-05-15 15:54:17 -07:00
fragosti
2ba78eb740 Fix circular dependency 2018-05-15 15:27:27 -07:00
fragosti
f43b275f16 Add my profile image to images 2018-05-15 14:50:33 -07:00
fragosti
509a81a572 Add myself to about page 2018-05-15 14:44:57 -07:00
Brandon Millman
184232ba4f Add dogfood configs to website 2018-05-15 13:51:43 -07:00
Alex Browne
0bc338ba42 Merge pull request #578 from 0xProject/document-node-version
Document Node.js version requirement and add it to package.json
2018-05-15 10:51:49 -07:00
Fabio Berger
406e91d387 Merge pull request #588 from 0xProject/improvement/use-wsrun
Individual package building & watching!!! 💪 🌹
2018-05-15 11:41:51 +02:00
Fabio Berger
473acafd14 Revert to lerna:run lint 2018-05-15 11:21:49 +02:00
Fabio Berger
7474e6b1c9 Do lint sequentially 2018-05-15 11:05:02 +02:00
Fabio Berger
323955277c Exclude monorepo-scripts from tslint as test 2018-05-15 10:47:00 +02:00
Fabio Berger
03b5b09122 Fix prettier 2018-05-15 10:43:41 +02:00
Fabio Berger
fe00c06d4b Merge development 2018-05-15 10:22:22 +02:00
Brandon Millman
ca08dd9705 Add hover state to top tokens 2018-05-15 00:52:51 -07:00
Brandon Millman
b3e53b609b Change to weekly txn volume 2018-05-14 22:49:08 -07:00
Alex Browne
fdeab0475c Change minimum Node version to 6.12 2018-05-14 18:46:53 -07:00
Alex Browne
f86cc0dc7a Document Node.js version requirement and add it to package.json 2018-05-14 18:46:52 -07:00
Alex Browne
0457c959dd Merge pull request #590 from 0xProject/fix-prettier
Apply prettier to some files which were not formatted correctly
2018-05-14 18:41:45 -07:00
Alex Browne
c520b7f1fb Apply prettier to some files which were not formatted correctly 2018-05-14 15:44:09 -07:00
Fabio Berger
5422bf5733 Fix TSLint issues 2018-05-14 23:27:41 +02:00
Fabio Berger
a703160226 Merge branch 'development' into improvement/use-wsrun
* development:
  Update ethereeumjs-testrpc to ganache-cli

# Conflicts:
#	package.json
2018-05-14 22:31:53 +02:00
Fabio Berger
d0905eda49 Fix TSLint issues 2018-05-14 21:48:46 +02:00
Leonid Logvinov
da60008048 Update ethereeumjs-testrpc to ganache-cli 2018-05-14 20:16:13 +02:00
Fabio Berger
7c023233f2 Fix infinite loop 2018-05-14 20:02:41 +02:00
Fabio Berger
1e7003a307 Add changelog entries for packages where executable binary exporting fixed 2018-05-14 19:57:41 +02:00
Fabio Berger
8cb074657d Rename bin to server in testnet-faucets since bin is no longer gitignored 2018-05-14 19:33:45 +02:00
Fabio Berger
5f72b86ce4 Fix sra-report binary 2018-05-14 19:33:23 +02:00
Fabio Berger
09d33792f3 rename build:watch to watch and remove build from docs:stage 2018-05-14 19:32:52 +02:00
Fabio Berger
a6773b85d2 Fix sol-compiler binary so it can be called directly from packages 2018-05-14 19:32:32 +02:00
Fabio Berger
5f678acf46 Fix abi-gen binary so it can be called directly from packages 2018-05-14 19:31:56 +02:00
Fabio Berger
76f9ad0705 Remove build from docs:stage commands 2018-05-14 19:24:47 +02:00
Fabio Berger
478f6ed011 Move from using lerna multi-package commands to wsrun, update README's accordingly 2018-05-14 19:23:50 +02:00
Fabio Berger
c94d1b2275 Merge branch 'development' of github.com:0xProject/0x-monorepo into development
* 'development' of github.com:0xProject/0x-monorepo:
  Add missing type definitions
2018-05-14 11:30:51 +02:00
Fabio Berger
7d60356fac Remove tslint-config as dep to monorepo-scripts to avoid circular dependency. Since monorepo-scripts is only expected to be used from within the monorepo, we reference tslint-config w/ a relative path 2018-05-14 11:30:15 +02:00
Leonid Logvinov
58fa35641d Merge pull request #585 from 0xProject/feature/typedef
Add missing type definitions. Enable typedef linter rule
2018-05-14 10:36:13 +02:00
Leonid Logvinov
b74957acdf Add missing type definitions 2018-05-14 10:35:13 +02:00
Fabio Berger
6aed4fb1ae Merge pull request #579 from 0xProject/breakUp0xjs
Split 0x.js into: contract-wrappers & order-watcher
2018-05-11 19:11:27 +02:00
Fabio Berger
ad8e12eeae Add missing .gitkeeps 2018-05-11 18:54:33 +02:00
Fabio Berger
31763a018c Revert "Remove gitkeeps"
This reverts commit 3f6876c419.
2018-05-11 18:50:50 +02:00
Fabio Berger
bc20f8a004 improve wording 2018-05-11 18:24:07 +02:00
Fabio Berger
3f6876c419 Remove gitkeeps 2018-05-11 17:41:35 +02:00
Fabio Berger
fb9c774558 Create coverage dir if doesn't exist 2018-05-11 17:41:25 +02:00
Fabio Berger
7df9393d29 Add compilerSettings to compiler.json 2018-05-11 16:26:08 +02:00
Fabio Berger
c6439def2c Add deployedBytecode to artifacts since it is needed by sol-cov 2018-05-11 16:25:52 +02:00
Fabio Berger
273d3445e4 Revert throw conditions since it messes with the expected test timing 2018-05-11 16:04:03 +02:00
Fabio Berger
bc3dc52377 Revert back to hack, we need the configured web3Wrapper 2018-05-11 15:40:19 +02:00
Fabio Berger
ef1d484d9e Add comment to TransactionReceiptWithDecodedLogs explaining that it doesn't always return "decodedLogs" 2018-05-11 15:39:15 +02:00
Fabio Berger
63cd5a6296 Get rid of hack 2018-05-11 15:24:31 +02:00
Fabio Berger
657dc785ea Get networkId from web3Wrapper 2018-05-11 15:23:50 +02:00
Fabio Berger
461e74d8be Throw if tx reverts 2018-05-11 15:23:34 +02:00
Fabio Berger
a7daea1728 Remove unused methods and imports 2018-05-11 15:22:57 +02:00
Fabio Berger
c4416f9696 Prettier ignore artifact files 2018-05-11 14:45:50 +02:00
Fabio Berger
f9ad34170d Add compiler dep 2018-05-11 14:25:48 +02:00
Fabio Berger
45f2a8ad06 Update yarn.lock 2018-05-11 13:31:49 +02:00
Fabio Berger
3dad802c90 Fix version 2018-05-11 13:18:13 +02:00
Fabio Berger
735166f06c remove unused modules 2018-05-11 13:15:41 +02:00
Fabio Berger
042df52e5c Fix deps 2018-05-11 13:15:21 +02:00
Fabio Berger
294a65f842 Fix prettier 2018-05-11 13:11:50 +02:00
Fabio Berger
bf8550ae1e Update artifacts 2018-05-11 12:59:14 +02:00
Fabio Berger
91549ef28c Update yarn.lock 2018-05-11 12:58:45 +02:00
Fabio Berger
95956eff64 Update global_hooks 2018-05-11 12:58:34 +02:00
Fabio Berger
bcae71dfa4 Remove legacy test 2018-05-11 12:33:39 +02:00
Fabio Berger
d370296e82 Merge branch 'development' into breakUp0xjs
* development:
  Fix ganache subprovider config
  Fix a bug in compiler config precedence
  Fix linter errors
  Fix templates
  Remove unused deployer docs configs
  Add a legacy endpoint for the deployer
  Add a check for compiler output
  Add a comment
  Put ARTIFACTS_VERSION in a config
  Improve a comment
  Remove _applyDefaultsToDeployTxDataAsync
  Add a HACK comment
  Fix linter issues
  Rename deployer to sol-compiler
  Remove deployer
  Remove deployer from 0x.js and migrations
  Configure migrations with a compiler.json
  Remove deployer from metacoin and contract tests
  Update wallet footer and add remove token functionality

# Conflicts:
#	.gitignore
#	packages/0x.js/package.json
#	packages/0x.js/src/0x.ts
#	packages/contracts/package.json
#	packages/contracts/test/multi_sig_with_time_lock.ts
#	packages/contracts/test/multi_sig_with_time_lock_except_remove_auth_addr.ts
#	packages/contracts/util/artifacts.ts
#	packages/deployer/test/deployer_test.ts
#	packages/migrations/package.json
2018-05-11 12:32:57 +02:00
Leonid Logvinov
f42f608f3f Merge pull request #574 from 0xProject/feature/rm-rf-deployer
Remove @0xproject/deployer.Deployer. Make contracts able to deploy themselves
2018-05-11 12:12:39 +02:00
Fabio Berger
f78b5741c3 Add missing version directory to path 2018-05-11 12:05:46 +02:00
Fabio Berger
733fe5b335 Add artifacts to clean command 2018-05-11 12:05:32 +02:00
Leonid Logvinov
c093aab350 Fix ganache subprovider config 2018-05-11 11:59:08 +02:00
Brandon Millman
44f17c1706 Merge pull request #580 from 0xProject/feature/website/remove-tokens
Update wallet footer and add remove token functionality
2018-05-10 10:55:17 -07:00
Fabio Berger
8302e1687a Remove unnecessary compile command 2018-05-10 19:03:58 +02:00
Fabio Berger
7ad4380653 Standardize gitignores and remove migrations/artifacts 2018-05-10 19:02:59 +02:00
Fabio Berger
bea185ce8b Commit v1 artifacts to migrations package and remove compile step from prebuild 2018-05-10 19:02:41 +02:00
Fabio Berger
5a73b8a8e6 Replace mkdir with mkdirp so it also created any missing intermediate directories 2018-05-10 18:56:32 +02:00
Fabio Berger
da62a0af3b Fix path to artifacts 2018-05-10 18:55:30 +02:00
Leonid Logvinov
1137abfd33 Fix a bug in compiler config precedence 2018-05-10 18:26:44 +02:00
Leonid Logvinov
e972ed8456 Fix linter errors 2018-05-10 18:12:34 +02:00
Leonid Logvinov
2e1c2d9dfe Fix templates 2018-05-10 17:56:57 +02:00
Fabio Berger
83dd333eba Fix tslint errors 2018-05-10 17:55:27 +02:00
Leonid Logvinov
f854f3ee2b Remove unused deployer docs configs 2018-05-10 17:47:38 +02:00
Leonid Logvinov
1055ca6d44 Add a legacy endpoint for the deployer 2018-05-10 17:47:38 +02:00
Leonid Logvinov
a5fea3b9c3 Add a check for compiler output 2018-05-10 17:47:38 +02:00
Leonid Logvinov
62f1430a2c Add a comment 2018-05-10 17:47:38 +02:00
Leonid Logvinov
1dec6a442e Put ARTIFACTS_VERSION in a config 2018-05-10 17:47:38 +02:00
Leonid Logvinov
97831e3702 Improve a comment 2018-05-10 17:47:38 +02:00
Leonid Logvinov
7eb9444458 Remove _applyDefaultsToDeployTxDataAsync 2018-05-10 17:47:38 +02:00
Leonid Logvinov
ebc296ea31 Add a HACK comment 2018-05-10 17:47:38 +02:00
Leonid Logvinov
75d24dea0e Fix linter issues 2018-05-10 17:47:38 +02:00
Leonid Logvinov
a6f72de09d Rename deployer to sol-compiler 2018-05-10 17:47:38 +02:00
Leonid Logvinov
96037aed52 Remove deployer 2018-05-10 17:46:57 +02:00
Leonid Logvinov
f9d80adaee Remove deployer from 0x.js and migrations 2018-05-10 17:46:57 +02:00
Leonid Logvinov
422e5a19d4 Configure migrations with a compiler.json 2018-05-10 17:46:57 +02:00
Leonid Logvinov
3d58b38e4e Remove deployer from metacoin and contract tests 2018-05-10 17:46:57 +02:00
Fabio Berger
0a044199a1 Add missing DummyToken 2018-05-10 17:29:59 +02:00
Fabio Berger
cd5f00ac4d Merge branch 'development' into breakUp0xjs
* development: (38 commits)
  Add fallback image support to relayer grid tile
  Clear relayer grid state when fetching
  Configure the compiler to generate artifacts with deployedBytecode
  Implement loading and error state for relayer grid
  Fallback image for relayer grid tile
  Change relayer grid tile to link on header
  Display top tokens from backend
  Remove overflowZ property from portal
  Suggestions and fix bad merge
  Fix typo
  Only show untracked tokens
  Make wallet scrollable
  Add token flow
  Update The Ocean logo
  Fix artifacts paths
  Create an artifacts folder
  Introduce a var
  Add removeHexPrefix util method
  CHeck if ABI exists
  Improve the readability of the check for should compile
  ...

# Conflicts:
#	.gitignore
#	packages/contracts/test/multi_sig_with_time_lock.ts
#	packages/contracts/test/multi_sig_with_time_lock_except_remove_auth_addr.ts
#	packages/contracts/util/artifacts.ts
2018-05-10 17:08:07 +02:00
Fabio Berger
23c4027c83 Add missing uuid types 2018-05-10 16:53:12 +02:00
Fabio Berger
eeb08b7fae Fix type error for latched on property 2018-05-10 16:53:03 +02:00
Fabio Berger
20beb2bdb6 Add generated contracts in contract-wrappers to gitignore 2018-05-10 16:52:47 +02:00
Fabio Berger
c6882d0bd8 Rename zeroExContract... to contractWrappers... 2018-05-10 16:51:45 +02:00
Fabio Berger
ce47e83939 Update yarn.lock 2018-05-10 16:41:05 +02:00
Fabio Berger
832e1e2cf7 Add missing quote 2018-05-10 15:26:19 +02:00
Fabio Berger
6d61616492 Add PR number 2018-05-10 15:23:17 +02:00
Fabio Berger
d5304fb5bd Remove provider instance variable 2018-05-10 15:23:04 +02:00
Fabio Berger
13a61db289 Add var returns 2018-05-10 15:22:51 +02:00
Fabio Berger
93b74cc766 Remove unneeded tslint disable 2018-05-10 15:22:33 +02:00
Fabio Berger
28e83c21e2 Remove uneeded tslint config 2018-05-10 15:22:13 +02:00
Fabio Berger
33ed5cd437 Remove generated contract wrappers 2018-05-10 15:21:37 +02:00
Fabio Berger
37c8e21f25 Remove extra tslint config 2018-05-10 15:00:06 +02:00
Fabio Berger
7b726650e9 Improve createOrderWatcherAsync 2018-05-10 14:59:54 +02:00
Fabio Berger
d3adb48c2e Fix no-any-propagation 2018-05-10 14:59:37 +02:00
Fabio Berger
9838124abc Remove unnecessary tslint config 2018-05-10 14:59:10 +02:00
Fabio Berger
4df847c349 Add pr number to changelogs 2018-05-10 14:58:15 +02:00
Brandon Millman
c64ad1af28 Add fallback image support to relayer grid tile 2018-05-09 17:29:02 -07:00
Brandon Millman
e83b056bd4 Clear relayer grid state when fetching 2018-05-09 15:59:53 -07:00
Brandon Millman
eba6dcc497 Update wallet footer and add remove token functionality 2018-05-09 15:46:18 -07:00
Fabio Berger
017b5a23d8 Fix website and 0x.js docs 2018-05-09 23:26:51 +02:00
Leonid Logvinov
c7a147f49d Configure the compiler to generate artifacts with deployedBytecode 2018-05-09 23:14:44 +02:00
Fabio Berger
f84a466d16 Remove last artifact 2018-05-09 22:15:35 +02:00
Fabio Berger
382a805c7e Remove artifacts 2018-05-09 22:14:19 +02:00
Fabio Berger
0b38e575d6 Fix package.json 2018-05-09 22:08:41 +02:00
Fabio Berger
209266dbed Split 0x.js into contract-wrappers, order-watcher but keep 0x.js as a unifying library with the same interface 2018-05-09 20:36:28 +02:00
Brandon Millman
20f6d8d3d0 Implement loading and error state for relayer grid 2018-05-09 10:57:26 -07:00
Brandon Millman
09b26645ee Fallback image for relayer grid tile 2018-05-09 10:04:28 -07:00
Brandon Millman
9f2258ebd9 Change relayer grid tile to link on header 2018-05-09 09:28:57 -07:00
Brandon Millman
71e2ee62e4 Merge pull request #576 from 0xProject/feature/website/top-tokens
Display top tokens from backend
2018-05-08 14:30:26 -07:00
Brandon Millman
6c8ee4d55d Merge pull request #557 from 0xProject/feature/website/top-bar-redesign
Redesign top bar for portal v2
2018-05-08 14:29:30 -07:00
Brandon Millman
f94d4b492d Display top tokens from backend 2018-05-08 11:32:44 -07:00
Brandon Millman
e01a4fcbb4 Merge branch 'development' into feature/website/top-bar-redesign
* development:
  Remove overflowZ property from portal
  Fix typo
  Only show untracked tokens
  Make wallet scrollable
  Add token flow
2018-05-08 11:17:00 -07:00
Brandon Millman
5ed9b8b1dc Remove overflowZ property from portal 2018-05-08 11:16:12 -07:00
Brandon Millman
17f3d5f6ba Suggestions and fix bad merge 2018-05-08 11:12:46 -07:00
Brandon Millman
607d738342 Merge branch 'development' into feature/website/top-bar-redesign
* development: (63 commits)
  Update The Ocean logo
  Fix artifacts paths
  Create an artifacts folder
  Introduce a var
  Add removeHexPrefix util method
  CHeck if ABI exists
  Improve the readability of the check for should compile
  Use named constants
  Add a comment
  Fix comments
  Rename args to constructor-args
  Fix a typo
  Define a separator const
  Move artifacts from src/artifacts to artifacts/v1
  Fix sol-cov to work with the new artifacts format
  Implement new artifacts format
  Publish
  Updated CHANGELOGS
  Make node types a dependency
  Fix type errors in CSS properties
  ...
2018-05-08 11:04:31 -07:00
Brandon Millman
1b102f9ed3 Merge pull request #570 from 0xProject/feature/website/wallet-add-tokens
Portal v2 add tokens flow
2018-05-08 11:01:40 -07:00
Brandon Millman
6c38481550 Fix typo 2018-05-08 10:17:04 -07:00
Brandon Millman
9cbd151658 Only show untracked tokens 2018-05-08 10:16:08 -07:00
Brandon Millman
419b670aa3 Make wallet scrollable 2018-05-08 10:16:08 -07:00
Brandon Millman
a44874d2eb Add token flow 2018-05-08 10:16:08 -07:00
Brandon Millman
e9d70b7b1e Merge pull request #556 from 0xProject/feature/website/portal-v2
Add new top-level portal component with wallet and relayer index layout
2018-05-08 10:14:33 -07:00
Fabio Berger
73c6f11c9c Update The Ocean logo 2018-05-08 10:47:35 +02:00
Leonid Logvinov
a9c5488620 Merge pull request #537 from 0xProject/feature/artifacts-v2
Implement the new artifacts format
2018-05-07 14:46:28 +02:00
Leonid Logvinov
906af858a5 Fix artifacts paths 2018-05-07 14:32:17 +02:00
Leonid Logvinov
b699a61f56 Create an artifacts folder 2018-05-07 14:23:24 +02:00
Leonid Logvinov
8eabc49e9d Introduce a var 2018-05-07 14:06:00 +02:00
Leonid Logvinov
9e67e12732 Add removeHexPrefix util method 2018-05-07 14:04:58 +02:00
Leonid Logvinov
2d30183d65 CHeck if ABI exists 2018-05-07 13:57:03 +02:00
Leonid Logvinov
fcb0a05880 Improve the readability of the check for should compile 2018-05-07 13:49:21 +02:00
Leonid Logvinov
fad7dc9f04 Use named constants 2018-05-07 13:46:44 +02:00
Leonid Logvinov
7c1e05d33c Add a comment 2018-05-07 13:42:47 +02:00
Leonid Logvinov
02147f546e Fix comments 2018-05-07 13:41:50 +02:00
Leonid Logvinov
3d51bc1ada Rename args to constructor-args 2018-05-07 13:40:53 +02:00
Leonid Logvinov
95df4433dc Fix a typo 2018-05-07 13:40:05 +02:00
Leonid Logvinov
0f1589a43f Define a separator const 2018-05-07 13:37:21 +02:00
Leonid Logvinov
27262c4e56 Move artifacts from src/artifacts to artifacts/v1 2018-05-07 13:32:24 +02:00
Leonid Logvinov
c9b8f2a397 Fix sol-cov to work with the new artifacts format 2018-05-07 10:52:28 +02:00
Leonid Logvinov
72b2a1c66f Implement new artifacts format 2018-05-07 10:23:08 +02:00
Leonid Logvinov
69a6166b6a Publish
- 0x.js@0.37.2
 - @0xproject/abi-gen@0.2.13
 - @0xproject/assert@0.2.9
 - @0xproject/base-contract@0.3.1
 - @0xproject/connect@0.6.12
 - contracts@2.1.28
 - @0xproject/deployer@0.4.3
 - @0xproject/dev-utils@0.4.1
 - @0xproject/json-schemas@0.7.23
 - @0xproject/metacoin@0.0.6
 - @0xproject/migrations@0.0.5
 - @0xproject/order-utils@0.0.4
 - @0xproject/react-docs-example@0.0.11
 - @0xproject/react-docs@0.0.11
 - @0xproject/react-shared@0.1.6
 - @0xproject/sol-cov@0.0.10
 - @0xproject/sol-resolver@0.0.4
 - @0xproject/sra-report@0.0.14
 - @0xproject/subproviders@0.10.1
 - @0xproject/testnet-faucets@1.0.29
 - @0xproject/types@0.6.3
 - @0xproject/typescript-typings@0.3.1
 - @0xproject/utils@0.6.1
 - @0xproject/web3-wrapper@0.6.3
 - @0xproject/website@0.0.32
2018-05-05 01:55:12 +02:00
Leonid Logvinov
bf87b1a6af Updated CHANGELOGS 2018-05-05 01:55:04 +02:00
Leonid Logvinov
2e8a5602b2 Make node types a dependency 2018-05-05 01:33:35 +02:00
Leonid Logvinov
0ec1c4ad6d Fix type errors in CSS properties 2018-05-05 01:26:02 +02:00
Leonid Logvinov
15a3a8c62f Use a single version of react types 2018-05-05 01:13:22 +02:00
Leonid Logvinov
f001181e39 Revert yarn.lock changes 2018-05-05 01:10:48 +02:00
Leonid Logvinov
2c659d3d82 Publish
- @0xproject/react-docs-example@0.0.10
 - @0xproject/react-docs@0.0.10
 - @0xproject/react-shared@0.1.5
 - @0xproject/website@0.0.31
2018-05-04 23:55:03 +02:00
Leonid Logvinov
5ffff7397e Updated CHANGELOGS 2018-05-04 23:54:57 +02:00
Leonid Logvinov
1a36459ab8 Fix property name 2018-05-04 22:41:39 +02:00
Leonid Logvinov
33cc79c13b Upgrade react types version 2018-05-04 21:17:07 +02:00
Leonid Logvinov
b4cb21b55e Publish
- 0x.js@0.37.1
 - contracts@2.1.27
 - @0xproject/order-utils@0.0.3
 - @0xproject/sra-report@0.0.13
 - @0xproject/testnet-faucets@1.0.28
 - @0xproject/website@0.0.30
2018-05-04 20:44:18 +02:00
Leonid Logvinov
ae68c3abe4 Updated CHANGELOGS 2018-05-04 20:44:12 +02:00
Brandon Millman
939e2c70c4 Add headers to wallet and relayer index 2018-05-04 11:04:58 -07:00
Brandon Millman
14b29172b1 Add scrolling to relayer index 2018-05-04 11:04:58 -07:00
Brandon Millman
58794fc8e9 Lay out wallet and relayers 2018-05-04 11:04:58 -07:00
Leonid Logvinov
91fdd6fc29 Make a negligible change to order-utils to publish a new version 2018-05-04 19:07:02 +02:00
Leonid Logvinov
8dd9124863 Publish
- 0x.js@0.37.0
 - @0xproject/abi-gen@0.2.12
 - @0xproject/assert@0.2.8
 - @0xproject/base-contract@0.3.0
 - @0xproject/connect@0.6.11
 - contracts@2.1.26
 - @0xproject/deployer@0.4.2
 - @0xproject/dev-utils@0.4.0
 - @0xproject/json-schemas@0.7.22
 - @0xproject/metacoin@0.0.5
 - @0xproject/migrations@0.0.4
 - @0xproject/monorepo-scripts@0.1.19
 - @0xproject/order-utils@0.0.2
 - @0xproject/react-docs-example@0.0.9
 - @0xproject/react-docs@0.0.9
 - @0xproject/react-shared@0.1.4
 - @0xproject/sol-cov@0.0.9
 - @0xproject/sol-resolver@0.0.3
 - @0xproject/sra-report@0.0.12
 - @0xproject/subproviders@0.10.0
 - @0xproject/testnet-faucets@1.0.27
 - @0xproject/tslint-config@0.4.17
 - @0xproject/types@0.6.2
 - @0xproject/typescript-typings@0.3.0
 - @0xproject/utils@0.6.0
 - @0xproject/web3-wrapper@0.6.2
 - @0xproject/website@0.0.29
2018-05-04 12:16:17 +02:00
Leonid Logvinov
3fc99dbad5 Updated CHANGELOGS 2018-05-04 12:16:11 +02:00
Leonid Logvinov
01dd84dced Add order utils docs to the menu 2018-05-04 12:09:46 +02:00
Brandon Millman
6b92ef733c Open relayer app when clicking on grid tile 2018-05-03 13:59:08 -07:00
Brandon Millman
fe0f4ae257 Add header images to relayer grid tiles 2018-05-03 13:59:00 -07:00
Fabio Berger
cf9555debc Fix logo left padding on mobile 2018-05-03 12:35:21 +02:00
Fabio Berger
528008b1a9 Add new section to homepage 2018-05-03 12:35:07 +02:00
Brandon Millman
5e3576ed69 Remove id property from WebsiteBackendRelayerInfo 2018-05-02 17:03:59 -07:00
Leonid Logvinov
28ee9e247e Add order-utils to monorepo-scripts 2018-05-02 20:00:06 +03:00
Leonid Logvinov
a054b485d0 Merge pull request #559 from 0xProject/feature/order-utils
Move order utils to @0xproject/order-utils
2018-05-02 19:42:59 +03:00
Leonid Logvinov
3585326d7e Fix signature utils tests 2018-05-02 19:30:32 +03:00
Leonid Logvinov
a6046af024 Stop exporting assertions from order-utils 2018-05-02 18:38:50 +03:00
Leonid Logvinov
adaff92c92 Create wrapper functions so that docs render properly 2018-05-02 16:01:01 +03:00
Leonid Logvinov
0499541e11 Move order utils to @0xproject/order-utils 2018-05-02 15:10:24 +03:00
Brandon Millman
f08738e133 Add Greg and Remco to the about page 2018-05-01 17:11:06 -07:00
Brandon Millman
1fbdc14734 Merge pull request #550 from 0xProject/feature/website/crypto-compare-prices
Grab wallet price information by token symbol
2018-05-01 10:09:04 -07:00
Jacob Evans
3e683162e9 Merge pull request #568 from 0xProject/bug/0x.js/trade-simulator-trading-zrx
Execute Taker side in trade simulation
2018-05-01 21:55:49 +10:00
Jacob Evans
8e7937bdb6 Update comment to be more descriptive of null address in exchange simulator 2018-05-01 19:06:17 +10:00
Jacob Evans
b36587fac8 Execute taker side in trade simulation
Fill if the taker address is open
2018-05-01 14:43:47 +10:00
Brandon Millman
3a1f9d01e8 Remove WETH special case, website backend handles this now 2018-04-30 16:49:47 -07:00
Brandon Millman
1131d66b3d Hit website backend for price information 2018-04-30 16:40:02 -07:00
Brandon Millman
7104ae4752 Merge pull request #564 from 0xProject/add-code-of-conduct-1
Create CODE_OF_CONDUCT.md
2018-04-30 09:47:33 -07:00
Brandon Millman
2403323463 Style suggestions 2018-04-27 15:05:23 -07:00
Brandon Millman
feb7dfffa1 Move quote currency string into config 2018-04-27 15:05:23 -07:00
Brandon Millman
005e633e2a yarn.lock 2018-04-27 15:05:00 -07:00
Brandon Millman
127fe971e9 Prettier 2018-04-27 14:50:04 -07:00
Brandon Millman
3c4bde6ea1 Create CODE_OF_CONDUCT.md 2018-04-27 14:09:25 -07:00
Brandon Millman
dc19690863 Merge branch 'development' into feature/website/crypto-compare-prices
* development:
  Fix react type versions to avoid minor version bumps with breaking changes
  Update Web3 Provider Engine to 14.0.4
  Remove auto-assignment of everyone to PR's
  Check for Yarn instead of npm
  Add hack comment about the use of sudo
  Fix lazy load component name
  Rename Portal and PortalMenu components to LegacyPortal and LegacyPortalMenu
  Remove unnecessary additional params
  Remove outside declaration
  Capitalize yarn
  Use path for platform independence
  Consolidate github personal access token env to one place: constants.ts
  Use methods moved to utils since now shared by multiple scripts
  Add comment
  Improve comments
  Add checks for the required local setup before running the publish script
  Add descriptions for all commands in monorepo-scripts
  Add removeGitTags script that can be run after a failed Lerna publish
2018-04-26 17:11:01 -07:00
Jacob Evans
47604384d4 Merge pull request #555 from 0xProject/feature/subproviders/upgrade-provider-engine
Update Web3 Provider Engine to 14.0.4
2018-04-26 15:44:55 +10:00
Fabio Berger
c69984e309 Fix react type versions to avoid minor version bumps with breaking changes 2018-04-24 20:06:09 +09:00
Brandon Millman
b8c611de2b ProviderDisplay changes 2018-04-24 01:11:01 -07:00
Brandon Millman
9c827a0298 Top bar expanded display type 2018-04-23 23:47:37 -07:00
Brandon Millman
766aeaa9e1 Relayer grid spacing tweaks 2018-04-23 23:47:04 -07:00
Brandon Millman
567768c66a Add headers to wallet and relayer index 2018-04-23 22:17:26 -07:00
Brandon Millman
deaa5f3211 Add scrolling to relayer index 2018-04-23 21:45:05 -07:00
Jacob Evans
5682cd0048 Update Web3 Provider Engine to 14.0.4 2018-04-24 14:33:32 +10:00
Brandon Millman
11f1ccf3ff Lay out wallet and relayers 2018-04-23 21:17:23 -07:00
Fabio Berger
2896110d4d Merge branch 'development' of github.com:0xProject/0x-monorepo into development
* 'development' of github.com:0xProject/0x-monorepo:
  Fix lazy load component name
  Rename Portal and PortalMenu components to LegacyPortal and LegacyPortalMenu
2018-04-24 13:01:15 +09:00
Fabio Berger
d05b175e04 Remove auto-assignment of everyone to PR's 2018-04-24 12:53:54 +09:00
Brandon Millman
10a379077c Merge pull request #552 from 0xProject/refactor/website/legacy-portal
Rename Portal component to LegacyPortal
2018-04-23 22:42:07 -04:00
Fabio Berger
ffd9b79100 Check for Yarn instead of npm 2018-04-24 10:43:44 +09:00
Fabio Berger
04c07d9006 Merge pull request #541 from 0xProject/improveMonorepoScripts
Improve Monorepo-scripts
2018-04-24 10:34:40 +09:00
Fabio Berger
a3cc5c1dd7 Add hack comment about the use of sudo 2018-04-24 10:32:44 +09:00
Brandon Millman
941342cc24 Fix lazy load component name 2018-04-23 16:49:53 -07:00
Brandon Millman
cc471dd127 Rename Portal and PortalMenu components to LegacyPortal and LegacyPortalMenu 2018-04-23 14:27:11 -07:00
Brandon Millman
9b535e3cec Rename baseCurrency to quoteCurrency 2018-04-22 14:20:42 -04:00
Brandon Millman
9656895726 Remove some unused imports 2018-04-22 14:17:34 -04:00
Brandon Millman
121b6949a1 Rate limit crypto compare calls 2018-04-22 14:05:03 -04:00
Brandon Millman
fb31c49317 Refactor common fetch logic into fetch_utils 2018-04-22 13:28:13 -04:00
Brandon Millman
e51f9b3593 Grab price information from crypto compare api 2018-04-22 13:10:58 -04:00
Amir Bandeali
d08bfbf705 Merge pull request #545 from 0xProject/feature/deployer/solidity-0.4.23
Feature/deployer/solidity 0.4.23
2018-04-20 13:55:49 -07:00
Amir Bandeali
a10e466fed Fix getABIEncodedTransactionData in contract templates 2018-04-20 13:54:33 -07:00
Amir Bandeali
35bb010c35 Add support for solidity 0.4.23 2018-04-20 13:54:28 -07:00
Brandon Millman
0046a0762c Merge pull request #543 from 0xProject/feature/website/integrate-relayer-info
Integrate relayer index with website backend
2018-04-20 15:37:41 -04:00
Brandon Millman
c453012a8e Add specific render path for error and loading 2018-04-20 15:36:40 -04:00
Fabio Berger
1f82c7eadf Remove unnecessary additional params 2018-04-20 10:04:22 +09:00
Fabio Berger
b6fb8dbb52 Remove outside declaration 2018-04-20 10:03:53 +09:00
Fabio Berger
30256cbe51 Capitalize yarn 2018-04-20 10:01:21 +09:00
Fabio Berger
7f46e9af2c Use path for platform independence 2018-04-20 10:00:37 +09:00
Fabio Berger
417cec9e04 Consolidate github personal access token env to one place: constants.ts 2018-04-20 09:36:03 +09:00
Jacob Evans
62a55c0135 Merge pull request #540 from 0xProject/feature/abi-gen/tuple-return-types
Support Tuples returned from functions
2018-04-20 08:49:23 +10:00
Jacob Evans
72336eb393 Remove ethers-contracts types 2018-04-20 08:26:10 +10:00
Brandon Millman
12d8c0b6af Integrate relayer index with website backend 2018-04-19 16:28:35 -04:00
Jacob Evans
5c232b6a8d Update CHANGELOGs 2018-04-19 17:16:05 +10:00
Fabio Berger
f6fd4281a4 Add ImToken to landing page 2018-04-19 15:35:12 +09:00
Jacob Evans
4bee63afc6 Interface for EventDescription renamed topics 2018-04-19 16:28:46 +10:00
Jacob Evans
d186f6148b Use ethers in abi_decoder utils 2018-04-19 15:25:04 +10:00
Fabio Berger
2b15c03b9a Use methods moved to utils since now shared by multiple scripts 2018-04-19 14:19:34 +09:00
Fabio Berger
60d879e045 Add comment 2018-04-19 14:16:11 +09:00
Fabio Berger
858d1768ce Improve comments 2018-04-19 14:14:10 +09:00
Fabio Berger
fc2b7f747b Add checks for the required local setup before running the publish script 2018-04-19 14:10:48 +09:00
Jacob Evans
207019c7f3 Add ethers to web3-wrapper 2018-04-19 14:59:10 +10:00
Jacob Evans
b264bbea84 Update 0x.js package json for ethers 2018-04-19 14:57:14 +10:00
Jacob Evans
32efb3e280 Update ethers in metacoin project 2018-04-19 13:44:14 +10:00
Fabio Berger
1a0d68d49a Add descriptions for all commands in monorepo-scripts 2018-04-19 11:56:41 +09:00
Fabio Berger
7dd3b2d38b Add removeGitTags script that can be run after a failed Lerna publish 2018-04-19 11:40:22 +09:00
Fabio Berger
4bc65faf1a Merge pull request #526 from 0xProject/fix/expiration-watcher
Fix expiration watcher comparator
2018-04-19 11:28:18 +09:00
Brandon Millman
8634551f53 Merge pull request #539 from 0xProject/feature/website/backend-client
Implement backendClient object to unify calls to the portal api
2018-04-18 22:25:03 -04:00
Brandon Millman
089663ccc1 Merge pull request #534 from 0xProject/feature/website/integrate-prices
Add price information to wallet
2018-04-18 22:20:03 -04:00
Fabio Berger
d1d26f8bf6 Merge branch 'development' into fix/expiration-watcher
* development:
  Publish
  Updated CHANGELOGS
  Move @0xproject/migrations to devDependencies
  Publish
  Updated CHANGELOGS
  Make @0xproject/migrations public

# Conflicts:
#	packages/0x.js/CHANGELOG.json
#	packages/0x.js/package.json
2018-04-19 10:38:43 +09:00
Fabio Berger
1ca86730fa Remove hack above migrations package 2018-04-19 10:37:13 +09:00
Jacob Evans
12ae7c009d Support Tuples from function returns 2018-04-19 11:21:32 +10:00
Brandon Millman
51b2fce8c1 Implement backendClient object to unify calls to the portal api 2018-04-18 20:12:38 -04:00
Leonid Logvinov
62fcb51e1a Publish
- 0x.js@0.36.3
 - contracts@2.1.25
 - @0xproject/sra-report@0.0.11
 - @0xproject/testnet-faucets@1.0.26
 - @0xproject/website@0.0.28
2018-04-18 21:30:28 +02:00
Leonid Logvinov
cbc55f2ef8 Updated CHANGELOGS 2018-04-18 21:30:20 +02:00
Leonid Logvinov
679f828e4e Move @0xproject/migrations to devDependencies 2018-04-18 21:18:18 +02:00
Leonid Logvinov
4a8b4e7398 Publish
- 0x.js@0.36.2
 - contracts@2.1.24
 - @0xproject/migrations@0.0.3
 - @0xproject/sra-report@0.0.10
 - @0xproject/testnet-faucets@1.0.25
 - @0xproject/website@0.0.27
2018-04-18 19:57:42 +02:00
Leonid Logvinov
b6a11ca31e Updated CHANGELOGS 2018-04-18 19:57:36 +02:00
Leonid Logvinov
a30ccf2b25 Make @0xproject/migrations public 2018-04-18 19:32:53 +02:00
Leonid Logvinov
2574405699 Fix expiration watcher comparator 2018-04-18 13:45:04 +02:00
Fabio Berger
3ba78553f0 Publish
- 0x.js@0.36.1
 - @0xproject/abi-gen@0.2.11
 - @0xproject/assert@0.2.7
 - @0xproject/base-contract@0.2.1
 - @0xproject/connect@0.6.10
 - contracts@2.1.23
 - @0xproject/deployer@0.4.1
 - @0xproject/dev-utils@0.3.6
 - @0xproject/json-schemas@0.7.21
 - @0xproject/metacoin@0.0.4
 - @0xproject/migrations@0.0.2
 - @0xproject/monorepo-scripts@0.1.18
 - @0xproject/react-docs-example@0.0.8
 - @0xproject/react-docs@0.0.8
 - @0xproject/react-shared@0.1.3
 - @0xproject/sol-cov@0.0.8
 - @0xproject/sol-resolver@0.0.2
 - @0xproject/sra-report@0.0.9
 - @0xproject/subproviders@0.9.0
 - @0xproject/testnet-faucets@1.0.24
 - @0xproject/tslint-config@0.4.16
 - @0xproject/types@0.6.1
 - @0xproject/typescript-typings@0.2.0
 - @0xproject/utils@0.5.2
 - @0xproject/web3-wrapper@0.6.1
 - @0xproject/website@0.0.26
2018-04-18 20:16:29 +09:00
Fabio Berger
4d485fc424 Print out stderr 2018-04-18 20:03:50 +09:00
Brandon Millman
39c0064ffb Add price information to wallet 2018-04-18 00:30:52 -04:00
601 changed files with 26919 additions and 11450 deletions

View File

@@ -3,7 +3,7 @@ version: 2
jobs: jobs:
build: build:
docker: docker:
- image: circleci/node:6.12 - image: circleci/node:9
environment: environment:
CONTRACTS_COMMIT_HASH: '9ed05f5' CONTRACTS_COMMIT_HASH: '9ed05f5'
working_directory: ~/repo working_directory: ~/repo
@@ -11,25 +11,25 @@ jobs:
- checkout - checkout
- run: echo 'export PATH=$HOME/CIRCLE_PROJECT_REPONAME/node_modules/.bin:$PATH' >> $BASH_ENV - run: echo 'export PATH=$HOME/CIRCLE_PROJECT_REPONAME/node_modules/.bin:$PATH' >> $BASH_ENV
- restore_cache: - restore_cache:
key: dependency-cache-{{ checksum "package.json" }} key: dependency-cache-v1-{{ checksum "package.json" }}
- run: - run:
name: yarn name: yarn
command: yarn --frozen-lockfile command: yarn --frozen-lockfile
- save_cache: - save_cache:
key: dependency-cache-{{ checksum "package.json" }} key: dependency-cache-v1-{{ checksum "package.json" }}
paths: paths:
- ./node_modules - ./node_modules
- run: wget https://s3.amazonaws.com/testrpc-shapshots/${CONTRACTS_COMMIT_HASH}.zip - run: wget https://s3.amazonaws.com/testrpc-shapshots/${CONTRACTS_COMMIT_HASH}.zip
- run: unzip ${CONTRACTS_COMMIT_HASH}.zip -d testrpc_snapshot - run: unzip ${CONTRACTS_COMMIT_HASH}.zip -d testrpc_snapshot
- run: node ./node_modules/lerna/bin/lerna.js bootstrap - run: node ./node_modules/lerna/bin/lerna.js bootstrap
- run: yarn lerna:run build - run: yarn build
- save_cache: - save_cache:
key: repo-{{ .Environment.CIRCLE_SHA1 }} key: repo-{{ .Environment.CIRCLE_SHA1 }}
paths: paths:
- ~/repo - ~/repo
test-installation: test-installation:
docker: docker:
- image: circleci/node:6.12 - image: circleci/node:9
working_directory: ~/repo working_directory: ~/repo
steps: steps:
- restore_cache: - restore_cache:
@@ -38,7 +38,7 @@ jobs:
- run: yarn test:installation - run: yarn test:installation
test-0xjs: test-0xjs:
docker: docker:
- image: circleci/node:6.12 - image: circleci/node:9
working_directory: ~/repo working_directory: ~/repo
steps: steps:
- restore_cache: - restore_cache:
@@ -48,14 +48,14 @@ jobs:
name: testrpc name: testrpc
command: npm run testrpc -- --db testrpc_snapshot command: npm run testrpc -- --db testrpc_snapshot
background: true background: true
- run: yarn lerna:run --scope 0x.js test:circleci - run: yarn wsrun test:circleci 0x.js
- save_cache: - save_cache:
key: coverage-0xjs-{{ .Environment.CIRCLE_SHA1 }} key: coverage-0xjs-{{ .Environment.CIRCLE_SHA1 }}
paths: paths:
- ~/repo/packages/0x.js/coverage/lcov.info - ~/repo/packages/0x.js/coverage/lcov.info
test-contracts: test-contracts:
docker: docker:
- image: circleci/node:6.12 - image: circleci/node:9
working_directory: ~/repo working_directory: ~/repo
steps: steps:
- restore_cache: - restore_cache:
@@ -65,14 +65,14 @@ jobs:
name: testrpc name: testrpc
command: npm run testrpc -- --db testrpc_snapshot command: npm run testrpc -- --db testrpc_snapshot
background: true background: true
- run: yarn lerna:run --scope contracts test:circleci - run: yarn wsrun test:circleci contracts
- save_cache: - save_cache:
key: coverage-contracts-{{ .Environment.CIRCLE_SHA1 }} key: coverage-contracts-{{ .Environment.CIRCLE_SHA1 }}
paths: paths:
- ~/repo/packages/contracts/coverage/lcov.info - ~/repo/packages/contracts/coverage/lcov.info
test-deployer: test-sol-compiler:
docker: docker:
- image: circleci/node:6.12 - image: circleci/node:9
working_directory: ~/repo working_directory: ~/repo
steps: steps:
- restore_cache: - restore_cache:
@@ -82,14 +82,14 @@ jobs:
name: testrpc name: testrpc
command: npm run testrpc -- --db testrpc_snapshot command: npm run testrpc -- --db testrpc_snapshot
background: true background: true
- run: yarn lerna:run --scope @0xproject/deployer test:circleci - run: yarn wsrun test:circleci @0xproject/sol-compiler
- save_cache: - save_cache:
key: coverage-deployer-{{ .Environment.CIRCLE_SHA1 }} key: coverage-sol-compiler-{{ .Environment.CIRCLE_SHA1 }}
paths: paths:
- ~/repo/packages/deployer/coverage/lcov.info - ~/repo/packages/sol-compiler/coverage/lcov.info
test-rest: test-rest:
docker: docker:
- image: circleci/node:6.12 - image: circleci/node:9
working_directory: ~/repo working_directory: ~/repo
steps: steps:
- restore_cache: - restore_cache:
@@ -99,7 +99,7 @@ jobs:
name: testrpc name: testrpc
command: npm run testrpc -- --db testrpc_snapshot command: npm run testrpc -- --db testrpc_snapshot
background: true background: true
- run: yarn lerna:run --ignore contracts --ignore 0x.js --ignore @0xproject/deployer test:circleci - run: yarn wsrun test:circleci --exclude contracts --exclude 0x.js --exclude @0xproject/sol-compiler --stages --exclude-missing
- save_cache: - save_cache:
key: coverage-assert-{{ .Environment.CIRCLE_SHA1 }} key: coverage-assert-{{ .Environment.CIRCLE_SHA1 }}
paths: paths:
@@ -131,7 +131,7 @@ jobs:
lint: lint:
working_directory: ~/repo working_directory: ~/repo
docker: docker:
- image: circleci/node:6.12 - image: circleci/node:9
steps: steps:
- restore_cache: - restore_cache:
keys: keys:
@@ -140,7 +140,7 @@ jobs:
prettier: prettier:
working_directory: ~/repo working_directory: ~/repo
docker: docker:
- image: circleci/node:6.12 - image: circleci/node:9
steps: steps:
- restore_cache: - restore_cache:
keys: keys:
@@ -148,7 +148,7 @@ jobs:
- run: yarn prettier:ci - run: yarn prettier:ci
submit-coverage: submit-coverage:
docker: docker:
- image: circleci/node:6.12 - image: circleci/node:9
working_directory: ~/repo working_directory: ~/repo
steps: steps:
- restore_cache: - restore_cache:
@@ -177,7 +177,7 @@ jobs:
- coverage-sol-cov-{{ .Environment.CIRCLE_SHA1 }} - coverage-sol-cov-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache: - restore_cache:
keys: keys:
- coverage-deployer-{{ .Environment.CIRCLE_SHA1 }} - coverage-sol-compiler-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache: - restore_cache:
keys: keys:
- coverage-0xjs-{{ .Environment.CIRCLE_SHA1 }} - coverage-0xjs-{{ .Environment.CIRCLE_SHA1 }}
@@ -199,7 +199,7 @@ workflows:
- test-contracts: - test-contracts:
requires: requires:
- build - build
- test-deployer: - test-sol-compiler:
requires: requires:
- build - build
- test-rest: - test-rest:
@@ -214,6 +214,6 @@ workflows:
- submit-coverage: - submit-coverage:
requires: requires:
- test-0xjs - test-0xjs
- test-deployer - test-sol-compiler
- test-rest - test-rest
- test-contracts - test-contracts

27
.gitignore vendored
View File

@@ -67,25 +67,34 @@ generated_docs/
TODO.md TODO.md
# VSCode file
.vscode
packages/website/public/bundle* packages/website/public/bundle*
packages/react-docs/example/public/bundle* packages/react-docs/example/public/bundle*
# generated binaries # server cli
bin/ packages/testnet-faucets/server/
# generated contract artifacts # generated contract artifacts/
packages/sol-cov/test/fixtures/artifacts packages/sol-cov/test/fixtures/artifacts/
packages/metacoin/artifacts packages/metacoin/artifacts/
packages/0x.js/test/artifacts packages/order-watcher/test/artifacts/
packages/migrations/src/artifacts packages/contract-wrappers/test/artifacts/
# generated contract wrappers # generated contract wrappers
packages/0x.js/src/contract_wrappers/generated/ packages/0x.js/src/contract_wrappers/generated/
packages/contracts/src/contract_wrappers/generated/ packages/contracts/src/contract_wrappers/generated/
packages/contract-wrappers/src/contract_wrappers/generated/
packages/metacoin/src/contract_wrappers packages/metacoin/src/contract_wrappers
packages/fill-scenarios/src/generated_contract_wrappers/
packages/order-watcher/src/generated_contract_wrappers/
packages/migrations/src/contract_wrappers
# solc-bin in deployer # solc-bin in sol-compiler
packages/deployer/solc_bin/ packages/sol-compiler/solc_bin/
# Monorepo scripts # Monorepo scripts
packages/*/scripts/ packages/*/scripts/
ganache.log

View File

@@ -1,7 +1,10 @@
lib lib
.nyc_output .nyc_output
/packages/0x.js/test/artifacts
/packages/contracts/src/artifacts /packages/contracts/src/artifacts
/packages/metacoin/artifacts /packages/metacoin/artifacts
/packages/migrations/src/artifacts /packages/contract-wrappers/test/artifacts
/packages/order-watcher/test/artifacts
/packages/migrations/artifacts/1.0.0
package.json package.json
scripts/postpublish_utils.js scripts/postpublish_utils.js

View File

@@ -1 +0,0 @@
* @abandeali1 @BMillman19 @dekz @fabioberger @LogvinovLeon @Recmo

46
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at team@0xproject.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

123
README.md
View File

@@ -17,27 +17,27 @@ This repository is a monorepo including the 0x protocol smart contracts and nume
### Published Packages ### Published Packages
| Package | Version | Description | | Package | Version | Description |
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| [`0x.js`](/packages/0x.js) | [![npm](https://img.shields.io/npm/v/0x.js.svg)](https://www.npmjs.com/package/0x.js) | A Javascript library for interacting with the 0x protocol | | [`0x.js`](/packages/0x.js) | [![npm](https://img.shields.io/npm/v/0x.js.svg)](https://www.npmjs.com/package/0x.js) | A Javascript library for interacting with the 0x protocol |
| [`@0xproject/abi-gen`](/packages/abi-gen) | [![npm](https://img.shields.io/npm/v/@0xproject/abi-gen.svg)](https://www.npmjs.com/package/@0xproject/abi-gen) | Tool to generate TS wrappers from smart contract ABIs | | [`@0xproject/abi-gen`](/packages/abi-gen) | [![npm](https://img.shields.io/npm/v/@0xproject/abi-gen.svg)](https://www.npmjs.com/package/@0xproject/abi-gen) | Tool to generate TS wrappers from smart contract ABIs |
| [`@0xproject/assert`](/packages/assert) | [![npm](https://img.shields.io/npm/v/@0xproject/assert.svg)](https://www.npmjs.com/package/@0xproject/assert) | Type and schema assertions used by our packages | | [`@0xproject/assert`](/packages/assert) | [![npm](https://img.shields.io/npm/v/@0xproject/assert.svg)](https://www.npmjs.com/package/@0xproject/assert) | Type and schema assertions used by our packages |
| [`@0xproject/base-contract`](/packages/base-contract) | [![npm](https://img.shields.io/npm/v/@0xproject/base-contract.svg)](https://www.npmjs.com/package/@0xproject/base-contract) | BaseContract used by auto-generated `abi-gen` wrapper contracts | | [`@0xproject/base-contract`](/packages/base-contract) | [![npm](https://img.shields.io/npm/v/@0xproject/base-contract.svg)](https://www.npmjs.com/package/@0xproject/base-contract) | BaseContract used by auto-generated `abi-gen` wrapper contracts |
| [`@0xproject/connect`](/packages/connect) | [![npm](https://img.shields.io/npm/v/@0xproject/connect.svg)](https://www.npmjs.com/package/@0xproject/connect) | A Javascript library for interacting with the Standard Relayer API | | [`@0xproject/connect`](/packages/connect) | [![npm](https://img.shields.io/npm/v/@0xproject/connect.svg)](https://www.npmjs.com/package/@0xproject/connect) | A Javascript library for interacting with the Standard Relayer API |
| [`@0xproject/deployer`](/packages/deployer) | [![npm](https://img.shields.io/npm/v/@0xproject/deployer.svg)](https://www.npmjs.com/package/@0xproject/deployer) | Solidity project compiler and deployer framework | | [`@0xproject/sol-compiler`](/packages/sol-compiler) | [![npm](https://img.shields.io/npm/v/@0xproject/sol-compiler.svg)](https://www.npmjs.com/package/@0xproject/sol-compiler) | A thin wrapper around Solc.js that outputs artifacts, resolves imports, only re-compiles when needed, and other niceties. |
| [`@0xproject/dev-utils`](/packages/dev-utils) | [![npm](https://img.shields.io/npm/v/@0xproject/dev-utils.svg)](https://www.npmjs.com/package/@0xproject/dev-utils) | Dev utils to be shared across 0x projects and packages | | [`@0xproject/dev-utils`](/packages/dev-utils) | [![npm](https://img.shields.io/npm/v/@0xproject/dev-utils.svg)](https://www.npmjs.com/package/@0xproject/dev-utils) | Dev utils to be shared across 0x projects and packages |
| [`@0xproject/json-schemas`](/packages/json-schemas) | [![npm](https://img.shields.io/npm/v/@0xproject/json-schemas.svg)](https://www.npmjs.com/package/@0xproject/json-schemas) | 0x-related json schemas | | [`@0xproject/json-schemas`](/packages/json-schemas) | [![npm](https://img.shields.io/npm/v/@0xproject/json-schemas.svg)](https://www.npmjs.com/package/@0xproject/json-schemas) | 0x-related json schemas |
| [`@0xproject/monorepo-scripts`](/packages/monorepo-scripts) | [![npm](https://img.shields.io/npm/v/@0xproject/monorepo-scripts.svg)](https://www.npmjs.com/package/@0xproject/monorepo-scripts) | Monorepo scripts | | [`@0xproject/monorepo-scripts`](/packages/monorepo-scripts) | [![npm](https://img.shields.io/npm/v/@0xproject/monorepo-scripts.svg)](https://www.npmjs.com/package/@0xproject/monorepo-scripts) | Monorepo scripts |
| [`@0xproject/react-docs`](/packages/react-docs) | [![npm](https://img.shields.io/npm/v/@0xproject/react-docs.svg)](https://www.npmjs.com/package/@0xproject/react-docs) | React documentation component for rendering TypeDoc & Doxity generated JSON | | [`@0xproject/react-docs`](/packages/react-docs) | [![npm](https://img.shields.io/npm/v/@0xproject/react-docs.svg)](https://www.npmjs.com/package/@0xproject/react-docs) | React documentation component for rendering TypeDoc & Doxity generated JSON |
| [`@0xproject/react-shared`](/packages/react-shared) | [![npm](https://img.shields.io/npm/v/@0xproject/react-shared.svg)](https://www.npmjs.com/package/@0xproject/react-shared) | 0x shared react components | | [`@0xproject/react-shared`](/packages/react-shared) | [![npm](https://img.shields.io/npm/v/@0xproject/react-shared.svg)](https://www.npmjs.com/package/@0xproject/react-shared) | 0x shared react components |
| [`@0xproject/sra-report`](/packages/sra-report) | [![npm](https://img.shields.io/npm/v/@0xproject/sra-report.svg)](https://www.npmjs.com/package/@0xproject/sra-report) | Generate reports for standard relayer API compliance | | [`@0xproject/sra-report`](/packages/sra-report) | [![npm](https://img.shields.io/npm/v/@0xproject/sra-report.svg)](https://www.npmjs.com/package/@0xproject/sra-report) | Generate reports for standard relayer API compliance |
| [`@0xproject/sol-cov`](/packages/sol-cov) | [![npm](https://img.shields.io/npm/v/@0xproject/sol-cov.svg)](https://www.npmjs.com/package/@0xproject/sol-cov) | Solidity test coverage tool | | [`@0xproject/sol-cov`](/packages/sol-cov) | [![npm](https://img.shields.io/npm/v/@0xproject/sol-cov.svg)](https://www.npmjs.com/package/@0xproject/sol-cov) | Solidity test coverage tool |
| [`@0xproject/subproviders`](/packages/subproviders) | [![npm](https://img.shields.io/npm/v/@0xproject/subproviders.svg)](https://www.npmjs.com/package/@0xproject/subproviders) | Useful web3 subproviders (e.g LedgerSubprovider) | | [`@0xproject/subproviders`](/packages/subproviders) | [![npm](https://img.shields.io/npm/v/@0xproject/subproviders.svg)](https://www.npmjs.com/package/@0xproject/subproviders) | Useful web3 subproviders (e.g LedgerSubprovider) |
| [`@0xproject/tslint-config`](/packages/tslint-config) | [![npm](https://img.shields.io/npm/v/@0xproject/tslint-config.svg)](https://www.npmjs.com/package/@0xproject/tslint-config) | Custom 0x development TSLint rules | | [`@0xproject/tslint-config`](/packages/tslint-config) | [![npm](https://img.shields.io/npm/v/@0xproject/tslint-config.svg)](https://www.npmjs.com/package/@0xproject/tslint-config) | Custom 0x development TSLint rules |
| [`@0xproject/types`](/packages/types) | [![npm](https://img.shields.io/npm/v/@0xproject/types.svg)](https://www.npmjs.com/package/@0xproject/types) | Shared type declarations | | [`@0xproject/types`](/packages/types) | [![npm](https://img.shields.io/npm/v/@0xproject/types.svg)](https://www.npmjs.com/package/@0xproject/types) | Shared type declarations |
| [`@0xproject/typescript-typings`](/packages/typescript-typings) | [![npm](https://img.shields.io/npm/v/@0xproject/typescript-typings.svg)](https://www.npmjs.com/package/@0xproject/typescript-typings) | Repository of types for external packages | | [`@0xproject/typescript-typings`](/packages/typescript-typings) | [![npm](https://img.shields.io/npm/v/@0xproject/typescript-typings.svg)](https://www.npmjs.com/package/@0xproject/typescript-typings) | Repository of types for external packages |
| [`@0xproject/utils`](/packages/utils) | [![npm](https://img.shields.io/npm/v/@0xproject/utils.svg)](https://www.npmjs.com/package/@0xproject/utils) | Shared utilities | | [`@0xproject/utils`](/packages/utils) | [![npm](https://img.shields.io/npm/v/@0xproject/utils.svg)](https://www.npmjs.com/package/@0xproject/utils) | Shared utilities |
| [`@0xproject/web3-wrapper`](/packages/web3-wrapper) | [![npm](https://img.shields.io/npm/v/@0xproject/web3-wrapper.svg)](https://www.npmjs.com/package/@0xproject/web3-wrapper) | Web3 wrapper | | [`@0xproject/web3-wrapper`](/packages/web3-wrapper) | [![npm](https://img.shields.io/npm/v/@0xproject/web3-wrapper.svg)](https://www.npmjs.com/package/@0xproject/web3-wrapper) | Web3 wrapper |
### Private Packages ### Private Packages
@@ -56,12 +56,14 @@ Dedicated documentation pages:
* [0x Connect](https://0xproject.com/docs/connect) * [0x Connect](https://0xproject.com/docs/connect)
* [Smart contracts](https://0xproject.com/docs/contracts) * [Smart contracts](https://0xproject.com/docs/contracts)
* [Subproviders](https://0xproject.com/docs/subproviders) * [Subproviders](https://0xproject.com/docs/subproviders)
* [Deployer](https://0xproject.com/docs/deployer) * [Sol Compiler](https://0xproject.com/docs/sol-compiler)
* [Web3-wrapper](https://0xproject.com/docs/web3-wrapper) * [Web3-wrapper](https://0xproject.com/docs/web3-wrapper)
* [JSON-schemas](https://0xproject.com/docs/json-schemas) * [JSON-schemas](https://0xproject.com/docs/json-schemas)
* [Sol-cov](https://0xproject.com/docs/sol-cov) * [Sol-cov](https://0xproject.com/docs/sol-cov)
* [Standard Relayer API](https://github.com/0xProject/standard-relayer-api/blob/master/README.md) * [Standard Relayer API](https://github.com/0xProject/standard-relayer-api/blob/master/README.md)
Node version >= 6.12 is required.
Most of the packages require additional typings for external dependencies. Most of the packages require additional typings for external dependencies.
You can include those by prepending @0xproject/typescript-typings package to your [`typeRoots`](http://www.typescriptlang.org/docs/handbook/tsconfig-json.html) config. You can include those by prepending @0xproject/typescript-typings package to your [`typeRoots`](http://www.typescriptlang.org/docs/handbook/tsconfig-json.html) config.
@@ -91,32 +93,87 @@ yarn install
### Build ### Build
Build all packages. You need to do this before working on any given package. Although these packages To build all packages:
as independent, when run from within the monorepo, they are internally symlinked, to make development
easier. You can change several packages and run the changes without publishing them first to NPM. When
running `rebuild`, Lerna will figure out the dependency order of all the packages, and build them in
this order.
```bash ```bash
yarn lerna:rebuild yarn build
``` ```
Or continuously rebuild on change: To build a specific package:
```bash ```bash
yarn dev PKG=@0xproject/web3-wrapper yarn build
```
### Watch
To re-build all packages on change:
```bash
yarn watch
```
To watch a specific package and all it's dependent packages:
```bash
PKG=[NPM_PACKAGE_NAME] yarn watch
e.g
PKG=@0xproject/web3-wrapper yarn watch
```
### Clean
Clean all packages:
```bash
yarn clean
```
Clean a specific package
```bash
PKG=0x.js yarn clean
```
### Rebuild
To re-build (clean & build) all packages:
```bash
yarn rebuild
```
To re-build (clean & build) a specific package & it's deps:
```bash
PKG=0x.js yarn rebuild
``` ```
### Lint ### Lint
Lint all packages Lint all packages:
```bash ```bash
yarn lerna:run lint yarn lint
```
Lint a specific package:
```bash
PKG=0x.js yarn lint
``` ```
### Run Tests ### Run Tests
Run all tests:
```bash ```bash
yarn lerna:test yarn test
```
Run a specific package's test:
```bash
PKG=@0xproject/web3-wrapper yarn test
``` ```

View File

@@ -1,38 +1,46 @@
{ {
"private": true, "private": true,
"name": "0x-monorepo", "name": "0x-monorepo",
"engines": {
"node" : ">=6.12"
},
"workspaces": [ "workspaces": [
"packages/*" "packages/*"
], ],
"scripts": { "scripts": {
"dev": "lerna run --parallel build:watch", "ganache": "ganache-cli -p 8545 --networkId 50 -m \"${npm_package_config_mnemonic}\"",
"testrpc": "testrpc -p 8545 --networkId 50 -m \"${npm_package_config_mnemonic}\"",
"prettier": "prettier --write '**/*.{ts,tsx,json,md}' --config .prettierrc", "prettier": "prettier --write '**/*.{ts,tsx,json,md}' --config .prettierrc",
"prettier:ci": "prettier --list-different '**/*.{ts,tsx,json,md}' --config .prettierrc", "prettier:ci": "prettier --list-different '**/*.{ts,tsx,json,md}' --config .prettierrc",
"report_coverage": "lcov-result-merger 'packages/*/coverage/lcov.info' | coveralls", "report_coverage": "lcov-result-merger 'packages/*/coverage/lcov.info' | coveralls",
"test:installation": "node ./packages/monorepo-scripts/lib/test_installation.js", "test:installation": "node ./packages/monorepo-scripts/lib/test_installation.js",
"lerna:install": "yarn install", "run:publish": "run-s install:all build:monorepo_scripts script:prepublish_checks rebuild script:publish",
"lerna:run": "lerna run", "run:publish:dry": "run-s install:all build:monorepo_scripts script:prepublish_checks rebuild script:publish:dry",
"lerna:test": "lerna run test", "script:prepublish_checks": "node ./packages/monorepo-scripts/lib/prepublish_checks.js",
"lerna:clean": "lerna run clean",
"lerna:build": "lerna run build",
"lerna:rebuild": "run-s lerna:clean lerna:build",
"lerna:publish": "run-s lerna:install lerna:rebuild script:publish",
"lerna:publish:dry": "run-s lerna:install lerna:rebuild script:publish:dry",
"lerna:stage_docs": "lerna run docs:stage",
"script:publish": "node ./packages/monorepo-scripts/lib/publish.js", "script:publish": "node ./packages/monorepo-scripts/lib/publish.js",
"script:publish:dry": "IS_DRY_RUN=true yarn script:publish" "script:publish:dry": "IS_DRY_RUN=true yarn script:publish",
"install:all": "yarn install",
"wsrun": "wsrun",
"lerna:run": "lerna run",
"watch": "wsrun watch $PKG --fast-exit -r --stages --done-criteria='complete|successfully'",
"build": "wsrun build $PKG --fast-exit -r --stages",
"build:monorepo_scripts": "PKG=@0xproject/monorepo-scripts yarn build",
"clean": "wsrun clean $PKG --fast-exit -r --parallel",
"rebuild": "run-s clean build",
"test": "wsrun test $PKG --serial --exclude-missing",
"stage_docs": "wsrun docs:stage $PKG --parallel --exclude-missing",
"lint": "wsrun lint $PKG --parallel --exclude-missing"
}, },
"config": { "config": {
"mnemonic": "concert load couple harbor equip island argue ramp clarify fence smart topic" "mnemonic": "concert load couple harbor equip island argue ramp clarify fence smart topic"
}, },
"devDependencies": { "devDependencies": {
"async-child-process": "^1.1.1", "async-child-process": "1.1.1",
"coveralls": "^3.0.0", "coveralls": "^3.0.0",
"ethereumjs-testrpc": "^6.0.3", "ganache-cli": "^6.1.0",
"lcov-result-merger": "^2.0.0", "lcov-result-merger": "^3.0.0",
"lerna": "^2.5.1", "lerna": "^2.5.1",
"npm-run-all": "^4.1.2", "npm-run-all": "4.1.2",
"prettier": "^1.11.1" "prettier": "1.12.1",
"wsrun": "^2.2.0"
} }
} }

View File

@@ -9,3 +9,5 @@ test/
/generated_docs/ /generated_docs/
/scripts/ /scripts/
/lib/src/monorepo_scripts/ /lib/src/monorepo_scripts/
/lib/test/
ganache.log

View File

@@ -1,4 +1,131 @@
[ [
{
"timestamp": 1531919263,
"version": "0.38.6",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1531149657,
"version": "0.38.5",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1529397769,
"version": "0.38.4",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1527617805,
"version": "0.38.3",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1527617227,
"version": "0.38.2",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1527616612,
"version": "0.38.1",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "0.38.0",
"changes": [
{
"note": "Renamed createOrderStateWatcher to createOrderWatcherAsync since it is now async",
"pr": 579
},
{
"note":
"Renamed ZeroExError to ContractWrappersErrors since they now lives in the @0xproject/contract-wrappers subpackage",
"pr": 579
}
],
"timestamp": 1527008270
},
{
"timestamp": 1525477860,
"version": "0.37.2",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1525453812,
"version": "0.37.1",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "0.37.0",
"changes": [
{
"note": "Fixed expiration watcher comparator to handle orders with equal expiration times",
"pr": 526
},
{
"note": "Update Web3 Provider Engine to 14.0.4",
"pr": 555
},
{
"note": "Add `zeroEx.getProvider()`",
"pr": 559
},
{
"note": "Move `ZeroExError.InvalidSignature` to `@0xproject/order-utils` `OrderError.InvalidSignature`",
"pr": 559
}
],
"timestamp": 1525428773
},
{
"version": "0.36.3",
"changes": [
{
"note": "Move @0xproject/migrations to devDependencies"
}
],
"timestamp": 1524079658
},
{
"timestamp": 1524073495,
"version": "0.36.2",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{ {
"version": "0.36.1", "version": "0.36.1",
"changes": [ "changes": [

View File

@@ -5,12 +5,64 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG CHANGELOG
## v0.38.6 - _July 18, 2018_
* Dependencies updated
## v0.38.5 - _July 9, 2018_
* Dependencies updated
## v0.38.4 - _June 19, 2018_
* Dependencies updated
## v0.38.3 - _May 29, 2018_
* Dependencies updated
## v0.38.2 - _May 29, 2018_
* Dependencies updated
## v0.38.1 - _May 29, 2018_
* Dependencies updated
## v0.38.0 - _May 22, 2018_
* Renamed createOrderStateWatcher to createOrderWatcherAsync since it is now async (#579)
* Renamed ZeroExError to ContractWrappersErrors since they now lives in the @0xproject/contract-wrappers subpackage (#579)
## v0.37.2 - _May 5, 2018_
* Dependencies updated
## v0.37.1 - _May 4, 2018_
* Dependencies updated
## v0.37.0 - _May 4, 2018_
* Fixed expiration watcher comparator to handle orders with equal expiration times (#526)
* Update Web3 Provider Engine to 14.0.4 (#555)
* Add `zeroEx.getProvider()` (#559)
* Move `ZeroExError.InvalidSignature` to `@0xproject/order-utils` `OrderError.InvalidSignature` (#559)
## v0.36.3 - _April 18, 2018_
* Move @0xproject/migrations to devDependencies
## v0.36.2 - _April 18, 2018_
* Dependencies updated
## v0.36.1 - _April 18, 2018_ ## v0.36.1 - _April 18, 2018_
* Internal changes and refactoring * Internal changes and refactoring
* Fix redundant expired order removal bug (#527) * Fix redundant expired order removal bug (#527)
## v0.36.0 - _April 12, 2018_ ## v0.36.0 - _April 11, 2018_
* Moved Web3.Provider to `@0xproject/types:Provider` (#501) * Moved Web3.Provider to `@0xproject/types:Provider` (#501)
* Add `zeroEx.exchange.getOrderStateAsync` to allow obtaining current OrderState for a signedOrder (#510) * Add `zeroEx.exchange.getOrderStateAsync` to allow obtaining current OrderState for a signedOrder (#510)
@@ -26,16 +78,16 @@ CHANGELOG
* Add `zeroEx.createOrderStateWatcher` to allow creating arbitrary number of OrderStateWatchers (#488) * Add `zeroEx.createOrderStateWatcher` to allow creating arbitrary number of OrderStateWatchers (#488)
* Added `stateLayer` setting to `OrderStateWatcherConfig` so OrderStateWatcher can be set to monitor different blockchain state layers (#488) * Added `stateLayer` setting to `OrderStateWatcherConfig` so OrderStateWatcher can be set to monitor different blockchain state layers (#488)
## v0.33.2 - _March 18, 2018_ ## v0.33.2 - _March 17, 2018_
* Consolidate all `console.log` calls into `logUtils` in the `@0xproject/utils` package (#452) * Consolidate all `console.log` calls into `logUtils` in the `@0xproject/utils` package (#452)
* Consolidate `Order`, `SignedOrder`, and `ECSignature` into the `@0xproject/types` package (#456) * Consolidate `Order`, `SignedOrder`, and `ECSignature` into the `@0xproject/types` package (#456)
## v0.33.1 - _March 8, 2018_ ## v0.33.1 - _March 7, 2018_
* Add missing EthersJs typescript typings as dependency * Add missing EthersJs typescript typings as dependency
## v0.33.0 - _March 4, 2018_ ## v0.33.0 - _March 3, 2018_
* Validate and lowercase all addresses in public methods (#373) * Validate and lowercase all addresses in public methods (#373)
* Improve validation to force passing contract addresses on private networks (#385) * Improve validation to force passing contract addresses on private networks (#385)
@@ -43,54 +95,54 @@ CHANGELOG
* Rename all public `_unsubscribeAll` methods to `unsubscribeAll` (#415) * Rename all public `_unsubscribeAll` methods to `unsubscribeAll` (#415)
* Move web3 typings from devDep to dep since cannot use this package without it (#429) * Move web3 typings from devDep to dep since cannot use this package without it (#429)
## v0.32.2 - _February 9, 2018_ ## v0.32.2 - _February 8, 2018_
* Fix publishing issue where .npmignore was not properly excluding undesired content (#389) * Fix publishing issue where .npmignore was not properly excluding undesired content (#389)
## v0.32.1 - _February 7, 2018_ ## v0.32.1 - _February 6, 2018_
* Reorganized `BlockParamLiteral` export into `@0xproject/types` package (#355) * Reorganized `BlockParamLiteral` export into `@0xproject/types` package (#355)
* Now using `abi-gen` package to generate ContractEventArgs types (#371) * Now using `abi-gen` package to generate ContractEventArgs types (#371)
## v0.32.0 - _February 5, 2018_ ## v0.32.0 - _February 4, 2018_
* Add `zeroEx.etherToken.getContractAddressIfExists` (#350) * Add `zeroEx.etherToken.getContractAddressIfExists` (#350)
* Fixed the bug causing order watcher to throw if there is an event with the same signature but different indexed fields (#366) * Fixed the bug causing order watcher to throw if there is an event with the same signature but different indexed fields (#366)
## v0.31.1 - _February 1, 2018_ ## v0.31.1 - _January 31, 2018_
* Fix the bug causing order watcher to throw if makerToken === zrx (#357) * Fix the bug causing order watcher to throw if makerToken === zrx (#357)
## v0.31.0 - _January 30, 2018_ ## v0.31.0 - _January 29, 2018_
* Add the `shouldAddPersonalMessagePrefix` parameter to `signOrderHashAsync` so that the caller can decide on whether to add the personalMessage prefix before relaying the request to the signer. Parity Signer, Ledger and TestRPC add the prefix themselves, Metamask expects it to have already been added. (#349) * Add the `shouldAddPersonalMessagePrefix` parameter to `signOrderHashAsync` so that the caller can decide on whether to add the personalMessage prefix before relaying the request to the signer. Parity Signer, Ledger and TestRPC add the prefix themselves, Metamask expects it to have already been added. (#349)
## v0.30.2 - _January 29, 2018_ ## v0.30.2 - _January 28, 2018_
* Add Rinkeby testnet addresses to artifacts (#337) * Add Rinkeby testnet addresses to artifacts (#337)
* Move @0xproject/types to dependencies from devDependencies fixing missing type errors * Move @0xproject/types to dependencies from devDependencies fixing missing type errors
## v0.30.1 - _January 24, 2018_ ## v0.30.1 - _January 23, 2018_
* Fix a bug allowing negative fill values (#212) * Fix a bug allowing negative fill values (#212)
* Fix a bug that made it impossible to pass a custom ZRX address (#341) * Fix a bug that made it impossible to pass a custom ZRX address (#341)
## v0.30.0 - _January 17, 2018_ ## v0.30.0 - _January 16, 2018_
* Add an error parameter to the order watcher callback (#312) * Add an error parameter to the order watcher callback (#312)
* Fix a bug making it impossible to catch some errors from awaitTransactionMinedAsync (#312) * Fix a bug making it impossible to catch some errors from awaitTransactionMinedAsync (#312)
* Fix a bug in fillOrdersUpTo validation making it impossible to fill up to if user doesn't have enough balance to fully fill all the orders (#321) * Fix a bug in fillOrdersUpTo validation making it impossible to fill up to if user doesn't have enough balance to fully fill all the orders (#321)
## v0.29.1 - _January 11, 2018_ ## v0.29.1 - _January 10, 2018_
* Fixed bignumber config issue #301 (#305) * Fixed bignumber config issue #301 (#305)
## v0.29.0 - _December 28, 2017_ ## v0.29.0 - _December 27, 2017_
* Assert baseUnit amount supplied to `toUnitAmount` is integer amount. (#287) * Assert baseUnit amount supplied to `toUnitAmount` is integer amount. (#287)
* `toBaseUnitAmount` throws if amount supplied has too many decimals (#287) * `toBaseUnitAmount` throws if amount supplied has too many decimals (#287)
## v0.28.0 - _December 20, 2017_ ## v0.28.0 - _December 19, 2017_
* Add `etherTokenAddress` arg to `depositAsync` and `withdrawAsync` methods on `zeroEx.etherToken` (#267) * Add `etherTokenAddress` arg to `depositAsync` and `withdrawAsync` methods on `zeroEx.etherToken` (#267)
* Removed accidentally included `unsubscribeAll` method from `zeroEx.proxy`, `zeroEx.etherToken` and `zeroEx.tokenRegistry` (#267) * Removed accidentally included `unsubscribeAll` method from `zeroEx.proxy`, `zeroEx.etherToken` and `zeroEx.tokenRegistry` (#267)
@@ -102,11 +154,11 @@ CHANGELOG
* Support `Deposit` and `Withdraw` events on etherToken (#277) * Support `Deposit` and `Withdraw` events on etherToken (#277)
* Improve the error message when taker is not a string (#278) * Improve the error message when taker is not a string (#278)
## v0.27.1 - _November 28, 2017_ ## v0.27.1 - _November 27, 2017_
* Export `TransactionOpts` type * Export `TransactionOpts` type
## v0.27.0 - _November 28, 2017_ ## v0.27.0 - _November 27, 2017_
* Make `ZeroExConfig` required parameter of `ZeroEx` constructor (#233) * Make `ZeroExConfig` required parameter of `ZeroEx` constructor (#233)
* Add a required property `networkId` to `ZeroExConfig` (#233) * Add a required property `networkId` to `ZeroExConfig` (#233)
@@ -118,65 +170,65 @@ CHANGELOG
* All transaction sending methods now call `estimateGas` if no gas amount was supplied (#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) * Modify order validation methods to validate against the `latest` block, not against the `pending` block (#236)
## v0.26.0 - _November 21, 2017_ ## v0.26.0 - _November 20, 2017_
* Add post-formatter for logs converting `blockNumber`, `logIndex`, `transactionIndex` from hexes to numbers (#231) * 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) * 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) * In OrderWatcher subscribe to ZRX Token Transfer and Approval events when maker token is different (#225)
## v0.25.1 - _November 13, 2017_ ## v0.25.1 - _November 12, 2017_
* Standardise on Cancelled over Canceled (#217) * Standardise on Cancelled over Canceled (#217)
* Add missing `DecodedLogEvent` type to exported types (#205) * 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) * 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_ ## v0.23.0 - _November 11, 2017_
* Fixed unhandled promise rejection error in subscribe methods (#209) * Fixed unhandled promise rejection error in subscribe methods (#209)
* Subscribe callbacks now receive an error object as their first argument * Subscribe callbacks now receive an error object as their first argument
## v0.22.6 - _November 10, 2017_ ## v0.22.6 - _November 9, 2017_
* Add a timeout parameter to transaction awaiting (#206) * Add a timeout parameter to transaction awaiting (#206)
## v0.22.5 - _November 7, 2017_ ## v0.22.5 - _November 6, 2017_
* Re-publish v0.22.4 to fix publishing issue * Re-publish v0.22.4 to fix publishing issue
## v0.22.4 - _October 25, 2017_ ## v0.22.4 - _October 24, 2017_
* Upgraded bignumber.js to a new version that ships with native typings * Upgraded bignumber.js to a new version that ships with native typings
## v0.22.3 - _October 25, 2017_ ## v0.22.3 - _October 24, 2017_
* Fixed an issue with new version of testrpc and unlimited proxy allowance (#199) * Fixed an issue with new version of testrpc and unlimited proxy allowance (#199)
## v0.22.2 - _October 24, 2017_ ## v0.22.2 - _October 23, 2017_
* Fixed rounding of maker fill amount and incorrect validation of partial fees (#197) * Fixed rounding of maker fill amount and incorrect validation of partial fees (#197)
## v0.22.0 - _October 16, 2017_ ## v0.22.0 - _October 15, 2017_
* Started using `OrderFillRequest` interface instead of `OrderFillOrKillRequest` interface for `zeroEx.exchange.batchFillOrKill` (#187) * Started using `OrderFillRequest` interface instead of `OrderFillOrKillRequest` interface for `zeroEx.exchange.batchFillOrKill` (#187)
* Removed `OrderFillOrKillRequest` (#187) * Removed `OrderFillOrKillRequest` (#187)
## v0.21.4 - _October 13, 2017_ ## v0.21.4 - _October 12, 2017_
* Made 0x.js more type-safe by making `getLogsAsync` and `subscribe/subscribeAsync` generics parametrized with arg type (#194) * Made 0x.js more type-safe by making `getLogsAsync` and `subscribe/subscribeAsync` generics parametrized with arg type (#194)
## v0.21.3 - _October 12, 2017_ ## v0.21.3 - _October 11, 2017_
* Fixed a bug causing order fills to throw `INSUFFICIENT_TAKER_ALLOWANCE` (#193) * Fixed a bug causing order fills to throw `INSUFFICIENT_TAKER_ALLOWANCE` (#193)
## v0.21.2 - _October 11, 2017_ ## v0.21.2 - _October 10, 2017_
* Exported `ContractEventArg` as a public type (#190) * Exported `ContractEventArg` as a public type (#190)
## v0.21.1 - _October 11, 2017_ ## v0.21.1 - _October 10, 2017_
* Fixed a bug in subscriptions (#189) * Fixed a bug in subscriptions (#189)
## v0.21.0 - _October 10, 2017_ ## v0.21.0 - _October 9, 2017_
* Complete rewrite of subscription logic (#182) * Complete rewrite of subscription logic (#182)
* Subscriptions no longer return historical logs. If you want them - use `getLogsAsync` * Subscriptions no longer return historical logs. If you want them - use `getLogsAsync`
@@ -191,27 +243,27 @@ CHANGELOG
* Renamed `zeroEx.token.stopWatchingAllEventsAsync` to `zeroEx.token.unsubscribeAll` * Renamed `zeroEx.token.stopWatchingAllEventsAsync` to `zeroEx.token.unsubscribeAll`
* Fixed the batch fills validation by emulating all balance & proxy allowance changes (#185) * Fixed the batch fills validation by emulating all balance & proxy allowance changes (#185)
## v0.20.0 - _October 5, 2017_ ## v0.20.0 - _October 4, 2017_
* Add `zeroEx.token.getLogsAsync` (#178) * Add `zeroEx.token.getLogsAsync` (#178)
* Add `zeroEx.exchange.getLogsAsync` (#178) * Add `zeroEx.exchange.getLogsAsync` (#178)
* Fixed fees validation when one of the tokens transferred is ZRX (#181) * Fixed fees validation when one of the tokens transferred is ZRX (#181)
## v0.19.0 - _September 29, 2017_ ## v0.19.0 - _September 28, 2017_
* Made order validation optional (#172) * Made order validation optional (#172)
* Added Ropsten testnet support (#173) * Added Ropsten testnet support (#173)
* Fixed a bug causing awaitTransactionMinedAsync to DDos backend nodes (#175) * Fixed a bug causing awaitTransactionMinedAsync to DDos backend nodes (#175)
## v0.18.0 - _September 26, 2017_ ## v0.18.0 - _September 25, 2017_
* Added `zeroEx.exchange.validateOrderFillableOrThrowAsync` to simplify orderbook pruning (#170) * Added `zeroEx.exchange.validateOrderFillableOrThrowAsync` to simplify orderbook pruning (#170)
## v0.17.0 - _September 26, 2017_ ## v0.17.0 - _September 25, 2017_
* Made `zeroEx.exchange.getZRXTokenAddressAsync` public (#171) * Made `zeroEx.exchange.getZRXTokenAddressAsync` public (#171)
## v0.16.0 - _September 20, 2017_ ## v0.16.0 - _September 19, 2017_
* Added the ability to specify custom contract addresses to be used with 0x.js (#165) * Added the ability to specify custom contract addresses to be used with 0x.js (#165)
* ZeroExConfig.exchangeContractAddress * ZeroExConfig.exchangeContractAddress
@@ -219,48 +271,48 @@ CHANGELOG
* ZeroExConfig.etherTokenContractAddress * ZeroExConfig.etherTokenContractAddress
* Added `zeroEx.tokenRegistry.getContractAddressAsync` (#165) * Added `zeroEx.tokenRegistry.getContractAddressAsync` (#165)
## v0.15.0 - _September 8, 2017_ ## v0.15.0 - _September 7, 2017_
* Added the ability to specify a historical `blockNumber` at which to query the blockchain's state when calling a token or exchange method (#161) * Added the ability to specify a historical `blockNumber` at which to query the blockchain's state when calling a token or exchange method (#161)
## v0.14.2 - _September 7, 2017_ ## v0.14.2 - _September 6, 2017_
* Fixed an issue with bignumber.js types not found (#160) * Fixed an issue with bignumber.js types not found (#160)
## v0.14.1 - _September 7, 2017_ ## v0.14.1 - _September 6, 2017_
* Fixed an issue with Artifact type not found (#159) * Fixed an issue with Artifact type not found (#159)
## v0.14.0 - _September 6, 2017_ ## v0.14.0 - _September 5, 2017_
* Added `zeroEx.exchange.throwLogErrorsAsErrors` method to public interface (#157) * Added `zeroEx.exchange.throwLogErrorsAsErrors` method to public interface (#157)
* Fixed an issue with overlapping async intervals in `zeroEx.awaitTransactionMinedAsync` (#157) * Fixed an issue with overlapping async intervals in `zeroEx.awaitTransactionMinedAsync` (#157)
* Fixed an issue with log decoder returning `BigNumber`s as `strings` (#157) * Fixed an issue with log decoder returning `BigNumber`s as `strings` (#157)
## v0.13.0 - _September 6, 2017_ ## v0.13.0 - _September 5, 2017_
* Made all the functions submitting transactions to the network to immediately return transaction hash (#151) * Made all the functions submitting transactions to the network to immediately return transaction hash (#151)
* Added `zeroEx.awaitTransactionMinedAsync` (#151) * Added `zeroEx.awaitTransactionMinedAsync` (#151)
* Added `TransactionReceiptWithDecodedLogs`, `LogWithDecodedArgs`, `DecodedLogArgs` to public types (#151) * Added `TransactionReceiptWithDecodedLogs`, `LogWithDecodedArgs`, `DecodedLogArgs` to public types (#151)
* Added signature validation to `validateFillOrderThrowIfInvalidAsync` (#152) * Added signature validation to `validateFillOrderThrowIfInvalidAsync` (#152)
## v0.12.1 - _September 2, 2017_ ## v0.12.1 - _September 1, 2017_
* Added the support for web3@1.x.x provider (#142) * Added the support for web3@1.x.x provider (#142)
* Added the optional `zeroExConfig` parameter to the constructor of `ZeroEx` (#139) * Added the optional `zeroExConfig` parameter to the constructor of `ZeroEx` (#139)
* Added the ability to specify `gasPrice` when instantiating `ZeroEx` (#139) * Added the ability to specify `gasPrice` when instantiating `ZeroEx` (#139)
## v0.11.0 - _August 24, 2017_ ## v0.11.0 - _August 23, 2017_
* Added `zeroEx.token.setUnlimitedProxyAllowanceAsync` (#137) * Added `zeroEx.token.setUnlimitedProxyAllowanceAsync` (#137)
* Added `zeroEx.token.setUnlimitedAllowanceAsync` (#137) * Added `zeroEx.token.setUnlimitedAllowanceAsync` (#137)
* Added `zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS` (#137) * Added `zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS` (#137)
## v0.10.4 - _August 24, 2017_ ## v0.10.4 - _August 23, 2017_
* Fixed a bug where checksummed addresses were being pulled from artifacts and not lower-cased. (#135) * Fixed a bug where checksummed addresses were being pulled from artifacts and not lower-cased. (#135)
## v0.10.1 - _August 24, 2017_ ## v0.10.1 - _August 23, 2017_
* Added `zeroEx.exchange.validateFillOrderThrowIfInvalidAsync` (#128) * Added `zeroEx.exchange.validateFillOrderThrowIfInvalidAsync` (#128)
* Added `zeroEx.exchange.validateFillOrKillOrderThrowIfInvalidAsync` (#128) * Added `zeroEx.exchange.validateFillOrKillOrderThrowIfInvalidAsync` (#128)
@@ -275,20 +327,20 @@ CHANGELOG
* Added clear error message when checksummed address is passed to a public method (#124) * Added clear error message when checksummed address is passed to a public method (#124)
* Fixes the description of `shouldThrowOnInsufficientBalanceOrAllowance` in docs (#127) * Fixes the description of `shouldThrowOnInsufficientBalanceOrAllowance` in docs (#127)
## v0.9.3 - _August 22, 2017_ ## v0.9.3 - _August 21, 2017_
* Update contract artifacts to include latest Kovan and Mainnet deploys (#118) * Update contract artifacts to include latest Kovan and Mainnet deploys (#118)
## v0.9.2 - _August 21, 2017_ ## v0.9.2 - _August 20, 2017_
* *This version was unpublished because of a publishing issue.* * *This version was unpublished because of a publishing issue.*
* Update contract artifacts to include latest Kovan and Mainnet deploys (#118) * Update contract artifacts to include latest Kovan and Mainnet deploys (#118)
## v0.9.1 - _August 16, 2017_ ## v0.9.1 - _August 15, 2017_
* Fixed the bug causing `zeroEx.token.getBalanceAsync()` to fail if no addresses available (#120) * Fixed the bug causing `zeroEx.token.getBalanceAsync()` to fail if no addresses available (#120)
## v0.9.0 - _July 26, 2017_ ## v0.9.0 - _July 25, 2017_
* Migrated to the new version of smart contracts (#101) * Migrated to the new version of smart contracts (#101)
* Removed the ability to call methods on multiple authorized Exchange smart contracts (#106) * Removed the ability to call methods on multiple authorized Exchange smart contracts (#106)
@@ -299,7 +351,7 @@ CHANGELOG
* Updated to typescript v2.4 (#104) * Updated to typescript v2.4 (#104)
* Fixed an issue with incorrect balance/allowance validation when ZRX is one of the tokens traded (#109) * Fixed an issue with incorrect balance/allowance validation when ZRX is one of the tokens traded (#109)
## v0.8.0 - _July 4, 2017_ ## v0.8.0 - _July 3, 2017_
* Added the ability to call methods on different authorized versions of the Exchange smart contract (#82) * Added the ability to call methods on different authorized versions of the Exchange smart contract (#82)
* Updated contract artifacts to reflect latest changes to the smart contracts (0xproject/contracts#59) * Updated contract artifacts to reflect latest changes to the smart contracts (0xproject/contracts#59)
@@ -312,35 +364,35 @@ CHANGELOG
* `zeroEx.tokenRegistry.invalidateContractInstance` * `zeroEx.tokenRegistry.invalidateContractInstance`
* Fixed the bug where `zeroEx.setProviderAsync` didn't invalidate etherToken contract's instance * Fixed the bug where `zeroEx.setProviderAsync` didn't invalidate etherToken contract's instance
## v0.7.1 - _June 26, 2017_ ## v0.7.1 - _June 25, 2017_
* Added the ability to convert Ether to wrapped Ether tokens and back via `zeroEx.etherToken.depostAsync` and `zeroEx.etherToken.withdrawAsync` (#81) * Added the ability to convert Ether to wrapped Ether tokens and back via `zeroEx.etherToken.depostAsync` and `zeroEx.etherToken.withdrawAsync` (#81)
## v0.7.0 - _June 22, 2017_ ## v0.7.0 - _June 21, 2017_
* Added Kovan smart contract artifacts (#78) * Added Kovan smart contract artifacts (#78)
* Started returning fillAmount from `fillOrderAsync` and `fillUpToAsync` (#72) * Started returning fillAmount from `fillOrderAsync` and `fillUpToAsync` (#72)
* Started returning cancelledAmount from `cancelOrderAsync` (#72) * Started returning cancelledAmount from `cancelOrderAsync` (#72)
* Renamed type `LogCancelArgs` to `LogCancelContractEventArgs` and `LogFillArgs` to `LogFillContractEventArgs` * Renamed type `LogCancelArgs` to `LogCancelContractEventArgs` and `LogFillArgs` to `LogFillContractEventArgs`
## v0.6.2 - _June 21, 2017_ ## v0.6.2 - _June 20, 2017_
* Reduced bundle size * Reduced bundle size
* Improved documentation * Improved documentation
## v0.6.1 - _June 19, 2017_ ## v0.6.1 - _June 18, 2017_
* Improved documentation * Improved documentation
## v0.6.0 - _June 19, 2017_ ## v0.6.0 - _June 18, 2017_
* Made `ZeroEx` class accept `Web3Provider` instance instead of `Web3` instance * Made `ZeroEx` class accept `Web3Provider` instance instead of `Web3` instance
* Added types for contract event arguments * Added types for contract event arguments
## v0.5.2 - _June 15, 2017_ ## v0.5.2 - _June 14, 2017_
* Fixed the bug in `postpublish` script that caused that only unminified UMD bundle was uploaded to release page * Fixed the bug in `postpublish` script that caused that only unminified UMD bundle was uploaded to release page
## v0.5.1 - _June 15, 2017_ ## v0.5.1 - _June 14, 2017_
* Added `postpublish` script to publish to Github Releases with assets. * Added `postpublish` script to publish to Github Releases with assets.

View File

@@ -44,7 +44,7 @@ Download the UMD module from our [releases page](https://github.com/0xProject/0x
## Contributing ## Contributing
We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. We strongly recommend that the community help us make improvements and determine the future direction of 0x protocol. To report bugs within this package, please create an issue in this repository.
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
@@ -64,28 +64,16 @@ yarn install
### Build ### Build
If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory:
```bash ```bash
yarn lerna:rebuild PKG=0x.js yarn build
``` ```
Or continuously rebuild on change: Or continuously rebuild on change:
```bash ```bash
yarn dev PKG=0x.js yarn watch
```
You can also build this specific package by running the following from within its directory:
```bash
yarn build
```
or continuously rebuild on change:
```bash
yarn build:watch
``` ```
### Clean ### Clean

View File

@@ -1,6 +1,9 @@
{ {
"name": "0x.js", "name": "0x.js",
"version": "0.36.0", "version": "0.38.6",
"engines": {
"node": ">=6.12"
},
"description": "A javascript library for interacting with the 0x protocol", "description": "A javascript library for interacting with the 0x protocol",
"keywords": [ "keywords": [
"0x.js", "0x.js",
@@ -12,29 +15,27 @@
"main": "lib/src/index.js", "main": "lib/src/index.js",
"types": "lib/src/index.d.ts", "types": "lib/src/index.d.ts",
"scripts": { "scripts": {
"build:watch": "tsc -w", "watch": "tsc -w",
"prebuild": "run-s clean generate_contract_wrappers", "prebuild": "run-s clean generate_contract_wrappers",
"build": "run-p build:umd:prod build:commonjs; exit 0;", "build": "run-p build:umd:prod build:commonjs; exit 0;",
"generate_contract_wrappers": "node ../abi-gen/lib/index.js --abis 'src/compact_artifacts/@(Exchange|Token|TokenTransferProxy|EtherToken|TokenRegistry|DummyToken).json' --template ../contract_templates/contract.handlebars --partials '../contract_templates/partials/**/*.handlebars' --output src/contract_wrappers/generated --backend ethers && prettier --write 'src/contract_wrappers/generated/**.ts'", "generate_contract_wrappers": "abi-gen --abis 'src/compact_artifacts/@(Exchange|Token|TokenTransferProxy|EtherToken|TokenRegistry|DummyToken).json' --template ../contract_templates/contract.handlebars --partials '../contract_templates/partials/**/*.handlebars' --output src/contract_wrappers/generated --backend ethers && prettier --write 'src/contract_wrappers/generated/**.ts'",
"lint": "tslint --project . 'src/**/*.ts' 'test/**/*.ts'", "lint": "tslint --project .",
"test:circleci": "run-s test:coverage", "test:circleci": "run-s test:coverage",
"test": "run-s clean test:commonjs", "test": "run-s clean test:commonjs",
"test:coverage": "nyc npm run test --all && yarn coverage:report:lcov", "test:coverage": "nyc npm run test --all && yarn coverage:report:lcov",
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info", "coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info",
"update_artifacts": "for i in ${npm_package_config_contracts}; do copyfiles -u 4 ../migrations/src/artifacts/$i.json test/artifacts; done;", "clean": "shx rm -rf _bundles lib test_temp scripts src/contract_wrappers/generated",
"clean": "shx rm -rf _bundles lib test_temp scripts",
"build:umd:prod": "NODE_ENV=production webpack", "build:umd:prod": "NODE_ENV=production webpack",
"build:commonjs": "tsc && yarn update_artifacts && copyfiles -u 2 './src/compact_artifacts/**/*.json' ./lib/src/compact_artifacts && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts", "build:commonjs": "tsc && copyfiles -u 2 './src/compact_artifacts/**/*.json' ./lib/src/compact_artifacts && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"test:commonjs": "run-s build:commonjs run_mocha", "test:commonjs": "run-s build:commonjs run_mocha",
"run_mocha": "mocha lib/test/**/*_test.js --timeout 10000 --bail --exit", "run_mocha": "mocha lib/test/**/*_test.js lib/test/global_hooks.js --timeout 10000 --bail --exit",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js", "manual:postpublish": "yarn build; node ./scripts/postpublish.js",
"docs:stage": "yarn build && node ./scripts/stage_docs.js", "docs:stage": "node scripts/stage_docs.js",
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES", "docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES",
"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" "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"
}, },
"config": { "config": {
"compact_artifacts": "Exchange DummyToken ZRXToken Token EtherToken TokenTransferProxy TokenRegistry", "compact_artifacts": "Exchange DummyToken ZRXToken Token EtherToken TokenTransferProxy TokenRegistry",
"contracts": "Exchange DummyToken ZRXToken Token WETH9 TokenTransferProxy MultiSigWallet MultiSigWalletWithTimeLock MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress MaliciousToken TokenRegistry Arbitrage EtherDelta AccountLevels",
"postpublish": { "postpublish": {
"assets": [ "assets": [
"packages/0x.js/_bundles/index.js", "packages/0x.js/_bundles/index.js",
@@ -43,6 +44,13 @@
"docPublishConfigs": { "docPublishConfigs": {
"extraFileIncludes": [ "extraFileIncludes": [
"../types/src/index.ts", "../types/src/index.ts",
"../contract-wrappers/src/types.ts",
"../contract-wrappers/src/contract_wrappers/ether_token_wrapper.ts",
"../contract-wrappers/src/contract_wrappers/exchange_wrapper.ts",
"../contract-wrappers/src/contract_wrappers/token_registry_wrapper.ts",
"../contract-wrappers/src/contract_wrappers/token_transfer_proxy_wrapper.ts",
"../contract-wrappers/src/contract_wrappers/token_wrapper.ts",
"../order-watcher/src/order_watcher/order_watcher.ts",
"./src/contract_wrappers/generated/ether_token.ts", "./src/contract_wrappers/generated/ether_token.ts",
"./src/contract_wrappers/generated/token.ts", "./src/contract_wrappers/generated/token.ts",
"./src/contract_wrappers/generated/exchange.ts" "./src/contract_wrappers/generated/exchange.ts"
@@ -57,65 +65,50 @@
"url": "https://github.com/0xProject/0x-monorepo" "url": "https://github.com/0xProject/0x-monorepo"
}, },
"license": "Apache-2.0", "license": "Apache-2.0",
"engines": {
"node": ">=6.0.0"
},
"devDependencies": { "devDependencies": {
"@0xproject/deployer": "^0.4.0", "@0xproject/abi-gen": "^0.3.4",
"@0xproject/dev-utils": "^0.3.5", "@0xproject/dev-utils": "^0.4.6",
"@0xproject/monorepo-scripts": "^0.1.17", "@0xproject/migrations": "^0.0.10",
"@0xproject/subproviders": "^0.8.4", "@0xproject/monorepo-scripts": "^0.2.2",
"@0xproject/tslint-config": "^0.4.15", "@0xproject/tslint-config": "^0.4.21",
"@types/bintrees": "^1.0.2",
"@types/lodash": "4.14.104", "@types/lodash": "4.14.104",
"@types/mocha": "^2.2.42", "@types/mocha": "2.2.48",
"@types/node": "^8.0.53", "@types/node": "9.6.0",
"@types/request": "2.47.0", "@types/sinon": "2.3.7",
"@types/sinon": "^2.2.2", "awesome-typescript-loader": "3.5.0",
"@types/uuid": "^3.4.2", "chai": "4.1.2",
"awesome-typescript-loader": "^3.1.3", "chai-as-promised": "7.1.1",
"chai": "^4.0.1", "chai-bignumber": "2.0.1",
"chai-as-promised": "^7.1.0", "copyfiles": "1.2.0",
"chai-bignumber": "^2.0.1", "dirty-chai": "2.0.1",
"copyfiles": "^1.2.0", "json-loader": "0.5.7",
"dirty-chai": "^2.0.1", "make-promises-safe": "1.1.0",
"json-loader": "^0.5.4", "mocha": "4.1.0",
"mocha": "^4.0.1", "npm-run-all": "4.1.2",
"npm-run-all": "^4.1.2", "nyc": "11.6.0",
"nyc": "^11.0.1", "opn-cli": "3.1.0",
"opn-cli": "^3.1.0", "prettier": "1.12.1",
"prettier": "^1.11.1", "shx": "0.2.2",
"request": "^2.81.0", "sinon": "4.4.9",
"shx": "^0.2.2", "source-map-support": "0.5.4",
"sinon": "^4.0.0",
"source-map-support": "^0.5.0",
"tslint": "5.8.0", "tslint": "5.8.0",
"typedoc": "0xProject/typedoc", "typedoc": "0xProject/typedoc",
"typescript": "2.7.1", "typescript": "2.7.1",
"web3-provider-engine": "^13.0.1", "webpack": "3.11.0"
"webpack": "^3.1.0"
}, },
"dependencies": { "dependencies": {
"@0xproject/assert": "^0.2.6", "@0xproject/assert": "^0.2.14",
"@0xproject/base-contract": "^0.2.0", "@0xproject/base-contract": "^0.3.6",
"@0xproject/json-schemas": "^0.7.20", "@0xproject/contract-wrappers": "^0.1.1",
"@0xproject/types": "^0.6.0", "@0xproject/order-utils": "^0.0.9",
"@0xproject/typescript-typings": "^0.1.0", "@0xproject/order-watcher": "^0.0.8",
"@0xproject/utils": "^0.5.1", "@0xproject/sol-compiler": "^0.5.4",
"@0xproject/web3-wrapper": "^0.6.0", "@0xproject/types": "^0.8.2",
"bintrees": "^1.0.2", "@0xproject/typescript-typings": "^0.4.3",
"bn.js": "^4.11.8", "@0xproject/utils": "^0.7.3",
"ethereumjs-abi": "^0.6.4", "@0xproject/web3-wrapper": "^0.7.3",
"ethereumjs-blockstream": "^2.0.6", "ethers": "3.0.22",
"ethereumjs-util": "^5.1.1", "lodash": "4.17.10"
"ethers-contracts": "^2.2.1",
"js-sha3": "^0.7.0",
"lodash": "^4.17.4",
"uuid": "^3.1.0",
"web3": "^0.20.0"
},
"optionalDependencies": {
"@0xproject/migrations": "^0.0.1"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"

View File

@@ -1,26 +1,27 @@
import { schemas, SchemaValidator } from '@0xproject/json-schemas'; import { assert } from '@0xproject/assert';
import {
ContractWrappers,
ContractWrappersConfig,
EtherTokenWrapper,
ExchangeWrapper,
TokenRegistryWrapper,
TokenTransferProxyWrapper,
TokenWrapper,
} from '@0xproject/contract-wrappers';
import {
generatePseudoRandomSalt,
getOrderHashHex,
isValidOrderHash,
isValidSignature,
signOrderHashAsync,
} from '@0xproject/order-utils';
import { OrderWatcher, OrderWatcherConfig } from '@0xproject/order-watcher';
import { ECSignature, Order, Provider, SignedOrder, TransactionReceiptWithDecodedLogs } from '@0xproject/types'; import { ECSignature, Order, Provider, SignedOrder, TransactionReceiptWithDecodedLogs } from '@0xproject/types';
import { AbiDecoder, BigNumber, intervalUtils } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as ethUtil from 'ethereumjs-util';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { artifacts } from './artifacts';
import { EtherTokenWrapper } from './contract_wrappers/ether_token_wrapper';
import { ExchangeWrapper } from './contract_wrappers/exchange_wrapper';
import { TokenRegistryWrapper } from './contract_wrappers/token_registry_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 { zeroExPrivateNetworkConfigSchema } from './schemas/zero_ex_private_network_config_schema';
import { zeroExPublicNetworkConfigSchema } from './schemas/zero_ex_public_network_config_schema';
import { OrderStateWatcherConfig, ZeroExConfig, ZeroExError } from './types';
import { assert } from './utils/assert';
import { constants } from './utils/constants'; import { constants } from './utils/constants';
import { decorators } from './utils/decorators';
import { signatureUtils } from './utils/signature_utils';
import { utils } from './utils/utils';
/** /**
* The ZeroEx class is the single entry-point into the 0x.js library. It contains all of the library's functionality * The ZeroEx class is the single entry-point into the 0x.js library. It contains all of the library's functionality
@@ -33,7 +34,6 @@ export class ZeroEx {
* this constant for your convenience. * this constant for your convenience.
*/ */
public static NULL_ADDRESS = constants.NULL_ADDRESS; public static NULL_ADDRESS = constants.NULL_ADDRESS;
/** /**
* An instance of the ExchangeWrapper class containing methods for interacting with the 0x Exchange smart contract. * An instance of the ExchangeWrapper class containing methods for interacting with the 0x Exchange smart contract.
*/ */
@@ -57,7 +57,16 @@ export class ZeroEx {
* tokenTransferProxy smart contract. * tokenTransferProxy smart contract.
*/ */
public proxy: TokenTransferProxyWrapper; public proxy: TokenTransferProxyWrapper;
private _web3Wrapper: Web3Wrapper; private _contractWrappers: ContractWrappers;
/**
* Generates a pseudo-random 256-bit salt.
* The salt can be included in a 0x order, ensuring that the order generates a unique orderHash
* 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 {
return generatePseudoRandomSalt();
}
/** /**
* Verifies that the elliptic curve signature `signature` was generated * Verifies that the elliptic curve signature `signature` was generated
* by signing `data` with the private key corresponding to the `signerAddress` address. * by signing `data` with the private key corresponding to the `signerAddress` address.
@@ -67,27 +76,15 @@ export class ZeroEx {
* @return Whether the signature is valid for the supplied signerAddress and data. * @return Whether the signature is valid for the supplied signerAddress and data.
*/ */
public static isValidSignature(data: string, signature: ECSignature, signerAddress: string): boolean { public static isValidSignature(data: string, signature: ECSignature, signerAddress: string): boolean {
assert.isHexString('data', data); return isValidSignature(data, signature, signerAddress);
assert.doesConformToSchema('signature', signature, schemas.ecSignatureSchema);
assert.isETHAddressHex('signerAddress', signerAddress);
const normalizedSignerAddress = signerAddress.toLowerCase();
const isValidSignature = signatureUtils.isValidSignature(data, signature, normalizedSignerAddress);
return isValidSignature;
} }
/** /**
* Generates a pseudo-random 256-bit salt. * Computes the orderHash for a supplied order.
* The salt can be included in a 0x order, ensuring that the order generates a unique orderHash * @param order An object that conforms to the Order or SignedOrder interface definitions.
* and will not collide with other outstanding orders that are identical in all other parameters. * @return The resulting orderHash from hashing the supplied order.
* @return A pseudo-random 256-bit number that can be used as a salt.
*/ */
public static generatePseudoRandomSalt(): BigNumber { public static getOrderHashHex(order: Order | SignedOrder): string {
// BigNumber.random returns a pseudo-random number between 0 & 1 with a passed in number of decimal places. return getOrderHashHex(order);
// Source: https://mikemcl.github.io/bignumber.js/#random
const randomNumber = BigNumber.random(constants.MAX_DIGITS_IN_UNSIGNED_256_INT);
const factor = new BigNumber(10).pow(constants.MAX_DIGITS_IN_UNSIGNED_256_INT - 1);
const salt = randomNumber.times(factor).round();
return salt;
} }
/** /**
* Checks if the supplied hex encoded order hash is valid. * Checks if the supplied hex encoded order hash is valid.
@@ -97,12 +94,7 @@ export class ZeroEx {
* @return Whether the supplied orderHash has the expected format. * @return Whether the supplied orderHash has the expected format.
*/ */
public static isValidOrderHash(orderHash: string): boolean { public static isValidOrderHash(orderHash: string): boolean {
// Since this method can be called to check if any arbitrary string conforms to an orderHash's return isValidOrderHash(orderHash);
// format, we only assert that we were indeed passed a string.
assert.isString('orderHash', orderHash);
const schemaValidator = new SchemaValidator();
const isValidOrderHash = schemaValidator.validate(orderHash, schemas.orderHashSchema).valid;
return isValidOrderHash;
} }
/** /**
* A unit amount is defined as the amount of a token above the specified decimal places (integer part). * A unit amount is defined as the amount of a token above the specified decimal places (integer part).
@@ -132,17 +124,6 @@ export class ZeroEx {
const baseUnitAmount = Web3Wrapper.toBaseUnitAmount(amount, decimals); const baseUnitAmount = Web3Wrapper.toBaseUnitAmount(amount, decimals);
return baseUnitAmount; return baseUnitAmount;
} }
/**
* Computes the orderHash for a supplied order.
* @param order An object that conforms to the Order or SignedOrder interface definitions.
* @return The resulting orderHash from hashing the supplied order.
*/
@decorators.syncZeroExErrorHandler
public static getOrderHashHex(order: Order | SignedOrder): string {
assert.doesConformToSchema('order', order, schemas.orderSchema);
const orderHashHex = utils.getOrderHashHex(order);
return orderHashHex;
}
/** /**
* Instantiates a new ZeroEx instance that provides the public interface to the 0x.js library. * Instantiates a new ZeroEx instance that provides the public interface to the 0x.js library.
* @param provider The Provider instance you would like the 0x.js library to use for interacting with * @param provider The Provider instance you would like the 0x.js library to use for interacting with
@@ -150,40 +131,15 @@ export class ZeroEx {
* @param config The configuration object. Look up the type for the description. * @param config The configuration object. Look up the type for the description.
* @return An instance of the 0x.js ZeroEx class. * @return An instance of the 0x.js ZeroEx class.
*/ */
constructor(provider: Provider, config: ZeroExConfig) { constructor(provider: Provider, config: ContractWrappersConfig) {
assert.isWeb3Provider('provider', provider); assert.isWeb3Provider('provider', provider);
assert.doesConformToSchema('config', config, zeroExConfigSchema, [ this._contractWrappers = new ContractWrappers(provider, config);
zeroExPrivateNetworkConfigSchema,
zeroExPublicNetworkConfigSchema, this.proxy = this._contractWrappers.proxy;
]); this.token = this._contractWrappers.token;
const artifactJSONs = _.values(artifacts); this.exchange = this._contractWrappers.exchange;
const abiArrays = _.map(artifactJSONs, artifact => artifact.abi); this.tokenRegistry = this._contractWrappers.tokenRegistry;
const defaults = { this.etherToken = this._contractWrappers.etherToken;
gasPrice: config.gasPrice,
};
this._web3Wrapper = new Web3Wrapper(provider, defaults);
_.forEach(abiArrays, abi => {
this._web3Wrapper.abiDecoder.addABI(abi);
});
this.proxy = new TokenTransferProxyWrapper(
this._web3Wrapper,
config.networkId,
config.tokenTransferProxyContractAddress,
);
this.token = new TokenWrapper(this._web3Wrapper, config.networkId, this.proxy);
this.exchange = new ExchangeWrapper(
this._web3Wrapper,
config.networkId,
this.token,
config.exchangeContractAddress,
config.zrxContractAddress,
);
this.tokenRegistry = new TokenRegistryWrapper(
this._web3Wrapper,
config.networkId,
config.tokenRegistryContractAddress,
);
this.etherToken = new EtherTokenWrapper(this._web3Wrapper, config.networkId, this.token);
} }
/** /**
* Sets a new web3 provider for 0x.js. Updating the provider will stop all * Sets a new web3 provider for 0x.js. Updating the provider will stop all
@@ -192,24 +148,23 @@ export class ZeroEx {
* @param networkId The id of the network your provider is connected to * @param networkId The id of the network your provider is connected to
*/ */
public setProvider(provider: Provider, networkId: number): void { public setProvider(provider: Provider, networkId: number): void {
this._web3Wrapper.setProvider(provider); this._contractWrappers.setProvider(provider, networkId);
(this.exchange as any)._invalidateContractInstances(); }
(this.exchange as any)._setNetworkId(networkId); /**
(this.tokenRegistry as any)._invalidateContractInstance(); * Get the provider instance currently used by 0x.js
(this.tokenRegistry as any)._setNetworkId(networkId); * @return Web3 provider instance
(this.token as any)._invalidateContractInstances(); */
(this.token as any)._setNetworkId(networkId); public getProvider(): Provider {
(this.proxy as any)._invalidateContractInstance(); return this._contractWrappers.getProvider();
(this.proxy as any)._setNetworkId(networkId);
(this.etherToken as any)._invalidateContractInstance();
(this.etherToken as any)._setNetworkId(networkId);
} }
/** /**
* Get user Ethereum addresses available through the supplied web3 provider available for sending transactions. * Get user Ethereum addresses available through the supplied web3 provider available for sending transactions.
* @return An array of available user Ethereum addresses. * @return An array of available user Ethereum addresses.
*/ */
public async getAvailableAddressesAsync(): Promise<string[]> { public async getAvailableAddressesAsync(): Promise<string[]> {
const availableAddresses = await this._web3Wrapper.getAvailableAddressesAsync(); // Hack: Get Web3Wrapper from ContractWrappers
const web3Wrapper: Web3Wrapper = (this._contractWrappers as any)._web3Wrapper;
const availableAddresses = await web3Wrapper.getAvailableAddressesAsync();
return availableAddresses; return availableAddresses;
} }
/** /**
@@ -229,41 +184,12 @@ export class ZeroEx {
signerAddress: string, signerAddress: string,
shouldAddPersonalMessagePrefix: boolean, shouldAddPersonalMessagePrefix: boolean,
): Promise<ECSignature> { ): Promise<ECSignature> {
assert.isHexString('orderHash', orderHash); return signOrderHashAsync(
await assert.isSenderAddressAsync('signerAddress', signerAddress, this._web3Wrapper); this._contractWrappers.getProvider(),
const normalizedSignerAddress = signerAddress.toLowerCase(); orderHash,
signerAddress,
let msgHashHex = orderHash; shouldAddPersonalMessagePrefix,
if (shouldAddPersonalMessagePrefix) { );
const orderHashBuff = ethUtil.toBuffer(orderHash);
const msgHashBuff = ethUtil.hashPersonalMessage(orderHashBuff);
msgHashHex = ethUtil.bufferToHex(msgHashBuff);
}
const signature = await this._web3Wrapper.signMessageAsync(normalizedSignerAddress, msgHashHex);
// HACK: There is no consensus on whether the signatureHex string should be formatted as
// v + r + s OR r + s + v, and different clients (even different versions of the same client)
// return the signature params in different orders. In order to support all client implementations,
// we parse the signature in both ways, and evaluate if either one is a valid signature.
const validVParamValues = [27, 28];
const ecSignatureVRS = signatureUtils.parseSignatureHexAsVRS(signature);
if (_.includes(validVParamValues, ecSignatureVRS.v)) {
const isValidVRSSignature = ZeroEx.isValidSignature(orderHash, ecSignatureVRS, normalizedSignerAddress);
if (isValidVRSSignature) {
return ecSignatureVRS;
}
}
const ecSignatureRSV = signatureUtils.parseSignatureHexAsRSV(signature);
if (_.includes(validVParamValues, ecSignatureRSV.v)) {
const isValidRSVSignature = ZeroEx.isValidSignature(orderHash, ecSignatureRSV, normalizedSignerAddress);
if (isValidRSVSignature) {
return ecSignatureRSV;
}
}
throw new Error(ZeroExError.InvalidSignature);
} }
/** /**
* Waits for a transaction to be mined and returns the transaction receipt. * Waits for a transaction to be mined and returns the transaction receipt.
@@ -274,10 +200,12 @@ export class ZeroEx {
*/ */
public async awaitTransactionMinedAsync( public async awaitTransactionMinedAsync(
txHash: string, txHash: string,
pollingIntervalMs = 1000, pollingIntervalMs: number = 1000,
timeoutMs?: number, timeoutMs?: number,
): Promise<TransactionReceiptWithDecodedLogs> { ): Promise<TransactionReceiptWithDecodedLogs> {
const transactionReceiptWithDecodedLogs = await this._web3Wrapper.awaitTransactionMinedAsync( // Hack: Get Web3Wrapper from ContractWrappers
const web3Wrapper: Web3Wrapper = (this._contractWrappers as any)._web3Wrapper;
const transactionReceiptWithDecodedLogs = await web3Wrapper.awaitTransactionMinedAsync(
txHash, txHash,
pollingIntervalMs, pollingIntervalMs,
timeoutMs, timeoutMs,
@@ -285,22 +213,17 @@ export class ZeroEx {
return transactionReceiptWithDecodedLogs; return transactionReceiptWithDecodedLogs;
} }
/** /**
* Instantiates and returns a new OrderStateWatcher instance. * Instantiates and returns a new OrderWatcher instance.
* Defaults to watching the pending state. * Defaults to watching the pending state.
* @param config The configuration object. Look up the type for the description. * @param config The configuration object. Look up the type for the description.
* @return An instance of the 0x.js OrderStateWatcher class. * @return An instance of the 0x.js OrderWatcher class.
*/ */
public createOrderStateWatcher(config?: OrderStateWatcherConfig) { public async createOrderWatcherAsync(config?: OrderWatcherConfig): Promise<OrderWatcher> {
return new OrderStateWatcher(this._web3Wrapper, this.token, this.exchange, config); // Hack: Get Web3Wrapper from ContractWrappers
} const web3Wrapper: Web3Wrapper = (this._contractWrappers as any)._web3Wrapper;
/* const networkId = await web3Wrapper.getNetworkIdAsync();
* HACK: `TokenWrapper` needs a token transfer proxy address. `TokenTransferProxy` address is fetched from const provider = this._contractWrappers.getProvider();
* an `ExchangeWrapper`. `ExchangeWrapper` needs `TokenWrapper` to validate orders, creating a dependency cycle. const orderWatcher = new OrderWatcher(provider, networkId, config);
* In order to break this - we create this function here and pass it as a parameter to the `TokenWrapper` return orderWatcher;
* and `ProxyWrapper`.
*/
private async _getTokenTransferProxyAddressAsync(): Promise<string> {
const tokenTransferProxyAddress = await (this.exchange as any)._getTokenTransferProxyAddressAsync();
return tokenTransferProxyAddress;
} }
} }

View File

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

View File

@@ -1,61 +1,53 @@
export { ZeroEx } from './0x'; export { ZeroEx } from './0x';
export {
ZeroExError,
EventCallback,
ExchangeContractErrs,
ContractEvent,
Token,
IndexedFilterValues,
BlockRange,
OrderCancellationRequest,
OrderFillRequest,
ContractEventArgs,
ZeroExConfig,
MethodOpts,
OrderTransactionOpts,
TransactionOpts,
LogEvent,
DecodedLogEvent,
EventWatcherCallback,
OnOrderStateChangeCallback,
OrderStateValid,
OrderStateInvalid,
OrderState,
} from './types';
export { export {
BlockParamLiteral, BlockParamLiteral,
FilterObject, FilterObject,
BlockParam, BlockParam,
ContractEventArg, ContractEventArg,
ExchangeContractErrs,
LogWithDecodedArgs, LogWithDecodedArgs,
Order, Order,
Provider, Provider,
SignedOrder, SignedOrder,
ECSignature, ECSignature,
OrderStateValid,
OrderStateInvalid,
OrderState,
Token,
TransactionReceipt, TransactionReceipt,
TransactionReceiptWithDecodedLogs, TransactionReceiptWithDecodedLogs,
} from '@0xproject/types'; } from '@0xproject/types';
export { OrderWatcherConfig } from '@0xproject/order-watcher';
export { export {
EventCallback,
ContractEvent,
IndexedFilterValues,
BlockRange,
OrderCancellationRequest,
OrderFillRequest,
ContractEventArgs,
MethodOpts,
OrderTransactionOpts,
TransactionOpts,
LogEvent,
DecodedLogEvent,
OnOrderStateChangeCallback,
ContractWrappersError,
EtherTokenContractEventArgs, EtherTokenContractEventArgs,
WithdrawalContractEventArgs, WithdrawalContractEventArgs,
DepositContractEventArgs, DepositContractEventArgs,
EtherTokenEvents, EtherTokenEvents,
} from './contract_wrappers/generated/ether_token';
export {
TransferContractEventArgs, TransferContractEventArgs,
ApprovalContractEventArgs, ApprovalContractEventArgs,
TokenContractEventArgs, TokenContractEventArgs,
TokenEvents, TokenEvents,
} from './contract_wrappers/generated/token';
export {
LogErrorContractEventArgs, LogErrorContractEventArgs,
LogCancelContractEventArgs, LogCancelContractEventArgs,
LogFillContractEventArgs, LogFillContractEventArgs,
ExchangeContractEventArgs, ExchangeContractEventArgs,
ExchangeEvents, ExchangeEvents,
} from './contract_wrappers/generated/exchange'; ContractWrappersConfig,
} from '@0xproject/contract-wrappers';

View File

@@ -1,99 +0,0 @@
import { BlockParamLiteral, LogEntry } from '@0xproject/types';
import { intervalUtils } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash';
import { EventWatcherCallback, ZeroExError } from '../types';
import { assert } from '../utils/assert';
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: LogEntry[] = [];
private _stateLayer: BlockParamLiteral;
constructor(
web3Wrapper: Web3Wrapper,
pollingIntervalIfExistsMs: undefined | number,
stateLayer: BlockParamLiteral = BlockParamLiteral.Latest,
) {
this._web3Wrapper = web3Wrapper;
this._stateLayer = stateLayer;
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,
(err: Error) => {
this.unsubscribe();
callback(err);
},
);
}
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 (_.isUndefined(pendingEvents)) {
// HACK: This should never happen, but happens frequently on CI due to a ganache bug
return;
}
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<LogEntry[]> {
const eventFilter = {
fromBlock: this._stateLayer,
toBlock: this._stateLayer,
};
const events = await this._web3Wrapper.getLogsAsync(eventFilter);
return events;
}
private async _emitDifferencesAsync(
logs: LogEntry[],
logEventState: LogEventState,
callback: EventWatcherCallback,
): Promise<void> {
for (const log of logs) {
const logEvent = {
removed: logEventState === LogEventState.Removed,
...log,
};
if (!_.isUndefined(this._intervalIdIfExists)) {
callback(null, logEvent);
}
}
}
}

View File

@@ -1,9 +1,23 @@
const networkNameToId: { [networkName: string]: number } = {
mainnet: 1,
ropsten: 3,
rinkeby: 4,
kovan: 42,
ganache: 50,
};
export const zeroExPublicNetworkConfigSchema = { export const zeroExPublicNetworkConfigSchema = {
id: '/ZeroExPublicNetworkConfig', id: '/ZeroExPublicNetworkConfig',
properties: { properties: {
networkId: { networkId: {
type: 'number', type: 'number',
enum: [1, 3, 4, 42, 50], enum: [
networkNameToId.mainnet,
networkNameToId.ropsten,
networkNameToId.rinkeby,
networkNameToId.kovan,
networkNameToId.ganache,
],
}, },
gasPrice: { $ref: '/Number' }, gasPrice: { $ref: '/Number' },
zrxContractAddress: { $ref: '/Address' }, zrxContractAddress: { $ref: '/Address' },

View File

@@ -1,277 +1,20 @@
import { BigNumber } from '@0xproject/utils';
import { import {
BlockParam, BlockParam,
BlockParamLiteral, BlockParamLiteral,
ContractAbi, ContractAbi,
ContractEventArg, ContractEventArg,
ExchangeContractErrs,
FilterObject, FilterObject,
LogEntryEvent,
LogWithDecodedArgs, LogWithDecodedArgs,
Order, Order,
OrderState,
SignedOrder, SignedOrder,
} from '@0xproject/types'; } from '@0xproject/types';
import * as Web3 from 'web3';
import { EtherTokenContractEventArgs, EtherTokenEvents } from './contract_wrappers/generated/ether_token';
import { ExchangeContractEventArgs, ExchangeEvents } from './contract_wrappers/generated/exchange';
import { TokenContractEventArgs, TokenEvents } from './contract_wrappers/generated/token';
export enum ZeroExError {
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',
ContractNotDeployedOnNetwork = 'CONTRACT_NOT_DEPLOYED_ON_NETWORK',
InsufficientAllowanceForTransfer = 'INSUFFICIENT_ALLOWANCE_FOR_TRANSFER',
InsufficientBalanceForTransfer = 'INSUFFICIENT_BALANCE_FOR_TRANSFER',
InsufficientEthBalanceForDeposit = 'INSUFFICIENT_ETH_BALANCE_FOR_DEPOSIT',
InsufficientWEthBalanceForWithdrawal = 'INSUFFICIENT_WETH_BALANCE_FOR_WITHDRAWAL',
InvalidJump = 'INVALID_JUMP',
OutOfGas = 'OUT_OF_GAS',
NoNetworkId = 'NO_NETWORK_ID',
SubscriptionNotFound = 'SUBSCRIPTION_NOT_FOUND',
SubscriptionAlreadyPresent = 'SUBSCRIPTION_ALREADY_PRESENT',
}
export enum InternalZeroExError { export enum InternalZeroExError {
NoAbiDecoder = 'NO_ABI_DECODER', NoAbiDecoder = 'NO_ABI_DECODER',
ZrxNotInTokenRegistry = 'ZRX_NOT_IN_TOKEN_REGISTRY', ZrxNotInTokenRegistry = 'ZRX_NOT_IN_TOKEN_REGISTRY',
WethNotInTokenRegistry = 'WETH_NOT_IN_TOKEN_REGISTRY', WethNotInTokenRegistry = 'WETH_NOT_IN_TOKEN_REGISTRY',
} }
export type OrderAddresses = [string, string, string, string, string];
export type OrderValues = [BigNumber, BigNumber, BigNumber, BigNumber, BigNumber, BigNumber];
export type LogEvent = LogEntryEvent;
export interface DecodedLogEvent<ArgsType> {
isRemoved: boolean;
log: LogWithDecodedArgs<ArgsType>;
}
export type EventCallback<ArgsType> = (err: null | Error, log?: DecodedLogEvent<ArgsType>) => void;
export type EventWatcherCallback = (err: null | Error, log?: LogEvent) => void;
export enum ExchangeContractErrCodes {
ERROR_FILL_EXPIRED, // Order has already expired
ERROR_FILL_NO_VALUE, // Order has already been fully filled or cancelled
ERROR_FILL_TRUNCATION, // Rounding error too large
ERROR_FILL_BALANCE_ALLOWANCE, // Insufficient balance or allowance for token transfer
ERROR_CANCEL_EXPIRED, // Order has already expired
ERROR_CANCEL_NO_VALUE, // Order has already been fully filled or cancelled
}
export enum ExchangeContractErrs {
OrderFillExpired = 'ORDER_FILL_EXPIRED',
OrderCancelExpired = 'ORDER_CANCEL_EXPIRED',
OrderCancelAmountZero = 'ORDER_CANCEL_AMOUNT_ZERO',
OrderAlreadyCancelledOrFilled = 'ORDER_ALREADY_CANCELLED_OR_FILLED',
OrderFillAmountZero = 'ORDER_FILL_AMOUNT_ZERO',
OrderRemainingFillAmountZero = 'ORDER_REMAINING_FILL_AMOUNT_ZERO',
OrderFillRoundingError = 'ORDER_FILL_ROUNDING_ERROR',
FillBalanceAllowanceError = 'FILL_BALANCE_ALLOWANCE_ERROR',
InsufficientTakerBalance = 'INSUFFICIENT_TAKER_BALANCE',
InsufficientTakerAllowance = 'INSUFFICIENT_TAKER_ALLOWANCE',
InsufficientMakerBalance = 'INSUFFICIENT_MAKER_BALANCE',
InsufficientMakerAllowance = 'INSUFFICIENT_MAKER_ALLOWANCE',
InsufficientTakerFeeBalance = 'INSUFFICIENT_TAKER_FEE_BALANCE',
InsufficientTakerFeeAllowance = 'INSUFFICIENT_TAKER_FEE_ALLOWANCE',
InsufficientMakerFeeBalance = 'INSUFFICIENT_MAKER_FEE_BALANCE',
InsufficientMakerFeeAllowance = 'INSUFFICIENT_MAKER_FEE_ALLOWANCE',
TransactionSenderIsNotFillOrderTaker = 'TRANSACTION_SENDER_IS_NOT_FILL_ORDER_TAKER',
MultipleMakersInSingleCancelBatchDisallowed = 'MULTIPLE_MAKERS_IN_SINGLE_CANCEL_BATCH_DISALLOWED',
InsufficientRemainingFillAmount = 'INSUFFICIENT_REMAINING_FILL_AMOUNT',
MultipleTakerTokensInFillUpToDisallowed = 'MULTIPLE_TAKER_TOKENS_IN_FILL_UP_TO_DISALLOWED',
BatchOrdersMustHaveSameExchangeAddress = 'BATCH_ORDERS_MUST_HAVE_SAME_EXCHANGE_ADDRESS',
BatchOrdersMustHaveAtLeastOneItem = 'BATCH_ORDERS_MUST_HAVE_AT_LEAST_ONE_ITEM',
}
export interface ContractEvent {
logIndex: number;
transactionIndex: number;
transactionHash: string;
blockHash: string;
blockNumber: number;
address: string;
type: string;
event: string;
args: ContractEventArgs;
}
export type ContractEventArgs = ExchangeContractEventArgs | TokenContractEventArgs | EtherTokenContractEventArgs;
// [address, name, symbol, decimals, ipfsHash, swarmHash]
export type TokenMetadata = [string, string, string, number, string, string];
export interface Token {
name: string;
address: string;
symbol: string;
decimals: number;
}
export interface TxOpts {
from: string;
gas?: number;
value?: BigNumber;
gasPrice?: BigNumber;
}
export interface TokenAddressBySymbol {
[symbol: string]: string;
}
export type ContractEvents = TokenEvents | ExchangeEvents | EtherTokenEvents;
export interface IndexedFilterValues {
[index: string]: ContractEventArg;
}
export interface BlockRange {
fromBlock: BlockParam;
toBlock: BlockParam;
}
export type DoneCallback = (err?: Error) => void;
export interface OrderCancellationRequest {
order: Order | SignedOrder;
takerTokenCancelAmount: BigNumber;
}
export interface OrderFillRequest {
signedOrder: SignedOrder;
takerTokenFillAmount: BigNumber;
}
export type AsyncMethod = (...args: any[]) => Promise<any>;
export type SyncMethod = (...args: any[]) => any;
/**
* orderExpirationCheckingIntervalMs: How often to check for expired orders. Default=50.
* eventPollingIntervalMs: How often to poll the Ethereum node for new events. Default=200.
* expirationMarginMs: Amount of time before order expiry that you'd like to be notified
* of an orders expiration. Default=0.
* cleanupJobIntervalMs: How often to run a cleanup job which revalidates all the orders. Default=1hr.
* stateLayer: Optional blockchain state layer OrderWatcher will monitor for new events. Default=latest.
*/
export interface OrderStateWatcherConfig {
orderExpirationCheckingIntervalMs?: number;
eventPollingIntervalMs?: number;
expirationMarginMs?: number;
cleanupJobIntervalMs?: number;
stateLayer: BlockParamLiteral;
}
/**
* networkId: The id of the underlying ethereum network your provider is connected to. (1-mainnet, 3-ropsten, 4-rinkeby, 42-kovan, 50-testrpc)
* gasPrice: Gas price to use with every transaction
* exchangeContractAddress: The address of an exchange contract to use
* zrxContractAddress: The address of the ZRX contract to use
* tokenRegistryContractAddress: The address of a token registry 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 {
networkId: number;
gasPrice?: BigNumber;
exchangeContractAddress?: string;
zrxContractAddress?: string;
tokenRegistryContractAddress?: string;
tokenTransferProxyContractAddress?: string;
orderWatcherConfig?: OrderStateWatcherConfig;
}
export type ArtifactContractName = 'ZRX' | 'TokenTransferProxy' | 'TokenRegistry' | 'Token' | 'Exchange' | 'EtherToken';
export interface Artifact {
contract_name: ArtifactContractName;
abi: ContractAbi;
networks: {
[networkId: number]: {
address: string;
};
};
}
/**
* expectedFillTakerTokenAmount: If specified, the validation method will ensure that the
* supplied order maker has a sufficient allowance/balance to fill this amount of the order's
* takerTokenAmount. If not specified, the validation method ensures that the maker has a sufficient
* allowance/balance to fill the entire remaining order amount.
*/
export interface ValidateOrderFillableOpts {
expectedFillTakerTokenAmount?: BigNumber;
}
/**
* defaultBlock: The block up to which to query the blockchain state. Setting this to a historical block number
* let's the user query the blockchain's state at an arbitrary point in time. In order for this to work, the
* backing Ethereum node must keep the entire historical state of the chain (e.g setting `--pruning=archive`
* flag when running Parity).
*/
export interface MethodOpts {
defaultBlock?: BlockParam;
}
/**
* gasPrice: Gas price in Wei to use for a transaction
* gasLimit: The amount of gas to send with a transaction
*/
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 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 = (err: Error | null, orderState?: OrderState) => void;
// tslint:disable:max-file-line-count // tslint:disable:max-file-line-count

View File

@@ -3,10 +3,4 @@ import { BigNumber } from '@0xproject/utils';
export const constants = { export const constants = {
NULL_ADDRESS: '0x0000000000000000000000000000000000000000', NULL_ADDRESS: '0x0000000000000000000000000000000000000000',
TESTRPC_NETWORK_ID: 50, TESTRPC_NETWORK_ID: 50,
MAX_DIGITS_IN_UNSIGNED_256_INT: 78,
INVALID_JUMP_PATTERN: 'invalid JUMP at',
OUT_OF_GAS_PATTERN: 'out of gas',
INVALID_TAKER_FORMAT: 'instance.taker is not of a type(s) string',
UNLIMITED_ALLOWANCE_IN_BASE_UNITS: new BigNumber(2).pow(256).minus(1),
DEFAULT_BLOCK_POLLING_INTERVAL: 1000,
}; };

View File

@@ -1,45 +0,0 @@
import { ECSignature } from '@0xproject/types';
import * as ethUtil from 'ethereumjs-util';
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];
if (v < 27) {
v += 27;
}
const r = signatureBuffer.slice(1, 33);
const s = signatureBuffer.slice(33, 65);
const ecSignature: ECSignature = {
v,
r: ethUtil.bufferToHex(r),
s: ethUtil.bufferToHex(s),
};
return ecSignature;
},
parseSignatureHexAsRSV(signatureHex: string): ECSignature {
const { v, r, s } = ethUtil.fromRpcSig(signatureHex);
const ecSignature: ECSignature = {
v,
r: ethUtil.bufferToHex(r),
s: ethUtil.bufferToHex(s),
};
return ecSignature;
},
};

View File

@@ -1,63 +0,0 @@
import { Order, SignedOrder, SolidityTypes } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils';
import BN = require('bn.js');
import * as ethABI from 'ethereumjs-abi';
import * as ethUtil from 'ethereumjs-util';
import * as _ from 'lodash';
export const utils = {
/**
* Converts BigNumber instance to BN
* The only reason we convert to BN is to remain compatible with `ethABI. soliditySHA3` that
* 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) {
return new BN(value.toString(), 10);
},
spawnSwitchErr(name: string, value: any): Error {
return new Error(`Unexpected switch value: ${value} encountered for ${name}`);
},
getOrderHashHex(order: Order | SignedOrder): string {
const orderParts = [
{ value: order.exchangeContractAddress, type: SolidityTypes.Address },
{ value: order.maker, type: SolidityTypes.Address },
{ value: order.taker, type: SolidityTypes.Address },
{ value: order.makerTokenAddress, type: SolidityTypes.Address },
{ value: order.takerTokenAddress, type: SolidityTypes.Address },
{ value: order.feeRecipient, type: SolidityTypes.Address },
{
value: utils.bigNumberToBN(order.makerTokenAmount),
type: SolidityTypes.Uint256,
},
{
value: utils.bigNumberToBN(order.takerTokenAmount),
type: SolidityTypes.Uint256,
},
{
value: utils.bigNumberToBN(order.makerFee),
type: SolidityTypes.Uint256,
},
{
value: utils.bigNumberToBN(order.takerFee),
type: SolidityTypes.Uint256,
},
{
value: utils.bigNumberToBN(order.expirationUnixTimestampSec),
type: SolidityTypes.Uint256,
},
{ value: utils.bigNumberToBN(order.salt), type: SolidityTypes.Uint256 },
];
const types = _.map(orderParts, o => o.type);
const values = _.map(orderParts, o => o.value);
const hashBuff = ethABI.soliditySHA3(types, values);
const hashHex = ethUtil.bufferToHex(hashBuff);
return hashHex;
},
getCurrentUnixTimestampSec(): BigNumber {
return new BigNumber(Date.now() / 1000).round();
},
getCurrentUnixTimestampMs(): BigNumber {
return new BigNumber(Date.now());
},
};

View File

@@ -1,12 +1,9 @@
import { Deployer } from '@0xproject/deployer'; import { ContractWrappers } from '@0xproject/contract-wrappers';
import { BlockchainLifecycle, devConstants, web3Factory } from '@0xproject/dev-utils'; import { BlockchainLifecycle, devConstants, web3Factory } from '@0xproject/dev-utils';
// HACK: This dependency is optional since it is only available when run from within
// the monorepo. tslint doesn't handle optional dependencies
// tslint:disable-next-line:no-implicit-dependencies
import { runMigrationsAsync } from '@0xproject/migrations';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as chai from 'chai'; import * as chai from 'chai';
import * as _ from 'lodash'; import * as _ from 'lodash';
import 'make-promises-safe';
import 'mocha'; import 'mocha';
import * as path from 'path'; import * as path from 'path';
import * as Sinon from 'sinon'; import * as Sinon from 'sinon';
@@ -15,7 +12,6 @@ import { ApprovalContractEventArgs, LogWithDecodedArgs, Order, TokenEvents, Zero
import { chaiSetup } from './utils/chai_setup'; import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants'; import { constants } from './utils/constants';
import { deployer } from './utils/deployer';
import { TokenUtils } from './utils/token_utils'; import { TokenUtils } from './utils/token_utils';
import { provider, web3Wrapper } from './utils/web3_wrapper'; import { provider, web3Wrapper } from './utils/web3_wrapper';
@@ -23,12 +19,9 @@ const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
chaiSetup.configure(); chaiSetup.configure();
const expect = chai.expect; const expect = chai.expect;
const SHOULD_ADD_PERSONAL_MESSAGE_PREFIX = false;
describe('ZeroEx library', () => { describe('ZeroEx library', () => {
let zeroEx: ZeroEx; let zeroEx: ZeroEx;
before(async () => { before(async () => {
await runMigrationsAsync(deployer);
const config = { const config = {
networkId: constants.TESTRPC_NETWORK_ID, networkId: constants.TESTRPC_NETWORK_ID,
}; };
@@ -50,9 +43,9 @@ describe('ZeroEx library', () => {
expect((zeroEx.exchange as any)._exchangeContractIfExists).to.be.undefined(); expect((zeroEx.exchange as any)._exchangeContractIfExists).to.be.undefined();
expect((zeroEx.tokenRegistry as any)._tokenRegistryContractIfExists).to.be.undefined(); expect((zeroEx.tokenRegistry as any)._tokenRegistryContractIfExists).to.be.undefined();
// Check that all nested web3 wrapper instances return the updated provider // Check that all nested zeroExContract/web3Wrapper instances return the updated provider
const nestedWeb3WrapperProvider = (zeroEx as any)._web3Wrapper.getProvider(); const nestedWeb3WrapperProvider = ((zeroEx as any)._contractWrappers as ContractWrappers).getProvider();
expect(nestedWeb3WrapperProvider.zeroExTestId).to.be.a('number'); expect((nestedWeb3WrapperProvider as any).zeroExTestId).to.be.a('number');
const exchangeWeb3WrapperProvider = (zeroEx.exchange as any)._web3Wrapper.getProvider(); const exchangeWeb3WrapperProvider = (zeroEx.exchange as any)._web3Wrapper.getProvider();
expect(exchangeWeb3WrapperProvider.zeroExTestId).to.be.a('number'); expect(exchangeWeb3WrapperProvider.zeroExTestId).to.be.a('number');
const tokenRegistryWeb3WrapperProvider = (zeroEx.tokenRegistry as any)._web3Wrapper.getProvider(); const tokenRegistryWeb3WrapperProvider = (zeroEx.tokenRegistry as any)._web3Wrapper.getProvider();
@@ -70,14 +63,12 @@ describe('ZeroEx library', () => {
}; };
const address = '0x5409ed021d9299bf6814279a6a1411a7e866a631'; const address = '0x5409ed021d9299bf6814279a6a1411a7e866a631';
it("should return false if the data doesn't pertain to the signature & address", async () => { it("should return false if the data doesn't pertain to the signature & address", async () => {
expect(ZeroEx.isValidSignature('0x0', signature, address)).to.be.false();
return expect( return expect(
(zeroEx.exchange as any)._isValidSignatureUsingContractCallAsync('0x0', signature, address), (zeroEx.exchange as any)._isValidSignatureUsingContractCallAsync('0x0', signature, address),
).to.become(false); ).to.become(false);
}); });
it("should return false if the address doesn't pertain to the signature & data", async () => { it("should return false if the address doesn't pertain to the signature & data", async () => {
const validUnrelatedAddress = '0x8b0292b11a196601ed2ce54b665cafeca0347d42'; const validUnrelatedAddress = '0x8b0292b11a196601ed2ce54b665cafeca0347d42';
expect(ZeroEx.isValidSignature(dataHex, signature, validUnrelatedAddress)).to.be.false();
return expect( return expect(
(zeroEx.exchange as any)._isValidSignatureUsingContractCallAsync( (zeroEx.exchange as any)._isValidSignatureUsingContractCallAsync(
dataHex, dataHex,
@@ -88,45 +79,16 @@ describe('ZeroEx library', () => {
}); });
it("should return false if the signature doesn't pertain to the dataHex & address", async () => { it("should return false if the signature doesn't pertain to the dataHex & address", async () => {
const wrongSignature = _.assign({}, signature, { v: 28 }); const wrongSignature = _.assign({}, signature, { v: 28 });
expect(ZeroEx.isValidSignature(dataHex, wrongSignature, address)).to.be.false();
return expect( return expect(
(zeroEx.exchange as any)._isValidSignatureUsingContractCallAsync(dataHex, wrongSignature, address), (zeroEx.exchange as any)._isValidSignatureUsingContractCallAsync(dataHex, wrongSignature, address),
).to.become(false); ).to.become(false);
}); });
it('should return true if the signature does pertain to the dataHex & address', async () => { it('should return true if the signature does pertain to the dataHex & address', async () => {
const isValidSignatureLocal = ZeroEx.isValidSignature(dataHex, signature, address);
expect(isValidSignatureLocal).to.be.true();
return expect( return expect(
(zeroEx.exchange as any)._isValidSignatureUsingContractCallAsync(dataHex, signature, address), (zeroEx.exchange as any)._isValidSignatureUsingContractCallAsync(dataHex, signature, address),
).to.become(true); ).to.become(true);
}); });
}); });
describe('#generateSalt', () => {
it('generates different salts', () => {
const equal = ZeroEx.generatePseudoRandomSalt().eq(ZeroEx.generatePseudoRandomSalt());
expect(equal).to.be.false();
});
it('generates salt in range [0..2^256)', () => {
const salt = ZeroEx.generatePseudoRandomSalt();
expect(salt.greaterThanOrEqualTo(0)).to.be.true();
const twoPow256 = new BigNumber(2).pow(256);
expect(salt.lessThan(twoPow256)).to.be.true();
});
});
describe('#isValidOrderHash', () => {
it('returns false if the value is not a hex string', () => {
const isValid = ZeroEx.isValidOrderHash('not a hex');
expect(isValid).to.be.false();
});
it('returns false if the length is wrong', () => {
const isValid = ZeroEx.isValidOrderHash('0xdeadbeef');
expect(isValid).to.be.false();
});
it('returns true if order hash is correct', () => {
const isValid = ZeroEx.isValidOrderHash('0x' + Array(65).join('0'));
expect(isValid).to.be.true();
});
});
describe('#toUnitAmount', () => { describe('#toUnitAmount', () => {
it('should throw if invalid baseUnit amount supplied as argument', () => { it('should throw if invalid baseUnit amount supplied as argument', () => {
const invalidBaseUnitAmount = new BigNumber(1000000000.4); const invalidBaseUnitAmount = new BigNumber(1000000000.4);
@@ -159,106 +121,6 @@ describe('ZeroEx library', () => {
); );
}); });
}); });
describe('#getOrderHashHex', () => {
const expectedOrderHash = '0x39da987067a3c9e5f1617694f1301326ba8c8b0498ebef5df4863bed394e3c83';
const fakeExchangeContractAddress = '0xb69e673309512a9d726f87304c6984054f87a93b';
const order: Order = {
maker: constants.NULL_ADDRESS,
taker: constants.NULL_ADDRESS,
feeRecipient: constants.NULL_ADDRESS,
makerTokenAddress: constants.NULL_ADDRESS,
takerTokenAddress: constants.NULL_ADDRESS,
exchangeContractAddress: fakeExchangeContractAddress,
salt: new BigNumber(0),
makerFee: new BigNumber(0),
takerFee: new BigNumber(0),
makerTokenAmount: new BigNumber(0),
takerTokenAmount: new BigNumber(0),
expirationUnixTimestampSec: new BigNumber(0),
};
it('calculates the order hash', async () => {
const orderHash = ZeroEx.getOrderHashHex(order);
expect(orderHash).to.be.equal(expectedOrderHash);
});
it('throws a readable error message if taker format is invalid', async () => {
const orderWithInvalidtakerFormat = {
...order,
taker: (null as any) as string,
};
const expectedErrorMessage =
'Order taker must be of type string. If you want anyone to be able to fill an order - pass ZeroEx.NULL_ADDRESS';
expect(() => ZeroEx.getOrderHashHex(orderWithInvalidtakerFormat)).to.throw(expectedErrorMessage);
});
});
describe('#signOrderHashAsync', () => {
let stubs: Sinon.SinonStub[] = [];
let makerAddress: string;
before(async () => {
const availableAddreses = await zeroEx.getAvailableAddressesAsync();
makerAddress = availableAddreses[0];
});
afterEach(() => {
// clean up any stubs after the test has completed
_.each(stubs, s => s.restore());
stubs = [];
});
it('Should return the correct ECSignature', async () => {
const orderHash = '0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b0';
const expectedECSignature = {
v: 27,
r: '0x61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33',
s: '0x40349190569279751135161d22529dc25add4f6069af05be04cacbda2ace2254',
};
const ecSignature = await zeroEx.signOrderHashAsync(
orderHash,
makerAddress,
SHOULD_ADD_PERSONAL_MESSAGE_PREFIX,
);
expect(ecSignature).to.deep.equal(expectedECSignature);
});
it('should return the correct ECSignature for signatureHex concatenated as R + S + V', async () => {
const orderHash = '0x34decbedc118904df65f379a175bb39ca18209d6ce41d5ed549d54e6e0a95004';
const signature =
'0x22109d11d79cb8bf96ed88625e1cd9558800c4073332a9a02857499883ee5ce3050aa3cc1f2c435e67e114cdce54b9527b4f50548342401bc5d2b77adbdacb021b';
const expectedECSignature = {
v: 27,
r: '0x22109d11d79cb8bf96ed88625e1cd9558800c4073332a9a02857499883ee5ce3',
s: '0x050aa3cc1f2c435e67e114cdce54b9527b4f50548342401bc5d2b77adbdacb02',
};
stubs = [
Sinon.stub((zeroEx as any)._web3Wrapper, 'signMessageAsync').returns(Promise.resolve(signature)),
Sinon.stub(ZeroEx, 'isValidSignature').returns(true),
];
const ecSignature = await zeroEx.signOrderHashAsync(
orderHash,
makerAddress,
SHOULD_ADD_PERSONAL_MESSAGE_PREFIX,
);
expect(ecSignature).to.deep.equal(expectedECSignature);
});
it('should return the correct ECSignature for signatureHex concatenated as V + R + S', async () => {
const orderHash = '0xc793e33ffded933b76f2f48d9aa3339fc090399d5e7f5dec8d3660f5480793f7';
const signature =
'0x1bc80bedc6756722672753413efdd749b5adbd4fd552595f59c13427407ee9aee02dea66f25a608bbae457e020fb6decb763deb8b7192abab624997242da248960';
const expectedECSignature = {
v: 27,
r: '0xc80bedc6756722672753413efdd749b5adbd4fd552595f59c13427407ee9aee0',
s: '0x2dea66f25a608bbae457e020fb6decb763deb8b7192abab624997242da248960',
};
stubs = [
Sinon.stub((zeroEx as any)._web3Wrapper, 'signMessageAsync').returns(Promise.resolve(signature)),
Sinon.stub(ZeroEx, 'isValidSignature').returns(true),
];
const ecSignature = await zeroEx.signOrderHashAsync(
orderHash,
makerAddress,
SHOULD_ADD_PERSONAL_MESSAGE_PREFIX,
);
expect(ecSignature).to.deep.equal(expectedECSignature);
});
});
describe('#awaitTransactionMinedAsync', () => { describe('#awaitTransactionMinedAsync', () => {
beforeEach(async () => { beforeEach(async () => {
await blockchainLifecycle.startAsync(); await blockchainLifecycle.startAsync();

View File

@@ -1,5 +1,6 @@
import { web3Factory } from '@0xproject/dev-utils'; import { web3Factory } from '@0xproject/dev-utils';
import * as fs from 'fs'; import * as fs from 'fs';
import 'make-promises-safe';
import { ZeroEx } from '../src'; import { ZeroEx } from '../src';

View File

@@ -1,43 +0,0 @@
import { web3Factory } from '@0xproject/dev-utils';
import * as chai from 'chai';
import 'mocha';
import { ZeroEx } from '../src';
import { assert } from '../src/utils/assert';
import { constants } from './utils/constants';
import { provider } from './utils/web3_wrapper';
const expect = chai.expect;
describe('Assertion library', () => {
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
const zeroEx = new ZeroEx(provider, config);
describe('#isSenderAddressHexAsync', () => {
it('throws when address is invalid', async () => {
const address = '0xdeadbeef';
const varName = 'address';
return expect(
assert.isSenderAddressAsync(varName, address, (zeroEx as any)._web3Wrapper),
).to.be.rejectedWith(`Expected ${varName} to be of type ETHAddressHex, encountered: ${address}`);
});
it('throws when address is unavailable', async () => {
const validUnrelatedAddress = '0x8b0292b11a196601eddce54b665cafeca0347d42';
const varName = 'address';
return expect(
assert.isSenderAddressAsync(varName, validUnrelatedAddress, (zeroEx as any)._web3Wrapper),
).to.be.rejectedWith(
`Specified ${varName} ${validUnrelatedAddress} isn't available through the supplied web3 provider`,
);
});
it("doesn't throw if address is available", async () => {
const availableAddress = (await zeroEx.getAvailableAddressesAsync())[0];
const varName = 'address';
return expect(
assert.isSenderAddressAsync(varName, availableAddress, (zeroEx as any)._web3Wrapper),
).to.become(undefined);
});
});
});

View File

@@ -1,125 +0,0 @@
import { web3Factory } from '@0xproject/dev-utils';
import { LogEntry } from '@0xproject/types';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as chai from 'chai';
import * as _ from 'lodash';
import 'mocha';
import * as Sinon from 'sinon';
import { LogEvent } from '../src';
import { EventWatcher } from '../src/order_watcher/event_watcher';
import { DoneCallback } from '../src/types';
import { chaiSetup } from './utils/chai_setup';
import { reportNodeCallbackErrors } from './utils/report_callback_errors';
import { provider } from './utils/web3_wrapper';
chaiSetup.configure();
const expect = chai.expect;
describe('EventWatcher', () => {
let stubs: Sinon.SinonStub[] = [];
let eventWatcher: EventWatcher;
let web3Wrapper: Web3Wrapper;
const logA: LogEntry = {
address: '0x71d271f8b14adef568f8f28f1587ce7271ac4ca5',
blockHash: null,
blockNumber: null,
data: '',
logIndex: null,
topics: [],
transactionHash: '0x004881d38cd4a8f72f1a0d68c8b9b8124504706041ff37019c1d1ed6bfda8e17',
transactionIndex: 0,
};
const logB: LogEntry = {
address: '0x8d12a197cb00d4747a1fe03395095ce2a5cc6819',
blockHash: null,
blockNumber: null,
data: '',
logIndex: null,
topics: ['0xf341246adaac6f497bc2a656f546ab9e182111d630394f0c57c710a59a2cb567'],
transactionHash: '0x01ef3c048b18d9b09ea195b4ed94cf8dd5f3d857a1905ff886b152cfb1166f25',
transactionIndex: 0,
};
const logC: LogEntry = {
address: '0x1d271f8b174adef58f1587ce68f8f27271ac4ca5',
blockHash: null,
blockNumber: null,
data: '',
logIndex: null,
topics: ['0xf341246adaac6f497bc2a656f546ab9e182111d630394f0c57c710a59a2cb567'],
transactionHash: '0x01ef3c048b18d9b09ea195b4ed94cf8dd5f3d857a1905ff886b152cfb1166f25',
transactionIndex: 0,
};
before(async () => {
const pollingIntervalMs = 10;
web3Wrapper = new Web3Wrapper(provider);
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: 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 expectedToBeCalledOnce = false;
const callback = reportNodeCallbackErrors(done, expectedToBeCalledOnce)((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: LogEntry[] = [logA, logB];
const changedLogs: 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 expectedToBeCalledOnce = false;
const callback = reportNodeCallbackErrors(done, expectedToBeCalledOnce)((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,19 @@
import { devConstants } from '@0xproject/dev-utils';
import { runMigrationsAsync } from '@0xproject/migrations';
import * as path from 'path';
import { constants } from './utils/constants';
import { provider } from './utils/web3_wrapper';
before('migrate contracts', async function(): Promise<void> {
// HACK: Since the migrations take longer then our global mocha timeout limit
// we manually increase it for this before hook.
const mochaTestTimeoutMs = 20000;
this.timeout(mochaTestTimeoutMs);
const txDefaults = {
gas: devConstants.GAS_ESTIMATE,
from: devConstants.TESTRPC_FIRST_ADDRESS,
};
const artifactsDir = `../migrations/artifacts/1.0.0`;
await runMigrationsAsync(provider, artifactsDir, txDefaults);
});

View File

@@ -1,82 +0,0 @@
import { BlockchainLifecycle, devConstants } from '@0xproject/dev-utils';
import { BigNumber } from '@0xproject/utils';
import * as _ from 'lodash';
import 'mocha';
import * as Sinon from 'sinon';
import { ApprovalContractEventArgs, DecodedLogEvent, Token, TokenEvents, ZeroEx } from '../src';
import { DoneCallback } from '../src/types';
import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants';
import { assertNodeCallbackError } from './utils/report_callback_errors';
import { provider, web3Wrapper } from './utils/web3_wrapper';
chaiSetup.configure();
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
describe('SubscriptionTest', () => {
let zeroEx: ZeroEx;
let userAddresses: string[];
let tokens: Token[];
let coinbase: string;
let addressWithoutFunds: string;
const config = {
networkId: constants.TESTRPC_NETWORK_ID,
};
before(async () => {
zeroEx = new ZeroEx(provider, config);
userAddresses = await zeroEx.getAvailableAddressesAsync();
tokens = await zeroEx.tokenRegistry.getTokensAsync();
coinbase = userAddresses[0];
addressWithoutFunds = userAddresses[1];
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('#subscribe', () => {
const indexFilterValues = {};
let tokenAddress: string;
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 = assertNodeCallbackError(done, errMsg);
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 = assertNodeCallbackError(done, errMsg);
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 | null, 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

@@ -4,7 +4,7 @@ import ChaiBigNumber = require('chai-bignumber');
import * as dirtyChai from 'dirty-chai'; import * as dirtyChai from 'dirty-chai';
export const chaiSetup = { export const chaiSetup = {
configure() { configure(): void {
chai.config.includeStack = true; chai.config.includeStack = true;
chai.use(ChaiBigNumber()); chai.use(ChaiBigNumber());
chai.use(dirtyChai); chai.use(dirtyChai);

View File

@@ -1,18 +0,0 @@
import { Deployer } from '@0xproject/deployer';
import { devConstants } from '@0xproject/dev-utils';
import * as path from 'path';
import { constants } from './constants';
import { provider } from './web3_wrapper';
const artifactsDir = path.resolve('test', 'artifacts');
const deployerOpts = {
artifactsDir,
provider,
networkId: constants.TESTRPC_NETWORK_ID,
defaults: {
gas: devConstants.GAS_ESTIMATE,
},
};
export const deployer = new Deployer(deployerOpts);

View File

@@ -1,66 +0,0 @@
import * as chai from 'chai';
import * as _ from 'lodash';
import { DoneCallback } from '../../src/types';
const expect = chai.expect;
export const reportNoErrorCallbackErrors = (done: DoneCallback, expectToBeCalledOnce = true) => {
return <T>(f?: (value: T) => void) => {
const wrapped = (value: T) => {
if (_.isUndefined(f)) {
done();
return;
}
try {
f(value);
if (expectToBeCalledOnce) {
done();
}
} catch (err) {
done(err);
}
};
return wrapped;
};
};
export const reportNodeCallbackErrors = (done: DoneCallback, expectToBeCalledOnce = true) => {
return <T>(f?: (value: T) => void) => {
const wrapped = (error: Error | null, value: T | undefined) => {
if (!_.isNull(error)) {
done(error);
} else {
if (_.isUndefined(f)) {
done();
return;
}
try {
f(value as T);
if (expectToBeCalledOnce) {
done();
}
} catch (err) {
done(err);
}
}
};
return wrapped;
};
};
export const assertNodeCallbackError = (done: DoneCallback, errMsg: string) => {
const wrapped = <T>(error: Error | null, value: T | undefined) => {
if (_.isNull(error)) {
done(new Error('Expected callback to receive an error'));
} else {
try {
expect(error.message).to.be.equal(errMsg);
done();
} catch (err) {
done(err);
}
}
};
return wrapped;
};

View File

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

View File

@@ -1,9 +1,6 @@
import { devConstants, web3Factory } from '@0xproject/dev-utils'; import { devConstants, web3Factory } from '@0xproject/dev-utils';
import { Provider } from '@0xproject/types'; import { Provider } from '@0xproject/types';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as Web3 from 'web3';
import { constants } from './constants';
const web3 = web3Factory.create({ shouldUseInProcessGanache: true }); const web3 = web3Factory.create({ shouldUseInProcessGanache: true });
const provider: Provider = web3.currentProvider; const provider: Provider = web3.currentProvider;

View File

@@ -1,4 +1,68 @@
[ [
{
"timestamp": 1531919263,
"version": "0.3.4",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1531149657,
"version": "0.3.3",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1529397769,
"version": "0.3.2",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "0.3.1",
"changes": [
{
"note": "Incorrect publish that was unpublished"
}
],
"timestamp": 1527810075
},
{
"version": "0.3.0",
"changes": [
{
"note": "Properly export the executable binary",
"pr": 588
}
],
"timestamp": 1527008270
},
{
"timestamp": 1525477860,
"version": "0.2.13",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1525428773,
"version": "0.2.12",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{ {
"timestamp": 1524044013, "timestamp": 1524044013,
"version": "0.2.11", "version": "0.2.11",

View File

@@ -5,11 +5,39 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG CHANGELOG
## v0.3.4 - _July 18, 2018_
* Dependencies updated
## v0.3.3 - _July 9, 2018_
* Dependencies updated
## v0.3.2 - _June 19, 2018_
* Dependencies updated
## v0.3.1 - _June 1, 2018_
* Incorrect publish that was unpublished
## v0.3.0 - _May 22, 2018_
* Properly export the executable binary (#588)
## v0.2.13 - _May 5, 2018_
* Dependencies updated
## v0.2.12 - _May 4, 2018_
* Dependencies updated
## v0.2.11 - _April 18, 2018_ ## v0.2.11 - _April 18, 2018_
* Dependencies updated * Dependencies updated
## v0.2.10 - _April 12, 2018_ ## v0.2.10 - _April 11, 2018_
* Dependencies updated * Dependencies updated
@@ -21,26 +49,26 @@ CHANGELOG
* Dependencies updated * Dependencies updated
## v0.2.5 - _March 18, 2018_ ## v0.2.5 - _March 17, 2018_
* Consolidate all `console.log` calls into `logUtils` in the `@0xproject/utils` package (#452) * Consolidate all `console.log` calls into `logUtils` in the `@0xproject/utils` package (#452)
## v0.2.4 - _March 4, 2018_ ## v0.2.4 - _March 3, 2018_
* Add a `backend` parameter that allows you to specify the Ethereum library you use in your templates (`web3` or `ethers`). Ethers auto-converts small ints to numbers whereas Web3 doesn't. Defaults to `web3` (#413) * Add a `backend` parameter that allows you to specify the Ethereum library you use in your templates (`web3` or `ethers`). Ethers auto-converts small ints to numbers whereas Web3 doesn't. Defaults to `web3` (#413)
* Add support for [tuple types](https://solidity.readthedocs.io/en/develop/abi-spec.html#handling-tuple-types) (#413) * Add support for [tuple types](https://solidity.readthedocs.io/en/develop/abi-spec.html#handling-tuple-types) (#413)
* Add `hasReturnValue` to context data (#413) * Add `hasReturnValue` to context data (#413)
## v0.2.1 - _February 9, 2018_ ## v0.2.1 - _February 8, 2018_
* Fix publishing issue where .npmignore was not properly excluding undesired content (#389) * Fix publishing issue where .npmignore was not properly excluding undesired content (#389)
## v0.2.0 - _February 7, 2018_ ## v0.2.0 - _February 6, 2018_
* Added CLI options for explicit specifying location of partials and main template (#346) * Added CLI options for explicit specifying location of partials and main template (#346)
* Added CLI option to specify networkId, adding support for the JSON artifact format found in @0xproject/contracts (#388) * Added CLI option to specify networkId, adding support for the JSON artifact format found in @0xproject/contracts (#388)
## v0.1.0 - _January 11, 2018_ ## v0.1.0 - _January 10, 2018_
* Fixed array typings with union types (#295) * Fixed array typings with union types (#295)
* Add event ABIs to context data passed to templates (#302) * Add event ABIs to context data passed to templates (#302)

View File

@@ -80,28 +80,16 @@ yarn install
### Build ### Build
If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory:
```bash ```bash
yarn lerna:rebuild PKG=@0xproject/abi-gen yarn build
``` ```
Or continuously rebuild on change: Or continuously rebuild on change:
```bash ```bash
yarn dev PKG=@0xproject/abi-gen yarn watch
```
You can also build this specific package by running the following from within its directory:
```bash
yarn build
```
or continuously rebuild on change:
```bash
yarn build:watch
``` ```
### Clean ### Clean

View File

@@ -0,0 +1,2 @@
#!/usr/bin/env node
require('../lib/index.js')

View File

@@ -1,18 +1,21 @@
{ {
"name": "@0xproject/abi-gen", "name": "@0xproject/abi-gen",
"version": "0.2.10", "version": "0.3.4",
"engines": {
"node": ">=6.12"
},
"description": "Generate contract wrappers from ABI and handlebars templates", "description": "Generate contract wrappers from ABI and handlebars templates",
"main": "lib/index.js", "main": "lib/index.js",
"types": "lib/index.d.ts", "types": "lib/index.d.ts",
"scripts": { "scripts": {
"build:watch": "tsc -w", "watch": "tsc -w",
"lint": "tslint --project . 'src/**/*.ts'", "lint": "tslint --project .",
"clean": "shx rm -rf lib scripts", "clean": "shx rm -rf lib scripts",
"build": "tsc && copyfiles -u 2 './lib/monorepo_scripts/**/*' ./scripts", "build": "tsc && copyfiles -u 2 './lib/monorepo_scripts/**/*' ./scripts",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js" "manual:postpublish": "yarn build; node ./scripts/postpublish.js"
}, },
"bin": { "bin": {
"abi-gen": "lib/index.js" "abi-gen": "bin/abi-gen.js"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@@ -24,28 +27,29 @@
}, },
"homepage": "https://github.com/0xProject/0x-monorepo/packages/abi-gen/README.md", "homepage": "https://github.com/0xProject/0x-monorepo/packages/abi-gen/README.md",
"dependencies": { "dependencies": {
"@0xproject/types": "^0.6.0", "@0xproject/types": "^0.8.2",
"@0xproject/typescript-typings": "^0.1.0", "@0xproject/typescript-typings": "^0.4.3",
"@0xproject/utils": "^0.5.1", "@0xproject/utils": "^0.7.3",
"chalk": "^2.3.0", "chalk": "2.3.2",
"glob": "^7.1.2", "glob": "7.1.1",
"handlebars": "^4.0.11", "handlebars": "4.0.11",
"lodash": "^4.17.4", "lodash": "4.17.10",
"mkdirp": "^0.5.1", "mkdirp": "0.5.1",
"to-snake-case": "^1.0.0", "to-snake-case": "1.0.0",
"yargs": "^10.0.3" "yargs": "11.1.0"
}, },
"devDependencies": { "devDependencies": {
"@0xproject/monorepo-scripts": "^0.1.17", "@0xproject/monorepo-scripts": "^0.2.2",
"@0xproject/tslint-config": "^0.4.15", "@0xproject/tslint-config": "^0.4.21",
"@types/glob": "^5.0.33", "@types/glob": "5.0.35",
"@types/handlebars": "^4.0.36", "@types/handlebars": "4.0.36",
"@types/mkdirp": "^0.5.1", "@types/mkdirp": "0.5.2",
"@types/node": "^8.0.53", "@types/node": "9.6.0",
"@types/yargs": "^10.0.0", "@types/yargs": "10.0.2",
"copyfiles": "^1.2.0", "copyfiles": "1.2.0",
"npm-run-all": "^4.1.2", "make-promises-safe": "1.1.0",
"shx": "^0.2.2", "npm-run-all": "4.1.2",
"shx": "0.2.2",
"tslint": "5.8.0", "tslint": "5.8.0",
"typescript": "2.7.1" "typescript": "2.7.1"
}, },

View File

@@ -61,14 +61,13 @@ const args = yargs
'Full usage example', 'Full usage example',
).argv; ).argv;
function registerPartials(partialsGlob: string) { function registerPartials(partialsGlob: string): void {
const partialTemplateFileNames = globSync(partialsGlob); const partialTemplateFileNames = globSync(partialsGlob);
logUtils.log(`Found ${chalk.green(`${partialTemplateFileNames.length}`)} ${chalk.bold('partial')} templates`); logUtils.log(`Found ${chalk.green(`${partialTemplateFileNames.length}`)} ${chalk.bold('partial')} templates`);
for (const partialTemplateFileName of partialTemplateFileNames) { for (const partialTemplateFileName of partialTemplateFileNames) {
const namedContent = utils.getNamedContent(partialTemplateFileName); const namedContent = utils.getNamedContent(partialTemplateFileName);
Handlebars.registerPartial(namedContent.name, namedContent.content); Handlebars.registerPartial(namedContent.name, namedContent.content);
} }
return partialsGlob;
} }
function writeOutputFile(name: string, renderedTsCode: string): void { function writeOutputFile(name: string, renderedTsCode: string): void {
@@ -108,13 +107,13 @@ for (const abiFileName of abiFileNames) {
ABI = parsedContent; // ABI file ABI = parsedContent; // ABI file
} else if (!_.isUndefined(parsedContent.abi)) { } else if (!_.isUndefined(parsedContent.abi)) {
ABI = parsedContent.abi; // Truffle artifact ABI = parsedContent.abi; // Truffle artifact
} else if (!_.isUndefined(parsedContent.networks) && !_.isUndefined(parsedContent.networks[args.networkId])) { } else if (!_.isUndefined(parsedContent.compilerOutput.abi)) {
ABI = parsedContent.networks[args.networkId].abi; // 0x contracts package artifact ABI = parsedContent.compilerOutput.abi; // 0x artifact
} }
if (_.isUndefined(ABI)) { if (_.isUndefined(ABI)) {
logUtils.log(`${chalk.red(`ABI not found in ${abiFileName}.`)}`); logUtils.log(`${chalk.red(`ABI not found in ${abiFileName}.`)}`);
logUtils.log( logUtils.log(
`Please make sure your ABI file is either an array with ABI entries or a truffle artifact or 0x deployer artifact`, `Please make sure your ABI file is either an array with ABI entries or a truffle artifact or 0x sol-compiler artifact`,
); );
process.exit(1); process.exit(1);
} }

View File

@@ -1,4 +1,67 @@
[ [
{
"timestamp": 1531919263,
"version": "0.2.14",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1531149657,
"version": "0.2.13",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1529397769,
"version": "0.2.12",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "0.2.11",
"changes": [
{
"note": "Incorrect publish that was unpublished"
}
],
"timestamp": 1527810075
},
{
"timestamp": 1527008270,
"version": "0.2.10",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1525477860,
"version": "0.2.9",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1525428773,
"version": "0.2.8",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{ {
"timestamp": 1524044013, "timestamp": 1524044013,
"version": "0.2.7", "version": "0.2.7",

View File

@@ -5,11 +5,39 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG CHANGELOG
## v0.2.14 - _July 18, 2018_
* Dependencies updated
## v0.2.13 - _July 9, 2018_
* Dependencies updated
## v0.2.12 - _June 19, 2018_
* Dependencies updated
## v0.2.11 - _June 1, 2018_
* Incorrect publish that was unpublished
## v0.2.10 - _May 22, 2018_
* Dependencies updated
## v0.2.9 - _May 5, 2018_
* Dependencies updated
## v0.2.8 - _May 4, 2018_
* Dependencies updated
## v0.2.7 - _April 18, 2018_ ## v0.2.7 - _April 18, 2018_
* Dependencies updated * Dependencies updated
## v0.2.6 - _April 12, 2018_ ## v0.2.6 - _April 11, 2018_
* Dependencies updated * Dependencies updated
@@ -21,20 +49,20 @@ CHANGELOG
* Dependencies updated * Dependencies updated
## v0.2.0 - _March 8, 2018_ ## v0.2.0 - _March 7, 2018_
* Rename `isHttpUrl` to `isWebUri` (#412) * Rename `isHttpUrl` to `isWebUri` (#412)
## v0.1.0 - _March 4, 2018_ ## v0.1.0 - _March 3, 2018_
* Remove isETHAddressHex checksum address check and assume address will be lowercased (#373) * Remove isETHAddressHex checksum address check and assume address will be lowercased (#373)
* Add an optional parameter `subSchemas` to `doesConformToSchema` method (#385) * Add an optional parameter `subSchemas` to `doesConformToSchema` method (#385)
## v0.0.18 - _February 9, 2017_ ## v0.0.18 - _February 8, 2017_
* Fix publishing issue where .npmignore was not properly excluding undesired content (#389) * Fix publishing issue where .npmignore was not properly excluding undesired content (#389)
## v0.0.4 - _November 14, 2017_ ## v0.0.4 - _November 13, 2017_
* Re-publish Assert previously published under NPM package @0xproject/0x-assert * 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. * Added assertion isValidBaseUnitAmount which checks both that the value is a valid bigNumber and that it does not contain decimals.

View File

@@ -46,28 +46,16 @@ yarn install
### Build ### Build
If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory:
```bash ```bash
yarn lerna:rebuild PKG=@0xproject/assert yarn build
``` ```
Or continuously rebuild on change: Or continuously rebuild on change:
```bash ```bash
yarn dev PKG=@0xproject/assert yarn watch
```
You can also build this specific package by running the following from within its directory:
```bash
yarn build
```
or continuously rebuild on change:
```bash
yarn build:watch
``` ```
### Clean ### Clean

View File

@@ -1,14 +1,17 @@
{ {
"name": "@0xproject/assert", "name": "@0xproject/assert",
"version": "0.2.6", "version": "0.2.14",
"engines": {
"node": ">=6.12"
},
"description": "Provides a standard way of performing type and schema validation across 0x projects", "description": "Provides a standard way of performing type and schema validation across 0x projects",
"main": "lib/src/index.js", "main": "lib/src/index.js",
"types": "lib/src/index.d.ts", "types": "lib/src/index.d.ts",
"scripts": { "scripts": {
"build:watch": "tsc -w", "watch": "tsc -w",
"build": "tsc && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts", "build": "tsc && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"clean": "shx rm -rf lib test_temp scripts", "clean": "shx rm -rf lib test_temp scripts",
"lint": "tslint --project . 'src/**/*.ts' 'test/**/*.ts'", "lint": "tslint --project .",
"run_mocha": "mocha lib/test/**/*_test.js --exit", "run_mocha": "mocha lib/test/**/*_test.js --exit",
"prepublishOnly": "run-p build", "prepublishOnly": "run-p build",
"test": "run-s clean build run_mocha", "test": "run-s clean build run_mocha",
@@ -27,27 +30,28 @@
}, },
"homepage": "https://github.com/0xProject/0x-monorepo/packages/assert/README.md", "homepage": "https://github.com/0xProject/0x-monorepo/packages/assert/README.md",
"devDependencies": { "devDependencies": {
"@0xproject/monorepo-scripts": "^0.1.17", "@0xproject/monorepo-scripts": "^0.2.2",
"@0xproject/tslint-config": "^0.4.15", "@0xproject/tslint-config": "^0.4.21",
"@types/lodash": "4.14.104", "@types/lodash": "4.14.104",
"@types/mocha": "^2.2.42", "@types/mocha": "2.2.48",
"@types/valid-url": "^1.0.2", "@types/valid-url": "1.0.2",
"chai": "^4.0.1", "chai": "4.1.2",
"copyfiles": "^1.2.0", "copyfiles": "1.2.0",
"dirty-chai": "^2.0.1", "dirty-chai": "2.0.1",
"mocha": "^4.0.1", "make-promises-safe": "1.1.0",
"npm-run-all": "^4.1.2", "mocha": "4.1.0",
"nyc": "^11.0.1", "npm-run-all": "4.1.2",
"shx": "^0.2.2", "nyc": "11.6.0",
"shx": "0.2.2",
"tslint": "5.8.0", "tslint": "5.8.0",
"typescript": "2.7.1" "typescript": "2.7.1"
}, },
"dependencies": { "dependencies": {
"@0xproject/json-schemas": "^0.7.20", "@0xproject/json-schemas": "^0.8.3",
"@0xproject/typescript-typings": "^0.1.0", "@0xproject/typescript-typings": "^0.4.3",
"@0xproject/utils": "^0.5.1", "@0xproject/utils": "^0.7.3",
"lodash": "^4.17.4", "lodash": "4.17.10",
"valid-url": "^1.0.9" "valid-url": "1.0.9"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"

View File

@@ -10,7 +10,7 @@ export const assert = {
const isBigNumber = _.isObject(value) && (value as any).isBigNumber; const isBigNumber = _.isObject(value) && (value as any).isBigNumber;
this.assert(isBigNumber, this.typeAssertionMessage(variableName, 'BigNumber', value)); this.assert(isBigNumber, this.typeAssertionMessage(variableName, 'BigNumber', value));
}, },
isValidBaseUnitAmount(variableName: string, value: BigNumber) { isValidBaseUnitAmount(variableName: string, value: BigNumber): void {
assert.isBigNumber(variableName, value); assert.isBigNumber(variableName, value);
const isNegative = value.lessThan(0); const isNegative = value.lessThan(0);
this.assert(!isNegative, `${variableName} cannot be a negative number, found value: ${value.toNumber()}`); this.assert(!isNegative, `${variableName} cannot be a negative number, found value: ${value.toNumber()}`);

View File

@@ -2,6 +2,7 @@ import { schemas } from '@0xproject/json-schemas';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as chai from 'chai'; import * as chai from 'chai';
import * as dirtyChai from 'dirty-chai'; import * as dirtyChai from 'dirty-chai';
import 'make-promises-safe';
import 'mocha'; import 'mocha';
import { assert } from '../src/index'; import { assert } from '../src/index';
@@ -10,6 +11,7 @@ chai.config.includeStack = true;
chai.use(dirtyChai); chai.use(dirtyChai);
const expect = chai.expect; const expect = chai.expect;
// tslint:disable:custom-no-magic-numbers
describe('Assertions', () => { describe('Assertions', () => {
const variableName = 'variable'; const variableName = 'variable';
describe('#isBigNumber', () => { describe('#isBigNumber', () => {
@@ -251,3 +253,4 @@ describe('Assertions', () => {
}); });
}); });
}); });
// tslint:enable:custom-no-magic-numbers

View File

@@ -1,4 +1,69 @@
[ [
{
"timestamp": 1531919263,
"version": "0.3.6",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1531149657,
"version": "0.3.5",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "0.3.4",
"changes": [
{
"note":
"Update EthersJs to fix the `value.toLowerCase()` is not a function bug caused by `ethers.js` breaking patch version https://github.com/ethers-io/ethers.js/issues/201"
}
],
"timestamp": 1529397769
},
{
"timestamp": 1527810075,
"version": "0.3.3",
"changes": [
{
"note": "Incorrect publish that was unpublished"
}
]
},
{
"timestamp": 1527008270,
"version": "0.3.2",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1525477860,
"version": "0.3.1",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "0.3.0",
"changes": [
{
"note": "Update ethers-contracts to ethers.js",
"pr": 540
}
],
"timestamp": 1525428773
},
{ {
"timestamp": 1524044013, "timestamp": 1524044013,
"version": "0.2.1", "version": "0.2.1",

View File

@@ -5,11 +5,39 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG CHANGELOG
## v0.3.6 - _July 18, 2018_
* Dependencies updated
## v0.3.5 - _July 9, 2018_
* Dependencies updated
## v0.3.4 - _June 19, 2018_
* Update EthersJs to fix the `value.toLowerCase()` is not a function bug caused by `ethers.js` breaking patch version https://github.com/ethers-io/ethers.js/issues/201
## v0.3.3 - _June 1, 2018_
* Incorrect publish that was unpublished
## v0.3.2 - _May 22, 2018_
* Dependencies updated
## v0.3.1 - _May 5, 2018_
* Dependencies updated
## v0.3.0 - _May 4, 2018_
* Update ethers-contracts to ethers.js (#540)
## v0.2.1 - _April 18, 2018_ ## v0.2.1 - _April 18, 2018_
* Dependencies updated * Dependencies updated
## v0.2.0 - _April 12, 2018_ ## v0.2.0 - _April 11, 2018_
* Contract wrappers now accept Provider and defaults instead of Web3Wrapper (#501) * Contract wrappers now accept Provider and defaults instead of Web3Wrapper (#501)
@@ -23,6 +51,6 @@ CHANGELOG
* Dependencies updated * Dependencies updated
## v0.0.2 - _March 4, 2018_ ## v0.0.2 - _March 3, 2018_
* Initial release * Initial release

View File

@@ -44,14 +44,16 @@ yarn install
### Build ### Build
To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory:
```bash ```bash
yarn build PKG=@0xproject/base-contract yarn build
``` ```
or Or continuously rebuild on change:
```bash ```bash
yarn build:watch PKG=@0xproject/base-contract yarn watch
``` ```
### Lint ### Lint

View File

@@ -1,11 +1,14 @@
{ {
"name": "@0xproject/base-contract", "name": "@0xproject/base-contract",
"version": "0.2.0", "version": "0.3.6",
"engines": {
"node": ">=6.12"
},
"description": "0x Base TS contract", "description": "0x Base TS contract",
"main": "lib/src/index.js", "main": "lib/src/index.js",
"types": "lib/src/index.d.ts", "types": "lib/src/index.d.ts",
"scripts": { "scripts": {
"build:watch": "tsc -w", "watch": "tsc -w",
"build": "tsc && copyfiles -u 2 './lib/monorepo_scripts/**/*' ./scripts", "build": "tsc && copyfiles -u 2 './lib/monorepo_scripts/**/*' ./scripts",
"clean": "shx rm -rf lib scripts", "clean": "shx rm -rf lib scripts",
"test": "run-s clean build run_mocha", "test": "run-s clean build run_mocha",
@@ -26,24 +29,25 @@
}, },
"homepage": "https://github.com/0xProject/0x-monorepo/packages/base-contract/README.md", "homepage": "https://github.com/0xProject/0x-monorepo/packages/base-contract/README.md",
"devDependencies": { "devDependencies": {
"@0xproject/monorepo-scripts": "^0.1.17", "@0xproject/monorepo-scripts": "^0.2.2",
"@0xproject/tslint-config": "^0.4.15", "@0xproject/tslint-config": "^0.4.21",
"@types/lodash": "4.14.104", "@types/lodash": "4.14.104",
"chai": "^4.0.1", "chai": "4.1.2",
"copyfiles": "^1.2.0", "copyfiles": "1.2.0",
"mocha": "^4.0.1", "make-promises-safe": "1.1.0",
"npm-run-all": "^4.1.2", "mocha": "4.1.0",
"shx": "^0.2.2", "npm-run-all": "4.1.2",
"shx": "0.2.2",
"tslint": "5.8.0", "tslint": "5.8.0",
"typescript": "2.7.1" "typescript": "2.7.1"
}, },
"dependencies": { "dependencies": {
"@0xproject/types": "^0.6.0", "@0xproject/types": "^0.8.2",
"@0xproject/typescript-typings": "^0.1.0", "@0xproject/typescript-typings": "^0.4.3",
"@0xproject/utils": "^0.5.1", "@0xproject/utils": "^0.7.3",
"@0xproject/web3-wrapper": "^0.6.0", "@0xproject/web3-wrapper": "^0.7.3",
"ethers-contracts": "^2.2.1", "ethers": "3.0.22",
"lodash": "^4.17.4" "lodash": "4.17.10"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"

View File

@@ -1,6 +1,7 @@
import { import {
AbiDefinition, AbiDefinition,
AbiType, AbiType,
ConstructorAbi,
ContractAbi, ContractAbi,
DataItem, DataItem,
MethodAbi, MethodAbi,
@@ -10,13 +11,13 @@ import {
} from '@0xproject/types'; } from '@0xproject/types';
import { abiUtils, BigNumber } from '@0xproject/utils'; import { abiUtils, BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as ethersContracts from 'ethers-contracts'; import * as ethers from 'ethers';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { formatABIDataItem } from './utils'; import { formatABIDataItem } from './utils';
export interface EthersInterfaceByFunctionSignature { export interface EthersInterfaceByFunctionSignature {
[key: string]: ethersContracts.Interface; [key: string]: ethers.Interface;
} }
export class BaseContract { export class BaseContract {
@@ -24,6 +25,8 @@ export class BaseContract {
protected _web3Wrapper: Web3Wrapper; protected _web3Wrapper: Web3Wrapper;
public abi: ContractAbi; public abi: ContractAbi;
public address: string; public address: string;
public contractName: string;
public constructorArgs: any[] = [];
protected static _formatABIDataItemList( protected static _formatABIDataItemList(
abis: DataItem[], abis: DataItem[],
values: any[], values: any[],
@@ -37,11 +40,31 @@ export class BaseContract {
protected static _bigNumberToString(type: string, value: any): any { protected static _bigNumberToString(type: string, value: any): any {
return _.isObject(value) && value.isBigNumber ? value.toString() : value; return _.isObject(value) && value.isBigNumber ? value.toString() : value;
} }
protected static _lookupConstructorAbi(abi: ContractAbi): ConstructorAbi {
const constructorAbiIfExists = _.find(
abi,
(abiDefinition: AbiDefinition) => abiDefinition.type === AbiType.Constructor,
) as ConstructorAbi | undefined;
if (!_.isUndefined(constructorAbiIfExists)) {
return constructorAbiIfExists;
} else {
// If the constructor is not explicitly defined, it won't be included in the ABI. It is
// still callable however, so we construct what the ABI would look like were it to exist.
const defaultConstructorAbi: ConstructorAbi = {
type: AbiType.Constructor,
stateMutability: 'nonpayable',
payable: false,
inputs: [],
};
return defaultConstructorAbi;
}
}
protected static _bnToBigNumber(type: string, value: any): any { protected static _bnToBigNumber(type: string, value: any): any {
return _.isObject(value) && value._bn ? new BigNumber(value.toString()) : value; return _.isObject(value) && value._bn ? new BigNumber(value.toString()) : value;
} }
protected async _applyDefaultsToTxDataAsync<T extends Partial<TxData | TxDataPayable>>( protected static async _applyDefaultsToTxDataAsync<T extends Partial<TxData | TxDataPayable>>(
txData: T, txData: T,
txDefaults: Partial<TxData>,
estimateGasAsync?: (txData: T) => Promise<number>, estimateGasAsync?: (txData: T) => Promise<number>,
): Promise<TxData> { ): Promise<TxData> {
// Gas amount sourced with the following priorities: // Gas amount sourced with the following priorities:
@@ -49,20 +72,19 @@ export class BaseContract {
// 2. Global config passed in at library instantiation // 2. Global config passed in at library instantiation
// 3. Gas estimate calculation + safety margin // 3. Gas estimate calculation + safety margin
const removeUndefinedProperties = _.pickBy; const removeUndefinedProperties = _.pickBy;
const txDataWithDefaults = ({ const txDataWithDefaults: TxData = {
to: this.address, ...removeUndefinedProperties(txDefaults),
...removeUndefinedProperties(this._web3Wrapper.getContractDefaults()),
...removeUndefinedProperties(txData as any), ...removeUndefinedProperties(txData as any),
// HACK: TS can't prove that T is spreadable. // HACK: TS can't prove that T is spreadable.
// Awaiting https://github.com/Microsoft/TypeScript/pull/13288 to be merged // Awaiting https://github.com/Microsoft/TypeScript/pull/13288 to be merged
} as any) as TxData; } as any;
if (_.isUndefined(txDataWithDefaults.gas) && !_.isUndefined(estimateGasAsync)) { if (_.isUndefined(txDataWithDefaults.gas) && !_.isUndefined(estimateGasAsync)) {
const estimatedGas = await estimateGasAsync(txData); const estimatedGas = await estimateGasAsync(txData);
txDataWithDefaults.gas = estimatedGas; txDataWithDefaults.gas = estimatedGas;
} }
return txDataWithDefaults; return txDataWithDefaults;
} }
protected _lookupEthersInterface(functionSignature: string): ethersContracts.Interface { protected _lookupEthersInterface(functionSignature: string): ethers.Interface {
const ethersInterface = this._ethersInterfacesByFunctionSignature[functionSignature]; const ethersInterface = this._ethersInterfacesByFunctionSignature[functionSignature];
if (_.isUndefined(ethersInterface)) { if (_.isUndefined(ethersInterface)) {
throw new Error(`Failed to lookup method with function signature '${functionSignature}'`); throw new Error(`Failed to lookup method with function signature '${functionSignature}'`);
@@ -82,8 +104,15 @@ export class BaseContract {
}) as MethodAbi; }) as MethodAbi;
return methodAbi; return methodAbi;
} }
constructor(abi: ContractAbi, address: string, provider: Provider, defaults?: Partial<TxData>) { constructor(
this._web3Wrapper = new Web3Wrapper(provider, defaults); contractName: string,
abi: ContractAbi,
address: string,
provider: Provider,
txDefaults?: Partial<TxData>,
) {
this.contractName = contractName;
this._web3Wrapper = new Web3Wrapper(provider, txDefaults);
this.abi = abi; this.abi = abi;
this.address = address; this.address = address;
const methodAbis = this.abi.filter( const methodAbis = this.abi.filter(
@@ -92,7 +121,7 @@ export class BaseContract {
this._ethersInterfacesByFunctionSignature = {}; this._ethersInterfacesByFunctionSignature = {};
_.each(methodAbis, methodAbi => { _.each(methodAbis, methodAbi => {
const functionSignature = abiUtils.getFunctionSignature(methodAbi); const functionSignature = abiUtils.getFunctionSignature(methodAbi);
this._ethersInterfacesByFunctionSignature[functionSignature] = new ethersContracts.Interface([methodAbi]); this._ethersInterfacesByFunctionSignature[functionSignature] = new ethers.Interface([methodAbi]);
}); });
} }
} }

View File

@@ -1,5 +1,6 @@
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as chai from 'chai'; import * as chai from 'chai';
import 'make-promises-safe';
import 'mocha'; import 'mocha';
import { formatABIDataItem } from '../src/utils'; import { formatABIDataItem } from '../src/utils';

View File

@@ -1,4 +1,67 @@
[ [
{
"timestamp": 1531919263,
"version": "0.6.17",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1531149657,
"version": "0.6.16",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1529397769,
"version": "0.6.15",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1527616612,
"version": "0.6.14",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1527008270,
"version": "0.6.13",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1525477860,
"version": "0.6.12",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1525428773,
"version": "0.6.11",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{ {
"timestamp": 1524044013, "timestamp": 1524044013,
"version": "0.6.10", "version": "0.6.10",

View File

@@ -5,11 +5,39 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG CHANGELOG
## v0.6.17 - _July 18, 2018_
* Dependencies updated
## v0.6.16 - _July 9, 2018_
* Dependencies updated
## v0.6.15 - _June 19, 2018_
* Dependencies updated
## v0.6.14 - _May 29, 2018_
* Dependencies updated
## v0.6.13 - _May 22, 2018_
* Dependencies updated
## v0.6.12 - _May 5, 2018_
* Dependencies updated
## v0.6.11 - _May 4, 2018_
* Dependencies updated
## v0.6.10 - _April 18, 2018_ ## v0.6.10 - _April 18, 2018_
* Dependencies updated * Dependencies updated
## v0.6.9 - _April 12, 2018_ ## v0.6.9 - _April 11, 2018_
* Dependencies updated * Dependencies updated
@@ -21,44 +49,44 @@ CHANGELOG
* Dependencies updated * Dependencies updated
## v0.6.4 - _March 18, 2018_ ## v0.6.4 - _March 17, 2018_
* Consolidate `Order`, `SignedOrder`, and `ECSignature` into the `@0xproject/types` package (#456) * Consolidate `Order`, `SignedOrder`, and `ECSignature` into the `@0xproject/types` package (#456)
## v0.6.2 - _February 16, 2018_ ## v0.6.2 - _February 15, 2018_
* Fix JSON parse empty response (#407) * Fix JSON parse empty response (#407)
## v0.6.0 - _February 16, 2018_ ## v0.6.0 - _February 15, 2018_
* Add pagination options to HttpClient methods (#393) * Add pagination options to HttpClient methods (#393)
* Add heartbeat configuration to WebSocketOrderbookChannel constructor (#406) * Add heartbeat configuration to WebSocketOrderbookChannel constructor (#406)
## v0.5.7 - _February 9, 2018_ ## v0.5.7 - _February 8, 2018_
* Fix publishing issue where .npmignore was not properly excluding undesired content (#389) * Fix publishing issue where .npmignore was not properly excluding undesired content (#389)
## v0.5.0 - _January 17, 2018_ ## v0.5.0 - _January 16, 2018_
* Sanitize api endpoint url and remove trailing slashes (#318) * Sanitize api endpoint url and remove trailing slashes (#318)
* Improve error message text in HttpClient (#318) * Improve error message text in HttpClient (#318)
* Stop appending '/v0' to api endpoint url in HttpClient (#318) * Stop appending '/v0' to api endpoint url in HttpClient (#318)
## v0.4.0 - _January 11, 2018_ ## v0.4.0 - _January 10, 2018_
* Prevent getFeesAsync method on HttpClient from mutating input (#296) * Prevent getFeesAsync method on HttpClient from mutating input (#296)
## v0.3.0 - _December 8, 2017_ ## v0.3.0 - _December 7, 2017_
* Expose WebSocketOrderbookChannel and associated types to public interface (#251) * Expose WebSocketOrderbookChannel and associated types to public interface (#251)
* Remove tokenA and tokenB fields from OrdersRequest (#256) * Remove tokenA and tokenB fields from OrdersRequest (#256)
## v0.2.0 - _November 29, 2017_ ## v0.2.0 - _November 28, 2017_
* Add SignedOrder and TokenTradeInfo to the public interface * Add SignedOrder and TokenTradeInfo to the public interface
* Add ECSignature and Order to the public interface * Add ECSignature and Order to the public interface
* Remove dependency on 0x.js * Remove dependency on 0x.js
## v0.1.0 - _November 22, 2017_ ## v0.1.0 - _November 21, 2017_
* Provide a HttpClient class for interacting with standard relayer api compliant HTTP urls * Provide a HttpClient class for interacting with standard relayer api compliant HTTP urls

View File

@@ -43,28 +43,16 @@ yarn install
### Build ### Build
If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory:
```bash ```bash
yarn lerna:rebuild PKG=@0xproject/connect yarn build
``` ```
Or continuously rebuild on change: Or continuously rebuild on change:
```bash ```bash
yarn dev PKG=@0xproject/connect yarn watch
```
You can also build this specific package by running the following from within its directory:
```bash
yarn build
```
or continuously rebuild on change:
```bash
yarn build:watch
``` ```
### Clean ### Clean

View File

@@ -1,6 +1,9 @@
{ {
"name": "@0xproject/connect", "name": "@0xproject/connect",
"version": "0.6.9", "version": "0.6.17",
"engines": {
"node": ">=6.12"
},
"description": "A javascript library for interacting with the standard relayer api", "description": "A javascript library for interacting with the standard relayer api",
"keywords": [ "keywords": [
"connect", "connect",
@@ -12,18 +15,18 @@
"main": "lib/src/index.js", "main": "lib/src/index.js",
"types": "lib/src/index.d.ts", "types": "lib/src/index.d.ts",
"scripts": { "scripts": {
"build:watch": "tsc -w", "watch": "tsc -w",
"build": "tsc && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts", "build": "tsc && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"clean": "shx rm -rf lib test_temp scripts", "clean": "shx rm -rf lib test_temp scripts",
"copy_test_fixtures": "copyfiles -u 2 './test/fixtures/**/*.json' ./lib/test/fixtures", "copy_test_fixtures": "copyfiles -u 2 './test/fixtures/**/*.json' ./lib/test/fixtures",
"lint": "tslint --project . 'src/**/*.ts' 'test/**/*.ts'", "lint": "tslint --project .",
"run_mocha": "mocha lib/test/**/*_test.js --exit", "run_mocha": "mocha lib/test/**/*_test.js --exit",
"test": "run-s clean build copy_test_fixtures run_mocha", "test": "run-s clean build copy_test_fixtures run_mocha",
"test:coverage": "nyc npm run test --all && yarn coverage:report:lcov", "test:coverage": "nyc npm run test --all && yarn coverage:report:lcov",
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info", "coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info",
"test:circleci": "yarn test:coverage", "test:circleci": "yarn test:coverage",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js", "manual:postpublish": "yarn build; node ./scripts/postpublish.js",
"docs:stage": "yarn build && node ./scripts/stage_docs.js", "docs:stage": "node scripts/stage_docs.js",
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES", "docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES",
"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" "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"
}, },
@@ -42,44 +45,42 @@
}, },
"author": "Brandon Millman", "author": "Brandon Millman",
"license": "Apache-2.0", "license": "Apache-2.0",
"engines": {
"node": ">=6.0.0"
},
"bugs": { "bugs": {
"url": "https://github.com/0xProject/0x-monorepo/issues" "url": "https://github.com/0xProject/0x-monorepo/issues"
}, },
"homepage": "https://github.com/0xProject/0x-monorepo/packages/connect/README.md", "homepage": "https://github.com/0xProject/0x-monorepo/packages/connect/README.md",
"dependencies": { "dependencies": {
"@0xproject/assert": "^0.2.6", "@0xproject/assert": "^0.2.14",
"@0xproject/json-schemas": "^0.7.20", "@0xproject/json-schemas": "^0.8.3",
"@0xproject/types": "^0.6.0", "@0xproject/types": "^0.8.2",
"@0xproject/typescript-typings": "^0.1.0", "@0xproject/typescript-typings": "^0.4.3",
"@0xproject/utils": "^0.5.1", "@0xproject/utils": "^0.7.3",
"isomorphic-fetch": "^2.2.1", "isomorphic-fetch": "2.2.1",
"lodash": "^4.17.4", "lodash": "4.17.10",
"query-string": "^5.0.1", "query-string": "4.3.4",
"websocket": "^1.0.25" "websocket": "1.0.25"
}, },
"devDependencies": { "devDependencies": {
"@0xproject/monorepo-scripts": "^0.1.17", "@0xproject/monorepo-scripts": "^0.2.2",
"@0xproject/tslint-config": "^0.4.15", "@0xproject/tslint-config": "^0.4.21",
"@types/fetch-mock": "^5.12.1", "@types/fetch-mock": "5.12.2",
"@types/lodash": "4.14.104", "@types/lodash": "4.14.104",
"@types/mocha": "^2.2.42", "@types/mocha": "2.2.48",
"@types/query-string": "^5.0.1", "@types/query-string": "5.1.0",
"@types/websocket": "^0.0.34", "@types/websocket": "0.0.34",
"async-child-process": "^1.1.1", "async-child-process": "1.1.1",
"chai": "^4.0.1", "chai": "4.1.2",
"chai-as-promised": "^7.1.0", "chai-as-promised": "7.1.1",
"copyfiles": "^1.2.0", "copyfiles": "1.2.0",
"dirty-chai": "^2.0.1", "dirty-chai": "2.0.1",
"fetch-mock": "^5.13.1", "fetch-mock": "5.13.1",
"mocha": "^4.0.1", "make-promises-safe": "1.1.0",
"npm-run-all": "^4.1.2", "mocha": "4.1.0",
"nyc": "^11.0.1", "npm-run-all": "4.1.2",
"shx": "^0.2.2", "nyc": "11.6.0",
"shx": "0.2.2",
"tslint": "5.8.0", "tslint": "5.8.0",
"typedoc": "~0.8.0", "typedoc": "0.8.0",
"typescript": "2.7.1" "typescript": "2.7.1"
}, },
"publishConfig": { "publishConfig": {

View File

@@ -16,7 +16,7 @@ export interface OrderbookChannel {
} }
/** /**
* heartbeatInterval: Interval in milliseconds that the orderbook channel should ping the underlying websocket. Default: 15000 * heartbeatIntervalMs: Interval in milliseconds that the orderbook channel should ping the underlying websocket. Default: 15000
*/ */
export interface WebSocketOrderbookChannelConfig { export interface WebSocketOrderbookChannelConfig {
heartbeatIntervalMs?: number; heartbeatIntervalMs?: number;

View File

@@ -91,7 +91,7 @@ export class WebSocketOrderbookChannel implements OrderbookChannel {
/** /**
* Close the websocket and stop receiving updates * Close the websocket and stop receiving updates
*/ */
public close() { public close(): void {
if (!_.isUndefined(this._connectionIfExists)) { if (!_.isUndefined(this._connectionIfExists)) {
this._connectionIfExists.close(); this._connectionIfExists.close();
} }
@@ -99,7 +99,7 @@ export class WebSocketOrderbookChannel implements OrderbookChannel {
clearInterval(this._heartbeatTimerIfExists); clearInterval(this._heartbeatTimerIfExists);
} }
} }
private _getConnection(callback: (error?: Error, connection?: WebSocket.connection) => void) { private _getConnection(callback: (error?: Error, connection?: WebSocket.connection) => void): void {
if (!_.isUndefined(this._connectionIfExists) && this._connectionIfExists.connected) { if (!_.isUndefined(this._connectionIfExists) && this._connectionIfExists.connected) {
callback(undefined, this._connectionIfExists); callback(undefined, this._connectionIfExists);
} else { } else {

View File

@@ -3,6 +3,7 @@ import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised'; import * as chaiAsPromised from 'chai-as-promised';
import * as dirtyChai from 'dirty-chai'; import * as dirtyChai from 'dirty-chai';
import * as fetchMock from 'fetch-mock'; import * as fetchMock from 'fetch-mock';
import 'make-promises-safe';
import 'mocha'; import 'mocha';
import { HttpClient } from '../src/index'; import { HttpClient } from '../src/index';

View File

@@ -1,5 +1,6 @@
import * as chai from 'chai'; import * as chai from 'chai';
import * as dirtyChai from 'dirty-chai'; import * as dirtyChai from 'dirty-chai';
import 'make-promises-safe';
import 'mocha'; import 'mocha';
import { orderbookChannelMessageParser } from '../src/utils/orderbook_channel_message_parser'; import { orderbookChannelMessageParser } from '../src/utils/orderbook_channel_message_parser';

View File

@@ -1,6 +1,7 @@
import * as chai from 'chai'; import * as chai from 'chai';
import * as dirtyChai from 'dirty-chai'; import * as dirtyChai from 'dirty-chai';
import * as _ from 'lodash'; import * as _ from 'lodash';
import 'make-promises-safe';
import 'mocha'; import 'mocha';
import { WebSocketOrderbookChannel } from '../src/ws_orderbook_channel'; import { WebSocketOrderbookChannel } from '../src/ws_orderbook_channel';

View File

@@ -0,0 +1,11 @@
.*
tsconfig.json
webpack.config.js
yarn-error.log
test/
/src/
/_bundles/
/contract_templates/
/generated_docs/
/scripts/
/lib/src/monorepo_scripts/

View File

@@ -0,0 +1,67 @@
[
{
"timestamp": 1531919263,
"version": "0.1.1",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "0.1.0",
"changes": [
{
"note":
"Update Blockstream dep. to V5.0 and no longer force unsubscribe on blockstream error (which are not recoverable)"
}
],
"timestamp": 1531149657
},
{
"timestamp": 1529397769,
"version": "0.0.5",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1527617227,
"version": "0.0.4",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1527616612,
"version": "0.0.3",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "0.0.2",
"changes": [
{
"note": "Dependencies updated"
}
],
"timestamp": 1527008544
},
{
"timestamp": 1527008270,
"version": "0.0.1",
"changes": [
{
"note": "Moved contractWrappers out of 0x.js",
"pr": 579
}
]
}
]

View File

@@ -0,0 +1,34 @@
<!--
This file is auto-generated using the monorepo-scripts package. Don't edit directly.
Edit the package's CHANGELOG.json file only.
-->
CHANGELOG
## v0.1.1 - _July 18, 2018_
* Dependencies updated
## v0.1.0 - _July 9, 2018_
* Update Blockstream dep. to V5.0 and no longer force unsubscribe on blockstream error (which are not recoverable)
## v0.0.5 - _June 19, 2018_
* Dependencies updated
## v0.0.4 - _May 29, 2018_
* Dependencies updated
## v0.0.3 - _May 29, 2018_
* Dependencies updated
## v0.0.2 - _May 22, 2018_
* Dependencies updated
## v0.0.1 - _May 22, 2018_
* Moved contractWrappers out of 0x.js (#579)

View File

@@ -0,0 +1,89 @@
## @0xproject/contract-wrappers
Smart TS wrappers for 0x smart contracts. The wrappers have simplified interfaces, perform client-side validation on transactions and throw helpful error messages.
### Read the [Documentation](https://0xproject.com/docs/0x.js).
## Installation
**Install**
```bash
npm install @0xproject/contract-wrappers --save
```
**Import**
```javascript
import { ContractWrappers } from '@0xproject/contract-wrappers';
```
If your project is in [TypeScript](https://www.typescriptlang.org/), add the following to your `tsconfig.json`:
```json
"compilerOptions": {
"typeRoots": ["node_modules/@0xproject/typescript-typings/types", "node_modules/@types"],
}
```
## Contributing
We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository.
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
### Install dependencies
If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them:
```bash
yarn config set workspaces-experimental true
```
Then install dependencies
```bash
yarn install
```
### Build
To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory:
```bash
PKG=@0xproject/contract-wrappers yarn build
```
Or continuously rebuild on change:
```bash
PKG=@0xproject/contract-wrappers yarn watch
```
```bash
yarn build
```
or continuously rebuild on change:
```bash
yarn watch
```
### Clean
```bash
yarn clean
```
### Lint
```bash
yarn lint
```
### Run Tests
```bash
yarn test
```

View File

@@ -0,0 +1,92 @@
{
"name": "@0xproject/contract-wrappers",
"version": "0.1.1",
"description": "Smart TS wrappers for 0x smart contracts",
"keywords": [
"0xproject",
"ethereum",
"tokens",
"exchange"
],
"main": "lib/src/index.js",
"types": "lib/src/index.d.ts",
"scripts": {
"watch": "tsc -w",
"prebuild": "run-s clean generate_contract_wrappers",
"generate_contract_wrappers": "abi-gen --abis 'src/compact_artifacts/@(Exchange|Token|TokenTransferProxy|EtherToken|TokenRegistry|DummyToken).json' --template ../contract_templates/contract.handlebars --partials '../contract_templates/partials/**/*.handlebars' --output src/contract_wrappers/generated --backend ethers && prettier --write 'src/contract_wrappers/generated/**.ts'",
"lint": "tslint --project .",
"test:circleci": "run-s test:coverage",
"test": "run-s clean build run_mocha",
"test:coverage": "nyc npm run test --all && yarn coverage:report:lcov",
"coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info",
"update_artifacts": "for i in ${npm_package_config_contracts}; do copyfiles -u 4 ../migrations/artifacts/1.0.0/$i.json test/artifacts; done;",
"clean": "shx rm -rf _bundles lib test_temp scripts test/artifacts src/contract_wrappers/generated",
"build": "tsc && yarn update_artifacts && copyfiles -u 2 './src/compact_artifacts/**/*.json' ./lib/src/compact_artifacts && copyfiles -u 3 './lib/src/monorepo_scripts/**/*' ./scripts",
"run_mocha": "mocha lib/test/**/*_test.js lib/test/global_hooks.js --timeout 10000 --bail --exit",
"manual:postpublish": "yarn build; node ./scripts/postpublish.js"
},
"config": {
"compact_artifacts": "Exchange DummyToken ZRXToken Token EtherToken TokenTransferProxy TokenRegistry",
"contracts": "Exchange DummyToken ZRXToken Token WETH9 TokenTransferProxy MultiSigWallet MultiSigWalletWithTimeLock MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress MaliciousToken TokenRegistry Arbitrage EtherDelta AccountLevels"
},
"repository": {
"type": "git",
"url": "https://github.com/0xProject/0x-monorepo"
},
"license": "Apache-2.0",
"engines": {
"node": ">=6.0.0"
},
"devDependencies": {
"@0xproject/abi-gen": "^0.3.4",
"@0xproject/dev-utils": "^0.4.6",
"@0xproject/migrations": "^0.0.10",
"@0xproject/monorepo-scripts": "^0.2.2",
"@0xproject/subproviders": "^0.10.6",
"@0xproject/tslint-config": "^0.4.21",
"@types/lodash": "4.14.104",
"@types/mocha": "2.2.48",
"@types/node": "9.6.0",
"@types/sinon": "2.3.7",
"@types/uuid": "3.4.3",
"awesome-typescript-loader": "3.5.0",
"chai": "4.1.2",
"chai-as-promised": "7.1.1",
"chai-bignumber": "2.0.1",
"copyfiles": "1.2.0",
"dirty-chai": "2.0.1",
"make-promises-safe": "1.1.0",
"mocha": "4.1.0",
"npm-run-all": "4.1.2",
"nyc": "11.6.0",
"opn-cli": "3.1.0",
"prettier": "1.12.1",
"shx": "0.2.2",
"sinon": "4.4.9",
"source-map-support": "0.5.4",
"tslint": "5.8.0",
"typescript": "2.7.1",
"web3-provider-engine": "13.8.0"
},
"dependencies": {
"@0xproject/assert": "^0.2.14",
"@0xproject/base-contract": "^0.3.6",
"@0xproject/fill-scenarios": "^0.0.6",
"@0xproject/json-schemas": "^0.8.3",
"@0xproject/order-utils": "^0.0.9",
"@0xproject/sol-compiler": "^0.5.4",
"@0xproject/types": "^0.8.2",
"@0xproject/typescript-typings": "^0.4.3",
"@0xproject/utils": "^0.7.3",
"@0xproject/web3-wrapper": "^0.7.3",
"ethereumjs-blockstream": "5.0.0",
"ethereumjs-util": "5.1.5",
"ethers": "3.0.22",
"js-sha3": "0.7.0",
"lodash": "4.17.10",
"uuid": "3.2.1"
},
"publishConfig": {
"access": "public"
}
}

View File

@@ -0,0 +1,18 @@
import { Artifact } from '@0xproject/types';
import * as DummyToken from './compact_artifacts/DummyToken.json';
import * as EtherToken from './compact_artifacts/EtherToken.json';
import * as Exchange from './compact_artifacts/Exchange.json';
import * as Token from './compact_artifacts/Token.json';
import * as TokenRegistry from './compact_artifacts/TokenRegistry.json';
import * as TokenTransferProxy from './compact_artifacts/TokenTransferProxy.json';
import * as ZRX from './compact_artifacts/ZRX.json';
export const artifacts = {
ZRX: (ZRX as any) as Artifact,
DummyToken: (DummyToken as any) as Artifact,
Token: (Token as any) as Artifact,
Exchange: (Exchange as any) as Artifact,
EtherToken: (EtherToken as any) as Artifact,
TokenRegistry: (TokenRegistry as any) as Artifact,
TokenTransferProxy: (TokenTransferProxy as any) as Artifact,
};

View File

@@ -0,0 +1,22 @@
{
"contract_name": "DummyToken",
"abi": [
{
"constant": false,
"inputs": [
{
"name": "_target",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "setBalance",
"outputs": [],
"payable": false,
"type": "function"
}
]
}

View File

@@ -0,0 +1,287 @@
{
"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"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_owner",
"type": "address"
},
{
"indexed": false,
"name": "_value",
"type": "uint256"
}
],
"name": "Deposit",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_owner",
"type": "address"
},
{
"indexed": false,
"name": "_value",
"type": "uint256"
}
],
"name": "Withdrawal",
"type": "event"
}
],
"networks": {
"1": {
"address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
},
"3": {
"address": "0xc00fd9820cd2898cc4c054b7bf142de637ad129a"
},
"4": {
"address": "0xc778417e063141139fce010982780140aa0cd5ab"
},
"42": {
"address": "0x653e49e301e508a13237c0ddc98ae7d4cd2667a1"
},
"50": {
"address": "0x871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c"
}
}
}

View File

@@ -0,0 +1,610 @@
{
"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"
},
"4": {
"address": "0x1d16ef40fac01cec8adac2ac49427b9384192c05"
},
"42": {
"address": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364"
},
"50": {
"address": "0x48bacb9266a570d521063ef5dd96e61686dbe788"
}
}
}

View File

@@ -0,0 +1,172 @@
{
"contract_name": "Token",
"abi": [
{
"constant": false,
"inputs": [
{
"name": "_spender",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"name": "supply",
"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": "success",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"name": "balance",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"payable": false,
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
},
{
"name": "_spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"name": "remaining",
"type": "uint256"
}
],
"payable": false,
"type": "function"
},
{
"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"
}
]
}

View File

@@ -0,0 +1,547 @@
{
"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"
},
"4": {
"address": "0x4e9aad8184de8833365fea970cd9149372fdf1e6"
},
"42": {
"address": "0xf18e504561f4347bea557f3d4558f559dddbae7f"
},
"50": {
"address": "0x0b1ba0af832d7c05fd64161e0db78e85978e8082"
}
}
}

View File

@@ -0,0 +1,187 @@
{
"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"
},
"4": {
"address": "0xa8e9fa8f91e5ae138c74648c9c304f1c75003a8d"
},
"42": {
"address": "0x087eed4bc1ee3de49befbd66c662b434b15d49d4"
},
"50": {
"address": "0x1dc4c1cefef38a777b15aa20260a54e584b16c48"
}
}
}

View File

@@ -0,0 +1,20 @@
{
"contract_name": "ZRX",
"networks": {
"1": {
"address": "0xe41d2489571d322189246dafa5ebde1f4699f498"
},
"3": {
"address": "0xa8e9fa8f91e5ae138c74648c9c304f1c75003a8d"
},
"4": {
"address": "0x00f58d6d585f84b2d7267940cede30ce2fe6eae8"
},
"42": {
"address": "0x6ff6c0ff1d68b964901f986d4c9fa3ac68346570"
},
"50": {
"address": "0x1d7022f5b17d2f8b695918fb48fa1089c9f85401"
}
}
}

View File

@@ -0,0 +1,112 @@
import { Provider } from '@0xproject/types';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash';
import { artifacts } from './artifacts';
import { EtherTokenWrapper } from './contract_wrappers/ether_token_wrapper';
import { ExchangeWrapper } from './contract_wrappers/exchange_wrapper';
import { TokenRegistryWrapper } from './contract_wrappers/token_registry_wrapper';
import { TokenTransferProxyWrapper } from './contract_wrappers/token_transfer_proxy_wrapper';
import { TokenWrapper } from './contract_wrappers/token_wrapper';
import { ContractWrappersConfigSchema } from './schemas/contract_wrappers_config_schema';
import { contractWrappersPrivateNetworkConfigSchema } from './schemas/contract_wrappers_private_network_config_schema';
import { contractWrappersPublicNetworkConfigSchema } from './schemas/contract_wrappers_public_network_config_schema';
import { ContractWrappersConfig } from './types';
import { assert } from './utils/assert';
/**
* The ContractWrappers class contains smart contract wrappers helpful when building on 0x protocol.
*/
export class ContractWrappers {
/**
* An instance of the ExchangeWrapper class containing methods for interacting with the 0x Exchange smart contract.
*/
public exchange: ExchangeWrapper;
/**
* An instance of the TokenRegistryWrapper class containing methods for interacting with the 0x
* TokenRegistry smart contract.
*/
public tokenRegistry: TokenRegistryWrapper;
/**
* An instance of the TokenWrapper class containing methods for interacting with any ERC20 token smart contract.
*/
public token: TokenWrapper;
/**
* An instance of the EtherTokenWrapper class containing methods for interacting with the
* wrapped ETH ERC20 token smart contract.
*/
public etherToken: EtherTokenWrapper;
/**
* An instance of the TokenTransferProxyWrapper class containing methods for interacting with the
* tokenTransferProxy smart contract.
*/
public proxy: TokenTransferProxyWrapper;
private _web3Wrapper: Web3Wrapper;
/**
* Instantiates a new ContractWrappers instance.
* @param provider The Provider instance you would like the 0x.js library to use for interacting with
* the Ethereum network.
* @param config The configuration object. Look up the type for the description.
* @return An instance of the ContractWrappers class.
*/
constructor(provider: Provider, config: ContractWrappersConfig) {
assert.isWeb3Provider('provider', provider);
assert.doesConformToSchema('config', config, ContractWrappersConfigSchema, [
contractWrappersPrivateNetworkConfigSchema,
contractWrappersPublicNetworkConfigSchema,
]);
const artifactJSONs = _.values(artifacts);
const abiArrays = _.map(artifactJSONs, artifact => artifact.abi);
const txDefaults = {
gasPrice: config.gasPrice,
};
this._web3Wrapper = new Web3Wrapper(provider, txDefaults);
_.forEach(abiArrays, abi => {
this._web3Wrapper.abiDecoder.addABI(abi);
});
this.proxy = new TokenTransferProxyWrapper(
this._web3Wrapper,
config.networkId,
config.tokenTransferProxyContractAddress,
);
this.token = new TokenWrapper(this._web3Wrapper, config.networkId, this.proxy);
this.exchange = new ExchangeWrapper(
this._web3Wrapper,
config.networkId,
this.token,
config.exchangeContractAddress,
config.zrxContractAddress,
);
this.tokenRegistry = new TokenRegistryWrapper(
this._web3Wrapper,
config.networkId,
config.tokenRegistryContractAddress,
);
this.etherToken = new EtherTokenWrapper(this._web3Wrapper, config.networkId, this.token);
}
/**
* 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 setProvider(provider: Provider, networkId: number): void {
this._web3Wrapper.setProvider(provider);
(this.exchange as any)._invalidateContractInstances();
(this.exchange as any)._setNetworkId(networkId);
(this.tokenRegistry as any)._invalidateContractInstance();
(this.tokenRegistry as any)._setNetworkId(networkId);
(this.token as any)._invalidateContractInstances();
(this.token as any)._setNetworkId(networkId);
(this.proxy as any)._invalidateContractInstance();
(this.proxy as any)._setNetworkId(networkId);
(this.etherToken as any)._invalidateContractInstance();
(this.etherToken as any)._setNetworkId(networkId);
}
/**
* Get the provider instance currently used by 0x.js
* @return Web3 provider instance
*/
public getProvider(): Provider {
return this._web3Wrapper.getProvider();
}
}

View File

@@ -1,38 +1,44 @@
import { BlockParamLiteral, ContractAbi, FilterObject, LogEntry, LogWithDecodedArgs, RawLog } from '@0xproject/types';
import { AbiDecoder, intervalUtils } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import { Block, BlockAndLogStreamer } from 'ethereumjs-blockstream';
import * as _ from 'lodash';
import * as Web3 from 'web3';
import { import {
Artifact, Artifact,
BlockParamLiteral,
ContractAbi,
FilterObject,
LogEntry,
LogWithDecodedArgs,
RawLog,
} from '@0xproject/types';
import { intervalUtils, logUtils } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import { Block, BlockAndLogStreamer, Log } from 'ethereumjs-blockstream';
import * as _ from 'lodash';
import {
BlockRange, BlockRange,
ContractEventArgs, ContractEventArgs,
ContractEvents, ContractEvents,
ContractWrappersError,
EventCallback, EventCallback,
IndexedFilterValues, IndexedFilterValues,
InternalZeroExError, InternalContractWrappersError,
ZeroExError,
} from '../types'; } from '../types';
import { constants } from '../utils/constants'; import { constants } from '../utils/constants';
import { filterUtils } from '../utils/filter_utils'; import { filterUtils } from '../utils/filter_utils';
const CONTRACT_NAME_TO_NOT_FOUND_ERROR: { const CONTRACT_NAME_TO_NOT_FOUND_ERROR: {
[contractName: string]: ZeroExError; [contractName: string]: ContractWrappersError;
} = { } = {
ZRX: ZeroExError.ZRXContractDoesNotExist, ZRX: ContractWrappersError.ZRXContractDoesNotExist,
EtherToken: ZeroExError.EtherTokenContractDoesNotExist, EtherToken: ContractWrappersError.EtherTokenContractDoesNotExist,
Token: ZeroExError.TokenContractDoesNotExist, Token: ContractWrappersError.TokenContractDoesNotExist,
TokenRegistry: ZeroExError.TokenRegistryContractDoesNotExist, TokenRegistry: ContractWrappersError.TokenRegistryContractDoesNotExist,
TokenTransferProxy: ZeroExError.TokenTransferProxyContractDoesNotExist, TokenTransferProxy: ContractWrappersError.TokenTransferProxyContractDoesNotExist,
Exchange: ZeroExError.ExchangeContractDoesNotExist, Exchange: ContractWrappersError.ExchangeContractDoesNotExist,
}; };
export class ContractWrapper { export class ContractWrapper {
protected _web3Wrapper: Web3Wrapper; protected _web3Wrapper: Web3Wrapper;
protected _networkId: number; protected _networkId: number;
private _blockAndLogStreamerIfExists?: BlockAndLogStreamer; private _blockAndLogStreamerIfExists?: BlockAndLogStreamer<Block, Log> | undefined;
private _blockAndLogStreamIntervalIfExists?: NodeJS.Timer; private _blockAndLogStreamIntervalIfExists?: NodeJS.Timer;
private _filters: { [filterToken: string]: FilterObject }; private _filters: { [filterToken: string]: FilterObject };
private _filterCallbacks: { private _filterCallbacks: {
@@ -40,6 +46,13 @@ export class ContractWrapper {
}; };
private _onLogAddedSubscriptionToken: string | undefined; private _onLogAddedSubscriptionToken: string | undefined;
private _onLogRemovedSubscriptionToken: string | undefined; private _onLogRemovedSubscriptionToken: string | undefined;
private static _onBlockstreamError(isVerbose: boolean, err: Error): void {
// Noop on blockstream errors since they are automatically
// recovered from and don't cause Blockstream to exit.
if (isVerbose) {
logUtils.warn(err.message);
}
}
constructor(web3Wrapper: Web3Wrapper, networkId: number) { constructor(web3Wrapper: Web3Wrapper, networkId: number) {
this._web3Wrapper = web3Wrapper; this._web3Wrapper = web3Wrapper;
this._networkId = networkId; this._networkId = networkId;
@@ -57,7 +70,7 @@ export class ContractWrapper {
} }
protected _unsubscribe(filterToken: string, err?: Error): void { protected _unsubscribe(filterToken: string, err?: Error): void {
if (_.isUndefined(this._filters[filterToken])) { if (_.isUndefined(this._filters[filterToken])) {
throw new Error(ZeroExError.SubscriptionNotFound); throw new Error(ContractWrappersError.SubscriptionNotFound);
} }
if (!_.isUndefined(err)) { if (!_.isUndefined(err)) {
const callback = this._filterCallbacks[filterToken]; const callback = this._filterCallbacks[filterToken];
@@ -75,10 +88,11 @@ export class ContractWrapper {
indexFilterValues: IndexedFilterValues, indexFilterValues: IndexedFilterValues,
abi: ContractAbi, abi: ContractAbi,
callback: EventCallback<ArgsType>, callback: EventCallback<ArgsType>,
isVerbose: boolean = false,
): string { ): string {
const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi); const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi);
if (_.isUndefined(this._blockAndLogStreamerIfExists)) { if (_.isUndefined(this._blockAndLogStreamerIfExists)) {
this._startBlockAndLogStream(); this._startBlockAndLogStream(isVerbose);
} }
const filterToken = filterUtils.generateUUID(); const filterToken = filterUtils.generateUUID();
this._filters[filterToken] = filter; this._filters[filterToken] = filter;
@@ -101,7 +115,7 @@ export class ContractWrapper {
log: LogEntry, log: LogEntry,
): LogWithDecodedArgs<ArgsType> | RawLog { ): LogWithDecodedArgs<ArgsType> | RawLog {
if (_.isUndefined(this._web3Wrapper.abiDecoder)) { if (_.isUndefined(this._web3Wrapper.abiDecoder)) {
throw new Error(InternalZeroExError.NoAbiDecoder); throw new Error(InternalContractWrappersError.NoAbiDecoder);
} }
const logWithDecodedArgs = this._web3Wrapper.abiDecoder.tryToDecodeLogOrNoop(log); const logWithDecodedArgs = this._web3Wrapper.abiDecoder.tryToDecodeLogOrNoop(log);
return logWithDecodedArgs; return logWithDecodedArgs;
@@ -113,7 +127,7 @@ export class ContractWrapper {
let contractAddress: string; let contractAddress: string;
if (_.isUndefined(addressIfExists)) { if (_.isUndefined(addressIfExists)) {
if (_.isUndefined(artifact.networks[this._networkId])) { if (_.isUndefined(artifact.networks[this._networkId])) {
throw new Error(ZeroExError.ContractNotDeployedOnNetwork); throw new Error(ContractWrappersError.ContractNotDeployedOnNetwork);
} }
contractAddress = artifact.networks[this._networkId].address.toLowerCase(); contractAddress = artifact.networks[this._networkId].address.toLowerCase();
} else { } else {
@@ -130,7 +144,7 @@ export class ContractWrapper {
if (_.isUndefined(addressIfExists)) { if (_.isUndefined(addressIfExists)) {
const contractAddress = artifact.networks[this._networkId].address; const contractAddress = artifact.networks[this._networkId].address;
if (_.isUndefined(contractAddress)) { if (_.isUndefined(contractAddress)) {
throw new Error(ZeroExError.ExchangeContractDoesNotExist); throw new Error(ContractWrappersError.ExchangeContractDoesNotExist);
} }
return contractAddress; return contractAddress;
} else { } else {
@@ -149,20 +163,21 @@ export class ContractWrapper {
} }
}); });
} }
private _startBlockAndLogStream(): void { private _startBlockAndLogStream(isVerbose: boolean): void {
if (!_.isUndefined(this._blockAndLogStreamerIfExists)) { if (!_.isUndefined(this._blockAndLogStreamerIfExists)) {
throw new Error(ZeroExError.SubscriptionAlreadyPresent); throw new Error(ContractWrappersError.SubscriptionAlreadyPresent);
} }
this._blockAndLogStreamerIfExists = new BlockAndLogStreamer( this._blockAndLogStreamerIfExists = new BlockAndLogStreamer(
this._web3Wrapper.getBlockAsync.bind(this._web3Wrapper), this._web3Wrapper.getBlockAsync.bind(this._web3Wrapper),
this._web3Wrapper.getLogsAsync.bind(this._web3Wrapper), this._web3Wrapper.getLogsAsync.bind(this._web3Wrapper),
ContractWrapper._onBlockstreamError.bind(this, isVerbose),
); );
const catchAllLogFilter = {}; const catchAllLogFilter = {};
this._blockAndLogStreamerIfExists.addLogFilter(catchAllLogFilter); this._blockAndLogStreamerIfExists.addLogFilter(catchAllLogFilter);
this._blockAndLogStreamIntervalIfExists = intervalUtils.setAsyncExcludingInterval( this._blockAndLogStreamIntervalIfExists = intervalUtils.setAsyncExcludingInterval(
this._reconcileBlockAsync.bind(this), this._reconcileBlockAsync.bind(this),
constants.DEFAULT_BLOCK_POLLING_INTERVAL, constants.DEFAULT_BLOCK_POLLING_INTERVAL,
this._onReconcileBlockError.bind(this), ContractWrapper._onBlockstreamError.bind(this, isVerbose),
); );
let isRemoved = false; let isRemoved = false;
this._onLogAddedSubscriptionToken = this._blockAndLogStreamerIfExists.subscribeToOnLogAdded( this._onLogAddedSubscriptionToken = this._blockAndLogStreamerIfExists.subscribeToOnLogAdded(
@@ -173,18 +188,12 @@ export class ContractWrapper {
this._onLogStateChanged.bind(this, isRemoved), this._onLogStateChanged.bind(this, isRemoved),
); );
} }
private _onReconcileBlockError(err: Error): void {
const filterTokens = _.keys(this._filterCallbacks);
_.each(filterTokens, filterToken => {
this._unsubscribe(filterToken, err);
});
}
private _setNetworkId(networkId: number): void { private _setNetworkId(networkId: number): void {
this._networkId = networkId; this._networkId = networkId;
} }
private _stopBlockAndLogStream(): void { private _stopBlockAndLogStream(): void {
if (_.isUndefined(this._blockAndLogStreamerIfExists)) { if (_.isUndefined(this._blockAndLogStreamerIfExists)) {
throw new Error(ZeroExError.SubscriptionNotFound); throw new Error(ContractWrappersError.SubscriptionNotFound);
} }
this._blockAndLogStreamerIfExists.unsubscribeFromOnLogAdded(this._onLogAddedSubscriptionToken as string); this._blockAndLogStreamerIfExists.unsubscribeFromOnLogAdded(this._onLogAddedSubscriptionToken as string);
this._blockAndLogStreamerIfExists.unsubscribeFromOnLogRemoved(this._onLogRemovedSubscriptionToken as string); this._blockAndLogStreamerIfExists.unsubscribeFromOnLogRemoved(this._onLogRemovedSubscriptionToken as string);

View File

@@ -5,7 +5,7 @@ import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { artifacts } from '../artifacts'; import { artifacts } from '../artifacts';
import { BlockRange, EventCallback, IndexedFilterValues, TransactionOpts, ZeroExError } from '../types'; import { BlockRange, ContractWrappersError, EventCallback, IndexedFilterValues, TransactionOpts } from '../types';
import { assert } from '../utils/assert'; import { assert } from '../utils/assert';
import { ContractWrapper } from './contract_wrapper'; import { ContractWrapper } from './contract_wrapper';
@@ -48,7 +48,7 @@ export class EtherTokenWrapper extends ContractWrapper {
const normalizedDepositorAddress = depositor.toLowerCase(); const normalizedDepositorAddress = depositor.toLowerCase();
const ethBalanceInWei = await this._web3Wrapper.getBalanceInWeiAsync(normalizedDepositorAddress); const ethBalanceInWei = await this._web3Wrapper.getBalanceInWeiAsync(normalizedDepositorAddress);
assert.assert(ethBalanceInWei.gte(amountInWei), ZeroExError.InsufficientEthBalanceForDeposit); assert.assert(ethBalanceInWei.gte(amountInWei), ContractWrappersError.InsufficientEthBalanceForDeposit);
const wethContract = await this._getEtherTokenContractAsync(normalizedEtherTokenAddress); const wethContract = await this._getEtherTokenContractAsync(normalizedEtherTokenAddress);
const txHash = await wethContract.deposit.sendTransactionAsync({ const txHash = await wethContract.deposit.sendTransactionAsync({
@@ -84,7 +84,10 @@ export class EtherTokenWrapper extends ContractWrapper {
normalizedEtherTokenAddress, normalizedEtherTokenAddress,
normalizedWithdrawerAddress, normalizedWithdrawerAddress,
); );
assert.assert(WETHBalanceInBaseUnits.gte(amountInWei), ZeroExError.InsufficientWEthBalanceForWithdrawal); assert.assert(
WETHBalanceInBaseUnits.gte(amountInWei),
ContractWrappersError.InsufficientWEthBalanceForWithdrawal,
);
const wethContract = await this._getEtherTokenContractAsync(normalizedEtherTokenAddress); const wethContract = await this._getEtherTokenContractAsync(normalizedEtherTokenAddress);
const txHash = await wethContract.withdraw.sendTransactionAsync(amountInWei, { const txHash = await wethContract.withdraw.sendTransactionAsync(amountInWei, {
@@ -119,7 +122,7 @@ export class EtherTokenWrapper extends ContractWrapper {
eventName, eventName,
blockRange, blockRange,
indexFilterValues, indexFilterValues,
artifacts.EtherTokenArtifact.abi, artifacts.EtherToken.abi,
); );
return logs; return logs;
} }
@@ -130,6 +133,7 @@ export class EtherTokenWrapper extends ContractWrapper {
* @param indexFilterValues An object where the keys are indexed args returned by the event and * @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 `{_owner: aUserAddressHex}` * the value is the value you are interested in. E.g `{_owner: aUserAddressHex}`
* @param callback Callback that gets called when a log is added/removed * @param callback Callback that gets called when a log is added/removed
* @param isVerbose Enable verbose subscription warnings (e.g recoverable network issues encountered)
* @return Subscription token used later to unsubscribe * @return Subscription token used later to unsubscribe
*/ */
public subscribe<ArgsType extends EtherTokenContractEventArgs>( public subscribe<ArgsType extends EtherTokenContractEventArgs>(
@@ -137,6 +141,7 @@ export class EtherTokenWrapper extends ContractWrapper {
eventName: EtherTokenEvents, eventName: EtherTokenEvents,
indexFilterValues: IndexedFilterValues, indexFilterValues: IndexedFilterValues,
callback: EventCallback<ArgsType>, callback: EventCallback<ArgsType>,
isVerbose: boolean = false,
): string { ): string {
assert.isETHAddressHex('etherTokenAddress', etherTokenAddress); assert.isETHAddressHex('etherTokenAddress', etherTokenAddress);
const normalizedEtherTokenAddress = etherTokenAddress.toLowerCase(); const normalizedEtherTokenAddress = etherTokenAddress.toLowerCase();
@@ -147,8 +152,9 @@ export class EtherTokenWrapper extends ContractWrapper {
normalizedEtherTokenAddress, normalizedEtherTokenAddress,
eventName, eventName,
indexFilterValues, indexFilterValues,
artifacts.EtherTokenArtifact.abi, artifacts.EtherToken.abi,
callback, callback,
isVerbose,
); );
return subscriptionToken; return subscriptionToken;
} }
@@ -172,7 +178,7 @@ export class EtherTokenWrapper extends ContractWrapper {
* @returns The Ethereum address of the EtherToken contract or undefined. * @returns The Ethereum address of the EtherToken contract or undefined.
*/ */
public getContractAddressIfExists(): string | undefined { public getContractAddressIfExists(): string | undefined {
const networkSpecificArtifact = artifacts.EtherTokenArtifact.networks[this._networkId]; const networkSpecificArtifact = artifacts.EtherToken.networks[this._networkId];
const contractAddressIfExists = _.isUndefined(networkSpecificArtifact) const contractAddressIfExists = _.isUndefined(networkSpecificArtifact)
? undefined ? undefined
: networkSpecificArtifact.address; : networkSpecificArtifact.address;
@@ -188,7 +194,7 @@ export class EtherTokenWrapper extends ContractWrapper {
return etherTokenContract; return etherTokenContract;
} }
const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync( const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync(
artifacts.EtherTokenArtifact, artifacts.EtherToken,
etherTokenAddress, etherTokenAddress,
); );
const contractInstance = new EtherTokenContract( const contractInstance = new EtherTokenContract(

View File

@@ -1,11 +1,16 @@
import { schemas } from '@0xproject/json-schemas'; import { schemas } from '@0xproject/json-schemas';
import { formatters, getOrderHashHex, OrderStateUtils } from '@0xproject/order-utils';
import { import {
BlockParamLiteral, BlockParamLiteral,
DecodedLogArgs, DecodedLogArgs,
ECSignature, ECSignature,
ExchangeContractErrs,
LogEntry, LogEntry,
LogWithDecodedArgs, LogWithDecodedArgs,
Order, Order,
OrderAddresses,
OrderState,
OrderValues,
SignedOrder, SignedOrder,
} from '@0xproject/types'; } from '@0xproject/types';
import { AbiDecoder, BigNumber } from '@0xproject/utils'; import { AbiDecoder, BigNumber } from '@0xproject/utils';
@@ -19,21 +24,16 @@ import {
BlockRange, BlockRange,
EventCallback, EventCallback,
ExchangeContractErrCodes, ExchangeContractErrCodes,
ExchangeContractErrs,
IndexedFilterValues, IndexedFilterValues,
MethodOpts, MethodOpts,
OrderAddresses,
OrderCancellationRequest, OrderCancellationRequest,
OrderFillRequest, OrderFillRequest,
OrderState,
OrderTransactionOpts, OrderTransactionOpts,
OrderValues,
ValidateOrderFillableOpts, ValidateOrderFillableOpts,
} from '../types'; } from '../types';
import { assert } from '../utils/assert'; import { assert } from '../utils/assert';
import { decorators } from '../utils/decorators'; import { decorators } from '../utils/decorators';
import { ExchangeTransferSimulator } from '../utils/exchange_transfer_simulator'; import { ExchangeTransferSimulator } from '../utils/exchange_transfer_simulator';
import { OrderStateUtils } from '../utils/order_state_utils';
import { OrderValidationUtils } from '../utils/order_validation_utils'; import { OrderValidationUtils } from '../utils/order_validation_utils';
import { utils } from '../utils/utils'; import { utils } from '../utils/utils';
@@ -69,24 +69,6 @@ export class ExchangeWrapper extends ContractWrapper {
}; };
private _contractAddressIfExists?: string; private _contractAddressIfExists?: string;
private _zrxContractAddressIfExists?: string; private _zrxContractAddressIfExists?: string;
private static _getOrderAddressesAndValues(order: Order): [OrderAddresses, OrderValues] {
const orderAddresses: OrderAddresses = [
order.maker,
order.taker,
order.makerTokenAddress,
order.takerTokenAddress,
order.feeRecipient,
];
const orderValues: OrderValues = [
order.makerTokenAmount,
order.takerTokenAmount,
order.makerFee,
order.takerFee,
order.expirationUnixTimestampSec,
order.salt,
];
return [orderAddresses, orderValues];
}
constructor( constructor(
web3Wrapper: Web3Wrapper, web3Wrapper: Web3Wrapper,
networkId: number, networkId: number,
@@ -208,7 +190,7 @@ export class ExchangeWrapper extends ContractWrapper {
); );
} }
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(signedOrder); const [orderAddresses, orderValues] = formatters.getOrderAddressesAndValues(signedOrder);
const txHash: string = await exchangeInstance.fillOrder.sendTransactionAsync( const txHash: string = await exchangeInstance.fillOrder.sendTransactionAsync(
orderAddresses, orderAddresses,
@@ -295,7 +277,7 @@ export class ExchangeWrapper extends ContractWrapper {
const orderAddressesValuesAndSignatureArray = _.map(signedOrders, signedOrder => { const orderAddressesValuesAndSignatureArray = _.map(signedOrders, signedOrder => {
return [ return [
...ExchangeWrapper._getOrderAddressesAndValues(signedOrder), ...formatters.getOrderAddressesAndValues(signedOrder),
signedOrder.ecSignature.v, signedOrder.ecSignature.v,
signedOrder.ecSignature.r, signedOrder.ecSignature.r,
signedOrder.ecSignature.s, signedOrder.ecSignature.s,
@@ -383,7 +365,7 @@ export class ExchangeWrapper extends ContractWrapper {
const orderAddressesValuesAmountsAndSignatureArray = _.map(orderFillRequests, orderFillRequest => { const orderAddressesValuesAmountsAndSignatureArray = _.map(orderFillRequests, orderFillRequest => {
return [ return [
...ExchangeWrapper._getOrderAddressesAndValues(orderFillRequest.signedOrder), ...formatters.getOrderAddressesAndValues(orderFillRequest.signedOrder),
orderFillRequest.takerTokenFillAmount, orderFillRequest.takerTokenFillAmount,
orderFillRequest.signedOrder.ecSignature.v, orderFillRequest.signedOrder.ecSignature.v,
orderFillRequest.signedOrder.ecSignature.r, orderFillRequest.signedOrder.ecSignature.r,
@@ -452,7 +434,7 @@ export class ExchangeWrapper extends ContractWrapper {
); );
} }
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(signedOrder); const [orderAddresses, orderValues] = formatters.getOrderAddressesAndValues(signedOrder);
const txHash = await exchangeInstance.fillOrKillOrder.sendTransactionAsync( const txHash = await exchangeInstance.fillOrKillOrder.sendTransactionAsync(
orderAddresses, orderAddresses,
orderValues, orderValues,
@@ -518,7 +500,7 @@ export class ExchangeWrapper extends ContractWrapper {
const orderAddressesValuesAndTakerTokenFillAmounts = _.map(orderFillRequests, request => { const orderAddressesValuesAndTakerTokenFillAmounts = _.map(orderFillRequests, request => {
return [ return [
...ExchangeWrapper._getOrderAddressesAndValues(request.signedOrder), ...formatters.getOrderAddressesAndValues(request.signedOrder),
request.takerTokenFillAmount, request.takerTokenFillAmount,
request.signedOrder.ecSignature.v, request.signedOrder.ecSignature.v,
request.signedOrder.ecSignature.r, request.signedOrder.ecSignature.r,
@@ -570,7 +552,7 @@ export class ExchangeWrapper extends ContractWrapper {
? SHOULD_VALIDATE_BY_DEFAULT ? SHOULD_VALIDATE_BY_DEFAULT
: orderTransactionOpts.shouldValidate; : orderTransactionOpts.shouldValidate;
if (shouldValidate) { if (shouldValidate) {
const orderHash = utils.getOrderHashHex(order); const orderHash = getOrderHashHex(order);
const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash); const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash);
OrderValidationUtils.validateCancelOrderThrowIfInvalid( OrderValidationUtils.validateCancelOrderThrowIfInvalid(
order, order,
@@ -579,7 +561,7 @@ export class ExchangeWrapper extends ContractWrapper {
); );
} }
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(order); const [orderAddresses, orderValues] = formatters.getOrderAddressesAndValues(order);
const txHash = await exchangeInstance.cancelOrder.sendTransactionAsync( const txHash = await exchangeInstance.cancelOrder.sendTransactionAsync(
orderAddresses, orderAddresses,
orderValues, orderValues,
@@ -629,7 +611,7 @@ export class ExchangeWrapper extends ContractWrapper {
: orderTransactionOpts.shouldValidate; : orderTransactionOpts.shouldValidate;
if (shouldValidate) { if (shouldValidate) {
for (const orderCancellationRequest of orderCancellationRequests) { for (const orderCancellationRequest of orderCancellationRequests) {
const orderHash = utils.getOrderHashHex(orderCancellationRequest.order); const orderHash = getOrderHashHex(orderCancellationRequest.order);
const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash); const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash);
OrderValidationUtils.validateCancelOrderThrowIfInvalid( OrderValidationUtils.validateCancelOrderThrowIfInvalid(
orderCancellationRequest.order, orderCancellationRequest.order,
@@ -644,7 +626,7 @@ export class ExchangeWrapper extends ContractWrapper {
const exchangeInstance = await this._getExchangeContractAsync(); const exchangeInstance = await this._getExchangeContractAsync();
const orderAddressesValuesAndTakerTokenCancelAmounts = _.map(orderCancellationRequests, cancellationRequest => { const orderAddressesValuesAndTakerTokenCancelAmounts = _.map(orderCancellationRequests, cancellationRequest => {
return [ return [
...ExchangeWrapper._getOrderAddressesAndValues(cancellationRequest.order), ...formatters.getOrderAddressesAndValues(cancellationRequest.order),
cancellationRequest.takerTokenCancelAmount, cancellationRequest.takerTokenCancelAmount,
]; ];
}); });
@@ -670,12 +652,14 @@ export class ExchangeWrapper extends ContractWrapper {
* @param indexFilterValues An object where the keys are indexed args returned by the event and * @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}` * 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 * @param callback Callback that gets called when a log is added/removed
* @param isVerbose Enable verbose subscription warnings (e.g recoverable network issues encountered)
* @return Subscription token used later to unsubscribe * @return Subscription token used later to unsubscribe
*/ */
public subscribe<ArgsType extends ExchangeContractEventArgs>( public subscribe<ArgsType extends ExchangeContractEventArgs>(
eventName: ExchangeEvents, eventName: ExchangeEvents,
indexFilterValues: IndexedFilterValues, indexFilterValues: IndexedFilterValues,
callback: EventCallback<ArgsType>, callback: EventCallback<ArgsType>,
isVerbose: boolean = false,
): string { ): string {
assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents); assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents);
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
@@ -685,8 +669,9 @@ export class ExchangeWrapper extends ContractWrapper {
exchangeContractAddress, exchangeContractAddress,
eventName, eventName,
indexFilterValues, indexFilterValues,
artifacts.ExchangeArtifact.abi, artifacts.Exchange.abi,
callback, callback,
isVerbose,
); );
return subscriptionToken; return subscriptionToken;
} }
@@ -725,7 +710,7 @@ export class ExchangeWrapper extends ContractWrapper {
eventName, eventName,
blockRange, blockRange,
indexFilterValues, indexFilterValues,
artifacts.ExchangeArtifact.abi, artifacts.Exchange.abi,
); );
return logs; return logs;
} }
@@ -735,7 +720,7 @@ export class ExchangeWrapper extends ContractWrapper {
* @returns The Ethereum address of the Exchange contract being used. * @returns The Ethereum address of the Exchange contract being used.
*/ */
public getContractAddress(): string { public getContractAddress(): string {
const contractAddress = this._getContractAddress(artifacts.ExchangeArtifact, this._contractAddressIfExists); const contractAddress = this._getContractAddress(artifacts.Exchange, this._contractAddressIfExists);
return contractAddress; return contractAddress;
} }
/** /**
@@ -801,7 +786,7 @@ export class ExchangeWrapper extends ContractWrapper {
): Promise<void> { ): Promise<void> {
assert.doesConformToSchema('order', order, schemas.orderSchema); assert.doesConformToSchema('order', order, schemas.orderSchema);
assert.isValidBaseUnitAmount('cancelTakerTokenAmount', cancelTakerTokenAmount); assert.isValidBaseUnitAmount('cancelTakerTokenAmount', cancelTakerTokenAmount);
const orderHash = utils.getOrderHashHex(order); const orderHash = getOrderHashHex(order);
const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash); const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash);
OrderValidationUtils.validateCancelOrderThrowIfInvalid( OrderValidationUtils.validateCancelOrderThrowIfInvalid(
order, order,
@@ -903,7 +888,7 @@ export class ExchangeWrapper extends ContractWrapper {
* @return Address of ZRX token * @return Address of ZRX token
*/ */
public getZRXTokenAddress(): string { public getZRXTokenAddress(): string {
const contractAddress = this._getContractAddress(artifacts.ZRXArtifact, this._zrxContractAddressIfExists); const contractAddress = this._getContractAddress(artifacts.ZRX, this._zrxContractAddressIfExists);
return contractAddress; return contractAddress;
} }
private _invalidateContractInstances(): void { private _invalidateContractInstances(): void {
@@ -933,7 +918,7 @@ export class ExchangeWrapper extends ContractWrapper {
} }
private async _getOrderHashHexUsingContractCallAsync(order: Order | SignedOrder): Promise<string> { private async _getOrderHashHexUsingContractCallAsync(order: Order | SignedOrder): Promise<string> {
const exchangeInstance = await this._getExchangeContractAsync(); const exchangeInstance = await this._getExchangeContractAsync();
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(order); const [orderAddresses, orderValues] = formatters.getOrderAddressesAndValues(order);
const orderHashHex = await exchangeInstance.getOrderHash.callAsync(orderAddresses, orderValues); const orderHashHex = await exchangeInstance.getOrderHash.callAsync(orderAddresses, orderValues);
return orderHashHex; return orderHashHex;
} }
@@ -942,7 +927,7 @@ export class ExchangeWrapper extends ContractWrapper {
return this._exchangeContractIfExists; return this._exchangeContractIfExists;
} }
const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync( const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync(
artifacts.ExchangeArtifact, artifacts.Exchange,
this._contractAddressIfExists, this._contractAddressIfExists,
); );
const contractInstance = new ExchangeContract( const contractInstance = new ExchangeContract(
@@ -954,10 +939,4 @@ export class ExchangeWrapper extends ContractWrapper {
this._exchangeContractIfExists = contractInstance; this._exchangeContractIfExists = contractInstance;
return this._exchangeContractIfExists; return this._exchangeContractIfExists;
} }
private async _getTokenTransferProxyAddressAsync(): Promise<string> {
const exchangeInstance = await this._getExchangeContractAsync();
const tokenTransferProxyAddress = await exchangeInstance.TOKEN_TRANSFER_PROXY_CONTRACT.callAsync();
const tokenTransferProxyAddressLowerCase = tokenTransferProxyAddress.toLowerCase();
return tokenTransferProxyAddressLowerCase;
}
} // tslint:disable:max-file-line-count } // tslint:disable:max-file-line-count

View File

@@ -1,8 +1,9 @@
import { Token } from '@0xproject/types';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { artifacts } from '../artifacts'; import { artifacts } from '../artifacts';
import { Token, TokenMetadata } from '../types'; import { TokenMetadata } from '../types';
import { assert } from '../utils/assert'; import { assert } from '../utils/assert';
import { constants } from '../utils/constants'; import { constants } from '../utils/constants';
@@ -104,10 +105,7 @@ export class TokenRegistryWrapper extends ContractWrapper {
* @returns The Ethereum address of the TokenRegistry contract being used. * @returns The Ethereum address of the TokenRegistry contract being used.
*/ */
public getContractAddress(): string { public getContractAddress(): string {
const contractAddress = this._getContractAddress( const contractAddress = this._getContractAddress(artifacts.TokenRegistry, this._contractAddressIfExists);
artifacts.TokenRegistryArtifact,
this._contractAddressIfExists,
);
return contractAddress; return contractAddress;
} }
private _invalidateContractInstance(): void { private _invalidateContractInstance(): void {
@@ -118,7 +116,7 @@ export class TokenRegistryWrapper extends ContractWrapper {
return this._tokenRegistryContractIfExists; return this._tokenRegistryContractIfExists;
} }
const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync( const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync(
artifacts.TokenRegistryArtifact, artifacts.TokenRegistry,
this._contractAddressIfExists, this._contractAddressIfExists,
); );
const contractInstance = new TokenRegistryContract( const contractInstance = new TokenRegistryContract(

View File

@@ -46,10 +46,7 @@ export class TokenTransferProxyWrapper extends ContractWrapper {
* @returns The Ethereum address of the TokenTransferProxy contract being used. * @returns The Ethereum address of the TokenTransferProxy contract being used.
*/ */
public getContractAddress(): string { public getContractAddress(): string {
const contractAddress = this._getContractAddress( const contractAddress = this._getContractAddress(artifacts.TokenTransferProxy, this._contractAddressIfExists);
artifacts.TokenTransferProxyArtifact,
this._contractAddressIfExists,
);
return contractAddress; return contractAddress;
} }
private _invalidateContractInstance(): void { private _invalidateContractInstance(): void {
@@ -60,7 +57,7 @@ export class TokenTransferProxyWrapper extends ContractWrapper {
return this._tokenTransferProxyContractIfExists; return this._tokenTransferProxyContractIfExists;
} }
const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync( const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync(
artifacts.TokenTransferProxyArtifact, artifacts.TokenTransferProxy,
this._contractAddressIfExists, this._contractAddressIfExists,
); );
const contractInstance = new TokenTransferProxyContract( const contractInstance = new TokenTransferProxyContract(

View File

@@ -5,7 +5,14 @@ import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { artifacts } from '../artifacts'; import { artifacts } from '../artifacts';
import { BlockRange, EventCallback, IndexedFilterValues, MethodOpts, TransactionOpts, ZeroExError } from '../types'; import {
BlockRange,
ContractWrappersError,
EventCallback,
IndexedFilterValues,
MethodOpts,
TransactionOpts,
} from '../types';
import { assert } from '../utils/assert'; import { assert } from '../utils/assert';
import { constants } from '../utils/constants'; import { constants } from '../utils/constants';
@@ -266,7 +273,7 @@ export class TokenWrapper extends ContractWrapper {
const fromAddressBalance = await this.getBalanceAsync(normalizedTokenAddress, normalizedFromAddress); const fromAddressBalance = await this.getBalanceAsync(normalizedTokenAddress, normalizedFromAddress);
if (fromAddressBalance.lessThan(amountInBaseUnits)) { if (fromAddressBalance.lessThan(amountInBaseUnits)) {
throw new Error(ZeroExError.InsufficientBalanceForTransfer); throw new Error(ContractWrappersError.InsufficientBalanceForTransfer);
} }
const txHash = await tokenContract.transfer.sendTransactionAsync(normalizedToAddress, amountInBaseUnits, { const txHash = await tokenContract.transfer.sendTransactionAsync(normalizedToAddress, amountInBaseUnits, {
@@ -316,12 +323,12 @@ export class TokenWrapper extends ContractWrapper {
normalizedSenderAddress, normalizedSenderAddress,
); );
if (fromAddressAllowance.lessThan(amountInBaseUnits)) { if (fromAddressAllowance.lessThan(amountInBaseUnits)) {
throw new Error(ZeroExError.InsufficientAllowanceForTransfer); throw new Error(ContractWrappersError.InsufficientAllowanceForTransfer);
} }
const fromAddressBalance = await this.getBalanceAsync(normalizedTokenAddress, normalizedFromAddress); const fromAddressBalance = await this.getBalanceAsync(normalizedTokenAddress, normalizedFromAddress);
if (fromAddressBalance.lessThan(amountInBaseUnits)) { if (fromAddressBalance.lessThan(amountInBaseUnits)) {
throw new Error(ZeroExError.InsufficientBalanceForTransfer); throw new Error(ContractWrappersError.InsufficientBalanceForTransfer);
} }
const txHash = await tokenContract.transferFrom.sendTransactionAsync( const txHash = await tokenContract.transferFrom.sendTransactionAsync(
@@ -343,6 +350,7 @@ export class TokenWrapper extends ContractWrapper {
* @param indexFilterValues An object where the keys are indexed args returned by the event and * @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}` * 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 * @param callback Callback that gets called when a log is added/removed
* @param isVerbose Enable verbose subscription warnings (e.g recoverable network issues encountered)
* @return Subscription token used later to unsubscribe * @return Subscription token used later to unsubscribe
*/ */
public subscribe<ArgsType extends TokenContractEventArgs>( public subscribe<ArgsType extends TokenContractEventArgs>(
@@ -350,6 +358,7 @@ export class TokenWrapper extends ContractWrapper {
eventName: TokenEvents, eventName: TokenEvents,
indexFilterValues: IndexedFilterValues, indexFilterValues: IndexedFilterValues,
callback: EventCallback<ArgsType>, callback: EventCallback<ArgsType>,
isVerbose: boolean = false,
): string { ): string {
assert.isETHAddressHex('tokenAddress', tokenAddress); assert.isETHAddressHex('tokenAddress', tokenAddress);
const normalizedTokenAddress = tokenAddress.toLowerCase(); const normalizedTokenAddress = tokenAddress.toLowerCase();
@@ -360,8 +369,9 @@ export class TokenWrapper extends ContractWrapper {
normalizedTokenAddress, normalizedTokenAddress,
eventName, eventName,
indexFilterValues, indexFilterValues,
artifacts.TokenArtifact.abi, artifacts.Token.abi,
callback, callback,
isVerbose,
); );
return subscriptionToken; return subscriptionToken;
} }
@@ -403,7 +413,7 @@ export class TokenWrapper extends ContractWrapper {
eventName, eventName,
blockRange, blockRange,
indexFilterValues, indexFilterValues,
artifacts.TokenArtifact.abi, artifacts.Token.abi,
); );
return logs; return logs;
} }
@@ -418,7 +428,7 @@ export class TokenWrapper extends ContractWrapper {
return tokenContract; return tokenContract;
} }
const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync( const [abi, address] = await this._getContractAbiAndAddressFromArtifactsAsync(
artifacts.TokenArtifact, artifacts.Token,
normalizedTokenAddress, normalizedTokenAddress,
); );
const contractInstance = new TokenContract( const contractInstance = new TokenContract(

View File

@@ -1,10 +1,10 @@
import { AbstractBalanceAndProxyAllowanceFetcher } from '@0xproject/order-utils';
import { BlockParamLiteral } from '@0xproject/types'; import { BlockParamLiteral } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import { BalanceAndProxyAllowanceFetcher } from '../abstract/balance_and_proxy_allowance_fetcher';
import { TokenWrapper } from '../contract_wrappers/token_wrapper'; import { TokenWrapper } from '../contract_wrappers/token_wrapper';
export class SimpleBalanceAndProxyAllowanceFetcher implements BalanceAndProxyAllowanceFetcher { export class SimpleBalanceAndProxyAllowanceFetcher implements AbstractBalanceAndProxyAllowanceFetcher {
private _tokenWrapper: TokenWrapper; private _tokenWrapper: TokenWrapper;
private _defaultBlock: BlockParamLiteral; private _defaultBlock: BlockParamLiteral;
constructor(token: TokenWrapper, defaultBlock: BlockParamLiteral) { constructor(token: TokenWrapper, defaultBlock: BlockParamLiteral) {

View File

@@ -1,10 +1,10 @@
import { AbstractOrderFilledCancelledFetcher } from '@0xproject/order-utils';
import { BlockParamLiteral } from '@0xproject/types'; import { BlockParamLiteral } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import { OrderFilledCancelledFetcher } from '../abstract/order_filled_cancelled_fetcher';
import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper'; import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper';
export class SimpleOrderFilledCancelledFetcher implements OrderFilledCancelledFetcher { export class SimpleOrderFilledCancelledFetcher implements AbstractOrderFilledCancelledFetcher {
private _exchangeWrapper: ExchangeWrapper; private _exchangeWrapper: ExchangeWrapper;
private _defaultBlock: BlockParamLiteral; private _defaultBlock: BlockParamLiteral;
constructor(exchange: ExchangeWrapper, defaultBlock: BlockParamLiteral) { constructor(exchange: ExchangeWrapper, defaultBlock: BlockParamLiteral) {
@@ -25,4 +25,12 @@ export class SimpleOrderFilledCancelledFetcher implements OrderFilledCancelledFe
const cancelledTakerAmount = this._exchangeWrapper.getCancelledTakerAmountAsync(orderHash, methodOpts); const cancelledTakerAmount = this._exchangeWrapper.getCancelledTakerAmountAsync(orderHash, methodOpts);
return cancelledTakerAmount; return cancelledTakerAmount;
} }
public async getUnavailableTakerAmountAsync(orderHash: string): Promise<BigNumber> {
const unavailableTakerAmount = await this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash);
return unavailableTakerAmount;
}
public getZRXTokenAddress(): string {
const zrxToken = this._exchangeWrapper.getZRXTokenAddress();
return zrxToken;
}
} }

View File

@@ -0,0 +1,68 @@
export { ContractWrappers } from './contract_wrappers';
export { ExchangeWrapper } from './contract_wrappers/exchange_wrapper';
export { TokenWrapper } from './contract_wrappers/token_wrapper';
export { TokenRegistryWrapper } from './contract_wrappers/token_registry_wrapper';
export { EtherTokenWrapper } from './contract_wrappers/ether_token_wrapper';
export { TokenTransferProxyWrapper } from './contract_wrappers/token_transfer_proxy_wrapper';
export {
ContractWrappersError,
EventCallback,
ContractEvent,
Token,
IndexedFilterValues,
BlockRange,
OrderCancellationRequest,
OrderFillRequest,
ContractEventArgs,
ContractWrappersConfig,
MethodOpts,
OrderTransactionOpts,
TransactionOpts,
LogEvent,
DecodedLogEvent,
OnOrderStateChangeCallback,
} from './types';
export {
BlockParamLiteral,
FilterObject,
BlockParam,
ContractEventArg,
ExchangeContractErrs,
LogWithDecodedArgs,
Order,
Provider,
SignedOrder,
ECSignature,
OrderStateValid,
OrderStateInvalid,
OrderState,
TransactionReceipt,
TransactionReceiptWithDecodedLogs,
} from '@0xproject/types';
export {
EtherTokenContractEventArgs,
WithdrawalContractEventArgs,
DepositContractEventArgs,
EtherTokenEvents,
} from './contract_wrappers/generated/ether_token';
export {
TransferContractEventArgs,
ApprovalContractEventArgs,
TokenContractEventArgs,
TokenEvents,
} from './contract_wrappers/generated/token';
export {
LogErrorContractEventArgs,
LogCancelContractEventArgs,
LogFillContractEventArgs,
ExchangeContractEventArgs,
ExchangeEvents,
} from './contract_wrappers/generated/exchange';
export { BalanceAndProxyAllowanceLazyStore } from './stores/balance_proxy_allowance_lazy_store';
export { OrderFilledCancelledLazyStore } from './stores/order_filled_cancelled_lazy_store';

View File

@@ -0,0 +1,5 @@
export const ContractWrappersConfigSchema = {
id: '/ContractWrappersConfig',
oneOf: [{ $ref: '/ZeroExContractPrivateNetworkConfig' }, { $ref: '/ZeroExContractPublicNetworkConfig' }],
type: 'object',
};

View File

@@ -0,0 +1,35 @@
export const contractWrappersPrivateNetworkConfigSchema = {
id: '/ZeroExContractPrivateNetworkConfig',
properties: {
networkId: {
type: 'number',
minimum: 1,
},
gasPrice: { $ref: '/Number' },
zrxContractAddress: { $ref: '/Address' },
exchangeContractAddress: { $ref: '/Address' },
tokenRegistryContractAddress: { $ref: '/Address' },
tokenTransferProxyContractAddress: { $ref: '/Address' },
orderWatcherConfig: {
type: 'object',
properties: {
pollingIntervalMs: {
type: 'number',
minimum: 0,
},
numConfirmations: {
type: 'number',
minimum: 0,
},
},
},
},
type: 'object',
required: [
'networkId',
'zrxContractAddress',
'exchangeContractAddress',
'tokenRegistryContractAddress',
'tokenTransferProxyContractAddress',
],
};

View File

@@ -0,0 +1,43 @@
const networkNameToId: { [networkName: string]: number } = {
mainnet: 1,
ropsten: 3,
rinkeby: 4,
kovan: 42,
ganache: 50,
};
export const contractWrappersPublicNetworkConfigSchema = {
id: '/ZeroExContractPublicNetworkConfig',
properties: {
networkId: {
type: 'number',
enum: [
networkNameToId.mainnet,
networkNameToId.kovan,
networkNameToId.ropsten,
networkNameToId.rinkeby,
networkNameToId.ganache,
],
},
gasPrice: { $ref: '/Number' },
zrxContractAddress: { $ref: '/Address' },
exchangeContractAddress: { $ref: '/Address' },
tokenRegistryContractAddress: { $ref: '/Address' },
tokenTransferProxyContractAddress: { $ref: '/Address' },
orderWatcherConfig: {
type: 'object',
properties: {
pollingIntervalMs: {
type: 'number',
minimum: 0,
},
numConfirmations: {
type: 'number',
minimum: 0,
},
},
},
},
type: 'object',
required: ['networkId'],
};

View File

@@ -1,14 +1,14 @@
import { AbstractBalanceAndProxyAllowanceFetcher } from '@0xproject/order-utils';
import { BlockParamLiteral } from '@0xproject/types'; import { BlockParamLiteral } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { BalanceAndProxyAllowanceFetcher } from '../abstract/balance_and_proxy_allowance_fetcher';
import { TokenWrapper } from '../contract_wrappers/token_wrapper'; import { TokenWrapper } from '../contract_wrappers/token_wrapper';
/** /**
* Copy on read store for balances/proxyAllowances of tokens/accounts * Copy on read store for balances/proxyAllowances of tokens/accounts
*/ */
export class BalanceAndProxyAllowanceLazyStore implements BalanceAndProxyAllowanceFetcher { export class BalanceAndProxyAllowanceLazyStore implements AbstractBalanceAndProxyAllowanceFetcher {
private _tokenWrapper: TokenWrapper; private _tokenWrapper: TokenWrapper;
private _defaultBlock: BlockParamLiteral; private _defaultBlock: BlockParamLiteral;
private _balance: { private _balance: {

View File

@@ -1,14 +1,14 @@
import { AbstractOrderFilledCancelledFetcher } from '@0xproject/order-utils';
import { BlockParamLiteral } from '@0xproject/types'; import { BlockParamLiteral } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { OrderFilledCancelledFetcher } from '../abstract/order_filled_cancelled_fetcher';
import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper'; import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper';
/** /**
* Copy on read store for filled/cancelled taker amounts * Copy on read store for filled/cancelled taker amounts
*/ */
export class OrderFilledCancelledLazyStore implements OrderFilledCancelledFetcher { export class OrderFilledCancelledLazyStore implements AbstractOrderFilledCancelledFetcher {
private _exchangeWrapper: ExchangeWrapper; private _exchangeWrapper: ExchangeWrapper;
private _defaultBlock: BlockParamLiteral; private _defaultBlock: BlockParamLiteral;
private _filledTakerAmount: { private _filledTakerAmount: {
@@ -64,4 +64,12 @@ export class OrderFilledCancelledLazyStore implements OrderFilledCancelledFetche
this._filledTakerAmount = {}; this._filledTakerAmount = {};
this._cancelledTakerAmount = {}; this._cancelledTakerAmount = {};
} }
public async getUnavailableTakerAmountAsync(orderHash: string): Promise<BigNumber> {
const unavailableTakerAmount = await this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash);
return unavailableTakerAmount;
}
public getZRXTokenAddress(): string {
const zrxToken = this._exchangeWrapper.getZRXTokenAddress();
return zrxToken;
}
} }

View File

@@ -0,0 +1,186 @@
import { BigNumber } from '@0xproject/utils';
import {
BlockParam,
BlockParamLiteral,
ContractAbi,
ContractEventArg,
ExchangeContractErrs,
FilterObject,
LogEntryEvent,
LogWithDecodedArgs,
Order,
OrderState,
SignedOrder,
} from '@0xproject/types';
import { EtherTokenContractEventArgs, EtherTokenEvents } from './contract_wrappers/generated/ether_token';
import { ExchangeContractEventArgs, ExchangeEvents } from './contract_wrappers/generated/exchange';
import { TokenContractEventArgs, TokenEvents } from './contract_wrappers/generated/token';
export enum ContractWrappersError {
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',
ContractNotDeployedOnNetwork = 'CONTRACT_NOT_DEPLOYED_ON_NETWORK',
InsufficientAllowanceForTransfer = 'INSUFFICIENT_ALLOWANCE_FOR_TRANSFER',
InsufficientBalanceForTransfer = 'INSUFFICIENT_BALANCE_FOR_TRANSFER',
InsufficientEthBalanceForDeposit = 'INSUFFICIENT_ETH_BALANCE_FOR_DEPOSIT',
InsufficientWEthBalanceForWithdrawal = 'INSUFFICIENT_WETH_BALANCE_FOR_WITHDRAWAL',
InvalidJump = 'INVALID_JUMP',
OutOfGas = 'OUT_OF_GAS',
SubscriptionNotFound = 'SUBSCRIPTION_NOT_FOUND',
SubscriptionAlreadyPresent = 'SUBSCRIPTION_ALREADY_PRESENT',
}
export enum InternalContractWrappersError {
NoAbiDecoder = 'NO_ABI_DECODER',
ZrxNotInTokenRegistry = 'ZRX_NOT_IN_TOKEN_REGISTRY',
WethNotInTokenRegistry = 'WETH_NOT_IN_TOKEN_REGISTRY',
}
export type LogEvent = LogEntryEvent;
export interface DecodedLogEvent<ArgsType> {
isRemoved: boolean;
log: LogWithDecodedArgs<ArgsType>;
}
export type EventCallback<ArgsType> = (err: null | Error, log?: DecodedLogEvent<ArgsType>) => void;
export enum ExchangeContractErrCodes {
ERROR_FILL_EXPIRED, // Order has already expired
ERROR_FILL_NO_VALUE, // Order has already been fully filled or cancelled
ERROR_FILL_TRUNCATION, // Rounding error too large
ERROR_FILL_BALANCE_ALLOWANCE, // Insufficient balance or allowance for token transfer
ERROR_CANCEL_EXPIRED, // Order has already expired
ERROR_CANCEL_NO_VALUE, // Order has already been fully filled or cancelled
}
export interface ContractEvent {
logIndex: number;
transactionIndex: number;
transactionHash: string;
blockHash: string;
blockNumber: number;
address: string;
type: string;
event: string;
args: ContractEventArgs;
}
export type ContractEventArgs = ExchangeContractEventArgs | TokenContractEventArgs | EtherTokenContractEventArgs;
// [address, name, symbol, decimals, ipfsHash, swarmHash]
export type TokenMetadata = [string, string, string, number, string, string];
export interface Token {
name: string;
address: string;
symbol: string;
decimals: number;
}
export interface TxOpts {
from: string;
gas?: number;
value?: BigNumber;
gasPrice?: BigNumber;
}
export interface TokenAddressBySymbol {
[symbol: string]: string;
}
export type ContractEvents = TokenEvents | ExchangeEvents | EtherTokenEvents;
export interface IndexedFilterValues {
[index: string]: ContractEventArg;
}
export interface BlockRange {
fromBlock: BlockParam;
toBlock: BlockParam;
}
export interface OrderCancellationRequest {
order: Order | SignedOrder;
takerTokenCancelAmount: BigNumber;
}
export interface OrderFillRequest {
signedOrder: SignedOrder;
takerTokenFillAmount: BigNumber;
}
export type AsyncMethod = (...args: any[]) => Promise<any>;
export type SyncMethod = (...args: any[]) => any;
/**
* networkId: The id of the underlying ethereum network your provider is connected to. (1-mainnet, 3-ropsten, 4-rinkeby, 42-kovan, 50-testrpc)
* gasPrice: Gas price to use with every transaction
* exchangeContractAddress: The address of an exchange contract to use
* zrxContractAddress: The address of the ZRX contract to use
* tokenRegistryContractAddress: The address of a token registry contract to use
* tokenTransferProxyContractAddress: The address of the token transfer proxy contract to use
* orderWatcherConfig: All the configs related to the orderWatcher
*/
export interface ContractWrappersConfig {
networkId: number;
gasPrice?: BigNumber;
exchangeContractAddress?: string;
zrxContractAddress?: string;
tokenRegistryContractAddress?: string;
tokenTransferProxyContractAddress?: string;
}
/**
* expectedFillTakerTokenAmount: If specified, the validation method will ensure that the
* supplied order maker has a sufficient allowance/balance to fill this amount of the order's
* takerTokenAmount. If not specified, the validation method ensures that the maker has a sufficient
* allowance/balance to fill the entire remaining order amount.
*/
export interface ValidateOrderFillableOpts {
expectedFillTakerTokenAmount?: BigNumber;
}
/**
* defaultBlock: The block up to which to query the blockchain state. Setting this to a historical block number
* let's the user query the blockchain's state at an arbitrary point in time. In order for this to work, the
* backing Ethereum node must keep the entire historical state of the chain (e.g setting `--pruning=archive`
* flag when running Parity).
*/
export interface MethodOpts {
defaultBlock?: BlockParam;
}
/**
* gasPrice: Gas price in Wei to use for a transaction
* gasLimit: The amount of gas to send with a transaction
*/
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 enum TradeSide {
Maker = 'maker',
Taker = 'taker',
}
export enum TransferType {
Trade = 'trade',
Fee = 'fee',
}
export type OnOrderStateChangeCallback = (err: Error | null, orderState?: OrderState) => void;

View File

@@ -8,13 +8,13 @@ import { BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { signatureUtils } from '../utils/signature_utils'; import { isValidSignature } from '@0xproject/order-utils';
export const assert = { export const assert = {
...sharedAssert, ...sharedAssert,
isValidSignature(orderHash: string, ecSignature: ECSignature, signerAddress: string) { isValidSignature(orderHash: string, ecSignature: ECSignature, signerAddress: string): void {
const isValidSignature = signatureUtils.isValidSignature(orderHash, ecSignature, signerAddress); const isValid = isValidSignature(orderHash, ecSignature, signerAddress);
this.assert(isValidSignature, `Expected order with hash '${orderHash}' to have a valid signature`); this.assert(isValid, `Expected order with hash '${orderHash}' to have a valid signature`);
}, },
async isSenderAddressAsync( async isSenderAddressAsync(
variableName: string, variableName: string,
@@ -28,8 +28,4 @@ export const assert = {
`Specified ${variableName} ${senderAddressHex} isn't available through the supplied web3 provider`, `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

@@ -0,0 +1,12 @@
import { BigNumber } from '@0xproject/utils';
export const constants = {
NULL_ADDRESS: '0x0000000000000000000000000000000000000000',
TESTRPC_NETWORK_ID: 50,
INVALID_JUMP_PATTERN: 'invalid JUMP at',
OUT_OF_GAS_PATTERN: 'out of gas',
INVALID_TAKER_FORMAT: 'instance.taker is not of a type(s) string',
// tslint:disable-next-line:custom-no-magic-numbers
UNLIMITED_ALLOWANCE_IN_BASE_UNITS: new BigNumber(2).pow(256).minus(1),
DEFAULT_BLOCK_POLLING_INTERVAL: 1000,
};

View File

@@ -1,6 +1,6 @@
import * as _ from 'lodash'; import * as _ from 'lodash';
import { AsyncMethod, SyncMethod, ZeroExError } from '../types'; import { AsyncMethod, ContractWrappersError, SyncMethod } from '../types';
import { constants } from './constants'; import { constants } from './constants';
@@ -8,10 +8,10 @@ type ErrorTransformer = (err: Error) => Error;
const contractCallErrorTransformer = (error: Error) => { const contractCallErrorTransformer = (error: Error) => {
if (_.includes(error.message, constants.INVALID_JUMP_PATTERN)) { if (_.includes(error.message, constants.INVALID_JUMP_PATTERN)) {
return new Error(ZeroExError.InvalidJump); return new Error(ContractWrappersError.InvalidJump);
} }
if (_.includes(error.message, constants.OUT_OF_GAS_PATTERN)) { if (_.includes(error.message, constants.OUT_OF_GAS_PATTERN)) {
return new Error(ZeroExError.OutOfGas); return new Error(ContractWrappersError.OutOfGas);
} }
return error; return error;
}; };
@@ -39,7 +39,7 @@ const asyncErrorHandlerFactory = (errorTransformer: ErrorTransformer) => {
// Do not use arrow syntax here. Use a function expression in // Do not use arrow syntax here. Use a function expression in
// order to use the correct value of `this` in this method // order to use the correct value of `this` in this method
// tslint:disable-next-line:only-arrow-functions // tslint:disable-next-line:only-arrow-functions
descriptor.value = async function(...args: any[]) { descriptor.value = async function(...args: any[]): Promise<any> {
try { try {
const result = await originalMethod.apply(this, args); const result = await originalMethod.apply(this, args);
return result; return result;
@@ -66,7 +66,7 @@ const syncErrorHandlerFactory = (errorTransformer: ErrorTransformer) => {
// Do not use arrow syntax here. Use a function expression in // Do not use arrow syntax here. Use a function expression in
// order to use the correct value of `this` in this method // order to use the correct value of `this` in this method
// tslint:disable-next-line:only-arrow-functions // tslint:disable-next-line:only-arrow-functions
descriptor.value = function(...args: any[]) { descriptor.value = function(...args: any[]): any {
try { try {
const result = originalMethod.apply(this, args); const result = originalMethod.apply(this, args);
return result; return result;

View File

@@ -1,10 +1,11 @@
import { BlockParamLiteral } from '@0xproject/types'; import { BlockParamLiteral, ExchangeContractErrs } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { TokenWrapper } from '../contract_wrappers/token_wrapper'; import { TokenWrapper } from '../contract_wrappers/token_wrapper';
import { BalanceAndProxyAllowanceLazyStore } from '../stores/balance_proxy_allowance_lazy_store'; import { BalanceAndProxyAllowanceLazyStore } from '../stores/balance_proxy_allowance_lazy_store';
import { ExchangeContractErrs, TradeSide, TransferType } from '../types'; import { TradeSide, TransferType } from '../types';
import { constants } from '../utils/constants';
enum FailureReason { enum FailureReason {
Balance = 'balance', Balance = 'balance',
@@ -66,6 +67,13 @@ export class ExchangeTransferSimulator {
tradeSide: TradeSide, tradeSide: TradeSide,
transferType: TransferType, transferType: TransferType,
): Promise<void> { ): Promise<void> {
// HACK: When simulating an open order (e.g taker is NULL_ADDRESS), we don't want to adjust balances/
// allowances for the taker. We do however, want to increase the balance of the maker since the maker
// might be relying on those funds to fill subsequent orders or pay the order's fees.
if (from === constants.NULL_ADDRESS && tradeSide === TradeSide.Taker) {
await this._increaseBalanceAsync(tokenAddress, to, amountInBaseUnits);
return;
}
const balance = await this._store.getBalanceAsync(tokenAddress, from); const balance = await this._store.getBalanceAsync(tokenAddress, from);
const proxyAllowance = await this._store.getProxyAllowanceAsync(tokenAddress, from); const proxyAllowance = await this._store.getProxyAllowanceAsync(tokenAddress, from);
if (proxyAllowance.lessThan(amountInBaseUnits)) { if (proxyAllowance.lessThan(amountInBaseUnits)) {

View File

@@ -73,14 +73,14 @@ export const filterUtils = {
return false; return false;
} }
if (!_.isUndefined(filter.topics)) { if (!_.isUndefined(filter.topics)) {
return filterUtils.matchesTopics(log.topics, filter.topics); return filterUtils.doesMatchTopics(log.topics, filter.topics);
} }
return true; return true;
}, },
matchesTopics(logTopics: string[], filterTopics: Array<string[] | string | null>): boolean { doesMatchTopics(logTopics: string[], filterTopics: Array<string[] | string | null>): boolean {
const matchesTopic = _.zipWith(logTopics, filterTopics, filterUtils.matchesTopic.bind(filterUtils)); const matchesTopic = _.zipWith(logTopics, filterTopics, filterUtils.matchesTopic.bind(filterUtils));
const matchesTopics = _.every(matchesTopic); const doesMatchTopics = _.every(matchesTopic);
return matchesTopics; return doesMatchTopics;
}, },
matchesTopic(logTopic: string, filterTopic: string[] | string | null): boolean { matchesTopic(logTopic: string, filterTopic: string[] | string | null): boolean {
if (_.isArray(filterTopic)) { if (_.isArray(filterTopic)) {

View File

@@ -1,10 +1,10 @@
import { Order, SignedOrder } from '@0xproject/types'; import { getOrderHashHex, isValidSignature, OrderError } from '@0xproject/order-utils';
import { ExchangeContractErrs, Order, SignedOrder } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { ZeroEx } from '../0x';
import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper'; import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper';
import { ExchangeContractErrs, TradeSide, TransferType, ZeroExError } from '../types'; import { ContractWrappersError, TradeSide, TransferType } from '../types';
import { constants } from '../utils/constants'; import { constants } from '../utils/constants';
import { utils } from '../utils/utils'; import { utils } from '../utils/utils';
@@ -86,12 +86,12 @@ export class OrderValidationUtils {
private static _validateRemainingFillAmountNotZeroOrThrow( private static _validateRemainingFillAmountNotZeroOrThrow(
takerTokenAmount: BigNumber, takerTokenAmount: BigNumber,
unavailableTakerTokenAmount: BigNumber, unavailableTakerTokenAmount: BigNumber,
) { ): void {
if (takerTokenAmount.eq(unavailableTakerTokenAmount)) { if (takerTokenAmount.eq(unavailableTakerTokenAmount)) {
throw new Error(ExchangeContractErrs.OrderRemainingFillAmountZero); throw new Error(ExchangeContractErrs.OrderRemainingFillAmountZero);
} }
} }
private static _validateOrderNotExpiredOrThrow(expirationUnixTimestampSec: BigNumber) { private static _validateOrderNotExpiredOrThrow(expirationUnixTimestampSec: BigNumber): void {
const currentUnixTimestampSec = utils.getCurrentUnixTimestampSec(); const currentUnixTimestampSec = utils.getCurrentUnixTimestampSec();
if (expirationUnixTimestampSec.lessThan(currentUnixTimestampSec)) { if (expirationUnixTimestampSec.lessThan(currentUnixTimestampSec)) {
throw new Error(ExchangeContractErrs.OrderFillExpired); throw new Error(ExchangeContractErrs.OrderFillExpired);
@@ -113,7 +113,7 @@ export class OrderValidationUtils {
zrxTokenAddress: string, zrxTokenAddress: string,
expectedFillTakerTokenAmount?: BigNumber, expectedFillTakerTokenAmount?: BigNumber,
): Promise<void> { ): Promise<void> {
const orderHash = utils.getOrderHashHex(signedOrder); const orderHash = getOrderHashHex(signedOrder);
const unavailableTakerTokenAmount = await this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash); const unavailableTakerTokenAmount = await this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash);
OrderValidationUtils._validateRemainingFillAmountNotZeroOrThrow( OrderValidationUtils._validateRemainingFillAmountNotZeroOrThrow(
signedOrder.takerTokenAmount, signedOrder.takerTokenAmount,
@@ -124,31 +124,12 @@ export class OrderValidationUtils {
if (!_.isUndefined(expectedFillTakerTokenAmount)) { if (!_.isUndefined(expectedFillTakerTokenAmount)) {
fillTakerTokenAmount = expectedFillTakerTokenAmount; fillTakerTokenAmount = expectedFillTakerTokenAmount;
} }
const fillMakerTokenAmount = OrderValidationUtils._getPartialAmount( await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
exchangeTradeEmulator,
signedOrder,
fillTakerTokenAmount, fillTakerTokenAmount,
signedOrder.takerTokenAmount,
signedOrder.makerTokenAmount,
);
await exchangeTradeEmulator.transferFromAsync(
signedOrder.makerTokenAddress,
signedOrder.maker,
signedOrder.taker, signedOrder.taker,
fillMakerTokenAmount,
TradeSide.Maker,
TransferType.Trade,
);
const makerFeeAmount = OrderValidationUtils._getPartialAmount(
fillTakerTokenAmount,
signedOrder.takerTokenAmount,
signedOrder.makerFee,
);
await exchangeTradeEmulator.transferFromAsync(
zrxTokenAddress, zrxTokenAddress,
signedOrder.maker,
signedOrder.feeRecipient,
makerFeeAmount,
TradeSide.Maker,
TransferType.Fee,
); );
} }
public async validateFillOrderThrowIfInvalidAsync( public async validateFillOrderThrowIfInvalidAsync(
@@ -161,9 +142,9 @@ export class OrderValidationUtils {
if (fillTakerTokenAmount.eq(0)) { if (fillTakerTokenAmount.eq(0)) {
throw new Error(ExchangeContractErrs.OrderFillAmountZero); throw new Error(ExchangeContractErrs.OrderFillAmountZero);
} }
const orderHash = utils.getOrderHashHex(signedOrder); const orderHash = getOrderHashHex(signedOrder);
if (!ZeroEx.isValidSignature(orderHash, signedOrder.ecSignature, signedOrder.maker)) { if (!isValidSignature(orderHash, signedOrder.ecSignature, signedOrder.maker)) {
throw new Error(ZeroExError.InvalidSignature); throw new Error(OrderError.InvalidSignature);
} }
const unavailableTakerTokenAmount = await this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash); const unavailableTakerTokenAmount = await this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash);
OrderValidationUtils._validateRemainingFillAmountNotZeroOrThrow( OrderValidationUtils._validateRemainingFillAmountNotZeroOrThrow(

View File

@@ -0,0 +1,14 @@
import { BigNumber } from '@0xproject/utils';
export const utils = {
spawnSwitchErr(name: string, value: any): Error {
return new Error(`Unexpected switch value: ${value} encountered for ${name}`);
},
getCurrentUnixTimestampSec(): BigNumber {
const milisecondsInSecond = 1000;
return new BigNumber(Date.now() / milisecondsInSecond).round();
},
getCurrentUnixTimestampMs(): BigNumber {
return new BigNumber(Date.now());
},
};

View File

@@ -0,0 +1,50 @@
import { web3Factory } from '@0xproject/dev-utils';
import * as fs from 'fs';
import 'make-promises-safe';
import { ContractWrappers } from '../src';
import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants';
chaiSetup.configure();
// Those tests are slower cause they're talking to a remote node
const TIMEOUT = 10000;
describe('Artifacts', () => {
describe('contracts are deployed on kovan', () => {
const kovanRpcUrl = constants.KOVAN_RPC_URL;
const provider = web3Factory.create({ rpcUrl: kovanRpcUrl }).currentProvider;
const config = {
networkId: constants.KOVAN_NETWORK_ID,
};
const contractWrappers = new ContractWrappers(provider, config);
it('token registry contract is deployed', async () => {
await (contractWrappers.tokenRegistry as any)._getTokenRegistryContractAsync();
}).timeout(TIMEOUT);
it('proxy contract is deployed', async () => {
await (contractWrappers.proxy as any)._getTokenTransferProxyContractAsync();
}).timeout(TIMEOUT);
it('exchange contract is deployed', async () => {
await (contractWrappers.exchange as any)._getExchangeContractAsync();
}).timeout(TIMEOUT);
});
describe('contracts are deployed on ropsten', () => {
const ropstenRpcUrl = constants.ROPSTEN_RPC_URL;
const provider = web3Factory.create({ rpcUrl: ropstenRpcUrl }).currentProvider;
const config = {
networkId: constants.ROPSTEN_NETWORK_ID,
};
const contractWrappers = new ContractWrappers(provider, config);
it('token registry contract is deployed', async () => {
await (contractWrappers.tokenRegistry as any)._getTokenRegistryContractAsync();
}).timeout(TIMEOUT);
it('proxy contract is deployed', async () => {
await (contractWrappers.proxy as any)._getTokenTransferProxyContractAsync();
}).timeout(TIMEOUT);
it('exchange contract is deployed', async () => {
await (contractWrappers.exchange as any)._getExchangeContractAsync();
}).timeout(TIMEOUT);
});
});

View File

@@ -1,27 +1,27 @@
import { BlockchainLifecycle, devConstants, web3Factory } from '@0xproject/dev-utils'; import { BlockchainLifecycle, callbackErrorReporter, devConstants, web3Factory } from '@0xproject/dev-utils';
import { DoneCallback } from '@0xproject/types';
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as chai from 'chai'; import * as chai from 'chai';
import 'make-promises-safe';
import 'mocha'; import 'mocha';
import { import {
ApprovalContractEventArgs, ApprovalContractEventArgs,
BlockParamLiteral, BlockParamLiteral,
BlockRange, BlockRange,
ContractWrappers,
ContractWrappersError,
DecodedLogEvent, DecodedLogEvent,
DepositContractEventArgs, DepositContractEventArgs,
EtherTokenEvents, EtherTokenEvents,
Token, Token,
TransferContractEventArgs, TransferContractEventArgs,
WithdrawalContractEventArgs, WithdrawalContractEventArgs,
ZeroEx,
ZeroExError,
} from '../src'; } from '../src';
import { DoneCallback } from '../src/types';
import { chaiSetup } from './utils/chai_setup'; import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants'; import { constants } from './utils/constants';
import { reportNodeCallbackErrors } from './utils/report_callback_errors';
import { TokenUtils } from './utils/token_utils'; import { TokenUtils } from './utils/token_utils';
import { provider, web3Wrapper } from './utils/web3_wrapper'; import { provider, web3Wrapper } from './utils/web3_wrapper';
@@ -36,13 +36,13 @@ const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
const MAX_REASONABLE_GAS_COST_IN_WEI = 62517; const MAX_REASONABLE_GAS_COST_IN_WEI = 62517;
describe('EtherTokenWrapper', () => { describe('EtherTokenWrapper', () => {
let zeroEx: ZeroEx; let contractWrappers: ContractWrappers;
let tokens: Token[]; let tokens: Token[];
let userAddresses: string[]; let userAddresses: string[];
let addressWithETH: string; let addressWithETH: string;
let wethContractAddress: string; let wethContractAddress: string;
let depositWeiAmount: BigNumber; let depositWeiAmount: BigNumber;
let decimalPlaces: number; const decimalPlaces = 7;
let addressWithoutFunds: string; let addressWithoutFunds: string;
const gasPrice = new BigNumber(1); const gasPrice = new BigNumber(1);
const zeroExConfig = { const zeroExConfig = {
@@ -54,13 +54,12 @@ describe('EtherTokenWrapper', () => {
const depositAmount = new BigNumber(42); const depositAmount = new BigNumber(42);
const withdrawalAmount = new BigNumber(42); const withdrawalAmount = new BigNumber(42);
before(async () => { before(async () => {
zeroEx = new ZeroEx(provider, zeroExConfig); contractWrappers = new ContractWrappers(provider, zeroExConfig);
tokens = await zeroEx.tokenRegistry.getTokensAsync(); tokens = await contractWrappers.tokenRegistry.getTokensAsync();
userAddresses = await zeroEx.getAvailableAddressesAsync(); userAddresses = await web3Wrapper.getAvailableAddressesAsync();
addressWithETH = userAddresses[0]; addressWithETH = userAddresses[0];
wethContractAddress = zeroEx.etherToken.getContractAddressIfExists() as string; wethContractAddress = contractWrappers.etherToken.getContractAddressIfExists() as string;
depositWeiAmount = Web3Wrapper.toWei(new BigNumber(5)); depositWeiAmount = Web3Wrapper.toWei(new BigNumber(5));
decimalPlaces = 7;
addressWithoutFunds = userAddresses[1]; addressWithoutFunds = userAddresses[1];
}); });
beforeEach(async () => { beforeEach(async () => {
@@ -71,14 +70,14 @@ describe('EtherTokenWrapper', () => {
}); });
describe('#getContractAddressIfExists', async () => { describe('#getContractAddressIfExists', async () => {
it('should return contract address if connected to a known network', () => { it('should return contract address if connected to a known network', () => {
const contractAddressIfExists = zeroEx.etherToken.getContractAddressIfExists(); const contractAddressIfExists = contractWrappers.etherToken.getContractAddressIfExists();
expect(contractAddressIfExists).to.not.be.undefined(); expect(contractAddressIfExists).to.not.be.undefined();
}); });
it('should throw if connected to a private network and contract addresses are not specified', () => { it('should throw if connected to a private network and contract addresses are not specified', () => {
const UNKNOWN_NETWORK_NETWORK_ID = 10; const UNKNOWN_NETWORK_NETWORK_ID = 10;
expect( expect(
() => () =>
new ZeroEx(provider, { new ContractWrappers(provider, {
networkId: UNKNOWN_NETWORK_NETWORK_ID, networkId: UNKNOWN_NETWORK_NETWORK_ID,
} as any), } as any),
).to.throw(); ).to.throw();
@@ -86,16 +85,23 @@ describe('EtherTokenWrapper', () => {
}); });
describe('#depositAsync', () => { describe('#depositAsync', () => {
it('should successfully deposit ETH and issue Wrapped ETH tokens', async () => { it('should successfully deposit ETH and issue Wrapped ETH tokens', async () => {
const preETHBalance = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH); const preETHBalance = await web3Wrapper.getBalanceInWeiAsync(addressWithETH);
const preWETHBalance = await zeroEx.token.getBalanceAsync(wethContractAddress, addressWithETH); const preWETHBalance = await contractWrappers.token.getBalanceAsync(wethContractAddress, addressWithETH);
expect(preETHBalance).to.be.bignumber.gt(0); expect(preETHBalance).to.be.bignumber.gt(0);
expect(preWETHBalance).to.be.bignumber.equal(0); expect(preWETHBalance).to.be.bignumber.equal(0);
const txHash = await zeroEx.etherToken.depositAsync(wethContractAddress, depositWeiAmount, addressWithETH); const txHash = await contractWrappers.etherToken.depositAsync(
await zeroEx.awaitTransactionMinedAsync(txHash); wethContractAddress,
depositWeiAmount,
addressWithETH,
);
await web3Wrapper.awaitTransactionMinedAsync(txHash);
const postETHBalanceInWei = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH); const postETHBalanceInWei = await web3Wrapper.getBalanceInWeiAsync(addressWithETH);
const postWETHBalanceInBaseUnits = await zeroEx.token.getBalanceAsync(wethContractAddress, addressWithETH); const postWETHBalanceInBaseUnits = await contractWrappers.token.getBalanceAsync(
wethContractAddress,
addressWithETH,
);
expect(postWETHBalanceInBaseUnits).to.be.bignumber.equal(depositWeiAmount); expect(postWETHBalanceInBaseUnits).to.be.bignumber.equal(depositWeiAmount);
const remainingETHInWei = preETHBalance.minus(depositWeiAmount); const remainingETHInWei = preETHBalance.minus(depositWeiAmount);
@@ -103,34 +109,41 @@ describe('EtherTokenWrapper', () => {
expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI); expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI);
}); });
it('should throw if user has insufficient ETH balance for deposit', async () => { it('should throw if user has insufficient ETH balance for deposit', async () => {
const preETHBalance = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH); const preETHBalance = await web3Wrapper.getBalanceInWeiAsync(addressWithETH);
const extraETHBalance = Web3Wrapper.toWei(new BigNumber(5)); const extraETHBalance = Web3Wrapper.toWei(new BigNumber(5));
const overETHBalanceinWei = preETHBalance.add(extraETHBalance); const overETHBalanceinWei = preETHBalance.add(extraETHBalance);
return expect( return expect(
zeroEx.etherToken.depositAsync(wethContractAddress, overETHBalanceinWei, addressWithETH), contractWrappers.etherToken.depositAsync(wethContractAddress, overETHBalanceinWei, addressWithETH),
).to.be.rejectedWith(ZeroExError.InsufficientEthBalanceForDeposit); ).to.be.rejectedWith(ContractWrappersError.InsufficientEthBalanceForDeposit);
}); });
}); });
describe('#withdrawAsync', () => { describe('#withdrawAsync', () => {
it('should successfully withdraw ETH in return for Wrapped ETH tokens', async () => { it('should successfully withdraw ETH in return for Wrapped ETH tokens', async () => {
const ETHBalanceInWei = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH); const ETHBalanceInWei = await web3Wrapper.getBalanceInWeiAsync(addressWithETH);
await zeroEx.etherToken.depositAsync(wethContractAddress, depositWeiAmount, addressWithETH); await contractWrappers.etherToken.depositAsync(wethContractAddress, depositWeiAmount, addressWithETH);
const expectedPreETHBalance = ETHBalanceInWei.minus(depositWeiAmount); const expectedPreETHBalance = ETHBalanceInWei.minus(depositWeiAmount);
const preETHBalance = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH); const preETHBalance = await web3Wrapper.getBalanceInWeiAsync(addressWithETH);
const preWETHBalance = await zeroEx.token.getBalanceAsync(wethContractAddress, addressWithETH); const preWETHBalance = await contractWrappers.token.getBalanceAsync(wethContractAddress, addressWithETH);
let gasCost = expectedPreETHBalance.minus(preETHBalance); let gasCost = expectedPreETHBalance.minus(preETHBalance);
expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI); expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI);
expect(preWETHBalance).to.be.bignumber.equal(depositWeiAmount); expect(preWETHBalance).to.be.bignumber.equal(depositWeiAmount);
const txHash = await zeroEx.etherToken.withdrawAsync(wethContractAddress, depositWeiAmount, addressWithETH); const txHash = await contractWrappers.etherToken.withdrawAsync(
await zeroEx.awaitTransactionMinedAsync(txHash); wethContractAddress,
depositWeiAmount,
addressWithETH,
);
await web3Wrapper.awaitTransactionMinedAsync(txHash);
const postETHBalance = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH); const postETHBalance = await web3Wrapper.getBalanceInWeiAsync(addressWithETH);
const postWETHBalanceInBaseUnits = await zeroEx.token.getBalanceAsync(wethContractAddress, addressWithETH); const postWETHBalanceInBaseUnits = await contractWrappers.token.getBalanceAsync(
wethContractAddress,
addressWithETH,
);
expect(postWETHBalanceInBaseUnits).to.be.bignumber.equal(0); expect(postWETHBalanceInBaseUnits).to.be.bignumber.equal(0);
const expectedETHBalance = preETHBalance.add(depositWeiAmount).round(decimalPlaces); const expectedETHBalance = preETHBalance.add(depositWeiAmount).round(decimalPlaces);
@@ -138,14 +151,15 @@ describe('EtherTokenWrapper', () => {
expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI); expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI);
}); });
it('should throw if user has insufficient WETH balance for withdrawal', async () => { it('should throw if user has insufficient WETH balance for withdrawal', async () => {
const preWETHBalance = await zeroEx.token.getBalanceAsync(wethContractAddress, addressWithETH); const preWETHBalance = await contractWrappers.token.getBalanceAsync(wethContractAddress, addressWithETH);
expect(preWETHBalance).to.be.bignumber.equal(0); expect(preWETHBalance).to.be.bignumber.equal(0);
// tslint:disable-next-line:custom-no-magic-numbers
const overWETHBalance = preWETHBalance.add(999999999); const overWETHBalance = preWETHBalance.add(999999999);
return expect( return expect(
zeroEx.etherToken.withdrawAsync(wethContractAddress, overWETHBalance, addressWithETH), contractWrappers.etherToken.withdrawAsync(wethContractAddress, overWETHBalance, addressWithETH),
).to.be.rejectedWith(ZeroExError.InsufficientWEthBalanceForWithdrawal); ).to.be.rejectedWith(ContractWrappersError.InsufficientWEthBalanceForWithdrawal);
}); });
}); });
describe('#subscribe', () => { describe('#subscribe', () => {
@@ -157,7 +171,7 @@ describe('EtherTokenWrapper', () => {
etherTokenAddress = etherToken.address; etherTokenAddress = etherToken.address;
}); });
afterEach(() => { afterEach(() => {
zeroEx.etherToken.unsubscribeAll(); contractWrappers.etherToken.unsubscribeAll();
}); });
// Hack: Mocha does not allow a test to be both async and have a `done` callback // 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 `subscribe` callback, // Since we need to await the receipt of the event in the `subscribe` callback,
@@ -166,7 +180,7 @@ describe('EtherTokenWrapper', () => {
// Source: https://github.com/mochajs/mocha/issues/2407 // Source: https://github.com/mochajs/mocha/issues/2407
it('Should receive the Transfer event when tokens are transfered', (done: DoneCallback) => { it('Should receive the Transfer event when tokens are transfered', (done: DoneCallback) => {
(async () => { (async () => {
const callback = reportNodeCallbackErrors(done)( const callback = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<TransferContractEventArgs>) => { (logEvent: DecodedLogEvent<TransferContractEventArgs>) => {
expect(logEvent).to.not.be.undefined(); expect(logEvent).to.not.be.undefined();
expect(logEvent.isRemoved).to.be.false(); expect(logEvent.isRemoved).to.be.false();
@@ -179,9 +193,14 @@ describe('EtherTokenWrapper', () => {
expect(args._value).to.be.bignumber.equal(transferAmount); expect(args._value).to.be.bignumber.equal(transferAmount);
}, },
); );
await zeroEx.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH); await contractWrappers.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH);
zeroEx.etherToken.subscribe(etherTokenAddress, EtherTokenEvents.Transfer, indexFilterValues, callback); contractWrappers.etherToken.subscribe(
await zeroEx.token.transferAsync( etherTokenAddress,
EtherTokenEvents.Transfer,
indexFilterValues,
callback,
);
await contractWrappers.token.transferAsync(
etherTokenAddress, etherTokenAddress,
addressWithETH, addressWithETH,
addressWithoutFunds, addressWithoutFunds,
@@ -191,7 +210,7 @@ describe('EtherTokenWrapper', () => {
}); });
it('Should receive the Approval event when allowance is being set', (done: DoneCallback) => { it('Should receive the Approval event when allowance is being set', (done: DoneCallback) => {
(async () => { (async () => {
const callback = reportNodeCallbackErrors(done)( const callback = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => { (logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
expect(logEvent).to.not.be.undefined(); expect(logEvent).to.not.be.undefined();
expect(logEvent.isRemoved).to.be.false(); expect(logEvent.isRemoved).to.be.false();
@@ -201,8 +220,13 @@ describe('EtherTokenWrapper', () => {
expect(args._value).to.be.bignumber.equal(allowanceAmount); expect(args._value).to.be.bignumber.equal(allowanceAmount);
}, },
); );
zeroEx.etherToken.subscribe(etherTokenAddress, EtherTokenEvents.Approval, indexFilterValues, callback); contractWrappers.etherToken.subscribe(
await zeroEx.token.setAllowanceAsync( etherTokenAddress,
EtherTokenEvents.Approval,
indexFilterValues,
callback,
);
await contractWrappers.token.setAllowanceAsync(
etherTokenAddress, etherTokenAddress,
addressWithETH, addressWithETH,
addressWithoutFunds, addressWithoutFunds,
@@ -212,7 +236,7 @@ describe('EtherTokenWrapper', () => {
}); });
it('Should receive the Deposit event when ether is being deposited', (done: DoneCallback) => { it('Should receive the Deposit event when ether is being deposited', (done: DoneCallback) => {
(async () => { (async () => {
const callback = reportNodeCallbackErrors(done)( const callback = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<DepositContractEventArgs>) => { (logEvent: DecodedLogEvent<DepositContractEventArgs>) => {
expect(logEvent).to.not.be.undefined(); expect(logEvent).to.not.be.undefined();
expect(logEvent.isRemoved).to.be.false(); expect(logEvent.isRemoved).to.be.false();
@@ -221,13 +245,18 @@ describe('EtherTokenWrapper', () => {
expect(args._value).to.be.bignumber.equal(depositAmount); expect(args._value).to.be.bignumber.equal(depositAmount);
}, },
); );
zeroEx.etherToken.subscribe(etherTokenAddress, EtherTokenEvents.Deposit, indexFilterValues, callback); contractWrappers.etherToken.subscribe(
await zeroEx.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH); etherTokenAddress,
EtherTokenEvents.Deposit,
indexFilterValues,
callback,
);
await contractWrappers.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH);
})().catch(done); })().catch(done);
}); });
it('Should receive the Withdrawal event when ether is being withdrawn', (done: DoneCallback) => { it('Should receive the Withdrawal event when ether is being withdrawn', (done: DoneCallback) => {
(async () => { (async () => {
const callback = reportNodeCallbackErrors(done)( const callback = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<WithdrawalContractEventArgs>) => { (logEvent: DecodedLogEvent<WithdrawalContractEventArgs>) => {
expect(logEvent).to.not.be.undefined(); expect(logEvent).to.not.be.undefined();
expect(logEvent.isRemoved).to.be.false(); expect(logEvent.isRemoved).to.be.false();
@@ -236,39 +265,39 @@ describe('EtherTokenWrapper', () => {
expect(args._value).to.be.bignumber.equal(depositAmount); expect(args._value).to.be.bignumber.equal(depositAmount);
}, },
); );
await zeroEx.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH); await contractWrappers.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH);
zeroEx.etherToken.subscribe( contractWrappers.etherToken.subscribe(
etherTokenAddress, etherTokenAddress,
EtherTokenEvents.Withdrawal, EtherTokenEvents.Withdrawal,
indexFilterValues, indexFilterValues,
callback, callback,
); );
await zeroEx.etherToken.withdrawAsync(etherTokenAddress, withdrawalAmount, addressWithETH); await contractWrappers.etherToken.withdrawAsync(etherTokenAddress, withdrawalAmount, addressWithETH);
})().catch(done); })().catch(done);
}); });
it('should cancel outstanding subscriptions when ZeroEx.setProvider is called', (done: DoneCallback) => { it('should cancel outstanding subscriptions when ZeroEx.setProvider is called', (done: DoneCallback) => {
(async () => { (async () => {
const callbackNeverToBeCalled = reportNodeCallbackErrors(done)( const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => { (logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
done(new Error('Expected this subscription to have been cancelled')); done(new Error('Expected this subscription to have been cancelled'));
}, },
); );
zeroEx.etherToken.subscribe( contractWrappers.etherToken.subscribe(
etherTokenAddress, etherTokenAddress,
EtherTokenEvents.Transfer, EtherTokenEvents.Transfer,
indexFilterValues, indexFilterValues,
callbackNeverToBeCalled, callbackNeverToBeCalled,
); );
const callbackToBeCalled = reportNodeCallbackErrors(done)(); const callbackToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)();
zeroEx.setProvider(provider, constants.TESTRPC_NETWORK_ID); contractWrappers.setProvider(provider, constants.TESTRPC_NETWORK_ID);
await zeroEx.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH); await contractWrappers.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH);
zeroEx.etherToken.subscribe( contractWrappers.etherToken.subscribe(
etherTokenAddress, etherTokenAddress,
EtherTokenEvents.Transfer, EtherTokenEvents.Transfer,
indexFilterValues, indexFilterValues,
callbackToBeCalled, callbackToBeCalled,
); );
await zeroEx.token.transferAsync( await contractWrappers.token.transferAsync(
etherTokenAddress, etherTokenAddress,
addressWithETH, addressWithETH,
addressWithoutFunds, addressWithoutFunds,
@@ -278,20 +307,20 @@ describe('EtherTokenWrapper', () => {
}); });
it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => { it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => {
(async () => { (async () => {
const callbackNeverToBeCalled = reportNodeCallbackErrors(done)( const callbackNeverToBeCalled = callbackErrorReporter.reportNodeCallbackErrors(done)(
(logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => { (logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
done(new Error('Expected this subscription to have been cancelled')); done(new Error('Expected this subscription to have been cancelled'));
}, },
); );
await zeroEx.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH); await contractWrappers.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH);
const subscriptionToken = zeroEx.etherToken.subscribe( const subscriptionToken = contractWrappers.etherToken.subscribe(
etherTokenAddress, etherTokenAddress,
EtherTokenEvents.Transfer, EtherTokenEvents.Transfer,
indexFilterValues, indexFilterValues,
callbackNeverToBeCalled, callbackNeverToBeCalled,
); );
zeroEx.etherToken.unsubscribe(subscriptionToken); contractWrappers.etherToken.unsubscribe(subscriptionToken);
await zeroEx.token.transferAsync( await contractWrappers.token.transferAsync(
etherTokenAddress, etherTokenAddress,
addressWithETH, addressWithETH,
addressWithoutFunds, addressWithoutFunds,
@@ -314,14 +343,14 @@ describe('EtherTokenWrapper', () => {
const tokenUtils = new TokenUtils(tokens); const tokenUtils = new TokenUtils(tokens);
const etherToken = tokenUtils.getWethTokenOrThrow(); const etherToken = tokenUtils.getWethTokenOrThrow();
etherTokenAddress = etherToken.address; etherTokenAddress = etherToken.address;
tokenTransferProxyAddress = zeroEx.proxy.getContractAddress(); tokenTransferProxyAddress = contractWrappers.proxy.getContractAddress();
}); });
it('should get logs with decoded args emitted by Approval', async () => { it('should get logs with decoded args emitted by Approval', async () => {
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH); txHash = await contractWrappers.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const eventName = EtherTokenEvents.Approval; const eventName = EtherTokenEvents.Approval;
const indexFilterValues = {}; const indexFilterValues = {};
const logs = await zeroEx.etherToken.getLogsAsync<ApprovalContractEventArgs>( const logs = await contractWrappers.etherToken.getLogsAsync<ApprovalContractEventArgs>(
etherTokenAddress, etherTokenAddress,
eventName, eventName,
blockRange, blockRange,
@@ -332,13 +361,13 @@ describe('EtherTokenWrapper', () => {
expect(logs[0].event).to.be.equal(eventName); expect(logs[0].event).to.be.equal(eventName);
expect(args._owner).to.be.equal(addressWithETH); expect(args._owner).to.be.equal(addressWithETH);
expect(args._spender).to.be.equal(tokenTransferProxyAddress); expect(args._spender).to.be.equal(tokenTransferProxyAddress);
expect(args._value).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); expect(args._value).to.be.bignumber.equal(contractWrappers.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
}); });
it('should get logs with decoded args emitted by Deposit', async () => { it('should get logs with decoded args emitted by Deposit', async () => {
await zeroEx.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH); await contractWrappers.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH);
const eventName = EtherTokenEvents.Deposit; const eventName = EtherTokenEvents.Deposit;
const indexFilterValues = {}; const indexFilterValues = {};
const logs = await zeroEx.etherToken.getLogsAsync<DepositContractEventArgs>( const logs = await contractWrappers.etherToken.getLogsAsync<DepositContractEventArgs>(
etherTokenAddress, etherTokenAddress,
eventName, eventName,
blockRange, blockRange,
@@ -351,11 +380,11 @@ describe('EtherTokenWrapper', () => {
expect(args._value).to.be.bignumber.equal(depositAmount); expect(args._value).to.be.bignumber.equal(depositAmount);
}); });
it('should only get the logs with the correct event name', async () => { it('should only get the logs with the correct event name', async () => {
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH); txHash = await contractWrappers.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
const differentEventName = EtherTokenEvents.Transfer; const differentEventName = EtherTokenEvents.Transfer;
const indexFilterValues = {}; const indexFilterValues = {};
const logs = await zeroEx.etherToken.getLogsAsync( const logs = await contractWrappers.etherToken.getLogsAsync(
etherTokenAddress, etherTokenAddress,
differentEventName, differentEventName,
blockRange, blockRange,
@@ -364,15 +393,18 @@ describe('EtherTokenWrapper', () => {
expect(logs).to.have.length(0); expect(logs).to.have.length(0);
}); });
it('should only get the logs with the correct indexed fields', async () => { it('should only get the logs with the correct indexed fields', async () => {
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH); txHash = await contractWrappers.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH);
await zeroEx.awaitTransactionMinedAsync(txHash); await web3Wrapper.awaitTransactionMinedAsync(txHash);
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithoutFunds); txHash = await contractWrappers.token.setUnlimitedProxyAllowanceAsync(
await zeroEx.awaitTransactionMinedAsync(txHash); etherTokenAddress,
addressWithoutFunds,
);
await web3Wrapper.awaitTransactionMinedAsync(txHash);
const eventName = EtherTokenEvents.Approval; const eventName = EtherTokenEvents.Approval;
const indexFilterValues = { const indexFilterValues = {
_owner: addressWithETH, _owner: addressWithETH,
}; };
const logs = await zeroEx.etherToken.getLogsAsync<ApprovalContractEventArgs>( const logs = await contractWrappers.etherToken.getLogsAsync<ApprovalContractEventArgs>(
etherTokenAddress, etherTokenAddress,
eventName, eventName,
blockRange, blockRange,

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