Compare commits
616 Commits
@0xproject
...
@0xproject
Author | SHA1 | Date | |
---|---|---|---|
|
f684cc3711 | ||
|
ab0c8c3496 | ||
|
47534b200d | ||
|
f2976af734 | ||
|
ee463058f1 | ||
|
c36a7471a8 | ||
|
6ea8cee551 | ||
|
69806c8839 | ||
|
690036aa30 | ||
|
eda6b8d01b | ||
|
cbf06b2165 | ||
|
e884eb9882 | ||
|
f8cbfea4a1 | ||
|
e01c0f054d | ||
|
12dc8c0d15 | ||
|
cb3582289f | ||
|
734d220d60 | ||
|
d725de7286 | ||
|
3e91773cd9 | ||
|
dc1d2a33a5 | ||
|
ac4074911d | ||
|
66cf60f9cb | ||
|
fffe8c355e | ||
|
b94d13b413 | ||
|
85e16c1233 | ||
|
2d53b7d9a4 | ||
|
23052a5c2e | ||
|
42b3a7c9d7 | ||
|
33315046cd | ||
|
2cf647d5ad | ||
|
b1d88ca643 | ||
|
b79b48cfbe | ||
|
a2bf19efc1 | ||
|
6636a0861d | ||
|
5d4078bcf4 | ||
|
396e3d3ec2 | ||
|
e88b01ed5b | ||
|
cb11aec84d | ||
|
3e3587c281 | ||
|
972e1675f6 | ||
|
05ee368763 | ||
|
291e2c8fa0 | ||
|
ad61fe4b54 | ||
|
439fe10e1e | ||
|
d05a36deed | ||
|
03fd73fab8 | ||
|
1d430cf62f | ||
|
9ed05f56d3 | ||
|
23aa3ec5ea | ||
|
a0f5ceddce | ||
|
3171943228 | ||
|
455f74d449 | ||
|
01bc254cd0 | ||
|
2a7cafbf20 | ||
|
bf1603839e | ||
|
8ed776e113 | ||
|
c3508dcdc6 | ||
|
3579f063d6 | ||
|
ecc6cb2b7c | ||
|
de6fe25751 | ||
|
d639a22cff | ||
|
b1f36a9024 | ||
|
d8d15149fc | ||
|
c07de97fd8 | ||
|
78eb79396e | ||
|
abce410897 | ||
|
9594185f11 | ||
|
35c20d505e | ||
|
b829d55752 | ||
|
e92d6ff84f | ||
|
0056c66d32 | ||
|
613fada49f | ||
|
b603197ae8 | ||
|
69b81836fe | ||
|
0be4e1e1b3 | ||
|
14c994ce14 | ||
|
dd39fadce7 | ||
|
5d24022209 | ||
|
c75eaca5b6 | ||
|
53798302da | ||
|
b799a8a108 | ||
|
3d6c0b75a1 | ||
|
c531d734d4 | ||
|
f239522a19 | ||
|
d1c36f50d5 | ||
|
484312e677 | ||
|
0dc5178083 | ||
|
08f2406ca2 | ||
|
41104b2d45 | ||
|
766824120a | ||
|
c39ac903a9 | ||
|
ca2bb60877 | ||
|
3c66f18a46 | ||
|
8a940a800a | ||
|
06bd5a9b03 | ||
|
93518802d6 | ||
|
75f637bd75 | ||
|
e38c7ff076 | ||
|
66fe7b88b0 | ||
|
16179d2f8e | ||
|
1316a2dd2a | ||
|
e5b5fc400a | ||
|
786ea52738 | ||
|
ed6756898f | ||
|
a5d2cbfd6f | ||
|
04268d7f4b | ||
|
156dae1d33 | ||
|
436d78eb93 | ||
|
f269ecd95e | ||
|
1e4fdcf615 | ||
|
b7004b3002 | ||
|
c6af59a3e7 | ||
|
32396b5eca | ||
|
2930537a51 | ||
|
16c91bca0a | ||
|
1f85d31663 | ||
|
684542d073 | ||
|
bab01abe27 | ||
|
c63f76dde7 | ||
|
79bd416c61 | ||
|
7710989dee | ||
|
fb0b7efc45 | ||
|
1af427e4a7 | ||
|
bb6d594ec7 | ||
|
a57dda2c2a | ||
|
a3a2df098b | ||
|
90d1c3e2c9 | ||
|
950406f1f9 | ||
|
064405126d | ||
|
6d447fd8a5 | ||
|
400228e139 | ||
|
edfae32484 | ||
|
1aed970ce3 | ||
|
445ff1e28e | ||
|
df9d3e3e16 | ||
|
4dc6694651 | ||
|
98c01c2f80 | ||
|
f698dd4077 | ||
|
0578116f1d | ||
|
abbad68eb8 | ||
|
90d274ffc4 | ||
|
449fd9f024 | ||
|
22c4ee6ef7 | ||
|
951fbc9b76 | ||
|
89f368a8b8 | ||
|
672c8acaca | ||
|
681617480a | ||
|
95dfac6f9b | ||
|
b2256679be | ||
|
9e914be975 | ||
|
edbe6915e0 | ||
|
fd3e8cd813 | ||
|
b640e2cc49 | ||
|
51af6de624 | ||
|
054c00e323 | ||
|
5664333490 | ||
|
ac78c64f9e | ||
|
1f748afed9 | ||
|
4a73c05435 | ||
|
fe8f2d87c7 | ||
|
a71a1edf2c | ||
|
87209b8f57 | ||
|
13279f1f20 | ||
|
b46dd2e0a2 | ||
|
3eb08735d4 | ||
|
c8e52882ca | ||
|
484dd4c33a | ||
|
94f40a54b4 | ||
|
818a50a3fb | ||
|
2041e9945e | ||
|
126048bac9 | ||
|
274aa50d74 | ||
|
c36d85a46c | ||
|
ac1fbeb962 | ||
|
de8c445f96 | ||
|
c23d42fea5 | ||
|
a0aa21103b | ||
|
ce242b10e2 | ||
|
6d386220d9 | ||
|
7ce1021798 | ||
|
9ad9e1204c | ||
|
a63061f5b2 | ||
|
4997331410 | ||
|
f7f4b6da8d | ||
|
c975676f6c | ||
|
d702c65a5b | ||
|
4391f9913e | ||
|
28c409fc6d | ||
|
449a04d39c | ||
|
4bcd7ba31e | ||
|
5bda301fec | ||
|
84c7c6eb12 | ||
|
a5b7980b06 | ||
|
f746f5bfa3 | ||
|
3ed2eedfda | ||
|
4ce8eaa158 | ||
|
7abb026819 | ||
|
abd55411d4 | ||
|
cb596c1413 | ||
|
6120a43fff | ||
|
02e7354b53 | ||
|
0a0d3503c0 | ||
|
105bcc6664 | ||
|
ceae51fe32 | ||
|
b054080fa1 | ||
|
565010408e | ||
|
5619780cc1 | ||
|
d69143487e | ||
|
2ef763a195 | ||
|
6ba4ed99c4 | ||
|
aec3c83191 | ||
|
19d8449981 | ||
|
91f276d925 | ||
|
6bda6a22e3 | ||
|
1fbe638950 | ||
|
1e9f23ebba | ||
|
bbb768c5cf | ||
|
5678196706 | ||
|
987637abed | ||
|
ff422ecfb2 | ||
|
1fb643cb69 | ||
|
88db8c3724 | ||
|
cf50a82ecc | ||
|
145fea5253 | ||
|
b97f140b78 | ||
|
1dda4d5f78 | ||
|
6f2cb66163 | ||
|
8b29f6f18d | ||
|
2cc410e61f | ||
|
548fda8dba | ||
|
b58bf8259d | ||
|
e6862e9739 | ||
|
7008e882c0 | ||
|
7d59faa650 | ||
|
eaa6484f24 | ||
|
6630b1d8a5 | ||
|
d0916e196c | ||
|
8e74a22c6f | ||
|
2ffcc853fd | ||
|
caeb5cb6ab | ||
|
4f72c527de | ||
|
71cb2e05d1 | ||
|
d1fb61e0de | ||
|
cb7188d473 | ||
|
02f22d9155 | ||
|
707b98849c | ||
|
d778378b37 | ||
|
f3f596b231 | ||
|
276ee9903a | ||
|
16a970b65d | ||
|
1647e45247 | ||
|
3477a84bbd | ||
|
c61fe3ce64 | ||
|
f94dc1fe44 | ||
|
1339aadf4e | ||
|
a14424ae5f | ||
|
f1e7ea118b | ||
|
9c6453e129 | ||
|
a6f9718131 | ||
|
47075edc97 | ||
|
25cee41358 | ||
|
d08d65a3af | ||
|
d14ed71191 | ||
|
f341f62b2b | ||
|
828dffffed | ||
|
af8d24d0eb | ||
|
ca85a97106 | ||
|
5eea829be9 | ||
|
e822e3562d | ||
|
f109d132e4 | ||
|
1fc1eae39a | ||
|
deb6aeae43 | ||
|
f48f126b3a | ||
|
e0d79bd332 | ||
|
5e75aab8ea | ||
|
36125c3539 | ||
|
72ced622d7 | ||
|
b362e2c28e | ||
|
2260a0a4cd | ||
|
3c64b33f5c | ||
|
5301086c68 | ||
|
5687279c8d | ||
|
6c2bf8ed26 | ||
|
f1ecdcf602 | ||
|
1eaefac12b | ||
|
be17b75ad3 | ||
|
0c23f5e07e | ||
|
86e1fa8153 | ||
|
fae0651b0c | ||
|
720641f14c | ||
|
e8495b0c7b | ||
|
e80579a605 | ||
|
5967d39ca9 | ||
|
b82b50e2f0 | ||
|
e893e8c442 | ||
|
3db5efa264 | ||
|
5401c69163 | ||
|
b7030cffd9 | ||
|
73b4b4488e | ||
|
825402b0f9 | ||
|
f23071a214 | ||
|
f1b267cc9f | ||
|
adf1afc6ba | ||
|
0abbdc6b96 | ||
|
598f1dd2d8 | ||
|
594bd2de1c | ||
|
55083316fc | ||
|
8c87394b2b | ||
|
1dba4b85d0 | ||
|
22de68205b | ||
|
f76543ebfa | ||
|
f0c27f98b8 | ||
|
da678ba018 | ||
|
86ed1b4554 | ||
|
06e348f80b | ||
|
f05e0174a0 | ||
|
6bea3ac157 | ||
|
e4d42a079c | ||
|
5bbdb7a8f7 | ||
|
3cf7cb1054 | ||
|
78274440cb | ||
|
e59934ca21 | ||
|
c93bb4ef98 | ||
|
e3763bade2 | ||
|
1ea1c02387 | ||
|
f6321a8e70 | ||
|
08168c6e7d | ||
|
b5030df4e3 | ||
|
8414c18866 | ||
|
038668efdf | ||
|
4441d76725 | ||
|
1f494feec4 | ||
|
1153fa093b | ||
|
c64ec92fb2 | ||
|
20e28d6c70 | ||
|
c0015c2c11 | ||
|
3880f2b3cc | ||
|
293847053a | ||
|
e042f49e27 | ||
|
c036b96848 | ||
|
e95dba2c25 | ||
|
9891d7aaa6 | ||
|
1ce66b4a81 | ||
|
63b1199bd5 | ||
|
47789d770d | ||
|
df58593ff4 | ||
|
e2ef7a74db | ||
|
cde52b10b1 | ||
|
43983f1bb3 | ||
|
eb4adcf797 | ||
|
32568ebf09 | ||
|
c53d195ed0 | ||
|
9b1c9ecb8b | ||
|
8cd204423a | ||
|
2abc5a88c5 | ||
|
4c0bc02c48 | ||
|
16b27c4ae8 | ||
|
dc5f4ab28b | ||
|
f88ecaa035 | ||
|
c0cf47138e | ||
|
e1127dc2e8 | ||
|
5d1b845cad | ||
|
355514ca38 | ||
|
518d0eba84 | ||
|
78fb8d2bdc | ||
|
5673b42ec4 | ||
|
438c8ff807 | ||
|
ee15143dd7 | ||
|
042caa3363 | ||
|
eb667f653c | ||
|
6cbd0d4537 | ||
|
11bf2a0e06 | ||
|
9485e4f4f3 | ||
|
865ee090c8 | ||
|
0fc356740a | ||
|
f285a46d05 | ||
|
1e1c99d8d6 | ||
|
c291419141 | ||
|
290a96d41f | ||
|
ca9518c48c | ||
|
d44d6ccfd8 | ||
|
cec0b2afe3 | ||
|
e85a69655c | ||
|
4b3e038323 | ||
|
c57190dead | ||
|
3d73167f53 | ||
|
2eefec54b4 | ||
|
ab72656fdf | ||
|
b6f2f98db6 | ||
|
c051c48600 | ||
|
04fc16587b | ||
|
f1d5a7d31f | ||
|
7197356928 | ||
|
a75d547af6 | ||
|
bdecb18e3e | ||
|
e2adcaa185 | ||
|
4193893349 | ||
|
53522a98b9 | ||
|
0e856ccfab | ||
|
6093ee7824 | ||
|
46f185bbeb | ||
|
8bfa880371 | ||
|
a7f0d03611 | ||
|
9ce899d3f3 | ||
|
e71c7fdb16 | ||
|
4258e6dab1 | ||
|
e59b683047 | ||
|
3c3033586d | ||
|
166c741beb | ||
|
629a0fa3a5 | ||
|
15ce862334 | ||
|
840557be0d | ||
|
72a00ac2df | ||
|
da0af12834 | ||
|
7617b6681c | ||
|
8e13c477a3 | ||
|
ff334b0e53 | ||
|
a98d6bf496 | ||
|
bbcf669bd9 | ||
|
328ecd0533 | ||
|
ab91717199 | ||
|
e4dfdc6b5c | ||
|
9e673f0073 | ||
|
353abffba9 | ||
|
bead76a5b7 | ||
|
9f5e724aec | ||
|
50bf6a991d | ||
|
1d584b1329 | ||
|
0c5a9fbc2c | ||
|
d5e58ecdd8 | ||
|
d6a9e7520d | ||
|
36b21e6e7b | ||
|
977a6b2794 | ||
|
fcddd503b7 | ||
|
3472bdcfd4 | ||
|
78f0ab3682 | ||
|
5a59ac4c6b | ||
|
0a19ba3014 | ||
|
88bd0f5328 | ||
|
6e2a69976b | ||
|
0500602ac3 | ||
|
e6887dc9d4 | ||
|
082c5c375e | ||
|
5977fa881e | ||
|
128fccb763 | ||
|
65697f5896 | ||
|
ee93f091ea | ||
|
33a8c7a9fb | ||
|
d1065cd266 | ||
|
0e44a630f0 | ||
|
7a21c6854b | ||
|
54ef916b93 | ||
|
4a770dee84 | ||
|
426a412ba1 | ||
|
f862a2af6d | ||
|
32867c9a07 | ||
|
cf0a8b2d05 | ||
|
4a17f5e820 | ||
|
694c37150c | ||
|
b04d07815f | ||
|
e7b523074a | ||
|
4e03155588 | ||
|
3e5abc60d3 | ||
|
edf80aba1a | ||
|
25ec4cf7b0 | ||
|
48b3d85265 | ||
|
ecfee00fec | ||
|
b5ce876327 | ||
|
d1342c6326 | ||
|
d3dcb2fd40 | ||
|
c448d048fd | ||
|
f0b3ee84b4 | ||
|
ab78c54d6a | ||
|
cee0d2706f | ||
|
8dea47f038 | ||
|
b7b1721145 | ||
|
5068f1666a | ||
|
37f0051d83 | ||
|
c780d04cee | ||
|
8c54e9a873 | ||
|
062f85e506 | ||
|
b3c0d54acd | ||
|
3d11afd872 | ||
|
96d15a8931 | ||
|
50915e6007 | ||
|
52007e5864 | ||
|
0c74d5ba01 | ||
|
0cd1959706 | ||
|
55ddf62df2 | ||
|
7f69d26247 | ||
|
b3c01f6750 | ||
|
34beee1edc | ||
|
7bc6a7b23f | ||
|
4a19655fb0 | ||
|
e32c453bc3 | ||
|
7b8d9193e2 | ||
|
74633126ce | ||
|
2fa5bb2028 | ||
|
010e6f8d7f | ||
|
3d5b6ec110 | ||
|
db2917b01c | ||
|
87d34f9c7f | ||
|
d20926e150 | ||
|
c453099f6b | ||
|
08569dbe6c | ||
|
a38ef3655b | ||
|
c586d3e81d | ||
|
c72745b0b2 | ||
|
8935146240 | ||
|
66aaceea91 | ||
|
4fe28ec53c | ||
|
efe8e07854 | ||
|
63dc606a9c | ||
|
131236305b | ||
|
45c9171a2c | ||
|
311d42626a | ||
|
cbf35de4c1 | ||
|
92efc65847 | ||
|
17e41f2391 | ||
|
fcd37808d4 | ||
|
6323badc19 | ||
|
e01468b492 | ||
|
f7f2390ce1 | ||
|
6118561bb5 | ||
|
6a9f10cd36 | ||
|
e7a4e03194 | ||
|
a42e8ae873 | ||
|
bcc5d63516 | ||
|
f97074dc84 | ||
|
bd81124b5a | ||
|
5a18f43b51 | ||
|
924b96ce2a | ||
|
47236dbaec | ||
|
437ac301db | ||
|
215740fab2 | ||
|
c66fc63452 | ||
|
02aefc40f3 | ||
|
cd42ca1bbd | ||
|
05bfd764b6 | ||
|
99f2026ce2 | ||
|
6a8717b294 | ||
|
c3f24a9cea | ||
|
805a055946 | ||
|
c0e17f6136 | ||
|
b38142ddb1 | ||
|
0b29514836 | ||
|
27ce87f652 | ||
|
a61a7b688a | ||
|
f74408f390 | ||
|
f5e0fd8de5 | ||
|
353b6f3d6d | ||
|
cb377f29c2 | ||
|
0e03ef385b | ||
|
ac2c723ec9 | ||
|
3fc0eae4c0 | ||
|
beed223281 | ||
|
9c9ce97525 | ||
|
4bfb1fcc71 | ||
|
15628a1206 | ||
|
a1411e3d52 | ||
|
66750f7349 | ||
|
f7f1397e52 | ||
|
3660ba28d7 | ||
|
351b7557b6 | ||
|
4dc1962f9e | ||
|
335b9629b8 | ||
|
d16f0508bd | ||
|
da03331015 | ||
|
43128234bb | ||
|
bbcee8dfa7 | ||
|
5b8f84f59a | ||
|
cfcbf34305 | ||
|
4bd5789203 | ||
|
c4669013ab | ||
|
3ad6020e19 | ||
|
3fc8645d92 | ||
|
fb812d59b0 | ||
|
3e0371685f | ||
|
3bc3666215 | ||
|
b01a4af99e | ||
|
9745d5348c | ||
|
c858ff61f7 | ||
|
d39c0bee39 | ||
|
5788b90c52 | ||
|
71475d3cea | ||
|
a613c3b7e7 | ||
|
35668fe225 | ||
|
83a2abeee4 | ||
|
49d926013c | ||
|
c068ec5231 | ||
|
86d19657b1 | ||
|
67ad07020d | ||
|
fa2c4160b5 | ||
|
a37f019806 | ||
|
20449a0cb2 | ||
|
856a5c3369 | ||
|
2c193a1244 | ||
|
c4d10a6f2d | ||
|
d6589004c7 | ||
|
519f1318c6 | ||
|
7460a36ce2 | ||
|
c8f6e3f923 | ||
|
7b373e29ea | ||
|
94ce7a54c3 | ||
|
3bb6d8871b | ||
|
e755ed927c | ||
|
d3e03744cd | ||
|
34926eb66a | ||
|
b7585318c7 | ||
|
cf7727debc | ||
|
9133e764a5 | ||
|
c32938fa43 | ||
|
88d020f9f2 | ||
|
54c891a447 | ||
|
a2e1d28efc | ||
|
590552d3e0 |
@@ -5,7 +5,7 @@ jobs:
|
||||
docker:
|
||||
- image: circleci/node:6.12
|
||||
environment:
|
||||
CONTRACTS_COMMIT_HASH: '78fe8dd'
|
||||
CONTRACTS_COMMIT_HASH: '9ed05f5'
|
||||
steps:
|
||||
- checkout
|
||||
- run: echo 'export PATH=$HOME/CIRCLE_PROJECT_REPONAME/node_modules/.bin:$PATH' >> $BASH_ENV
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
- run: wget https://s3.amazonaws.com/testrpc-shapshots/${CONTRACTS_COMMIT_HASH}.zip
|
||||
- run: unzip ${CONTRACTS_COMMIT_HASH}.zip -d testrpc_snapshot
|
||||
- run: node ./node_modules/lerna/bin/lerna.js bootstrap
|
||||
- run: yarn lerna:run bootstrap
|
||||
- run: yarn lerna:run build
|
||||
- run:
|
||||
name: testrpc
|
||||
command: npm run testrpc -- --db testrpc_snapshot
|
||||
|
9
.gitignore
vendored
9
.gitignore
vendored
@@ -63,4 +63,11 @@ lib/
|
||||
_bundles
|
||||
|
||||
# generated documentation
|
||||
docs/
|
||||
generated_docs/
|
||||
|
||||
TODO.md
|
||||
|
||||
packages/website/public/bundle*
|
||||
|
||||
# generated binaries
|
||||
bin/
|
||||
|
@@ -1,62 +1,47 @@
|
||||
# 0x.js CONTRIBUTING.md
|
||||
0x Contribution Guide
|
||||
---------------------
|
||||
|
||||
Thank you for your interest in contributing to 0x.js! We welcome contributions from anyone on the internet, and are grateful for even the smallest of fixes!
|
||||
Thank you for your interest in contributing to 0x protocol! We welcome contributions from anyone on the internet, and are grateful for even the smallest of fixes!
|
||||
|
||||
## Developer's guide
|
||||
### How to contribute
|
||||
|
||||
## How to contribute
|
||||
If you'd like to contribute to 0x protocol, please fork the repo, fix, commit and send a pull request against the `development` branch for the maintainers to review and merge into the main code base. If you wish to submit more complex changes though, please check with a core dev first on [our RocketChat #dev channel](http://chat.0xproject.com) to ensure those changes are in-line with the general philosophy of the project and/or to get some early feedback which can make both your efforts easier as well as our review and merge procedures quick and simple.
|
||||
|
||||
If you'd like to contribute to 0x.js, please fork the repo, fix, commit and send a pull request against the `development` branch for the maintainers to review and merge into the main code base. If you wish to submit more complex changes though, please check up with a core dev first on [our gitter channel](https://gitter.im/0xProject/Lobby) or in the `#dev` channel on our [slack](https://slack.0xproject.com/) to ensure those changes are in line with the general philosophy of the project and/or to get some early feedback which can make both your efforts easier as well as our review and merge procedures quick and simple.
|
||||
|
||||
We encourage a “PR early” approach so create the PR as early as possible even without the fix/feature ready, so that devs and other volunteers know you have picked up the issue. These early PRs should indicate an 'in progress' status by adding the '[WIP]' prefix to the PR title. Please make sure your contributions adhere to our coding guidelines:
|
||||
We encourage a “PR early” approach so create the PR as early as possible even without the fix/feature ready, so that devs and other contributors know you have picked up the issue. These early PRs should indicate an 'in progress' status by adding the '[WIP]' prefix to the PR title. Please make sure your contributions adhere to our coding guidelines:
|
||||
|
||||
* Pull requests adding features or refactoring should be opened against the `development` branch
|
||||
* Pull requests fixing bugs in the latest release version should be opened again the `master` branch
|
||||
* Write [good commit messages](https://chris.beams.io/posts/git-commit/)
|
||||
|
||||
## Code quality
|
||||
### Code quality
|
||||
|
||||
Because 0x.js is used by multiple relayers in production and their businesses depend on it, we strive for exceptional code quality. Please follow the existing code standards and conventions. `tslint` and `prettier` (described below) will help you.
|
||||
|
||||
Because 0x.js is used by multiple relayers in production and their businesses depend on it, we strive for excellent code quality. Please follow the existing code standards and conventions. `tslint` (described below) will help you.
|
||||
If you're adding functionality, please also add tests and make sure they pass. We have an automatic coverage reporting tool, so we'll see it if they are missing ;)
|
||||
If you're adding a new public function/member, make sure you document it with Java doc-style comments. We use typedoc to generate [awesome documentation](https://0xproject.com/docs/0xjs) from the comments within our source code.
|
||||
|
||||
## Running and building
|
||||
If the sub-package you are modifying has a `CHANGELOG.md` file, make sure to add an entry in it for the change made to the package. For published packages, only changes that modify the public interface or behavior of the package need a CHANGELOG entry.
|
||||
|
||||
First thing to do with an unknown code base is to run the tests.
|
||||
We assume that you have `npm` and `yarn` installed.
|
||||
### Styleguide
|
||||
|
||||
To do that:
|
||||
|
||||
* Install dependencies: `yarn`
|
||||
* Initialize the testrpc state (migrate the contracts) by doing one of the following:
|
||||
* Manual contracts migration:
|
||||
* Run testrpc: `yarn testrpc`
|
||||
* Clone the `[contracts](https://github.com/0xProject/contracts)` repo and run `yarn migrate`
|
||||
* Use one of the existing testrpc snapshots
|
||||
* Check out `circle.yml` for an example
|
||||
* Run tests: `yarn test`
|
||||
|
||||
To build run: `yarn build`
|
||||
|
||||
We also recommend you read through the tests.
|
||||
|
||||
## Styleguide
|
||||
|
||||
We use `[tslint](https://palantir.github.io/tslint/)` with [custom configs](https://github.com/0xProject/tslint-config-0xproject) to keep our code style consistent.
|
||||
We use [TSLint](https://palantir.github.io/tslint/) with [custom configs](https://github.com/0xProject/0x.js/tree/development/packages/tslint-config) to keep our code style consistent.
|
||||
|
||||
To lint your code just run: `yarn lint`
|
||||
|
||||
We also use [Prettier](https://prettier.io/) to auto-format our code. Be sure to either add a [text editor integration](https://prettier.io/docs/en/editors.html) or a [pre-commit hook](https://prettier.io/docs/en/precommit.html) to properly format your code changes.
|
||||
|
||||
If using the Atom text editor, we recommend you install the following packages:
|
||||
|
||||
* [atom-typescript](https://atom.io/packages/atom-typescript)
|
||||
* [linter-tslint](https://atom.io/packages/linter-tslint)
|
||||
* [prettier-atom](https://atom.io/packages/prettier-atom)
|
||||
* [language-ethereum](https://atom.io/packages/language-ethereum)
|
||||
|
||||
Our CI will also run it as a part of the test run when you submit your PR.
|
||||
Our CI will also run TSLint and Prettier as a part of the test run when you submit your PR. Make sure that the CI tests pass for your contribution.
|
||||
|
||||
### Branch structure & versioning
|
||||
|
||||
## Branch structure & versioning
|
||||
|
||||
We use [semantic versioning](http://semver.org/), but before we reach v1.0.0 all breaking changes as well as new features will be minor version bumps.
|
||||
We use [semantic versioning](http://semver.org/), but before a package reaches v1.0.0 all breaking changes as well as new features will be minor version bumps.
|
||||
|
||||
We have two main branches: `master` and `development`.
|
||||
|
||||
|
89
README.md
89
README.md
@@ -17,11 +17,88 @@ This repository contains all the 0x developer tools written in TypeScript. Our h
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
[](https://greenkeeper.io/)
|
||||
|
||||
### Core Packages
|
||||
### Published Packages
|
||||
|
||||
| Package | Version | Description |
|
||||
|--------|-------|------------|
|
||||
| [`0x.js`](/packages/0x.js) | [](https://www.npmjs.com/package/0x.js) | A Javascript library for interacting with the 0x protocol |
|
||||
| [`@0xproject/assert`](/packages/assert) | [](https://www.npmjs.com/package/@0xproject/assert) | Standard type and schema assertions |
|
||||
| [`@0xproject/json-schemas`](/packages/json-schemas) | [](https://www.npmjs.com/package/@0xproject/json-schemas) | 0x-related json schemas |
|
||||
| [`@0xproject/tslint-config`](/packages/tslint-config) | [](https://www.npmjs.com/package/@0xproject/tslint-config) | Custom 0x project TSLint rules |
|
||||
|---------|---------|-------------|
|
||||
| [`0x.js`](/packages/0x.js) | [](https://www.npmjs.com/package/0x.js) | A Javascript library for interacting with the 0x protocol |
|
||||
| [`@0xproject/abi-gen`](/packages/abi-gen) | [](https://www.npmjs.com/package/@0xproject/abi-gen) | Tool to generate TS wrappers from smart contract ABIs |
|
||||
| [`@0xproject/assert`](/packages/assert) | [](https://www.npmjs.com/package/@0xproject/assert) | Type and schema assertions used by our packages |
|
||||
| [`@0xproject/connect`](/packages/connect) | [](https://www.npmjs.com/package/@0xproject/connect) | A Javascript library for interacting with the standard relayer api |
|
||||
| [`@0xproject/json-schemas`](/packages/json-schemas) | [](https://www.npmjs.com/package/@0xproject/json-schemas) | 0x-related json schemas |
|
||||
| [`@0xproject/subproviders`](/packages/subproviders) | [](https://www.npmjs.com/package/@0xproject/subproviders) | Useful web3 subproviders (e.g LedgerSubprovider) |
|
||||
| [`@0xproject/tslint-config`](/packages/tslint-config) | [](https://www.npmjs.com/package/@0xproject/tslint-config) | Custom 0x development TSLint rules |
|
||||
| [`@0xproject/types`](/packages/types) | [](https://www.npmjs.com/package/@0xproject/types) | Shared type declarations |
|
||||
| [`@0xproject/utils`](/packages/utils) | [](https://www.npmjs.com/package/@0xproject/utils) | Shared utilities |
|
||||
| [`@0xproject/web3-wrapper`](/packages/web3-wrapper) | [](https://www.npmjs.com/package/@0xproject/web3-wrapper) | Web3 wrapper |
|
||||
|
||||
### Private Packages
|
||||
|
||||
| Package | Description |
|
||||
|---------|-------------|
|
||||
| [`@0xproject/contracts`](/packages/contracts) | 0x solidity smart contracts & tests |
|
||||
| [`@0xproject/kovan_faucets`](/packages/kovan-faucets) | A faucet micro-service that dispenses test ERC20 tokens or Ether |
|
||||
| [`@0xproject/monorepo-scripts`](/packages/monorepo-scripts) | Shared monorepo scripts |
|
||||
| [`@0xproject/website`](/packages/website) | 0x website & Portal DApp |
|
||||
|
||||
## Usage
|
||||
|
||||
Dedicated documentation pages:
|
||||
- [0x.js Library](https://0xproject.com/docs/0xjs)
|
||||
- [0x Connect](https://0xproject.com/docs/connect)
|
||||
- [Smart contracts](https://0xproject.com/docs/contracts)
|
||||
- [Standard Relayer API](https://github.com/0xProject/standard-relayer-api/blob/master/README.md)
|
||||
|
||||
## 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
|
||||
|
||||
Build all packages
|
||||
|
||||
```bash
|
||||
yarn lerna:run build
|
||||
```
|
||||
|
||||
### Lint
|
||||
|
||||
Lint all packages
|
||||
```bash
|
||||
yarn lerna:run lint
|
||||
```
|
||||
|
||||
### Run Tests
|
||||
|
||||
Before running the tests, you will need to spin up a [TestRPC](https://www.npmjs.com/package/ethereumjs-testrpc) instance and deploy all the 0x smart contracts.
|
||||
|
||||
In a separate terminal, start TestRPC (a convenience command is provided as part of this repo)
|
||||
```bash
|
||||
yarn testrpc
|
||||
```
|
||||
|
||||
Then in your main terminal run
|
||||
```
|
||||
cd packages/contracts
|
||||
yarn migrate
|
||||
cd ..
|
||||
```
|
||||
|
||||
And finally from the root project directory run
|
||||
```bash
|
||||
yarn lerna:run test
|
||||
```
|
||||
|
12
package.json
12
package.json
@@ -7,16 +7,18 @@
|
||||
"scripts": {
|
||||
"testrpc": "testrpc -p 8545 --networkId 50 -m \"${npm_package_config_mnemonic}\"",
|
||||
"lerna:run": "lerna run",
|
||||
"lerna:publish": "lerna run clean; lerna run build; lerna publish"
|
||||
"lerna:rebuild": "lerna run clean; lerna run build;",
|
||||
"lerna:publish": "yarn install; lerna run clean; lerna run build; lerna publish --registry=https://registry.npmjs.org/"
|
||||
},
|
||||
"config": {
|
||||
"mnemonic": "concert load couple harbor equip island argue ramp clarify fence smart topic"
|
||||
"mnemonic": "concert load couple harbor equip island argue ramp clarify fence smart topic"
|
||||
},
|
||||
"devDependencies": {
|
||||
"lerna": "^2.5.1",
|
||||
"@0xproject/utils": "^0.1.0",
|
||||
"async-child-process": "^1.1.1",
|
||||
"semver-sort": "^0.0.4",
|
||||
"ethereumjs-testrpc": "6.0.3",
|
||||
"lerna": "^2.5.1",
|
||||
"publish-release": "0xproject/publish-release",
|
||||
"es6-promisify": "^5.0.0"
|
||||
"semver-sort": "^0.0.4"
|
||||
}
|
||||
}
|
||||
|
@@ -1,6 +1,39 @@
|
||||
# CHANGELOG
|
||||
|
||||
vx.x.x
|
||||
v0.29.0 - _December 28, 2017_
|
||||
------------------------
|
||||
* Assert baseUnit amount supplied to `toUnitAmount` is integer amount. (#287)
|
||||
* `toBaseUnitAmount` throws if amount supplied has too many decimals (#287)
|
||||
|
||||
v0.28.0 - _December 20, 2017_
|
||||
------------------------
|
||||
* 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 `etherTokenContractAddress` from `ZeroEx` constructor arg `ZeroExConfig` (#267)
|
||||
* Rename `SubscriptionOpts` to `BlockRange` (#272)
|
||||
* Add `zeroEx.etherToken.subscribe`, `zeroEx.etherToken.unsubscribe`, `zeroEx.etherToken.unsubscribeAll` (#277)
|
||||
* Add `zeroEx.etherToken.getLogsAsync` (#277)
|
||||
* Add new public types `BlockParamLiteral`, `EtherTokenEvents`, `EtherTokenContractEventArgs`, `DepositContractEventArgs`, `WithdrawalContractEventArgs` (#277)
|
||||
* Support `Deposit` and `Withdraw` events on etherToken (#277)
|
||||
* Improve the error message when taker is not a string (#278)
|
||||
|
||||
v0.27.1 - _November 28, 2017_
|
||||
------------------------
|
||||
* Export `TransactionOpts` type
|
||||
|
||||
v0.27.0 - _November 28, 2017_
|
||||
------------------------
|
||||
* Make `ZeroExConfig` required parameter of `ZeroEx` constructor (#233)
|
||||
* Add a required property `networkId` to `ZeroExConfig` (#233)
|
||||
* Make all `getContractAddress` functions, `zeroEx.exchange.subscribe`, `zeroEx.exchange.getZRXTokenAddress` sync (#233)
|
||||
* Remove `ZeroExError.ContractNotFound` and replace it with contract-specific errors (#233)
|
||||
* Make `DecodedLogEvent<A>` contain `LogWithDecodedArgs<A>` under log key instead of merging it in like web3 does (#234)
|
||||
* Rename `removed` to `isRemoved` in `DecodedLogEvent<A>` (#234)
|
||||
* Add config allowing to specify gasPrice and gasLimit for every transaction sending method (#235)
|
||||
* All transaction sending methods now call `estimateGas` if no gas amount was supplied (#235)
|
||||
* Modify order validation methods to validate against the `latest` block, not against the `pending` block (#236)
|
||||
|
||||
v0.26.0 - _November 21, 2017_
|
||||
------------------------
|
||||
* Add post-formatter for logs converting `blockNumber`, `logIndex`, `transactionIndex` from hexes to numbers (#231)
|
||||
* Remove support for Async callback types when used in Subscribe functions (#222)
|
||||
|
26
packages/0x.js/contract_templates/contract.mustache
Normal file
26
packages/0x.js/contract_templates/contract.mustache
Normal file
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* This file is auto-generated using abi-gen. Don't edit directly.
|
||||
* Templates can be found at https://github.com/0xProject/0x.js/tree/development/packages/abi-gen-templates.
|
||||
*/
|
||||
// tslint:disable-next-line:no-unused-variable
|
||||
import {TxData, TxDataPayable} from '@0xproject/types';
|
||||
import {classUtils, promisify} from '@0xproject/utils';
|
||||
import {BigNumber} from 'bignumber.js';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {BaseContract} from './base_contract';
|
||||
|
||||
export class {{contractName}}Contract extends BaseContract {
|
||||
{{#each methods}}
|
||||
{{#this.constant}}
|
||||
{{> call contractName=../contractName}}
|
||||
{{/this.constant}}
|
||||
{{^this.constant}}
|
||||
{{> tx contractName=../contractName}}
|
||||
{{/this.constant}}
|
||||
{{/each}}
|
||||
constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) {
|
||||
super(web3ContractInstance, defaults);
|
||||
classUtils.bindAll(this, ['web3ContractInstance', 'defaults']);
|
||||
}
|
||||
} // tslint:disable:max-file-line-count
|
15
packages/0x.js/contract_templates/partials/call.mustache
Normal file
15
packages/0x.js/contract_templates/partials/call.mustache
Normal file
@@ -0,0 +1,15 @@
|
||||
public {{this.name}} = {
|
||||
async callAsync(
|
||||
{{> typed_params inputs=inputs}}
|
||||
defaultBlock?: Web3.BlockParam,
|
||||
): Promise<{{> return_type outputs=outputs}}> {
|
||||
const self = this as {{contractName}}Contract;
|
||||
const result = await promisify<{{> return_type outputs=outputs}}>(
|
||||
self.web3ContractInstance.{{this.name}}.call,
|
||||
self.web3ContractInstance,
|
||||
)(
|
||||
{{> params inputs=inputs}}
|
||||
);
|
||||
return result;
|
||||
},
|
||||
};
|
@@ -0,0 +1,3 @@
|
||||
{{#each inputs}}
|
||||
{{name}},
|
||||
{{/each}}
|
@@ -0,0 +1,6 @@
|
||||
{{#singleReturnValue}}
|
||||
{{#returnType outputs.0.type}}{{/returnType}}
|
||||
{{/singleReturnValue}}
|
||||
{{^singleReturnValue}}
|
||||
[{{#each outputs}}{{#returnType type}}{{/returnType}}{{#unless @last}}, {{/unless}}{{/each}}]
|
||||
{{/singleReturnValue}}
|
51
packages/0x.js/contract_templates/partials/tx.mustache
Normal file
51
packages/0x.js/contract_templates/partials/tx.mustache
Normal file
@@ -0,0 +1,51 @@
|
||||
public {{this.name}} = {
|
||||
async sendTransactionAsync(
|
||||
{{> typed_params inputs=inputs}}
|
||||
{{#this.payable}}
|
||||
txData: TxDataPayable = {},
|
||||
{{/this.payable}}
|
||||
{{^this.payable}}
|
||||
txData: TxData = {},
|
||||
{{/this.payable}}
|
||||
): Promise<string> {
|
||||
const self = this as {{contractName}}Contract;
|
||||
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
|
||||
txData,
|
||||
self.{{this.name}}.estimateGasAsync.bind(
|
||||
self,
|
||||
{{> params inputs=inputs}}
|
||||
),
|
||||
);
|
||||
const txHash = await promisify<string>(
|
||||
self.web3ContractInstance.{{this.name}}, self.web3ContractInstance,
|
||||
)(
|
||||
{{> params inputs=inputs}}
|
||||
txDataWithDefaults,
|
||||
);
|
||||
return txHash;
|
||||
},
|
||||
async estimateGasAsync(
|
||||
{{> typed_params inputs=inputs}}
|
||||
txData: TxData = {},
|
||||
): Promise<number> {
|
||||
const self = this as {{contractName}}Contract;
|
||||
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
|
||||
txData,
|
||||
);
|
||||
const gas = await promisify<number>(
|
||||
self.web3ContractInstance.{{this.name}}.estimateGas, self.web3ContractInstance,
|
||||
)(
|
||||
{{> params inputs=inputs}}
|
||||
txDataWithDefaults,
|
||||
);
|
||||
return gas;
|
||||
},
|
||||
getABIEncodedTransactionData(
|
||||
{{> typed_params inputs=inputs}}
|
||||
txData: TxData = {},
|
||||
): string {
|
||||
const self = this as {{contractName}}Contract;
|
||||
const abiEncodedTransactionData = self.web3ContractInstance.{{this.name}}.getData();
|
||||
return abiEncodedTransactionData;
|
||||
},
|
||||
};
|
@@ -0,0 +1,3 @@
|
||||
{{#each inputs}}
|
||||
{{name}}: {{#parameterType type}}{{/parameterType}},
|
||||
{{/each}}
|
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "0x.js",
|
||||
"version": "0.26.0",
|
||||
"version": "0.29.0",
|
||||
"description": "A javascript library for interacting with the 0x protocol",
|
||||
"keywords": [
|
||||
"0x.js",
|
||||
@@ -12,12 +12,13 @@
|
||||
"main": "lib/src/index.js",
|
||||
"types": "lib/src/index.d.ts",
|
||||
"scripts": {
|
||||
"prebuild": "npm run clean",
|
||||
"prebuild": "run-s clean generate_contract_wrappers",
|
||||
"build": "run-p build:umd:prod build:commonjs; exit 0;",
|
||||
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_DIR",
|
||||
"upload_docs_json": "aws s3 cp docs/index.json $S3_URL --profile 0xproject --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --content-type aplication/json",
|
||||
"lint": "tslint src/**/*.ts test/**/*.ts",
|
||||
"test:circleci": "run-s test:coverage report_test_coverage; if [ $CIRCLE_BRANCH = \"development\" ]; then yarn test:umd; fi",
|
||||
"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",
|
||||
"generate_contract_wrappers": "node ../abi-gen/lib/index.js --abiGlob 'src/artifacts/@(Exchange|Token|TokenTransferProxy|EtherToken|TokenRegistry|DummyToken).json' --templates contract_templates --output src/contract_wrappers/generated",
|
||||
"lint": "tslint --project . 'src/**/*.ts' 'test/**/*.ts'",
|
||||
"test:circleci": "run-s test:coverage report_test_coverage && if [ $CIRCLE_BRANCH = \"development\" ]; then yarn test:umd; fi",
|
||||
"test": "run-s clean test:commonjs",
|
||||
"test:umd": "./scripts/test_umd.sh",
|
||||
"test:coverage": "nyc npm run test --all",
|
||||
@@ -30,7 +31,7 @@
|
||||
"test:commonjs": "run-s build:commonjs run_mocha",
|
||||
"pretest:umd": "run-s clean build:umd:dev build:commonjs",
|
||||
"substitute_umd_bundle": "shx mv _bundles/* lib/src",
|
||||
"run_mocha": "mocha lib/test/**/*_test.js --timeout 5000 --bail --exit"
|
||||
"run_mocha": "mocha lib/test/**/*_test.js --timeout 10000 --bail --exit"
|
||||
},
|
||||
"config": {
|
||||
"artifacts": "TokenTransferProxy Exchange TokenRegistry Token EtherToken"
|
||||
@@ -44,26 +45,29 @@
|
||||
"node": ">=6.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@0xproject/tslint-config": "^0.1.1",
|
||||
"@0xproject/abi-gen": "^0.0.4",
|
||||
"@0xproject/dev-utils": "^0.0.3",
|
||||
"@0xproject/tslint-config": "^0.4.0",
|
||||
"@0xproject/types": "^0.1.2",
|
||||
"@types/bintrees": "^1.0.2",
|
||||
"@types/jsonschema": "^1.1.1",
|
||||
"@types/lodash": "^4.14.64",
|
||||
"@types/mocha": "^2.2.41",
|
||||
"@types/node": "^8.0.1",
|
||||
"@types/lodash": "^4.14.86",
|
||||
"@types/mocha": "^2.2.42",
|
||||
"@types/node": "^8.0.53",
|
||||
"@types/sinon": "^2.2.2",
|
||||
"@types/uuid": "^3.4.2",
|
||||
"awesome-typescript-loader": "^3.1.3",
|
||||
"chai": "^4.0.1",
|
||||
"chai-as-promised": "^7.1.0",
|
||||
"chai-as-promised-typescript-typings": "0.0.3",
|
||||
"chai-as-promised-typescript-typings": "^0.0.3",
|
||||
"chai-bignumber": "^2.0.1",
|
||||
"chai-typescript-typings": "^0.0.1",
|
||||
"copyfiles": "^1.2.0",
|
||||
"coveralls": "^3.0.0",
|
||||
"dirty-chai": "^2.0.1",
|
||||
"ethereumjs-testrpc": "4.0.1",
|
||||
"json-loader": "^0.5.4",
|
||||
"mocha": "^4.0.0",
|
||||
"npm-run-all": "^4.0.2",
|
||||
"mocha": "^4.0.1",
|
||||
"npm-run-all": "^4.1.2",
|
||||
"nyc": "^11.0.1",
|
||||
"opn-cli": "^3.1.0",
|
||||
"request": "^2.81.0",
|
||||
@@ -74,20 +78,20 @@
|
||||
"truffle-hdwallet-provider": "^0.0.3",
|
||||
"tslint": "5.8.0",
|
||||
"typedoc": "~0.8.0",
|
||||
"types-bn": "^0.0.1",
|
||||
"types-ethereumjs-util": "0xProject/types-ethereumjs-util",
|
||||
"typescript": "~2.6.1",
|
||||
"web3-provider-engine": "^13.0.1",
|
||||
"web3-typescript-typings": "^0.7.1",
|
||||
"web3-typescript-typings": "^0.7.2",
|
||||
"webpack": "^3.1.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@0xproject/assert": "^0.0.5",
|
||||
"@0xproject/json-schemas": "^0.6.8",
|
||||
"@0xproject/assert": "^0.0.9",
|
||||
"@0xproject/json-schemas": "^0.7.1",
|
||||
"@0xproject/utils": "^0.1.2",
|
||||
"@0xproject/web3-wrapper": "^0.1.2",
|
||||
"bignumber.js": "~4.1.0",
|
||||
"bn.js": "4.11.8",
|
||||
"bintrees": "^1.0.2",
|
||||
"bn.js": "^4.11.8",
|
||||
"compare-versions": "^3.0.1",
|
||||
"es6-promisify": "^5.0.0",
|
||||
"ethereumjs-abi": "^0.6.4",
|
||||
"ethereumjs-blockstream": "^2.0.6",
|
||||
"ethereumjs-util": "^5.1.1",
|
||||
|
@@ -21,8 +21,9 @@ postpublish_utils.getLatestTagAndVersionAsync(subPackageName)
|
||||
})
|
||||
.then(function(release) {
|
||||
console.log('POSTPUBLISH: Release successful, generating docs...');
|
||||
const jsonFilePath = __dirname + '/../' + postpublish_utils.generatedDocsDirectoryName + '/index.json';
|
||||
return execAsync(
|
||||
'JSON_FILE_PATH=' + __dirname + '/../docs/index.json PROJECT_DIR=' + __dirname + '/.. yarn docs:json',
|
||||
'JSON_FILE_PATH=' + jsonFilePath + ' PROJECT_DIR=' + __dirname + '/.. yarn docs:json',
|
||||
{
|
||||
cwd,
|
||||
}
|
||||
|
@@ -1,34 +1,33 @@
|
||||
import * as _ from 'lodash';
|
||||
import {schemas, SchemaValidator} from '@0xproject/json-schemas';
|
||||
import {bigNumberConfigs, intervalUtils} from '@0xproject/utils';
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import {SchemaValidator, schemas} from '@0xproject/json-schemas';
|
||||
import {bigNumberConfigs} from './bignumber_config';
|
||||
import * as ethUtil from 'ethereumjs-util';
|
||||
import {Web3Wrapper} from './web3_wrapper';
|
||||
import {constants} from './utils/constants';
|
||||
import {utils} from './utils/utils';
|
||||
import {signatureUtils} from './utils/signature_utils';
|
||||
import {assert} from './utils/assert';
|
||||
import {AbiDecoder} from './utils/abi_decoder';
|
||||
import {intervalUtils} from './utils/interval_utils';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {artifacts} from './artifacts';
|
||||
import {EtherTokenWrapper} from './contract_wrappers/ether_token_wrapper';
|
||||
import {ExchangeWrapper} from './contract_wrappers/exchange_wrapper';
|
||||
import {TokenRegistryWrapper} from './contract_wrappers/token_registry_wrapper';
|
||||
import {EtherTokenWrapper} from './contract_wrappers/ether_token_wrapper';
|
||||
import {TokenWrapper} from './contract_wrappers/token_wrapper';
|
||||
import {TokenTransferProxyWrapper} from './contract_wrappers/token_transfer_proxy_wrapper';
|
||||
import {TokenWrapper} from './contract_wrappers/token_wrapper';
|
||||
import {OrderStateWatcher} from './order_watcher/order_state_watcher';
|
||||
import {OrderStateUtils} from './utils/order_state_utils';
|
||||
import {zeroExConfigSchema} from './schemas/zero_ex_config_schema';
|
||||
import {
|
||||
ECSignature,
|
||||
ZeroExError,
|
||||
Order,
|
||||
SignedOrder,
|
||||
TransactionReceiptWithDecodedLogs,
|
||||
Web3Provider,
|
||||
ZeroExConfig,
|
||||
OrderStateWatcherConfig,
|
||||
TransactionReceiptWithDecodedLogs,
|
||||
ZeroExError,
|
||||
} from './types';
|
||||
import {zeroExConfigSchema} from './schemas/zero_ex_config_schema';
|
||||
import {AbiDecoder} from './utils/abi_decoder';
|
||||
import {assert} from './utils/assert';
|
||||
import {constants} from './utils/constants';
|
||||
import {decorators} from './utils/decorators';
|
||||
import {signatureUtils} from './utils/signature_utils';
|
||||
import {utils} from './utils/utils';
|
||||
|
||||
// Customize our BigNumber instances
|
||||
bigNumberConfigs.configure();
|
||||
@@ -129,7 +128,7 @@ export class ZeroEx {
|
||||
* @return The amount in units.
|
||||
*/
|
||||
public static toUnitAmount(amount: BigNumber, decimals: number): BigNumber {
|
||||
assert.isBigNumber('amount', amount);
|
||||
assert.isValidBaseUnitAmount('amount', amount);
|
||||
assert.isNumber('decimals', decimals);
|
||||
|
||||
const aUnit = new BigNumber(10).pow(decimals);
|
||||
@@ -150,6 +149,10 @@ export class ZeroEx {
|
||||
|
||||
const unit = new BigNumber(10).pow(decimals);
|
||||
const baseUnitAmount = amount.times(unit);
|
||||
const hasDecimals = baseUnitAmount.decimalPlaces() !== 0;
|
||||
if (hasDecimals) {
|
||||
throw new Error(`Invalid unit amount: ${amount.toString()} - Too many decimal places`);
|
||||
}
|
||||
return baseUnitAmount;
|
||||
}
|
||||
/**
|
||||
@@ -157,6 +160,7 @@ export class ZeroEx {
|
||||
* @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);
|
||||
@@ -169,56 +173,55 @@ export class ZeroEx {
|
||||
* @param config The configuration object. Look up the type for the description.
|
||||
* @return An instance of the 0x.js ZeroEx class.
|
||||
*/
|
||||
constructor(provider: Web3Provider, config?: ZeroExConfig) {
|
||||
constructor(provider: Web3Provider, config: ZeroExConfig) {
|
||||
assert.isWeb3Provider('provider', provider);
|
||||
if (!_.isUndefined(config)) {
|
||||
assert.doesConformToSchema('config', config, zeroExConfigSchema);
|
||||
}
|
||||
assert.doesConformToSchema('config', config, zeroExConfigSchema);
|
||||
const artifactJSONs = _.values(artifacts);
|
||||
const abiArrays = _.map(artifactJSONs, artifact => artifact.abi);
|
||||
this._abiDecoder = new AbiDecoder(abiArrays);
|
||||
const gasPrice = _.isUndefined(config) ? undefined : config.gasPrice;
|
||||
const defaults = {
|
||||
gasPrice,
|
||||
gasPrice: config.gasPrice,
|
||||
};
|
||||
this._web3Wrapper = new Web3Wrapper(provider, defaults);
|
||||
this.token = new TokenWrapper(
|
||||
this._web3Wrapper,
|
||||
this._abiDecoder,
|
||||
this._getTokenTransferProxyAddressAsync.bind(this),
|
||||
);
|
||||
const exchageContractAddressIfExists = _.isUndefined(config) ? undefined : config.exchangeContractAddress;
|
||||
this.exchange = new ExchangeWrapper(
|
||||
this._web3Wrapper,
|
||||
this._abiDecoder,
|
||||
this.token,
|
||||
exchageContractAddressIfExists,
|
||||
);
|
||||
this.proxy = new TokenTransferProxyWrapper(
|
||||
this._web3Wrapper,
|
||||
this._getTokenTransferProxyAddressAsync.bind(this),
|
||||
config.networkId,
|
||||
config.tokenTransferProxyContractAddress,
|
||||
);
|
||||
this.token = new TokenWrapper(
|
||||
this._web3Wrapper,
|
||||
config.networkId,
|
||||
this._abiDecoder,
|
||||
this.proxy,
|
||||
);
|
||||
this.exchange = new ExchangeWrapper(
|
||||
this._web3Wrapper,
|
||||
config.networkId,
|
||||
this._abiDecoder,
|
||||
this.token,
|
||||
config.exchangeContractAddress,
|
||||
);
|
||||
this.tokenRegistry = new TokenRegistryWrapper(
|
||||
this._web3Wrapper, config.networkId, config.tokenRegistryContractAddress,
|
||||
);
|
||||
this.etherToken = new EtherTokenWrapper(
|
||||
this._web3Wrapper, config.networkId, this._abiDecoder, this.token,
|
||||
);
|
||||
const tokenRegistryContractAddressIfExists = _.isUndefined(config) ?
|
||||
undefined :
|
||||
config.tokenRegistryContractAddress;
|
||||
this.tokenRegistry = new TokenRegistryWrapper(this._web3Wrapper, tokenRegistryContractAddressIfExists);
|
||||
const etherTokenContractAddressIfExists = _.isUndefined(config) ? undefined : config.etherTokenContractAddress;
|
||||
this.etherToken = new EtherTokenWrapper(this._web3Wrapper, this.token, etherTokenContractAddressIfExists);
|
||||
const orderWatcherConfig = _.isUndefined(config) ? undefined : config.orderWatcherConfig;
|
||||
this.orderStateWatcher = new OrderStateWatcher(
|
||||
this._web3Wrapper, this._abiDecoder, this.token, this.exchange, orderWatcherConfig,
|
||||
this._web3Wrapper, this._abiDecoder, this.token, this.exchange, config.orderWatcherConfig,
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Sets a new web3 provider for 0x.js. Updating the provider will stop all
|
||||
* subscriptions so you will need to re-subscribe to all events relevant to your app after this call.
|
||||
* @param provider The Web3Provider you would like the 0x.js library to use from now on.
|
||||
* @param networkId The id of the network your provider is connected to
|
||||
*/
|
||||
public async setProviderAsync(provider: Web3Provider) {
|
||||
this._web3Wrapper.setProvider(provider);
|
||||
await (this.exchange as any)._invalidateContractInstancesAsync();
|
||||
public setProvider(provider: Web3Provider, networkId: number): void {
|
||||
this._web3Wrapper.setProvider(provider, networkId);
|
||||
(this.exchange as any)._invalidateContractInstances();
|
||||
(this.tokenRegistry as any)._invalidateContractInstance();
|
||||
await (this.token as any)._invalidateContractInstancesAsync();
|
||||
(this.token as any)._invalidateContractInstances();
|
||||
(this.proxy as any)._invalidateContractInstance();
|
||||
(this.etherToken as any)._invalidateContractInstance();
|
||||
}
|
||||
|
@@ -1,11 +1,15 @@
|
||||
import {Artifact} from './types';
|
||||
import * as TokenArtifact from './artifacts/Token.json';
|
||||
import * as ExchangeArtifact from './artifacts/Exchange.json';
|
||||
import * as DummyTokenArtifact from './artifacts/DummyToken.json';
|
||||
import * as EtherTokenArtifact from './artifacts/EtherToken.json';
|
||||
import * as ExchangeArtifact from './artifacts/Exchange.json';
|
||||
import * as TokenArtifact from './artifacts/Token.json';
|
||||
import * as TokenRegistryArtifact from './artifacts/TokenRegistry.json';
|
||||
import * as TokenTransferProxyArtifact from './artifacts/TokenTransferProxy.json';
|
||||
import * as ZRXArtifact from './artifacts/ZRX.json';
|
||||
import {Artifact} from './types';
|
||||
|
||||
export const artifacts = {
|
||||
ZRXArtifact: ZRXArtifact as any as Artifact,
|
||||
DummyTokenArtifact: DummyTokenArtifact as any as Artifact,
|
||||
TokenArtifact: TokenArtifact as any as Artifact,
|
||||
ExchangeArtifact: ExchangeArtifact as any as Artifact,
|
||||
EtherTokenArtifact: EtherTokenArtifact as any as Artifact,
|
||||
|
23
packages/0x.js/src/artifacts/DummyToken.json
Normal file
23
packages/0x.js/src/artifacts/DummyToken.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"contract_name": "DummyToken",
|
||||
"abi":
|
||||
[
|
||||
{
|
||||
"constant": false,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "_target",
|
||||
"type": "address"
|
||||
},
|
||||
{
|
||||
"name": "_value",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"name": "setBalance",
|
||||
"outputs": [],
|
||||
"payable": false,
|
||||
"type": "function"
|
||||
}
|
||||
]
|
||||
}
|
@@ -231,215 +231,54 @@
|
||||
],
|
||||
"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"
|
||||
}
|
||||
],
|
||||
"unlinked_binary": "0x6060604052341561000c57fe5b5b6107598061001c6000396000f300606060405236156100935763ffffffff60e060020a60003504166306fdde0381146100a4578063095ea7b31461013457806318160ddd1461016757806323b872dd146101895780632e1a7d4d146101c2578063313ce567146101d757806370a08231146101fd57806395d89b411461022b578063a9059cbb146102bb578063d0e30db0146102ee578063dd62ed3e146102f8575b6100a25b61009f61032c565b5b565b005b34156100ac57fe5b6100b461037b565b6040805160208082528351818301528351919283929083019185019080838382156100fa575b8051825260208311156100fa57601f1990920191602091820191016100da565b505050905090810190601f1680156101265780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561013c57fe5b610153600160a060020a03600435166024356103a3565b604080519115158252519081900360200190f35b341561016f57fe5b61017761040e565b60408051918252519081900360200190f35b341561019157fe5b610153600160a060020a0360043581169060243516604435610414565b604080519115158252519081900360200190f35b34156101ca57fe5b6100a2600435610537565b005b34156101df57fe5b6101e76105b8565b6040805160ff9092168252519081900360200190f35b341561020557fe5b610177600160a060020a03600435166105bd565b60408051918252519081900360200190f35b341561023357fe5b6100b46105dc565b6040805160208082528351818301528351919283929083019185019080838382156100fa575b8051825260208311156100fa57601f1990920191602091820191016100da565b505050905090810190601f1680156101265780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34156102c357fe5b610153600160a060020a03600435166024356105fd565b604080519115158252519081900360200190f35b6100a261032c565b005b341561030057fe5b610177600160a060020a03600435811690602435166106af565b60408051918252519081900360200190f35b600160a060020a03331660009081526020819052604090205461034f90346106dc565b600160a060020a03331660009081526020819052604090205560025461037590346106dc565b6002555b565b60408051808201909152600b815260a960020a6a22ba3432b9102a37b5b2b702602082015281565b600160a060020a03338116600081815260016020908152604080832094871680845294825280832086905580518681529051929493927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060015b92915050565b60025481565b600160a060020a03808416600081815260016020908152604080832033909516835293815283822054928252819052918220548390108015906104575750828110155b801561047d5750600160a060020a03841660009081526020819052604090205483810110155b1561052957600160a060020a03808516600090815260208190526040808220805487019055918716815220805484900390556000198110156104e757600160a060020a03808616600090815260016020908152604080832033909416835292905220805484900390555b83600160a060020a031685600160a060020a031660008051602061070e833981519152856040518082815260200191505060405180910390a36001915061052e565b600091505b5b509392505050565b600160a060020a03331660009081526020819052604090205461055a90826106f6565b600160a060020a03331660009081526020819052604090205560025461058090826106f6565b600255604051600160a060020a0333169082156108fc029083906000818181858888f1935050505015156105b45760006000fd5b5b50565b601281565b600160a060020a0381166000908152602081905260409020545b919050565b604080518082019091526004815260e360020a630ae8aa8902602082015281565b600160a060020a0333166000908152602081905260408120548290108015906106405750600160a060020a03831660009081526020819052604090205482810110155b156106a057600160a060020a03338116600081815260208181526040808320805488900390559387168083529184902080548701905583518681529351919360008051602061070e833981519152929081900390910190a3506001610408565b506000610408565b5b92915050565b600160a060020a038083166000908152600160209081526040808320938516835292905220545b92915050565b6000828201838110156106eb57fe5b8091505b5092915050565b60008282111561070257fe5b508082035b929150505600ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa165627a7a72305820ec42c469bb8ddd5de28c55b9cc393c812397c063a57fb88926e3f6de246318b70029",
|
||||
"networks": {
|
||||
"1": {
|
||||
"links": {},
|
||||
"events": {
|
||||
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef": {
|
||||
"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"
|
||||
},
|
||||
"0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925": {
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"updated_at": 1502488087000,
|
||||
"address": "0x2956356cd2a2bf3202f771f50d3d14a367b48070"
|
||||
"address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
|
||||
},
|
||||
"3": {
|
||||
"links": {},
|
||||
"events": {
|
||||
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef": {
|
||||
"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"
|
||||
},
|
||||
"0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925": {
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"updated_at": 1506602007000,
|
||||
"address": "0xc00fd9820cd2898cc4c054b7bf142de637ad129a"
|
||||
},
|
||||
"42": {
|
||||
"links": {},
|
||||
"events": {
|
||||
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef": {
|
||||
"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"
|
||||
},
|
||||
"0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925": {
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"updated_at": 1502391794392,
|
||||
"address": "0x05d090b51c40b020eab3bfcb6a2dff130df22e9c"
|
||||
"address": "0x653e49e301e508a13237c0ddc98ae7d4cd2667a1"
|
||||
},
|
||||
"50": {
|
||||
"links": {},
|
||||
"events": {
|
||||
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef": {
|
||||
"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"
|
||||
},
|
||||
"0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925": {
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"updated_at": 1503318938233,
|
||||
"address": "0x48bacb9266a570d521063ef5dd96e61686dbe788"
|
||||
"address": "0x871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c"
|
||||
}
|
||||
},
|
||||
"schema_version": "0.0.5",
|
||||
"updated_at": 1503318938233
|
||||
}
|
||||
}
|
||||
|
File diff suppressed because one or more lines are too long
@@ -168,9 +168,5 @@
|
||||
"name": "Approval",
|
||||
"type": "event"
|
||||
}
|
||||
],
|
||||
"unlinked_binary": "0x6060604052341561000c57fe5b5b6101e08061001c6000396000f3006060604052361561005c5763ffffffff60e060020a600035041663095ea7b3811461005e57806318160ddd1461009157806323b872dd146100b357806370a08231146100ec578063a9059cbb1461005e578063dd62ed3e1461014d575bfe5b341561006657fe5b61007d600160a060020a0360043516602435610181565b604080519115158252519081900360200190f35b341561009957fe5b6100a161018a565b60408051918252519081900360200190f35b34156100bb57fe5b61007d600160a060020a0360043581169060243516604435610190565b604080519115158252519081900360200190f35b34156100f457fe5b6100a1600160a060020a036004351661019a565b60408051918252519081900360200190f35b341561006657fe5b61007d600160a060020a0360043516602435610181565b604080519115158252519081900360200190f35b341561015557fe5b6100a1600160a060020a0360043581169060243516610181565b60408051918252519081900360200190f35b60005b92915050565b60005b90565b60005b9392505050565b60005b919050565b60005b92915050565b60005b929150505600a165627a7a723058202e3f7ac17048343c0d0ea24fccb64620577374eeeed61539e543df4025d7d0db0029",
|
||||
"networks": {},
|
||||
"schema_version": "0.0.5",
|
||||
"updated_at": 1503317882695
|
||||
}
|
||||
]
|
||||
}
|
||||
|
File diff suppressed because one or more lines are too long
@@ -167,8 +167,18 @@
|
||||
"type": "event"
|
||||
}
|
||||
],
|
||||
"unlinked_binary": "0x60606040525b60008054600160a060020a03191633600160a060020a03161790555b5b6106e6806100316000396000f300606060405236156100725763ffffffff60e060020a60003504166315dacbea811461007457806342f1181e146100b3578063494503d4146100d157806370712939146101005780638da5cb5b1461011e578063b91816111461014a578063d39de6e91461017a578063f2fde38b146101e5575bfe5b341561007c57fe5b61009f600160a060020a0360043581169060243581169060443516606435610203565b604080519115158252519081900360200190f35b34156100bb57fe5b6100cf600160a060020a03600435166102ae565b005b34156100d957fe5b6100e4600435610390565b60408051600160a060020a039092168252519081900360200190f35b341561010857fe5b6100cf600160a060020a03600435166103c2565b005b341561012657fe5b6100e461055a565b60408051600160a060020a039092168252519081900360200190f35b341561015257fe5b61009f600160a060020a0360043516610569565b604080519115158252519081900360200190f35b341561018257fe5b61018a61057e565b60408051602080825283518183015283519192839290830191858101910280838382156101d2575b8051825260208311156101d257601f1990920191602091820191016101b2565b5050509050019250505060405180910390f35b34156101ed57fe5b6100cf600160a060020a03600435166105e7565b005b600160a060020a03331660009081526001602052604081205460ff16151561022b5760006000fd5b6040805160006020918201819052825160e060020a6323b872dd028152600160a060020a0388811660048301528781166024830152604482018790529351938916936323b872dd9360648084019491938390030190829087803b151561028d57fe5b6102c65a03f1151561029b57fe5b5050604051519150505b5b949350505050565b60005433600160a060020a039081169116146102ca5760006000fd5b600160a060020a038116600090815260016020526040902054819060ff16156102f35760006000fd5b600160a060020a0382166000908152600160208190526040909120805460ff191682179055600280549091810161032a8382610633565b916000526020600020900160005b81546101009190910a600160a060020a0381810219909216868316918202179092556040513390911692507f94bb87f4c15c4587ff559a7584006fa01ddf9299359be6b512b94527aa961aca90600090a35b5b505b50565b600280548290811061039e57fe5b906000526020600020900160005b915054906101000a9004600160a060020a031681565b6000805433600160a060020a039081169116146103df5760006000fd5b600160a060020a038216600090815260016020526040902054829060ff1615156104095760006000fd5b600160a060020a0383166000908152600160205260408120805460ff1916905591505b6002548210156105195782600160a060020a031660028381548110151561044f57fe5b906000526020600020900160005b9054906101000a9004600160a060020a0316600160a060020a0316141561050d5760028054600019810190811061049057fe5b906000526020600020900160005b9054906101000a9004600160a060020a03166002838154811015156104bf57fe5b906000526020600020900160005b6101000a815481600160a060020a030219169083600160a060020a0316021790555060016002818180549050039150816105079190610633565b50610519565b5b60019091019061042c565b604051600160a060020a0333811691908516907ff5b347a1e40749dd050f5f07fbdbeb7e3efa9756903044dd29401fd1d4bb4a1c90600090a35b5b505b5050565b600054600160a060020a031681565b60016020526000908152604090205460ff1681565b610586610687565b60028054806020026020016040519081016040528092919081815260200182805480156105dc57602002820191906000526020600020905b8154600160a060020a031681526001909101906020018083116105be575b505050505090505b90565b60005433600160a060020a039081169116146106035760006000fd5b600160a060020a0381161561038d5760008054600160a060020a031916600160a060020a0383161790555b5b5b50565b81548183558181151161055357600083815260209020610553918101908301610699565b5b505050565b81548183558181151161055357600083815260209020610553918101908301610699565b5b505050565b60408051602081019091526000815290565b6105e491905b808211156106b3576000815560010161069f565b5090565b905600a165627a7a72305820d2924957bb88a128789172e164d874fe5445218fc2dde2f5eb265839a1f341a20029",
|
||||
"networks": {},
|
||||
"schema_version": "0.0.5",
|
||||
"updated_at": 1503318938227
|
||||
"networks": {
|
||||
"1": {
|
||||
"address": "0x8da0d80f5007ef1e431dd2127178d224e32c2ef4"
|
||||
},
|
||||
"3": {
|
||||
"address": "0x4e9aad8184de8833365fea970cd9149372fdf1e6"
|
||||
},
|
||||
"42": {
|
||||
"address": "0x087eed4bc1ee3de49befbd66c662b434b15d49d4"
|
||||
},
|
||||
"50": {
|
||||
"address": "0x1dc4c1cefef38a777b15aa20260a54e584b16c48"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
17
packages/0x.js/src/artifacts/ZRX.json
Normal file
17
packages/0x.js/src/artifacts/ZRX.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"contract_name": "ZRX",
|
||||
"networks": {
|
||||
"1": {
|
||||
"address": "0xe41d2489571d322189246dafa5ebde1f4699f498"
|
||||
},
|
||||
"3": {
|
||||
"address": "0xa8e9fa8f91e5ae138c74648c9c304f1c75003a8d"
|
||||
},
|
||||
"42": {
|
||||
"address": "0x6ff6c0ff1d68b964901f986d4c9fa3ac68346570"
|
||||
},
|
||||
"50": {
|
||||
"address": "0x1d7022f5b17d2f8b695918fb48fa1089c9f85401"
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,47 +1,56 @@
|
||||
import {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 {BlockAndLogStreamer, Block} from 'ethereumjs-blockstream';
|
||||
import {Web3Wrapper} from '../web3_wrapper';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
|
||||
import {
|
||||
ZeroExError,
|
||||
InternalZeroExError,
|
||||
Artifact,
|
||||
BlockParamLiteral,
|
||||
BlockRange,
|
||||
ContractEventArgs,
|
||||
ContractEvents,
|
||||
EventCallback,
|
||||
IndexedFilterValues,
|
||||
InternalZeroExError,
|
||||
LogWithDecodedArgs,
|
||||
RawLog,
|
||||
ContractEvents,
|
||||
SubscriptionOpts,
|
||||
IndexedFilterValues,
|
||||
EventCallback,
|
||||
BlockParamLiteral,
|
||||
ContractEventArgs,
|
||||
ZeroExError,
|
||||
} from '../types';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
import {constants} from '../utils/constants';
|
||||
import {intervalUtils} from '../utils/interval_utils';
|
||||
import {filterUtils} from '../utils/filter_utils';
|
||||
|
||||
const CONTRACT_NAME_TO_NOT_FOUND_ERROR: {[contractName: string]: ZeroExError} = {
|
||||
ZRX: ZeroExError.ZRXContractDoesNotExist,
|
||||
EtherToken: ZeroExError.EtherTokenContractDoesNotExist,
|
||||
Token: ZeroExError.TokenContractDoesNotExist,
|
||||
TokenRegistry: ZeroExError.TokenRegistryContractDoesNotExist,
|
||||
TokenTransferProxy: ZeroExError.TokenTransferProxyContractDoesNotExist,
|
||||
Exchange: ZeroExError.ExchangeContractDoesNotExist,
|
||||
};
|
||||
|
||||
export class ContractWrapper {
|
||||
protected _web3Wrapper: Web3Wrapper;
|
||||
private _networkId: number;
|
||||
private _abiDecoder?: AbiDecoder;
|
||||
private _blockAndLogStreamer: BlockAndLogStreamer|undefined;
|
||||
private _blockAndLogStreamerIfExists: BlockAndLogStreamer|undefined;
|
||||
private _blockAndLogStreamInterval: NodeJS.Timer;
|
||||
private _filters: {[filterToken: string]: Web3.FilterObject};
|
||||
private _filterCallbacks: {[filterToken: string]: EventCallback<ContractEventArgs>};
|
||||
private _onLogAddedSubscriptionToken: string|undefined;
|
||||
private _onLogRemovedSubscriptionToken: string|undefined;
|
||||
constructor(web3Wrapper: Web3Wrapper, abiDecoder?: AbiDecoder) {
|
||||
constructor(web3Wrapper: Web3Wrapper, networkId: number, abiDecoder?: AbiDecoder) {
|
||||
this._web3Wrapper = web3Wrapper;
|
||||
this._networkId = networkId;
|
||||
this._abiDecoder = abiDecoder;
|
||||
this._filters = {};
|
||||
this._filterCallbacks = {};
|
||||
this._blockAndLogStreamer = undefined;
|
||||
this._blockAndLogStreamerIfExists = undefined;
|
||||
this._onLogAddedSubscriptionToken = undefined;
|
||||
this._onLogRemovedSubscriptionToken = undefined;
|
||||
}
|
||||
/**
|
||||
* Cancels all existing subscriptions
|
||||
*/
|
||||
public unsubscribeAll(): void {
|
||||
protected unsubscribeAll(): void {
|
||||
const filterTokens = _.keys(this._filterCallbacks);
|
||||
_.each(filterTokens, filterToken => {
|
||||
this._unsubscribe(filterToken);
|
||||
@@ -65,7 +74,7 @@ export class ContractWrapper {
|
||||
address: string, eventName: ContractEvents, indexFilterValues: IndexedFilterValues, abi: Web3.ContractAbi,
|
||||
callback: EventCallback<ArgsType>): string {
|
||||
const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi);
|
||||
if (_.isUndefined(this._blockAndLogStreamer)) {
|
||||
if (_.isUndefined(this._blockAndLogStreamerIfExists)) {
|
||||
this._startBlockAndLogStream();
|
||||
}
|
||||
const filterToken = filterUtils.generateUUID();
|
||||
@@ -74,9 +83,9 @@ export class ContractWrapper {
|
||||
return filterToken;
|
||||
}
|
||||
protected async _getLogsAsync<ArgsType extends ContractEventArgs>(
|
||||
address: string, eventName: ContractEvents, subscriptionOpts: SubscriptionOpts,
|
||||
address: string, eventName: ContractEvents, blockRange: BlockRange,
|
||||
indexFilterValues: IndexedFilterValues, abi: Web3.ContractAbi): Promise<Array<LogWithDecodedArgs<ArgsType>>> {
|
||||
const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi, subscriptionOpts);
|
||||
const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi, blockRange);
|
||||
const logs = await this._web3Wrapper.getLogsAsync(filter);
|
||||
const logsWithDecodedArguments = _.map(logs, this._tryToDecodeLogOrNoop.bind(this));
|
||||
return logsWithDecodedArguments;
|
||||
@@ -89,58 +98,88 @@ export class ContractWrapper {
|
||||
const logWithDecodedArgs = this._abiDecoder.tryToDecodeLogOrNoop(log);
|
||||
return logWithDecodedArgs;
|
||||
}
|
||||
protected async _instantiateContractIfExistsAsync<ContractType extends Web3.ContractInstance>(
|
||||
artifact: Artifact, addressIfExists?: string): Promise<ContractType> {
|
||||
const contractInstance =
|
||||
await this._web3Wrapper.getContractInstanceFromArtifactAsync<ContractType>(artifact, addressIfExists);
|
||||
protected async _instantiateContractIfExistsAsync(
|
||||
artifact: Artifact, addressIfExists?: string,
|
||||
): Promise<Web3.ContractInstance> {
|
||||
let contractAddress: string;
|
||||
if (_.isUndefined(addressIfExists)) {
|
||||
if (_.isUndefined(artifact.networks[this._networkId])) {
|
||||
throw new Error(ZeroExError.ContractNotDeployedOnNetwork);
|
||||
}
|
||||
contractAddress = artifact.networks[this._networkId].address.toLowerCase();
|
||||
} else {
|
||||
contractAddress = addressIfExists;
|
||||
}
|
||||
const doesContractExist = await this._web3Wrapper.doesContractExistAtAddressAsync(contractAddress);
|
||||
if (!doesContractExist) {
|
||||
throw new Error(CONTRACT_NAME_TO_NOT_FOUND_ERROR[artifact.contract_name]);
|
||||
}
|
||||
const contractInstance = this._web3Wrapper.getContractInstance(
|
||||
artifact.abi, contractAddress,
|
||||
);
|
||||
return contractInstance;
|
||||
}
|
||||
private _onLogStateChanged<ArgsType extends ContractEventArgs>(removed: boolean, log: Web3.LogEntry): void {
|
||||
protected _getContractAddress(artifact: Artifact, addressIfExists?: string): string {
|
||||
if (_.isUndefined(addressIfExists)) {
|
||||
const contractAddress = artifact.networks[this._networkId].address;
|
||||
if (_.isUndefined(contractAddress)) {
|
||||
throw new Error(ZeroExError.ExchangeContractDoesNotExist);
|
||||
}
|
||||
return contractAddress;
|
||||
} else {
|
||||
return addressIfExists;
|
||||
}
|
||||
}
|
||||
private _onLogStateChanged<ArgsType extends ContractEventArgs>(isRemoved: boolean, log: Web3.LogEntry): void {
|
||||
_.forEach(this._filters, (filter: Web3.FilterObject, filterToken: string) => {
|
||||
if (filterUtils.matchesFilter(log, filter)) {
|
||||
const decodedLog = this._tryToDecodeLogOrNoop(log) as LogWithDecodedArgs<ArgsType>;
|
||||
const logEvent = {
|
||||
...decodedLog,
|
||||
removed,
|
||||
log: decodedLog,
|
||||
isRemoved,
|
||||
};
|
||||
this._filterCallbacks[filterToken](null, logEvent);
|
||||
}
|
||||
});
|
||||
}
|
||||
private _startBlockAndLogStream(): void {
|
||||
this._blockAndLogStreamer = new BlockAndLogStreamer(
|
||||
if (!_.isUndefined(this._blockAndLogStreamerIfExists)) {
|
||||
throw new Error(ZeroExError.SubscriptionAlreadyPresent);
|
||||
}
|
||||
this._blockAndLogStreamerIfExists = new BlockAndLogStreamer(
|
||||
this._web3Wrapper.getBlockAsync.bind(this._web3Wrapper),
|
||||
this._web3Wrapper.getLogsAsync.bind(this._web3Wrapper),
|
||||
);
|
||||
const catchAllLogFilter = {};
|
||||
this._blockAndLogStreamer.addLogFilter(catchAllLogFilter);
|
||||
this._blockAndLogStreamerIfExists.addLogFilter(catchAllLogFilter);
|
||||
this._blockAndLogStreamInterval = intervalUtils.setAsyncExcludingInterval(
|
||||
this._reconcileBlockAsync.bind(this), constants.DEFAULT_BLOCK_POLLING_INTERVAL,
|
||||
);
|
||||
let removed = false;
|
||||
this._onLogAddedSubscriptionToken = this._blockAndLogStreamer.subscribeToOnLogAdded(
|
||||
this._onLogStateChanged.bind(this, removed),
|
||||
let isRemoved = false;
|
||||
this._onLogAddedSubscriptionToken = this._blockAndLogStreamerIfExists.subscribeToOnLogAdded(
|
||||
this._onLogStateChanged.bind(this, isRemoved),
|
||||
);
|
||||
removed = true;
|
||||
this._onLogRemovedSubscriptionToken = this._blockAndLogStreamer.subscribeToOnLogRemoved(
|
||||
this._onLogStateChanged.bind(this, removed),
|
||||
isRemoved = true;
|
||||
this._onLogRemovedSubscriptionToken = this._blockAndLogStreamerIfExists.subscribeToOnLogRemoved(
|
||||
this._onLogStateChanged.bind(this, isRemoved),
|
||||
);
|
||||
}
|
||||
private _stopBlockAndLogStream(): void {
|
||||
(this._blockAndLogStreamer as BlockAndLogStreamer).unsubscribeFromOnLogAdded(
|
||||
this._onLogAddedSubscriptionToken as string);
|
||||
(this._blockAndLogStreamer as BlockAndLogStreamer).unsubscribeFromOnLogRemoved(
|
||||
this._onLogRemovedSubscriptionToken as string);
|
||||
if (_.isUndefined(this._blockAndLogStreamerIfExists)) {
|
||||
throw new Error(ZeroExError.SubscriptionNotFound);
|
||||
}
|
||||
this._blockAndLogStreamerIfExists.unsubscribeFromOnLogAdded(this._onLogAddedSubscriptionToken as string);
|
||||
this._blockAndLogStreamerIfExists.unsubscribeFromOnLogRemoved(this._onLogRemovedSubscriptionToken as string);
|
||||
intervalUtils.clearAsyncExcludingInterval(this._blockAndLogStreamInterval);
|
||||
delete this._blockAndLogStreamer;
|
||||
delete this._blockAndLogStreamerIfExists;
|
||||
}
|
||||
private async _reconcileBlockAsync(): Promise<void> {
|
||||
try {
|
||||
const latestBlock = await this._web3Wrapper.getBlockAsync(BlockParamLiteral.Latest);
|
||||
// We need to coerce to Block type cause Web3.Block includes types for mempool blocks
|
||||
if (!_.isUndefined(this._blockAndLogStreamer)) {
|
||||
if (!_.isUndefined(this._blockAndLogStreamerIfExists)) {
|
||||
// If we clear the interval while fetching the block - this._blockAndLogStreamer will be undefined
|
||||
this._blockAndLogStreamer.reconcileNewBlock(latestBlock as any as Block);
|
||||
await this._blockAndLogStreamerIfExists.reconcileNewBlock(latestBlock as any as Block);
|
||||
}
|
||||
} catch (err) {
|
||||
const filterTokens = _.keys(this._filterCallbacks);
|
||||
|
@@ -1,87 +1,161 @@
|
||||
import * as _ from 'lodash';
|
||||
import {schemas} from '@0xproject/json-schemas';
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import {Web3Wrapper} from '../web3_wrapper';
|
||||
import {ContractWrapper} from './contract_wrapper';
|
||||
import {TokenWrapper} from './token_wrapper';
|
||||
import {EtherTokenContract, ZeroExError} from '../types';
|
||||
import {assert} from '../utils/assert';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {artifacts} from '../artifacts';
|
||||
import {
|
||||
BlockRange,
|
||||
EtherTokenContractEventArgs,
|
||||
EtherTokenEvents,
|
||||
EventCallback,
|
||||
IndexedFilterValues,
|
||||
LogWithDecodedArgs,
|
||||
TransactionOpts,
|
||||
ZeroExError,
|
||||
} from '../types';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
import {assert} from '../utils/assert';
|
||||
|
||||
import {ContractWrapper} from './contract_wrapper';
|
||||
import {EtherTokenContract} from './generated/ether_token';
|
||||
import {TokenWrapper} from './token_wrapper';
|
||||
|
||||
/**
|
||||
* This class includes all the functionality related to interacting with a wrapped Ether ERC20 token contract.
|
||||
* The caller can convert ETH into the equivalent number of wrapped ETH ERC20 tokens and back.
|
||||
*/
|
||||
export class EtherTokenWrapper extends ContractWrapper {
|
||||
private _etherTokenContractIfExists?: EtherTokenContract;
|
||||
private _etherTokenContractsByAddress: {[address: string]: EtherTokenContract} = {};
|
||||
private _tokenWrapper: TokenWrapper;
|
||||
private _contractAddressIfExists?: string;
|
||||
constructor(web3Wrapper: Web3Wrapper, tokenWrapper: TokenWrapper, contractAddressIfExists?: string) {
|
||||
super(web3Wrapper);
|
||||
constructor(web3Wrapper: Web3Wrapper, networkId: number, abiDecoder: AbiDecoder, tokenWrapper: TokenWrapper) {
|
||||
super(web3Wrapper, networkId, abiDecoder);
|
||||
this._tokenWrapper = tokenWrapper;
|
||||
this._contractAddressIfExists = contractAddressIfExists;
|
||||
}
|
||||
/**
|
||||
* Deposit ETH into the Wrapped ETH smart contract and issues the equivalent number of wrapped ETH tokens
|
||||
* to the depositor address. These wrapped ETH tokens can be used in 0x trades and are redeemable for 1-to-1
|
||||
* for ETH.
|
||||
* @param amountInWei Amount of ETH in Wei the caller wishes to deposit.
|
||||
* @param depositor The hex encoded user Ethereum address that would like to make the deposit.
|
||||
* @param etherTokenAddress EtherToken address you wish to deposit into.
|
||||
* @param amountInWei Amount of ETH in Wei the caller wishes to deposit.
|
||||
* @param depositor The hex encoded user Ethereum address that would like to make the deposit.
|
||||
* @param txOpts Transaction parameters.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
public async depositAsync(amountInWei: BigNumber, depositor: string): Promise<string> {
|
||||
public async depositAsync(
|
||||
etherTokenAddress: string, amountInWei: BigNumber, depositor: string, txOpts: TransactionOpts = {},
|
||||
): Promise<string> {
|
||||
assert.isValidBaseUnitAmount('amountInWei', amountInWei);
|
||||
await assert.isSenderAddressAsync('depositor', depositor, this._web3Wrapper);
|
||||
|
||||
const ethBalanceInWei = await this._web3Wrapper.getBalanceInWeiAsync(depositor);
|
||||
assert.assert(ethBalanceInWei.gte(amountInWei), ZeroExError.InsufficientEthBalanceForDeposit);
|
||||
|
||||
const wethContract = await this._getEtherTokenContractAsync();
|
||||
const wethContract = await this._getEtherTokenContractAsync(etherTokenAddress);
|
||||
const txHash = await wethContract.deposit.sendTransactionAsync({
|
||||
from: depositor,
|
||||
value: amountInWei,
|
||||
gas: txOpts.gasLimit,
|
||||
gasPrice: txOpts.gasPrice,
|
||||
});
|
||||
return txHash;
|
||||
}
|
||||
/**
|
||||
* Withdraw ETH to the withdrawer's address from the wrapped ETH smart contract in exchange for the
|
||||
* equivalent number of wrapped ETH tokens.
|
||||
* @param etherTokenAddress EtherToken address you wish to withdraw from.
|
||||
* @param amountInWei Amount of ETH in Wei the caller wishes to withdraw.
|
||||
* @param withdrawer The hex encoded user Ethereum address that would like to make the withdrawl.
|
||||
* @param txOpts Transaction parameters.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
public async withdrawAsync(amountInWei: BigNumber, withdrawer: string): Promise<string> {
|
||||
public async withdrawAsync(
|
||||
etherTokenAddress: string, amountInWei: BigNumber, withdrawer: string, txOpts: TransactionOpts = {},
|
||||
): Promise<string> {
|
||||
assert.isValidBaseUnitAmount('amountInWei', amountInWei);
|
||||
await assert.isSenderAddressAsync('withdrawer', withdrawer, this._web3Wrapper);
|
||||
|
||||
const wethContractAddress = await this.getContractAddressAsync();
|
||||
const WETHBalanceInBaseUnits = await this._tokenWrapper.getBalanceAsync(wethContractAddress, withdrawer);
|
||||
const WETHBalanceInBaseUnits = await this._tokenWrapper.getBalanceAsync(etherTokenAddress, withdrawer);
|
||||
assert.assert(WETHBalanceInBaseUnits.gte(amountInWei), ZeroExError.InsufficientWEthBalanceForWithdrawal);
|
||||
|
||||
const wethContract = await this._getEtherTokenContractAsync();
|
||||
const wethContract = await this._getEtherTokenContractAsync(etherTokenAddress);
|
||||
const txHash = await wethContract.withdraw.sendTransactionAsync(amountInWei, {
|
||||
from: withdrawer,
|
||||
gas: txOpts.gasLimit,
|
||||
gasPrice: txOpts.gasPrice,
|
||||
});
|
||||
return txHash;
|
||||
}
|
||||
/**
|
||||
* Retrieves the Wrapped Ether token contract address
|
||||
* @return The Wrapped Ether token contract address
|
||||
* Gets historical logs without creating a subscription
|
||||
* @param etherTokenAddress An address of the ether token that emmited the logs.
|
||||
* @param eventName The ether token contract event you would like to subscribe to.
|
||||
* @param blockRange Block range to get logs from.
|
||||
* @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}`
|
||||
* @return Array of logs that match the parameters
|
||||
*/
|
||||
public async getContractAddressAsync(): Promise<string> {
|
||||
const wethContract = await this._getEtherTokenContractAsync();
|
||||
return wethContract.address;
|
||||
public async getLogsAsync<ArgsType extends EtherTokenContractEventArgs>(
|
||||
etherTokenAddress: string, eventName: EtherTokenEvents, blockRange: BlockRange,
|
||||
indexFilterValues: IndexedFilterValues): Promise<Array<LogWithDecodedArgs<ArgsType>>> {
|
||||
assert.isETHAddressHex('etherTokenAddress', etherTokenAddress);
|
||||
assert.doesBelongToStringEnum('eventName', eventName, EtherTokenEvents);
|
||||
assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema);
|
||||
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
|
||||
const logs = await this._getLogsAsync<ArgsType>(
|
||||
etherTokenAddress, eventName, blockRange, indexFilterValues, artifacts.EtherTokenArtifact.abi,
|
||||
);
|
||||
return logs;
|
||||
}
|
||||
/**
|
||||
* Subscribe to an event type emitted by the Token contract.
|
||||
* @param etherTokenAddress The hex encoded address where the ether token is deployed.
|
||||
* @param eventName The ether token contract event you would like to subscribe to.
|
||||
* @param indexFilterValues An object where the keys are indexed args returned by the event and
|
||||
* the value is the value you are interested in. E.g `{_owner: aUserAddressHex}`
|
||||
* @param callback Callback that gets called when a log is added/removed
|
||||
* @return Subscription token used later to unsubscribe
|
||||
*/
|
||||
public subscribe<ArgsType extends EtherTokenContractEventArgs>(
|
||||
etherTokenAddress: string, eventName: EtherTokenEvents, indexFilterValues: IndexedFilterValues,
|
||||
callback: EventCallback<ArgsType>): string {
|
||||
assert.isETHAddressHex('etherTokenAddress', etherTokenAddress);
|
||||
assert.doesBelongToStringEnum('eventName', eventName, EtherTokenEvents);
|
||||
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
|
||||
assert.isFunction('callback', callback);
|
||||
const subscriptionToken = this._subscribe<ArgsType>(
|
||||
etherTokenAddress, eventName, indexFilterValues, artifacts.EtherTokenArtifact.abi, callback,
|
||||
);
|
||||
return subscriptionToken;
|
||||
}
|
||||
/**
|
||||
* Cancel a subscription
|
||||
* @param subscriptionToken Subscription token returned by `subscribe()`
|
||||
*/
|
||||
public unsubscribe(subscriptionToken: string): void {
|
||||
this._unsubscribe(subscriptionToken);
|
||||
}
|
||||
/**
|
||||
* Cancels all existing subscriptions
|
||||
*/
|
||||
public unsubscribeAll(): void {
|
||||
super.unsubscribeAll();
|
||||
}
|
||||
private _invalidateContractInstance(): void {
|
||||
delete this._etherTokenContractIfExists;
|
||||
this.unsubscribeAll();
|
||||
this._etherTokenContractsByAddress = {};
|
||||
}
|
||||
private async _getEtherTokenContractAsync(): Promise<EtherTokenContract> {
|
||||
if (!_.isUndefined(this._etherTokenContractIfExists)) {
|
||||
return this._etherTokenContractIfExists;
|
||||
private async _getEtherTokenContractAsync(etherTokenAddress: string): Promise<EtherTokenContract> {
|
||||
let etherTokenContract = this._etherTokenContractsByAddress[etherTokenAddress];
|
||||
if (!_.isUndefined(etherTokenContract)) {
|
||||
return etherTokenContract;
|
||||
}
|
||||
const contractInstance = await this._instantiateContractIfExistsAsync<EtherTokenContract>(
|
||||
artifacts.EtherTokenArtifact, this._contractAddressIfExists,
|
||||
const web3ContractInstance = await this._instantiateContractIfExistsAsync(
|
||||
artifacts.EtherTokenArtifact, etherTokenAddress,
|
||||
);
|
||||
this._etherTokenContractIfExists = contractInstance as EtherTokenContract;
|
||||
return this._etherTokenContractIfExists;
|
||||
const contractInstance = new EtherTokenContract(web3ContractInstance, this._web3Wrapper.getContractDefaults());
|
||||
etherTokenContract = contractInstance;
|
||||
this._etherTokenContractsByAddress[etherTokenAddress] = etherTokenContract;
|
||||
return etherTokenContract;
|
||||
}
|
||||
}
|
||||
|
@@ -1,44 +1,43 @@
|
||||
import {schemas} from '@0xproject/json-schemas';
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as _ from 'lodash';
|
||||
import * as Web3 from 'web3';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import {schemas} from '@0xproject/json-schemas';
|
||||
import {Web3Wrapper} from '../web3_wrapper';
|
||||
|
||||
import {artifacts} from '../artifacts';
|
||||
import {
|
||||
BlockParamLiteral,
|
||||
BlockRange,
|
||||
DecodedLogArgs,
|
||||
ECSignature,
|
||||
ExchangeContract,
|
||||
EventCallback,
|
||||
ExchangeContractErrCodes,
|
||||
ExchangeContractErrs,
|
||||
ZeroExError,
|
||||
OrderValues,
|
||||
OrderAddresses,
|
||||
Order,
|
||||
SignedOrder,
|
||||
ExchangeContractEventArgs,
|
||||
ExchangeEvents,
|
||||
SubscriptionOpts,
|
||||
IndexedFilterValues,
|
||||
OrderCancellationRequest,
|
||||
OrderFillRequest,
|
||||
LogErrorContractEventArgs,
|
||||
LogFillContractEventArgs,
|
||||
LogCancelContractEventArgs,
|
||||
LogWithDecodedArgs,
|
||||
MethodOpts,
|
||||
ValidateOrderFillableOpts,
|
||||
Order,
|
||||
OrderAddresses,
|
||||
OrderCancellationRequest,
|
||||
OrderFillRequest,
|
||||
OrderTransactionOpts,
|
||||
RawLog,
|
||||
EventCallback,
|
||||
ExchangeContractEventArgs,
|
||||
DecodedLogArgs,
|
||||
OrderValues,
|
||||
SignedOrder,
|
||||
ValidateOrderFillableOpts,
|
||||
} from '../types';
|
||||
import {assert} from '../utils/assert';
|
||||
import {utils} from '../utils/utils';
|
||||
import {OrderValidationUtils} from '../utils/order_validation_utils';
|
||||
import {ContractWrapper} from './contract_wrapper';
|
||||
import {TokenWrapper} from './token_wrapper';
|
||||
import {decorators} from '../utils/decorators';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
import {assert} from '../utils/assert';
|
||||
import {decorators} from '../utils/decorators';
|
||||
import {ExchangeTransferSimulator} from '../utils/exchange_transfer_simulator';
|
||||
import {artifacts} from '../artifacts';
|
||||
import {OrderValidationUtils} from '../utils/order_validation_utils';
|
||||
import {utils} from '../utils/utils';
|
||||
|
||||
import {ContractWrapper} from './contract_wrapper';
|
||||
import {ExchangeContract} from './generated/exchange';
|
||||
import {TokenWrapper} from './token_wrapper';
|
||||
|
||||
const SHOULD_VALIDATE_BY_DEFAULT = true;
|
||||
|
||||
@@ -63,6 +62,7 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
[ExchangeContractErrCodes.ERROR_FILL_BALANCE_ALLOWANCE]: ExchangeContractErrs.FillBalanceAllowanceError,
|
||||
};
|
||||
private _contractAddressIfExists?: string;
|
||||
private _zrxContractAddressIfExists?: string;
|
||||
private static _getOrderAddressesAndValues(order: Order): [OrderAddresses, OrderValues] {
|
||||
const orderAddresses: OrderAddresses = [
|
||||
order.maker,
|
||||
@@ -81,11 +81,11 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
];
|
||||
return [orderAddresses, orderValues];
|
||||
}
|
||||
constructor(web3Wrapper: Web3Wrapper, abiDecoder: AbiDecoder,
|
||||
constructor(web3Wrapper: Web3Wrapper, networkId: number, abiDecoder: AbiDecoder,
|
||||
tokenWrapper: TokenWrapper, contractAddressIfExists?: string) {
|
||||
super(web3Wrapper, abiDecoder);
|
||||
super(web3Wrapper, networkId, abiDecoder);
|
||||
this._tokenWrapper = tokenWrapper;
|
||||
this._orderValidationUtils = new OrderValidationUtils(tokenWrapper, this);
|
||||
this._orderValidationUtils = new OrderValidationUtils(this);
|
||||
this._contractAddressIfExists = contractAddressIfExists;
|
||||
}
|
||||
/**
|
||||
@@ -162,41 +162,29 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param orderTransactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async fillOrderAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber,
|
||||
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
|
||||
takerAddress: string,
|
||||
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
|
||||
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
|
||||
assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
|
||||
assert.isValidBaseUnitAmount('fillTakerTokenAmount', fillTakerTokenAmount);
|
||||
assert.isBoolean('shouldThrowOnInsufficientBalanceOrAllowance', shouldThrowOnInsufficientBalanceOrAllowance);
|
||||
await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper);
|
||||
|
||||
const exchangeInstance = await this._getExchangeContractAsync();
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
if (shouldValidate) {
|
||||
const zrxTokenAddress = await this.getZRXTokenAddressAsync();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper);
|
||||
const zrxTokenAddress = this.getZRXTokenAddress();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
|
||||
await this._orderValidationUtils.validateFillOrderThrowIfInvalidAsync(
|
||||
exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress);
|
||||
}
|
||||
|
||||
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(signedOrder);
|
||||
|
||||
const gas = await exchangeInstance.fillOrder.estimateGasAsync(
|
||||
orderAddresses,
|
||||
orderValues,
|
||||
fillTakerTokenAmount,
|
||||
shouldThrowOnInsufficientBalanceOrAllowance,
|
||||
signedOrder.ecSignature.v,
|
||||
signedOrder.ecSignature.r,
|
||||
signedOrder.ecSignature.s,
|
||||
{
|
||||
from: takerAddress,
|
||||
},
|
||||
);
|
||||
const txHash: string = await exchangeInstance.fillOrder.sendTransactionAsync(
|
||||
orderAddresses,
|
||||
orderValues,
|
||||
@@ -207,7 +195,8 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
signedOrder.ecSignature.s,
|
||||
{
|
||||
from: takerAddress,
|
||||
gas,
|
||||
gas: orderTransactionOpts.gasLimit,
|
||||
gasPrice: orderTransactionOpts.gasPrice,
|
||||
},
|
||||
);
|
||||
return txHash;
|
||||
@@ -229,11 +218,11 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param orderTransactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async fillOrdersUpToAsync(signedOrders: SignedOrder[], fillTakerTokenAmount: BigNumber,
|
||||
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
|
||||
takerAddress: string,
|
||||
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
|
||||
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
|
||||
assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema);
|
||||
const takerTokenAddresses = _.map(signedOrders, signedOrder => signedOrder.takerTokenAddress);
|
||||
assert.hasAtMostOneUniqueValue(takerTokenAddresses,
|
||||
@@ -245,12 +234,12 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
assert.isBoolean('shouldThrowOnInsufficientBalanceOrAllowance', shouldThrowOnInsufficientBalanceOrAllowance);
|
||||
await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper);
|
||||
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
if (shouldValidate) {
|
||||
const zrxTokenAddress = await this.getZRXTokenAddressAsync();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper);
|
||||
const zrxTokenAddress = this.getZRXTokenAddress();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
|
||||
for (const signedOrder of signedOrders) {
|
||||
await this._orderValidationUtils.validateFillOrderThrowIfInvalidAsync(
|
||||
exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress);
|
||||
@@ -275,18 +264,6 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
);
|
||||
|
||||
const exchangeInstance = await this._getExchangeContractAsync();
|
||||
const gas = await exchangeInstance.fillOrdersUpTo.estimateGasAsync(
|
||||
orderAddressesArray,
|
||||
orderValuesArray,
|
||||
fillTakerTokenAmount,
|
||||
shouldThrowOnInsufficientBalanceOrAllowance,
|
||||
vArray,
|
||||
rArray,
|
||||
sArray,
|
||||
{
|
||||
from: takerAddress,
|
||||
},
|
||||
);
|
||||
const txHash = await exchangeInstance.fillOrdersUpTo.sendTransactionAsync(
|
||||
orderAddressesArray,
|
||||
orderValuesArray,
|
||||
@@ -297,7 +274,8 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
sArray,
|
||||
{
|
||||
from: takerAddress,
|
||||
gas,
|
||||
gas: orderTransactionOpts.gasLimit,
|
||||
gasPrice: orderTransactionOpts.gasPrice,
|
||||
},
|
||||
);
|
||||
return txHash;
|
||||
@@ -321,11 +299,11 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param orderTransactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async batchFillOrdersAsync(orderFillRequests: OrderFillRequest[],
|
||||
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
|
||||
takerAddress: string,
|
||||
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
|
||||
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
|
||||
assert.doesConformToSchema('orderFillRequests', orderFillRequests, schemas.orderFillRequestsSchema);
|
||||
const exchangeContractAddresses = _.map(
|
||||
orderFillRequests,
|
||||
@@ -335,12 +313,12 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
ExchangeContractErrs.BatchOrdersMustHaveSameExchangeAddress);
|
||||
assert.isBoolean('shouldThrowOnInsufficientBalanceOrAllowance', shouldThrowOnInsufficientBalanceOrAllowance);
|
||||
await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper);
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
if (shouldValidate) {
|
||||
const zrxTokenAddress = await this.getZRXTokenAddressAsync();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper);
|
||||
const zrxTokenAddress = this.getZRXTokenAddress();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
|
||||
for (const orderFillRequest of orderFillRequests) {
|
||||
await this._orderValidationUtils.validateFillOrderThrowIfInvalidAsync(
|
||||
exchangeTradeEmulator, orderFillRequest.signedOrder, orderFillRequest.takerTokenFillAmount,
|
||||
@@ -367,18 +345,6 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
);
|
||||
|
||||
const exchangeInstance = await this._getExchangeContractAsync();
|
||||
const gas = await exchangeInstance.batchFillOrders.estimateGasAsync(
|
||||
orderAddressesArray,
|
||||
orderValuesArray,
|
||||
fillTakerTokenAmounts,
|
||||
shouldThrowOnInsufficientBalanceOrAllowance,
|
||||
vArray,
|
||||
rArray,
|
||||
sArray,
|
||||
{
|
||||
from: takerAddress,
|
||||
},
|
||||
);
|
||||
const txHash = await exchangeInstance.batchFillOrders.sendTransactionAsync(
|
||||
orderAddressesArray,
|
||||
orderValuesArray,
|
||||
@@ -389,7 +355,8 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
sArray,
|
||||
{
|
||||
from: takerAddress,
|
||||
gas,
|
||||
gas: orderTransactionOpts.gasLimit,
|
||||
gasPrice: orderTransactionOpts.gasPrice,
|
||||
},
|
||||
);
|
||||
return txHash;
|
||||
@@ -405,39 +372,27 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param orderTransactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async fillOrKillOrderAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber,
|
||||
takerAddress: string,
|
||||
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
|
||||
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
|
||||
assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
|
||||
assert.isValidBaseUnitAmount('fillTakerTokenAmount', fillTakerTokenAmount);
|
||||
await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper);
|
||||
|
||||
const exchangeInstance = await this._getExchangeContractAsync();
|
||||
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
if (shouldValidate) {
|
||||
const zrxTokenAddress = await this.getZRXTokenAddressAsync();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper);
|
||||
const zrxTokenAddress = this.getZRXTokenAddress();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
|
||||
await this._orderValidationUtils.validateFillOrKillOrderThrowIfInvalidAsync(
|
||||
exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress);
|
||||
}
|
||||
|
||||
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(signedOrder);
|
||||
|
||||
const gas = await exchangeInstance.fillOrKillOrder.estimateGasAsync(
|
||||
orderAddresses,
|
||||
orderValues,
|
||||
fillTakerTokenAmount,
|
||||
signedOrder.ecSignature.v,
|
||||
signedOrder.ecSignature.r,
|
||||
signedOrder.ecSignature.s,
|
||||
{
|
||||
from: takerAddress,
|
||||
},
|
||||
);
|
||||
const txHash = await exchangeInstance.fillOrKillOrder.sendTransactionAsync(
|
||||
orderAddresses,
|
||||
orderValues,
|
||||
@@ -447,7 +402,8 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
signedOrder.ecSignature.s,
|
||||
{
|
||||
from: takerAddress,
|
||||
gas,
|
||||
gas: orderTransactionOpts.gasLimit,
|
||||
gasPrice: orderTransactionOpts.gasPrice,
|
||||
},
|
||||
);
|
||||
return txHash;
|
||||
@@ -461,10 +417,10 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param orderTransactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async batchFillOrKillAsync(orderFillRequests: OrderFillRequest[],
|
||||
takerAddress: string,
|
||||
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
|
||||
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
|
||||
assert.doesConformToSchema('orderFillRequests', orderFillRequests,
|
||||
schemas.orderFillRequestsSchema);
|
||||
const exchangeContractAddresses = _.map(
|
||||
@@ -479,12 +435,12 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
}
|
||||
const exchangeInstance = await this._getExchangeContractAsync();
|
||||
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
if (shouldValidate) {
|
||||
const zrxTokenAddress = await this.getZRXTokenAddressAsync();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper);
|
||||
const zrxTokenAddress = this.getZRXTokenAddress();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
|
||||
for (const orderFillRequest of orderFillRequests) {
|
||||
await this._orderValidationUtils.validateFillOrKillOrderThrowIfInvalidAsync(
|
||||
exchangeTradeEmulator, orderFillRequest.signedOrder, orderFillRequest.takerTokenFillAmount,
|
||||
@@ -506,18 +462,6 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
// We use _.unzip<any> because _.unzip doesn't type check if values have different types :'(
|
||||
const [orderAddresses, orderValues, fillTakerTokenAmounts, vParams, rParams, sParams] =
|
||||
_.unzip<any>(orderAddressesValuesAndTakerTokenFillAmounts);
|
||||
|
||||
const gas = await exchangeInstance.batchFillOrKillOrders.estimateGasAsync(
|
||||
orderAddresses,
|
||||
orderValues,
|
||||
fillTakerTokenAmounts,
|
||||
vParams,
|
||||
rParams,
|
||||
sParams,
|
||||
{
|
||||
from: takerAddress,
|
||||
},
|
||||
);
|
||||
const txHash = await exchangeInstance.batchFillOrKillOrders.sendTransactionAsync(
|
||||
orderAddresses,
|
||||
orderValues,
|
||||
@@ -527,7 +471,8 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
sParams,
|
||||
{
|
||||
from: takerAddress,
|
||||
gas,
|
||||
gas: orderTransactionOpts.gasLimit,
|
||||
gasPrice: orderTransactionOpts.gasPrice,
|
||||
},
|
||||
);
|
||||
return txHash;
|
||||
@@ -540,42 +485,35 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param transactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async cancelOrderAsync(order: Order|SignedOrder,
|
||||
cancelTakerTokenAmount: BigNumber,
|
||||
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
|
||||
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
|
||||
assert.doesConformToSchema('order', order, schemas.orderSchema);
|
||||
assert.isValidBaseUnitAmount('takerTokenCancelAmount', cancelTakerTokenAmount);
|
||||
await assert.isSenderAddressAsync('order.maker', order.maker, this._web3Wrapper);
|
||||
|
||||
const exchangeInstance = await this._getExchangeContractAsync();
|
||||
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
if (shouldValidate) {
|
||||
const orderHash = utils.getOrderHashHex(order);
|
||||
const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash);
|
||||
await this._orderValidationUtils.validateCancelOrderThrowIfInvalidAsync(
|
||||
OrderValidationUtils.validateCancelOrderThrowIfInvalid(
|
||||
order, cancelTakerTokenAmount, unavailableTakerTokenAmount);
|
||||
}
|
||||
|
||||
const [orderAddresses, orderValues] = ExchangeWrapper._getOrderAddressesAndValues(order);
|
||||
const gas = await exchangeInstance.cancelOrder.estimateGasAsync(
|
||||
orderAddresses,
|
||||
orderValues,
|
||||
cancelTakerTokenAmount,
|
||||
{
|
||||
from: order.maker,
|
||||
},
|
||||
);
|
||||
const txHash = await exchangeInstance.cancelOrder.sendTransactionAsync(
|
||||
orderAddresses,
|
||||
orderValues,
|
||||
cancelTakerTokenAmount,
|
||||
{
|
||||
from: order.maker,
|
||||
gas,
|
||||
gas: orderTransactionOpts.gasLimit,
|
||||
gasPrice: orderTransactionOpts.gasPrice,
|
||||
},
|
||||
);
|
||||
return txHash;
|
||||
@@ -588,9 +526,9 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param transactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async batchCancelOrdersAsync(orderCancellationRequests: OrderCancellationRequest[],
|
||||
orderTransactionOpts?: OrderTransactionOpts): Promise<string> {
|
||||
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
|
||||
assert.doesConformToSchema('orderCancellationRequests', orderCancellationRequests,
|
||||
schemas.orderCancellationRequestsSchema);
|
||||
const exchangeContractAddresses = _.map(
|
||||
@@ -603,14 +541,14 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
assert.hasAtMostOneUniqueValue(makers, ExchangeContractErrs.MultipleMakersInSingleCancelBatchDisallowed);
|
||||
const maker = makers[0];
|
||||
await assert.isSenderAddressAsync('maker', maker, this._web3Wrapper);
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
const shouldValidate = _.isUndefined(orderTransactionOpts.shouldValidate) ?
|
||||
SHOULD_VALIDATE_BY_DEFAULT :
|
||||
orderTransactionOpts.shouldValidate;
|
||||
if (shouldValidate) {
|
||||
for (const orderCancellationRequest of orderCancellationRequests) {
|
||||
const orderHash = utils.getOrderHashHex(orderCancellationRequest.order);
|
||||
const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash);
|
||||
await this._orderValidationUtils.validateCancelOrderThrowIfInvalidAsync(
|
||||
OrderValidationUtils.validateCancelOrderThrowIfInvalid(
|
||||
orderCancellationRequest.order, orderCancellationRequest.takerTokenCancelAmount,
|
||||
unavailableTakerTokenAmount,
|
||||
);
|
||||
@@ -630,21 +568,14 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
// We use _.unzip<any> because _.unzip doesn't type check if values have different types :'(
|
||||
const [orderAddresses, orderValues, cancelTakerTokenAmounts] =
|
||||
_.unzip<any>(orderAddressesValuesAndTakerTokenCancelAmounts);
|
||||
const gas = await exchangeInstance.batchCancelOrders.estimateGasAsync(
|
||||
orderAddresses,
|
||||
orderValues,
|
||||
cancelTakerTokenAmounts,
|
||||
{
|
||||
from: maker,
|
||||
},
|
||||
);
|
||||
const txHash = await exchangeInstance.batchCancelOrders.sendTransactionAsync(
|
||||
orderAddresses,
|
||||
orderValues,
|
||||
cancelTakerTokenAmounts,
|
||||
{
|
||||
from: maker,
|
||||
gas,
|
||||
gas: orderTransactionOpts.gasLimit,
|
||||
gasPrice: orderTransactionOpts.gasPrice,
|
||||
},
|
||||
);
|
||||
return txHash;
|
||||
@@ -657,13 +588,13 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param callback Callback that gets called when a log is added/removed
|
||||
* @return Subscription token used later to unsubscribe
|
||||
*/
|
||||
public async subscribeAsync<ArgsType extends ExchangeContractEventArgs>(
|
||||
public subscribe<ArgsType extends ExchangeContractEventArgs>(
|
||||
eventName: ExchangeEvents, indexFilterValues: IndexedFilterValues,
|
||||
callback: EventCallback<ArgsType>): Promise<string> {
|
||||
callback: EventCallback<ArgsType>): string {
|
||||
assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents);
|
||||
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
|
||||
assert.isFunction('callback', callback);
|
||||
const exchangeContractAddress = await this.getContractAddressAsync();
|
||||
const exchangeContractAddress = this.getContractAddress();
|
||||
const subscriptionToken = this._subscribe<ArgsType>(
|
||||
exchangeContractAddress, eventName, indexFilterValues, artifacts.ExchangeArtifact.abi, callback,
|
||||
);
|
||||
@@ -676,23 +607,29 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
public unsubscribe(subscriptionToken: string): void {
|
||||
this._unsubscribe(subscriptionToken);
|
||||
}
|
||||
/**
|
||||
* Cancels all existing subscriptions
|
||||
*/
|
||||
public unsubscribeAll(): void {
|
||||
super.unsubscribeAll();
|
||||
}
|
||||
/**
|
||||
* Gets historical logs without creating a subscription
|
||||
* @param eventName The exchange contract event you would like to subscribe to.
|
||||
* @param subscriptionOpts Subscriptions options that let you configure the subscription.
|
||||
* @param blockRange Block range to get logs from.
|
||||
* @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 `{_from: aUserAddressHex}`
|
||||
* @return Array of logs that match the parameters
|
||||
*/
|
||||
public async getLogsAsync<ArgsType extends ExchangeContractEventArgs>(
|
||||
eventName: ExchangeEvents, subscriptionOpts: SubscriptionOpts, indexFilterValues: IndexedFilterValues,
|
||||
eventName: ExchangeEvents, blockRange: BlockRange, indexFilterValues: IndexedFilterValues,
|
||||
): Promise<Array<LogWithDecodedArgs<ArgsType>>> {
|
||||
assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents);
|
||||
assert.doesConformToSchema('subscriptionOpts', subscriptionOpts, schemas.subscriptionOptsSchema);
|
||||
assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema);
|
||||
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
|
||||
const exchangeContractAddress = await this.getContractAddressAsync();
|
||||
const exchangeContractAddress = this.getContractAddress();
|
||||
const logs = await this._getLogsAsync<ArgsType>(
|
||||
exchangeContractAddress, eventName, subscriptionOpts, indexFilterValues, artifacts.ExchangeArtifact.abi,
|
||||
exchangeContractAddress, eventName, blockRange, indexFilterValues, artifacts.ExchangeArtifact.abi,
|
||||
);
|
||||
return logs;
|
||||
}
|
||||
@@ -701,10 +638,9 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* that the user-passed web3 provider is connected to.
|
||||
* @returns The Ethereum address of the Exchange contract being used.
|
||||
*/
|
||||
public async getContractAddressAsync(): Promise<string> {
|
||||
const exchangeInstance = await this._getExchangeContractAsync();
|
||||
const exchangeAddress = exchangeInstance.address;
|
||||
return exchangeAddress;
|
||||
public getContractAddress(): string {
|
||||
const contractAddress = this._getContractAddress(artifacts.ExchangeArtifact, this._contractAddressIfExists);
|
||||
return contractAddress;
|
||||
}
|
||||
/**
|
||||
* Checks if order is still fillable and throws an error otherwise. Useful for orderbook
|
||||
@@ -719,9 +655,9 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
signedOrder: SignedOrder, opts?: ValidateOrderFillableOpts,
|
||||
): Promise<void> {
|
||||
assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
|
||||
const zrxTokenAddress = await this.getZRXTokenAddressAsync();
|
||||
const zrxTokenAddress = this.getZRXTokenAddress();
|
||||
const expectedFillTakerTokenAmount = !_.isUndefined(opts) ? opts.expectedFillTakerTokenAmount : undefined;
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper);
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
|
||||
await this._orderValidationUtils.validateOrderFillableOrThrowAsync(
|
||||
exchangeTradeEmulator, signedOrder, zrxTokenAddress, expectedFillTakerTokenAmount,
|
||||
);
|
||||
@@ -740,8 +676,8 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
|
||||
assert.isValidBaseUnitAmount('fillTakerTokenAmount', fillTakerTokenAmount);
|
||||
await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper);
|
||||
const zrxTokenAddress = await this.getZRXTokenAddressAsync();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper);
|
||||
const zrxTokenAddress = this.getZRXTokenAddress();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
|
||||
await this._orderValidationUtils.validateFillOrderThrowIfInvalidAsync(
|
||||
exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress);
|
||||
}
|
||||
@@ -757,7 +693,7 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
assert.isValidBaseUnitAmount('cancelTakerTokenAmount', cancelTakerTokenAmount);
|
||||
const orderHash = utils.getOrderHashHex(order);
|
||||
const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash);
|
||||
await this._orderValidationUtils.validateCancelOrderThrowIfInvalidAsync(
|
||||
OrderValidationUtils.validateCancelOrderThrowIfInvalid(
|
||||
order, cancelTakerTokenAmount, unavailableTakerTokenAmount);
|
||||
}
|
||||
/**
|
||||
@@ -774,8 +710,8 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
|
||||
assert.isValidBaseUnitAmount('fillTakerTokenAmount', fillTakerTokenAmount);
|
||||
await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper);
|
||||
const zrxTokenAddress = await this.getZRXTokenAddressAsync();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper);
|
||||
const zrxTokenAddress = this.getZRXTokenAddress();
|
||||
const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest);
|
||||
await this._orderValidationUtils.validateFillOrKillOrderThrowIfInvalidAsync(
|
||||
exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress);
|
||||
}
|
||||
@@ -819,12 +755,13 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* Returns the ZRX token address used by the exchange contract.
|
||||
* @return Address of ZRX token
|
||||
*/
|
||||
public async getZRXTokenAddressAsync(): Promise<string> {
|
||||
const exchangeInstance = await this._getExchangeContractAsync();
|
||||
const ZRXtokenAddress = await exchangeInstance.ZRX_TOKEN_CONTRACT.callAsync();
|
||||
return ZRXtokenAddress;
|
||||
public getZRXTokenAddress(): string {
|
||||
const contractAddress = this._getContractAddress(
|
||||
artifacts.ZRXArtifact, this._zrxContractAddressIfExists,
|
||||
);
|
||||
return contractAddress;
|
||||
}
|
||||
private async _invalidateContractInstancesAsync(): Promise<void> {
|
||||
private _invalidateContractInstances(): void {
|
||||
this.unsubscribeAll();
|
||||
delete this._exchangeContractIfExists;
|
||||
}
|
||||
@@ -855,10 +792,11 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
if (!_.isUndefined(this._exchangeContractIfExists)) {
|
||||
return this._exchangeContractIfExists;
|
||||
}
|
||||
const contractInstance = await this._instantiateContractIfExistsAsync<ExchangeContract>(
|
||||
const web3ContractInstance = await this._instantiateContractIfExistsAsync(
|
||||
artifacts.ExchangeArtifact, this._contractAddressIfExists,
|
||||
);
|
||||
this._exchangeContractIfExists = contractInstance as ExchangeContract;
|
||||
const contractInstance = new ExchangeContract(web3ContractInstance, this._web3Wrapper.getContractDefaults());
|
||||
this._exchangeContractIfExists = contractInstance;
|
||||
return this._exchangeContractIfExists;
|
||||
}
|
||||
private async _getTokenTransferProxyAddressAsync(): Promise<string> {
|
||||
@@ -867,4 +805,4 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
const tokenTransferProxyAddressLowerCase = tokenTransferProxyAddress.toLowerCase();
|
||||
return tokenTransferProxyAddressLowerCase;
|
||||
}
|
||||
}
|
||||
} // tslint:disable:max-file-line-count
|
||||
|
6
packages/0x.js/src/contract_wrappers/generated/.gitignore
vendored
Normal file
6
packages/0x.js/src/contract_wrappers/generated/.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
dummy_token.ts
|
||||
ether_token.ts
|
||||
exchange.ts
|
||||
token_registry.ts
|
||||
token_transfer_proxy.ts
|
||||
token.ts
|
@@ -0,0 +1,33 @@
|
||||
import {TxData, TxDataPayable} from '@0xproject/types';
|
||||
import * as _ from 'lodash';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
export class BaseContract {
|
||||
protected web3ContractInstance: Web3.ContractInstance;
|
||||
protected defaults: Partial<TxData>;
|
||||
protected async applyDefaultsToTxDataAsync<T extends TxData|TxDataPayable>(
|
||||
txData: T,
|
||||
estimateGasAsync?: (txData: T) => Promise<number>,
|
||||
): Promise<TxData> {
|
||||
// Gas amount sourced with the following priorities:
|
||||
// 1. Optional param passed in to public method call
|
||||
// 2. Global config passed in at library instantiation
|
||||
// 3. Gas estimate calculation + safety margin
|
||||
const removeUndefinedProperties = _.pickBy;
|
||||
const txDataWithDefaults = {
|
||||
...removeUndefinedProperties(this.defaults),
|
||||
...removeUndefinedProperties(txData as any),
|
||||
// HACK: TS can't prove that T is spreadable.
|
||||
// Awaiting https://github.com/Microsoft/TypeScript/pull/13288 to be merged
|
||||
};
|
||||
if (_.isUndefined(txDataWithDefaults.gas) && !_.isUndefined(estimateGasAsync)) {
|
||||
const estimatedGas = await estimateGasAsync(txData);
|
||||
txDataWithDefaults.gas = estimatedGas;
|
||||
}
|
||||
return txDataWithDefaults;
|
||||
}
|
||||
constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) {
|
||||
this.web3ContractInstance = web3ContractInstance;
|
||||
this.defaults = defaults;
|
||||
}
|
||||
}
|
@@ -1,10 +1,13 @@
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import * as _ from 'lodash';
|
||||
import {Web3Wrapper} from '../web3_wrapper';
|
||||
import {assert} from '../utils/assert';
|
||||
import {Token, TokenRegistryContract, TokenMetadata} from '../types';
|
||||
import {constants} from '../utils/constants';
|
||||
import {ContractWrapper} from './contract_wrapper';
|
||||
|
||||
import {artifacts} from '../artifacts';
|
||||
import {Token, TokenMetadata} from '../types';
|
||||
import {assert} from '../utils/assert';
|
||||
import {constants} from '../utils/constants';
|
||||
|
||||
import {ContractWrapper} from './contract_wrapper';
|
||||
import {TokenRegistryContract} from './generated/token_registry';
|
||||
|
||||
/**
|
||||
* This class includes all the functionality related to interacting with the 0x Token Registry smart contract.
|
||||
@@ -12,8 +15,20 @@ import {artifacts} from '../artifacts';
|
||||
export class TokenRegistryWrapper extends ContractWrapper {
|
||||
private _tokenRegistryContractIfExists?: TokenRegistryContract;
|
||||
private _contractAddressIfExists?: string;
|
||||
constructor(web3Wrapper: Web3Wrapper, contractAddressIfExists?: string) {
|
||||
super(web3Wrapper);
|
||||
private static _createTokenFromMetadata(metadata: TokenMetadata): Token|undefined {
|
||||
if (metadata[0] === constants.NULL_ADDRESS) {
|
||||
return undefined;
|
||||
}
|
||||
const token = {
|
||||
address: metadata[0],
|
||||
name: metadata[1],
|
||||
symbol: metadata[2],
|
||||
decimals: metadata[3].toNumber(),
|
||||
};
|
||||
return token;
|
||||
}
|
||||
constructor(web3Wrapper: Web3Wrapper, networkId: number, contractAddressIfExists?: string) {
|
||||
super(web3Wrapper, networkId);
|
||||
this._contractAddressIfExists = contractAddressIfExists;
|
||||
}
|
||||
/**
|
||||
@@ -21,12 +36,10 @@ export class TokenRegistryWrapper extends ContractWrapper {
|
||||
* @return An array of objects that conform to the Token interface.
|
||||
*/
|
||||
public async getTokensAsync(): Promise<Token[]> {
|
||||
const tokenRegistryContract = await this._getTokenRegistryContractAsync();
|
||||
|
||||
const addresses = await this.getTokenAddressesAsync();
|
||||
const tokenPromises: Array<Promise<Token|undefined>> = _.map(
|
||||
addresses,
|
||||
(address: string) => (this.getTokenIfExistsAsync(address)),
|
||||
async (address: string) => this.getTokenIfExistsAsync(address),
|
||||
);
|
||||
const tokens = await Promise.all(tokenPromises);
|
||||
return tokens as Token[];
|
||||
@@ -49,7 +62,7 @@ export class TokenRegistryWrapper extends ContractWrapper {
|
||||
|
||||
const tokenRegistryContract = await this._getTokenRegistryContractAsync();
|
||||
const metadata = await tokenRegistryContract.getTokenMetaData.callAsync(address);
|
||||
const token = this._createTokenFromMetadata(metadata);
|
||||
const token = TokenRegistryWrapper._createTokenFromMetadata(metadata);
|
||||
return token;
|
||||
}
|
||||
public async getTokenAddressBySymbolIfExistsAsync(symbol: string): Promise<string|undefined> {
|
||||
@@ -74,14 +87,14 @@ export class TokenRegistryWrapper extends ContractWrapper {
|
||||
assert.isString('symbol', symbol);
|
||||
const tokenRegistryContract = await this._getTokenRegistryContractAsync();
|
||||
const metadata = await tokenRegistryContract.getTokenBySymbol.callAsync(symbol);
|
||||
const token = this._createTokenFromMetadata(metadata);
|
||||
const token = TokenRegistryWrapper._createTokenFromMetadata(metadata);
|
||||
return token;
|
||||
}
|
||||
public async getTokenByNameIfExistsAsync(name: string): Promise<Token|undefined> {
|
||||
assert.isString('name', name);
|
||||
const tokenRegistryContract = await this._getTokenRegistryContractAsync();
|
||||
const metadata = await tokenRegistryContract.getTokenByName.callAsync(name);
|
||||
const token = this._createTokenFromMetadata(metadata);
|
||||
const token = TokenRegistryWrapper._createTokenFromMetadata(metadata);
|
||||
return token;
|
||||
}
|
||||
/**
|
||||
@@ -89,22 +102,11 @@ export class TokenRegistryWrapper extends ContractWrapper {
|
||||
* that the user-passed web3 provider is connected to.
|
||||
* @returns The Ethereum address of the TokenRegistry contract being used.
|
||||
*/
|
||||
public async getContractAddressAsync(): Promise<string> {
|
||||
const tokenRegistryInstance = await this._getTokenRegistryContractAsync();
|
||||
const tokenRegistryAddress = tokenRegistryInstance.address;
|
||||
return tokenRegistryAddress;
|
||||
}
|
||||
private _createTokenFromMetadata(metadata: TokenMetadata): Token|undefined {
|
||||
if (metadata[0] === constants.NULL_ADDRESS) {
|
||||
return undefined;
|
||||
}
|
||||
const token = {
|
||||
address: metadata[0],
|
||||
name: metadata[1],
|
||||
symbol: metadata[2],
|
||||
decimals: metadata[3].toNumber(),
|
||||
};
|
||||
return token;
|
||||
public getContractAddress(): string {
|
||||
const contractAddress = this._getContractAddress(
|
||||
artifacts.TokenRegistryArtifact, this._contractAddressIfExists,
|
||||
);
|
||||
return contractAddress;
|
||||
}
|
||||
private _invalidateContractInstance(): void {
|
||||
delete this._tokenRegistryContractIfExists;
|
||||
@@ -113,10 +115,13 @@ export class TokenRegistryWrapper extends ContractWrapper {
|
||||
if (!_.isUndefined(this._tokenRegistryContractIfExists)) {
|
||||
return this._tokenRegistryContractIfExists;
|
||||
}
|
||||
const contractInstance = await this._instantiateContractIfExistsAsync<TokenRegistryContract>(
|
||||
const web3ContractInstance = await this._instantiateContractIfExistsAsync(
|
||||
artifacts.TokenRegistryArtifact, this._contractAddressIfExists,
|
||||
);
|
||||
this._tokenRegistryContractIfExists = contractInstance as TokenRegistryContract;
|
||||
const contractInstance = new TokenRegistryContract(
|
||||
web3ContractInstance, this._web3Wrapper.getContractDefaults(),
|
||||
);
|
||||
this._tokenRegistryContractIfExists = contractInstance;
|
||||
return this._tokenRegistryContractIfExists;
|
||||
}
|
||||
}
|
||||
|
@@ -1,18 +1,20 @@
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import * as _ from 'lodash';
|
||||
import {Web3Wrapper} from '../web3_wrapper';
|
||||
import {ContractWrapper} from './contract_wrapper';
|
||||
|
||||
import {artifacts} from '../artifacts';
|
||||
import {TokenTransferProxyContract} from '../types';
|
||||
|
||||
import {ContractWrapper} from './contract_wrapper';
|
||||
import {TokenTransferProxyContract} from './generated/token_transfer_proxy';
|
||||
|
||||
/**
|
||||
* This class includes the functionality related to interacting with the TokenTransferProxy contract.
|
||||
*/
|
||||
export class TokenTransferProxyWrapper extends ContractWrapper {
|
||||
private _tokenTransferProxyContractIfExists?: TokenTransferProxyContract;
|
||||
private _tokenTransferProxyContractAddressFetcher: () => Promise<string>;
|
||||
constructor(web3Wrapper: Web3Wrapper, tokenTransferProxyContractAddressFetcher: () => Promise<string>) {
|
||||
super(web3Wrapper);
|
||||
this._tokenTransferProxyContractAddressFetcher = tokenTransferProxyContractAddressFetcher;
|
||||
private _contractAddressIfExists?: string;
|
||||
constructor(web3Wrapper: Web3Wrapper, networkId: number, contractAddressIfExists?: string) {
|
||||
super(web3Wrapper, networkId);
|
||||
this._contractAddressIfExists = contractAddressIfExists;
|
||||
}
|
||||
/**
|
||||
* Check if the Exchange contract address is authorized by the TokenTransferProxy contract.
|
||||
@@ -38,10 +40,11 @@ export class TokenTransferProxyWrapper extends ContractWrapper {
|
||||
* that the user-passed web3 provider is connected to.
|
||||
* @returns The Ethereum address of the TokenTransferProxy contract being used.
|
||||
*/
|
||||
public async getContractAddressAsync(): Promise<string> {
|
||||
const proxyInstance = await this._getTokenTransferProxyContractAsync();
|
||||
const proxyAddress = proxyInstance.address;
|
||||
return proxyAddress;
|
||||
public getContractAddress(): string {
|
||||
const contractAddress = this._getContractAddress(
|
||||
artifacts.TokenTransferProxyArtifact, this._contractAddressIfExists,
|
||||
);
|
||||
return contractAddress;
|
||||
}
|
||||
private _invalidateContractInstance(): void {
|
||||
delete this._tokenTransferProxyContractIfExists;
|
||||
@@ -50,11 +53,13 @@ export class TokenTransferProxyWrapper extends ContractWrapper {
|
||||
if (!_.isUndefined(this._tokenTransferProxyContractIfExists)) {
|
||||
return this._tokenTransferProxyContractIfExists;
|
||||
}
|
||||
const contractAddress = await this._tokenTransferProxyContractAddressFetcher();
|
||||
const contractInstance = await this._instantiateContractIfExistsAsync<TokenTransferProxyContract>(
|
||||
artifacts.TokenTransferProxyArtifact, contractAddress,
|
||||
const web3ContractInstance = await this._instantiateContractIfExistsAsync(
|
||||
artifacts.TokenTransferProxyArtifact, this._contractAddressIfExists,
|
||||
);
|
||||
this._tokenTransferProxyContractIfExists = contractInstance as TokenTransferProxyContract;
|
||||
const contractInstance = new TokenTransferProxyContract(
|
||||
web3ContractInstance, this._web3Wrapper.getContractDefaults(),
|
||||
);
|
||||
this._tokenTransferProxyContractIfExists = contractInstance;
|
||||
return this._tokenTransferProxyContractIfExists;
|
||||
}
|
||||
}
|
||||
|
@@ -1,25 +1,27 @@
|
||||
import * as _ from 'lodash';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import {schemas} from '@0xproject/json-schemas';
|
||||
import {Web3Wrapper} from '../web3_wrapper';
|
||||
import {assert} from '../utils/assert';
|
||||
import {constants} from '../utils/constants';
|
||||
import {ContractWrapper} from './contract_wrapper';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {artifacts} from '../artifacts';
|
||||
import {
|
||||
TokenContract,
|
||||
ZeroExError,
|
||||
TokenEvents,
|
||||
IndexedFilterValues,
|
||||
SubscriptionOpts,
|
||||
MethodOpts,
|
||||
LogWithDecodedArgs,
|
||||
BlockRange,
|
||||
EventCallback,
|
||||
IndexedFilterValues,
|
||||
LogWithDecodedArgs,
|
||||
MethodOpts,
|
||||
TokenContractEventArgs,
|
||||
TokenEvents,
|
||||
TransactionOpts,
|
||||
ZeroExError,
|
||||
} from '../types';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
import {assert} from '../utils/assert';
|
||||
import {constants} from '../utils/constants';
|
||||
|
||||
const ALLOWANCE_TO_ZERO_GAS_AMOUNT = 47275;
|
||||
import {ContractWrapper} from './contract_wrapper';
|
||||
import {TokenContract} from './generated/token';
|
||||
import {TokenTransferProxyWrapper} from './token_transfer_proxy_wrapper';
|
||||
|
||||
/**
|
||||
* This class includes all the functionality related to interacting with ERC20 token contracts.
|
||||
@@ -29,12 +31,12 @@ const ALLOWANCE_TO_ZERO_GAS_AMOUNT = 47275;
|
||||
export class TokenWrapper extends ContractWrapper {
|
||||
public UNLIMITED_ALLOWANCE_IN_BASE_UNITS = constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
|
||||
private _tokenContractsByAddress: {[address: string]: TokenContract};
|
||||
private _tokenTransferProxyContractAddressFetcher: () => Promise<string>;
|
||||
constructor(web3Wrapper: Web3Wrapper, abiDecoder: AbiDecoder,
|
||||
tokenTransferProxyContractAddressFetcher: () => Promise<string>) {
|
||||
super(web3Wrapper, abiDecoder);
|
||||
private _tokenTransferProxyWrapper: TokenTransferProxyWrapper;
|
||||
constructor(web3Wrapper: Web3Wrapper, networkId: number, abiDecoder: AbiDecoder,
|
||||
tokenTransferProxyWrapper: TokenTransferProxyWrapper) {
|
||||
super(web3Wrapper, networkId, abiDecoder);
|
||||
this._tokenContractsByAddress = {};
|
||||
this._tokenTransferProxyContractAddressFetcher = tokenTransferProxyContractAddressFetcher;
|
||||
this._tokenTransferProxyWrapper = tokenTransferProxyWrapper;
|
||||
}
|
||||
/**
|
||||
* Retrieves an owner's ERC20 token balance.
|
||||
@@ -63,24 +65,21 @@ export class TokenWrapper extends ContractWrapper {
|
||||
* for spenderAddress.
|
||||
* @param spenderAddress The hex encoded user Ethereum address who will be able to spend the set allowance.
|
||||
* @param amountInBaseUnits The allowance amount you would like to set.
|
||||
* @param txOpts Transaction parameters.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
public async setAllowanceAsync(tokenAddress: string, ownerAddress: string, spenderAddress: string,
|
||||
amountInBaseUnits: BigNumber): Promise<string> {
|
||||
amountInBaseUnits: BigNumber, txOpts: TransactionOpts = {}): Promise<string> {
|
||||
await assert.isSenderAddressAsync('ownerAddress', ownerAddress, this._web3Wrapper);
|
||||
assert.isETHAddressHex('spenderAddress', spenderAddress);
|
||||
assert.isETHAddressHex('tokenAddress', tokenAddress);
|
||||
assert.isValidBaseUnitAmount('amountInBaseUnits', amountInBaseUnits);
|
||||
|
||||
const tokenContract = await this._getTokenContractAsync(tokenAddress);
|
||||
// Hack: for some reason default estimated gas amount causes `base fee exceeds gas limit` exception
|
||||
// on testrpc. Probably related to https://github.com/ethereumjs/testrpc/issues/294
|
||||
// TODO: Debug issue in testrpc and submit a PR, then remove this hack
|
||||
const networkIdIfExists = await this._web3Wrapper.getNetworkIdIfExistsAsync();
|
||||
const gas = networkIdIfExists === constants.TESTRPC_NETWORK_ID ? ALLOWANCE_TO_ZERO_GAS_AMOUNT : undefined;
|
||||
const txHash = await tokenContract.approve.sendTransactionAsync(spenderAddress, amountInBaseUnits, {
|
||||
from: ownerAddress,
|
||||
gas,
|
||||
gas: txOpts.gasLimit,
|
||||
gasPrice: txOpts.gasPrice,
|
||||
});
|
||||
return txHash;
|
||||
}
|
||||
@@ -93,12 +92,13 @@ export class TokenWrapper extends ContractWrapper {
|
||||
* @param ownerAddress The hex encoded user Ethereum address who would like to set an allowance
|
||||
* for spenderAddress.
|
||||
* @param spenderAddress The hex encoded user Ethereum address who will be able to spend the set allowance.
|
||||
* @param txOpts Transaction parameters.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
public async setUnlimitedAllowanceAsync(tokenAddress: string, ownerAddress: string,
|
||||
spenderAddress: string): Promise<string> {
|
||||
spenderAddress: string, txOpts: TransactionOpts = {}): Promise<string> {
|
||||
const txHash = await this.setAllowanceAsync(
|
||||
tokenAddress, ownerAddress, spenderAddress, this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS,
|
||||
tokenAddress, ownerAddress, spenderAddress, this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS, txOpts,
|
||||
);
|
||||
return txHash;
|
||||
}
|
||||
@@ -133,7 +133,7 @@ export class TokenWrapper extends ContractWrapper {
|
||||
assert.isETHAddressHex('ownerAddress', ownerAddress);
|
||||
assert.isETHAddressHex('tokenAddress', tokenAddress);
|
||||
|
||||
const proxyAddress = await this._getTokenTransferProxyAddressAsync();
|
||||
const proxyAddress = this._tokenTransferProxyWrapper.getContractAddress();
|
||||
const allowanceInBaseUnits = await this.getAllowanceAsync(tokenAddress, ownerAddress, proxyAddress, methodOpts);
|
||||
return allowanceInBaseUnits;
|
||||
}
|
||||
@@ -144,16 +144,19 @@ export class TokenWrapper extends ContractWrapper {
|
||||
* @param ownerAddress The hex encoded user Ethereum address who is setting an allowance
|
||||
* for the Proxy contract.
|
||||
* @param amountInBaseUnits The allowance amount specified in baseUnits.
|
||||
* @param txOpts Transaction parameters.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
public async setProxyAllowanceAsync(tokenAddress: string, ownerAddress: string,
|
||||
amountInBaseUnits: BigNumber): Promise<string> {
|
||||
amountInBaseUnits: BigNumber, txOpts: TransactionOpts = {}): Promise<string> {
|
||||
assert.isETHAddressHex('ownerAddress', ownerAddress);
|
||||
assert.isETHAddressHex('tokenAddress', tokenAddress);
|
||||
assert.isValidBaseUnitAmount('amountInBaseUnits', amountInBaseUnits);
|
||||
|
||||
const proxyAddress = await this._getTokenTransferProxyAddressAsync();
|
||||
const txHash = await this.setAllowanceAsync(tokenAddress, ownerAddress, proxyAddress, amountInBaseUnits);
|
||||
const proxyAddress = this._tokenTransferProxyWrapper.getContractAddress();
|
||||
const txHash = await this.setAllowanceAsync(
|
||||
tokenAddress, ownerAddress, proxyAddress, amountInBaseUnits, txOpts,
|
||||
);
|
||||
return txHash;
|
||||
}
|
||||
/**
|
||||
@@ -164,11 +167,14 @@ export class TokenWrapper extends ContractWrapper {
|
||||
* @param tokenAddress The hex encoded contract Ethereum address where the ERC20 token is deployed.
|
||||
* @param ownerAddress The hex encoded user Ethereum address who is setting an allowance
|
||||
* for the Proxy contract.
|
||||
* @param txOpts Transaction parameters.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
public async setUnlimitedProxyAllowanceAsync(tokenAddress: string, ownerAddress: string): Promise<string> {
|
||||
public async setUnlimitedProxyAllowanceAsync(
|
||||
tokenAddress: string, ownerAddress: string, txOpts: TransactionOpts = {},
|
||||
): Promise<string> {
|
||||
const txHash = await this.setProxyAllowanceAsync(
|
||||
tokenAddress, ownerAddress, this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS,
|
||||
tokenAddress, ownerAddress, this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS, txOpts,
|
||||
);
|
||||
return txHash;
|
||||
}
|
||||
@@ -178,10 +184,11 @@ export class TokenWrapper extends ContractWrapper {
|
||||
* @param fromAddress The hex encoded user Ethereum address that will send the funds.
|
||||
* @param toAddress The hex encoded user Ethereum address that will receive the funds.
|
||||
* @param amountInBaseUnits The amount (specified in baseUnits) of the token to transfer.
|
||||
* @param txOpts Transaction parameters.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
public async transferAsync(tokenAddress: string, fromAddress: string, toAddress: string,
|
||||
amountInBaseUnits: BigNumber): Promise<string> {
|
||||
amountInBaseUnits: BigNumber, txOpts: TransactionOpts = {}): Promise<string> {
|
||||
assert.isETHAddressHex('tokenAddress', tokenAddress);
|
||||
await assert.isSenderAddressAsync('fromAddress', fromAddress, this._web3Wrapper);
|
||||
assert.isETHAddressHex('toAddress', toAddress);
|
||||
@@ -196,6 +203,8 @@ export class TokenWrapper extends ContractWrapper {
|
||||
|
||||
const txHash = await tokenContract.transfer.sendTransactionAsync(toAddress, amountInBaseUnits, {
|
||||
from: fromAddress,
|
||||
gas: txOpts.gasLimit,
|
||||
gasPrice: txOpts.gasPrice,
|
||||
});
|
||||
return txHash;
|
||||
}
|
||||
@@ -210,10 +219,11 @@ export class TokenWrapper extends ContractWrapper {
|
||||
* `fromAddress` must have set an allowance to the `senderAddress`
|
||||
* before this call.
|
||||
* @param amountInBaseUnits The amount (specified in baseUnits) of the token to transfer.
|
||||
* @param txOpts Transaction parameters.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
public async transferFromAsync(tokenAddress: string, fromAddress: string, toAddress: string,
|
||||
senderAddress: string, amountInBaseUnits: BigNumber):
|
||||
senderAddress: string, amountInBaseUnits: BigNumber, txOpts: TransactionOpts = {}):
|
||||
Promise<string> {
|
||||
assert.isETHAddressHex('tokenAddress', tokenAddress);
|
||||
assert.isETHAddressHex('fromAddress', fromAddress);
|
||||
@@ -237,6 +247,8 @@ export class TokenWrapper extends ContractWrapper {
|
||||
fromAddress, toAddress, amountInBaseUnits,
|
||||
{
|
||||
from: senderAddress,
|
||||
gas: txOpts.gasLimit,
|
||||
gasPrice: txOpts.gasPrice,
|
||||
},
|
||||
);
|
||||
return txHash;
|
||||
@@ -269,28 +281,34 @@ export class TokenWrapper extends ContractWrapper {
|
||||
public unsubscribe(subscriptionToken: string): void {
|
||||
this._unsubscribe(subscriptionToken);
|
||||
}
|
||||
/**
|
||||
* Cancels all existing subscriptions
|
||||
*/
|
||||
public unsubscribeAll(): void {
|
||||
super.unsubscribeAll();
|
||||
}
|
||||
/**
|
||||
* Gets historical logs without creating a subscription
|
||||
* @param tokenAddress An address of the token that emmited the logs.
|
||||
* @param eventName The token contract event you would like to subscribe to.
|
||||
* @param subscriptionOpts Subscriptions options that let you configure the subscription.
|
||||
* @param blockRange Block range to get logs from.
|
||||
* @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 `{_from: aUserAddressHex}`
|
||||
* @return Array of logs that match the parameters
|
||||
*/
|
||||
public async getLogsAsync<ArgsType extends TokenContractEventArgs>(
|
||||
tokenAddress: string, eventName: TokenEvents, subscriptionOpts: SubscriptionOpts,
|
||||
tokenAddress: string, eventName: TokenEvents, blockRange: BlockRange,
|
||||
indexFilterValues: IndexedFilterValues): Promise<Array<LogWithDecodedArgs<ArgsType>>> {
|
||||
assert.isETHAddressHex('tokenAddress', tokenAddress);
|
||||
assert.doesBelongToStringEnum('eventName', eventName, TokenEvents);
|
||||
assert.doesConformToSchema('subscriptionOpts', subscriptionOpts, schemas.subscriptionOptsSchema);
|
||||
assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema);
|
||||
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
|
||||
const logs = await this._getLogsAsync<ArgsType>(
|
||||
tokenAddress, eventName, subscriptionOpts, indexFilterValues, artifacts.TokenArtifact.abi,
|
||||
tokenAddress, eventName, blockRange, indexFilterValues, artifacts.TokenArtifact.abi,
|
||||
);
|
||||
return logs;
|
||||
}
|
||||
private _invalidateContractInstancesAsync(): void {
|
||||
private _invalidateContractInstances(): void {
|
||||
this.unsubscribeAll();
|
||||
this._tokenContractsByAddress = {};
|
||||
}
|
||||
@@ -299,15 +317,14 @@ export class TokenWrapper extends ContractWrapper {
|
||||
if (!_.isUndefined(tokenContract)) {
|
||||
return tokenContract;
|
||||
}
|
||||
const contractInstance = await this._instantiateContractIfExistsAsync<TokenContract>(
|
||||
const web3ContractInstance = await this._instantiateContractIfExistsAsync(
|
||||
artifacts.TokenArtifact, tokenAddress,
|
||||
);
|
||||
tokenContract = contractInstance as TokenContract;
|
||||
const contractInstance = new TokenContract(
|
||||
web3ContractInstance, this._web3Wrapper.getContractDefaults(),
|
||||
);
|
||||
tokenContract = contractInstance;
|
||||
this._tokenContractsByAddress[tokenAddress] = tokenContract;
|
||||
return tokenContract;
|
||||
}
|
||||
private async _getTokenTransferProxyAddressAsync(): Promise<string> {
|
||||
const tokenTransferProxyContractAddress = await this._tokenTransferProxyContractAddressFetcher();
|
||||
return tokenTransferProxyContractAddress;
|
||||
}
|
||||
}
|
||||
|
6
packages/0x.js/src/globals.d.ts
vendored
6
packages/0x.js/src/globals.d.ts
vendored
@@ -39,12 +39,6 @@ declare module 'compare-versions' {
|
||||
export = compareVersions;
|
||||
}
|
||||
|
||||
// es6-promisify declarations
|
||||
declare function promisify(original: any, settings?: any): ((...arg: any[]) => Promise<any>);
|
||||
declare module 'es6-promisify' {
|
||||
export = promisify;
|
||||
}
|
||||
|
||||
declare module 'ethereumjs-abi' {
|
||||
const soliditySHA3: (argTypes: string[], args: any[]) => Buffer;
|
||||
}
|
||||
|
@@ -2,6 +2,7 @@ export {ZeroEx} from './0x';
|
||||
|
||||
export {
|
||||
Order,
|
||||
BlockParamLiteral,
|
||||
SignedOrder,
|
||||
ECSignature,
|
||||
ZeroExError,
|
||||
@@ -12,7 +13,7 @@ export {
|
||||
ExchangeEvents,
|
||||
TokenEvents,
|
||||
IndexedFilterValues,
|
||||
SubscriptionOpts,
|
||||
BlockRange,
|
||||
BlockParam,
|
||||
OrderCancellationRequest,
|
||||
OrderFillRequest,
|
||||
@@ -23,15 +24,19 @@ export {
|
||||
TransferContractEventArgs,
|
||||
ApprovalContractEventArgs,
|
||||
TokenContractEventArgs,
|
||||
EtherTokenContractEventArgs,
|
||||
WithdrawalContractEventArgs,
|
||||
DepositContractEventArgs,
|
||||
ContractEventArgs,
|
||||
ContractEventArg,
|
||||
Web3Provider,
|
||||
ZeroExConfig,
|
||||
TransactionReceipt,
|
||||
EtherTokenEvents,
|
||||
TransactionReceiptWithDecodedLogs,
|
||||
LogWithDecodedArgs,
|
||||
MethodOpts,
|
||||
OrderTransactionOpts,
|
||||
TransactionOpts,
|
||||
FilterObject,
|
||||
LogEvent,
|
||||
DecodedLogEvent,
|
||||
@@ -41,3 +46,7 @@ export {
|
||||
OrderStateInvalid,
|
||||
OrderState,
|
||||
} from './types';
|
||||
|
||||
export {
|
||||
TransactionReceipt,
|
||||
} from '@0xproject/types';
|
||||
|
@@ -1,18 +1,16 @@
|
||||
import * as Web3 from 'web3';
|
||||
import {intervalUtils} from '@0xproject/utils';
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import * as _ from 'lodash';
|
||||
import {Web3Wrapper} from '../web3_wrapper';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {
|
||||
BlockParamLiteral,
|
||||
EventCallback,
|
||||
EventWatcherCallback,
|
||||
ZeroExError,
|
||||
} from '../types';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
import {intervalUtils} from '../utils/interval_utils';
|
||||
import {assert} from '../utils/assert';
|
||||
import {utils} from '../utils/utils';
|
||||
|
||||
const DEFAULT_EVENT_POLLING_INTERVAL = 200;
|
||||
const DEFAULT_EVENT_POLLING_INTERVAL_MS = 200;
|
||||
|
||||
enum LogEventState {
|
||||
Removed,
|
||||
@@ -28,11 +26,11 @@ export class EventWatcher {
|
||||
private _pollingIntervalMs: number;
|
||||
private _intervalIdIfExists?: NodeJS.Timer;
|
||||
private _lastEvents: Web3.LogEntry[] = [];
|
||||
constructor(web3Wrapper: Web3Wrapper, pollingIntervalMs: undefined|number) {
|
||||
constructor(web3Wrapper: Web3Wrapper, pollingIntervalIfExistsMs: undefined|number) {
|
||||
this._web3Wrapper = web3Wrapper;
|
||||
this._pollingIntervalMs = _.isUndefined(pollingIntervalMs) ?
|
||||
DEFAULT_EVENT_POLLING_INTERVAL :
|
||||
pollingIntervalMs;
|
||||
this._pollingIntervalMs = _.isUndefined(pollingIntervalIfExistsMs) ?
|
||||
DEFAULT_EVENT_POLLING_INTERVAL_MS :
|
||||
pollingIntervalIfExistsMs;
|
||||
}
|
||||
public subscribe(callback: EventWatcherCallback): void {
|
||||
assert.isFunction('callback', callback);
|
||||
|
76
packages/0x.js/src/order_watcher/expiration_watcher.ts
Normal file
76
packages/0x.js/src/order_watcher/expiration_watcher.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import {intervalUtils} from '@0xproject/utils';
|
||||
import {BigNumber} from 'bignumber.js';
|
||||
import {RBTree} from 'bintrees';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {ZeroExError} from '../types';
|
||||
import {utils} from '../utils/utils';
|
||||
|
||||
const DEFAULT_EXPIRATION_MARGIN_MS = 0;
|
||||
const DEFAULT_ORDER_EXPIRATION_CHECKING_INTERVAL_MS = 50;
|
||||
|
||||
/**
|
||||
* This class includes the functionality to detect expired orders.
|
||||
* It stores them in a min heap by expiration time and checks for expired ones every `orderExpirationCheckingIntervalMs`
|
||||
*/
|
||||
export class ExpirationWatcher {
|
||||
private _orderHashByExpirationRBTree: RBTree<string>;
|
||||
private _expiration: {[orderHash: string]: BigNumber} = {};
|
||||
private _orderExpirationCheckingIntervalMs: number;
|
||||
private _expirationMarginMs: number;
|
||||
private _orderExpirationCheckingIntervalIdIfExists?: NodeJS.Timer;
|
||||
constructor(expirationMarginIfExistsMs?: number,
|
||||
orderExpirationCheckingIntervalIfExistsMs?: number) {
|
||||
this._expirationMarginMs = expirationMarginIfExistsMs ||
|
||||
DEFAULT_EXPIRATION_MARGIN_MS;
|
||||
this._orderExpirationCheckingIntervalMs = expirationMarginIfExistsMs ||
|
||||
DEFAULT_ORDER_EXPIRATION_CHECKING_INTERVAL_MS;
|
||||
const scoreFunction = (orderHash: string) => this._expiration[orderHash].toNumber();
|
||||
const comparator = (lhs: string, rhs: string) => scoreFunction(lhs) - scoreFunction(rhs);
|
||||
this._orderHashByExpirationRBTree = new RBTree(comparator);
|
||||
}
|
||||
public subscribe(callback: (orderHash: string) => void): void {
|
||||
if (!_.isUndefined(this._orderExpirationCheckingIntervalIdIfExists)) {
|
||||
throw new Error(ZeroExError.SubscriptionAlreadyPresent);
|
||||
}
|
||||
this._orderExpirationCheckingIntervalIdIfExists = intervalUtils.setAsyncExcludingInterval(
|
||||
this._pruneExpiredOrders.bind(this, callback), this._orderExpirationCheckingIntervalMs,
|
||||
);
|
||||
}
|
||||
public unsubscribe(): void {
|
||||
if (_.isUndefined(this._orderExpirationCheckingIntervalIdIfExists)) {
|
||||
throw new Error(ZeroExError.SubscriptionNotFound);
|
||||
}
|
||||
intervalUtils.clearAsyncExcludingInterval(this._orderExpirationCheckingIntervalIdIfExists);
|
||||
delete this._orderExpirationCheckingIntervalIdIfExists;
|
||||
}
|
||||
public addOrder(orderHash: string, expirationUnixTimestampMs: BigNumber): void {
|
||||
this._expiration[orderHash] = expirationUnixTimestampMs;
|
||||
this._orderHashByExpirationRBTree.insert(orderHash);
|
||||
}
|
||||
public removeOrder(orderHash: string): void {
|
||||
this._orderHashByExpirationRBTree.remove(orderHash);
|
||||
delete this._expiration[orderHash];
|
||||
}
|
||||
private _pruneExpiredOrders(callback: (orderHash: string) => void): void {
|
||||
const currentUnixTimestampMs = utils.getCurrentUnixTimestampMs();
|
||||
while (true) {
|
||||
const hasTrakedOrders = this._orderHashByExpirationRBTree.size === 0;
|
||||
if (hasTrakedOrders) {
|
||||
break;
|
||||
}
|
||||
const nextOrderHashToExpire = this._orderHashByExpirationRBTree.min();
|
||||
const hasNoExpiredOrders = this._expiration[nextOrderHashToExpire].greaterThan(
|
||||
currentUnixTimestampMs.plus(this._expirationMarginMs),
|
||||
);
|
||||
const isSubscriptionActive = _.isUndefined(this._orderExpirationCheckingIntervalIdIfExists);
|
||||
if (hasNoExpiredOrders || isSubscriptionActive) {
|
||||
break;
|
||||
}
|
||||
const orderHash = this._orderHashByExpirationRBTree.min();
|
||||
this._orderHashByExpirationRBTree.remove(orderHash);
|
||||
delete this._expiration[orderHash];
|
||||
callback(orderHash);
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,41 +1,45 @@
|
||||
import * as _ from 'lodash';
|
||||
import {schemas} from '@0xproject/json-schemas';
|
||||
import {intervalUtils} from '@0xproject/utils';
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {ZeroEx} from '../0x';
|
||||
import {EventWatcher} from './event_watcher';
|
||||
import {assert} from '../utils/assert';
|
||||
import {utils} from '../utils/utils';
|
||||
import {artifacts} from '../artifacts';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
import {OrderStateUtils} from '../utils/order_state_utils';
|
||||
import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper';
|
||||
import {TokenWrapper} from '../contract_wrappers/token_wrapper';
|
||||
import {BalanceAndProxyAllowanceLazyStore} from '../stores/balance_proxy_allowance_lazy_store';
|
||||
import {OrderFilledCancelledLazyStore} from '../stores/order_filled_cancelled_lazy_store';
|
||||
import {
|
||||
LogEvent,
|
||||
OrderState,
|
||||
SignedOrder,
|
||||
Web3Provider,
|
||||
BlockParamLiteral,
|
||||
LogWithDecodedArgs,
|
||||
ContractEventArgs,
|
||||
OnOrderStateChangeCallback,
|
||||
OrderStateWatcherConfig,
|
||||
ApprovalContractEventArgs,
|
||||
TransferContractEventArgs,
|
||||
LogFillContractEventArgs,
|
||||
LogCancelContractEventArgs,
|
||||
BlockParamLiteral,
|
||||
ContractEventArgs,
|
||||
DepositContractEventArgs,
|
||||
EtherTokenEvents,
|
||||
ExchangeContractErrs,
|
||||
ExchangeEvents,
|
||||
LogCancelContractEventArgs,
|
||||
LogEvent,
|
||||
LogFillContractEventArgs,
|
||||
LogWithDecodedArgs,
|
||||
OnOrderStateChangeCallback,
|
||||
OrderState,
|
||||
OrderStateWatcherConfig,
|
||||
SignedOrder,
|
||||
TokenEvents,
|
||||
TransferContractEventArgs,
|
||||
WithdrawalContractEventArgs,
|
||||
ZeroExError,
|
||||
} from '../types';
|
||||
import {Web3Wrapper} from '../web3_wrapper';
|
||||
import {TokenWrapper} from '../contract_wrappers/token_wrapper';
|
||||
import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper';
|
||||
import {OrderFilledCancelledLazyStore} from '../stores/order_filled_cancelled_lazy_store';
|
||||
import {BalanceAndProxyAllowanceLazyStore} from '../stores/balance_proxy_allowance_lazy_store';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
import {assert} from '../utils/assert';
|
||||
import {OrderStateUtils} from '../utils/order_state_utils';
|
||||
import {utils} from '../utils/utils';
|
||||
|
||||
const DEFAULT_NUM_CONFIRMATIONS = 0;
|
||||
import {EventWatcher} from './event_watcher';
|
||||
import {ExpirationWatcher} from './expiration_watcher';
|
||||
|
||||
interface DependentOrderHashes {
|
||||
[makerAddress: string]: {
|
||||
[makerToken: string]: Set<string>,
|
||||
[makerToken: string]: Set<string>;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -43,6 +47,12 @@ interface OrderByOrderHash {
|
||||
[orderHash: string]: SignedOrder;
|
||||
}
|
||||
|
||||
interface OrderStateByOrderHash {
|
||||
[orderHash: string]: OrderState;
|
||||
}
|
||||
|
||||
const DEFAULT_CLEANUP_JOB_INTERVAL_MS = 1000 * 60 * 60; // 1h
|
||||
|
||||
/**
|
||||
* This class includes all the functionality related to watching a set of orders
|
||||
* for potential changes in order validity/fillability. The orderWatcher notifies
|
||||
@@ -50,56 +60,78 @@ interface OrderByOrderHash {
|
||||
* the order should be deemed invalid.
|
||||
*/
|
||||
export class OrderStateWatcher {
|
||||
private _orderStateByOrderHashCache: OrderStateByOrderHash = {};
|
||||
private _orderByOrderHash: OrderByOrderHash = {};
|
||||
private _dependentOrderHashes: DependentOrderHashes = {};
|
||||
private _callbackIfExists?: OnOrderStateChangeCallback;
|
||||
private _eventWatcher: EventWatcher;
|
||||
private _web3Wrapper: Web3Wrapper;
|
||||
private _abiDecoder: AbiDecoder;
|
||||
private _expirationWatcher: ExpirationWatcher;
|
||||
private _orderStateUtils: OrderStateUtils;
|
||||
private _orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore;
|
||||
private _balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore;
|
||||
private _cleanupJobInterval: number;
|
||||
private _cleanupJobIntervalIdIfExists?: NodeJS.Timer;
|
||||
constructor(
|
||||
web3Wrapper: Web3Wrapper, abiDecoder: AbiDecoder, token: TokenWrapper, exchange: ExchangeWrapper,
|
||||
config?: OrderStateWatcherConfig,
|
||||
) {
|
||||
this._abiDecoder = abiDecoder;
|
||||
this._web3Wrapper = web3Wrapper;
|
||||
const eventPollingIntervalMs = _.isUndefined(config) ? undefined : config.eventPollingIntervalMs;
|
||||
this._eventWatcher = new EventWatcher(web3Wrapper, eventPollingIntervalMs);
|
||||
this._balanceAndProxyAllowanceLazyStore = new BalanceAndProxyAllowanceLazyStore(token);
|
||||
const pollingIntervalIfExistsMs = _.isUndefined(config) ? undefined : config.eventPollingIntervalMs;
|
||||
this._eventWatcher = new EventWatcher(web3Wrapper, pollingIntervalIfExistsMs);
|
||||
this._balanceAndProxyAllowanceLazyStore = new BalanceAndProxyAllowanceLazyStore(
|
||||
token, BlockParamLiteral.Pending,
|
||||
);
|
||||
this._orderFilledCancelledLazyStore = new OrderFilledCancelledLazyStore(exchange);
|
||||
this._orderStateUtils = new OrderStateUtils(
|
||||
this._balanceAndProxyAllowanceLazyStore, this._orderFilledCancelledLazyStore,
|
||||
);
|
||||
const orderExpirationCheckingIntervalMsIfExists = _.isUndefined(config) ?
|
||||
undefined :
|
||||
config.orderExpirationCheckingIntervalMs;
|
||||
const expirationMarginIfExistsMs = _.isUndefined(config) ?
|
||||
undefined :
|
||||
config.expirationMarginMs;
|
||||
this._expirationWatcher = new ExpirationWatcher(
|
||||
expirationMarginIfExistsMs, orderExpirationCheckingIntervalMsIfExists,
|
||||
);
|
||||
this._cleanupJobInterval = _.isUndefined(config) || _.isUndefined(config.cleanupJobIntervalMs) ?
|
||||
DEFAULT_CLEANUP_JOB_INTERVAL_MS :
|
||||
config.cleanupJobIntervalMs;
|
||||
}
|
||||
/**
|
||||
* Add an order to the orderStateWatcher. Before the order is added, it's
|
||||
* signature is verified.
|
||||
* @param signedOrder The order you wish to start watching.
|
||||
*/
|
||||
public async addOrderAsync(signedOrder: SignedOrder): Promise<void> {
|
||||
public addOrder(signedOrder: SignedOrder): void {
|
||||
assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
assert.isValidSignature(orderHash, signedOrder.ecSignature, signedOrder.maker);
|
||||
this._orderByOrderHash[orderHash] = signedOrder;
|
||||
await this.addToDependentOrderHashesAsync(signedOrder, orderHash);
|
||||
this._addToDependentOrderHashes(signedOrder, orderHash);
|
||||
const expirationUnixTimestampMs = signedOrder.expirationUnixTimestampSec.times(1000);
|
||||
this._expirationWatcher.addOrder(orderHash, expirationUnixTimestampMs);
|
||||
}
|
||||
/**
|
||||
* Removes an order from the orderStateWatcher
|
||||
* @param orderHash The orderHash of the order you wish to stop watching.
|
||||
*/
|
||||
public async removeOrderAsync(orderHash: string): Promise<void> {
|
||||
public removeOrder(orderHash: string): void {
|
||||
assert.doesConformToSchema('orderHash', orderHash, schemas.orderHashSchema);
|
||||
const signedOrder = this._orderByOrderHash[orderHash];
|
||||
if (_.isUndefined(signedOrder)) {
|
||||
return; // noop
|
||||
}
|
||||
delete this._orderByOrderHash[orderHash];
|
||||
const exchange = (this._orderFilledCancelledLazyStore as any).exchange as ExchangeWrapper;
|
||||
const zrxTokenAddress = await exchange.getZRXTokenAddressAsync();
|
||||
this.removeFromDependentOrderHashes(signedOrder.maker, zrxTokenAddress, orderHash);
|
||||
this.removeFromDependentOrderHashes(signedOrder.maker, signedOrder.makerTokenAddress, orderHash);
|
||||
delete this._orderStateByOrderHashCache[orderHash];
|
||||
const exchange = (this._orderFilledCancelledLazyStore as any)._exchange as ExchangeWrapper;
|
||||
const zrxTokenAddress = exchange.getZRXTokenAddress();
|
||||
this._removeFromDependentOrderHashes(signedOrder.maker, zrxTokenAddress, orderHash);
|
||||
this._removeFromDependentOrderHashes(signedOrder.maker, signedOrder.makerTokenAddress, orderHash);
|
||||
this._expirationWatcher.removeOrder(orderHash);
|
||||
}
|
||||
/**
|
||||
* Starts an orderStateWatcher subscription. The callback will be called every time a watched order's
|
||||
@@ -114,18 +146,64 @@ export class OrderStateWatcher {
|
||||
}
|
||||
this._callbackIfExists = callback;
|
||||
this._eventWatcher.subscribe(this._onEventWatcherCallbackAsync.bind(this));
|
||||
this._expirationWatcher.subscribe(this._onOrderExpired.bind(this));
|
||||
this._cleanupJobIntervalIdIfExists = intervalUtils.setAsyncExcludingInterval(
|
||||
this._cleanupAsync.bind(this), this._cleanupJobInterval,
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Ends an orderStateWatcher subscription.
|
||||
*/
|
||||
public unsubscribe(): void {
|
||||
if (_.isUndefined(this._callbackIfExists)) {
|
||||
if (_.isUndefined(this._callbackIfExists) || _.isUndefined(this._cleanupJobIntervalIdIfExists)) {
|
||||
throw new Error(ZeroExError.SubscriptionNotFound);
|
||||
}
|
||||
this._balanceAndProxyAllowanceLazyStore.deleteAll();
|
||||
this._orderFilledCancelledLazyStore.deleteAll();
|
||||
delete this._callbackIfExists;
|
||||
this._eventWatcher.unsubscribe();
|
||||
this._expirationWatcher.unsubscribe();
|
||||
intervalUtils.clearAsyncExcludingInterval(this._cleanupJobIntervalIdIfExists);
|
||||
}
|
||||
private async _cleanupAsync(): Promise<void> {
|
||||
for (const orderHash of _.keys(this._orderByOrderHash)) {
|
||||
this._cleanupOrderRelatedState(orderHash);
|
||||
await this._emitRevalidateOrdersAsync([orderHash]);
|
||||
}
|
||||
}
|
||||
private _cleanupOrderRelatedState(orderHash: string): void {
|
||||
const signedOrder = this._orderByOrderHash[orderHash];
|
||||
|
||||
this._orderFilledCancelledLazyStore.deleteFilledTakerAmount(orderHash);
|
||||
this._orderFilledCancelledLazyStore.deleteCancelledTakerAmount(orderHash);
|
||||
|
||||
this._balanceAndProxyAllowanceLazyStore.deleteBalance(signedOrder.makerTokenAddress, signedOrder.maker);
|
||||
this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(signedOrder.makerTokenAddress, signedOrder.maker);
|
||||
this._balanceAndProxyAllowanceLazyStore.deleteBalance(signedOrder.takerTokenAddress, signedOrder.taker);
|
||||
this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(signedOrder.takerTokenAddress, signedOrder.taker);
|
||||
|
||||
const zrxTokenAddress = this._getZRXTokenAddress();
|
||||
if (!signedOrder.makerFee.isZero()) {
|
||||
this._balanceAndProxyAllowanceLazyStore.deleteBalance(zrxTokenAddress, signedOrder.maker);
|
||||
this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(zrxTokenAddress, signedOrder.maker);
|
||||
}
|
||||
if (!signedOrder.takerFee.isZero()) {
|
||||
this._balanceAndProxyAllowanceLazyStore.deleteBalance(zrxTokenAddress, signedOrder.taker);
|
||||
this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(zrxTokenAddress, signedOrder.taker);
|
||||
}
|
||||
}
|
||||
private _onOrderExpired(orderHash: string): void {
|
||||
const orderState: OrderState = {
|
||||
isValid: false,
|
||||
orderHash,
|
||||
error: ExchangeContractErrs.OrderFillExpired,
|
||||
};
|
||||
if (!_.isUndefined(this._orderByOrderHash[orderHash])) {
|
||||
this.removeOrder(orderHash);
|
||||
if (!_.isUndefined(this._callbackIfExists)) {
|
||||
this._callbackIfExists(orderState);
|
||||
}
|
||||
}
|
||||
}
|
||||
private async _onEventWatcherCallbackAsync(log: LogEvent): Promise<void> {
|
||||
const maybeDecodedLog = this._abiDecoder.tryToDecodeLogOrNoop(log);
|
||||
@@ -168,6 +246,36 @@ export class OrderStateWatcher {
|
||||
}
|
||||
break;
|
||||
}
|
||||
case EtherTokenEvents.Deposit:
|
||||
{
|
||||
// Invalidate cache
|
||||
const args = decodedLog.args as DepositContractEventArgs;
|
||||
this._balanceAndProxyAllowanceLazyStore.deleteBalance(decodedLog.address, args._owner);
|
||||
// Revalidate orders
|
||||
makerToken = decodedLog.address;
|
||||
makerAddress = args._owner;
|
||||
if (!_.isUndefined(this._dependentOrderHashes[makerAddress]) &&
|
||||
!_.isUndefined(this._dependentOrderHashes[makerAddress][makerToken])) {
|
||||
const orderHashes = Array.from(this._dependentOrderHashes[makerAddress][makerToken]);
|
||||
await this._emitRevalidateOrdersAsync(orderHashes);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case EtherTokenEvents.Withdrawal:
|
||||
{
|
||||
// Invalidate cache
|
||||
const args = decodedLog.args as WithdrawalContractEventArgs;
|
||||
this._balanceAndProxyAllowanceLazyStore.deleteBalance(decodedLog.address, args._owner);
|
||||
// Revalidate orders
|
||||
makerToken = decodedLog.address;
|
||||
makerAddress = args._owner;
|
||||
if (!_.isUndefined(this._dependentOrderHashes[makerAddress]) &&
|
||||
!_.isUndefined(this._dependentOrderHashes[makerAddress][makerToken])) {
|
||||
const orderHashes = Array.from(this._dependentOrderHashes[makerAddress][makerToken]);
|
||||
await this._emitRevalidateOrdersAsync(orderHashes);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ExchangeEvents.LogFill:
|
||||
{
|
||||
// Invalidate cache
|
||||
@@ -203,17 +311,23 @@ export class OrderStateWatcher {
|
||||
}
|
||||
private async _emitRevalidateOrdersAsync(orderHashes: string[]): Promise<void> {
|
||||
for (const orderHash of orderHashes) {
|
||||
const signedOrder = this._orderByOrderHash[orderHash] as SignedOrder;
|
||||
const signedOrder = this._orderByOrderHash[orderHash];
|
||||
// Most of these calls will never reach the network because the data is fetched from stores
|
||||
// and only updated when cache is invalidated
|
||||
const orderState = await this._orderStateUtils.getOrderStateAsync(signedOrder);
|
||||
if (_.isUndefined(this._callbackIfExists)) {
|
||||
break; // Unsubscribe was called
|
||||
}
|
||||
if (_.isEqual(orderState, this._orderStateByOrderHashCache[orderHash])) {
|
||||
// Actual order state didn't change
|
||||
continue;
|
||||
} else {
|
||||
this._orderStateByOrderHashCache[orderHash] = orderState;
|
||||
}
|
||||
this._callbackIfExists(orderState);
|
||||
}
|
||||
}
|
||||
private async addToDependentOrderHashesAsync(signedOrder: SignedOrder, orderHash: string): Promise<void> {
|
||||
private _addToDependentOrderHashes(signedOrder: SignedOrder, orderHash: string): void {
|
||||
if (_.isUndefined(this._dependentOrderHashes[signedOrder.maker])) {
|
||||
this._dependentOrderHashes[signedOrder.maker] = {};
|
||||
}
|
||||
@@ -221,14 +335,13 @@ export class OrderStateWatcher {
|
||||
this._dependentOrderHashes[signedOrder.maker][signedOrder.makerTokenAddress] = new Set();
|
||||
}
|
||||
this._dependentOrderHashes[signedOrder.maker][signedOrder.makerTokenAddress].add(orderHash);
|
||||
const exchange = (this._orderFilledCancelledLazyStore as any).exchange as ExchangeWrapper;
|
||||
const zrxTokenAddress = await exchange.getZRXTokenAddressAsync();
|
||||
const zrxTokenAddress = this._getZRXTokenAddress();
|
||||
if (_.isUndefined(this._dependentOrderHashes[signedOrder.maker][zrxTokenAddress])) {
|
||||
this._dependentOrderHashes[signedOrder.maker][zrxTokenAddress] = new Set();
|
||||
}
|
||||
this._dependentOrderHashes[signedOrder.maker][zrxTokenAddress].add(orderHash);
|
||||
}
|
||||
private removeFromDependentOrderHashes(makerAddress: string, tokenAddress: string, orderHash: string) {
|
||||
private _removeFromDependentOrderHashes(makerAddress: string, tokenAddress: string, orderHash: string) {
|
||||
this._dependentOrderHashes[makerAddress][tokenAddress].delete(orderHash);
|
||||
if (this._dependentOrderHashes[makerAddress][tokenAddress].size === 0) {
|
||||
delete this._dependentOrderHashes[makerAddress][tokenAddress];
|
||||
@@ -237,4 +350,9 @@ export class OrderStateWatcher {
|
||||
delete this._dependentOrderHashes[makerAddress];
|
||||
}
|
||||
}
|
||||
private _getZRXTokenAddress(): string {
|
||||
const exchange = (this._orderFilledCancelledLazyStore as any)._exchange as ExchangeWrapper;
|
||||
const zrxTokenAddress = exchange.getZRXTokenAddress();
|
||||
return zrxTokenAddress;
|
||||
}
|
||||
}
|
||||
|
@@ -0,0 +1,87 @@
|
||||
import {BigNumber} from 'bignumber.js';
|
||||
|
||||
import {SignedOrder} from '../types';
|
||||
|
||||
export class RemainingFillableCalculator {
|
||||
private _signedOrder: SignedOrder;
|
||||
private _isMakerTokenZRX: boolean;
|
||||
// Transferrable Amount is the minimum of Approval and Balance
|
||||
private _transferrableMakerTokenAmount: BigNumber;
|
||||
private _transferrableMakerFeeTokenAmount: BigNumber;
|
||||
private _remainingMakerTokenAmount: BigNumber;
|
||||
private _remainingMakerFeeAmount: BigNumber;
|
||||
constructor(signedOrder: SignedOrder,
|
||||
isMakerTokenZRX: boolean,
|
||||
transferrableMakerTokenAmount: BigNumber,
|
||||
transferrableMakerFeeTokenAmount: BigNumber,
|
||||
remainingMakerTokenAmount: BigNumber) {
|
||||
this._signedOrder = signedOrder;
|
||||
this._isMakerTokenZRX = isMakerTokenZRX;
|
||||
this._transferrableMakerTokenAmount = transferrableMakerTokenAmount;
|
||||
this._transferrableMakerFeeTokenAmount = transferrableMakerFeeTokenAmount;
|
||||
this._remainingMakerTokenAmount = remainingMakerTokenAmount;
|
||||
this._remainingMakerFeeAmount = remainingMakerTokenAmount.times(signedOrder.makerFee)
|
||||
.dividedToIntegerBy(signedOrder.makerTokenAmount);
|
||||
}
|
||||
public computeRemainingMakerFillable(): BigNumber {
|
||||
if (this._hasSufficientFundsForFeeAndTransferAmount()) {
|
||||
return this._remainingMakerTokenAmount;
|
||||
}
|
||||
if (this._signedOrder.makerFee.isZero()) {
|
||||
return BigNumber.min(this._remainingMakerTokenAmount, this._transferrableMakerTokenAmount);
|
||||
}
|
||||
return this._calculatePartiallyFillableMakerTokenAmount();
|
||||
}
|
||||
public computeRemainingTakerFillable(): BigNumber {
|
||||
return this.computeRemainingMakerFillable().times(this._signedOrder.takerTokenAmount)
|
||||
.dividedToIntegerBy(this._signedOrder.makerTokenAmount);
|
||||
}
|
||||
private _hasSufficientFundsForFeeAndTransferAmount(): boolean {
|
||||
if (this._isMakerTokenZRX) {
|
||||
const totalZRXTransferAmountRequired = this._remainingMakerTokenAmount.plus(this._remainingMakerFeeAmount);
|
||||
const hasSufficientFunds = this._transferrableMakerTokenAmount.greaterThanOrEqualTo(
|
||||
totalZRXTransferAmountRequired);
|
||||
return hasSufficientFunds;
|
||||
} else {
|
||||
const hasSufficientFundsForTransferAmount = this._transferrableMakerTokenAmount.greaterThanOrEqualTo(
|
||||
this._remainingMakerTokenAmount);
|
||||
const hasSufficientFundsForFeeAmount = this._transferrableMakerFeeTokenAmount.greaterThanOrEqualTo(
|
||||
this._remainingMakerFeeAmount);
|
||||
const hasSufficientFunds = hasSufficientFundsForTransferAmount && hasSufficientFundsForFeeAmount;
|
||||
return hasSufficientFunds;
|
||||
}
|
||||
}
|
||||
private _calculatePartiallyFillableMakerTokenAmount(): BigNumber {
|
||||
// Given an order for 200 wei for 2 ZRXwei fee, find 100 wei for 1 ZRXwei. Order ratio is then 100:1
|
||||
const orderToFeeRatio = this._signedOrder.makerTokenAmount.dividedBy(this._signedOrder.makerFee);
|
||||
// The number of times the maker can fill the order, if each fill only required the transfer of a single
|
||||
// baseUnit of fee tokens.
|
||||
// Given 2 ZRXwei, the maximum amount of times Maker can fill this order, in terms of fees, is 2
|
||||
const fillableTimesInFeeTokenBaseUnits = BigNumber.min(this._transferrableMakerFeeTokenAmount,
|
||||
this._remainingMakerFeeAmount);
|
||||
// The number of times the Maker can fill the order, given the Maker Token Balance
|
||||
// Assuming a balance of 150 wei, and an orderToFeeRatio of 100:1, maker can fill this order 1 time.
|
||||
let fillableTimesInMakerTokenUnits = this._transferrableMakerTokenAmount.dividedBy(orderToFeeRatio);
|
||||
if (this._isMakerTokenZRX) {
|
||||
// If ZRX is the maker token, the Fee and the Maker amount need to be removed from the same pool;
|
||||
// 200 ZRXwei for 2ZRXwei fee can only be filled once (need 202 ZRXwei)
|
||||
const totalZRXTokenPooled = this._transferrableMakerTokenAmount;
|
||||
// The purchasing power here is less as the tokens are taken from the same Pool
|
||||
// For every one number of fills, we have to take an extra ZRX out of the pool
|
||||
fillableTimesInMakerTokenUnits = totalZRXTokenPooled.dividedBy(
|
||||
orderToFeeRatio.plus(new BigNumber(1)));
|
||||
|
||||
}
|
||||
// When Ratio is not fully divisible there can be remainders which cannot be represented, so they are floored.
|
||||
// This can result in a RoundingError being thrown by the Exchange Contract.
|
||||
const partiallyFillableMakerTokenAmount = fillableTimesInMakerTokenUnits
|
||||
.times(this._signedOrder.makerTokenAmount)
|
||||
.dividedToIntegerBy(this._signedOrder.makerFee);
|
||||
const partiallyFillableFeeTokenAmount = fillableTimesInFeeTokenBaseUnits
|
||||
.times(this._signedOrder.makerTokenAmount)
|
||||
.dividedToIntegerBy(this._signedOrder.makerFee);
|
||||
const partiallyFillableAmount = BigNumber.min(partiallyFillableMakerTokenAmount,
|
||||
partiallyFillableFeeTokenAmount);
|
||||
return partiallyFillableAmount;
|
||||
}
|
||||
}
|
@@ -1,10 +1,13 @@
|
||||
export const zeroExConfigSchema = {
|
||||
id: '/ZeroExConfig',
|
||||
properties: {
|
||||
networkId: {
|
||||
type: 'number',
|
||||
minimum: 0,
|
||||
},
|
||||
gasPrice: {$ref: '/Number'},
|
||||
exchangeContractAddress: {$ref: '/Address'},
|
||||
tokenRegistryContractAddress: {$ref: '/Address'},
|
||||
etherTokenContractAddress: {$ref: '/Address'},
|
||||
orderWatcherConfig: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
@@ -20,4 +23,5 @@ export const zeroExConfigSchema = {
|
||||
},
|
||||
},
|
||||
type: 'object',
|
||||
required: ['networkId'],
|
||||
};
|
||||
|
@@ -1,6 +1,6 @@
|
||||
import * as _ from 'lodash';
|
||||
import * as Web3 from 'web3';
|
||||
import {BigNumber} from 'bignumber.js';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {TokenWrapper} from '../contract_wrappers/token_wrapper';
|
||||
import {BlockParamLiteral} from '../types';
|
||||
|
||||
@@ -8,75 +8,77 @@ import {BlockParamLiteral} from '../types';
|
||||
* Copy on read store for balances/proxyAllowances of tokens/accounts
|
||||
*/
|
||||
export class BalanceAndProxyAllowanceLazyStore {
|
||||
private token: TokenWrapper;
|
||||
private balance: {
|
||||
private _token: TokenWrapper;
|
||||
private _defaultBlock: BlockParamLiteral;
|
||||
private _balance: {
|
||||
[tokenAddress: string]: {
|
||||
[userAddress: string]: BigNumber,
|
||||
},
|
||||
[userAddress: string]: BigNumber;
|
||||
};
|
||||
};
|
||||
private proxyAllowance: {
|
||||
private _proxyAllowance: {
|
||||
[tokenAddress: string]: {
|
||||
[userAddress: string]: BigNumber,
|
||||
},
|
||||
[userAddress: string]: BigNumber;
|
||||
};
|
||||
};
|
||||
constructor(token: TokenWrapper) {
|
||||
this.token = token;
|
||||
this.balance = {};
|
||||
this.proxyAllowance = {};
|
||||
constructor(token: TokenWrapper, defaultBlock: BlockParamLiteral) {
|
||||
this._token = token;
|
||||
this._defaultBlock = defaultBlock;
|
||||
this._balance = {};
|
||||
this._proxyAllowance = {};
|
||||
}
|
||||
public async getBalanceAsync(tokenAddress: string, userAddress: string): Promise<BigNumber> {
|
||||
if (_.isUndefined(this.balance[tokenAddress]) || _.isUndefined(this.balance[tokenAddress][userAddress])) {
|
||||
if (_.isUndefined(this._balance[tokenAddress]) || _.isUndefined(this._balance[tokenAddress][userAddress])) {
|
||||
const methodOpts = {
|
||||
defaultBlock: BlockParamLiteral.Pending,
|
||||
defaultBlock: this._defaultBlock,
|
||||
};
|
||||
const balance = await this.token.getBalanceAsync(tokenAddress, userAddress, methodOpts);
|
||||
const balance = await this._token.getBalanceAsync(tokenAddress, userAddress, methodOpts);
|
||||
this.setBalance(tokenAddress, userAddress, balance);
|
||||
}
|
||||
const cachedBalance = this.balance[tokenAddress][userAddress];
|
||||
const cachedBalance = this._balance[tokenAddress][userAddress];
|
||||
return cachedBalance;
|
||||
}
|
||||
public setBalance(tokenAddress: string, userAddress: string, balance: BigNumber): void {
|
||||
if (_.isUndefined(this.balance[tokenAddress])) {
|
||||
this.balance[tokenAddress] = {};
|
||||
if (_.isUndefined(this._balance[tokenAddress])) {
|
||||
this._balance[tokenAddress] = {};
|
||||
}
|
||||
this.balance[tokenAddress][userAddress] = balance;
|
||||
this._balance[tokenAddress][userAddress] = balance;
|
||||
}
|
||||
public deleteBalance(tokenAddress: string, userAddress: string): void {
|
||||
if (!_.isUndefined(this.balance[tokenAddress])) {
|
||||
delete this.balance[tokenAddress][userAddress];
|
||||
if (_.isEmpty(this.balance[tokenAddress])) {
|
||||
delete this.balance[tokenAddress];
|
||||
if (!_.isUndefined(this._balance[tokenAddress])) {
|
||||
delete this._balance[tokenAddress][userAddress];
|
||||
if (_.isEmpty(this._balance[tokenAddress])) {
|
||||
delete this._balance[tokenAddress];
|
||||
}
|
||||
}
|
||||
}
|
||||
public async getProxyAllowanceAsync(tokenAddress: string, userAddress: string): Promise<BigNumber> {
|
||||
if (_.isUndefined(this.proxyAllowance[tokenAddress]) ||
|
||||
_.isUndefined(this.proxyAllowance[tokenAddress][userAddress])) {
|
||||
if (_.isUndefined(this._proxyAllowance[tokenAddress]) ||
|
||||
_.isUndefined(this._proxyAllowance[tokenAddress][userAddress])) {
|
||||
const methodOpts = {
|
||||
defaultBlock: BlockParamLiteral.Pending,
|
||||
defaultBlock: this._defaultBlock,
|
||||
};
|
||||
const proxyAllowance = await this.token.getProxyAllowanceAsync(tokenAddress, userAddress, methodOpts);
|
||||
const proxyAllowance = await this._token.getProxyAllowanceAsync(tokenAddress, userAddress, methodOpts);
|
||||
this.setProxyAllowance(tokenAddress, userAddress, proxyAllowance);
|
||||
}
|
||||
const cachedProxyAllowance = this.proxyAllowance[tokenAddress][userAddress];
|
||||
const cachedProxyAllowance = this._proxyAllowance[tokenAddress][userAddress];
|
||||
return cachedProxyAllowance;
|
||||
}
|
||||
public setProxyAllowance(tokenAddress: string, userAddress: string, proxyAllowance: BigNumber): void {
|
||||
if (_.isUndefined(this.proxyAllowance[tokenAddress])) {
|
||||
this.proxyAllowance[tokenAddress] = {};
|
||||
if (_.isUndefined(this._proxyAllowance[tokenAddress])) {
|
||||
this._proxyAllowance[tokenAddress] = {};
|
||||
}
|
||||
this.proxyAllowance[tokenAddress][userAddress] = proxyAllowance;
|
||||
this._proxyAllowance[tokenAddress][userAddress] = proxyAllowance;
|
||||
}
|
||||
public deleteProxyAllowance(tokenAddress: string, userAddress: string): void {
|
||||
if (!_.isUndefined(this.proxyAllowance[tokenAddress])) {
|
||||
delete this.proxyAllowance[tokenAddress][userAddress];
|
||||
if (_.isEmpty(this.proxyAllowance[tokenAddress])) {
|
||||
delete this.proxyAllowance[tokenAddress];
|
||||
if (!_.isUndefined(this._proxyAllowance[tokenAddress])) {
|
||||
delete this._proxyAllowance[tokenAddress][userAddress];
|
||||
if (_.isEmpty(this._proxyAllowance[tokenAddress])) {
|
||||
delete this._proxyAllowance[tokenAddress];
|
||||
}
|
||||
}
|
||||
}
|
||||
public deleteAll(): void {
|
||||
this.balance = {};
|
||||
this.proxyAllowance = {};
|
||||
this._balance = {};
|
||||
this._proxyAllowance = {};
|
||||
}
|
||||
}
|
||||
|
@@ -1,6 +1,6 @@
|
||||
import * as _ from 'lodash';
|
||||
import * as Web3 from 'web3';
|
||||
import {BigNumber} from 'bignumber.js';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper';
|
||||
import {BlockParamLiteral} from '../types';
|
||||
|
||||
@@ -8,54 +8,54 @@ import {BlockParamLiteral} from '../types';
|
||||
* Copy on read store for filled/cancelled taker amounts
|
||||
*/
|
||||
export class OrderFilledCancelledLazyStore {
|
||||
private exchange: ExchangeWrapper;
|
||||
private filledTakerAmount: {
|
||||
[orderHash: string]: BigNumber,
|
||||
private _exchange: ExchangeWrapper;
|
||||
private _filledTakerAmount: {
|
||||
[orderHash: string]: BigNumber;
|
||||
};
|
||||
private cancelledTakerAmount: {
|
||||
[orderHash: string]: BigNumber,
|
||||
private _cancelledTakerAmount: {
|
||||
[orderHash: string]: BigNumber;
|
||||
};
|
||||
constructor(exchange: ExchangeWrapper) {
|
||||
this.exchange = exchange;
|
||||
this.filledTakerAmount = {};
|
||||
this.cancelledTakerAmount = {};
|
||||
this._exchange = exchange;
|
||||
this._filledTakerAmount = {};
|
||||
this._cancelledTakerAmount = {};
|
||||
}
|
||||
public async getFilledTakerAmountAsync(orderHash: string): Promise<BigNumber> {
|
||||
if (_.isUndefined(this.filledTakerAmount[orderHash])) {
|
||||
if (_.isUndefined(this._filledTakerAmount[orderHash])) {
|
||||
const methodOpts = {
|
||||
defaultBlock: BlockParamLiteral.Pending,
|
||||
};
|
||||
const filledTakerAmount = await this.exchange.getFilledTakerAmountAsync(orderHash, methodOpts);
|
||||
const filledTakerAmount = await this._exchange.getFilledTakerAmountAsync(orderHash, methodOpts);
|
||||
this.setFilledTakerAmount(orderHash, filledTakerAmount);
|
||||
}
|
||||
const cachedFilled = this.filledTakerAmount[orderHash];
|
||||
const cachedFilled = this._filledTakerAmount[orderHash];
|
||||
return cachedFilled;
|
||||
}
|
||||
public setFilledTakerAmount(orderHash: string, filledTakerAmount: BigNumber): void {
|
||||
this.filledTakerAmount[orderHash] = filledTakerAmount;
|
||||
this._filledTakerAmount[orderHash] = filledTakerAmount;
|
||||
}
|
||||
public deleteFilledTakerAmount(orderHash: string): void {
|
||||
delete this.filledTakerAmount[orderHash];
|
||||
delete this._filledTakerAmount[orderHash];
|
||||
}
|
||||
public async getCancelledTakerAmountAsync(orderHash: string): Promise<BigNumber> {
|
||||
if (_.isUndefined(this.cancelledTakerAmount[orderHash])) {
|
||||
if (_.isUndefined(this._cancelledTakerAmount[orderHash])) {
|
||||
const methodOpts = {
|
||||
defaultBlock: BlockParamLiteral.Pending,
|
||||
};
|
||||
const cancelledTakerAmount = await this.exchange.getCancelledTakerAmountAsync(orderHash, methodOpts);
|
||||
const cancelledTakerAmount = await this._exchange.getCancelledTakerAmountAsync(orderHash, methodOpts);
|
||||
this.setCancelledTakerAmount(orderHash, cancelledTakerAmount);
|
||||
}
|
||||
const cachedCancelled = this.cancelledTakerAmount[orderHash];
|
||||
const cachedCancelled = this._cancelledTakerAmount[orderHash];
|
||||
return cachedCancelled;
|
||||
}
|
||||
public setCancelledTakerAmount(orderHash: string, cancelledTakerAmount: BigNumber): void {
|
||||
this.cancelledTakerAmount[orderHash] = cancelledTakerAmount;
|
||||
this._cancelledTakerAmount[orderHash] = cancelledTakerAmount;
|
||||
}
|
||||
public deleteCancelledTakerAmount(orderHash: string): void {
|
||||
delete this.cancelledTakerAmount[orderHash];
|
||||
delete this._cancelledTakerAmount[orderHash];
|
||||
}
|
||||
public deleteAll(): void {
|
||||
this.filledTakerAmount = {};
|
||||
this.cancelledTakerAmount = {};
|
||||
this._filledTakerAmount = {};
|
||||
this._cancelledTakerAmount = {};
|
||||
}
|
||||
}
|
||||
|
@@ -1,9 +1,14 @@
|
||||
import * as Web3 from 'web3';
|
||||
import {TransactionReceipt} from '@0xproject/types';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
export enum ZeroExError {
|
||||
ContractDoesNotExist = 'CONTRACT_DOES_NOT_EXIST',
|
||||
ExchangeContractDoesNotExist = 'EXCHANGE_CONTRACT_DOES_NOT_EXIST',
|
||||
ZRXContractDoesNotExist = 'ZRX_CONTRACT_DOES_NOT_EXIST',
|
||||
EtherTokenContractDoesNotExist = 'ETHER_TOKEN_CONTRACT_DOES_NOT_EXIST',
|
||||
TokenTransferProxyContractDoesNotExist = 'TOKEN_TRANSFER_PROXY_CONTRACT_DOES_NOT_EXIST',
|
||||
TokenRegistryContractDoesNotExist = 'TOKEN_REGISTRY_CONTRACT_DOES_NOT_EXIST',
|
||||
TokenContractDoesNotExist = 'TOKEN_CONTRACT_DOES_NOT_EXIST',
|
||||
UnhandledError = 'UNHANDLED_ERROR',
|
||||
UserHasNoAssociatedAddress = 'USER_HAS_NO_ASSOCIATED_ADDRESSES',
|
||||
InvalidSignature = 'INVALID_SIGNATURE',
|
||||
@@ -23,6 +28,7 @@ export enum ZeroExError {
|
||||
export enum InternalZeroExError {
|
||||
NoAbiDecoder = 'NO_ABI_DECODER',
|
||||
ZrxNotInTokenRegistry = 'ZRX_NOT_IN_TOKEN_REGISTRY',
|
||||
WethNotInTokenRegistry = 'WETH_NOT_IN_TOKEN_REGISTRY',
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -40,161 +46,14 @@ export type OrderValues = [BigNumber, BigNumber, BigNumber,
|
||||
BigNumber, BigNumber, BigNumber];
|
||||
|
||||
export type LogEvent = Web3.LogEntryEvent;
|
||||
export type DecodedLogEvent<ArgsType> = Web3.DecodedLogEntryEvent<ArgsType>;
|
||||
export interface DecodedLogEvent<ArgsType> {
|
||||
isRemoved: boolean;
|
||||
log: LogWithDecodedArgs<ArgsType>;
|
||||
}
|
||||
|
||||
export type EventCallback<ArgsType> = (err: null|Error, log?: DecodedLogEvent<ArgsType>) => void;
|
||||
export type EventWatcherCallback = (log: LogEvent) => void;
|
||||
|
||||
export interface ExchangeContract extends Web3.ContractInstance {
|
||||
isValidSignature: {
|
||||
callAsync: (signerAddressHex: string, dataHex: string, v: number, r: string, s: string,
|
||||
txOpts?: TxOpts) => Promise<boolean>;
|
||||
};
|
||||
ZRX_TOKEN_CONTRACT: {
|
||||
callAsync: () => Promise<string>;
|
||||
};
|
||||
TOKEN_TRANSFER_PROXY_CONTRACT: {
|
||||
callAsync: () => Promise<string>;
|
||||
};
|
||||
getUnavailableTakerTokenAmount: {
|
||||
callAsync: (orderHash: string, defaultBlock?: Web3.BlockParam) => Promise<BigNumber>;
|
||||
};
|
||||
isRoundingError: {
|
||||
callAsync: (takerTokenFillAmount: BigNumber, takerTokenAmount: BigNumber,
|
||||
makerTokenAmount: BigNumber, txOpts?: TxOpts) => Promise<boolean>;
|
||||
};
|
||||
fillOrder: {
|
||||
sendTransactionAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues,
|
||||
fillTakerTokenAmount: BigNumber,
|
||||
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
|
||||
v: number, r: string, s: string, txOpts?: TxOpts) => Promise<string>;
|
||||
estimateGasAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues,
|
||||
fillTakerTokenAmount: BigNumber,
|
||||
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
|
||||
v: number, r: string, s: string, txOpts?: TxOpts) => Promise<number>;
|
||||
};
|
||||
batchFillOrders: {
|
||||
sendTransactionAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
|
||||
fillTakerTokenAmounts: BigNumber[],
|
||||
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
|
||||
v: number[], r: string[], s: string[], txOpts?: TxOpts) => Promise<string>;
|
||||
estimateGasAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
|
||||
fillTakerTokenAmounts: BigNumber[],
|
||||
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
|
||||
v: number[], r: string[], s: string[], txOpts?: TxOpts) => Promise<number>;
|
||||
};
|
||||
fillOrdersUpTo: {
|
||||
sendTransactionAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
|
||||
fillTakerTokenAmount: BigNumber,
|
||||
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
|
||||
v: number[], r: string[], s: string[], txOpts?: TxOpts) => Promise<string>;
|
||||
estimateGasAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
|
||||
fillTakerTokenAmount: BigNumber,
|
||||
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
|
||||
v: number[], r: string[], s: string[], txOpts?: TxOpts) => Promise<number>;
|
||||
};
|
||||
cancelOrder: {
|
||||
sendTransactionAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues,
|
||||
cancelTakerTokenAmount: BigNumber, txOpts?: TxOpts) => Promise<string>;
|
||||
estimateGasAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues,
|
||||
cancelTakerTokenAmount: BigNumber,
|
||||
txOpts?: TxOpts) => Promise<number>;
|
||||
};
|
||||
batchCancelOrders: {
|
||||
sendTransactionAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
|
||||
cancelTakerTokenAmounts: BigNumber[], txOpts?: TxOpts) => Promise<string>;
|
||||
estimateGasAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
|
||||
cancelTakerTokenAmounts: BigNumber[],
|
||||
txOpts?: TxOpts) => Promise<number>;
|
||||
};
|
||||
fillOrKillOrder: {
|
||||
sendTransactionAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues,
|
||||
fillTakerTokenAmount: BigNumber,
|
||||
v: number, r: string, s: string, txOpts?: TxOpts) => Promise<string>;
|
||||
estimateGasAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues,
|
||||
fillTakerTokenAmount: BigNumber,
|
||||
v: number, r: string, s: string, txOpts?: TxOpts) => Promise<number>;
|
||||
};
|
||||
batchFillOrKillOrders: {
|
||||
sendTransactionAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
|
||||
fillTakerTokenAmounts: BigNumber[],
|
||||
v: number[], r: string[], s: string[], txOpts: TxOpts) => Promise<string>;
|
||||
estimateGasAsync: (orderAddresses: OrderAddresses[], orderValues: OrderValues[],
|
||||
fillTakerTokenAmounts: BigNumber[],
|
||||
v: number[], r: string[], s: string[], txOpts?: TxOpts) => Promise<number>;
|
||||
};
|
||||
filled: {
|
||||
callAsync: (orderHash: string, defaultBlock?: Web3.BlockParam) => Promise<BigNumber>;
|
||||
};
|
||||
cancelled: {
|
||||
callAsync: (orderHash: string, defaultBlock?: Web3.BlockParam) => Promise<BigNumber>;
|
||||
};
|
||||
getOrderHash: {
|
||||
callAsync: (orderAddresses: OrderAddresses, orderValues: OrderValues) => Promise<string>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface TokenContract extends Web3.ContractInstance {
|
||||
balanceOf: {
|
||||
callAsync: (address: string, defaultBlock?: Web3.BlockParam) => Promise<BigNumber>;
|
||||
};
|
||||
allowance: {
|
||||
callAsync: (ownerAddress: string, allowedAddress: string,
|
||||
defaultBlock?: Web3.BlockParam) => Promise<BigNumber>;
|
||||
};
|
||||
transfer: {
|
||||
sendTransactionAsync: (toAddress: string, amountInBaseUnits: BigNumber,
|
||||
txOpts?: TxOpts) => Promise<string>;
|
||||
};
|
||||
transferFrom: {
|
||||
sendTransactionAsync: (fromAddress: string, toAddress: string, amountInBaseUnits: BigNumber,
|
||||
txOpts?: TxOpts) => Promise<string>;
|
||||
};
|
||||
approve: {
|
||||
sendTransactionAsync: (proxyAddress: string, amountInBaseUnits: BigNumber,
|
||||
txOpts?: TxOpts) => Promise<string>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface TokenRegistryContract extends Web3.ContractInstance {
|
||||
getTokenMetaData: {
|
||||
callAsync: (address: string) => Promise<TokenMetadata>;
|
||||
};
|
||||
getTokenAddresses: {
|
||||
callAsync: () => Promise<string[]>;
|
||||
};
|
||||
getTokenAddressBySymbol: {
|
||||
callAsync: (symbol: string) => Promise<string>;
|
||||
};
|
||||
getTokenAddressByName: {
|
||||
callAsync: (name: string) => Promise<string>;
|
||||
};
|
||||
getTokenBySymbol: {
|
||||
callAsync: (symbol: string) => Promise<TokenMetadata>;
|
||||
};
|
||||
getTokenByName: {
|
||||
callAsync: (name: string) => Promise<TokenMetadata>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface EtherTokenContract extends Web3.ContractInstance {
|
||||
deposit: {
|
||||
sendTransactionAsync: (txOpts: TxOpts) => Promise<string>;
|
||||
};
|
||||
withdraw: {
|
||||
sendTransactionAsync: (amount: BigNumber, txOpts: TxOpts) => Promise<string>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface TokenTransferProxyContract extends Web3.ContractInstance {
|
||||
getAuthorizedAddresses: {
|
||||
callAsync: () => Promise<string[]>;
|
||||
};
|
||||
authorized: {
|
||||
callAsync: (address: string) => Promise<boolean>;
|
||||
};
|
||||
}
|
||||
|
||||
export enum SolidityTypes {
|
||||
Address = 'address',
|
||||
Uint256 = 'uint256',
|
||||
@@ -288,8 +147,17 @@ export interface ApprovalContractEventArgs {
|
||||
_spender: string;
|
||||
_value: BigNumber;
|
||||
}
|
||||
export interface DepositContractEventArgs {
|
||||
_owner: string;
|
||||
_value: BigNumber;
|
||||
}
|
||||
export interface WithdrawalContractEventArgs {
|
||||
_owner: string;
|
||||
_value: BigNumber;
|
||||
}
|
||||
export type TokenContractEventArgs = TransferContractEventArgs|ApprovalContractEventArgs;
|
||||
export type ContractEventArgs = ExchangeContractEventArgs|TokenContractEventArgs;
|
||||
export type EtherTokenContractEventArgs = TokenContractEventArgs|DepositContractEventArgs|WithdrawalContractEventArgs;
|
||||
export type ContractEventArgs = ExchangeContractEventArgs|TokenContractEventArgs|EtherTokenContractEventArgs;
|
||||
export type ContractEventArg = string|BigNumber;
|
||||
|
||||
export interface Order {
|
||||
@@ -325,6 +193,7 @@ export interface TxOpts {
|
||||
from: string;
|
||||
gas?: number;
|
||||
value?: BigNumber;
|
||||
gasPrice?: BigNumber;
|
||||
}
|
||||
|
||||
export interface TokenAddressBySymbol {
|
||||
@@ -342,21 +211,30 @@ export enum TokenEvents {
|
||||
Approval = 'Approval',
|
||||
}
|
||||
|
||||
export type ContractEvents = TokenEvents|ExchangeEvents;
|
||||
export enum EtherTokenEvents {
|
||||
Transfer = 'Transfer',
|
||||
Approval = 'Approval',
|
||||
Deposit = 'Deposit',
|
||||
Withdrawal = 'Withdrawal',
|
||||
}
|
||||
|
||||
export type ContractEvents = TokenEvents|ExchangeEvents|EtherTokenEvents;
|
||||
|
||||
export interface IndexedFilterValues {
|
||||
[index: string]: ContractEventArg;
|
||||
}
|
||||
|
||||
// Earliest is omitted by design. It is simply an alias for the `0` constant and
|
||||
// is thus not very helpful. Moreover, this type is used in places that only accept
|
||||
// `latest` or `pending`.
|
||||
export enum BlockParamLiteral {
|
||||
Latest = 'latest',
|
||||
Earliest = 'earliest',
|
||||
Pending = 'pending',
|
||||
}
|
||||
|
||||
export type BlockParam = BlockParamLiteral|number;
|
||||
|
||||
export interface SubscriptionOpts {
|
||||
export interface BlockRange {
|
||||
fromBlock: BlockParam;
|
||||
toBlock: BlockParam;
|
||||
}
|
||||
@@ -374,42 +252,49 @@ export interface OrderFillRequest {
|
||||
}
|
||||
|
||||
export type AsyncMethod = (...args: any[]) => Promise<any>;
|
||||
export type SyncMethod = (...args: any[]) => any;
|
||||
|
||||
/**
|
||||
* We re-export the `Web3.Provider` type specified in the Web3 Typescript typings
|
||||
* since it is the type of the `provider` argument to the `ZeroEx` constructor.
|
||||
* It is however a `Web3` library type, not a native `0x.js` type.
|
||||
* It is however a `Web3` library type, not a native `0x.js` type. To learn more
|
||||
* about providers, visit https://0xproject.com/wiki#Web3-Provider-Explained
|
||||
*/
|
||||
export type Web3Provider = Web3.Provider;
|
||||
|
||||
export interface ExchangeContractByAddress {
|
||||
[address: string]: ExchangeContract;
|
||||
}
|
||||
|
||||
export interface JSONRPCPayload {
|
||||
params: any[];
|
||||
method: string;
|
||||
}
|
||||
|
||||
/*
|
||||
* eventPollingIntervalMs: How often to poll the Ethereum node for new events
|
||||
* orderExpirationCheckingIntervalMs: How often to check for expired orders. Default: 50
|
||||
* eventPollingIntervalMs: How often to poll the Ethereum node for new events. Defaults: 200
|
||||
* expirationMarginMs: Amount of time before order expiry that you'd like to be notified
|
||||
* of an orders expiration. Defaults: 0
|
||||
* cleanupJobIntervalMs: How often to run a cleanup job which revalidates all the orders. Defaults: 1h
|
||||
*/
|
||||
export interface OrderStateWatcherConfig {
|
||||
orderExpirationCheckingIntervalMs?: number;
|
||||
eventPollingIntervalMs?: number;
|
||||
expirationMarginMs?: number;
|
||||
cleanupJobIntervalMs?: number;
|
||||
}
|
||||
|
||||
/*
|
||||
* networkId: The id of the underlying ethereum network your provider is connected to. (1-mainnet, 42-kovan, 50-testrpc)
|
||||
* gasPrice: Gas price to use with every transaction
|
||||
* exchangeContractAddress: The address of an exchange contract to use
|
||||
* tokenRegistryContractAddress: The address of a token registry contract to use
|
||||
* etherTokenContractAddress: The address of an ether token contract to use
|
||||
* tokenTransferProxyContractAddress: The address of the token transfer proxy contract to use
|
||||
* orderWatcherConfig: All the configs related to the orderWatcher
|
||||
*/
|
||||
export interface ZeroExConfig {
|
||||
gasPrice?: BigNumber; // Gas price to use with every transaction
|
||||
networkId: number;
|
||||
gasPrice?: BigNumber;
|
||||
exchangeContractAddress?: string;
|
||||
tokenRegistryContractAddress?: string;
|
||||
etherTokenContractAddress?: string;
|
||||
tokenTransferProxyContractAddress?: string;
|
||||
orderWatcherConfig?: OrderStateWatcherConfig;
|
||||
}
|
||||
|
||||
@@ -430,11 +315,16 @@ export interface TransactionReceiptWithDecodedLogs extends TransactionReceipt {
|
||||
logs: Array<LogWithDecodedArgs<DecodedLogArgs>|Web3.LogEntry>;
|
||||
}
|
||||
|
||||
export type ArtifactContractName = 'ZRX'|'TokenTransferProxy'|'TokenRegistry'|'Token'|'Exchange'|'EtherToken';
|
||||
|
||||
export interface Artifact {
|
||||
abi: any;
|
||||
networks: {[networkId: number]: {
|
||||
address: string;
|
||||
}};
|
||||
contract_name: ArtifactContractName;
|
||||
abi: Web3.ContractAbi;
|
||||
networks: {
|
||||
[networkId: number]: {
|
||||
address: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -458,11 +348,20 @@ export interface MethodOpts {
|
||||
}
|
||||
|
||||
/*
|
||||
* shouldValidate: Flag indicating whether the library should make attempts to validate a transaction before
|
||||
* broadcasting it. For example, order has a valid signature, maker has sufficient funds, etc.
|
||||
* gasPrice: Gas price in Wei to use for a transaction
|
||||
* gasLimit: The amount of gas to send with a transaction
|
||||
*/
|
||||
export interface OrderTransactionOpts {
|
||||
shouldValidate: boolean;
|
||||
export interface TransactionOpts {
|
||||
gasPrice?: BigNumber;
|
||||
gasLimit?: number;
|
||||
}
|
||||
|
||||
/*
|
||||
* shouldValidate: Flag indicating whether the library should make attempts to validate a transaction before
|
||||
* broadcasting it. For example, order has a valid signature, maker has sufficient funds, etc. Default: true
|
||||
*/
|
||||
export interface OrderTransactionOpts extends TransactionOpts {
|
||||
shouldValidate?: boolean;
|
||||
}
|
||||
|
||||
export type FilterObject = Web3.FilterObject;
|
||||
@@ -503,17 +402,4 @@ export interface OrderStateInvalid {
|
||||
export type OrderState = OrderStateValid|OrderStateInvalid;
|
||||
|
||||
export type OnOrderStateChangeCallback = (orderState: OrderState) => void;
|
||||
|
||||
export interface TransactionReceipt {
|
||||
blockHash: string;
|
||||
blockNumber: number;
|
||||
transactionHash: string;
|
||||
transactionIndex: number;
|
||||
from: string;
|
||||
to: string;
|
||||
status: null|0|1;
|
||||
cumulativeGasUsed: number;
|
||||
gasUsed: number;
|
||||
contractAddress: string|null;
|
||||
logs: Web3.LogEntry[];
|
||||
}
|
||||
// tslint:disable:max-file-line-count
|
||||
|
@@ -1,20 +1,30 @@
|
||||
import * as Web3 from 'web3';
|
||||
import * as _ from 'lodash';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import {AbiType, DecodedLogArgs, LogWithDecodedArgs, RawLog, SolidityTypes, ContractEventArgs} from '../types';
|
||||
import * as _ from 'lodash';
|
||||
import * as Web3 from 'web3';
|
||||
import * as SolidityCoder from 'web3/lib/solidity/coder';
|
||||
|
||||
import {AbiType, ContractEventArgs, DecodedLogArgs, LogWithDecodedArgs, RawLog, SolidityTypes} from '../types';
|
||||
|
||||
export class AbiDecoder {
|
||||
private savedABIs: Web3.AbiDefinition[] = [];
|
||||
private methodIds: {[signatureHash: string]: Web3.EventAbi} = {};
|
||||
private _savedABIs: Web3.AbiDefinition[] = [];
|
||||
private _methodIds: {[signatureHash: string]: Web3.EventAbi} = {};
|
||||
private static _padZeros(address: string) {
|
||||
let formatted = address;
|
||||
if (_.startsWith(formatted, '0x')) {
|
||||
formatted = formatted.slice(2);
|
||||
}
|
||||
|
||||
formatted = _.padStart(formatted, 40, '0');
|
||||
return `0x${formatted}`;
|
||||
}
|
||||
constructor(abiArrays: Web3.AbiDefinition[][]) {
|
||||
_.map(abiArrays, this.addABI.bind(this));
|
||||
_.map(abiArrays, this._addABI.bind(this));
|
||||
}
|
||||
// This method can only decode logs from the 0x & ERC20 smart contracts
|
||||
public tryToDecodeLogOrNoop<ArgsType extends ContractEventArgs>(
|
||||
log: Web3.LogEntry): LogWithDecodedArgs<ArgsType>|RawLog {
|
||||
const methodId = log.topics[0];
|
||||
const event = this.methodIds[methodId];
|
||||
const event = this._methodIds[methodId];
|
||||
if (_.isUndefined(event)) {
|
||||
return log;
|
||||
}
|
||||
@@ -31,7 +41,7 @@ export class AbiDecoder {
|
||||
// Indexed parameters are stored in topics. Non-indexed ones in decodedData
|
||||
let value = param.indexed ? log.topics[topicsIndex++] : decodedData[dataIndex++];
|
||||
if (param.type === SolidityTypes.Address) {
|
||||
value = this.padZeros(new BigNumber(value).toString(16));
|
||||
value = AbiDecoder._padZeros(new BigNumber(value).toString(16));
|
||||
} else if (param.type === SolidityTypes.Uint256 ||
|
||||
param.type === SolidityTypes.Uint8 ||
|
||||
param.type === SolidityTypes.Uint) {
|
||||
@@ -46,23 +56,14 @@ export class AbiDecoder {
|
||||
args: decodedParams,
|
||||
};
|
||||
}
|
||||
private addABI(abiArray: Web3.AbiDefinition[]): void {
|
||||
private _addABI(abiArray: Web3.AbiDefinition[]): void {
|
||||
_.map(abiArray, (abi: Web3.AbiDefinition) => {
|
||||
if (abi.type === AbiType.Event) {
|
||||
const signature = `${abi.name}(${_.map(abi.inputs, input => input.type).join(',')})`;
|
||||
const signatureHash = new Web3().sha3(signature);
|
||||
this.methodIds[signatureHash] = abi;
|
||||
this._methodIds[signatureHash] = abi;
|
||||
}
|
||||
});
|
||||
this.savedABIs = this.savedABIs.concat(abiArray);
|
||||
}
|
||||
private padZeros(address: string) {
|
||||
let formatted = address;
|
||||
if (_.startsWith(formatted, '0x')) {
|
||||
formatted = formatted.slice(2);
|
||||
}
|
||||
|
||||
formatted = _.padStart(formatted, 40, '0');
|
||||
return `0x${formatted}`;
|
||||
this._savedABIs = this._savedABIs.concat(abiArray);
|
||||
}
|
||||
}
|
||||
|
@@ -1,13 +1,14 @@
|
||||
import * as _ from 'lodash';
|
||||
import * as Web3 from 'web3';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import {SchemaValidator, Schema} from '@0xproject/json-schemas';
|
||||
import {assert as sharedAssert} from '@0xproject/assert';
|
||||
import {Web3Wrapper} from '../web3_wrapper';
|
||||
import {signatureUtils} from '../utils/signature_utils';
|
||||
import {ECSignature} from '../types';
|
||||
// We need those two unused imports because they're actually used by sharedAssert which gets injected here
|
||||
// tslint:disable-next-line:no-unused-variable
|
||||
import {Schema} from '@0xproject/json-schemas';
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
// tslint:disable-next-line:no-unused-variable
|
||||
import * as BigNumber from 'bignumber.js';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
const HEX_REGEX = /^0x[0-9A-F]*$/i;
|
||||
import {ECSignature} from '../types';
|
||||
import {signatureUtils} from '../utils/signature_utils';
|
||||
|
||||
export const assert = {
|
||||
...sharedAssert,
|
||||
|
@@ -6,6 +6,7 @@ export const constants = {
|
||||
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,
|
||||
};
|
||||
|
@@ -1,15 +1,37 @@
|
||||
import * as _ from 'lodash';
|
||||
import {constants} from './constants';
|
||||
import {AsyncMethod, ZeroExError} from '../types';
|
||||
|
||||
export const decorators = {
|
||||
/**
|
||||
* Source: https://stackoverflow.com/a/29837695/3546986
|
||||
*/
|
||||
contractCallErrorHandler(target: object,
|
||||
key: string|symbol,
|
||||
descriptor: TypedPropertyDescriptor<AsyncMethod>,
|
||||
): TypedPropertyDescriptor<AsyncMethod> {
|
||||
import {AsyncMethod, SyncMethod, ZeroExError} from '../types';
|
||||
|
||||
import {constants} from './constants';
|
||||
|
||||
type ErrorTransformer = (err: Error) => Error;
|
||||
|
||||
const contractCallErrorTransformer = (error: Error) => {
|
||||
if (_.includes(error.message, constants.INVALID_JUMP_PATTERN)) {
|
||||
return new Error(ZeroExError.InvalidJump);
|
||||
}
|
||||
if (_.includes(error.message, constants.OUT_OF_GAS_PATTERN)) {
|
||||
return new Error(ZeroExError.OutOfGas);
|
||||
}
|
||||
return error;
|
||||
};
|
||||
|
||||
const schemaErrorTransformer = (error: Error) => {
|
||||
if (_.includes(error.message, constants.INVALID_TAKER_FORMAT)) {
|
||||
// tslint:disable-next-line:max-line-length
|
||||
const errMsg = 'Order taker must be of type string. If you want anyone to be able to fill an order - pass ZeroEx.NULL_ADDRESS';
|
||||
return new Error(errMsg);
|
||||
}
|
||||
return error;
|
||||
};
|
||||
|
||||
/**
|
||||
* Source: https://stackoverflow.com/a/29837695/3546986
|
||||
*/
|
||||
const asyncErrorHandlerFactory = (errorTransformer: ErrorTransformer) => {
|
||||
const asyncErrorHandlingDecorator = (
|
||||
target: object, key: string|symbol, descriptor: TypedPropertyDescriptor<AsyncMethod>,
|
||||
) => {
|
||||
const originalMethod = (descriptor.value as AsyncMethod);
|
||||
|
||||
// Do not use arrow syntax here. Use a function expression in
|
||||
@@ -20,16 +42,46 @@ export const decorators = {
|
||||
const result = await originalMethod.apply(this, args);
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (_.includes(error.message, constants.INVALID_JUMP_PATTERN)) {
|
||||
throw new Error(ZeroExError.InvalidJump);
|
||||
}
|
||||
if (_.includes(error.message, constants.OUT_OF_GAS_PATTERN)) {
|
||||
throw new Error(ZeroExError.OutOfGas);
|
||||
}
|
||||
throw error;
|
||||
const transformedError = errorTransformer(error);
|
||||
throw transformedError;
|
||||
}
|
||||
};
|
||||
|
||||
return descriptor;
|
||||
},
|
||||
};
|
||||
|
||||
return asyncErrorHandlingDecorator;
|
||||
};
|
||||
|
||||
const syncErrorHandlerFactory = (errorTransformer: ErrorTransformer) => {
|
||||
const syncErrorHandlingDecorator = (
|
||||
target: object, key: string|symbol, descriptor: TypedPropertyDescriptor<SyncMethod>,
|
||||
) => {
|
||||
const originalMethod = (descriptor.value as SyncMethod);
|
||||
|
||||
// Do not use arrow syntax here. Use a function expression in
|
||||
// order to use the correct value of `this` in this method
|
||||
// tslint:disable-next-line:only-arrow-functions
|
||||
descriptor.value = function(...args: any[]) {
|
||||
try {
|
||||
const result = originalMethod.apply(this, args);
|
||||
return result;
|
||||
} catch (error) {
|
||||
const transformedError = errorTransformer(error);
|
||||
throw transformedError;
|
||||
}
|
||||
};
|
||||
|
||||
return descriptor;
|
||||
};
|
||||
|
||||
return syncErrorHandlingDecorator;
|
||||
};
|
||||
|
||||
// _.flow(f, g) = f ∘ g
|
||||
const zeroExErrorTransformer = _.flow(schemaErrorTransformer, contractCallErrorTransformer);
|
||||
|
||||
export const decorators = {
|
||||
asyncZeroExErrorHandler: asyncErrorHandlerFactory(zeroExErrorTransformer),
|
||||
syncZeroExErrorHandler: syncErrorHandlerFactory(zeroExErrorTransformer),
|
||||
};
|
||||
|
@@ -1,8 +1,9 @@
|
||||
import * as _ from 'lodash';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import {ExchangeContractErrs, TradeSide, TransferType, BlockParamLiteral} from '../types';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {TokenWrapper} from '../contract_wrappers/token_wrapper';
|
||||
import {BalanceAndProxyAllowanceLazyStore} from '../stores/balance_proxy_allowance_lazy_store';
|
||||
import {BlockParamLiteral, ExchangeContractErrs, TradeSide, TransferType} from '../types';
|
||||
|
||||
enum FailureReason {
|
||||
Balance = 'balance',
|
||||
@@ -33,11 +34,16 @@ const ERR_MSG_MAPPING = {
|
||||
};
|
||||
|
||||
export class ExchangeTransferSimulator {
|
||||
private store: BalanceAndProxyAllowanceLazyStore;
|
||||
private UNLIMITED_ALLOWANCE_IN_BASE_UNITS: BigNumber;
|
||||
constructor(token: TokenWrapper) {
|
||||
this.store = new BalanceAndProxyAllowanceLazyStore(token);
|
||||
this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS = token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
|
||||
private _store: BalanceAndProxyAllowanceLazyStore;
|
||||
private _UNLIMITED_ALLOWANCE_IN_BASE_UNITS: BigNumber;
|
||||
private static _throwValidationError(failureReason: FailureReason, tradeSide: TradeSide,
|
||||
transferType: TransferType): never {
|
||||
const errMsg = ERR_MSG_MAPPING[failureReason][tradeSide][transferType];
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
constructor(token: TokenWrapper, defaultBlock: BlockParamLiteral) {
|
||||
this._store = new BalanceAndProxyAllowanceLazyStore(token, defaultBlock);
|
||||
this._UNLIMITED_ALLOWANCE_IN_BASE_UNITS = token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
|
||||
}
|
||||
/**
|
||||
* Simulates transferFrom call performed by a proxy
|
||||
@@ -51,38 +57,33 @@ export class ExchangeTransferSimulator {
|
||||
public async transferFromAsync(tokenAddress: string, from: string, to: string,
|
||||
amountInBaseUnits: BigNumber, tradeSide: TradeSide,
|
||||
transferType: TransferType): Promise<void> {
|
||||
const balance = await this.store.getBalanceAsync(tokenAddress, from);
|
||||
const proxyAllowance = await this.store.getProxyAllowanceAsync(tokenAddress, from);
|
||||
const balance = await this._store.getBalanceAsync(tokenAddress, from);
|
||||
const proxyAllowance = await this._store.getProxyAllowanceAsync(tokenAddress, from);
|
||||
if (proxyAllowance.lessThan(amountInBaseUnits)) {
|
||||
this.throwValidationError(FailureReason.ProxyAllowance, tradeSide, transferType);
|
||||
ExchangeTransferSimulator._throwValidationError(FailureReason.ProxyAllowance, tradeSide, transferType);
|
||||
}
|
||||
if (balance.lessThan(amountInBaseUnits)) {
|
||||
this.throwValidationError(FailureReason.Balance, tradeSide, transferType);
|
||||
ExchangeTransferSimulator._throwValidationError(FailureReason.Balance, tradeSide, transferType);
|
||||
}
|
||||
await this.decreaseProxyAllowanceAsync(tokenAddress, from, amountInBaseUnits);
|
||||
await this.decreaseBalanceAsync(tokenAddress, from, amountInBaseUnits);
|
||||
await this.increaseBalanceAsync(tokenAddress, to, amountInBaseUnits);
|
||||
await this._decreaseProxyAllowanceAsync(tokenAddress, from, amountInBaseUnits);
|
||||
await this._decreaseBalanceAsync(tokenAddress, from, amountInBaseUnits);
|
||||
await this._increaseBalanceAsync(tokenAddress, to, amountInBaseUnits);
|
||||
}
|
||||
private async decreaseProxyAllowanceAsync(tokenAddress: string, userAddress: string,
|
||||
amountInBaseUnits: BigNumber): Promise<void> {
|
||||
const proxyAllowance = await this.store.getProxyAllowanceAsync(tokenAddress, userAddress);
|
||||
if (!proxyAllowance.eq(this.UNLIMITED_ALLOWANCE_IN_BASE_UNITS)) {
|
||||
this.store.setProxyAllowance(tokenAddress, userAddress, proxyAllowance.minus(amountInBaseUnits));
|
||||
private async _decreaseProxyAllowanceAsync(tokenAddress: string, userAddress: string,
|
||||
amountInBaseUnits: BigNumber): Promise<void> {
|
||||
const proxyAllowance = await this._store.getProxyAllowanceAsync(tokenAddress, userAddress);
|
||||
if (!proxyAllowance.eq(this._UNLIMITED_ALLOWANCE_IN_BASE_UNITS)) {
|
||||
this._store.setProxyAllowance(tokenAddress, userAddress, proxyAllowance.minus(amountInBaseUnits));
|
||||
}
|
||||
}
|
||||
private async increaseBalanceAsync(tokenAddress: string, userAddress: string,
|
||||
amountInBaseUnits: BigNumber): Promise<void> {
|
||||
const balance = await this.store.getBalanceAsync(tokenAddress, userAddress);
|
||||
this.store.setBalance(tokenAddress, userAddress, balance.plus(amountInBaseUnits));
|
||||
private async _increaseBalanceAsync(tokenAddress: string, userAddress: string,
|
||||
amountInBaseUnits: BigNumber): Promise<void> {
|
||||
const balance = await this._store.getBalanceAsync(tokenAddress, userAddress);
|
||||
this._store.setBalance(tokenAddress, userAddress, balance.plus(amountInBaseUnits));
|
||||
}
|
||||
private async decreaseBalanceAsync(tokenAddress: string, userAddress: string,
|
||||
amountInBaseUnits: BigNumber): Promise<void> {
|
||||
const balance = await this.store.getBalanceAsync(tokenAddress, userAddress);
|
||||
this.store.setBalance(tokenAddress, userAddress, balance.minus(amountInBaseUnits));
|
||||
}
|
||||
private throwValidationError(failureReason: FailureReason, tradeSide: TradeSide,
|
||||
transferType: TransferType): Promise<never> {
|
||||
const errMsg = ERR_MSG_MAPPING[failureReason][tradeSide][transferType];
|
||||
throw new Error(errMsg);
|
||||
private async _decreaseBalanceAsync(tokenAddress: string, userAddress: string,
|
||||
amountInBaseUnits: BigNumber): Promise<void> {
|
||||
const balance = await this._store.getBalanceAsync(tokenAddress, userAddress);
|
||||
this._store.setBalance(tokenAddress, userAddress, balance.minus(amountInBaseUnits));
|
||||
}
|
||||
}
|
||||
|
@@ -1,9 +1,10 @@
|
||||
import * as _ from 'lodash';
|
||||
import * as Web3 from 'web3';
|
||||
import * as uuid from 'uuid/v4';
|
||||
import * as ethUtil from 'ethereumjs-util';
|
||||
import * as jsSHA3 from 'js-sha3';
|
||||
import {ContractEvents, IndexedFilterValues, SubscriptionOpts} from '../types';
|
||||
import * as _ from 'lodash';
|
||||
import * as uuid from 'uuid/v4';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {BlockRange, ContractEvents, IndexedFilterValues} from '../types';
|
||||
|
||||
const TOPIC_LENGTH = 32;
|
||||
|
||||
@@ -13,7 +14,7 @@ export const filterUtils = {
|
||||
},
|
||||
getFilter(address: string, eventName: ContractEvents,
|
||||
indexFilterValues: IndexedFilterValues, abi: Web3.ContractAbi,
|
||||
subscriptionOpts?: SubscriptionOpts): Web3.FilterObject {
|
||||
blockRange?: BlockRange): Web3.FilterObject {
|
||||
const eventAbi = _.find(abi, {name: eventName}) as Web3.EventAbi;
|
||||
const eventSignature = filterUtils.getEventSignatureFromAbiByName(eventAbi, eventName);
|
||||
const topicForEventSignature = ethUtil.addHexPrefix(jsSHA3.keccak256(eventSignature));
|
||||
@@ -23,9 +24,9 @@ export const filterUtils = {
|
||||
address,
|
||||
topics,
|
||||
};
|
||||
if (!_.isUndefined(subscriptionOpts)) {
|
||||
if (!_.isUndefined(blockRange)) {
|
||||
filter = {
|
||||
...subscriptionOpts,
|
||||
...blockRange,
|
||||
...filter,
|
||||
};
|
||||
}
|
||||
|
@@ -1,102 +1,26 @@
|
||||
import * as _ from 'lodash';
|
||||
import * as Web3 from 'web3';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {ZeroEx} from '../0x';
|
||||
import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper';
|
||||
import {RemainingFillableCalculator} from '../order_watcher/remaining_fillable_calculator';
|
||||
import {BalanceAndProxyAllowanceLazyStore} from '../stores/balance_proxy_allowance_lazy_store';
|
||||
import {OrderFilledCancelledLazyStore} from '../stores/order_filled_cancelled_lazy_store';
|
||||
import {
|
||||
ExchangeContractErrs,
|
||||
SignedOrder,
|
||||
OrderRelevantState,
|
||||
MethodOpts,
|
||||
OrderState,
|
||||
OrderStateValid,
|
||||
OrderStateInvalid,
|
||||
OrderStateValid,
|
||||
SignedOrder,
|
||||
} from '../types';
|
||||
import {ZeroEx} from '../0x';
|
||||
import {TokenWrapper} from '../contract_wrappers/token_wrapper';
|
||||
import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper';
|
||||
import {utils} from '../utils/utils';
|
||||
import {constants} from '../utils/constants';
|
||||
import {OrderFilledCancelledLazyStore} from '../stores/order_filled_cancelled_lazy_store';
|
||||
import {BalanceAndProxyAllowanceLazyStore} from '../stores/balance_proxy_allowance_lazy_store';
|
||||
|
||||
const ACCEPTABLE_RELATIVE_ROUNDING_ERROR = 0.0001;
|
||||
|
||||
export class OrderStateUtils {
|
||||
private balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore;
|
||||
private orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore;
|
||||
constructor(balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore,
|
||||
orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore) {
|
||||
this.balanceAndProxyAllowanceLazyStore = balanceAndProxyAllowanceLazyStore;
|
||||
this.orderFilledCancelledLazyStore = orderFilledCancelledLazyStore;
|
||||
}
|
||||
public async getOrderStateAsync(signedOrder: SignedOrder): Promise<OrderState> {
|
||||
const orderRelevantState = await this.getOrderRelevantStateAsync(signedOrder);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
try {
|
||||
this.validateIfOrderIsValid(signedOrder, orderRelevantState);
|
||||
const orderState: OrderStateValid = {
|
||||
isValid: true,
|
||||
orderHash,
|
||||
orderRelevantState,
|
||||
};
|
||||
return orderState;
|
||||
} catch (err) {
|
||||
const orderState: OrderStateInvalid = {
|
||||
isValid: false,
|
||||
orderHash,
|
||||
error: err.message,
|
||||
};
|
||||
return orderState;
|
||||
}
|
||||
}
|
||||
public async getOrderRelevantStateAsync(signedOrder: SignedOrder): Promise<OrderRelevantState> {
|
||||
// HACK: We access the private property here but otherwise the interface will be less nice.
|
||||
// If we pass it from the instantiator - there is no opportunity to get it there
|
||||
// because JS doesn't support async constructors.
|
||||
// Moreover - it's cached under the hood so it's equivalent to an async constructor.
|
||||
const exchange = (this.orderFilledCancelledLazyStore as any).exchange as ExchangeWrapper;
|
||||
const zrxTokenAddress = await exchange.getZRXTokenAddressAsync();
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
const makerBalance = await this.balanceAndProxyAllowanceLazyStore.getBalanceAsync(
|
||||
signedOrder.makerTokenAddress, signedOrder.maker,
|
||||
);
|
||||
const makerProxyAllowance = await this.balanceAndProxyAllowanceLazyStore.getProxyAllowanceAsync(
|
||||
signedOrder.makerTokenAddress, signedOrder.maker,
|
||||
);
|
||||
const makerFeeBalance = await this.balanceAndProxyAllowanceLazyStore.getBalanceAsync(
|
||||
zrxTokenAddress, signedOrder.maker,
|
||||
);
|
||||
const makerFeeProxyAllowance = await this.balanceAndProxyAllowanceLazyStore.getProxyAllowanceAsync(
|
||||
zrxTokenAddress, signedOrder.maker,
|
||||
);
|
||||
const filledTakerTokenAmount = await this.orderFilledCancelledLazyStore.getFilledTakerAmountAsync(orderHash);
|
||||
const cancelledTakerTokenAmount = await this.orderFilledCancelledLazyStore.getCancelledTakerAmountAsync(
|
||||
orderHash,
|
||||
);
|
||||
const unavailableTakerTokenAmount = await exchange.getUnavailableTakerAmountAsync(orderHash);
|
||||
const totalMakerTokenAmount = signedOrder.makerTokenAmount;
|
||||
const totalTakerTokenAmount = signedOrder.takerTokenAmount;
|
||||
const remainingTakerTokenAmount = totalTakerTokenAmount.minus(unavailableTakerTokenAmount);
|
||||
const remainingMakerTokenAmount = remainingTakerTokenAmount.times(totalMakerTokenAmount)
|
||||
.dividedToIntegerBy(totalTakerTokenAmount);
|
||||
const fillableMakerTokenAmount = BigNumber.min([makerProxyAllowance, makerBalance]);
|
||||
const remainingFillableMakerTokenAmount = BigNumber.min(fillableMakerTokenAmount, remainingMakerTokenAmount);
|
||||
const remainingFillableTakerTokenAmount = remainingFillableMakerTokenAmount
|
||||
.times(totalTakerTokenAmount)
|
||||
.dividedToIntegerBy(totalMakerTokenAmount);
|
||||
// TODO: Handle edge case where maker token is ZRX with fee
|
||||
const orderRelevantState = {
|
||||
makerBalance,
|
||||
makerProxyAllowance,
|
||||
makerFeeBalance,
|
||||
makerFeeProxyAllowance,
|
||||
filledTakerTokenAmount,
|
||||
cancelledTakerTokenAmount,
|
||||
remainingFillableMakerTokenAmount,
|
||||
remainingFillableTakerTokenAmount,
|
||||
};
|
||||
return orderRelevantState;
|
||||
}
|
||||
private validateIfOrderIsValid(signedOrder: SignedOrder, orderRelevantState: OrderRelevantState): void {
|
||||
private _balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore;
|
||||
private _orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore;
|
||||
private static _validateIfOrderIsValid(signedOrder: SignedOrder, orderRelevantState: OrderRelevantState): void {
|
||||
const unavailableTakerTokenAmount = orderRelevantState.cancelledTakerTokenAmount.add(
|
||||
orderRelevantState.filledTakerTokenAmount,
|
||||
);
|
||||
@@ -126,7 +50,83 @@ export class OrderStateUtils {
|
||||
.lessThan(minFillableTakerTokenAmountWithinNoRoundingErrorRange)) {
|
||||
throw new Error(ExchangeContractErrs.OrderFillRoundingError);
|
||||
}
|
||||
// TODO Add linear function solver when maker token is ZRX #badass
|
||||
// Return the max amount that's fillable
|
||||
}
|
||||
constructor(balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore,
|
||||
orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore) {
|
||||
this._balanceAndProxyAllowanceLazyStore = balanceAndProxyAllowanceLazyStore;
|
||||
this._orderFilledCancelledLazyStore = orderFilledCancelledLazyStore;
|
||||
}
|
||||
public async getOrderStateAsync(signedOrder: SignedOrder): Promise<OrderState> {
|
||||
const orderRelevantState = await this.getOrderRelevantStateAsync(signedOrder);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
try {
|
||||
OrderStateUtils._validateIfOrderIsValid(signedOrder, orderRelevantState);
|
||||
const orderState: OrderStateValid = {
|
||||
isValid: true,
|
||||
orderHash,
|
||||
orderRelevantState,
|
||||
};
|
||||
return orderState;
|
||||
} catch (err) {
|
||||
const orderState: OrderStateInvalid = {
|
||||
isValid: false,
|
||||
orderHash,
|
||||
error: err.message,
|
||||
};
|
||||
return orderState;
|
||||
}
|
||||
}
|
||||
public async getOrderRelevantStateAsync(signedOrder: SignedOrder): Promise<OrderRelevantState> {
|
||||
// HACK: We access the private property here but otherwise the interface will be less nice.
|
||||
// If we pass it from the instantiator - there is no opportunity to get it there
|
||||
// because JS doesn't support async constructors.
|
||||
// Moreover - it's cached under the hood so it's equivalent to an async constructor.
|
||||
const exchange = (this._orderFilledCancelledLazyStore as any)._exchange as ExchangeWrapper;
|
||||
const zrxTokenAddress = exchange.getZRXTokenAddress();
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
const makerBalance = await this._balanceAndProxyAllowanceLazyStore.getBalanceAsync(
|
||||
signedOrder.makerTokenAddress, signedOrder.maker,
|
||||
);
|
||||
const makerProxyAllowance = await this._balanceAndProxyAllowanceLazyStore.getProxyAllowanceAsync(
|
||||
signedOrder.makerTokenAddress, signedOrder.maker,
|
||||
);
|
||||
const makerFeeBalance = await this._balanceAndProxyAllowanceLazyStore.getBalanceAsync(
|
||||
zrxTokenAddress, signedOrder.maker,
|
||||
);
|
||||
const makerFeeProxyAllowance = await this._balanceAndProxyAllowanceLazyStore.getProxyAllowanceAsync(
|
||||
zrxTokenAddress, signedOrder.maker,
|
||||
);
|
||||
const filledTakerTokenAmount = await this._orderFilledCancelledLazyStore.getFilledTakerAmountAsync(orderHash);
|
||||
const cancelledTakerTokenAmount = await this._orderFilledCancelledLazyStore.getCancelledTakerAmountAsync(
|
||||
orderHash,
|
||||
);
|
||||
const unavailableTakerTokenAmount = await exchange.getUnavailableTakerAmountAsync(orderHash);
|
||||
const totalMakerTokenAmount = signedOrder.makerTokenAmount;
|
||||
const totalTakerTokenAmount = signedOrder.takerTokenAmount;
|
||||
const remainingTakerTokenAmount = totalTakerTokenAmount.minus(unavailableTakerTokenAmount);
|
||||
const remainingMakerTokenAmount = remainingTakerTokenAmount.times(totalMakerTokenAmount)
|
||||
.dividedToIntegerBy(totalTakerTokenAmount);
|
||||
const transferrableMakerTokenAmount = BigNumber.min([makerProxyAllowance, makerBalance]);
|
||||
const transferrableFeeTokenAmount = BigNumber.min([makerFeeProxyAllowance, makerFeeBalance]);
|
||||
|
||||
const isMakerTokenZRX = signedOrder.makerTokenAddress === zrxTokenAddress;
|
||||
const remainingFillableCalculator = new RemainingFillableCalculator(signedOrder,
|
||||
isMakerTokenZRX,
|
||||
transferrableMakerTokenAmount,
|
||||
transferrableFeeTokenAmount,
|
||||
remainingMakerTokenAmount);
|
||||
const remainingFillableMakerTokenAmount = remainingFillableCalculator.computeRemainingMakerFillable();
|
||||
const remainingFillableTakerTokenAmount = remainingFillableCalculator.computeRemainingTakerFillable();
|
||||
const orderRelevantState = {
|
||||
makerBalance,
|
||||
makerProxyAllowance,
|
||||
makerFeeBalance,
|
||||
makerFeeProxyAllowance,
|
||||
filledTakerTokenAmount,
|
||||
cancelledTakerTokenAmount,
|
||||
remainingFillableMakerTokenAmount,
|
||||
remainingFillableTakerTokenAmount,
|
||||
};
|
||||
return orderRelevantState;
|
||||
}
|
||||
}
|
||||
|
@@ -1,34 +1,104 @@
|
||||
import * as _ from 'lodash';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import {ExchangeContractErrs, SignedOrder, Order, ZeroExError, TradeSide, TransferType} from '../types';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {ZeroEx} from '../0x';
|
||||
import {TokenWrapper} from '../contract_wrappers/token_wrapper';
|
||||
import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper';
|
||||
import {utils} from '../utils/utils';
|
||||
import {ExchangeContractErrs, Order, SignedOrder, TradeSide, TransferType, ZeroExError} from '../types';
|
||||
import {constants} from '../utils/constants';
|
||||
import {utils} from '../utils/utils';
|
||||
|
||||
import {ExchangeTransferSimulator} from './exchange_transfer_simulator';
|
||||
|
||||
export class OrderValidationUtils {
|
||||
private tokenWrapper: TokenWrapper;
|
||||
private exchangeWrapper: ExchangeWrapper;
|
||||
constructor(tokenWrapper: TokenWrapper, exchangeWrapper: ExchangeWrapper) {
|
||||
this.tokenWrapper = tokenWrapper;
|
||||
this.exchangeWrapper = exchangeWrapper;
|
||||
private _exchangeWrapper: ExchangeWrapper;
|
||||
public static validateCancelOrderThrowIfInvalid(
|
||||
order: Order, cancelTakerTokenAmount: BigNumber, unavailableTakerTokenAmount: BigNumber,
|
||||
): void {
|
||||
if (cancelTakerTokenAmount.eq(0)) {
|
||||
throw new Error(ExchangeContractErrs.OrderCancelAmountZero);
|
||||
}
|
||||
if (order.takerTokenAmount.eq(unavailableTakerTokenAmount)) {
|
||||
throw new Error(ExchangeContractErrs.OrderAlreadyCancelledOrFilled);
|
||||
}
|
||||
const currentUnixTimestampSec = utils.getCurrentUnixTimestampSec();
|
||||
if (order.expirationUnixTimestampSec.lessThan(currentUnixTimestampSec)) {
|
||||
throw new Error(ExchangeContractErrs.OrderCancelExpired);
|
||||
}
|
||||
}
|
||||
public static async validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
|
||||
exchangeTradeEmulator: ExchangeTransferSimulator, signedOrder: SignedOrder,
|
||||
fillTakerTokenAmount: BigNumber, senderAddress: string, zrxTokenAddress: string,
|
||||
): Promise<void> {
|
||||
const fillMakerTokenAmount = OrderValidationUtils._getPartialAmount(
|
||||
fillTakerTokenAmount,
|
||||
signedOrder.takerTokenAmount,
|
||||
signedOrder.makerTokenAmount,
|
||||
);
|
||||
await exchangeTradeEmulator.transferFromAsync(
|
||||
signedOrder.makerTokenAddress, signedOrder.maker, senderAddress, fillMakerTokenAmount,
|
||||
TradeSide.Maker, TransferType.Trade,
|
||||
);
|
||||
await exchangeTradeEmulator.transferFromAsync(
|
||||
signedOrder.takerTokenAddress, senderAddress, signedOrder.maker, fillTakerTokenAmount,
|
||||
TradeSide.Taker, TransferType.Trade,
|
||||
);
|
||||
const makerFeeAmount = OrderValidationUtils._getPartialAmount(
|
||||
fillTakerTokenAmount,
|
||||
signedOrder.takerTokenAmount,
|
||||
signedOrder.makerFee,
|
||||
);
|
||||
await exchangeTradeEmulator.transferFromAsync(
|
||||
zrxTokenAddress, signedOrder.maker, signedOrder.feeRecipient, makerFeeAmount, TradeSide.Maker,
|
||||
TransferType.Fee,
|
||||
);
|
||||
const takerFeeAmount = OrderValidationUtils._getPartialAmount(
|
||||
fillTakerTokenAmount,
|
||||
signedOrder.takerTokenAmount,
|
||||
signedOrder.takerFee,
|
||||
);
|
||||
await exchangeTradeEmulator.transferFromAsync(
|
||||
zrxTokenAddress, senderAddress, signedOrder.feeRecipient, takerFeeAmount, TradeSide.Taker,
|
||||
TransferType.Fee,
|
||||
);
|
||||
}
|
||||
private static _validateRemainingFillAmountNotZeroOrThrow(
|
||||
takerTokenAmount: BigNumber, unavailableTakerTokenAmount: BigNumber,
|
||||
) {
|
||||
if (takerTokenAmount.eq(unavailableTakerTokenAmount)) {
|
||||
throw new Error(ExchangeContractErrs.OrderRemainingFillAmountZero);
|
||||
}
|
||||
}
|
||||
private static _validateOrderNotExpiredOrThrow(expirationUnixTimestampSec: BigNumber) {
|
||||
const currentUnixTimestampSec = utils.getCurrentUnixTimestampSec();
|
||||
if (expirationUnixTimestampSec.lessThan(currentUnixTimestampSec)) {
|
||||
throw new Error(ExchangeContractErrs.OrderFillExpired);
|
||||
}
|
||||
}
|
||||
private static _getPartialAmount(numerator: BigNumber, denominator: BigNumber,
|
||||
target: BigNumber): BigNumber {
|
||||
const fillMakerTokenAmount = numerator
|
||||
.mul(target)
|
||||
.div(denominator)
|
||||
.round(0);
|
||||
return fillMakerTokenAmount;
|
||||
}
|
||||
constructor(exchangeWrapper: ExchangeWrapper) {
|
||||
this._exchangeWrapper = exchangeWrapper;
|
||||
}
|
||||
public async validateOrderFillableOrThrowAsync(
|
||||
exchangeTradeEmulator: ExchangeTransferSimulator, signedOrder: SignedOrder, zrxTokenAddress: string,
|
||||
expectedFillTakerTokenAmount?: BigNumber): Promise<void> {
|
||||
const orderHash = utils.getOrderHashHex(signedOrder);
|
||||
const unavailableTakerTokenAmount = await this.exchangeWrapper.getUnavailableTakerAmountAsync(orderHash);
|
||||
this.validateRemainingFillAmountNotZeroOrThrow(
|
||||
const unavailableTakerTokenAmount = await this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash);
|
||||
OrderValidationUtils._validateRemainingFillAmountNotZeroOrThrow(
|
||||
signedOrder.takerTokenAmount, unavailableTakerTokenAmount,
|
||||
);
|
||||
this.validateOrderNotExpiredOrThrow(signedOrder.expirationUnixTimestampSec);
|
||||
OrderValidationUtils._validateOrderNotExpiredOrThrow(signedOrder.expirationUnixTimestampSec);
|
||||
let fillTakerTokenAmount = signedOrder.takerTokenAmount.minus(unavailableTakerTokenAmount);
|
||||
if (!_.isUndefined(expectedFillTakerTokenAmount)) {
|
||||
fillTakerTokenAmount = expectedFillTakerTokenAmount;
|
||||
}
|
||||
const fillMakerTokenAmount = this.getPartialAmount(
|
||||
const fillMakerTokenAmount = OrderValidationUtils._getPartialAmount(
|
||||
fillTakerTokenAmount,
|
||||
signedOrder.takerTokenAmount,
|
||||
signedOrder.makerTokenAmount,
|
||||
@@ -37,7 +107,7 @@ export class OrderValidationUtils {
|
||||
signedOrder.makerTokenAddress, signedOrder.maker, signedOrder.taker, fillMakerTokenAmount,
|
||||
TradeSide.Maker, TransferType.Trade,
|
||||
);
|
||||
const makerFeeAmount = this.getPartialAmount(
|
||||
const makerFeeAmount = OrderValidationUtils._getPartialAmount(
|
||||
fillTakerTokenAmount,
|
||||
signedOrder.takerTokenAmount,
|
||||
signedOrder.makerFee,
|
||||
@@ -58,23 +128,23 @@ export class OrderValidationUtils {
|
||||
if (!ZeroEx.isValidSignature(orderHash, signedOrder.ecSignature, signedOrder.maker)) {
|
||||
throw new Error(ZeroExError.InvalidSignature);
|
||||
}
|
||||
const unavailableTakerTokenAmount = await this.exchangeWrapper.getUnavailableTakerAmountAsync(orderHash);
|
||||
this.validateRemainingFillAmountNotZeroOrThrow(
|
||||
const unavailableTakerTokenAmount = await this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash);
|
||||
OrderValidationUtils._validateRemainingFillAmountNotZeroOrThrow(
|
||||
signedOrder.takerTokenAmount, unavailableTakerTokenAmount,
|
||||
);
|
||||
if (signedOrder.taker !== constants.NULL_ADDRESS && signedOrder.taker !== takerAddress) {
|
||||
throw new Error(ExchangeContractErrs.TransactionSenderIsNotFillOrderTaker);
|
||||
}
|
||||
this.validateOrderNotExpiredOrThrow(signedOrder.expirationUnixTimestampSec);
|
||||
OrderValidationUtils._validateOrderNotExpiredOrThrow(signedOrder.expirationUnixTimestampSec);
|
||||
const remainingTakerTokenAmount = signedOrder.takerTokenAmount.minus(unavailableTakerTokenAmount);
|
||||
const filledTakerTokenAmount = remainingTakerTokenAmount.lessThan(fillTakerTokenAmount) ?
|
||||
remainingTakerTokenAmount :
|
||||
fillTakerTokenAmount;
|
||||
await this.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
|
||||
await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
|
||||
exchangeTradeEmulator, signedOrder, filledTakerTokenAmount, takerAddress, zrxTokenAddress,
|
||||
);
|
||||
|
||||
const wouldRoundingErrorOccur = await this.exchangeWrapper.isRoundingErrorAsync(
|
||||
const wouldRoundingErrorOccur = await this._exchangeWrapper.isRoundingErrorAsync(
|
||||
filledTakerTokenAmount, signedOrder.takerTokenAmount, signedOrder.makerTokenAmount,
|
||||
);
|
||||
if (wouldRoundingErrorOccur) {
|
||||
@@ -92,75 +162,4 @@ export class OrderValidationUtils {
|
||||
throw new Error(ExchangeContractErrs.InsufficientRemainingFillAmount);
|
||||
}
|
||||
}
|
||||
public async validateCancelOrderThrowIfInvalidAsync(order: Order,
|
||||
cancelTakerTokenAmount: BigNumber,
|
||||
unavailableTakerTokenAmount: BigNumber,
|
||||
): Promise<void> {
|
||||
if (cancelTakerTokenAmount.eq(0)) {
|
||||
throw new Error(ExchangeContractErrs.OrderCancelAmountZero);
|
||||
}
|
||||
if (order.takerTokenAmount.eq(unavailableTakerTokenAmount)) {
|
||||
throw new Error(ExchangeContractErrs.OrderAlreadyCancelledOrFilled);
|
||||
}
|
||||
const currentUnixTimestampSec = utils.getCurrentUnixTimestamp();
|
||||
if (order.expirationUnixTimestampSec.lessThan(currentUnixTimestampSec)) {
|
||||
throw new Error(ExchangeContractErrs.OrderCancelExpired);
|
||||
}
|
||||
}
|
||||
public async validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
|
||||
exchangeTradeEmulator: ExchangeTransferSimulator, signedOrder: SignedOrder,
|
||||
fillTakerTokenAmount: BigNumber, senderAddress: string, zrxTokenAddress: string): Promise<void> {
|
||||
const fillMakerTokenAmount = this.getPartialAmount(
|
||||
fillTakerTokenAmount,
|
||||
signedOrder.takerTokenAmount,
|
||||
signedOrder.makerTokenAmount,
|
||||
);
|
||||
await exchangeTradeEmulator.transferFromAsync(
|
||||
signedOrder.makerTokenAddress, signedOrder.maker, senderAddress, fillMakerTokenAmount,
|
||||
TradeSide.Maker, TransferType.Trade,
|
||||
);
|
||||
await exchangeTradeEmulator.transferFromAsync(
|
||||
signedOrder.takerTokenAddress, senderAddress, signedOrder.maker, fillTakerTokenAmount,
|
||||
TradeSide.Taker, TransferType.Trade,
|
||||
);
|
||||
const makerFeeAmount = this.getPartialAmount(
|
||||
fillTakerTokenAmount,
|
||||
signedOrder.takerTokenAmount,
|
||||
signedOrder.makerFee,
|
||||
);
|
||||
await exchangeTradeEmulator.transferFromAsync(
|
||||
zrxTokenAddress, signedOrder.maker, signedOrder.feeRecipient, makerFeeAmount, TradeSide.Maker,
|
||||
TransferType.Fee,
|
||||
);
|
||||
const takerFeeAmount = this.getPartialAmount(
|
||||
fillTakerTokenAmount,
|
||||
signedOrder.takerTokenAmount,
|
||||
signedOrder.takerFee,
|
||||
);
|
||||
await exchangeTradeEmulator.transferFromAsync(
|
||||
zrxTokenAddress, senderAddress, signedOrder.feeRecipient, takerFeeAmount, TradeSide.Taker,
|
||||
TransferType.Fee,
|
||||
);
|
||||
}
|
||||
private validateRemainingFillAmountNotZeroOrThrow(
|
||||
takerTokenAmount: BigNumber, unavailableTakerTokenAmount: BigNumber,
|
||||
) {
|
||||
if (takerTokenAmount.eq(unavailableTakerTokenAmount)) {
|
||||
throw new Error(ExchangeContractErrs.OrderRemainingFillAmountZero);
|
||||
}
|
||||
}
|
||||
private validateOrderNotExpiredOrThrow(expirationUnixTimestampSec: BigNumber) {
|
||||
const currentUnixTimestampSec = utils.getCurrentUnixTimestamp();
|
||||
if (expirationUnixTimestampSec.lessThan(currentUnixTimestampSec)) {
|
||||
throw new Error(ExchangeContractErrs.OrderFillExpired);
|
||||
}
|
||||
}
|
||||
private getPartialAmount(numerator: BigNumber, denominator: BigNumber,
|
||||
target: BigNumber): BigNumber {
|
||||
const fillMakerTokenAmount = numerator
|
||||
.mul(target)
|
||||
.div(denominator)
|
||||
.round(0);
|
||||
return fillMakerTokenAmount;
|
||||
}
|
||||
}
|
||||
|
@@ -1,4 +1,5 @@
|
||||
import * as ethUtil from 'ethereumjs-util';
|
||||
|
||||
import {ECSignature} from '../types';
|
||||
|
||||
export const signatureUtils = {
|
||||
|
@@ -1,9 +1,10 @@
|
||||
import * as _ from 'lodash';
|
||||
import * as ethABI from 'ethereumjs-abi';
|
||||
import * as ethUtil from 'ethereumjs-util';
|
||||
import {Order, SignedOrder, SolidityTypes} from '../types';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import BN = require('bn.js');
|
||||
import * as ethABI from 'ethereumjs-abi';
|
||||
import * as ethUtil from 'ethereumjs-util';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {Order, SignedOrder, SolidityTypes} from '../types';
|
||||
|
||||
export const utils = {
|
||||
/**
|
||||
@@ -49,7 +50,10 @@ export const utils = {
|
||||
const hashHex = ethUtil.bufferToHex(hashBuff);
|
||||
return hashHex;
|
||||
},
|
||||
getCurrentUnixTimestamp(): BigNumber {
|
||||
return new BigNumber(Date.now() / 1000);
|
||||
getCurrentUnixTimestampSec(): BigNumber {
|
||||
return new BigNumber(Date.now() / 1000).round();
|
||||
},
|
||||
getCurrentUnixTimestampMs(): BigNumber {
|
||||
return new BigNumber(Date.now());
|
||||
},
|
||||
};
|
||||
|
@@ -1,200 +0,0 @@
|
||||
import * as _ from 'lodash';
|
||||
import * as Web3 from 'web3';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import promisify = require('es6-promisify');
|
||||
import {ZeroExError, Artifact, TransactionReceipt} from './types';
|
||||
import {Contract} from './contract';
|
||||
|
||||
interface RawLogEntry {
|
||||
logIndex: string|null;
|
||||
transactionIndex: string|null;
|
||||
transactionHash: string;
|
||||
blockHash: string|null;
|
||||
blockNumber: string|null;
|
||||
address: string;
|
||||
data: string;
|
||||
topics: string[];
|
||||
}
|
||||
|
||||
export class Web3Wrapper {
|
||||
private web3: Web3;
|
||||
private defaults: Partial<Web3.TxData>;
|
||||
private networkIdIfExists?: number;
|
||||
private jsonRpcRequestId: number;
|
||||
constructor(provider: Web3.Provider, defaults?: Partial<Web3.TxData>) {
|
||||
if (_.isUndefined((provider as any).sendAsync)) {
|
||||
// Web3@1.0 provider doesn't support synchronous http requests,
|
||||
// so it only has an async `send` method, instead of a `send` and `sendAsync` in web3@0.x.x`
|
||||
// We re-assign the send method so that Web3@1.0 providers work with 0x.js
|
||||
(provider as any).sendAsync = (provider as any).send;
|
||||
}
|
||||
this.web3 = new Web3();
|
||||
this.web3.setProvider(provider);
|
||||
this.defaults = defaults || {};
|
||||
this.jsonRpcRequestId = 0;
|
||||
}
|
||||
public setProvider(provider: Web3.Provider) {
|
||||
delete this.networkIdIfExists;
|
||||
this.web3.setProvider(provider);
|
||||
}
|
||||
public isAddress(address: string): boolean {
|
||||
return this.web3.isAddress(address);
|
||||
}
|
||||
public async isSenderAddressAvailableAsync(senderAddress: string): Promise<boolean> {
|
||||
const addresses = await this.getAvailableAddressesAsync();
|
||||
return _.includes(addresses, senderAddress);
|
||||
}
|
||||
public async getNodeVersionAsync(): Promise<string> {
|
||||
const nodeVersion = await promisify(this.web3.version.getNode)();
|
||||
return nodeVersion;
|
||||
}
|
||||
public async getTransactionReceiptAsync(txHash: string): Promise<TransactionReceipt> {
|
||||
const transactionReceipt = await promisify(this.web3.eth.getTransactionReceipt)(txHash);
|
||||
transactionReceipt.status = this.normalizeTxReceiptStatus(transactionReceipt.status);
|
||||
return transactionReceipt;
|
||||
}
|
||||
public getCurrentProvider(): Web3.Provider {
|
||||
return this.web3.currentProvider;
|
||||
}
|
||||
public async getNetworkIdIfExistsAsync(): Promise<number|undefined> {
|
||||
if (!_.isUndefined(this.networkIdIfExists)) {
|
||||
return this.networkIdIfExists;
|
||||
}
|
||||
|
||||
try {
|
||||
const networkId = await this.getNetworkAsync();
|
||||
this.networkIdIfExists = Number(networkId);
|
||||
return this.networkIdIfExists;
|
||||
} catch (err) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
public async getContractInstanceFromArtifactAsync<A extends Web3.ContractInstance>(artifact: Artifact,
|
||||
address?: string): Promise<A> {
|
||||
let contractAddress: string;
|
||||
if (_.isUndefined(address)) {
|
||||
const networkIdIfExists = await this.getNetworkIdIfExistsAsync();
|
||||
if (_.isUndefined(networkIdIfExists)) {
|
||||
throw new Error(ZeroExError.NoNetworkId);
|
||||
}
|
||||
if (_.isUndefined(artifact.networks[networkIdIfExists])) {
|
||||
throw new Error(ZeroExError.ContractNotDeployedOnNetwork);
|
||||
}
|
||||
contractAddress = artifact.networks[networkIdIfExists].address.toLowerCase();
|
||||
} else {
|
||||
contractAddress = address;
|
||||
}
|
||||
const doesContractExist = await this.doesContractExistAtAddressAsync(contractAddress);
|
||||
if (!doesContractExist) {
|
||||
throw new Error(ZeroExError.ContractDoesNotExist);
|
||||
}
|
||||
const contractInstance = this.getContractInstance<A>(
|
||||
artifact.abi, contractAddress,
|
||||
);
|
||||
return contractInstance;
|
||||
}
|
||||
public toWei(ethAmount: BigNumber): BigNumber {
|
||||
const balanceWei = this.web3.toWei(ethAmount, 'ether');
|
||||
return balanceWei;
|
||||
}
|
||||
public async getBalanceInWeiAsync(owner: string): Promise<BigNumber> {
|
||||
let balanceInWei = await promisify(this.web3.eth.getBalance)(owner);
|
||||
balanceInWei = new BigNumber(balanceInWei);
|
||||
return balanceInWei;
|
||||
}
|
||||
public async doesContractExistAtAddressAsync(address: string): Promise<boolean> {
|
||||
const code = await promisify(this.web3.eth.getCode)(address);
|
||||
// Regex matches 0x0, 0x00, 0x in order to accommodate poorly implemented clients
|
||||
const codeIsEmpty = /^0x0{0,40}$/i.test(code);
|
||||
return !codeIsEmpty;
|
||||
}
|
||||
public async signTransactionAsync(address: string, message: string): Promise<string> {
|
||||
const signData = await promisify(this.web3.eth.sign)(address, message);
|
||||
return signData;
|
||||
}
|
||||
public async getBlockNumberAsync(): Promise<number> {
|
||||
const blockNumber = await promisify(this.web3.eth.getBlockNumber)();
|
||||
return blockNumber;
|
||||
}
|
||||
public async getBlockAsync(blockParam: string|Web3.BlockParam): Promise<Web3.BlockWithoutTransactionData> {
|
||||
const block = await promisify(this.web3.eth.getBlock)(blockParam);
|
||||
return block;
|
||||
}
|
||||
public async getBlockTimestampAsync(blockParam: string|Web3.BlockParam): Promise<number> {
|
||||
const {timestamp} = await this.getBlockAsync(blockParam);
|
||||
return timestamp;
|
||||
}
|
||||
public async getAvailableAddressesAsync(): Promise<string[]> {
|
||||
const addresses: string[] = await promisify(this.web3.eth.getAccounts)();
|
||||
return addresses;
|
||||
}
|
||||
public async getLogsAsync(filter: Web3.FilterObject): Promise<Web3.LogEntry[]> {
|
||||
let fromBlock = filter.fromBlock;
|
||||
if (_.isNumber(fromBlock)) {
|
||||
fromBlock = this.web3.toHex(fromBlock);
|
||||
}
|
||||
let toBlock = filter.toBlock;
|
||||
if (_.isNumber(toBlock)) {
|
||||
toBlock = this.web3.toHex(toBlock);
|
||||
}
|
||||
const serializedFilter = {
|
||||
...filter,
|
||||
fromBlock,
|
||||
toBlock,
|
||||
};
|
||||
const payload = {
|
||||
jsonrpc: '2.0',
|
||||
id: this.jsonRpcRequestId++,
|
||||
method: 'eth_getLogs',
|
||||
params: [serializedFilter],
|
||||
};
|
||||
const rawLogs = await this.sendRawPayloadAsync<RawLogEntry[]>(payload);
|
||||
const formattedLogs = _.map(rawLogs, this.formatLog.bind(this));
|
||||
return formattedLogs;
|
||||
}
|
||||
private getContractInstance<A extends Web3.ContractInstance>(abi: Web3.ContractAbi, address: string): A {
|
||||
const web3ContractInstance = this.web3.eth.contract(abi).at(address);
|
||||
const contractInstance = new Contract(web3ContractInstance, this.defaults) as any as A;
|
||||
return contractInstance;
|
||||
}
|
||||
private async getNetworkAsync(): Promise<number> {
|
||||
const networkId = await promisify(this.web3.version.getNetwork)();
|
||||
return networkId;
|
||||
}
|
||||
private async sendRawPayloadAsync<A>(payload: Web3.JSONRPCRequestPayload): Promise<A> {
|
||||
const sendAsync = this.web3.currentProvider.sendAsync.bind(this.web3.currentProvider);
|
||||
const response = await promisify(sendAsync)(payload);
|
||||
const result = response.result;
|
||||
return result;
|
||||
}
|
||||
private normalizeTxReceiptStatus(status: undefined|null|string|0|1): null|0|1 {
|
||||
// Transaction status might have four values
|
||||
// undefined - Testrpc and other old clients
|
||||
// null - New clients on old transactions
|
||||
// number - Parity
|
||||
// hex - Geth
|
||||
if (_.isString(status)) {
|
||||
return this.web3.toDecimal(status) as 0|1;
|
||||
} else if (_.isUndefined(status)) {
|
||||
return null;
|
||||
} else {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
private formatLog(rawLog: RawLogEntry): Web3.LogEntry {
|
||||
const formattedLog = {
|
||||
...rawLog,
|
||||
logIndex: this.hexToDecimal(rawLog.logIndex),
|
||||
blockNumber: this.hexToDecimal(rawLog.blockNumber),
|
||||
transactionIndex: this.hexToDecimal(rawLog.transactionIndex),
|
||||
};
|
||||
return formattedLog;
|
||||
}
|
||||
private hexToDecimal(hex: string|null): number|null {
|
||||
if (_.isNull(hex)) {
|
||||
return null;
|
||||
}
|
||||
const decimal = this.web3.toDecimal(hex);
|
||||
return decimal;
|
||||
}
|
||||
}
|
@@ -1,22 +1,27 @@
|
||||
import * as _ from 'lodash';
|
||||
import * as chai from 'chai';
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import 'mocha';
|
||||
import {BlockchainLifecycle} from '@0xproject/dev-utils';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as chai from 'chai';
|
||||
import * as _ from 'lodash';
|
||||
import 'mocha';
|
||||
import * as Sinon from 'sinon';
|
||||
import {ZeroEx, Order, ZeroExError, LogWithDecodedArgs, ApprovalContractEventArgs, TokenEvents} from '../src';
|
||||
|
||||
import {ApprovalContractEventArgs, LogWithDecodedArgs, Order, TokenEvents, ZeroEx} from '../src';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
import {TokenUtils} from './utils/token_utils';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
|
||||
|
||||
const blockchainLifecycle = new BlockchainLifecycle();
|
||||
const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL);
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
|
||||
describe('ZeroEx library', () => {
|
||||
const web3 = web3Factory.create();
|
||||
const zeroEx = new ZeroEx(web3.currentProvider);
|
||||
const config = {
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
const zeroEx = new ZeroEx(web3.currentProvider, config);
|
||||
describe('#setProvider', () => {
|
||||
it('overrides provider in nested web3s and invalidates contractInstances', async () => {
|
||||
// Instantiate the contract instances with the current provider
|
||||
@@ -28,7 +33,7 @@ describe('ZeroEx library', () => {
|
||||
const newProvider = web3Factory.getRpcProvider();
|
||||
// Add property to newProvider so that we can differentiate it from old provider
|
||||
(newProvider as any).zeroExTestId = 1;
|
||||
await zeroEx.setProviderAsync(newProvider);
|
||||
zeroEx.setProvider(newProvider, constants.TESTRPC_NETWORK_ID);
|
||||
|
||||
// Check that contractInstances with old provider are removed after provider update
|
||||
expect((zeroEx.exchange as any)._exchangeContractIfExists).to.be.undefined();
|
||||
@@ -36,11 +41,11 @@ describe('ZeroEx library', () => {
|
||||
|
||||
// Check that all nested web3 wrapper instances return the updated provider
|
||||
const nestedWeb3WrapperProvider = (zeroEx as any)._web3Wrapper.getCurrentProvider();
|
||||
expect((nestedWeb3WrapperProvider as any).zeroExTestId).to.be.a('number');
|
||||
expect((nestedWeb3WrapperProvider).zeroExTestId).to.be.a('number');
|
||||
const exchangeWeb3WrapperProvider = (zeroEx.exchange as any)._web3Wrapper.getCurrentProvider();
|
||||
expect((exchangeWeb3WrapperProvider as any).zeroExTestId).to.be.a('number');
|
||||
expect((exchangeWeb3WrapperProvider).zeroExTestId).to.be.a('number');
|
||||
const tokenRegistryWeb3WrapperProvider = (zeroEx.tokenRegistry as any)._web3Wrapper.getCurrentProvider();
|
||||
expect((tokenRegistryWeb3WrapperProvider as any).zeroExTestId).to.be.a('number');
|
||||
expect((tokenRegistryWeb3WrapperProvider).zeroExTestId).to.be.a('number');
|
||||
});
|
||||
});
|
||||
describe('#isValidSignature', () => {
|
||||
@@ -77,9 +82,9 @@ describe('ZeroEx library', () => {
|
||||
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();
|
||||
const isValidSignatureOnContract = await (zeroEx.exchange as any)
|
||||
._isValidSignatureUsingContractCallAsync(dataHex, signature, address);
|
||||
return expect(isValidSignatureOnContract).to.be.true();
|
||||
return expect(
|
||||
(zeroEx.exchange as any)._isValidSignatureUsingContractCallAsync(dataHex, signature, address),
|
||||
).to.become(true);
|
||||
});
|
||||
});
|
||||
describe('#generateSalt', () => {
|
||||
@@ -109,6 +114,12 @@ describe('ZeroEx library', () => {
|
||||
});
|
||||
});
|
||||
describe('#toUnitAmount', () => {
|
||||
it('should throw if invalid baseUnit amount supplied as argument', () => {
|
||||
const invalidBaseUnitAmount = new BigNumber(1000000000.4);
|
||||
const decimals = 6;
|
||||
expect(() => ZeroEx.toUnitAmount(invalidBaseUnitAmount, decimals))
|
||||
.to.throw('amount should be in baseUnits (no decimals), found value: 1000000000.4');
|
||||
});
|
||||
it('Should return the expected unit amount for the decimals passed in', () => {
|
||||
const baseUnitAmount = new BigNumber(1000000000);
|
||||
const decimals = 6;
|
||||
@@ -125,6 +136,12 @@ describe('ZeroEx library', () => {
|
||||
const expectedUnitAmount = new BigNumber(1000000000);
|
||||
expect(baseUnitAmount).to.be.bignumber.equal(expectedUnitAmount);
|
||||
});
|
||||
it('should throw if unitAmount has more decimals then specified as the max decimal precision', () => {
|
||||
const unitAmount = new BigNumber(0.823091);
|
||||
const decimals = 5;
|
||||
expect(() => ZeroEx.toBaseUnitAmount(unitAmount, decimals))
|
||||
.to.throw('Invalid unit amount: 0.823091 - Too many decimal places');
|
||||
});
|
||||
});
|
||||
describe('#getOrderHashHex', () => {
|
||||
const expectedOrderHash = '0x39da987067a3c9e5f1617694f1301326ba8c8b0498ebef5df4863bed394e3c83';
|
||||
@@ -147,6 +164,15 @@ describe('ZeroEx library', () => {
|
||||
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,
|
||||
};
|
||||
// tslint:disable-next-line:max-line-length
|
||||
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[] = [];
|
||||
@@ -220,7 +246,7 @@ describe('ZeroEx library', () => {
|
||||
const tokens = await zeroEx.tokenRegistry.getTokensAsync();
|
||||
const tokenUtils = new TokenUtils(tokens);
|
||||
const zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address;
|
||||
const proxyAddress = await zeroEx.proxy.getContractAddressAsync();
|
||||
const proxyAddress = zeroEx.proxy.getContractAddress();
|
||||
const txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(zrxTokenAddress, coinbase);
|
||||
const txReceiptWithDecodedLogs = await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
const log = txReceiptWithDecodedLogs.logs[0] as LogWithDecodedArgs<ApprovalContractEventArgs>;
|
||||
@@ -232,28 +258,21 @@ describe('ZeroEx library', () => {
|
||||
});
|
||||
describe('#config', () => {
|
||||
it('allows to specify exchange contract address', async () => {
|
||||
const config = {
|
||||
const zeroExConfig = {
|
||||
exchangeContractAddress: ZeroEx.NULL_ADDRESS,
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
const zeroExWithWrongExchangeAddress = new ZeroEx(web3.currentProvider, config);
|
||||
return expect(zeroExWithWrongExchangeAddress.exchange.getContractAddressAsync())
|
||||
.to.be.rejectedWith(ZeroExError.ContractDoesNotExist);
|
||||
});
|
||||
it('allows to specify ether token contract address', async () => {
|
||||
const config = {
|
||||
etherTokenContractAddress: ZeroEx.NULL_ADDRESS,
|
||||
};
|
||||
const zeroExWithWrongEtherTokenAddress = new ZeroEx(web3.currentProvider, config);
|
||||
return expect(zeroExWithWrongEtherTokenAddress.etherToken.getContractAddressAsync())
|
||||
.to.be.rejectedWith(ZeroExError.ContractDoesNotExist);
|
||||
const zeroExWithWrongExchangeAddress = new ZeroEx(web3.currentProvider, zeroExConfig);
|
||||
expect(zeroExWithWrongExchangeAddress.exchange.getContractAddress()).to.be.equal(ZeroEx.NULL_ADDRESS);
|
||||
});
|
||||
it('allows to specify token registry token contract address', async () => {
|
||||
const config = {
|
||||
const zeroExConfig = {
|
||||
tokenRegistryContractAddress: ZeroEx.NULL_ADDRESS,
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
const zeroExWithWrongTokenRegistryAddress = new ZeroEx(web3.currentProvider, config);
|
||||
return expect(zeroExWithWrongTokenRegistryAddress.tokenRegistry.getContractAddressAsync())
|
||||
.to.be.rejectedWith(ZeroExError.ContractDoesNotExist);
|
||||
const zeroExWithWrongTokenRegistryAddress = new ZeroEx(web3.currentProvider, zeroExConfig);
|
||||
expect(zeroExWithWrongTokenRegistryAddress.tokenRegistry.getContractAddress())
|
||||
.to.be.equal(ZeroEx.NULL_ADDRESS);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -1,12 +1,12 @@
|
||||
import * as fs from 'fs';
|
||||
import * as chai from 'chai';
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import HDWalletProvider = require('truffle-hdwallet-provider');
|
||||
|
||||
import {ZeroEx} from '../src';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
|
||||
// Those tests are slower cause they're talking to a remote node
|
||||
const TIMEOUT = 10000;
|
||||
@@ -18,15 +18,18 @@ describe('Artifacts', () => {
|
||||
const packageJSON = JSON.parse(packageJSONContent);
|
||||
const mnemonic = packageJSON.config.mnemonic;
|
||||
const web3Provider = new HDWalletProvider(mnemonic, kovanRpcUrl);
|
||||
const zeroEx = new ZeroEx(web3Provider);
|
||||
const config = {
|
||||
networkId: constants.KOVAN_NETWORK_ID,
|
||||
};
|
||||
const zeroEx = new ZeroEx(web3Provider, config);
|
||||
it('token registry contract is deployed', async () => {
|
||||
await (zeroEx.tokenRegistry as any)._getTokenRegistryContractAsync();
|
||||
}).timeout(TIMEOUT);
|
||||
it('proxy contract is deployed', async () => {
|
||||
await (zeroEx.token as any)._getTokenTransferProxyAddressAsync();
|
||||
await (zeroEx.proxy as any)._getTokenTransferProxyContractAsync();
|
||||
}).timeout(TIMEOUT);
|
||||
it('exchange contract is deployed', async () => {
|
||||
await zeroEx.exchange.getContractAddressAsync();
|
||||
await (zeroEx.exchange as any)._getExchangeContractAsync();
|
||||
}).timeout(TIMEOUT);
|
||||
});
|
||||
describe('contracts are deployed on ropsten', () => {
|
||||
@@ -35,15 +38,18 @@ describe('Artifacts', () => {
|
||||
const packageJSON = JSON.parse(packageJSONContent);
|
||||
const mnemonic = packageJSON.config.mnemonic;
|
||||
const web3Provider = new HDWalletProvider(mnemonic, ropstenRpcUrl);
|
||||
const zeroEx = new ZeroEx(web3Provider);
|
||||
const config = {
|
||||
networkId: constants.ROPSTEN_NETWORK_ID,
|
||||
};
|
||||
const zeroEx = new ZeroEx(web3Provider, config);
|
||||
it('token registry contract is deployed', async () => {
|
||||
await (zeroEx.tokenRegistry as any)._getTokenRegistryContractAsync();
|
||||
}).timeout(TIMEOUT);
|
||||
it('proxy contract is deployed', async () => {
|
||||
await (zeroEx.token as any)._getTokenTransferProxyAddressAsync();
|
||||
await (zeroEx.proxy as any)._getTokenTransferProxyContractAsync();
|
||||
}).timeout(TIMEOUT);
|
||||
it('exchange contract is deployed', async () => {
|
||||
await zeroEx.exchange.getContractAddressAsync();
|
||||
await (zeroEx.exchange as any)._getExchangeContractAsync();
|
||||
}).timeout(TIMEOUT);
|
||||
});
|
||||
});
|
||||
|
@@ -1,14 +1,20 @@
|
||||
import * as chai from 'chai';
|
||||
import 'mocha';
|
||||
|
||||
import {ZeroEx} from '../src';
|
||||
import {assert} from '../src/utils/assert';
|
||||
|
||||
import {constants} from './utils/constants';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
|
||||
const expect = chai.expect;
|
||||
|
||||
describe('Assertion library', () => {
|
||||
const web3 = web3Factory.create();
|
||||
const zeroEx = new ZeroEx(web3.currentProvider);
|
||||
const config = {
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
const zeroEx = new ZeroEx(web3.currentProvider, config);
|
||||
describe('#isSenderAddressHexAsync', () => {
|
||||
it('throws when address is invalid', async () => {
|
||||
const address = '0xdeadbeef';
|
||||
|
@@ -1,42 +1,69 @@
|
||||
import 'mocha';
|
||||
import * as chai from 'chai';
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import * as Web3 from 'web3';
|
||||
import {BlockchainLifecycle} from '@0xproject/dev-utils';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as chai from 'chai';
|
||||
import 'mocha';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {
|
||||
ApprovalContractEventArgs,
|
||||
BlockParamLiteral,
|
||||
BlockRange,
|
||||
DecodedLogEvent,
|
||||
DepositContractEventArgs,
|
||||
EtherTokenEvents,
|
||||
Token,
|
||||
TransferContractEventArgs,
|
||||
WithdrawalContractEventArgs,
|
||||
ZeroEx,
|
||||
ZeroExError,
|
||||
} from '../src';
|
||||
import {artifacts} from '../src/artifacts';
|
||||
import {DoneCallback} from '../src/types';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
import {TokenUtils} from './utils/token_utils';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
import {ZeroEx, ZeroExError} from '../src';
|
||||
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
const blockchainLifecycle = new BlockchainLifecycle();
|
||||
const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL);
|
||||
|
||||
// Since the address depositing/withdrawing ETH/WETH also needs to pay gas costs for the transaction,
|
||||
// a small amount of ETH will be used to pay this gas cost. We therefore check that the difference between
|
||||
// the expected balance and actual balance (given the amount of ETH deposited), only deviates by the amount
|
||||
// required to pay gas costs.
|
||||
const MAX_REASONABLE_GAS_COST_IN_WEI = 62237;
|
||||
const MAX_REASONABLE_GAS_COST_IN_WEI = 62517;
|
||||
|
||||
describe('EtherTokenWrapper', () => {
|
||||
let web3: Web3;
|
||||
let zeroEx: ZeroEx;
|
||||
let tokens: Token[];
|
||||
let userAddresses: string[];
|
||||
let addressWithETH: string;
|
||||
let wethContractAddress: string;
|
||||
let depositWeiAmount: BigNumber;
|
||||
let decimalPlaces: number;
|
||||
let addressWithoutFunds: string;
|
||||
const gasPrice = new BigNumber(1);
|
||||
const zeroExConfig = {
|
||||
gasPrice,
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
const transferAmount = new BigNumber(42);
|
||||
const allowanceAmount = new BigNumber(42);
|
||||
const depositAmount = new BigNumber(42);
|
||||
const withdrawalAmount = new BigNumber(42);
|
||||
before(async () => {
|
||||
web3 = web3Factory.create();
|
||||
zeroEx = new ZeroEx(web3.currentProvider, zeroExConfig);
|
||||
tokens = await zeroEx.tokenRegistry.getTokensAsync();
|
||||
userAddresses = await zeroEx.getAvailableAddressesAsync();
|
||||
addressWithETH = userAddresses[0];
|
||||
wethContractAddress = await zeroEx.etherToken.getContractAddressAsync();
|
||||
wethContractAddress = (zeroEx.etherToken as any)._getContractAddress(artifacts.EtherTokenArtifact);
|
||||
depositWeiAmount = (zeroEx as any)._web3Wrapper.toWei(new BigNumber(5));
|
||||
decimalPlaces = 7;
|
||||
addressWithoutFunds = userAddresses[1];
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await blockchainLifecycle.startAsync();
|
||||
@@ -51,7 +78,7 @@ describe('EtherTokenWrapper', () => {
|
||||
expect(preETHBalance).to.be.bignumber.gt(0);
|
||||
expect(preWETHBalance).to.be.bignumber.equal(0);
|
||||
|
||||
const txHash = await zeroEx.etherToken.depositAsync(depositWeiAmount, addressWithETH);
|
||||
const txHash = await zeroEx.etherToken.depositAsync(wethContractAddress, depositWeiAmount, addressWithETH);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
|
||||
const postETHBalanceInWei = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH);
|
||||
@@ -69,7 +96,7 @@ describe('EtherTokenWrapper', () => {
|
||||
const overETHBalanceinWei = preETHBalance.add(extraETHBalance);
|
||||
|
||||
return expect(
|
||||
zeroEx.etherToken.depositAsync(overETHBalanceinWei, addressWithETH),
|
||||
zeroEx.etherToken.depositAsync(wethContractAddress, overETHBalanceinWei, addressWithETH),
|
||||
).to.be.rejectedWith(ZeroExError.InsufficientEthBalanceForDeposit);
|
||||
});
|
||||
});
|
||||
@@ -77,7 +104,7 @@ describe('EtherTokenWrapper', () => {
|
||||
it('should successfully withdraw ETH in return for Wrapped ETH tokens', async () => {
|
||||
const ETHBalanceInWei = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH);
|
||||
|
||||
await zeroEx.etherToken.depositAsync(depositWeiAmount, addressWithETH);
|
||||
await zeroEx.etherToken.depositAsync(wethContractAddress, depositWeiAmount, addressWithETH);
|
||||
|
||||
const expectedPreETHBalance = ETHBalanceInWei.minus(depositWeiAmount);
|
||||
const preETHBalance = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH);
|
||||
@@ -86,7 +113,7 @@ describe('EtherTokenWrapper', () => {
|
||||
expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI);
|
||||
expect(preWETHBalance).to.be.bignumber.equal(depositWeiAmount);
|
||||
|
||||
const txHash = await zeroEx.etherToken.withdrawAsync(depositWeiAmount, addressWithETH);
|
||||
const txHash = await zeroEx.etherToken.withdrawAsync(wethContractAddress, depositWeiAmount, addressWithETH);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
|
||||
const postETHBalance = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH);
|
||||
@@ -104,8 +131,213 @@ describe('EtherTokenWrapper', () => {
|
||||
const overWETHBalance = preWETHBalance.add(999999999);
|
||||
|
||||
return expect(
|
||||
zeroEx.etherToken.withdrawAsync(overWETHBalance, addressWithETH),
|
||||
zeroEx.etherToken.withdrawAsync(wethContractAddress, overWETHBalance, addressWithETH),
|
||||
).to.be.rejectedWith(ZeroExError.InsufficientWEthBalanceForWithdrawal);
|
||||
});
|
||||
});
|
||||
describe('#subscribe', () => {
|
||||
const indexFilterValues = {};
|
||||
let etherTokenAddress: string;
|
||||
before(() => {
|
||||
const tokenUtils = new TokenUtils(tokens);
|
||||
const etherToken = tokenUtils.getWethTokenOrThrow();
|
||||
etherTokenAddress = etherToken.address;
|
||||
});
|
||||
afterEach(() => {
|
||||
zeroEx.etherToken.unsubscribeAll();
|
||||
});
|
||||
// Hack: Mocha does not allow a test to be both async and have a `done` callback
|
||||
// Since we need to await the receipt of the event in the `subscribe` callback,
|
||||
// we do need both. A hack is to make the top-level async fn w/ a done callback and then
|
||||
// wrap the rest of the test in an async block
|
||||
// Source: https://github.com/mochajs/mocha/issues/2407
|
||||
it('Should receive the Transfer event when tokens are transfered', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<TransferContractEventArgs>) => {
|
||||
expect(err).to.be.null();
|
||||
expect(logEvent).to.not.be.undefined();
|
||||
expect(logEvent.isRemoved).to.be.false();
|
||||
expect(logEvent.log.logIndex).to.be.equal(0);
|
||||
expect(logEvent.log.transactionIndex).to.be.equal(0);
|
||||
expect(logEvent.log.blockNumber).to.be.a('number');
|
||||
const args = logEvent.log.args;
|
||||
expect(args._from).to.be.equal(addressWithETH);
|
||||
expect(args._to).to.be.equal(addressWithoutFunds);
|
||||
expect(args._value).to.be.bignumber.equal(transferAmount);
|
||||
done();
|
||||
};
|
||||
await zeroEx.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH);
|
||||
zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Transfer, indexFilterValues, callback);
|
||||
await zeroEx.token.transferAsync(
|
||||
etherTokenAddress, addressWithETH, addressWithoutFunds, transferAmount,
|
||||
);
|
||||
})().catch(done);
|
||||
});
|
||||
it('Should receive the Approval event when allowance is being set', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
|
||||
expect(err).to.be.null();
|
||||
expect(logEvent).to.not.be.undefined();
|
||||
expect(logEvent.isRemoved).to.be.false();
|
||||
const args = logEvent.log.args;
|
||||
expect(args._owner).to.be.equal(addressWithETH);
|
||||
expect(args._spender).to.be.equal(addressWithoutFunds);
|
||||
expect(args._value).to.be.bignumber.equal(allowanceAmount);
|
||||
done();
|
||||
};
|
||||
zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Approval, indexFilterValues, callback);
|
||||
await zeroEx.token.setAllowanceAsync(
|
||||
etherTokenAddress, addressWithETH, addressWithoutFunds, allowanceAmount,
|
||||
);
|
||||
})().catch(done);
|
||||
});
|
||||
it('Should receive the Deposit event when ether is being deposited', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<DepositContractEventArgs>) => {
|
||||
expect(err).to.be.null();
|
||||
expect(logEvent).to.not.be.undefined();
|
||||
expect(logEvent.isRemoved).to.be.false();
|
||||
const args = logEvent.log.args;
|
||||
expect(args._owner).to.be.equal(addressWithETH);
|
||||
expect(args._value).to.be.bignumber.equal(depositAmount);
|
||||
done();
|
||||
};
|
||||
zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Deposit, indexFilterValues, callback);
|
||||
await zeroEx.etherToken.depositAsync(
|
||||
etherTokenAddress, depositAmount, addressWithETH,
|
||||
);
|
||||
})().catch(done);
|
||||
});
|
||||
it('Should receive the Withdrawal event when ether is being withdrawn', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<WithdrawalContractEventArgs>) => {
|
||||
expect(err).to.be.null();
|
||||
expect(logEvent).to.not.be.undefined();
|
||||
expect(logEvent.isRemoved).to.be.false();
|
||||
const args = logEvent.log.args;
|
||||
expect(args._owner).to.be.equal(addressWithETH);
|
||||
expect(args._value).to.be.bignumber.equal(depositAmount);
|
||||
done();
|
||||
};
|
||||
await zeroEx.etherToken.depositAsync(
|
||||
etherTokenAddress, depositAmount, addressWithETH,
|
||||
);
|
||||
zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Withdrawal, indexFilterValues, callback);
|
||||
await zeroEx.etherToken.withdrawAsync(
|
||||
etherTokenAddress, withdrawalAmount, addressWithETH,
|
||||
);
|
||||
})().catch(done);
|
||||
});
|
||||
it('should cancel outstanding subscriptions when ZeroEx.setProvider is called', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callbackNeverToBeCalled = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
|
||||
done(new Error('Expected this subscription to have been cancelled'));
|
||||
};
|
||||
zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Transfer, indexFilterValues, callbackNeverToBeCalled,
|
||||
);
|
||||
const callbackToBeCalled = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
|
||||
done();
|
||||
};
|
||||
const newProvider = web3Factory.getRpcProvider();
|
||||
zeroEx.setProvider(newProvider, constants.TESTRPC_NETWORK_ID);
|
||||
await zeroEx.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH);
|
||||
zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Transfer, indexFilterValues, callbackToBeCalled,
|
||||
);
|
||||
await zeroEx.token.transferAsync(
|
||||
etherTokenAddress, addressWithETH, addressWithoutFunds, transferAmount,
|
||||
);
|
||||
})().catch(done);
|
||||
});
|
||||
it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callbackNeverToBeCalled = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
|
||||
done(new Error('Expected this subscription to have been cancelled'));
|
||||
};
|
||||
await zeroEx.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH);
|
||||
const subscriptionToken = zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Transfer, indexFilterValues, callbackNeverToBeCalled);
|
||||
zeroEx.etherToken.unsubscribe(subscriptionToken);
|
||||
await zeroEx.token.transferAsync(
|
||||
etherTokenAddress, addressWithETH, addressWithoutFunds, transferAmount,
|
||||
);
|
||||
done();
|
||||
})().catch(done);
|
||||
});
|
||||
});
|
||||
describe('#getLogsAsync', () => {
|
||||
let etherTokenAddress: string;
|
||||
let tokenTransferProxyAddress: string;
|
||||
const blockRange: BlockRange = {
|
||||
fromBlock: 0,
|
||||
toBlock: BlockParamLiteral.Latest,
|
||||
};
|
||||
let txHash: string;
|
||||
before(() => {
|
||||
addressWithETH = userAddresses[0];
|
||||
const tokenUtils = new TokenUtils(tokens);
|
||||
const etherToken = tokenUtils.getWethTokenOrThrow();
|
||||
etherTokenAddress = etherToken.address;
|
||||
tokenTransferProxyAddress = zeroEx.proxy.getContractAddress();
|
||||
});
|
||||
it('should get logs with decoded args emitted by Approval', async () => {
|
||||
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
const eventName = EtherTokenEvents.Approval;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.etherToken.getLogsAsync<ApprovalContractEventArgs>(
|
||||
etherTokenAddress, eventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(1);
|
||||
const args = logs[0].args;
|
||||
expect(logs[0].event).to.be.equal(eventName);
|
||||
expect(args._owner).to.be.equal(addressWithETH);
|
||||
expect(args._spender).to.be.equal(tokenTransferProxyAddress);
|
||||
expect(args._value).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
|
||||
});
|
||||
it('should get logs with decoded args emitted by Deposit', async () => {
|
||||
await zeroEx.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH);
|
||||
const eventName = EtherTokenEvents.Deposit;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.etherToken.getLogsAsync<DepositContractEventArgs>(
|
||||
etherTokenAddress, eventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(1);
|
||||
const args = logs[0].args;
|
||||
expect(logs[0].event).to.be.equal(eventName);
|
||||
expect(args._owner).to.be.equal(addressWithETH);
|
||||
expect(args._value).to.be.bignumber.equal(depositAmount);
|
||||
});
|
||||
it('should only get the logs with the correct event name', async () => {
|
||||
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
const differentEventName = EtherTokenEvents.Transfer;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.etherToken.getLogsAsync(
|
||||
etherTokenAddress, differentEventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(0);
|
||||
});
|
||||
it('should only get the logs with the correct indexed fields', async () => {
|
||||
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithoutFunds);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
const eventName = EtherTokenEvents.Approval;
|
||||
const indexFilterValues = {
|
||||
_owner: addressWithETH,
|
||||
};
|
||||
const logs = await zeroEx.etherToken.getLogsAsync<ApprovalContractEventArgs>(
|
||||
etherTokenAddress, eventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(1);
|
||||
const args = logs[0].args;
|
||||
expect(args._owner).to.be.equal(addressWithETH);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -1,19 +1,18 @@
|
||||
import 'mocha';
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import * as chai from 'chai';
|
||||
import * as _ from 'lodash';
|
||||
import 'mocha';
|
||||
import * as Sinon from 'sinon';
|
||||
import * as Web3 from 'web3';
|
||||
import BigNumber from 'bignumber.js';
|
||||
|
||||
import {
|
||||
LogEvent,
|
||||
} from '../src';
|
||||
import {EventWatcher} from '../src/order_watcher/event_watcher';
|
||||
import {DoneCallback} from '../src/types';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
import {Web3Wrapper} from '../src/web3_wrapper';
|
||||
import {EventWatcher} from '../src/order_watcher/event_watcher';
|
||||
import {
|
||||
ZeroEx,
|
||||
LogEvent,
|
||||
DecodedLogEvent,
|
||||
} from '../src';
|
||||
import {DoneCallback} from '../src/types';
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
@@ -23,7 +22,6 @@ describe('EventWatcher', () => {
|
||||
let stubs: Sinon.SinonStub[] = [];
|
||||
let eventWatcher: EventWatcher;
|
||||
let web3Wrapper: Web3Wrapper;
|
||||
const numConfirmations = 0;
|
||||
const logA: Web3.LogEntry = {
|
||||
address: '0x71d271f8b14adef568f8f28f1587ce7271ac4ca5',
|
||||
blockHash: null,
|
||||
|
@@ -1,19 +1,25 @@
|
||||
import * as chai from 'chai';
|
||||
import {BlockchainLifecycle} from '@0xproject/dev-utils';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
import {ZeroEx, ExchangeContractErrs, Token} from '../src';
|
||||
import {TradeSide, TransferType} from '../src/types';
|
||||
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
|
||||
import * as chai from 'chai';
|
||||
|
||||
import {ExchangeContractErrs, Token, ZeroEx} from '../src';
|
||||
import {BlockParamLiteral, TradeSide, TransferType} from '../src/types';
|
||||
import {ExchangeTransferSimulator} from '../src/utils/exchange_transfer_simulator';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
const blockchainLifecycle = new BlockchainLifecycle();
|
||||
const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL);
|
||||
|
||||
describe('ExchangeTransferSimulator', () => {
|
||||
const web3 = web3Factory.create();
|
||||
const zeroEx = new ZeroEx(web3.currentProvider);
|
||||
const config = {
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
const zeroEx = new ZeroEx(web3.currentProvider, config);
|
||||
const transferAmount = new BigNumber(5);
|
||||
let userAddresses: string[];
|
||||
let tokens: Token[];
|
||||
@@ -37,7 +43,7 @@ describe('ExchangeTransferSimulator', () => {
|
||||
});
|
||||
describe('#transferFromAsync', () => {
|
||||
beforeEach(() => {
|
||||
exchangeTransferSimulator = new ExchangeTransferSimulator(zeroEx.token);
|
||||
exchangeTransferSimulator = new ExchangeTransferSimulator(zeroEx.token, BlockParamLiteral.Latest);
|
||||
});
|
||||
it('throws if the user doesn\'t have enough allowance', async () => {
|
||||
return expect(exchangeTransferSimulator.transferFromAsync(
|
||||
@@ -59,7 +65,7 @@ describe('ExchangeTransferSimulator', () => {
|
||||
await exchangeTransferSimulator.transferFromAsync(
|
||||
exampleTokenAddress, sender, recipient, transferAmount, TradeSide.Taker, TransferType.Trade,
|
||||
);
|
||||
const store = (exchangeTransferSimulator as any).store;
|
||||
const store = (exchangeTransferSimulator as any)._store;
|
||||
const senderBalance = await store.getBalanceAsync(exampleTokenAddress, sender);
|
||||
const recipientBalance = await store.getBalanceAsync(exampleTokenAddress, recipient);
|
||||
const senderProxyAllowance = await store.getProxyAllowanceAsync(exampleTokenAddress, sender);
|
||||
@@ -75,7 +81,7 @@ describe('ExchangeTransferSimulator', () => {
|
||||
await exchangeTransferSimulator.transferFromAsync(
|
||||
exampleTokenAddress, sender, recipient, transferAmount, TradeSide.Taker, TransferType.Trade,
|
||||
);
|
||||
const store = (exchangeTransferSimulator as any).store;
|
||||
const store = (exchangeTransferSimulator as any)._store;
|
||||
const senderBalance = await store.getBalanceAsync(exampleTokenAddress, sender);
|
||||
const recipientBalance = await store.getBalanceAsync(exampleTokenAddress, recipient);
|
||||
const senderProxyAllowance = await store.getProxyAllowanceAsync(exampleTokenAddress, sender);
|
||||
|
@@ -1,31 +1,33 @@
|
||||
import 'mocha';
|
||||
import * as chai from 'chai';
|
||||
import * as Web3 from 'web3';
|
||||
import {BlockchainLifecycle} from '@0xproject/dev-utils';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
|
||||
import * as chai from 'chai';
|
||||
import 'mocha';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {
|
||||
ZeroEx,
|
||||
Token,
|
||||
SignedOrder,
|
||||
SubscriptionOpts,
|
||||
ExchangeEvents,
|
||||
BlockRange,
|
||||
DecodedLogEvent,
|
||||
ExchangeContractErrs,
|
||||
ExchangeEvents,
|
||||
LogCancelContractEventArgs,
|
||||
LogFillContractEventArgs,
|
||||
OrderCancellationRequest,
|
||||
OrderFillRequest,
|
||||
LogFillContractEventArgs,
|
||||
LogCancelContractEventArgs,
|
||||
LogEvent,
|
||||
DecodedLogEvent,
|
||||
SignedOrder,
|
||||
Token,
|
||||
ZeroEx,
|
||||
} from '../src';
|
||||
import {DoneCallback, BlockParamLiteral} from '../src/types';
|
||||
import {BlockParamLiteral, DoneCallback} from '../src/types';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
import {FillScenarios} from './utils/fill_scenarios';
|
||||
import {TokenUtils} from './utils/token_utils';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
const blockchainLifecycle = new BlockchainLifecycle();
|
||||
const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL);
|
||||
|
||||
const NON_EXISTENT_ORDER_HASH = '0x79370342234e7acd6bbeac335bd3bb1d368383294b64b8160a00f4060e4d3777';
|
||||
|
||||
@@ -38,15 +40,19 @@ describe('ExchangeWrapper', () => {
|
||||
let zrxTokenAddress: string;
|
||||
let fillScenarios: FillScenarios;
|
||||
let exchangeContractAddress: string;
|
||||
const config = {
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
before(async () => {
|
||||
web3 = web3Factory.create();
|
||||
zeroEx = new ZeroEx(web3.currentProvider);
|
||||
exchangeContractAddress = await zeroEx.exchange.getContractAddressAsync();
|
||||
zeroEx = new ZeroEx(web3.currentProvider, config);
|
||||
exchangeContractAddress = zeroEx.exchange.getContractAddress();
|
||||
userAddresses = await zeroEx.getAvailableAddressesAsync();
|
||||
tokens = await zeroEx.tokenRegistry.getTokensAsync();
|
||||
tokenUtils = new TokenUtils(tokens);
|
||||
zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address;
|
||||
fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress);
|
||||
await fillScenarios.initTokenBalancesAsync();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await blockchainLifecycle.startAsync();
|
||||
@@ -65,7 +71,7 @@ describe('ExchangeWrapper', () => {
|
||||
before(async () => {
|
||||
[coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses;
|
||||
tokens = await zeroEx.tokenRegistry.getTokensAsync();
|
||||
const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens();
|
||||
const [makerToken, takerToken] = tokenUtils.getDummyTokens();
|
||||
makerTokenAddress = makerToken.address;
|
||||
takerTokenAddress = takerToken.address;
|
||||
});
|
||||
@@ -195,7 +201,7 @@ describe('ExchangeWrapper', () => {
|
||||
before(async () => {
|
||||
[coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses;
|
||||
tokens = await zeroEx.tokenRegistry.getTokensAsync();
|
||||
const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens();
|
||||
const [makerToken, takerToken] = tokenUtils.getDummyTokens();
|
||||
makerTokenAddress = makerToken.address;
|
||||
takerTokenAddress = takerToken.address;
|
||||
});
|
||||
@@ -430,7 +436,7 @@ describe('ExchangeWrapper', () => {
|
||||
const cancelAmount = new BigNumber(3);
|
||||
beforeEach(async () => {
|
||||
[coinbase, makerAddress, takerAddress] = userAddresses;
|
||||
const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens();
|
||||
const [makerToken, takerToken] = tokenUtils.getDummyTokens();
|
||||
makerTokenAddress = makerToken.address;
|
||||
takerTokenAddress = takerToken.address;
|
||||
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
|
||||
@@ -551,7 +557,8 @@ describe('ExchangeWrapper', () => {
|
||||
let orderHash: string;
|
||||
before(() => {
|
||||
takerAddress = userAddresses[1];
|
||||
const [makerToken, takerToken] = tokens;
|
||||
tokenUtils = new TokenUtils(tokens);
|
||||
const [makerToken, takerToken] = tokenUtils.getDummyTokens();
|
||||
makerTokenAddress = makerToken.address;
|
||||
takerTokenAddress = takerToken.address;
|
||||
});
|
||||
@@ -613,7 +620,7 @@ describe('ExchangeWrapper', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('#subscribeAsync', () => {
|
||||
describe('#subscribe', () => {
|
||||
const indexFilterValues = {};
|
||||
const shouldThrowOnInsufficientBalanceOrAllowance = true;
|
||||
let makerTokenAddress: string;
|
||||
@@ -627,7 +634,7 @@ describe('ExchangeWrapper', () => {
|
||||
const cancelTakerAmountInBaseUnits = new BigNumber(1);
|
||||
before(() => {
|
||||
[coinbase, makerAddress, takerAddress] = userAddresses;
|
||||
const [makerToken, takerToken] = tokens;
|
||||
const [makerToken, takerToken] = tokenUtils.getDummyTokens();
|
||||
makerTokenAddress = makerToken.address;
|
||||
takerTokenAddress = takerToken.address;
|
||||
});
|
||||
@@ -649,10 +656,10 @@ describe('ExchangeWrapper', () => {
|
||||
(async () => {
|
||||
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<LogFillContractEventArgs>) => {
|
||||
expect(logEvent.event).to.be.equal(ExchangeEvents.LogFill);
|
||||
expect(logEvent.log.event).to.be.equal(ExchangeEvents.LogFill);
|
||||
done();
|
||||
};
|
||||
await zeroEx.exchange.subscribeAsync(
|
||||
zeroEx.exchange.subscribe(
|
||||
ExchangeEvents.LogFill, indexFilterValues, callback,
|
||||
);
|
||||
await zeroEx.exchange.fillOrderAsync(
|
||||
@@ -665,33 +672,33 @@ describe('ExchangeWrapper', () => {
|
||||
(async () => {
|
||||
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<LogCancelContractEventArgs>) => {
|
||||
expect(logEvent.event).to.be.equal(ExchangeEvents.LogCancel);
|
||||
expect(logEvent.log.event).to.be.equal(ExchangeEvents.LogCancel);
|
||||
done();
|
||||
};
|
||||
await zeroEx.exchange.subscribeAsync(
|
||||
zeroEx.exchange.subscribe(
|
||||
ExchangeEvents.LogCancel, indexFilterValues, callback,
|
||||
);
|
||||
await zeroEx.exchange.cancelOrderAsync(signedOrder, cancelTakerAmountInBaseUnits);
|
||||
})().catch(done);
|
||||
});
|
||||
it('Outstanding subscriptions are cancelled when zeroEx.setProviderAsync called', (done: DoneCallback) => {
|
||||
it('Outstanding subscriptions are cancelled when zeroEx.setProvider called', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
|
||||
const callbackNeverToBeCalled = (err: Error, logEvent: DecodedLogEvent<LogFillContractEventArgs>) => {
|
||||
done(new Error('Expected this subscription to have been cancelled'));
|
||||
};
|
||||
await zeroEx.exchange.subscribeAsync(
|
||||
zeroEx.exchange.subscribe(
|
||||
ExchangeEvents.LogFill, indexFilterValues, callbackNeverToBeCalled,
|
||||
);
|
||||
|
||||
const newProvider = web3Factory.getRpcProvider();
|
||||
await zeroEx.setProviderAsync(newProvider);
|
||||
zeroEx.setProvider(newProvider, constants.TESTRPC_NETWORK_ID);
|
||||
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<LogFillContractEventArgs>) => {
|
||||
expect(logEvent.event).to.be.equal(ExchangeEvents.LogFill);
|
||||
expect(logEvent.log.event).to.be.equal(ExchangeEvents.LogFill);
|
||||
done();
|
||||
};
|
||||
await zeroEx.exchange.subscribeAsync(
|
||||
zeroEx.exchange.subscribe(
|
||||
ExchangeEvents.LogFill, indexFilterValues, callback,
|
||||
);
|
||||
await zeroEx.exchange.fillOrderAsync(
|
||||
@@ -705,7 +712,7 @@ describe('ExchangeWrapper', () => {
|
||||
const callbackNeverToBeCalled = (err: Error, logEvent: DecodedLogEvent<LogFillContractEventArgs>) => {
|
||||
done(new Error('Expected this subscription to have been cancelled'));
|
||||
};
|
||||
const subscriptionToken = await zeroEx.exchange.subscribeAsync(
|
||||
const subscriptionToken = zeroEx.exchange.subscribe(
|
||||
ExchangeEvents.LogFill, indexFilterValues, callbackNeverToBeCalled,
|
||||
);
|
||||
zeroEx.exchange.unsubscribe(subscriptionToken);
|
||||
@@ -725,7 +732,7 @@ describe('ExchangeWrapper', () => {
|
||||
const fillableAmount = new BigNumber(5);
|
||||
before(async () => {
|
||||
[, makerAddress, takerAddress] = userAddresses;
|
||||
const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens();
|
||||
const [makerToken, takerToken] = tokenUtils.getDummyTokens();
|
||||
makerTokenAddress = makerToken.address;
|
||||
takerTokenAddress = takerToken.address;
|
||||
});
|
||||
@@ -740,8 +747,8 @@ describe('ExchangeWrapper', () => {
|
||||
});
|
||||
});
|
||||
describe('#getZRXTokenAddressAsync', () => {
|
||||
it('gets the same token as is in token registry', async () => {
|
||||
const zrxAddress = await zeroEx.exchange.getZRXTokenAddressAsync();
|
||||
it('gets the same token as is in token registry', () => {
|
||||
const zrxAddress = zeroEx.exchange.getZRXTokenAddress();
|
||||
const zrxToken = tokenUtils.getProtocolTokenOrThrow();
|
||||
expect(zrxAddress).to.equal(zrxToken.address);
|
||||
});
|
||||
@@ -753,14 +760,14 @@ describe('ExchangeWrapper', () => {
|
||||
let takerAddress: string;
|
||||
const fillableAmount = new BigNumber(5);
|
||||
const shouldThrowOnInsufficientBalanceOrAllowance = true;
|
||||
const subscriptionOpts: SubscriptionOpts = {
|
||||
fromBlock: BlockParamLiteral.Earliest,
|
||||
const blockRange: BlockRange = {
|
||||
fromBlock: 0,
|
||||
toBlock: BlockParamLiteral.Latest,
|
||||
};
|
||||
let txHash: string;
|
||||
before(async () => {
|
||||
[, makerAddress, takerAddress] = userAddresses;
|
||||
const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens();
|
||||
const [makerToken, takerToken] = tokenUtils.getDummyTokens();
|
||||
makerTokenAddress = makerToken.address;
|
||||
takerTokenAddress = takerToken.address;
|
||||
});
|
||||
@@ -774,7 +781,7 @@ describe('ExchangeWrapper', () => {
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
const eventName = ExchangeEvents.LogFill;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.exchange.getLogsAsync(eventName, subscriptionOpts, indexFilterValues);
|
||||
const logs = await zeroEx.exchange.getLogsAsync(eventName, blockRange, indexFilterValues);
|
||||
expect(logs).to.have.length(1);
|
||||
expect(logs[0].event).to.be.equal(eventName);
|
||||
});
|
||||
@@ -788,7 +795,7 @@ describe('ExchangeWrapper', () => {
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
const differentEventName = ExchangeEvents.LogCancel;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.exchange.getLogsAsync(differentEventName, subscriptionOpts, indexFilterValues);
|
||||
const logs = await zeroEx.exchange.getLogsAsync(differentEventName, blockRange, indexFilterValues);
|
||||
expect(logs).to.have.length(0);
|
||||
});
|
||||
it('should only get the logs with the correct indexed fields', async () => {
|
||||
@@ -814,11 +821,11 @@ describe('ExchangeWrapper', () => {
|
||||
maker: differentMakerAddress,
|
||||
};
|
||||
const logs = await zeroEx.exchange.getLogsAsync<LogFillContractEventArgs>(
|
||||
eventName, subscriptionOpts, indexFilterValues,
|
||||
eventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(1);
|
||||
const args = logs[0].args;
|
||||
expect(args.maker).to.be.equal(differentMakerAddress);
|
||||
});
|
||||
});
|
||||
});
|
||||
}); // tslint:disable:max-file-line-count
|
||||
|
144
packages/0x.js/test/expiration_watcher_test.ts
Normal file
144
packages/0x.js/test/expiration_watcher_test.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
import {BlockchainLifecycle} from '@0xproject/dev-utils';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as chai from 'chai';
|
||||
import * as _ from 'lodash';
|
||||
import 'mocha';
|
||||
import * as Sinon from 'sinon';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {ZeroEx} from '../src/0x';
|
||||
import {ExpirationWatcher} from '../src/order_watcher/expiration_watcher';
|
||||
import {DoneCallback, Token} from '../src/types';
|
||||
import {constants} from '../src/utils/constants';
|
||||
import {utils} from '../src/utils/utils';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants as testConstants} from './utils/constants';
|
||||
import {FillScenarios} from './utils/fill_scenarios';
|
||||
import {reportCallbackErrors} from './utils/report_callback_errors';
|
||||
import {TokenUtils} from './utils/token_utils';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
const blockchainLifecycle = new BlockchainLifecycle(testConstants.RPC_URL);
|
||||
|
||||
describe('ExpirationWatcher', () => {
|
||||
let web3: Web3;
|
||||
let zeroEx: ZeroEx;
|
||||
let tokenUtils: TokenUtils;
|
||||
let tokens: Token[];
|
||||
let userAddresses: string[];
|
||||
let zrxTokenAddress: string;
|
||||
let fillScenarios: FillScenarios;
|
||||
let exchangeContractAddress: string;
|
||||
let makerTokenAddress: string;
|
||||
let takerTokenAddress: string;
|
||||
let coinbase: string;
|
||||
let makerAddress: string;
|
||||
let takerAddress: string;
|
||||
let feeRecipient: string;
|
||||
const fillableAmount = new BigNumber(5);
|
||||
let currentUnixTimestampSec: BigNumber;
|
||||
let timer: Sinon.SinonFakeTimers;
|
||||
let expirationWatcher: ExpirationWatcher;
|
||||
before(async () => {
|
||||
web3 = web3Factory.create();
|
||||
const config = {
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
zeroEx = new ZeroEx(web3.currentProvider, config);
|
||||
exchangeContractAddress = zeroEx.exchange.getContractAddress();
|
||||
userAddresses = await zeroEx.getAvailableAddressesAsync();
|
||||
tokens = await zeroEx.tokenRegistry.getTokensAsync();
|
||||
tokenUtils = new TokenUtils(tokens);
|
||||
zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address;
|
||||
fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress);
|
||||
[coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses;
|
||||
tokens = await zeroEx.tokenRegistry.getTokensAsync();
|
||||
const [makerToken, takerToken] = tokenUtils.getDummyTokens();
|
||||
makerTokenAddress = makerToken.address;
|
||||
takerTokenAddress = takerToken.address;
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await blockchainLifecycle.startAsync();
|
||||
const sinonTimerConfig = {shouldAdvanceTime: true} as any;
|
||||
// This constructor has incorrect types
|
||||
timer = Sinon.useFakeTimers(sinonTimerConfig);
|
||||
currentUnixTimestampSec = utils.getCurrentUnixTimestampSec();
|
||||
expirationWatcher = new ExpirationWatcher();
|
||||
});
|
||||
afterEach(async () => {
|
||||
await blockchainLifecycle.revertAsync();
|
||||
timer.restore();
|
||||
expirationWatcher.unsubscribe();
|
||||
});
|
||||
it('correctly emits events when order expires', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const orderLifetimeSec = 60;
|
||||
const expirationUnixTimestampSec = currentUnixTimestampSec.plus(orderLifetimeSec);
|
||||
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
|
||||
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
|
||||
expirationUnixTimestampSec,
|
||||
);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
expirationWatcher.addOrder(orderHash, signedOrder.expirationUnixTimestampSec.times(1000));
|
||||
const callbackAsync = reportCallbackErrors(done)(async (hash: string) => {
|
||||
expect(hash).to.be.equal(orderHash);
|
||||
expect(utils.getCurrentUnixTimestampSec()).to.be.bignumber.gte(expirationUnixTimestampSec);
|
||||
done();
|
||||
});
|
||||
expirationWatcher.subscribe(callbackAsync);
|
||||
timer.tick(orderLifetimeSec * 1000);
|
||||
})().catch(done);
|
||||
});
|
||||
it('doesn\'t emit events before order expires', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const orderLifetimeSec = 60;
|
||||
const expirationUnixTimestampSec = currentUnixTimestampSec.plus(orderLifetimeSec);
|
||||
const signedOrder = await fillScenarios.createFillableSignedOrderAsync(
|
||||
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
|
||||
expirationUnixTimestampSec,
|
||||
);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
expirationWatcher.addOrder(orderHash, signedOrder.expirationUnixTimestampSec.times(1000));
|
||||
const callbackAsync = reportCallbackErrors(done)(async (hash: string) => {
|
||||
done(new Error('Emitted expiration went before the order actually expired'));
|
||||
});
|
||||
expirationWatcher.subscribe(callbackAsync);
|
||||
const notEnoughTime = orderLifetimeSec - 1;
|
||||
timer.tick(notEnoughTime * 1000);
|
||||
done();
|
||||
})().catch(done);
|
||||
});
|
||||
it('emits events in correct order', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const order1Lifetime = 60;
|
||||
const order2Lifetime = 120;
|
||||
const order1ExpirationUnixTimestampSec = currentUnixTimestampSec.plus(order1Lifetime);
|
||||
const order2ExpirationUnixTimestampSec = currentUnixTimestampSec.plus(order2Lifetime);
|
||||
const signedOrder1 = await fillScenarios.createFillableSignedOrderAsync(
|
||||
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
|
||||
order1ExpirationUnixTimestampSec,
|
||||
);
|
||||
const signedOrder2 = await fillScenarios.createFillableSignedOrderAsync(
|
||||
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
|
||||
order2ExpirationUnixTimestampSec,
|
||||
);
|
||||
const orderHash1 = ZeroEx.getOrderHashHex(signedOrder1);
|
||||
const orderHash2 = ZeroEx.getOrderHashHex(signedOrder2);
|
||||
expirationWatcher.addOrder(orderHash2, signedOrder2.expirationUnixTimestampSec.times(1000));
|
||||
expirationWatcher.addOrder(orderHash1, signedOrder1.expirationUnixTimestampSec.times(1000));
|
||||
const expirationOrder = [orderHash1, orderHash2];
|
||||
const callbackAsync = reportCallbackErrors(done)(async (hash: string) => {
|
||||
const orderHash = expirationOrder.shift();
|
||||
expect(hash).to.be.equal(orderHash);
|
||||
if (_.isEmpty(expirationOrder)) {
|
||||
done();
|
||||
}
|
||||
});
|
||||
expirationWatcher.subscribe(callbackAsync);
|
||||
timer.tick(order2Lifetime * 1000);
|
||||
})().catch(done);
|
||||
});
|
||||
});
|
@@ -1,36 +1,34 @@
|
||||
import 'mocha';
|
||||
import {BlockchainLifecycle} from '@0xproject/dev-utils';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as chai from 'chai';
|
||||
import * as _ from 'lodash';
|
||||
import 'mocha';
|
||||
import * as Web3 from 'web3';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import { chaiSetup } from './utils/chai_setup';
|
||||
import { web3Factory } from './utils/web3_factory';
|
||||
import { Web3Wrapper } from '../src/web3_wrapper';
|
||||
import { OrderStateWatcher } from '../src/order_watcher/order_state_watcher';
|
||||
|
||||
import {
|
||||
ExchangeContractErrs,
|
||||
OrderState,
|
||||
OrderStateInvalid,
|
||||
OrderStateValid,
|
||||
SignedOrder,
|
||||
Token,
|
||||
ZeroEx,
|
||||
LogEvent,
|
||||
DecodedLogEvent,
|
||||
ZeroExConfig,
|
||||
OrderState,
|
||||
SignedOrder,
|
||||
ZeroExError,
|
||||
OrderStateValid,
|
||||
OrderStateInvalid,
|
||||
ExchangeContractErrs,
|
||||
} from '../src';
|
||||
import { TokenUtils } from './utils/token_utils';
|
||||
import { FillScenarios } from './utils/fill_scenarios';
|
||||
import { DoneCallback } from '../src/types';
|
||||
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
|
||||
import {DoneCallback} from '../src/types';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
import {FillScenarios} from './utils/fill_scenarios';
|
||||
import {reportCallbackErrors} from './utils/report_callback_errors';
|
||||
import {TokenUtils} from './utils/token_utils';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
|
||||
const TIMEOUT_MS = 150;
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
const blockchainLifecycle = new BlockchainLifecycle();
|
||||
const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL);
|
||||
|
||||
describe('OrderStateWatcher', () => {
|
||||
let web3: Web3;
|
||||
@@ -45,21 +43,24 @@ describe('OrderStateWatcher', () => {
|
||||
let takerToken: Token;
|
||||
let maker: string;
|
||||
let taker: string;
|
||||
let web3Wrapper: Web3Wrapper;
|
||||
let signedOrder: SignedOrder;
|
||||
const fillableAmount = ZeroEx.toBaseUnitAmount(new BigNumber(5), 18);
|
||||
const config = {
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
const decimals = constants.ZRX_DECIMALS;
|
||||
const fillableAmount = ZeroEx.toBaseUnitAmount(new BigNumber(5), decimals);
|
||||
before(async () => {
|
||||
web3 = web3Factory.create();
|
||||
zeroEx = new ZeroEx(web3.currentProvider);
|
||||
exchangeContractAddress = await zeroEx.exchange.getContractAddressAsync();
|
||||
zeroEx = new ZeroEx(web3.currentProvider, config);
|
||||
exchangeContractAddress = zeroEx.exchange.getContractAddress();
|
||||
userAddresses = await zeroEx.getAvailableAddressesAsync();
|
||||
[, maker, taker] = userAddresses;
|
||||
tokens = await zeroEx.tokenRegistry.getTokensAsync();
|
||||
tokenUtils = new TokenUtils(tokens);
|
||||
zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address;
|
||||
fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress);
|
||||
[makerToken, takerToken] = tokenUtils.getNonProtocolTokens();
|
||||
web3Wrapper = (zeroEx as any)._web3Wrapper;
|
||||
await fillScenarios.initTokenBalancesAsync();
|
||||
[makerToken, takerToken] = tokenUtils.getDummyTokens();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await blockchainLifecycle.startAsync();
|
||||
@@ -73,13 +74,13 @@ describe('OrderStateWatcher', () => {
|
||||
makerToken.address, takerToken.address, maker, taker, fillableAmount,
|
||||
);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
await zeroEx.orderStateWatcher.addOrderAsync(signedOrder);
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
expect((zeroEx.orderStateWatcher as any)._orderByOrderHash).to.include({
|
||||
[orderHash]: signedOrder,
|
||||
});
|
||||
let dependentOrderHashes = (zeroEx.orderStateWatcher as any)._dependentOrderHashes;
|
||||
expect(dependentOrderHashes[signedOrder.maker][signedOrder.makerTokenAddress]).to.have.keys(orderHash);
|
||||
await zeroEx.orderStateWatcher.removeOrderAsync(orderHash);
|
||||
zeroEx.orderStateWatcher.removeOrder(orderHash);
|
||||
expect((zeroEx.orderStateWatcher as any)._orderByOrderHash).to.not.include({
|
||||
[orderHash]: signedOrder,
|
||||
});
|
||||
@@ -92,7 +93,7 @@ describe('OrderStateWatcher', () => {
|
||||
);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
const nonExistentOrderHash = `0x${orderHash.substr(2).split('').reverse().join('')}`;
|
||||
await zeroEx.orderStateWatcher.removeOrderAsync(nonExistentOrderHash);
|
||||
zeroEx.orderStateWatcher.removeOrder(nonExistentOrderHash);
|
||||
});
|
||||
});
|
||||
describe('#subscribe', async () => {
|
||||
@@ -109,7 +110,7 @@ describe('OrderStateWatcher', () => {
|
||||
afterEach(async () => {
|
||||
zeroEx.orderStateWatcher.unsubscribe();
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
await zeroEx.orderStateWatcher.removeOrderAsync(orderHash);
|
||||
zeroEx.orderStateWatcher.removeOrder(orderHash);
|
||||
});
|
||||
it('should emit orderStateInvalid when maker allowance set to 0 for watched order', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
@@ -117,7 +118,7 @@ describe('OrderStateWatcher', () => {
|
||||
makerToken.address, takerToken.address, maker, taker, fillableAmount,
|
||||
);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
await zeroEx.orderStateWatcher.addOrderAsync(signedOrder);
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
expect(orderState.isValid).to.be.false();
|
||||
const invalidOrderState = orderState as OrderStateInvalid;
|
||||
@@ -134,8 +135,7 @@ describe('OrderStateWatcher', () => {
|
||||
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
|
||||
makerToken.address, takerToken.address, maker, taker, fillableAmount,
|
||||
);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
await zeroEx.orderStateWatcher.addOrderAsync(signedOrder);
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
throw new Error('OrderState callback fired for irrelevant order');
|
||||
});
|
||||
@@ -143,7 +143,6 @@ describe('OrderStateWatcher', () => {
|
||||
const notTheMaker = userAddresses[0];
|
||||
const anyRecipient = taker;
|
||||
const transferAmount = new BigNumber(2);
|
||||
const notTheMakerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, notTheMaker);
|
||||
await zeroEx.token.transferAsync(makerToken.address, notTheMaker, anyRecipient, transferAmount);
|
||||
setTimeout(() => {
|
||||
done();
|
||||
@@ -156,7 +155,7 @@ describe('OrderStateWatcher', () => {
|
||||
makerToken.address, takerToken.address, maker, taker, fillableAmount,
|
||||
);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
await zeroEx.orderStateWatcher.addOrderAsync(signedOrder);
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
expect(orderState.isValid).to.be.false();
|
||||
const invalidOrderState = orderState as OrderStateInvalid;
|
||||
@@ -176,18 +175,14 @@ describe('OrderStateWatcher', () => {
|
||||
makerToken.address, takerToken.address, maker, taker, fillableAmount,
|
||||
);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
await zeroEx.orderStateWatcher.addOrderAsync(signedOrder);
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
|
||||
let eventCount = 0;
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
eventCount++;
|
||||
expect(orderState.isValid).to.be.false();
|
||||
const invalidOrderState = orderState as OrderStateInvalid;
|
||||
expect(invalidOrderState.orderHash).to.be.equal(orderHash);
|
||||
expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.OrderRemainingFillAmountZero);
|
||||
if (eventCount === 2) {
|
||||
done();
|
||||
}
|
||||
done();
|
||||
});
|
||||
zeroEx.orderStateWatcher.subscribe(callback);
|
||||
|
||||
@@ -204,15 +199,11 @@ describe('OrderStateWatcher', () => {
|
||||
);
|
||||
|
||||
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
|
||||
const takerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, taker);
|
||||
|
||||
const fillAmountInBaseUnits = new BigNumber(2);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
await zeroEx.orderStateWatcher.addOrderAsync(signedOrder);
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
|
||||
let eventCount = 0;
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
eventCount++;
|
||||
expect(orderState.isValid).to.be.true();
|
||||
const validOrderState = orderState as OrderStateValid;
|
||||
expect(validOrderState.orderHash).to.be.equal(orderHash);
|
||||
@@ -224,9 +215,7 @@ describe('OrderStateWatcher', () => {
|
||||
expect(orderRelevantState.remainingFillableTakerTokenAmount).to.be.bignumber.equal(
|
||||
remainingFillable);
|
||||
expect(orderRelevantState.makerBalance).to.be.bignumber.equal(remainingMakerBalance);
|
||||
if (eventCount === 2) {
|
||||
done();
|
||||
}
|
||||
done();
|
||||
});
|
||||
zeroEx.orderStateWatcher.subscribe(callback);
|
||||
const shouldThrowOnInsufficientBalanceOrAllowance = true;
|
||||
@@ -242,11 +231,10 @@ describe('OrderStateWatcher', () => {
|
||||
signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
|
||||
makerToken.address, takerToken.address, makerFee, takerFee, maker, taker, fillableAmount,
|
||||
taker);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
await zeroEx.orderStateWatcher.addOrderAsync(signedOrder);
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
done();
|
||||
});
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
zeroEx.orderStateWatcher.subscribe(callback);
|
||||
await zeroEx.token.setProxyAllowanceAsync(zrxTokenAddress, maker, new BigNumber(0));
|
||||
})().catch(done);
|
||||
@@ -254,31 +242,25 @@ describe('OrderStateWatcher', () => {
|
||||
describe('remainingFillable(M|T)akerTokenAmount', () => {
|
||||
it('should calculate correct remaining fillable', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const takerFillableAmount = ZeroEx.toBaseUnitAmount(new BigNumber(10), 18);
|
||||
const makerFillableAmount = ZeroEx.toBaseUnitAmount(new BigNumber(20), 18);
|
||||
const takerFillableAmount = ZeroEx.toBaseUnitAmount(new BigNumber(10), decimals);
|
||||
const makerFillableAmount = ZeroEx.toBaseUnitAmount(new BigNumber(20), decimals);
|
||||
signedOrder = await fillScenarios.createAsymmetricFillableSignedOrderAsync(
|
||||
makerToken.address, takerToken.address, maker, taker, makerFillableAmount,
|
||||
takerFillableAmount,
|
||||
);
|
||||
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
|
||||
const takerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, taker);
|
||||
const fillAmountInBaseUnits = ZeroEx.toBaseUnitAmount(new BigNumber(2), 18);
|
||||
const fillAmountInBaseUnits = ZeroEx.toBaseUnitAmount(new BigNumber(2), decimals);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
await zeroEx.orderStateWatcher.addOrderAsync(signedOrder);
|
||||
let eventCount = 0;
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
eventCount++;
|
||||
expect(orderState.isValid).to.be.true();
|
||||
const validOrderState = orderState as OrderStateValid;
|
||||
expect(validOrderState.orderHash).to.be.equal(orderHash);
|
||||
const orderRelevantState = validOrderState.orderRelevantState;
|
||||
expect(orderRelevantState.remainingFillableMakerTokenAmount).to.be.bignumber.equal(
|
||||
ZeroEx.toBaseUnitAmount(new BigNumber(16), 18));
|
||||
ZeroEx.toBaseUnitAmount(new BigNumber(16), decimals));
|
||||
expect(orderRelevantState.remainingFillableTakerTokenAmount).to.be.bignumber.equal(
|
||||
ZeroEx.toBaseUnitAmount(new BigNumber(8), 18));
|
||||
if (eventCount === 2) {
|
||||
done();
|
||||
}
|
||||
ZeroEx.toBaseUnitAmount(new BigNumber(8), decimals));
|
||||
done();
|
||||
});
|
||||
zeroEx.orderStateWatcher.subscribe(callback);
|
||||
const shouldThrowOnInsufficientBalanceOrAllowance = true;
|
||||
@@ -293,10 +275,8 @@ describe('OrderStateWatcher', () => {
|
||||
makerToken.address, takerToken.address, maker, taker, fillableAmount,
|
||||
);
|
||||
|
||||
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
|
||||
|
||||
const changedMakerApprovalAmount = ZeroEx.toBaseUnitAmount(new BigNumber(3), 18);
|
||||
await zeroEx.orderStateWatcher.addOrderAsync(signedOrder);
|
||||
const changedMakerApprovalAmount = ZeroEx.toBaseUnitAmount(new BigNumber(3), decimals);
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
const validOrderState = orderState as OrderStateValid;
|
||||
@@ -319,11 +299,12 @@ describe('OrderStateWatcher', () => {
|
||||
|
||||
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
|
||||
|
||||
const remainingAmount = ZeroEx.toBaseUnitAmount(new BigNumber(1), 18);
|
||||
const remainingAmount = ZeroEx.toBaseUnitAmount(new BigNumber(1), decimals);
|
||||
const transferAmount = makerBalance.sub(remainingAmount);
|
||||
await zeroEx.orderStateWatcher.addOrderAsync(signedOrder);
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
expect(orderState.isValid).to.be.true();
|
||||
const validOrderState = orderState as OrderStateValid;
|
||||
const orderRelevantState = validOrderState.orderRelevantState;
|
||||
expect(orderRelevantState.remainingFillableMakerTokenAmount).to.be.bignumber.equal(
|
||||
@@ -337,6 +318,82 @@ describe('OrderStateWatcher', () => {
|
||||
makerToken.address, maker, ZeroEx.NULL_ADDRESS, transferAmount);
|
||||
})().catch(done);
|
||||
});
|
||||
it('should equal remaining amount when partially cancelled and order has fees', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const takerFee = ZeroEx.toBaseUnitAmount(new BigNumber(0), decimals);
|
||||
const makerFee = ZeroEx.toBaseUnitAmount(new BigNumber(5), decimals);
|
||||
const feeRecipient = taker;
|
||||
signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
|
||||
makerToken.address, takerToken.address, makerFee, takerFee, maker,
|
||||
taker, fillableAmount, feeRecipient);
|
||||
|
||||
const remainingTokenAmount = ZeroEx.toBaseUnitAmount(new BigNumber(4), decimals);
|
||||
const transferTokenAmount = makerFee.sub(remainingTokenAmount);
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
expect(orderState.isValid).to.be.true();
|
||||
const validOrderState = orderState as OrderStateValid;
|
||||
const orderRelevantState = validOrderState.orderRelevantState;
|
||||
expect(orderRelevantState.remainingFillableMakerTokenAmount).to.be.bignumber.equal(
|
||||
remainingTokenAmount);
|
||||
done();
|
||||
});
|
||||
zeroEx.orderStateWatcher.subscribe(callback);
|
||||
await zeroEx.exchange.cancelOrderAsync(signedOrder, transferTokenAmount);
|
||||
})().catch(done);
|
||||
});
|
||||
it('should equal ratio amount when fee balance is lowered', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const takerFee = ZeroEx.toBaseUnitAmount(new BigNumber(0), decimals);
|
||||
const makerFee = ZeroEx.toBaseUnitAmount(new BigNumber(5), decimals);
|
||||
const feeRecipient = taker;
|
||||
signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
|
||||
makerToken.address, takerToken.address, makerFee, takerFee, maker,
|
||||
taker, fillableAmount, feeRecipient);
|
||||
|
||||
const remainingFeeAmount = ZeroEx.toBaseUnitAmount(new BigNumber(3), decimals);
|
||||
|
||||
const remainingTokenAmount = ZeroEx.toBaseUnitAmount(new BigNumber(4), decimals);
|
||||
const transferTokenAmount = makerFee.sub(remainingTokenAmount);
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
const validOrderState = orderState as OrderStateValid;
|
||||
const orderRelevantState = validOrderState.orderRelevantState;
|
||||
expect(orderRelevantState.remainingFillableMakerTokenAmount).to.be.bignumber.equal(
|
||||
remainingFeeAmount);
|
||||
done();
|
||||
});
|
||||
zeroEx.orderStateWatcher.subscribe(callback);
|
||||
await zeroEx.token.setProxyAllowanceAsync(zrxTokenAddress, maker, remainingFeeAmount);
|
||||
await zeroEx.token.transferAsync(
|
||||
makerToken.address, maker, ZeroEx.NULL_ADDRESS, transferTokenAmount);
|
||||
})().catch(done);
|
||||
});
|
||||
it('should calculate full amount when all available and non-divisible', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const takerFee = ZeroEx.toBaseUnitAmount(new BigNumber(0), decimals);
|
||||
const makerFee = ZeroEx.toBaseUnitAmount(new BigNumber(2), decimals);
|
||||
const feeRecipient = taker;
|
||||
signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
|
||||
makerToken.address, takerToken.address, makerFee, takerFee, maker,
|
||||
taker, fillableAmount, feeRecipient);
|
||||
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
const validOrderState = orderState as OrderStateValid;
|
||||
const orderRelevantState = validOrderState.orderRelevantState;
|
||||
expect(orderRelevantState.remainingFillableMakerTokenAmount).to.be.bignumber.equal(
|
||||
fillableAmount);
|
||||
done();
|
||||
});
|
||||
zeroEx.orderStateWatcher.subscribe(callback);
|
||||
await zeroEx.token.setProxyAllowanceAsync(
|
||||
makerToken.address, maker, ZeroEx.toBaseUnitAmount(new BigNumber(100), decimals));
|
||||
})().catch(done);
|
||||
});
|
||||
});
|
||||
it('should emit orderStateInvalid when watched order cancelled', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
@@ -344,7 +401,7 @@ describe('OrderStateWatcher', () => {
|
||||
makerToken.address, takerToken.address, maker, taker, fillableAmount,
|
||||
);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
await zeroEx.orderStateWatcher.addOrderAsync(signedOrder);
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
expect(orderState.isValid).to.be.false();
|
||||
@@ -355,7 +412,6 @@ describe('OrderStateWatcher', () => {
|
||||
});
|
||||
zeroEx.orderStateWatcher.subscribe(callback);
|
||||
|
||||
const shouldThrowOnInsufficientBalanceOrAllowance = true;
|
||||
await zeroEx.exchange.cancelOrderAsync(signedOrder, fillableAmount);
|
||||
})().catch(done);
|
||||
});
|
||||
@@ -366,7 +422,7 @@ describe('OrderStateWatcher', () => {
|
||||
makerToken.address, takerToken.address, maker, taker, fillableAmount,
|
||||
);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
await zeroEx.orderStateWatcher.addOrderAsync(signedOrder);
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
expect(orderState.isValid).to.be.false();
|
||||
@@ -387,12 +443,9 @@ describe('OrderStateWatcher', () => {
|
||||
makerToken.address, takerToken.address, maker, taker, fillableAmount,
|
||||
);
|
||||
|
||||
const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker);
|
||||
const takerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, taker);
|
||||
|
||||
const cancelAmountInBaseUnits = new BigNumber(2);
|
||||
const orderHash = ZeroEx.getOrderHashHex(signedOrder);
|
||||
await zeroEx.orderStateWatcher.addOrderAsync(signedOrder);
|
||||
zeroEx.orderStateWatcher.addOrder(signedOrder);
|
||||
|
||||
const callback = reportCallbackErrors(done)((orderState: OrderState) => {
|
||||
expect(orderState.isValid).to.be.true();
|
||||
@@ -407,4 +460,4 @@ describe('OrderStateWatcher', () => {
|
||||
})().catch(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
}); // tslint:disable:max-file-line-count
|
||||
|
@@ -1,20 +1,23 @@
|
||||
import * as chai from 'chai';
|
||||
import * as Web3 from 'web3';
|
||||
import {BlockchainLifecycle} from '@0xproject/dev-utils';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as chai from 'chai';
|
||||
import * as Sinon from 'sinon';
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
import {ZeroEx, SignedOrder, Token, ExchangeContractErrs, ZeroExError} from '../src';
|
||||
import {TradeSide, TransferType} from '../src/types';
|
||||
import {TokenUtils} from './utils/token_utils';
|
||||
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
|
||||
import {FillScenarios} from './utils/fill_scenarios';
|
||||
import {OrderValidationUtils} from '../src/utils/order_validation_utils';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {ExchangeContractErrs, SignedOrder, Token, ZeroEx, ZeroExError} from '../src';
|
||||
import {BlockParamLiteral, TradeSide, TransferType} from '../src/types';
|
||||
import {ExchangeTransferSimulator} from '../src/utils/exchange_transfer_simulator';
|
||||
import {OrderValidationUtils} from '../src/utils/order_validation_utils';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
import {FillScenarios} from './utils/fill_scenarios';
|
||||
import {TokenUtils} from './utils/token_utils';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
const blockchainLifecycle = new BlockchainLifecycle();
|
||||
const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL);
|
||||
|
||||
describe('OrderValidation', () => {
|
||||
let web3: Web3;
|
||||
@@ -31,23 +34,24 @@ describe('OrderValidation', () => {
|
||||
let makerAddress: string;
|
||||
let takerAddress: string;
|
||||
let feeRecipient: string;
|
||||
let orderValidationUtils: OrderValidationUtils;
|
||||
const fillableAmount = new BigNumber(5);
|
||||
const fillTakerAmount = new BigNumber(5);
|
||||
const config = {
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
before(async () => {
|
||||
web3 = web3Factory.create();
|
||||
zeroEx = new ZeroEx(web3.currentProvider);
|
||||
exchangeContractAddress = await zeroEx.exchange.getContractAddressAsync();
|
||||
zeroEx = new ZeroEx(web3.currentProvider, config);
|
||||
exchangeContractAddress = zeroEx.exchange.getContractAddress();
|
||||
userAddresses = await zeroEx.getAvailableAddressesAsync();
|
||||
[coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses;
|
||||
tokens = await zeroEx.tokenRegistry.getTokensAsync();
|
||||
tokenUtils = new TokenUtils(tokens);
|
||||
zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address;
|
||||
fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress);
|
||||
const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens();
|
||||
const [makerToken, takerToken] = tokenUtils.getDummyTokens();
|
||||
makerTokenAddress = makerToken.address;
|
||||
takerTokenAddress = takerToken.address;
|
||||
orderValidationUtils = new OrderValidationUtils(zeroEx.token, zeroEx.exchange);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await blockchainLifecycle.startAsync();
|
||||
@@ -110,7 +114,7 @@ describe('OrderValidation', () => {
|
||||
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
|
||||
);
|
||||
// 27 <--> 28
|
||||
signedOrder.ecSignature.v = 27 + (28 - signedOrder.ecSignature.v);
|
||||
signedOrder.ecSignature.v = (28 - signedOrder.ecSignature.v) + 27;
|
||||
return expect(zeroEx.exchange.validateFillOrderThrowIfInvalidAsync(
|
||||
signedOrder, fillableAmount, takerAddress,
|
||||
)).to.be.rejectedWith(ZeroExError.InvalidSignature);
|
||||
@@ -175,17 +179,15 @@ describe('OrderValidation', () => {
|
||||
});
|
||||
describe('validateCancelOrderAndThrowIfInvalidAsync', () => {
|
||||
let signedOrder: SignedOrder;
|
||||
let orderHashHex: string;
|
||||
const cancelAmount = new BigNumber(3);
|
||||
beforeEach(async () => {
|
||||
[coinbase, makerAddress, takerAddress] = userAddresses;
|
||||
const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens();
|
||||
const [makerToken, takerToken] = tokenUtils.getDummyTokens();
|
||||
makerTokenAddress = makerToken.address;
|
||||
takerTokenAddress = takerToken.address;
|
||||
signedOrder = await fillScenarios.createFillableSignedOrderAsync(
|
||||
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount,
|
||||
);
|
||||
orderHashHex = ZeroEx.getOrderHashHex(signedOrder);
|
||||
});
|
||||
it('should throw when cancel amount is zero', async () => {
|
||||
const zeroCancelAmount = new BigNumber(0);
|
||||
@@ -198,7 +200,6 @@ describe('OrderValidation', () => {
|
||||
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress,
|
||||
fillableAmount, expirationInPast,
|
||||
);
|
||||
orderHashHex = ZeroEx.getOrderHashHex(expiredSignedOrder);
|
||||
return expect(zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync(expiredSignedOrder, cancelAmount))
|
||||
.to.be.rejectedWith(ExchangeContractErrs.OrderCancelExpired);
|
||||
});
|
||||
@@ -215,7 +216,7 @@ describe('OrderValidation', () => {
|
||||
return Sinon.match((value: BigNumber) => value.eq(expected));
|
||||
};
|
||||
beforeEach('create exchangeTransferSimulator', async () => {
|
||||
exchangeTransferSimulator = new ExchangeTransferSimulator(zeroEx.token);
|
||||
exchangeTransferSimulator = new ExchangeTransferSimulator(zeroEx.token, BlockParamLiteral.Latest);
|
||||
transferFromAsync = Sinon.spy();
|
||||
exchangeTransferSimulator.transferFromAsync = transferFromAsync as any;
|
||||
});
|
||||
@@ -226,7 +227,7 @@ describe('OrderValidation', () => {
|
||||
makerTokenAddress, takerTokenAddress, makerFee, takerFee,
|
||||
makerAddress, takerAddress, fillableAmount, feeRecipient,
|
||||
);
|
||||
await orderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
|
||||
await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
|
||||
exchangeTransferSimulator, signedOrder, fillableAmount, takerAddress, zrxTokenAddress,
|
||||
);
|
||||
expect(transferFromAsync.callCount).to.be.equal(4);
|
||||
@@ -262,7 +263,7 @@ describe('OrderValidation', () => {
|
||||
makerTokenAddress, takerTokenAddress, makerFee, takerFee,
|
||||
makerAddress, ZeroEx.NULL_ADDRESS, fillableAmount, feeRecipient,
|
||||
);
|
||||
await orderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
|
||||
await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
|
||||
exchangeTransferSimulator, signedOrder, fillableAmount, takerAddress, zrxTokenAddress,
|
||||
);
|
||||
expect(transferFromAsync.callCount).to.be.equal(4);
|
||||
@@ -297,7 +298,7 @@ describe('OrderValidation', () => {
|
||||
const signedOrder = await fillScenarios.createAsymmetricFillableSignedOrderAsync(
|
||||
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, makerTokenAmount, takerTokenAmount,
|
||||
);
|
||||
await orderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
|
||||
await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
|
||||
exchangeTransferSimulator, signedOrder, takerTokenAmount, takerAddress, zrxTokenAddress,
|
||||
);
|
||||
expect(transferFromAsync.callCount).to.be.equal(4);
|
||||
@@ -312,7 +313,7 @@ describe('OrderValidation', () => {
|
||||
fillableAmount, ZeroEx.NULL_ADDRESS,
|
||||
);
|
||||
const fillTakerTokenAmount = fillableAmount.div(2).round(0);
|
||||
await orderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
|
||||
await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync(
|
||||
exchangeTransferSimulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress,
|
||||
);
|
||||
const makerPartialFee = makerFee.div(2);
|
||||
|
177
packages/0x.js/test/remaining_fillable_calculator_test.ts
Normal file
177
packages/0x.js/test/remaining_fillable_calculator_test.ts
Normal file
@@ -0,0 +1,177 @@
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as chai from 'chai';
|
||||
import 'mocha';
|
||||
|
||||
import {ZeroEx} from '../src/0x';
|
||||
import {RemainingFillableCalculator} from '../src/order_watcher/remaining_fillable_calculator';
|
||||
import {ECSignature, SignedOrder} from '../src/types';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
|
||||
describe('RemainingFillableCalculator', () => {
|
||||
let calculator: RemainingFillableCalculator;
|
||||
let signedOrder: SignedOrder;
|
||||
let transferrableMakerTokenAmount: BigNumber;
|
||||
let transferrableMakerFeeTokenAmount: BigNumber;
|
||||
let remainingMakerTokenAmount: BigNumber;
|
||||
let makerAmount: BigNumber;
|
||||
let takerAmount: BigNumber;
|
||||
let makerFeeAmount: BigNumber;
|
||||
let isMakerTokenZRX: boolean;
|
||||
const makerToken: string = '0x1';
|
||||
const takerToken: string = '0x2';
|
||||
const decimals: number = 4;
|
||||
const zero: BigNumber = new BigNumber(0);
|
||||
const zeroAddress = '0x0';
|
||||
const signature: ECSignature = {v: 27, r: '', s: ''};
|
||||
beforeEach(async () => {
|
||||
[makerAmount, takerAmount, makerFeeAmount] = [ZeroEx.toBaseUnitAmount(new BigNumber(50), decimals),
|
||||
ZeroEx.toBaseUnitAmount(new BigNumber(5), decimals),
|
||||
ZeroEx.toBaseUnitAmount(new BigNumber(1), decimals)];
|
||||
[transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount] = [
|
||||
ZeroEx.toBaseUnitAmount(new BigNumber(50), decimals),
|
||||
ZeroEx.toBaseUnitAmount(new BigNumber(5), decimals)];
|
||||
});
|
||||
function buildSignedOrder(): SignedOrder {
|
||||
return { ecSignature: signature,
|
||||
exchangeContractAddress: zeroAddress,
|
||||
feeRecipient: zeroAddress,
|
||||
maker: zeroAddress,
|
||||
taker: zeroAddress,
|
||||
makerFee: makerFeeAmount,
|
||||
takerFee: zero,
|
||||
makerTokenAmount: makerAmount,
|
||||
takerTokenAmount: takerAmount,
|
||||
makerTokenAddress: makerToken,
|
||||
takerTokenAddress: takerToken,
|
||||
salt: zero,
|
||||
expirationUnixTimestampSec: zero };
|
||||
}
|
||||
describe('Maker token is NOT ZRX', () => {
|
||||
before(async () => {
|
||||
isMakerTokenZRX = false;
|
||||
});
|
||||
it('calculates the correct amount when unfilled and funds available', () => {
|
||||
signedOrder = buildSignedOrder();
|
||||
remainingMakerTokenAmount = signedOrder.makerTokenAmount;
|
||||
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
|
||||
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
|
||||
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(remainingMakerTokenAmount);
|
||||
});
|
||||
it('calculates the correct amount when partially filled and funds available', () => {
|
||||
signedOrder = buildSignedOrder();
|
||||
remainingMakerTokenAmount = ZeroEx.toBaseUnitAmount(new BigNumber(1), decimals);
|
||||
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
|
||||
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
|
||||
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(remainingMakerTokenAmount);
|
||||
});
|
||||
it('calculates the amount to be 0 when all fee funds are transferred', () => {
|
||||
signedOrder = buildSignedOrder();
|
||||
transferrableMakerFeeTokenAmount = zero;
|
||||
remainingMakerTokenAmount = signedOrder.makerTokenAmount;
|
||||
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
|
||||
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
|
||||
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(zero);
|
||||
});
|
||||
it('calculates the correct amount when balance is less than remaining fillable', () => {
|
||||
signedOrder = buildSignedOrder();
|
||||
const partiallyFilledAmount = ZeroEx.toBaseUnitAmount(new BigNumber(2), decimals);
|
||||
remainingMakerTokenAmount = signedOrder.makerTokenAmount.minus(partiallyFilledAmount);
|
||||
transferrableMakerTokenAmount = remainingMakerTokenAmount.minus(partiallyFilledAmount);
|
||||
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
|
||||
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
|
||||
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(transferrableMakerTokenAmount);
|
||||
});
|
||||
describe('Order to Fee Ratio is < 1', () => {
|
||||
beforeEach(async () => {
|
||||
[makerAmount, takerAmount, makerFeeAmount] = [ZeroEx.toBaseUnitAmount(new BigNumber(3), decimals),
|
||||
ZeroEx.toBaseUnitAmount(new BigNumber(6), decimals),
|
||||
ZeroEx.toBaseUnitAmount(new BigNumber(6), decimals)];
|
||||
});
|
||||
it('calculates the correct amount when funds unavailable', () => {
|
||||
signedOrder = buildSignedOrder();
|
||||
remainingMakerTokenAmount = signedOrder.makerTokenAmount;
|
||||
const transferredAmount = ZeroEx.toBaseUnitAmount(new BigNumber(2), decimals);
|
||||
transferrableMakerTokenAmount = remainingMakerTokenAmount.minus(transferredAmount);
|
||||
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
|
||||
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount,
|
||||
remainingMakerTokenAmount);
|
||||
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(transferrableMakerTokenAmount);
|
||||
});
|
||||
});
|
||||
describe('Ratio is not evenly divisble', () => {
|
||||
beforeEach(async () => {
|
||||
[makerAmount, takerAmount, makerFeeAmount] = [ZeroEx.toBaseUnitAmount(new BigNumber(3), decimals),
|
||||
ZeroEx.toBaseUnitAmount(new BigNumber(7), decimals),
|
||||
ZeroEx.toBaseUnitAmount(new BigNumber(7), decimals)];
|
||||
});
|
||||
it('calculates the correct amount when funds unavailable', () => {
|
||||
signedOrder = buildSignedOrder();
|
||||
remainingMakerTokenAmount = signedOrder.makerTokenAmount;
|
||||
const transferredAmount = ZeroEx.toBaseUnitAmount(new BigNumber(2), decimals);
|
||||
transferrableMakerTokenAmount = remainingMakerTokenAmount.minus(transferredAmount);
|
||||
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
|
||||
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount,
|
||||
remainingMakerTokenAmount);
|
||||
const calculatedFillableAmount = calculator.computeRemainingMakerFillable();
|
||||
expect(calculatedFillableAmount.lessThanOrEqualTo(transferrableMakerTokenAmount)).to.be.true();
|
||||
expect(calculatedFillableAmount).to.be.bignumber.greaterThan(new BigNumber(0));
|
||||
const orderToFeeRatio = signedOrder.makerTokenAmount.dividedBy(signedOrder.makerFee);
|
||||
const calculatedFeeAmount = calculatedFillableAmount.dividedBy(orderToFeeRatio);
|
||||
expect(calculatedFeeAmount).to.be.bignumber.lessThan(transferrableMakerFeeTokenAmount);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('Maker Token is ZRX', () => {
|
||||
before(async () => {
|
||||
isMakerTokenZRX = true;
|
||||
});
|
||||
it('calculates the correct amount when unfilled and funds available', () => {
|
||||
signedOrder = buildSignedOrder();
|
||||
transferrableMakerTokenAmount = makerAmount.plus(makerFeeAmount);
|
||||
transferrableMakerFeeTokenAmount = transferrableMakerTokenAmount;
|
||||
remainingMakerTokenAmount = signedOrder.makerTokenAmount;
|
||||
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
|
||||
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
|
||||
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(remainingMakerTokenAmount);
|
||||
});
|
||||
it('calculates the correct amount when partially filled and funds available', () => {
|
||||
signedOrder = buildSignedOrder();
|
||||
remainingMakerTokenAmount = ZeroEx.toBaseUnitAmount(new BigNumber(1), decimals);
|
||||
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
|
||||
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
|
||||
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(remainingMakerTokenAmount);
|
||||
});
|
||||
it('calculates the amount to be 0 when all fee funds are transferred', () => {
|
||||
signedOrder = buildSignedOrder();
|
||||
transferrableMakerTokenAmount = zero;
|
||||
transferrableMakerFeeTokenAmount = zero;
|
||||
remainingMakerTokenAmount = signedOrder.makerTokenAmount;
|
||||
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
|
||||
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
|
||||
expect(calculator.computeRemainingMakerFillable()).to.be.bignumber.equal(zero);
|
||||
});
|
||||
it('calculates the correct amount when balance is less than remaining fillable', () => {
|
||||
signedOrder = buildSignedOrder();
|
||||
const partiallyFilledAmount = ZeroEx.toBaseUnitAmount(new BigNumber(2), decimals);
|
||||
remainingMakerTokenAmount = signedOrder.makerTokenAmount.minus(partiallyFilledAmount);
|
||||
transferrableMakerTokenAmount = remainingMakerTokenAmount.minus(partiallyFilledAmount);
|
||||
transferrableMakerFeeTokenAmount = transferrableMakerTokenAmount;
|
||||
|
||||
const orderToFeeRatio = signedOrder.makerTokenAmount.dividedToIntegerBy(signedOrder.makerFee);
|
||||
const expectedFillableAmount = new BigNumber(450980);
|
||||
calculator = new RemainingFillableCalculator(signedOrder, isMakerTokenZRX,
|
||||
transferrableMakerTokenAmount, transferrableMakerFeeTokenAmount, remainingMakerTokenAmount);
|
||||
const calculatedFillableAmount = calculator.computeRemainingMakerFillable();
|
||||
const numberOfFillsInRatio = calculatedFillableAmount.dividedToIntegerBy(orderToFeeRatio);
|
||||
const calculatedFillableAmountPlusFees = calculatedFillableAmount.plus(numberOfFillsInRatio);
|
||||
expect(calculatedFillableAmountPlusFees).to.be.bignumber.lessThan(transferrableMakerTokenAmount);
|
||||
expect(calculatedFillableAmountPlusFees).to.be.bignumber.lessThan(remainingMakerTokenAmount);
|
||||
expect(calculatedFillableAmount).to.be.bignumber.equal(expectedFillableAmount);
|
||||
expect(numberOfFillsInRatio.decimalPlaces()).to.be.equal(0);
|
||||
});
|
||||
});
|
||||
});
|
@@ -1,42 +1,44 @@
|
||||
import 'mocha';
|
||||
import * as _ from 'lodash';
|
||||
import * as chai from 'chai';
|
||||
import * as Sinon from 'sinon';
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import * as Web3 from 'web3';
|
||||
import {BlockchainLifecycle} from '@0xproject/dev-utils';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import promisify = require('es6-promisify');
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
import * as chai from 'chai';
|
||||
import * as _ from 'lodash';
|
||||
import 'mocha';
|
||||
import * as Sinon from 'sinon';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {
|
||||
ZeroEx,
|
||||
ZeroExError,
|
||||
Token,
|
||||
ApprovalContractEventArgs,
|
||||
TokenEvents,
|
||||
DecodedLogEvent,
|
||||
Token,
|
||||
TokenEvents,
|
||||
ZeroEx,
|
||||
} from '../src';
|
||||
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
|
||||
import {TokenUtils} from './utils/token_utils';
|
||||
import {DoneCallback, BlockParamLiteral} from '../src/types';
|
||||
import {DoneCallback} from '../src/types';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
import {reportCallbackErrors} from './utils/report_callback_errors';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
const blockchainLifecycle = new BlockchainLifecycle();
|
||||
const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL);
|
||||
|
||||
describe('SubscriptionTest', () => {
|
||||
let web3: Web3;
|
||||
let zeroEx: ZeroEx;
|
||||
let userAddresses: string[];
|
||||
let tokens: Token[];
|
||||
let tokenUtils: TokenUtils;
|
||||
let coinbase: string;
|
||||
let addressWithoutFunds: string;
|
||||
const config = {
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
before(async () => {
|
||||
web3 = web3Factory.create();
|
||||
zeroEx = new ZeroEx(web3.currentProvider);
|
||||
zeroEx = new ZeroEx(web3.currentProvider, config);
|
||||
userAddresses = await zeroEx.getAvailableAddressesAsync();
|
||||
tokens = await zeroEx.tokenRegistry.getTokensAsync();
|
||||
tokenUtils = new TokenUtils(tokens);
|
||||
coinbase = userAddresses[0];
|
||||
addressWithoutFunds = userAddresses[1];
|
||||
});
|
||||
@@ -48,9 +50,7 @@ describe('SubscriptionTest', () => {
|
||||
});
|
||||
describe('#subscribe', () => {
|
||||
const indexFilterValues = {};
|
||||
const shouldThrowOnInsufficientBalanceOrAllowance = true;
|
||||
let tokenAddress: string;
|
||||
const transferAmount = new BigNumber(42);
|
||||
const allowanceAmount = new BigNumber(42);
|
||||
let stubs: Sinon.SinonStub[] = [];
|
||||
before(() => {
|
||||
@@ -62,22 +62,44 @@ describe('SubscriptionTest', () => {
|
||||
_.each(stubs, s => s.restore());
|
||||
stubs = [];
|
||||
});
|
||||
it('Should receive the Error when an error occurs', (done: DoneCallback) => {
|
||||
it('Should receive the Error when an error occurs while fetching the block', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
|
||||
expect(err).to.not.be.null();
|
||||
expect(logEvent).to.be.undefined();
|
||||
done();
|
||||
};
|
||||
const errMsg = 'Error fetching block';
|
||||
const callback = reportCallbackErrors(done)(
|
||||
(err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
|
||||
expect(err.message).to.be.equal(errMsg);
|
||||
expect(logEvent).to.be.undefined();
|
||||
done();
|
||||
},
|
||||
);
|
||||
stubs = [
|
||||
Sinon.stub((zeroEx as any)._web3Wrapper, 'getBlockAsync')
|
||||
.throws('JSON RPC error'),
|
||||
.throws(new Error(errMsg)),
|
||||
];
|
||||
zeroEx.token.subscribe(
|
||||
tokenAddress, TokenEvents.Approval, indexFilterValues, callback);
|
||||
await zeroEx.token.setAllowanceAsync(tokenAddress, coinbase, addressWithoutFunds, allowanceAmount);
|
||||
})().catch(done);
|
||||
});
|
||||
});
|
||||
it('Should receive the Error when an error occurs while reconciling the new block', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const errMsg = 'Error fetching logs';
|
||||
const callback = reportCallbackErrors(done)(
|
||||
(err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
|
||||
expect(err.message).to.be.equal(errMsg);
|
||||
expect(logEvent).to.be.undefined();
|
||||
done();
|
||||
},
|
||||
);
|
||||
stubs = [
|
||||
Sinon.stub((zeroEx as any)._web3Wrapper, 'getLogsAsync')
|
||||
.throws(new Error(errMsg)),
|
||||
];
|
||||
zeroEx.token.subscribe(
|
||||
tokenAddress, TokenEvents.Approval, indexFilterValues, callback);
|
||||
await zeroEx.token.setAllowanceAsync(tokenAddress, coinbase, addressWithoutFunds, allowanceAmount);
|
||||
})().catch(done);
|
||||
});
|
||||
it('Should allow unsubscribeAll to be called successfully after an error', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => _.noop;
|
||||
@@ -85,11 +107,11 @@ describe('SubscriptionTest', () => {
|
||||
tokenAddress, TokenEvents.Approval, indexFilterValues, callback);
|
||||
stubs = [
|
||||
Sinon.stub((zeroEx as any)._web3Wrapper, 'getBlockAsync')
|
||||
.throws('JSON RPC error'),
|
||||
.throws(new Error('JSON RPC error')),
|
||||
];
|
||||
zeroEx.token.unsubscribeAll();
|
||||
done();
|
||||
})().catch(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -1,15 +1,18 @@
|
||||
import {BlockchainLifecycle} from '@0xproject/dev-utils';
|
||||
import {schemas, SchemaValidator} from '@0xproject/json-schemas';
|
||||
import * as chai from 'chai';
|
||||
import * as _ from 'lodash';
|
||||
import 'mocha';
|
||||
import * as chai from 'chai';
|
||||
import {SchemaValidator, schemas} from '@0xproject/json-schemas';
|
||||
|
||||
import {Token, ZeroEx} from '../src';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
import {ZeroEx, Token} from '../src';
|
||||
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
const blockchainLifecycle = new BlockchainLifecycle();
|
||||
const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL);
|
||||
|
||||
const TOKEN_REGISTRY_SIZE_AFTER_MIGRATION = 7;
|
||||
|
||||
@@ -24,9 +27,12 @@ describe('TokenRegistryWrapper', () => {
|
||||
const registeredName = '0x Protocol Token';
|
||||
const unregisteredSymbol = 'MAL';
|
||||
const unregisteredName = 'Malicious Token';
|
||||
const config = {
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
before(async () => {
|
||||
const web3 = web3Factory.create();
|
||||
zeroEx = new ZeroEx(web3.currentProvider);
|
||||
zeroEx = new ZeroEx(web3.currentProvider, config);
|
||||
tokens = await zeroEx.tokenRegistry.getTokensAsync();
|
||||
_.map(tokens, token => {
|
||||
tokenAddressBySymbol[token.symbol] = token.address;
|
||||
|
@@ -1,17 +1,22 @@
|
||||
import * as chai from 'chai';
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
|
||||
import {ZeroEx} from '../src';
|
||||
import {TokenTransferProxyWrapper} from '../src/contract_wrappers/token_transfer_proxy_wrapper';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
|
||||
describe('TokenTransferProxyWrapper', () => {
|
||||
let zeroEx: ZeroEx;
|
||||
const config = {
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
before(async () => {
|
||||
const web3 = web3Factory.create();
|
||||
zeroEx = new ZeroEx(web3.currentProvider);
|
||||
zeroEx = new ZeroEx(web3.currentProvider, config);
|
||||
});
|
||||
describe('#isAuthorizedAsync', () => {
|
||||
it('should return false if the address is not authorized', async () => {
|
||||
|
@@ -1,31 +1,31 @@
|
||||
import 'mocha';
|
||||
import * as chai from 'chai';
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import * as Web3 from 'web3';
|
||||
import {BlockchainLifecycle} from '@0xproject/dev-utils';
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import promisify = require('es6-promisify');
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
import * as chai from 'chai';
|
||||
import 'mocha';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {
|
||||
ApprovalContractEventArgs,
|
||||
BlockParamLiteral,
|
||||
BlockRange,
|
||||
DecodedLogEvent,
|
||||
Token,
|
||||
TokenEvents,
|
||||
TransferContractEventArgs,
|
||||
ZeroEx,
|
||||
ZeroExError,
|
||||
Token,
|
||||
SubscriptionOpts,
|
||||
TokenEvents,
|
||||
ContractEvent,
|
||||
TransferContractEventArgs,
|
||||
ApprovalContractEventArgs,
|
||||
TokenContractEventArgs,
|
||||
LogWithDecodedArgs,
|
||||
LogEvent,
|
||||
DecodedLogEvent,
|
||||
} from '../src';
|
||||
import {BlockchainLifecycle} from './utils/blockchain_lifecycle';
|
||||
import {DoneCallback} from '../src/types';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
import {TokenUtils} from './utils/token_utils';
|
||||
import {DoneCallback, BlockParamLiteral} from '../src/types';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
const blockchainLifecycle = new BlockchainLifecycle();
|
||||
const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL);
|
||||
|
||||
describe('TokenWrapper', () => {
|
||||
let web3: Web3;
|
||||
@@ -35,9 +35,14 @@ describe('TokenWrapper', () => {
|
||||
let tokenUtils: TokenUtils;
|
||||
let coinbase: string;
|
||||
let addressWithoutFunds: string;
|
||||
let web3Wrapper: Web3Wrapper;
|
||||
const config = {
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
before(async () => {
|
||||
web3 = web3Factory.create();
|
||||
zeroEx = new ZeroEx(web3.currentProvider);
|
||||
zeroEx = new ZeroEx(web3.currentProvider, config);
|
||||
web3Wrapper = new Web3Wrapper(web3.currentProvider);
|
||||
userAddresses = await zeroEx.getAvailableAddressesAsync();
|
||||
tokens = await zeroEx.tokenRegistry.getTokensAsync();
|
||||
tokenUtils = new TokenUtils(tokens);
|
||||
@@ -62,8 +67,7 @@ describe('TokenWrapper', () => {
|
||||
const toAddress = addressWithoutFunds;
|
||||
const preBalance = await zeroEx.token.getBalanceAsync(token.address, toAddress);
|
||||
expect(preBalance).to.be.bignumber.equal(0);
|
||||
const txHash = await zeroEx.token.transferAsync(token.address, fromAddress, toAddress, transferAmount);
|
||||
const receipt = await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
await zeroEx.token.transferAsync(token.address, fromAddress, toAddress, transferAmount);
|
||||
const postBalance = await zeroEx.token.getBalanceAsync(token.address, toAddress);
|
||||
return expect(postBalance).to.be.bignumber.equal(transferAmount);
|
||||
});
|
||||
@@ -80,7 +84,7 @@ describe('TokenWrapper', () => {
|
||||
const toAddress = coinbase;
|
||||
return expect(zeroEx.token.transferAsync(
|
||||
nonExistentTokenAddress, fromAddress, toAddress, transferAmount,
|
||||
)).to.be.rejectedWith(ZeroExError.ContractDoesNotExist);
|
||||
)).to.be.rejectedWith(ZeroExError.TokenContractDoesNotExist);
|
||||
});
|
||||
});
|
||||
describe('#transferFromAsync', () => {
|
||||
@@ -153,7 +157,7 @@ describe('TokenWrapper', () => {
|
||||
const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065';
|
||||
return expect(zeroEx.token.transferFromAsync(
|
||||
nonExistentTokenAddress, fromAddress, toAddress, senderAddress, new BigNumber(42),
|
||||
)).to.be.rejectedWith(ZeroExError.ContractDoesNotExist);
|
||||
)).to.be.rejectedWith(ZeroExError.TokenContractDoesNotExist);
|
||||
});
|
||||
});
|
||||
describe('#getBalanceAsync', () => {
|
||||
@@ -169,7 +173,7 @@ describe('TokenWrapper', () => {
|
||||
const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065';
|
||||
const ownerAddress = coinbase;
|
||||
return expect(zeroEx.token.getBalanceAsync(nonExistentTokenAddress, ownerAddress))
|
||||
.to.be.rejectedWith(ZeroExError.ContractDoesNotExist);
|
||||
.to.be.rejectedWith(ZeroExError.TokenContractDoesNotExist);
|
||||
});
|
||||
it('should return a balance of 0 for a non-existent owner address', async () => {
|
||||
const token = tokens[0];
|
||||
@@ -184,7 +188,7 @@ describe('TokenWrapper', () => {
|
||||
before(async () => {
|
||||
const hasAddresses = false;
|
||||
const web3WithoutAccounts = web3Factory.create(hasAddresses);
|
||||
zeroExWithoutAccounts = new ZeroEx(web3WithoutAccounts.currentProvider);
|
||||
zeroExWithoutAccounts = new ZeroEx(web3WithoutAccounts.currentProvider, config);
|
||||
});
|
||||
it('should return balance even when called with Web3 provider instance without addresses', async () => {
|
||||
const token = tokens[0];
|
||||
@@ -231,8 +235,10 @@ describe('TokenWrapper', () => {
|
||||
await zeroEx.token.setAllowanceAsync(zrx.address, coinbase, userWithNormalAllowance, transferAmount);
|
||||
await zeroEx.token.setUnlimitedAllowanceAsync(zrx.address, coinbase, userWithUnlimitedAllowance);
|
||||
|
||||
const initBalanceWithNormalAllowance = await promisify(web3.eth.getBalance)(userWithNormalAllowance);
|
||||
const initBalanceWithUnlimitedAllowance = await promisify(web3.eth.getBalance)(userWithUnlimitedAllowance);
|
||||
const initBalanceWithNormalAllowance = await web3Wrapper.getBalanceInWeiAsync(userWithNormalAllowance);
|
||||
const initBalanceWithUnlimitedAllowance = await web3Wrapper.getBalanceInWeiAsync(
|
||||
userWithUnlimitedAllowance,
|
||||
);
|
||||
|
||||
await zeroEx.token.transferFromAsync(
|
||||
zrx.address, coinbase, userWithNormalAllowance, userWithNormalAllowance, transferAmount,
|
||||
@@ -241,8 +247,10 @@ describe('TokenWrapper', () => {
|
||||
zrx.address, coinbase, userWithUnlimitedAllowance, userWithUnlimitedAllowance, transferAmount,
|
||||
);
|
||||
|
||||
const finalBalanceWithNormalAllowance = await promisify(web3.eth.getBalance)(userWithNormalAllowance);
|
||||
const finalBalanceWithUnlimitedAllowance = await promisify(web3.eth.getBalance)(userWithUnlimitedAllowance);
|
||||
const finalBalanceWithNormalAllowance = await web3Wrapper.getBalanceInWeiAsync(userWithNormalAllowance);
|
||||
const finalBalanceWithUnlimitedAllowance = await web3Wrapper.getBalanceInWeiAsync(
|
||||
userWithUnlimitedAllowance,
|
||||
);
|
||||
|
||||
const normalGasCost = initBalanceWithNormalAllowance.minus(finalBalanceWithNormalAllowance);
|
||||
const unlimitedGasCost = initBalanceWithUnlimitedAllowance.minus(finalBalanceWithUnlimitedAllowance);
|
||||
@@ -281,7 +289,7 @@ describe('TokenWrapper', () => {
|
||||
before(async () => {
|
||||
const hasAddresses = false;
|
||||
const web3WithoutAccounts = web3Factory.create(hasAddresses);
|
||||
zeroExWithoutAccounts = new ZeroEx(web3WithoutAccounts.currentProvider);
|
||||
zeroExWithoutAccounts = new ZeroEx(web3WithoutAccounts.currentProvider, config);
|
||||
});
|
||||
it('should get the proxy allowance', async () => {
|
||||
const token = tokens[0];
|
||||
@@ -341,7 +349,6 @@ describe('TokenWrapper', () => {
|
||||
});
|
||||
describe('#subscribe', () => {
|
||||
const indexFilterValues = {};
|
||||
const shouldThrowOnInsufficientBalanceOrAllowance = true;
|
||||
let tokenAddress: string;
|
||||
const transferAmount = new BigNumber(42);
|
||||
const allowanceAmount = new BigNumber(42);
|
||||
@@ -361,10 +368,11 @@ describe('TokenWrapper', () => {
|
||||
(async () => {
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<TransferContractEventArgs>) => {
|
||||
expect(logEvent).to.not.be.undefined();
|
||||
expect(logEvent.logIndex).to.be.equal(0);
|
||||
expect(logEvent.transactionIndex).to.be.equal(0);
|
||||
expect(logEvent.blockNumber).to.be.instanceOf(Number);
|
||||
const args = logEvent.args;
|
||||
expect(logEvent.isRemoved).to.be.false();
|
||||
expect(logEvent.log.logIndex).to.be.equal(0);
|
||||
expect(logEvent.log.transactionIndex).to.be.equal(0);
|
||||
expect(logEvent.log.blockNumber).to.be.a('number');
|
||||
const args = logEvent.log.args;
|
||||
expect(args._from).to.be.equal(coinbase);
|
||||
expect(args._to).to.be.equal(addressWithoutFunds);
|
||||
expect(args._value).to.be.bignumber.equal(transferAmount);
|
||||
@@ -379,7 +387,8 @@ describe('TokenWrapper', () => {
|
||||
(async () => {
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
|
||||
expect(logEvent).to.not.be.undefined();
|
||||
const args = logEvent.args;
|
||||
expect(logEvent.isRemoved).to.be.false();
|
||||
const args = logEvent.log.args;
|
||||
expect(args._owner).to.be.equal(coinbase);
|
||||
expect(args._spender).to.be.equal(addressWithoutFunds);
|
||||
expect(args._value).to.be.bignumber.equal(allowanceAmount);
|
||||
@@ -390,7 +399,7 @@ describe('TokenWrapper', () => {
|
||||
await zeroEx.token.setAllowanceAsync(tokenAddress, coinbase, addressWithoutFunds, allowanceAmount);
|
||||
})().catch(done);
|
||||
});
|
||||
it('Outstanding subscriptions are cancelled when zeroEx.setProviderAsync called', (done: DoneCallback) => {
|
||||
it('Outstanding subscriptions are cancelled when zeroEx.setProvider called', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callbackNeverToBeCalled = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
|
||||
done(new Error('Expected this subscription to have been cancelled'));
|
||||
@@ -402,7 +411,7 @@ describe('TokenWrapper', () => {
|
||||
done();
|
||||
};
|
||||
const newProvider = web3Factory.getRpcProvider();
|
||||
await zeroEx.setProviderAsync(newProvider);
|
||||
zeroEx.setProvider(newProvider, constants.TESTRPC_NETWORK_ID);
|
||||
zeroEx.token.subscribe(
|
||||
tokenAddress, TokenEvents.Transfer, indexFilterValues, callbackToBeCalled,
|
||||
);
|
||||
@@ -425,15 +434,15 @@ describe('TokenWrapper', () => {
|
||||
describe('#getLogsAsync', () => {
|
||||
let tokenAddress: string;
|
||||
let tokenTransferProxyAddress: string;
|
||||
const subscriptionOpts: SubscriptionOpts = {
|
||||
fromBlock: BlockParamLiteral.Earliest,
|
||||
const blockRange: BlockRange = {
|
||||
fromBlock: 0,
|
||||
toBlock: BlockParamLiteral.Latest,
|
||||
};
|
||||
let txHash: string;
|
||||
before(async () => {
|
||||
before(() => {
|
||||
const token = tokens[0];
|
||||
tokenAddress = token.address;
|
||||
tokenTransferProxyAddress = await zeroEx.proxy.getContractAddressAsync();
|
||||
tokenTransferProxyAddress = zeroEx.proxy.getContractAddress();
|
||||
});
|
||||
it('should get logs with decoded args emitted by Approval', async () => {
|
||||
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(tokenAddress, coinbase);
|
||||
@@ -441,7 +450,7 @@ describe('TokenWrapper', () => {
|
||||
const eventName = TokenEvents.Approval;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.token.getLogsAsync<ApprovalContractEventArgs>(
|
||||
tokenAddress, eventName, subscriptionOpts, indexFilterValues,
|
||||
tokenAddress, eventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(1);
|
||||
const args = logs[0].args;
|
||||
@@ -456,7 +465,7 @@ describe('TokenWrapper', () => {
|
||||
const differentEventName = TokenEvents.Transfer;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.token.getLogsAsync(
|
||||
tokenAddress, differentEventName, subscriptionOpts, indexFilterValues,
|
||||
tokenAddress, differentEventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(0);
|
||||
});
|
||||
@@ -470,7 +479,7 @@ describe('TokenWrapper', () => {
|
||||
_owner: coinbase,
|
||||
};
|
||||
const logs = await zeroEx.token.getLogsAsync<ApprovalContractEventArgs>(
|
||||
tokenAddress, eventName, subscriptionOpts, indexFilterValues,
|
||||
tokenAddress, eventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(1);
|
||||
const args = logs[0].args;
|
||||
|
@@ -1,26 +0,0 @@
|
||||
import {RPC} from './rpc';
|
||||
|
||||
export class BlockchainLifecycle {
|
||||
private rpc: RPC;
|
||||
private snapshotIdsStack: number[];
|
||||
constructor() {
|
||||
this.rpc = new RPC();
|
||||
this.snapshotIdsStack = [];
|
||||
}
|
||||
// TODO: In order to run these tests on an actual node, we should check if we are running against
|
||||
// TestRPC, if so, use snapshots, otherwise re-deploy contracts before every test
|
||||
public async startAsync(): Promise<void> {
|
||||
const snapshotId = await this.rpc.takeSnapshotAsync();
|
||||
this.snapshotIdsStack.push(snapshotId);
|
||||
}
|
||||
public async revertAsync(): Promise<void> {
|
||||
const snapshotId = this.snapshotIdsStack.pop() as number;
|
||||
const didRevert = await this.rpc.revertSnapshotAsync(snapshotId);
|
||||
if (!didRevert) {
|
||||
throw new Error(`Snapshot with id #${snapshotId} failed to revert`);
|
||||
}
|
||||
}
|
||||
public async mineABlock(): Promise<void> {
|
||||
await this.rpc.mineBlockAsync();
|
||||
}
|
||||
}
|
@@ -1,7 +1,7 @@
|
||||
import * as chai from 'chai';
|
||||
import * as dirtyChai from 'dirty-chai';
|
||||
import ChaiBigNumber = require('chai-bignumber');
|
||||
import chaiAsPromised = require('chai-as-promised');
|
||||
import ChaiBigNumber = require('chai-bignumber');
|
||||
import * as dirtyChai from 'dirty-chai';
|
||||
|
||||
export const chaiSetup = {
|
||||
configure() {
|
||||
|
@@ -1,8 +1,11 @@
|
||||
export const constants = {
|
||||
NULL_ADDRESS: '0x0000000000000000000000000000000000000000',
|
||||
RPC_HOST: 'localhost',
|
||||
RPC_PORT: 8545,
|
||||
RPC_URL: 'http://localhost:8545/',
|
||||
ROPSTEN_NETWORK_ID: 3,
|
||||
KOVAN_NETWORK_ID: 42,
|
||||
TESTRPC_NETWORK_ID: 50,
|
||||
KOVAN_RPC_URL: 'https://kovan.infura.io',
|
||||
ROPSTEN_RPC_URL: 'https://ropsten.infura.io',
|
||||
KOVAN_RPC_URL: 'https://kovan.infura.io/',
|
||||
ROPSTEN_RPC_URL: 'https://ropsten.infura.io/',
|
||||
ZRX_DECIMALS: 18,
|
||||
GAS_ESTIMATE: 500000,
|
||||
};
|
||||
|
@@ -1,23 +1,47 @@
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import {ZeroEx, Token, SignedOrder} from '../../src';
|
||||
|
||||
import {SignedOrder, Token, ZeroEx} from '../../src';
|
||||
import {artifacts} from '../../src/artifacts';
|
||||
import {DummyTokenContract} from '../../src/contract_wrappers/generated/dummy_token';
|
||||
import {orderFactory} from '../utils/order_factory';
|
||||
|
||||
import {constants} from './constants';
|
||||
|
||||
const INITIAL_COINBASE_TOKEN_SUPPLY_IN_UNITS = new BigNumber(100);
|
||||
|
||||
export class FillScenarios {
|
||||
private zeroEx: ZeroEx;
|
||||
private userAddresses: string[];
|
||||
private tokens: Token[];
|
||||
private coinbase: string;
|
||||
private zrxTokenAddress: string;
|
||||
private exchangeContractAddress: string;
|
||||
private _zeroEx: ZeroEx;
|
||||
private _userAddresses: string[];
|
||||
private _tokens: Token[];
|
||||
private _coinbase: string;
|
||||
private _zrxTokenAddress: string;
|
||||
private _exchangeContractAddress: string;
|
||||
constructor(zeroEx: ZeroEx, userAddresses: string[],
|
||||
tokens: Token[], zrxTokenAddress: string, exchangeContractAddress: string) {
|
||||
this.zeroEx = zeroEx;
|
||||
this.userAddresses = userAddresses;
|
||||
this.tokens = tokens;
|
||||
this.coinbase = userAddresses[0];
|
||||
this.zrxTokenAddress = zrxTokenAddress;
|
||||
this.exchangeContractAddress = exchangeContractAddress;
|
||||
this._zeroEx = zeroEx;
|
||||
this._userAddresses = userAddresses;
|
||||
this._tokens = tokens;
|
||||
this._coinbase = userAddresses[0];
|
||||
this._zrxTokenAddress = zrxTokenAddress;
|
||||
this._exchangeContractAddress = exchangeContractAddress;
|
||||
}
|
||||
public async initTokenBalancesAsync() {
|
||||
const web3Wrapper = (this._zeroEx as any)._web3Wrapper as Web3Wrapper;
|
||||
for (const token of this._tokens) {
|
||||
if (token.symbol !== 'ZRX' && token.symbol !== 'WETH') {
|
||||
const contractInstance = web3Wrapper.getContractInstance(
|
||||
artifacts.DummyTokenArtifact.abi, token.address,
|
||||
);
|
||||
const defaults = {};
|
||||
const dummyToken = new DummyTokenContract(contractInstance, defaults);
|
||||
const tokenSupply = ZeroEx.toBaseUnitAmount(INITIAL_COINBASE_TOKEN_SUPPLY_IN_UNITS, token.decimals);
|
||||
const txHash = await dummyToken.setBalance.sendTransactionAsync(this._coinbase, tokenSupply, {
|
||||
from: this._coinbase,
|
||||
});
|
||||
await this._zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
}
|
||||
}
|
||||
}
|
||||
public async createFillableSignedOrderAsync(makerTokenAddress: string, takerTokenAddress: string,
|
||||
makerAddress: string, takerAddress: string,
|
||||
@@ -36,7 +60,7 @@ export class FillScenarios {
|
||||
fillableAmount: BigNumber,
|
||||
feeRecepient: string, expirationUnixTimestampSec?: BigNumber,
|
||||
): Promise<SignedOrder> {
|
||||
return this.createAsymmetricFillableSignedOrderWithFeesAsync(
|
||||
return this._createAsymmetricFillableSignedOrderWithFeesAsync(
|
||||
makerTokenAddress, takerTokenAddress, makerFee, takerFee, makerAddress, takerAddress,
|
||||
fillableAmount, fillableAmount, feeRecepient, expirationUnixTimestampSec,
|
||||
);
|
||||
@@ -48,7 +72,7 @@ export class FillScenarios {
|
||||
const makerFee = new BigNumber(0);
|
||||
const takerFee = new BigNumber(0);
|
||||
const feeRecepient = constants.NULL_ADDRESS;
|
||||
return this.createAsymmetricFillableSignedOrderWithFeesAsync(
|
||||
return this._createAsymmetricFillableSignedOrderWithFeesAsync(
|
||||
makerTokenAddress, takerTokenAddress, makerFee, takerFee, makerAddress, takerAddress,
|
||||
makerFillableAmount, takerFillableAmount, feeRecepient, expirationUnixTimestampSec,
|
||||
);
|
||||
@@ -56,18 +80,18 @@ export class FillScenarios {
|
||||
public async createPartiallyFilledSignedOrderAsync(makerTokenAddress: string, takerTokenAddress: string,
|
||||
takerAddress: string, fillableAmount: BigNumber,
|
||||
partialFillAmount: BigNumber) {
|
||||
const [makerAddress] = this.userAddresses;
|
||||
const [makerAddress] = this._userAddresses;
|
||||
const signedOrder = await this.createAsymmetricFillableSignedOrderAsync(
|
||||
makerTokenAddress, takerTokenAddress, makerAddress, takerAddress,
|
||||
fillableAmount, fillableAmount,
|
||||
);
|
||||
const shouldThrowOnInsufficientBalanceOrAllowance = false;
|
||||
await this.zeroEx.exchange.fillOrderAsync(
|
||||
await this._zeroEx.exchange.fillOrderAsync(
|
||||
signedOrder, partialFillAmount, shouldThrowOnInsufficientBalanceOrAllowance, takerAddress,
|
||||
);
|
||||
return signedOrder;
|
||||
}
|
||||
private async createAsymmetricFillableSignedOrderWithFeesAsync(
|
||||
private async _createAsymmetricFillableSignedOrderWithFeesAsync(
|
||||
makerTokenAddress: string, takerTokenAddress: string,
|
||||
makerFee: BigNumber, takerFee: BigNumber,
|
||||
makerAddress: string, takerAddress: string,
|
||||
@@ -75,39 +99,39 @@ export class FillScenarios {
|
||||
feeRecepient: string, expirationUnixTimestampSec?: BigNumber): Promise<SignedOrder> {
|
||||
|
||||
await Promise.all([
|
||||
this.increaseBalanceAndAllowanceAsync(makerTokenAddress, makerAddress, makerFillableAmount),
|
||||
this.increaseBalanceAndAllowanceAsync(takerTokenAddress, takerAddress, takerFillableAmount),
|
||||
this._increaseBalanceAndAllowanceAsync(makerTokenAddress, makerAddress, makerFillableAmount),
|
||||
this._increaseBalanceAndAllowanceAsync(takerTokenAddress, takerAddress, takerFillableAmount),
|
||||
]);
|
||||
await Promise.all([
|
||||
this.increaseBalanceAndAllowanceAsync(this.zrxTokenAddress, makerAddress, makerFee),
|
||||
this.increaseBalanceAndAllowanceAsync(this.zrxTokenAddress, takerAddress, takerFee),
|
||||
this._increaseBalanceAndAllowanceAsync(this._zrxTokenAddress, makerAddress, makerFee),
|
||||
this._increaseBalanceAndAllowanceAsync(this._zrxTokenAddress, takerAddress, takerFee),
|
||||
]);
|
||||
|
||||
const signedOrder = await orderFactory.createSignedOrderAsync(this.zeroEx,
|
||||
const signedOrder = await orderFactory.createSignedOrderAsync(this._zeroEx,
|
||||
makerAddress, takerAddress, makerFee, takerFee,
|
||||
makerFillableAmount, makerTokenAddress, takerFillableAmount, takerTokenAddress,
|
||||
this.exchangeContractAddress, feeRecepient, expirationUnixTimestampSec);
|
||||
this._exchangeContractAddress, feeRecepient, expirationUnixTimestampSec);
|
||||
return signedOrder;
|
||||
}
|
||||
private async increaseBalanceAndAllowanceAsync(
|
||||
private async _increaseBalanceAndAllowanceAsync(
|
||||
tokenAddress: string, address: string, amount: BigNumber): Promise<void> {
|
||||
if (amount.isZero() || address === ZeroEx.NULL_ADDRESS) {
|
||||
return; // noop
|
||||
}
|
||||
await Promise.all([
|
||||
this.increaseBalanceAsync(tokenAddress, address, amount),
|
||||
this.increaseAllowanceAsync(tokenAddress, address, amount),
|
||||
this._increaseBalanceAsync(tokenAddress, address, amount),
|
||||
this._increaseAllowanceAsync(tokenAddress, address, amount),
|
||||
]);
|
||||
}
|
||||
private async increaseBalanceAsync(
|
||||
private async _increaseBalanceAsync(
|
||||
tokenAddress: string, address: string, amount: BigNumber): Promise<void> {
|
||||
await this.zeroEx.token.transferAsync(tokenAddress, this.coinbase, address, amount);
|
||||
await this._zeroEx.token.transferAsync(tokenAddress, this._coinbase, address, amount);
|
||||
}
|
||||
private async increaseAllowanceAsync(
|
||||
private async _increaseAllowanceAsync(
|
||||
tokenAddress: string, address: string, amount: BigNumber): Promise<void> {
|
||||
const oldMakerAllowance = await this.zeroEx.token.getProxyAllowanceAsync(tokenAddress, address);
|
||||
const oldMakerAllowance = await this._zeroEx.token.getProxyAllowanceAsync(tokenAddress, address);
|
||||
const newMakerAllowance = oldMakerAllowance.plus(amount);
|
||||
await this.zeroEx.token.setProxyAllowanceAsync(
|
||||
await this._zeroEx.token.setProxyAllowanceAsync(
|
||||
tokenAddress, address, newMakerAllowance,
|
||||
);
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
import * as _ from 'lodash';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import {ZeroEx, SignedOrder} from '../../src';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {SignedOrder, ZeroEx} from '../../src';
|
||||
|
||||
export const orderFactory = {
|
||||
async createSignedOrderAsync(
|
||||
@@ -15,11 +16,11 @@ export const orderFactory = {
|
||||
takerTokenAddress: string,
|
||||
exchangeContractAddress: string,
|
||||
feeRecipient: string,
|
||||
expirationUnixTimestampSec?: BigNumber): Promise<SignedOrder> {
|
||||
expirationUnixTimestampSecIfExists?: BigNumber): Promise<SignedOrder> {
|
||||
const defaultExpirationUnixTimestampSec = new BigNumber(2524604400); // Close to infinite
|
||||
expirationUnixTimestampSec = _.isUndefined(expirationUnixTimestampSec) ?
|
||||
const expirationUnixTimestampSec = _.isUndefined(expirationUnixTimestampSecIfExists) ?
|
||||
defaultExpirationUnixTimestampSec :
|
||||
expirationUnixTimestampSec;
|
||||
expirationUnixTimestampSecIfExists;
|
||||
const order = {
|
||||
maker,
|
||||
taker,
|
||||
|
@@ -1,8 +1,8 @@
|
||||
import { DoneCallback } from '../../src/types';
|
||||
import {DoneCallback} from '../../src/types';
|
||||
|
||||
export const reportCallbackErrors = (done: DoneCallback) => {
|
||||
return (f: (...args: any[]) => void) => {
|
||||
const wrapped = (...args: any[]) => {
|
||||
const wrapped = async (...args: any[]) => {
|
||||
try {
|
||||
f(...args);
|
||||
} catch (err) {
|
||||
|
@@ -1,11 +1,13 @@
|
||||
import {JSONRPCPayload} from '../types';
|
||||
import {JSONRPCPayload} from '../../../src/types';
|
||||
|
||||
/*
|
||||
* This class implements the web3-provider-engine subprovider interface and returns
|
||||
* that the provider has no addresses when queried.
|
||||
* Source: https://github.com/MetaMask/provider-engine/blob/master/subproviders/subprovider.js
|
||||
*/
|
||||
export class EmptyWalletSubProvider {
|
||||
export class EmptyWalletSubprovider {
|
||||
// This method needs to be here to satisfy the interface but linter wants it to be static.
|
||||
// tslint:disable-next-line:prefer-function-over-method
|
||||
public handleRequest(payload: JSONRPCPayload, next: () => void, end: (err: Error|null, result: any) => void) {
|
||||
switch (payload.method) {
|
||||
case 'eth_accounts':
|
||||
@@ -18,6 +20,7 @@ export class EmptyWalletSubProvider {
|
||||
}
|
||||
}
|
||||
// Required to implement this method despite not needing it for this subprovider
|
||||
// tslint:disable-next-line:prefer-function-over-method
|
||||
public setEngine(engine: any) {
|
||||
// noop
|
||||
}
|
@@ -0,0 +1,34 @@
|
||||
import {JSONRPCPayload} from '../../../src/types';
|
||||
|
||||
/*
|
||||
* This class implements the web3-provider-engine subprovider interface and returns
|
||||
* the constant gas estimate when queried.
|
||||
* HACK: We need this so that our tests don't use testrpc gas estimation which sometimes kills the node.
|
||||
* Source: https://github.com/trufflesuite/ganache-cli/issues/417
|
||||
* Source: https://github.com/trufflesuite/ganache-cli/issues/437
|
||||
* Source: https://github.com/MetaMask/provider-engine/blob/master/subproviders/subprovider.js
|
||||
*/
|
||||
export class FakeGasEstimateSubprovider {
|
||||
private _constantGasAmount: number;
|
||||
constructor(constantGasAmount: number) {
|
||||
this._constantGasAmount = constantGasAmount;
|
||||
}
|
||||
// This method needs to be here to satisfy the interface but linter wants it to be static.
|
||||
// tslint:disable-next-line:prefer-function-over-method
|
||||
public handleRequest(payload: JSONRPCPayload, next: () => void, end: (err: Error|null, result: any) => void) {
|
||||
switch (payload.method) {
|
||||
case 'eth_estimateGas':
|
||||
end(null, this._constantGasAmount);
|
||||
return;
|
||||
|
||||
default:
|
||||
next();
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Required to implement this method despite not needing it for this subprovider
|
||||
// tslint:disable-next-line:prefer-function-over-method
|
||||
public setEngine(engine: any) {
|
||||
// noop
|
||||
}
|
||||
}
|
@@ -1,24 +1,33 @@
|
||||
import * as _ from 'lodash';
|
||||
import {Token, InternalZeroExError} from '../../src/types';
|
||||
|
||||
import {InternalZeroExError, Token} from '../../src/types';
|
||||
|
||||
const PROTOCOL_TOKEN_SYMBOL = 'ZRX';
|
||||
const WETH_TOKEN_SYMBOL = 'WETH';
|
||||
|
||||
export class TokenUtils {
|
||||
private tokens: Token[];
|
||||
private _tokens: Token[];
|
||||
constructor(tokens: Token[]) {
|
||||
this.tokens = tokens;
|
||||
this._tokens = tokens;
|
||||
}
|
||||
public getProtocolTokenOrThrow(): Token {
|
||||
const zrxToken = _.find(this.tokens, {symbol: PROTOCOL_TOKEN_SYMBOL});
|
||||
const zrxToken = _.find(this._tokens, {symbol: PROTOCOL_TOKEN_SYMBOL});
|
||||
if (_.isUndefined(zrxToken)) {
|
||||
throw new Error(InternalZeroExError.ZrxNotInTokenRegistry);
|
||||
}
|
||||
return zrxToken;
|
||||
}
|
||||
public getNonProtocolTokens(): Token[] {
|
||||
const nonProtocolTokens = _.filter(this.tokens, token => {
|
||||
return token.symbol !== PROTOCOL_TOKEN_SYMBOL;
|
||||
public getWethTokenOrThrow(): Token {
|
||||
const wethToken = _.find(this._tokens, {symbol: WETH_TOKEN_SYMBOL});
|
||||
if (_.isUndefined(wethToken)) {
|
||||
throw new Error(InternalZeroExError.WethNotInTokenRegistry);
|
||||
}
|
||||
return wethToken;
|
||||
}
|
||||
public getDummyTokens(): Token[] {
|
||||
const dummyTokens = _.filter(this._tokens, token => {
|
||||
return !_.includes([PROTOCOL_TOKEN_SYMBOL, WETH_TOKEN_SYMBOL], token.symbol);
|
||||
});
|
||||
return nonProtocolTokens;
|
||||
return dummyTokens;
|
||||
}
|
||||
}
|
||||
|
@@ -5,9 +5,18 @@
|
||||
(global as any).XMLHttpRequest = undefined;
|
||||
import ProviderEngine = require('web3-provider-engine');
|
||||
import RpcSubprovider = require('web3-provider-engine/subproviders/rpc');
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {EmptyWalletSubprovider} from './subproviders/empty_wallet_subprovider';
|
||||
import {FakeGasEstimateSubprovider} from './subproviders/fake_gas_estimate_subprovider';
|
||||
|
||||
import {constants} from './constants';
|
||||
import {EmptyWalletSubProvider} from '../../src/subproviders/empty_wallet_subprovider';
|
||||
|
||||
// HACK: web3 leaks XMLHttpRequest into the global scope and causes requests to hang
|
||||
// because they are using the wrong XHR package.
|
||||
// importing web3 after subproviders fixes this issue
|
||||
// Filed issue: https://github.com/ethereum/web3.js/issues/844
|
||||
// tslint:disable-next-line:ordered-imports
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
export const web3Factory = {
|
||||
create(hasAddresses: boolean = true): Web3 {
|
||||
@@ -18,12 +27,12 @@ export const web3Factory = {
|
||||
},
|
||||
getRpcProvider(hasAddresses: boolean = true): Web3.Provider {
|
||||
const provider = new ProviderEngine();
|
||||
const rpcUrl = `http://${constants.RPC_HOST}:${constants.RPC_PORT}`;
|
||||
if (!hasAddresses) {
|
||||
provider.addProvider(new EmptyWalletSubProvider());
|
||||
provider.addProvider(new EmptyWalletSubprovider());
|
||||
}
|
||||
provider.addProvider(new FakeGasEstimateSubprovider(constants.GAS_ESTIMATE));
|
||||
provider.addProvider(new RpcSubprovider({
|
||||
rpcUrl,
|
||||
rpcUrl: constants.RPC_URL,
|
||||
}));
|
||||
provider.start();
|
||||
return provider;
|
||||
|
@@ -1,29 +0,0 @@
|
||||
import * as chai from 'chai';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
import {ZeroEx} from '../src/';
|
||||
import {Web3Wrapper} from '../src/web3_wrapper';
|
||||
import {constants} from './utils/constants';
|
||||
|
||||
chai.config.includeStack = true;
|
||||
const expect = chai.expect;
|
||||
|
||||
describe('Web3Wrapper', () => {
|
||||
const web3Provider = web3Factory.create().currentProvider;
|
||||
describe('#getNetworkIdIfExistsAsync', () => {
|
||||
it('caches network id requests', async () => {
|
||||
const web3Wrapper = (new ZeroEx(web3Provider) as any)._web3Wrapper as Web3Wrapper;
|
||||
expect((web3Wrapper as any).networkIdIfExists).to.be.undefined();
|
||||
const networkIdIfExists = await web3Wrapper.getNetworkIdIfExistsAsync();
|
||||
expect((web3Wrapper as any).networkIdIfExists).to.be.equal(constants.TESTRPC_NETWORK_ID);
|
||||
});
|
||||
it('invalidates network id cache on setProvider call', async () => {
|
||||
const web3Wrapper = (new ZeroEx(web3Provider) as any)._web3Wrapper as Web3Wrapper;
|
||||
expect((web3Wrapper as any).networkIdIfExists).to.be.undefined();
|
||||
const networkIdIfExists = await web3Wrapper.getNetworkIdIfExistsAsync();
|
||||
expect((web3Wrapper as any).networkIdIfExists).to.be.equal(constants.TESTRPC_NETWORK_ID);
|
||||
const newProvider = web3Factory.create().currentProvider;
|
||||
web3Wrapper.setProvider(newProvider);
|
||||
expect((web3Wrapper as any).networkIdIfExists).to.be.undefined();
|
||||
});
|
||||
});
|
||||
});
|
4
packages/abi-gen/CHANGELOG.md
Normal file
4
packages/abi-gen/CHANGELOG.md
Normal file
@@ -0,0 +1,4 @@
|
||||
# CHANGELOG
|
||||
|
||||
vx.x.x
|
||||
------------------------
|
39
packages/abi-gen/README.md
Normal file
39
packages/abi-gen/README.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# ABI Gen
|
||||
|
||||
This package allows you to generate TypeScript contract wrappers from ABI files.
|
||||
It's heavily inspired by [Geth abigen](https://github.com/ethereum/go-ethereum/wiki/Native-DApps:-Go-bindings-to-Ethereum-contracts) but takes a different approach.
|
||||
You can write your custom handlebars templates which will allow you to seamlessly integrate the generated code into your existing codebase with existing conventions.
|
||||
|
||||
For an example of the generated [wrapper files](https://github.com/0xProject/0x.js/tree/development/packages/0x.js/src/contract_wrappers/generated) check out 0x.js.
|
||||
[Here](https://github.com/0xProject/0x.js/tree/development/packages/0x.js/contract_templates) are the templates used to generate those files.
|
||||
|
||||
## Installation
|
||||
`yarn add -g @0xproject/abi-gen`
|
||||
## Usage
|
||||
```
|
||||
abi-gen
|
||||
Options:
|
||||
--help Show help [boolean]
|
||||
--version Show version number [boolean]
|
||||
--abiGlob Glob pattern to search for ABI JSON files [string] [required]
|
||||
--templates Folder where to search for templates [string] [required]
|
||||
--output Folder where to put the output files [string] [required]
|
||||
```
|
||||
## ABI files
|
||||
You're required to pass a [glob](https://en.wikipedia.org/wiki/Glob_(programming)) template where your abi files are located.
|
||||
TL;DR - here is the example from 0x.js.
|
||||
|
||||
`--abiGlob 'src/artifacts/@(Exchange|Token|TokenTransferProxy|EtherToken|TokenRegistry).json`
|
||||
|
||||
We could've just used `--abiGlob 'src/artifacts/*.json` but we wanted to exclude some of the abi files.
|
||||
|
||||
The abi file should be either a [Truffle](http://truffleframework.com/) contract artifact (a JSON object with an abi key) or a JSON abi array.
|
||||
## How to write custom templates?
|
||||
The best way to get started is to copy [0x.js templates](https://github.com/0xProject/0x.js/tree/development/packages/0x.js/contract_templates) and start adjusting them for your needs.
|
||||
We use [handlebars](http://handlebarsjs.com/) template engine under the hood.
|
||||
You need to have a master template called `contract.mustache`. it will be used to generate each contract wrapper. Although - you don't need and probably shouldn't write all your logic in a single template file. You can write [partial templates](http://handlebarsjs.com/partials.html) and as long as they are within a partials folder - they will be registered and available.
|
||||
## Which data/context do I get in my templates?
|
||||
For now you don't get much on top of methods abi, some useful helpers and a contract name because it was enough for our use-case, but if you need something else - create a PR.
|
||||
See the [type definition](https://github.com/0xProject/0x.js/tree/development/packages/abi-gen/src/types.ts) of what we pass to the render method.
|
||||
## Output files
|
||||
Output files will be generated within an output folder with names converted to camel case and taken from abi file names. If you already have some files in that folder they will be overwritten.
|
48
packages/abi-gen/package.json
Normal file
48
packages/abi-gen/package.json
Normal file
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"name": "@0xproject/abi-gen",
|
||||
"version": "0.0.4",
|
||||
"description": "Generate contract wrappers from ABI and handlebars templates",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/index.d.ts",
|
||||
"scripts": {
|
||||
"lint": "tslint --project . 'src/**/*.ts'",
|
||||
"clean": "shx rm -rf lib",
|
||||
"build": "tsc"
|
||||
},
|
||||
"bin": {
|
||||
"abi-gen": "lib/index.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/0xProject/0x.js.git"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/0xProject/0x.js/issues"
|
||||
},
|
||||
"homepage": "https://github.com/0xProject/0x.js/packages/abi-gen/README.md",
|
||||
"dependencies": {
|
||||
"bignumber.js": "~4.1.0",
|
||||
"chalk": "^2.3.0",
|
||||
"glob": "^7.1.2",
|
||||
"handlebars": "^4.0.11",
|
||||
"lodash": "^4.17.4",
|
||||
"mkdirp": "^0.5.1",
|
||||
"to-snake-case": "^1.0.0",
|
||||
"web3": "^0.20.0",
|
||||
"yargs": "^10.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@0xproject/tslint-config": "^0.4.0",
|
||||
"@types/glob": "^5.0.33",
|
||||
"@types/handlebars": "^4.0.36",
|
||||
"@types/mkdirp": "^0.5.1",
|
||||
"@types/node": "^8.0.53",
|
||||
"@types/yargs": "^10.0.0",
|
||||
"npm-run-all": "^4.1.2",
|
||||
"shx": "^0.2.2",
|
||||
"tslint": "5.8.0",
|
||||
"typescript": "~2.6.1",
|
||||
"web3-typescript-typings": "^0.7.2"
|
||||
}
|
||||
}
|
14
packages/abi-gen/scripts/postpublish.js
Normal file
14
packages/abi-gen/scripts/postpublish.js
Normal file
@@ -0,0 +1,14 @@
|
||||
const postpublish_utils = require('../../../scripts/postpublish_utils');
|
||||
const packageJSON = require('../package.json');
|
||||
|
||||
const subPackageName = packageJSON.name;
|
||||
|
||||
postpublish_utils.getLatestTagAndVersionAsync(subPackageName)
|
||||
.then(function(result) {
|
||||
const releaseName = postpublish_utils.getReleaseName(subPackageName, result.version);
|
||||
const assets = [];
|
||||
return postpublish_utils.publishReleaseNotes(result.tag, releaseName, assets);
|
||||
})
|
||||
.catch (function(err) {
|
||||
throw err;
|
||||
});
|
4
packages/abi-gen/src/globals.d.ts
vendored
Normal file
4
packages/abi-gen/src/globals.d.ts
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
declare function toSnakeCase(str: string): string;
|
||||
declare module 'to-snake-case' {
|
||||
export = toSnakeCase;
|
||||
}
|
98
packages/abi-gen/src/index.ts
Normal file
98
packages/abi-gen/src/index.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import chalk from 'chalk';
|
||||
import * as fs from 'fs';
|
||||
import {sync as globSync} from 'glob';
|
||||
import * as Handlebars from 'handlebars';
|
||||
import * as _ from 'lodash';
|
||||
import * as mkdirp from 'mkdirp';
|
||||
import * as yargs from 'yargs';
|
||||
|
||||
import toSnakeCase = require('to-snake-case');
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {ContextData, ParamKind} from './types';
|
||||
import {utils} from './utils';
|
||||
|
||||
const ABI_TYPE_METHOD = 'function';
|
||||
const MAIN_TEMPLATE_NAME = 'contract.mustache';
|
||||
|
||||
const args = yargs
|
||||
.option('abiGlob', {
|
||||
describe: 'Glob pattern to search for ABI JSON files',
|
||||
type: 'string',
|
||||
demand: true,
|
||||
})
|
||||
.option('templates', {
|
||||
describe: 'Folder where to search for templates',
|
||||
type: 'string',
|
||||
demand: true,
|
||||
})
|
||||
.option('output', {
|
||||
describe: 'Folder where to put the output files',
|
||||
type: 'string',
|
||||
demand: true,
|
||||
})
|
||||
.argv;
|
||||
|
||||
function writeOutputFile(name: string, renderedTsCode: string): void {
|
||||
const fileName = toSnakeCase(name);
|
||||
const filePath = `${args.output}/${fileName}.ts`;
|
||||
fs.writeFileSync(filePath, renderedTsCode);
|
||||
utils.log(`Created: ${chalk.bold(filePath)}`);
|
||||
}
|
||||
|
||||
Handlebars.registerHelper('parameterType', utils.solTypeToTsType.bind(utils, ParamKind.Input));
|
||||
Handlebars.registerHelper('returnType', utils.solTypeToTsType.bind(utils, ParamKind.Output));
|
||||
const partialTemplateFileNames = globSync(`${args.templates}/partials/**/*.mustache`);
|
||||
for (const partialTemplateFileName of partialTemplateFileNames) {
|
||||
const namedContent = utils.getNamedContent(partialTemplateFileName);
|
||||
Handlebars.registerPartial(namedContent.name, namedContent.content);
|
||||
}
|
||||
|
||||
const mainTemplate = utils.getNamedContent(`${args.templates}/${MAIN_TEMPLATE_NAME}`);
|
||||
const template = Handlebars.compile<ContextData>(mainTemplate.content);
|
||||
const abiFileNames = globSync(args.abiGlob);
|
||||
if (_.isEmpty(abiFileNames)) {
|
||||
utils.log(`${chalk.red(`No ABI files found.`)}`);
|
||||
utils.log(`Please make sure you've passed the correct folder name and that the files have
|
||||
${chalk.bold('*.json')} extensions`);
|
||||
process.exit(1);
|
||||
} else {
|
||||
utils.log(`Found ${chalk.green(`${abiFileNames.length}`)} ${chalk.bold('ABI')} files`);
|
||||
mkdirp.sync(args.output);
|
||||
}
|
||||
for (const abiFileName of abiFileNames) {
|
||||
const namedContent = utils.getNamedContent(abiFileName);
|
||||
utils.log(`Processing: ${chalk.bold(namedContent.name)}...`);
|
||||
const parsedContent = JSON.parse(namedContent.content);
|
||||
const ABI = _.isArray(parsedContent) ?
|
||||
parsedContent : // ABI file
|
||||
parsedContent.abi; // Truffle contracts file
|
||||
if (_.isUndefined(ABI)) {
|
||||
utils.log(`${chalk.red(`ABI not found in ${abiFileName}.`)}`);
|
||||
utils.log(`Please make sure your ABI file is either an array with ABI entries or an object with the abi key`);
|
||||
process.exit(1);
|
||||
}
|
||||
const methodAbis = ABI.filter((abi: Web3.AbiDefinition) => abi.type === ABI_TYPE_METHOD) as Web3.MethodAbi[];
|
||||
const methodsData = _.map(methodAbis, methodAbi => {
|
||||
_.map(methodAbi.inputs, input => {
|
||||
if (_.isEmpty(input.name)) {
|
||||
// Auto-generated getters don't have parameter names
|
||||
input.name = 'index';
|
||||
}
|
||||
});
|
||||
// This will make templates simpler
|
||||
const methodData = {
|
||||
...methodAbi,
|
||||
singleReturnValue: methodAbi.outputs.length === 1,
|
||||
};
|
||||
return methodData;
|
||||
});
|
||||
const contextData = {
|
||||
contractName: namedContent.name,
|
||||
methods: methodsData,
|
||||
};
|
||||
const renderedTsCode = template(contextData);
|
||||
writeOutputFile(namedContent.name, renderedTsCode);
|
||||
}
|
15
packages/abi-gen/src/types.ts
Normal file
15
packages/abi-gen/src/types.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
export enum ParamKind {
|
||||
Input = 'input',
|
||||
Output = 'output',
|
||||
}
|
||||
|
||||
export interface Method extends Web3.MethodAbi {
|
||||
singleReturnValue: boolean;
|
||||
}
|
||||
|
||||
export interface ContextData {
|
||||
contractName: string;
|
||||
methods: Method[];
|
||||
}
|
56
packages/abi-gen/src/utils.ts
Normal file
56
packages/abi-gen/src/utils.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import * as fs from 'fs';
|
||||
import * as _ from 'lodash';
|
||||
import * as path from 'path';
|
||||
|
||||
import {ParamKind} from './types';
|
||||
|
||||
export const utils = {
|
||||
solTypeToTsType(paramKind: ParamKind, solType: string): string {
|
||||
const trailingArrayRegex = /\[\d*\]$/;
|
||||
if (solType.match(trailingArrayRegex)) {
|
||||
const arrayItemSolType = solType.replace(trailingArrayRegex, '');
|
||||
const arrayItemTsType = utils.solTypeToTsType(paramKind, arrayItemSolType);
|
||||
const arrayTsType = `${arrayItemTsType}[]`;
|
||||
return arrayTsType;
|
||||
} else {
|
||||
const solTypeRegexToTsType = [
|
||||
{regex: '^string$', tsType: 'string'},
|
||||
{regex: '^address$', tsType: 'string'},
|
||||
{regex: '^bool$', tsType: 'boolean'},
|
||||
{regex: '^u?int\\d*$', tsType: 'BigNumber'},
|
||||
{regex: '^bytes\\d*$', tsType: 'string'},
|
||||
];
|
||||
if (paramKind === ParamKind.Input) {
|
||||
// web3 allows to pass those an non-bignumbers and that's nice
|
||||
// but it always returns stuff as BigNumbers
|
||||
solTypeRegexToTsType.unshift({regex: '^u?int(8|16|32)?$', tsType: 'number|BigNumber'});
|
||||
}
|
||||
for (const regexAndTxType of solTypeRegexToTsType) {
|
||||
const {regex, tsType} = regexAndTxType;
|
||||
if (solType.match(regex)) {
|
||||
return tsType;
|
||||
}
|
||||
}
|
||||
throw new Error(`Unknown Solidity type found: ${solType}`);
|
||||
}
|
||||
},
|
||||
log(...args: any[]): void {
|
||||
console.log(...args); // tslint:disable-line:no-console
|
||||
},
|
||||
getPartialNameFromFileName(filename: string): string {
|
||||
const name = path.parse(filename).name;
|
||||
return name;
|
||||
},
|
||||
getNamedContent(filename: string): {name: string; content: string} {
|
||||
const name = utils.getPartialNameFromFileName(filename);
|
||||
try {
|
||||
const content = fs.readFileSync(filename).toString();
|
||||
return {
|
||||
name,
|
||||
content,
|
||||
};
|
||||
} catch (err) {
|
||||
throw new Error(`Failed to read ${filename}: ${err}`);
|
||||
}
|
||||
},
|
||||
};
|
17
packages/abi-gen/tsconfig.json
Normal file
17
packages/abi-gen/tsconfig.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"target": "es5",
|
||||
"lib": ["es2015", "dom"],
|
||||
"outDir": "lib",
|
||||
"sourceMap": true,
|
||||
"declaration": true,
|
||||
"noImplicitAny": true,
|
||||
"strictNullChecks": true
|
||||
},
|
||||
"include": [
|
||||
"./src/**/*",
|
||||
"./test/**/*",
|
||||
"../../node_modules/web3-typescript-typings/index.d.ts"
|
||||
]
|
||||
}
|
5
packages/abi-gen/tslint.json
Normal file
5
packages/abi-gen/tslint.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": [
|
||||
"@0xproject/tslint-config"
|
||||
]
|
||||
}
|
@@ -1,10 +1,54 @@
|
||||
assert
|
||||
@0xproject/assert
|
||||
------
|
||||
|
||||
Standard type and schema assertions to be used across all 0x projects and packages
|
||||
|
||||
## Install
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @0xproject/assert --save
|
||||
yarn add @0xproject/assert
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```typescript
|
||||
import {assert} from '@0xproject/assert';
|
||||
|
||||
assert.isValidBaseUnitAmount('baseUnitAmount', baseUnitAmount);
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
We strongly encourage 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
|
||||
|
||||
```bash
|
||||
yarn build
|
||||
```
|
||||
|
||||
### Lint
|
||||
|
||||
```bash
|
||||
yarn lint
|
||||
```
|
||||
|
||||
### Run Tests
|
||||
|
||||
```bash
|
||||
yarn test
|
||||
```
|
||||
|
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"name": "@0xproject/assert",
|
||||
"version": "0.0.5",
|
||||
"version": "0.0.9",
|
||||
"description": "Provides a standard way of performing type and schema validation across 0x projects",
|
||||
"main": "lib/src/index.js",
|
||||
"types": "lib/src/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"clean": "shx rm -rf _bundles lib test_temp",
|
||||
"lint": "tslint src/**/*.ts test/**/*.ts",
|
||||
"lint": "tslint --project . 'src/**/*.ts' 'test/**/*.ts'",
|
||||
"run_mocha": "mocha lib/test/**/*_test.js",
|
||||
"prepublishOnly": "run-p build",
|
||||
"test": "run-s clean build run_mocha",
|
||||
@@ -23,23 +23,23 @@
|
||||
},
|
||||
"homepage": "https://github.com/0xProject/0x.js/packages/assert/README.md",
|
||||
"devDependencies": {
|
||||
"@0xproject/tslint-config": "^0.1.1",
|
||||
"@types/lodash": "^4.14.78",
|
||||
"@0xproject/tslint-config": "^0.4.0",
|
||||
"@types/lodash": "^4.14.86",
|
||||
"@types/mocha": "^2.2.42",
|
||||
"@types/valid-url": "^1.0.2",
|
||||
"chai": "^4.0.1",
|
||||
"chai-typescript-typings": "^0.0.1",
|
||||
"dirty-chai": "^2.0.1",
|
||||
"mocha": "^4.0.1",
|
||||
"npm-run-all": "^4.1.1",
|
||||
"npm-run-all": "^4.1.2",
|
||||
"shx": "^0.2.2",
|
||||
"tslint": "5.8.0",
|
||||
"typescript": "^2.4.2"
|
||||
"typescript": "~2.6.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@0xproject/json-schemas": "^0.6.8",
|
||||
"@0xproject/json-schemas": "^0.7.1",
|
||||
"@0xproject/utils": "^0.1.2",
|
||||
"bignumber.js": "~4.1.0",
|
||||
"ethereum-address": "^0.0.4",
|
||||
"lodash": "^4.17.4",
|
||||
"valid-url": "^1.0.9"
|
||||
}
|
||||
|
4
packages/assert/src/globals.d.ts
vendored
4
packages/assert/src/globals.d.ts
vendored
@@ -1,5 +1 @@
|
||||
declare module 'dirty-chai';
|
||||
|
||||
declare module 'ethereum-address' {
|
||||
const isAddress: (arg: any) => boolean;
|
||||
}
|
||||
|
@@ -1,11 +1,11 @@
|
||||
import {
|
||||
Schema,
|
||||
SchemaValidator,
|
||||
} from '@0xproject/json-schemas';
|
||||
import {addressUtils} from '@0xproject/utils';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as ethereum_address from 'ethereum-address';
|
||||
import * as _ from 'lodash';
|
||||
import * as validUrl from 'valid-url';
|
||||
import {
|
||||
SchemaValidator,
|
||||
Schema,
|
||||
} from '@0xproject/json-schemas';
|
||||
|
||||
const HEX_REGEX = /^0x[0-9A-F]*$/i;
|
||||
|
||||
@@ -35,9 +35,9 @@ export const assert = {
|
||||
this.typeAssertionMessage(variableName, 'HexString', value));
|
||||
},
|
||||
isETHAddressHex(variableName: string, value: string): void {
|
||||
this.assert(ethereum_address.isAddress(value), this.typeAssertionMessage(variableName, 'ETHAddressHex', value));
|
||||
this.assert(addressUtils.isAddress(value), this.typeAssertionMessage(variableName, 'ETHAddressHex', value));
|
||||
this.assert(
|
||||
ethereum_address.isAddress(value) && value.toLowerCase() === value,
|
||||
addressUtils.isAddress(value) && value.toLowerCase() === value,
|
||||
`Checksummed addresses are not supported. Convert ${variableName} to lower case before passing`,
|
||||
);
|
||||
},
|
||||
@@ -62,7 +62,7 @@ export const assert = {
|
||||
this.assert(_.isBoolean(value), this.typeAssertionMessage(variableName, 'boolean', value));
|
||||
},
|
||||
isWeb3Provider(variableName: string, value: any): void {
|
||||
const isWeb3Provider = _.isFunction((value as any).send) || _.isFunction((value as any).sendAsync);
|
||||
const isWeb3Provider = _.isFunction((value).send) || _.isFunction((value).sendAsync);
|
||||
this.assert(isWeb3Provider, this.typeAssertionMessage(variableName, 'Web3.Provider', value));
|
||||
},
|
||||
doesConformToSchema(variableName: string, value: any, schema: Schema): void {
|
||||
|
@@ -1,8 +1,9 @@
|
||||
import 'mocha';
|
||||
import * as dirtyChai from 'dirty-chai';
|
||||
import * as chai from 'chai';
|
||||
import {BigNumber} from 'bignumber.js';
|
||||
import {schemas} from '@0xproject/json-schemas';
|
||||
import {BigNumber} from 'bignumber.js';
|
||||
import * as chai from 'chai';
|
||||
import * as dirtyChai from 'dirty-chai';
|
||||
import 'mocha';
|
||||
|
||||
import {assert} from '../src/index';
|
||||
|
||||
chai.config.includeStack = true;
|
||||
@@ -24,7 +25,7 @@ describe('Assertions', () => {
|
||||
'test',
|
||||
42,
|
||||
false,
|
||||
{ random: 'test' },
|
||||
{random: 'test'},
|
||||
undefined,
|
||||
];
|
||||
invalidInputs.forEach(input => expect(assert.isBigNumber.bind(assert, variableName, input)).to.throw());
|
||||
@@ -42,7 +43,7 @@ describe('Assertions', () => {
|
||||
'test',
|
||||
42,
|
||||
false,
|
||||
{ random: 'test' },
|
||||
{random: 'test'},
|
||||
];
|
||||
invalidInputs.forEach(input => expect(assert.isUndefined.bind(assert, input, variableName)).to.throw());
|
||||
});
|
||||
@@ -59,7 +60,7 @@ describe('Assertions', () => {
|
||||
const invalidInputs = [
|
||||
42,
|
||||
false,
|
||||
{ random: 'test' },
|
||||
{random: 'test'},
|
||||
undefined,
|
||||
new BigNumber(45),
|
||||
];
|
||||
@@ -78,7 +79,7 @@ describe('Assertions', () => {
|
||||
const invalidInputs = [
|
||||
42,
|
||||
false,
|
||||
{ random: 'test' },
|
||||
{random: 'test'},
|
||||
undefined,
|
||||
new BigNumber(45),
|
||||
];
|
||||
@@ -97,7 +98,7 @@ describe('Assertions', () => {
|
||||
const invalidInputs = [
|
||||
42,
|
||||
false,
|
||||
{ random: 'test' },
|
||||
{random: 'test'},
|
||||
undefined,
|
||||
new BigNumber(45),
|
||||
'0x61a3ed31B43c8780e905a260a35faYfEc527be7516aa11c0256729b5b351bc33',
|
||||
@@ -120,7 +121,7 @@ describe('Assertions', () => {
|
||||
const invalidInputs = [
|
||||
42,
|
||||
false,
|
||||
{ random: 'test' },
|
||||
{random: 'test'},
|
||||
undefined,
|
||||
new BigNumber(45),
|
||||
'0x6FFFd0ae3f7d88c9b4925323f54c6e4b2918c5fd',
|
||||
@@ -149,7 +150,7 @@ describe('Assertions', () => {
|
||||
const invalidInputs = [
|
||||
42,
|
||||
false,
|
||||
{ random: 'test' },
|
||||
{random: 'test'},
|
||||
undefined,
|
||||
new BigNumber(45),
|
||||
];
|
||||
@@ -183,7 +184,7 @@ describe('Assertions', () => {
|
||||
it('should not throw for valid input', () => {
|
||||
const validInputs = [
|
||||
42,
|
||||
0.00,
|
||||
0,
|
||||
21e+42,
|
||||
];
|
||||
validInputs.forEach(input => expect(assert.isNumber.bind(assert, variableName, input)).to.not.throw());
|
||||
@@ -191,7 +192,7 @@ describe('Assertions', () => {
|
||||
it('should throw for invalid input', () => {
|
||||
const invalidInputs = [
|
||||
false,
|
||||
{ random: 'test' },
|
||||
{random: 'test'},
|
||||
undefined,
|
||||
new BigNumber(45),
|
||||
];
|
||||
@@ -209,7 +210,7 @@ describe('Assertions', () => {
|
||||
it('should throw for invalid input', () => {
|
||||
const invalidInputs = [
|
||||
42,
|
||||
{ random: 'test' },
|
||||
{random: 'test'},
|
||||
undefined,
|
||||
new BigNumber(45),
|
||||
];
|
||||
@@ -219,8 +220,8 @@ describe('Assertions', () => {
|
||||
describe('#isWeb3Provider', () => {
|
||||
it('should not throw for valid input', () => {
|
||||
const validInputs = [
|
||||
{ send: () => 45 },
|
||||
{ sendAsync: () => 45 },
|
||||
{send: () => 45},
|
||||
{sendAsync: () => 45},
|
||||
];
|
||||
validInputs.forEach(input =>
|
||||
expect(assert.isWeb3Provider.bind(assert, variableName, input)).to.not.throw(),
|
||||
@@ -229,7 +230,7 @@ describe('Assertions', () => {
|
||||
it('should throw for invalid input', () => {
|
||||
const invalidInputs = [
|
||||
42,
|
||||
{ random: 'test' },
|
||||
{random: 'test'},
|
||||
undefined,
|
||||
new BigNumber(45),
|
||||
];
|
||||
@@ -252,7 +253,7 @@ describe('Assertions', () => {
|
||||
it('should throw for invalid input', () => {
|
||||
const invalidInputs = [
|
||||
42,
|
||||
{ random: 'test' },
|
||||
{random: 'test'},
|
||||
undefined,
|
||||
new BigNumber(45),
|
||||
];
|
||||
@@ -276,7 +277,7 @@ describe('Assertions', () => {
|
||||
it('should throw for invalid input', () => {
|
||||
const invalidInputs = [
|
||||
42,
|
||||
{ random: 'test' },
|
||||
{random: 'test'},
|
||||
undefined,
|
||||
new BigNumber(45),
|
||||
'ws://www.api.example-relayer.net',
|
||||
@@ -308,7 +309,7 @@ describe('Assertions', () => {
|
||||
it('should throw for invalid input', () => {
|
||||
const invalidInputs = [
|
||||
42,
|
||||
{ random: 'test' },
|
||||
{random: 'test'},
|
||||
undefined,
|
||||
new BigNumber(45),
|
||||
'www.google.com',
|
||||
|
@@ -1,4 +1,16 @@
|
||||
# CHANGELOG
|
||||
|
||||
v0.0.0 - _Nov. 15, 2017_
|
||||
v0.3.0 - _December 8, 2017_
|
||||
------------------------
|
||||
* Expose WebSocketOrderbookChannel and associated types to public interface (#251)
|
||||
* Remove tokenA and tokenB fields from OrdersRequest (#256)
|
||||
|
||||
v0.2.0 - _November 29, 2017_
|
||||
------------------------
|
||||
* Add SignedOrder and TokenTradeInfo to the public interface
|
||||
* Add ECSignature and Order to the public interface
|
||||
* Remove dependency on 0x.js
|
||||
|
||||
v0.1.0 - _November 22, 2017_
|
||||
------------------------
|
||||
* Provide a HttpClient class for interacting with standard relayer api compliant HTTP urls
|
||||
|
@@ -1 +1,51 @@
|
||||
@0xproject/connect
|
||||
------
|
||||
|
||||
This repository contains a Javascript library that makes it easy to interact with Relayers that conform to the [Standard Relayer API](https://github.com/0xProject/standard-relayer-api)
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
yarn add @0xproject/connect
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
* [Docs](https://0xproject.com/docs/connect)
|
||||
* [Tutorials](https://0xproject.com/wiki#connect)
|
||||
|
||||
## 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
|
||||
|
||||
```bash
|
||||
yarn build
|
||||
```
|
||||
|
||||
### Lint
|
||||
|
||||
```bash
|
||||
yarn lint
|
||||
```
|
||||
|
||||
### Run Tests
|
||||
|
||||
```bash
|
||||
yarn test
|
||||
```
|
||||
|
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "@0xproject/connect",
|
||||
"version": "0.0.1",
|
||||
"version": "0.3.2",
|
||||
"description": "A javascript library for interacting with the standard relayer api",
|
||||
"keywords": [
|
||||
"0x-connect",
|
||||
"connect",
|
||||
"0xproject",
|
||||
"ethereum",
|
||||
"tokens",
|
||||
@@ -14,9 +14,10 @@
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"clean": "shx rm -rf _bundles lib test_temp",
|
||||
"docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_DIR",
|
||||
"upload_docs_json": "aws s3 cp generated_docs/index.json $S3_URL --profile 0xproject --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --content-type application/json",
|
||||
"copy_test_fixtures": "copyfiles -u 2 './test/fixtures/**/*.json' ./lib/test/fixtures",
|
||||
"lint": "tslint src/**/*.ts test/**/*.ts",
|
||||
"prepublishOnly": "run-p build",
|
||||
"lint": "tslint --project . 'src/**/*.ts' 'test/**/*.ts'",
|
||||
"run_mocha": "mocha lib/test/**/*_test.js",
|
||||
"test": "run-s clean build copy_test_fixtures run_mocha",
|
||||
"test:circleci": "yarn test"
|
||||
@@ -35,9 +36,9 @@
|
||||
},
|
||||
"homepage": "https://github.com/0xProject/0x.js/packages/connect/README.md",
|
||||
"dependencies": {
|
||||
"0x.js": "^0.26.0",
|
||||
"@0xproject/assert": "^0.0.5",
|
||||
"@0xproject/json-schemas": "^0.6.8",
|
||||
"@0xproject/assert": "^0.0.9",
|
||||
"@0xproject/json-schemas": "^0.7.1",
|
||||
"@0xproject/utils": "^0.1.2",
|
||||
"bignumber.js": "~4.1.0",
|
||||
"isomorphic-fetch": "^2.2.1",
|
||||
"lodash": "^4.17.4",
|
||||
@@ -45,24 +46,25 @@
|
||||
"websocket": "^1.0.25"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@0xproject/tslint-config": "^0.1.1",
|
||||
"@0xproject/tslint-config": "^0.4.0",
|
||||
"@types/fetch-mock": "^5.12.1",
|
||||
"@types/lodash": "^4.14.77",
|
||||
"@types/lodash": "^4.14.86",
|
||||
"@types/mocha": "^2.2.42",
|
||||
"@types/query-string": "^5.0.1",
|
||||
"@types/websocket": "^0.0.34",
|
||||
"chai": "^4.0.1",
|
||||
"chai-as-promised": "^7.1.0",
|
||||
"chai-as-promised-typescript-typings": "0.0.3",
|
||||
"chai-as-promised-typescript-typings": "^0.0.3",
|
||||
"chai-typescript-typings": "^0.0.1",
|
||||
"copyfiles": "^1.2.0",
|
||||
"dirty-chai": "^2.0.1",
|
||||
"fetch-mock": "^5.13.1",
|
||||
"mocha": "^4.0.0",
|
||||
"npm-run-all": "^4.0.2",
|
||||
"mocha": "^4.0.1",
|
||||
"npm-run-all": "^4.1.2",
|
||||
"shx": "^0.2.2",
|
||||
"tslint": "5.8.0",
|
||||
"typedoc": "~0.8.0",
|
||||
"typescript": "~2.6.1",
|
||||
"web3-typescript-typings": "^0.7.1"
|
||||
"web3-typescript-typings": "^0.7.2"
|
||||
}
|
||||
}
|
||||
|
@@ -1,14 +1,40 @@
|
||||
const execAsync = require('async-child-process').execAsync;
|
||||
const postpublish_utils = require('../../../scripts/postpublish_utils');
|
||||
const packageJSON = require('../package.json');
|
||||
|
||||
const cwd = __dirname + '/..';
|
||||
const subPackageName = packageJSON.name;
|
||||
const S3BucketPath = 's3://connect-docs-jsons/';
|
||||
|
||||
let tag;
|
||||
let version;
|
||||
postpublish_utils.getLatestTagAndVersionAsync(subPackageName)
|
||||
.then(function(result) {
|
||||
const releaseName = postpublish_utils.getReleaseName(subPackageName, result.version);
|
||||
const assets = [];
|
||||
return postpublish_utils.publishReleaseNotes(result.tag, releaseName, assets);
|
||||
tag = result.tag;
|
||||
version = result.version;
|
||||
const releaseName = postpublish_utils.getReleaseName(subPackageName, version);
|
||||
return postpublish_utils.publishReleaseNotes(tag, releaseName);
|
||||
})
|
||||
.catch (function(err) {
|
||||
.then(function(release) {
|
||||
console.log('POSTPUBLISH: Release successful, generating docs...');
|
||||
const jsonFilePath = __dirname + '/../' + postpublish_utils.generatedDocsDirectoryName + '/index.json';
|
||||
return execAsync(
|
||||
'JSON_FILE_PATH=' + jsonFilePath + ' PROJECT_DIR=' + __dirname + '/.. yarn docs:json',
|
||||
{
|
||||
cwd,
|
||||
}
|
||||
);
|
||||
})
|
||||
.then(function(result) {
|
||||
if (result.stderr !== '') {
|
||||
throw new Error(result.stderr);
|
||||
}
|
||||
const fileName = 'v' + version + '.json';
|
||||
console.log('POSTPUBLISH: Doc generation successful, uploading docs... as ', fileName);
|
||||
const s3Url = S3BucketPath + fileName;
|
||||
return execAsync('S3_URL=' + s3Url + ' yarn upload_docs_json', {
|
||||
cwd,
|
||||
});
|
||||
}).catch (function(err) {
|
||||
throw err;
|
||||
});
|
||||
|
@@ -1,47 +1,39 @@
|
||||
import 'isomorphic-fetch';
|
||||
import * as _ from 'lodash';
|
||||
import {BigNumber} from 'bignumber.js';
|
||||
import * as queryString from 'query-string';
|
||||
import {assert} from '@0xproject/assert';
|
||||
import {schemas} from '@0xproject/json-schemas';
|
||||
import {SignedOrder} from '0x.js';
|
||||
import 'isomorphic-fetch';
|
||||
import * as _ from 'lodash';
|
||||
import * as queryString from 'query-string';
|
||||
|
||||
import {schemas as clientSchemas} from './schemas/schemas';
|
||||
import {
|
||||
Client,
|
||||
FeesRequest,
|
||||
FeesResponse,
|
||||
HttpRequestOptions,
|
||||
HttpRequestType,
|
||||
OrderbookRequest,
|
||||
OrderbookResponse,
|
||||
OrdersRequest,
|
||||
SignedOrder,
|
||||
TokenPairsItem,
|
||||
TokenPairsRequest,
|
||||
} from './types';
|
||||
import {schemas as clientSchemas} from './schemas/schemas';
|
||||
import {typeConverters} from './utils/type_converters';
|
||||
|
||||
interface RequestOptions {
|
||||
params?: object;
|
||||
payload?: object;
|
||||
}
|
||||
|
||||
enum RequestType {
|
||||
Get = 'GET',
|
||||
Post = 'POST',
|
||||
}
|
||||
|
||||
/**
|
||||
* This class includes all the functionality related to interacting with a set of HTTP endpoints
|
||||
* that implement the standard relayer API v0
|
||||
*/
|
||||
export class HttpClient implements Client {
|
||||
private apiEndpointUrl: string;
|
||||
private _apiEndpointUrl: string;
|
||||
/**
|
||||
* Instantiates a new HttpClient instance
|
||||
* @param url The base url for making API calls
|
||||
* @param url The relayer API base HTTP url you would like to interact with
|
||||
* @return An instance of HttpClient
|
||||
*/
|
||||
constructor(url: string) {
|
||||
assert.isHttpUrl('url', url);
|
||||
this.apiEndpointUrl = url;
|
||||
this._apiEndpointUrl = url;
|
||||
}
|
||||
/**
|
||||
* Retrieve token pair info from the API
|
||||
@@ -56,7 +48,7 @@ export class HttpClient implements Client {
|
||||
const requestOpts = {
|
||||
params: request,
|
||||
};
|
||||
const tokenPairs = await this._requestAsync('/token_pairs', RequestType.Get, requestOpts);
|
||||
const tokenPairs = await this._requestAsync('/token_pairs', HttpRequestType.Get, requestOpts);
|
||||
assert.doesConformToSchema(
|
||||
'tokenPairs', tokenPairs, schemas.relayerApiTokenPairsResponseSchema);
|
||||
_.each(tokenPairs, (tokenPair: object) => {
|
||||
@@ -81,7 +73,7 @@ export class HttpClient implements Client {
|
||||
const requestOpts = {
|
||||
params: request,
|
||||
};
|
||||
const orders = await this._requestAsync(`/orders`, RequestType.Get, requestOpts);
|
||||
const orders = await this._requestAsync(`/orders`, HttpRequestType.Get, requestOpts);
|
||||
assert.doesConformToSchema('orders', orders, schemas.signedOrdersSchema);
|
||||
_.each(orders, (order: object) => typeConverters.convertOrderStringFieldsToBigNumber(order));
|
||||
return orders;
|
||||
@@ -93,7 +85,7 @@ export class HttpClient implements Client {
|
||||
*/
|
||||
public async getOrderAsync(orderHash: string): Promise<SignedOrder> {
|
||||
assert.doesConformToSchema('orderHash', orderHash, schemas.orderHashSchema);
|
||||
const order = await this._requestAsync(`/order/${orderHash}`, RequestType.Get);
|
||||
const order = await this._requestAsync(`/order/${orderHash}`, HttpRequestType.Get);
|
||||
assert.doesConformToSchema('order', order, schemas.signedOrderSchema);
|
||||
typeConverters.convertOrderStringFieldsToBigNumber(order);
|
||||
return order;
|
||||
@@ -108,7 +100,7 @@ export class HttpClient implements Client {
|
||||
const requestOpts = {
|
||||
params: request,
|
||||
};
|
||||
const orderBook = await this._requestAsync('/orderbook', RequestType.Get, requestOpts);
|
||||
const orderBook = await this._requestAsync('/orderbook', HttpRequestType.Get, requestOpts);
|
||||
assert.doesConformToSchema('orderBook', orderBook, schemas.relayerApiOrderBookResponseSchema);
|
||||
typeConverters.convertOrderbookStringFieldsToBigNumber(orderBook);
|
||||
return orderBook;
|
||||
@@ -129,7 +121,7 @@ export class HttpClient implements Client {
|
||||
const requestOpts = {
|
||||
payload: request,
|
||||
};
|
||||
const fees = await this._requestAsync('/fees', RequestType.Post, requestOpts);
|
||||
const fees = await this._requestAsync('/fees', HttpRequestType.Post, requestOpts);
|
||||
assert.doesConformToSchema('fees', fees, schemas.relayerApiFeesResponseSchema);
|
||||
typeConverters.convertStringsFieldsToBigNumbers(fees, ['makerFee', 'takerFee']);
|
||||
return fees;
|
||||
@@ -143,9 +135,10 @@ export class HttpClient implements Client {
|
||||
const requestOpts = {
|
||||
payload: signedOrder,
|
||||
};
|
||||
await this._requestAsync('/order', RequestType.Post, requestOpts);
|
||||
await this._requestAsync('/order', HttpRequestType.Post, requestOpts);
|
||||
}
|
||||
private async _requestAsync(path: string, requestType: RequestType, requestOptions?: RequestOptions): Promise<any> {
|
||||
private async _requestAsync(path: string, requestType: HttpRequestType,
|
||||
requestOptions?: HttpRequestOptions): Promise<any> {
|
||||
const params = _.get(requestOptions, 'params');
|
||||
const payload = _.get(requestOptions, 'payload');
|
||||
let query = '';
|
||||
@@ -153,13 +146,14 @@ export class HttpClient implements Client {
|
||||
const stringifiedParams = queryString.stringify(params);
|
||||
query = `?${stringifiedParams}`;
|
||||
}
|
||||
const url = `${this.apiEndpointUrl}/v0${path}${query}`;
|
||||
const url = `${this._apiEndpointUrl}/v0${path}${query}`;
|
||||
const headers = new Headers({
|
||||
'content-type': 'application/json',
|
||||
});
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: requestType,
|
||||
body: payload,
|
||||
body: JSON.stringify(payload),
|
||||
headers,
|
||||
});
|
||||
if (!response.ok) {
|
||||
|
@@ -1,15 +1,24 @@
|
||||
import {bigNumberConfigs} from '@0xproject/utils';
|
||||
|
||||
// Customize our BigNumber instances
|
||||
bigNumberConfigs.configure();
|
||||
|
||||
export {HttpClient} from './http_client';
|
||||
export {WebSocketOrderbookChannel} from './ws_orderbook_channel';
|
||||
export {
|
||||
Client,
|
||||
ECSignature,
|
||||
FeesRequest,
|
||||
FeesResponse,
|
||||
Order,
|
||||
OrderbookChannel,
|
||||
OrderbookChannelHandler,
|
||||
OrderbookChannelSubscriptionOpts,
|
||||
OrderbookRequest,
|
||||
OrderbookResponse,
|
||||
OrdersRequest,
|
||||
SignedOrder,
|
||||
TokenPairsItem,
|
||||
TokenPairsRequest,
|
||||
TokenTradeInfo,
|
||||
} from './types';
|
||||
|
@@ -1,6 +1,34 @@
|
||||
import {SignedOrder} from '0x.js';
|
||||
import {BigNumber} from 'bignumber.js';
|
||||
|
||||
// TODO: Consolidate Order, SignedOrder and ECSignature into a shared package instead of duplicating them from 0x.js
|
||||
export interface Order {
|
||||
maker: string;
|
||||
taker: string;
|
||||
makerFee: BigNumber;
|
||||
takerFee: BigNumber;
|
||||
makerTokenAmount: BigNumber;
|
||||
takerTokenAmount: BigNumber;
|
||||
makerTokenAddress: string;
|
||||
takerTokenAddress: string;
|
||||
salt: BigNumber;
|
||||
exchangeContractAddress: string;
|
||||
feeRecipient: string;
|
||||
expirationUnixTimestampSec: BigNumber;
|
||||
}
|
||||
|
||||
export interface SignedOrder extends Order {
|
||||
ecSignature: ECSignature;
|
||||
}
|
||||
|
||||
/**
|
||||
* Elliptic Curve signature
|
||||
*/
|
||||
export interface ECSignature {
|
||||
v: number;
|
||||
r: string;
|
||||
s: string;
|
||||
}
|
||||
|
||||
export interface Client {
|
||||
getTokenPairsAsync: (request?: TokenPairsRequest) => Promise<TokenPairsItem[]>;
|
||||
getOrdersAsync: (request?: OrdersRequest) => Promise<SignedOrder[]>;
|
||||
@@ -15,11 +43,27 @@ export interface OrderbookChannel {
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
/*
|
||||
* baseTokenAddress: The address of token designated as the baseToken in the currency pair calculation of price
|
||||
* quoteTokenAddress: The address of token designated as the quoteToken in the currency pair calculation of price
|
||||
* snapshot: If true, a snapshot of the orderbook will be sent before the updates to the orderbook
|
||||
* limit: Maximum number of bids and asks in orderbook snapshot
|
||||
*/
|
||||
export interface OrderbookChannelSubscriptionOpts {
|
||||
baseTokenAddress: string;
|
||||
quoteTokenAddress: string;
|
||||
snapshot: boolean;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
export interface OrderbookChannelHandler {
|
||||
onSnapshot: (channel: OrderbookChannel, snapshot: OrderbookResponse) => void;
|
||||
onUpdate: (channel: OrderbookChannel, order: SignedOrder) => void;
|
||||
onError: (channel: OrderbookChannel, err: Error) => void;
|
||||
onClose: (channel: OrderbookChannel) => void;
|
||||
onSnapshot: (channel: OrderbookChannel, subscriptionOpts: OrderbookChannelSubscriptionOpts,
|
||||
snapshot: OrderbookResponse) => void;
|
||||
onUpdate: (channel: OrderbookChannel, subscriptionOpts: OrderbookChannelSubscriptionOpts,
|
||||
order: SignedOrder) => void;
|
||||
onError: (channel: OrderbookChannel, subscriptionOpts: OrderbookChannelSubscriptionOpts,
|
||||
err: Error) => void;
|
||||
onClose: (channel: OrderbookChannel, subscriptionOpts: OrderbookChannelSubscriptionOpts) => void;
|
||||
}
|
||||
|
||||
export type OrderbookChannelMessage =
|
||||
@@ -35,30 +79,31 @@ export enum OrderbookChannelMessageTypes {
|
||||
|
||||
export interface SnapshotOrderbookChannelMessage {
|
||||
type: OrderbookChannelMessageTypes.Snapshot;
|
||||
requestId: number;
|
||||
payload: OrderbookResponse;
|
||||
}
|
||||
|
||||
export interface UpdateOrderbookChannelMessage {
|
||||
type: OrderbookChannelMessageTypes.Update;
|
||||
requestId: number;
|
||||
payload: SignedOrder;
|
||||
}
|
||||
|
||||
export interface UnknownOrderbookChannelMessage {
|
||||
type: OrderbookChannelMessageTypes.Unknown;
|
||||
requestId: number;
|
||||
payload: undefined;
|
||||
}
|
||||
|
||||
/*
|
||||
* baseTokenAddress: The address of token designated as the baseToken in the currency pair calculation of price
|
||||
* quoteTokenAddress: The address of token designated as the quoteToken in the currency pair calculation of price
|
||||
* snapshot: If true, a snapshot of the orderbook will be sent before the updates to the orderbook
|
||||
* limit: Maximum number of bids and asks in orderbook snapshot
|
||||
*/
|
||||
export interface OrderbookChannelSubscriptionOpts {
|
||||
baseTokenAddress: string;
|
||||
quoteTokenAddress: string;
|
||||
snapshot: boolean;
|
||||
limit: number;
|
||||
export enum WebsocketConnectionEventType {
|
||||
Close = 'close',
|
||||
Error = 'error',
|
||||
Message = 'message',
|
||||
}
|
||||
|
||||
export enum WebsocketClientEventType {
|
||||
Connect = 'connect',
|
||||
ConnectFailed = 'connectFailed',
|
||||
}
|
||||
|
||||
export interface TokenPairsRequest {
|
||||
@@ -83,8 +128,6 @@ export interface OrdersRequest {
|
||||
tokenAddress?: string;
|
||||
makerTokenAddress?: string;
|
||||
takerTokenAddress?: string;
|
||||
tokenA?: string;
|
||||
tokenB?: string;
|
||||
maker?: string;
|
||||
taker?: string;
|
||||
trader?: string;
|
||||
@@ -118,3 +161,13 @@ export interface FeesResponse {
|
||||
makerFee: BigNumber;
|
||||
takerFee: BigNumber;
|
||||
}
|
||||
|
||||
export interface HttpRequestOptions {
|
||||
params?: object;
|
||||
payload?: object;
|
||||
}
|
||||
|
||||
export enum HttpRequestType {
|
||||
Get = 'GET',
|
||||
Post = 'POST',
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user