Compare commits

..

695 Commits

Author SHA1 Message Date
fabioberger
2b8226a757 Publish
- @0x/contracts-asset-proxy@2.2.7
 - @0x/contracts-coordinator@2.0.12
 - @0x/contracts-dev-utils@0.0.9
 - @0x/contracts-erc1155@1.1.14
 - @0x/contracts-erc20@2.2.13
 - @0x/contracts-erc721@2.1.14
 - @0x/contracts-exchange-forwarder@3.0.11
 - @0x/contracts-exchange-libs@3.0.7
 - @0x/contracts-exchange@2.1.13
 - @0x/contracts-extensions@4.0.7
 - @0x/contracts-multisig@3.1.13
 - @0x/contracts-test-utils@3.1.15
 - @0x/contracts-utils@3.2.3
 - 0x.js@7.0.1
 - @0x/abi-gen-wrappers@5.3.1
 - @0x/abi-gen@4.2.0
 - @0x/assert@2.1.5
 - @0x/asset-buyer@6.1.13
 - @0x/asset-swapper@1.0.3
 - @0x/base-contract@5.3.3
 - @0x/connect@5.0.18
 - @0x/contract-artifacts@2.2.1
 - @0x/contract-wrappers@12.0.0
 - @0x/contracts-gen@1.0.14
 - @0x/dev-tools-pages@0.0.30
 - @0x/dev-utils@2.3.2
 - ethereum-types@2.1.5
 - @0x/fill-scenarios@3.0.18
 - @0x/instant@1.0.30
 - @0x/json-schemas@4.0.1
 - @0x/migrations@4.3.1
 - @0x/monorepo-scripts@1.0.36
 - @0x/order-utils@8.3.1
 - @0x/sol-compiler@3.1.14
 - @0x/sol-coverage@3.0.11
 - @0x/sol-doc@2.0.18
 - @0x/sol-profiler@3.1.13
 - @0x/sol-resolver@2.0.10
 - @0x/sol-trace@2.0.19
 - @0x/sol-tracing-utils@6.0.18
 - @0x/sra-spec@2.0.16
 - @0x/subproviders@5.0.3
 - @0x/testnet-faucets@1.0.86
 - @0x/types@2.4.2
 - @0x/typescript-typings@4.2.5
 - @0x/utils@4.5.1
 - @0x/web3-wrapper@6.0.12
 - @0x/website@0.0.89
2019-09-03 16:46:00 +02:00
fabioberger
92d5adaac4 Updated CHANGELOGS & MD docs 2019-09-03 16:45:49 +02:00
Fabio B
0c9daa693e Merge pull request #2023 from 0xProject/feature/new-docs
Docs 2.0
2019-09-03 15:25:47 +02:00
fabioberger
89729e828c Print out which snapshot version is being downloaded 2019-09-03 14:29:24 +02:00
Piotr Janosz
c2113caae1 Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-09-03 14:29:06 +02:00
Piotr Janosz
e0adb6624d Check if link is a valid url in mdx inline link: if so, open in a new tab, if not, same tab. 2019-09-03 14:28:55 +02:00
fabioberger
022855add0 Remove use of remove type 2019-09-03 13:27:04 +02:00
fabioberger
4dd1c48dc8 Increase the memory allocation for building the website 2019-09-03 13:08:05 +02:00
fabioberger
cdc2393aa6 Fix prettier 2019-09-03 12:57:57 +02:00
fabioberger
94f94bdda7 Add contract-wrappers MD docs and update it's index.ts so that no types are missing 2019-09-03 12:43:27 +02:00
fabioberger
3264bd223d Final update of reference docs 2019-09-03 12:30:05 +02:00
fabioberger
6292c0703c Export more of abi-gen-wrappers from contract-wrappers 2019-09-03 12:26:19 +02:00
fabioberger
9a28079f2a Re-wrote Ganache Setup guide into a Setting up a local 0x testnet guide 2019-09-03 12:26:01 +02:00
fabioberger
c612649f02 Update Web3 Provider Explained guide 2019-09-03 12:24:13 +02:00
fabioberger
eda44d1ffb Update market-making guide to mention Mesh as an alternative to SRA 2019-09-03 12:23:58 +02:00
fabioberger
4c2f77c014 Update contract addresses 2019-09-03 10:53:33 +02:00
fabioberger
6b8bbd3d5f Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-09-03 10:40:00 +02:00
fabioberger
e914e1b7fa Increase available memory for webpack 2019-09-03 10:39:55 +02:00
Fabio B
3d2ce749a8 Merge branch 'development' into feature/new-docs 2019-09-02 23:38:31 +02:00
Piotr Janosz
9892d8d6d2 Added keeping active link in view when scrolling content in the docs 2019-09-02 18:15:39 +02:00
fabioberger
218a7ab810 Remove bundle dirs too 2019-09-02 16:22:45 +02:00
fabioberger
6779e52813 Update ganache-cli to later version 2019-09-02 16:22:36 +02:00
Piotr Janosz
5d51b40541 Simplified table of contents 2019-09-02 15:34:56 +02:00
Piotr Janosz
b12b7069f7 Added a performance comment 2019-09-02 14:56:14 +02:00
Piotr Janosz
10a5d38446 Rendering sidebar on mobile without any event listeners / taxing calculations / changes in height 2019-09-02 14:54:32 +02:00
Piotr Janosz
e39e7a934e Added scrollbar size adjustment on resize / scroll 2019-09-02 14:39:15 +02:00
Piotr Janosz
b7127d8506 Merge branch 'feature/new-docs' into feature/new-docs-scrollbar-test 2019-09-02 11:38:15 +02:00
Piotr Janosz
a12e07b1a8 Removed a comment 2019-09-02 11:37:47 +02:00
Piotr Janosz
8ff5c0a603 Changed the order of indices in search suggestions 2019-09-02 11:33:36 +02:00
fabioberger
d7c61fea4c Fix prettier in algolia_meta 2019-09-01 12:17:15 +02:00
fabioberger
08dc5fafa0 Fix prettier 2019-09-01 12:03:23 +02:00
fabioberger
78493a9d98 Update Algolia to production account 2019-09-01 12:03:13 +02:00
fabioberger
e274d8994a Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-09-01 11:58:00 +02:00
fabioberger
2dee887e6f Update abi-gen-wrappers dep version 2019-09-01 11:57:49 +02:00
Piotr Janosz
f7eb20a235 Created a color scheme for code snippets. Fixed language not being passed to some code blocks in two guides. 2019-08-31 22:27:33 +02:00
fabioberger
f3cea0ebd0 Update outdating dep version 2019-08-31 15:34:28 +02:00
fabioberger
05e00d278f Fix prettier 2019-08-31 15:20:39 +02:00
fabioberger
107c7a71f9 Remove unused import 2019-08-31 14:44:13 +02:00
fabioberger
56698fb09e Remove unused imports 2019-08-31 12:48:26 +02:00
fabioberger
55bb6f89d3 Remove unused import 2019-08-31 12:15:34 +02:00
fabioberger
47d77cbddd Remove unused code 2019-08-31 11:20:08 +02:00
fabioberger
2547e0e5b1 Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-08-31 11:17:49 +02:00
fabioberger
1a4699ecac update yarn.lock 2019-08-31 11:17:39 +02:00
fabioberger
c825643b67 Update ts-doc-gen version to one that fixes issues with Object Literals and removes Hierarchy sections and Module headers 2019-08-31 11:16:21 +02:00
Piotr Janosz
a425d3a234 Removed the isCommunity filter / custom filter labels functionality (only used for that before) 2019-08-30 23:22:48 +02:00
Chris Kalani
3041e7459e Open legal guide in same window 2019-08-30 13:24:37 -07:00
Chris Kalani
1fb9d54174 Removed the word wiki from resources dropdown 2019-08-30 13:23:47 -07:00
Chris Kalani
598607f5a3 Sneaking in updated product dropdown menu titles based on Will's feedback 2019-08-30 13:22:42 -07:00
Chris Kalani
5c5bb20415 Nevermind, changed back to Trader 2019-08-30 11:57:10 -07:00
Chris Kalani
6199a17791 Changed trader keyword to trading 2019-08-30 11:52:56 -07:00
Chris Kalani
7dd42ad6aa Changed references from Asset Buyer to Asset Swapper 2019-08-30 11:49:16 -07:00
Chris Kalani
c7fd85633d Changed tools to Tools & Libraries - top nav left as just tools 2019-08-30 11:44:18 -07:00
fabioberger
b3df71bebf Several additional fixes to the reference MDX docs 2019-08-30 20:35:41 +02:00
Piotr Janosz
88d95ebdbc Correctly copying code samples 2019-08-30 20:04:35 +02:00
fabioberger
140cf4d378 Remove generated docs in clean 2019-08-30 17:18:58 +02:00
fabioberger
451a19117f Fix MD docs and make sure generated contract wrappers are being rendered 2019-08-30 17:18:40 +02:00
fabioberger
aa6ab33b93 Remove doc gen from abi-gen-wrappers since it'll be tested via contract-wrappers 2019-08-30 14:09:39 +02:00
fabioberger
8ec04271f3 Fix casing of PyPI 2019-08-30 12:59:37 +02:00
fabioberger
f583de652f Fix casing on TypeScript 2019-08-30 12:58:05 +02:00
fabioberger
96cd9de8a6 Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-08-30 12:50:17 +02:00
fabioberger
9a17cb4c92 Remove unnecessary link 2019-08-30 12:50:03 +02:00
Piotr Janosz
021cba9fad Fixed some types 2019-08-30 00:00:23 +02:00
Piotr Janosz
47f4321611 Adjust scrollbar / toc height to available space 2019-08-29 23:58:18 +02:00
Piotr Janosz
775a41a789 Changed line-height to 1.6 for paragraph 2019-08-29 23:04:33 +02:00
Piotr Janosz
f6c61ed79f Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-08-29 20:38:28 +02:00
Piotr Janosz
152e057e08 Unbroke build process / generating toc 2019-08-29 20:38:05 +02:00
fabioberger
8b84ecc593 Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-08-29 20:23:26 +02:00
fabioberger
9c10babefd Use a different babel plugin that works in a production webpack build 2019-08-29 20:23:11 +02:00
Piotr Janosz
67193d9472 Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-08-29 20:06:30 +02:00
Piotr Janosz
7d04dd9520 Fixed styles for table of contents 2019-08-29 20:04:50 +02:00
Piotr Janosz
93bda7972c Fixed an issue with other nodes than text being parsed incorrectly in the table of contents 2019-08-29 19:59:45 +02:00
fabioberger
92c0e34ed2 Fix header sizes to display optimally in sidebar 2019-08-29 19:20:54 +02:00
fabioberger
c0a471b349 Update README links 2019-08-29 18:54:06 +02:00
fabioberger
2543076d16 Replace 0xproject.com urls with 0x.org 2019-08-29 18:36:48 +02:00
fabioberger
e32bb6fc0f Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-08-29 18:32:03 +02:00
fabioberger
7020166473 Update ts-doc-gen and the reference docs 2019-08-29 18:30:45 +02:00
Piotr Janosz
16ae47f2ad Adjusted font-size for paragraph, ordered and unordered lists. Fixed line-heights and colors too. 2019-08-29 18:28:26 +02:00
fabioberger
abf1141ad8 Fix prettier 2019-08-29 17:54:12 +02:00
Piotr Janosz
3790e0a741 Autolink headings in mdx only up to h3. Added heading sizes (in px) for h4,h5,h6 in mdx headings 2019-08-29 17:43:56 +02:00
Piotr Janosz
9e1966b4fe Smoother animation on active table of contents state change 2019-08-29 17:32:19 +02:00
Piotr Janosz
38e06e57a3 Extracted common styles for levels of nesting deeper than 1 in the mdx table of contents 2019-08-29 17:27:34 +02:00
Piotr Janosz
7f2fc90677 Merge branch 'feature/docs-third-level-nesting' into feature/new-docs 2019-08-29 17:24:26 +02:00
Piotr Janosz
1f0ab54fc5 Revert webpack config 2019-08-29 17:23:17 +02:00
fabioberger
7f8c11a74c Remove unused variables 2019-08-29 15:39:53 +02:00
fabioberger
7a4d64d90d Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-08-29 14:20:41 +02:00
fabioberger
7217bfa35e Fix links in guides 2019-08-29 14:20:04 +02:00
fabioberger
25077affc8 Link Python tools to doc pages not PyPi 2019-08-29 14:19:52 +02:00
fabioberger
7a80583655 Open help link in new tab 2019-08-29 14:19:20 +02:00
Piotr Janosz
c21fe0cb50 Thrid level of nesting / temporary webpack config 2019-08-29 13:33:52 +02:00
Piotr Janosz
3d08e79089 Fixed a bug in algolia_meta 2019-08-29 11:45:56 +02:00
fabioberger
c43db2d096 Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-08-29 11:15:43 +02:00
Chris Kalani
220856d084 Added bug bounty program guide 2019-08-28 16:23:35 -07:00
Chris Kalani
a01eafa4e7 Cleaned up some Guide titles 2019-08-28 16:11:50 -07:00
Chris Kalani
f9c2d25352 Cleaned up CLI tag and added link to tools on API page 2019-08-28 16:08:52 -07:00
fabioberger
d2f77d74e6 Remove hr so we don't have a bunch in a row 2019-08-29 01:04:16 +02:00
fabioberger
c3b928c1f5 Prettier fix 2019-08-29 00:44:10 +02:00
fabioberger
9dfa9c194e Remove "Relayers" topic/tag 2019-08-29 00:17:11 +02:00
fabioberger
1a3dc6cefc Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-08-29 00:13:19 +02:00
fabioberger
1a73daf82a Update doc references 2019-08-29 00:09:27 +02:00
fabioberger
6b20c9a542 Update ts-doc-gen so that it properly converts module relative links to anchor links 2019-08-29 00:04:39 +02:00
Piotr Janosz
76c996250d Sorting tools by difficulty and alphabetically. Removed icons from featured tools. Extracted common difficultyOrder constant 2019-08-28 23:21:37 +02:00
Piotr Janosz
52e8de9966 Pushed sorting guides titles case-insensitive 2019-08-28 22:30:49 +02:00
Piotr Janosz
81ab84b087 Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-08-28 22:18:57 +02:00
Piotr Janosz
e34755a1ef Sorting guides by difficulty and alphabetically 2019-08-28 22:18:39 +02:00
fabioberger
6c11b2ad8a Remove committed reference file 2019-08-28 21:57:35 +02:00
fabioberger
ede6ecc3aa Add "On-chain" prefix to section name 2019-08-28 21:55:37 +02:00
fabioberger
9db69f33e4 Add blurb about on-chain API Explorer 2019-08-28 21:55:13 +02:00
fabioberger
17d5d4648b Remove order-watcher reference doc 2019-08-28 21:42:01 +02:00
fabioberger
e203b5593a Update tool naming to be more human readable 2019-08-28 21:41:36 +02:00
fabioberger
de9aa063c0 Link 0x.js to it's reference page 2019-08-28 21:41:08 +02:00
fabioberger
077d001b42 Hide tools from homepage that have isHidden flag 2019-08-28 20:31:15 +02:00
fabioberger
dfd46d68ac Update reference.mdx files 2019-08-28 18:54:06 +02:00
fabioberger
4dbe137999 Add more packages to those we generate docs for and remove unused flags 2019-08-28 18:53:45 +02:00
fabioberger
1ac5cb404f Remove duplicate algolia_meta 2019-08-28 18:53:22 +02:00
fabioberger
43ffa2dd77 Write algolia_metadata to utils dir 2019-08-28 18:53:13 +02:00
fabioberger
1efa7935b7 Add back logic to prune out private methods 2019-08-28 18:52:56 +02:00
fabioberger
b0835b005a Pass in provider, not Web3Wrapper 2019-08-28 18:52:39 +02:00
fabioberger
30946ac110 Update ts-doc-gen 2019-08-28 18:12:18 +02:00
fabioberger
9427858755 Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-08-28 18:09:42 +02:00
fabioberger
53864d3817 Refactor doc generation script to only generate MD docs and to have them reflect what is exported in their respective index.ts files 2019-08-28 18:09:29 +02:00
Piotr Janosz
ab283ddd9b Added autolinking headings in mdx docs 2019-08-28 17:44:46 +02:00
fabioberger
7efcf9066c Change CoordinatorWrapper constructor to take a provider 2019-08-28 17:11:16 +02:00
Piotr Janosz
219e09d157 Stylstic fix for the new way we sectionize headings / table of contents 2019-08-28 12:14:05 +02:00
Piotr Janosz
d816551dba Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-08-28 11:45:55 +02:00
Piotr Janosz
04c5752b8a Fixed sectionizing headings in docs: Nested sections do not get wrapped in parent sections anymore; only sectionizing headings that need to be sectionized (i.e. that appear in the table of contents) 2019-08-28 11:45:41 +02:00
Chris Kalani
ed12d8b95f Started updating tool titles 2019-08-27 15:32:35 -07:00
Chris Kalani
f48852742d Cleaned up core concept illustrations 2019-08-27 15:13:39 -07:00
Chris Kalani
b84d89367a Fixed huge width on instant screenshot 2019-08-27 14:09:07 -07:00
Piotr Janosz
d8dab6a070 Merge branch 'feature/new-docs' of github.com:0xProject/0x-monorepo into feature/new-docs 2019-08-27 18:46:46 +02:00
Piotr Janosz
ac2443690c Fixed regex to not remove hashes on links beyond the initial one 2019-08-27 18:46:34 +02:00
fabioberger
5df0f13eb0 Fix links in Core Concepts 2019-08-27 18:33:14 +02:00
fabioberger
24d782fb19 Remove deployer endpoint that is no longer used 2019-08-27 17:55:08 +02:00
fabioberger
01a5472318 Fix all /docs/{pkg} links to /docs/tools/{pkg} 2019-08-27 17:49:29 +02:00
fabioberger
4b7a2e9d49 Replace all links to wiki with links to guides section 2019-08-27 17:25:58 +02:00
fabioberger
62936e3502 Add 0x Extensions guide 2019-08-27 16:11:22 +02:00
fabioberger
d6b3e4fbaa Fix Get Started links 2019-08-27 15:33:25 +02:00
fabioberger
a5f011f4a4 Add MMing guide 2019-08-27 15:33:18 +02:00
fabioberger
c6efaab01d Add all guides to the sitemap.txt 2019-08-27 14:45:12 +02:00
fabioberger
0f7282d9a9 Prettier fix 2019-08-27 12:15:02 +02:00
fabioberger
a3b414a986 Ignore auto-generated MDX in website repo 2019-08-27 11:56:50 +02:00
fabioberger
8a6d0b67f1 Update Guides 2019-08-27 11:55:39 +02:00
fabioberger
f78ff91975 Add missing new line 2019-08-27 10:46:40 +02:00
fabioberger
c8e416f3b1 Fix TS error 2019-08-27 10:46:24 +02:00
fabioberger
d61f67d24a Remove unused components 2019-08-27 10:46:13 +02:00
fabioberger
258ffdcc94 Update doc links 2019-08-27 10:45:47 +02:00
fabioberger
1f93f09864 Combine @0x/utils exports 2019-08-27 10:45:30 +02:00
fabioberger
7afddb9309 Fix prettier 2019-08-27 10:29:47 +02:00
fabioberger
5eb4dbd5d9 Fix links 2019-08-27 10:29:42 +02:00
fabioberger
fc39ddfb71 Remove old doc md files 2019-08-27 10:29:30 +02:00
fabioberger
ba04a8bc0c Revert react and react-dom versions in Instant 2019-08-27 10:08:28 +02:00
fabioberger
02d4a28402 Fix clean command to remove bundles recursively 2019-08-27 10:08:08 +02:00
fabioberger
ea2bf07ea6 Fix linter errors 2019-08-26 19:35:57 +02:00
fabioberger
b5dc734dc4 Remove legacy doc pages 2019-08-26 19:22:48 +02:00
fabioberger
7dd9b0ba66 Improve indexing comment 2019-08-26 18:09:42 +02:00
fabioberger
69a5c8a317 Use yarn because otherwise the flags don't get passed down properly 2019-08-26 18:08:11 +02:00
fabioberger
b975ac7c31 Fix search and indexing 2019-08-26 17:51:38 +02:00
Piotr Janosz
dcede832c8 Removed webpack bundle analyzer 2019-08-26 16:59:27 +02:00
Piotr Janosz
f40bbbc238 Fixed 404 display for docs pages 2019-08-26 16:55:29 +02:00
fabioberger
361f5ca5cc Segregate indexes by environment 2019-08-26 16:25:40 +02:00
fabioberger
a710ebe5b3 Remove scripts gitignore since we don't have monorepo scripts in each package anymore 2019-08-26 16:18:21 +02:00
fabioberger
2becef23ff Add note about admin API env var needed for indexing docs 2019-08-26 14:50:40 +02:00
fabioberger
f916d293fa Add updating tools from S3 and indexing content on Algolia to deployment commands 2019-08-26 14:48:06 +02:00
fabioberger
f312a260cc Move out Algolia indexing command-line tool out of website and remove need to expose admin key 2019-08-26 14:41:40 +02:00
fabioberger
fd9b51c7db Redirect old docs pages and wiki to new doc pages 2019-08-26 13:57:05 +02:00
fabioberger
1dac6b6157 Gitignore the tool MDX files in website repo 2019-08-26 10:28:34 +02:00
fabioberger
c2ba6b3a0f Update the tools MDX files from authoritative S3 before build and dev server start 2019-08-26 10:28:21 +02:00
fabioberger
576bd5585f Add Golang Mesh RPC package and update versions 2019-08-26 10:16:43 +02:00
fabioberger
ae61a87190 merge development 2019-08-26 08:46:37 +02:00
fabioberger
2e8f2ae769 Update yarn.lock 2019-08-26 08:24:18 +02:00
fabioberger
b507a308e6 Fix home route 2019-08-26 08:20:29 +02:00
Fabio B
ad83b17fdf Merge pull request #2033 from 0xProject/feature/genMDDocs
Generate MD docs for all packages
2019-08-26 08:08:17 +02:00
fabioberger
e452cfcd59 Final docs gen 2019-08-26 07:11:29 +02:00
fabioberger
6474a4e08c Update ts-doc-gen with fix for multi-link lines 2019-08-26 07:10:11 +02:00
fabioberger
e78288ddfd Update yarn.lock 2019-08-25 22:34:34 +02:00
fabioberger
6e2d0ab13d Update docs to latest format 2019-08-25 22:34:28 +02:00
fabioberger
bfbc78c95c Remove unused dep 2019-08-25 22:14:08 +02:00
fabioberger
368ae86530 Add MD docs diff test to CI 2019-08-24 01:27:24 +02:00
fabioberger
d8ccc1694d merge development 2019-08-24 01:21:34 +02:00
fabioberger
b4e10b1e06 Update yarn.lock 2019-08-24 01:19:22 +02:00
fabioberger
05f76958ac Remove legacy FAQ 2019-08-24 01:19:15 +02:00
Piotr Janosz
1183cf5e6b Replaced images for core concepts. Fixed a bug causing duplicate props on image and its container in mdx 2019-08-24 00:06:30 +02:00
Piotr Janosz
bf9eb1413b Added animation wrapper with positioning props. Updated animations for core concepts. 2019-08-24 00:06:30 +02:00
Piotr Janosz
38d48a8f20 Moved @0x/types back to dependencies. 2019-08-24 00:06:30 +02:00
Piotr Janosz
ca222a470d Added opening step links in new tab if the url is valid 2019-08-24 00:06:08 +02:00
Piotr Janosz
49ca8840ea Moved animations to public and compressed files 2019-08-24 00:06:08 +02:00
Piotr Janosz
faaeba78bb Removed unused make-promises-safe package 2019-08-24 00:06:08 +02:00
Piotr Janosz
6c37d47f2f Replaced react loadable (only used in Icon) with the native react lazy / suspense. Removed loadable nad its types from package.json 2019-08-24 00:06:08 +02:00
Piotr Janosz
185e53149f Moves @0x/types and @0x/typescript-typings to devDependencies 2019-08-24 00:06:08 +02:00
Piotr Janosz
4329a252ee Removed react-tap-event types as it's not used anymore. Reinstalled node-sass as a dev dependency as it's needed by sass-loader 2019-08-24 00:05:36 +02:00
Piotr Janosz
8d38d69684 Removed unused package react-typist 2019-08-24 00:05:36 +02:00
Piotr Janosz
edb5e50253 Removed unused package react-lazyload 2019-08-24 00:05:36 +02:00
Piotr Janosz
81ab2e75ca Removed unusued node-sass package. Left sass-loader for webpack intact. 2019-08-24 00:05:36 +02:00
Piotr Janosz
e0d8398cf7 Removed unused less node package, adjusted less loader rules to match other loaders in webpack config 2019-08-24 00:05:36 +02:00
Piotr Janosz
4fd46d1c95 Removed unused jsonschema / @types/jsonschema packages 2019-08-24 00:05:36 +02:00
Piotr Janosz
c217764fe0 Removed unusued pkg: body-scroll-lock 2019-08-24 00:05:35 +02:00
Piotr Janosz
42124274c7 Webpack changes: using eval-source-map for development, added parallel option to Terser plugin, added cache loader and caching directory to mdx / babel loaders. 2019-08-24 00:05:35 +02:00
Piotr Janosz
562342ac99 Updated terser webpack plugin; Removed uglify plugin (unused). Added parallel option for terser. Added target browsers and cache directory option for babel-loader 2019-08-24 00:05:35 +02:00
Piotr Janosz
14b573ebfd Updated / cleaned up babel and mdx packages 2019-08-24 00:05:35 +02:00
Piotr Janosz
e3834c2fc0 Updated webpack, webpack-dev-server, webpack-bundle-analyzer, webpack-cli versions 2019-08-24 00:05:08 +02:00
Piotr Janosz
c2f3757de7 Fixed some types in guides 2019-08-24 00:05:07 +02:00
Piotr Janosz
4b0010be63 Added longer timeout for algolia admin operations. Added an option to apply hidden and custom labels to filters from algolia. Added sorting guides (alphabetically) and tools (by community maintenance and alphabetically). 2019-08-24 00:05:07 +02:00
Piotr Janosz
078af36e0e Fixed ordered list styles 2019-08-24 00:05:07 +02:00
Chris Kalani
b17d12fe23 Fixed sub headers on CFL guide 2019-08-24 00:05:07 +02:00
Chris Kalani
294c0b449b Added contract-fillable liquidity guide 2019-08-24 00:05:07 +02:00
Chris Kalani
bc3927e973 Added deployed addresses guide 2019-08-24 00:05:07 +02:00
Chris Kalani
a2cfdd2975 Added protocol, coordinator, and forwarder specifications to guides 2019-08-24 00:05:07 +02:00
Piotr Janosz
53b4f48b2e Better way of custom sorting difficulty filters 2019-08-24 00:05:07 +02:00
Piotr Janosz
635b80440a Moved sorting filters to filter group to sort difficulty filters in a custom wat 2019-08-24 00:05:07 +02:00
Piotr Janosz
f2d95477e6 Fixed not all guides / tools showing up on a page 2019-08-24 00:05:07 +02:00
Piotr Janosz
1005e4962a Fixed inline links opening in new tab for external links; fixed scrolling to container if hash is provided 2019-08-24 00:05:07 +02:00
Piotr Janosz
487bc1a08b Added additional props to mdx images 2019-08-24 00:05:07 +02:00
Piotr Janosz
0cf768185e Improved code blocks rendering 2019-08-24 00:05:07 +02:00
Piotr Janosz
b5558a8cff onyl include mdx folder for mdx files parsing 2019-08-24 00:04:47 +02:00
Piotr Janosz
af2b8dfde5 Added webpack chunk name to imported mdx docs. Fixed animation chunk name 2019-08-24 00:04:47 +02:00
Piotr Janosz
2bde5f7034 Fixes bundle analyzer plugin in webpack development 2019-08-24 00:04:47 +02:00
Chris Kalani
c38f913a84 Improved margin on seperator component 2019-08-24 00:04:47 +02:00
Chris Kalani
44b4f91208 TODO: need to fix interan page links before adding specifications 2019-08-24 00:04:47 +02:00
Chris Kalani
9c4ad6ac32 Added Web3 provider guide 2019-08-24 00:04:47 +02:00
Chris Kalani
b151c0b701 Fixed section link in instant guide 2019-08-24 00:04:47 +02:00
Chris Kalani
d4b6db773f Added 0x instant guide 2019-08-24 00:04:47 +02:00
Chris Kalani
7da71c0955 Cleaned up some copy on docs home 2019-08-24 00:04:47 +02:00
Chris Kalani
32adb35c2a Removed community maintained filter on tools page 2019-08-24 00:04:47 +02:00
Chris Kalani
2f197d128a Reduced font size and weight on step links component 2019-08-24 00:04:47 +02:00
fabioberger
5415bc4590 get the indexing script to work without a "stack too deep" error 2019-08-24 00:04:47 +02:00
fabioberger
f6086b8054 Update the MDX files for each tool 2019-08-24 00:04:47 +02:00
fabioberger
c9d77d7fa0 Add 0x.js to tools page 2019-08-24 00:04:47 +02:00
fabioberger
ab8c457c51 Update the Useful Links 2019-08-24 00:04:47 +02:00
fabioberger
5d91ad3656 Add Code Sandbox to tools page 2019-08-24 00:04:47 +02:00
fabioberger
78ffca06ea Add more tools 2019-08-24 00:04:46 +02:00
Piotr Janosz
0d71ec93e7 Fixed a substition blunder 2019-08-24 00:04:46 +02:00
Piotr Janosz
d4c771dc7d Fixed rendereing of docs pages, guides, resource... 2019-08-24 00:04:46 +02:00
Piotr Janosz
68004466bb Fixed search suggestions 2019-08-24 00:04:46 +02:00
fabioberger
4dd2d1afaf Refactor Algolia indexing to also index tools without corresponding mdx files 2019-08-24 00:04:46 +02:00
Piotr Janosz
4947676434 Set index settings and clear it only once 2019-08-24 00:04:46 +02:00
Piotr Janosz
ea5e83da03 Edited the images in core-concepts to be smaller 2019-08-24 00:04:46 +02:00
fabioberger
0705276ff9 Add more tools to docs 2019-08-24 00:04:46 +02:00
Piotr Janosz
0299abf1b5 Added image component that centers images in mdx 2019-08-24 00:04:46 +02:00
Piotr Janosz
132394ffbe snake-case and more accurate filenames for webpack plugins for remark/mdx 2019-08-24 00:04:46 +02:00
Piotr Janosz
40edcef340 Wrapped a comment 2019-08-24 00:04:46 +02:00
Piotr Janosz
bf22eba795 Added a TODO to include api explorer in the search index and autocomplete section titles when the page is ready to be indexed and displayed 2019-08-24 00:04:46 +02:00
Piotr Janosz
e990272db3 Removed custom interfaces by using @0x/types object map 2019-08-24 00:04:46 +02:00
Piotr Janosz
401a0eadb1 Removing dropdown developers as it's not used anymore 2019-08-24 00:04:46 +02:00
Piotr Janosz
5852e0b476 Added clearing index on algolia before pushing objects 2019-08-24 00:04:46 +02:00
Piotr Janosz
401df5f45d Renamed mobileNavs to snake case 2019-08-24 00:04:46 +02:00
fabioberger
7da40fd7bc Increase memory allocation to avoid heap out of memory errors 2019-08-24 00:04:46 +02:00
Piotr Janosz
89740dc24c Changed text / typo 2019-08-24 00:04:46 +02:00
fabioberger
4d7ba42f8f Remove all .DS_Store 2019-08-24 00:04:46 +02:00
fabioberger
bbd9c4ef67 Fix remaining merge issues 2019-08-24 00:04:46 +02:00
Piotr Janosz
de036ae96a Deleted ds store files 2019-08-24 00:03:50 +02:00
Piotr Janosz
e5985d7c3f Added illustrations and animations for core concepts 2019-08-24 00:03:50 +02:00
Piotr Janosz
fb54c45d7d Removed .DS_Store files 2019-08-24 00:03:50 +02:00
Piotr Janosz
f1b704a91a Added bold and italiciezed text example 2019-08-24 00:03:50 +02:00
Piotr Janosz
b99eab6804 Fixed a text example on page template 2019-08-24 00:03:50 +02:00
Piotr Janosz
82acc26f97 Added emphasis italicized text to mdx components 2019-08-24 00:03:50 +02:00
Piotr Janosz
569a165c87 Added keywords to meta for a page and content in algolia 2019-08-24 00:03:49 +02:00
Piotr Janosz
704adcb03d Added description from meta for doc pages 2019-08-24 00:03:49 +02:00
Piotr Janosz
197cdee604 Added updating SEO information on docs pages 2019-08-24 00:03:49 +02:00
Piotr Janosz
3dc5de936e Fixed responsive styles for note callout 2019-08-24 00:03:49 +02:00
Piotr Janosz
d88eb6a5c9 Added a shared folder to docs components. Added (next) step links to mdx 2019-08-24 00:03:49 +02:00
Piotr Janosz
a168f34538 Updated Note to be included in mdx 2019-08-24 00:03:49 +02:00
Piotr Janosz
7b150bab73 Removed newsletter widget from every page, included it in mdx components 2019-08-24 00:03:49 +02:00
Chris Kalani
b0e38f79ea Added legal content, still needs some work 2019-08-24 00:03:49 +02:00
Chris Kalani
a68ebc27ed Added Relayer Strategies guide 2019-08-24 00:03:49 +02:00
Chris Kalani
25705bd314 Disabled horizontal scroll on sidebar nav 2019-08-24 00:03:49 +02:00
Piotr Janosz
85c9b7d9c5 Remove redundant package 2019-08-24 00:03:49 +02:00
Piotr Janosz
629c2ecba2 Added some comments to algolia_index 2019-08-24 00:03:49 +02:00
Piotr Janosz
be0662a41d Updated README to add basic information about indexing the docs 2019-08-24 00:03:49 +02:00
Piotr Janosz
1985fec892 Coreectly setting current version for a doc page in version picker 2019-08-24 00:03:49 +02:00
Piotr Janosz
2cbdd76aa3 Fixed a filter glitch where it would remain disabled after unclicking some other ones 2019-08-24 00:03:49 +02:00
Piotr Janosz
73ae0541d8 Nicer scrollbars for firefox 2019-08-24 00:03:49 +02:00
Piotr Janosz
22621b9f76 Upgraded react helmet 2019-08-24 00:03:49 +02:00
Piotr Janosz
c9f214504a Fixed a lot of types 2019-08-24 00:03:49 +02:00
Piotr Janosz
e8a2d1240f Removed ts-ignore from tools. 2019-08-24 00:03:49 +02:00
Piotr Janosz
f2e0fe49f7 Fixed ts-ignore in animation mdx component 2019-08-24 00:03:49 +02:00
Piotr Janosz
4ce7bf56e7 Put ganache meta with teh other guides 2019-08-24 00:03:49 +02:00
Piotr Janosz
29be232ae9 Updated meta for algolia 2019-08-24 00:03:49 +02:00
Piotr Janosz
794c0342ee Fixed issue with filters not unchecking 2019-08-24 00:03:49 +02:00
Chris Kalani
d5a22829ac Added ganache setup guide 2019-08-24 00:03:49 +02:00
Piotr Janosz
b58d4005d3 Small API explorer title change 2019-08-24 00:03:49 +02:00
Piotr Janosz
c16d9d85a2 Cleaned up inline code component 2019-08-24 00:03:49 +02:00
Piotr Janosz
92aeca1f30 Restored and fixed indexing 2019-08-24 00:03:49 +02:00
Piotr Janosz
b81ed67975 Fixed version picker functionality 2019-08-24 00:03:49 +02:00
Piotr Janosz
2bc6582e6b [WIP] Working on version picker 2019-08-24 00:03:49 +02:00
Piotr Janosz
b27311da2e Added commented out index and suggestion title section for api explorer 2019-08-24 00:03:48 +02:00
Piotr Janosz
ab8a0da16a Added stringifying json prettified on updating algolia meta. Added api explorer to indexes 2019-08-24 00:03:48 +02:00
Piotr Janosz
800e37ed03 Auto-updating aloglia_meta 2019-08-24 00:03:48 +02:00
Piotr Janosz
950e84fe5c [WIP] autogenerating paths + versions for docs. Turned meta for algolia into a json file. 2019-08-24 00:03:48 +02:00
Piotr Janosz
fdbc235fd6 [WIP] new tools 2019-08-24 00:03:48 +02:00
Piotr Janosz
ffdb5c06f6 Removed _test suffix on algolia indices 2019-08-24 00:00:08 +02:00
Piotr Janosz
14f0f89798 Imporved styles for the version picker 2019-08-24 00:00:08 +02:00
Piotr Janosz
54b53184b7 Added a select for docs versions 2019-08-24 00:00:08 +02:00
Piotr Janosz
75b1cdac66 Restored old page + inline code with commented out synatx highlighting 2019-08-24 00:00:08 +02:00
Piotr Janosz
d21f394531 Changes to parsing new docs 2019-08-24 00:00:08 +02:00
Piotr Janosz
86d90599ca Removed unnecessary import 2019-08-24 00:00:08 +02:00
Piotr Janosz
ec24976789 Updated not found page header text color 2019-08-24 00:00:08 +02:00
Piotr Janosz
00eaa8bd34 Removed meta from mdx files 2019-08-24 00:00:08 +02:00
Piotr Janosz
5c44163d68 [WIP] algolia indexing rewrite: cleaned up indexing file 2019-08-24 00:00:08 +02:00
Piotr Janosz
f73bad5c13 [WIP] Rewrite of algolia indexing 2019-08-24 00:00:08 +02:00
Piotr Janosz
a063fa6fe0 Cleaned up nested divs in index.tsx 2019-08-23 23:58:59 +02:00
Piotr Janosz
894ad8af21 Added test content to mdx 2019-08-23 23:58:59 +02:00
Piotr Janosz
c01793599f Fixed react create element error for rendering mdx pages 2019-08-23 23:58:59 +02:00
Piotr Janosz
63db393b60 Adjusted a comment 2019-08-23 23:58:59 +02:00
Piotr Janosz
5846166c85 Changes that fix card links for tools and guides 2019-08-23 23:58:59 +02:00
Piotr Janosz
25e941128a Removed description from algolia snippets and searchable attributes 2019-08-23 23:58:59 +02:00
Piotr Janosz
22964ff913 Blurring input on mouse click 2019-08-23 23:58:59 +02:00
Piotr Janosz
62a58667ba Added scrolling to content if search suggestion links a different section on the page the user is already on 2019-08-23 23:58:59 +02:00
Piotr Janosz
c868015989 Made docs scrollable to section when selecting a link 2019-08-23 23:58:58 +02:00
Piotr Janosz
565e5e5770 Fixed a bug for text nodes not found under a heading. I.e. intro text. 2019-08-23 23:58:58 +02:00
Piotr Janosz
198831d084 Improved algolia indexing: content is now exported with a url hash which can link to a section instead of just the base url 2019-08-23 23:58:58 +02:00
Piotr Janosz
d3be097436 Small cleanup 2019-08-23 23:58:58 +02:00
Piotr Janosz
1259de5be4 Fixed scrolling to top of the window on route change resulting from snippet click / enter 2019-08-23 23:58:58 +02:00
Piotr Janosz
df6be48638 Added code-split animations to mdx 2019-08-23 23:58:58 +02:00
Piotr Janosz
4923fdbb73 Installed react-bodymovin for the new animations 2019-08-23 23:58:58 +02:00
Piotr Janosz
66964a5a2f Added hover transitions to docs home links 2019-08-23 23:58:58 +02:00
Piotr Janosz
97e24d0e14 Added common hover color for background light. Added hover states to other docs home components 2019-08-23 23:58:58 +02:00
Piotr Janosz
fe0b75ef26 Made suggestions / active search input more narrow 2019-08-23 23:58:58 +02:00
Piotr Janosz
4b76efbc28 Added animation to top search bar 2019-08-23 23:58:58 +02:00
Piotr Janosz
11cff4d391 Bluring input on escape key 2019-08-23 23:58:58 +02:00
Piotr Janosz
59211c1c1e Correctly populating input on enter / mouse clicks on suggestions. Bluring input on selecting suggestion (routing away) 2019-08-23 23:58:58 +02:00
Piotr Janosz
c0ab2e8127 D 2019-08-23 23:58:58 +02:00
Piotr Janosz
d39e90bfa1 Changed the way lock body scroll works to not scroll to top when user searches for something 2019-08-23 23:58:58 +02:00
Piotr Janosz
16e55457c8 Moved type definition 2019-08-23 23:58:58 +02:00
Piotr Janosz
ea2a453811 Changed a name of event handler in autocomplete 2019-08-23 23:58:58 +02:00
Piotr Janosz
7d2a768a0c Removed duplicate code for sitewraps 2019-08-23 23:58:58 +02:00
Piotr Janosz
78304c4369 Added matching background gray to footer in docs 2019-08-23 23:58:58 +02:00
Piotr Janosz
85f243e2e0 Added visually disabling filters instead of hiding them by algolia 2019-08-23 23:58:58 +02:00
Piotr Janosz
785ca4f5d1 Added scrolling on overflow of sidebar content in new docs 2019-08-23 23:58:57 +02:00
Piotr Janosz
730e8ad151 Updated react-syntax-highlighter 2019-08-23 23:58:57 +02:00
Piotr Janosz
b3e6e23508 Moved algolia indexing to utils 2019-08-23 23:58:57 +02:00
Piotr Janosz
f09d56cdb9 Removed borders over 900px for autosuggestions 2019-08-23 23:58:57 +02:00
Piotr Janosz
b51933c4d9 Fixed overflow scroll visible on search inputs and developer page in firefox 2019-08-23 23:58:57 +02:00
Piotr Janosz
477791a600 Fixed table overflow visible in firefox 2019-08-23 23:58:57 +02:00
Piotr Janosz
f0d6476f92 Reverted last commit 2019-08-23 23:58:57 +02:00
Piotr Janosz
fa4accd0c4 Increased line height on all paragraph components to 1.5 (better readability IMHO) 2019-08-23 23:58:57 +02:00
Piotr Janosz
e64754f554 Adjusted table borders and hero padding. Added subtitle to core concepts doc 2019-08-23 23:58:57 +02:00
Piotr Janosz
5badb1eb5d Fixed amrgins ob autocomplete highlights 2019-08-23 23:58:57 +02:00
Piotr Janosz
9c52fd1f2a Fixed inactive color ofr table of contents 2019-08-23 23:58:57 +02:00
Piotr Janosz
27e01b9249 Fixed clear filters background 2019-08-23 23:58:57 +02:00
Piotr Janosz
5bf0de5519 Added missing heading sizes to mdx 2019-08-23 23:58:57 +02:00
Piotr Janosz
139a4acb1b Deleted empty file 2019-08-23 23:58:57 +02:00
Piotr Janosz
9d8b2d9e0c Added core concepts to the website, search indexing, and settings 2019-08-23 23:58:57 +02:00
fabioberger
d16a0f1b56 Update yarn.lock 2019-08-23 23:58:57 +02:00
fabioberger
edb63c0f26 Make duration optional 2019-08-23 23:58:57 +02:00
fabioberger
bd3a80bcde Add offset default 2019-08-23 23:58:57 +02:00
fabioberger
9f0da8ec39 Fix remaining react-docs and react-shared issues 2019-08-23 23:58:57 +02:00
Piotr Janosz
42ed4e393f Fixed some mdx issues 2019-08-23 23:58:57 +02:00
Piotr Janosz
99ffe6bb2d Added constants for new docs 2019-08-23 23:58:57 +02:00
Piotr Janosz
70898be894 Added smooth scrolling to react-shared link. Changed docs scroll duration value to 500. Added offset for scrolling / active state to make place for react headroom on scrolling up. 2019-08-23 23:58:56 +02:00
Piotr Janosz
9f1859575d Fixed active color for toc links 2019-08-23 23:58:56 +02:00
Piotr Janosz
0167689374 Added creating distinct id based on file name from mdx instead of having to give each one a custom id 2019-08-23 23:58:56 +02:00
Piotr Janosz
053c5f0f88 Ran yarn 2019-08-23 23:58:56 +02:00
Piotr Janosz
fa6516d0be Added custom plugins for wrapping headings in sections / parsing table of contents based on sections from markdown 2019-08-23 23:58:56 +02:00
Piotr Janosz
7fb0e1b39c Added clear all filters button 2019-08-23 23:58:56 +02:00
Piotr Janosz
8ba439c263 Removed developers dropdown. Renamed developers link to docs 2019-08-23 23:58:56 +02:00
Piotr Janosz
1a1f24146c Styled table of contents links better 2019-08-23 23:58:56 +02:00
Piotr Janosz
086fa31d04 Adjusted the way we import react to match how it's done in the project. 2019-08-23 23:58:56 +02:00
Piotr Janosz
b5e02d1b74 Fixed a bug in index.tsx. Removed remark-headings-normalize 2019-08-23 23:58:56 +02:00
Piotr Janosz
e88aee6ad9 Added not found state for mdx page view 2019-08-23 23:58:26 +02:00
Piotr Janosz
fb4ead84f5 Added remark-normalize-headings to get rid of multiple h1 tags in parsed mdx content 2019-08-23 23:58:26 +02:00
Piotr Janosz
298967e639 Fixed content url parsing for algolia content 2019-08-23 23:58:26 +02:00
Piotr Janosz
903a9947a3 Fixed incorrect formatting by prettier 2019-08-23 23:58:26 +02:00
Piotr Janosz
72beb59d63 Fixed some text in page template 2019-08-23 23:58:26 +02:00
Piotr Janosz
75dd1be40e Added some text to comment 2019-08-23 23:58:26 +02:00
Piotr Janosz
6a7c2918bb Fixed a path bug in algolia indexing; added a yarn script to run docs indexing 2019-08-23 23:58:26 +02:00
Piotr Janosz
9b9ee2415d Further refactoring of algolia indexing 2019-08-23 23:58:26 +02:00
Piotr Janosz
f1f38fb8b0 Further polish of algolia indexing 2019-08-23 23:58:26 +02:00
Piotr Janosz
1e44bcb7c9 Added types to searcg indexing helpers 2019-08-23 23:58:26 +02:00
Piotr Janosz
11e689156e [WIP] added some types for indexing helpers 2019-08-23 23:58:26 +02:00
Piotr Janosz
6c792e89f9 [WIP] porting indexing to typescript, ts-node 2019-08-23 23:58:26 +02:00
Piotr Janosz
11026fe36a Started fixing routes a little bit 2019-08-23 23:58:25 +02:00
Piotr Janosz
3133dde3a3 Created mdx folder for new docs. Moved indexing into the new folder. 2019-08-23 23:58:25 +02:00
Piotr Janosz
b666ca0271 Added packages for aloglia indexing 2019-08-23 23:58:25 +02:00
Piotr Janosz
de5c6c1ed0 Made all search suggestion containers scrollable 2019-08-23 23:58:25 +02:00
Piotr Janosz
34f4cf133b Made header search suggestions scrollable 2019-08-23 23:58:25 +02:00
Piotr Janosz
1ba54af4e2 Added lock body scroll for search in header 2019-08-23 23:58:25 +02:00
Piotr Janosz
42e0d608c8 Added clearing search input in autosuggest on escape key press 2019-08-23 23:58:25 +02:00
Piotr Janosz
2c35d63976 Fixed header for docs (at least temporarily) 2019-08-23 23:58:25 +02:00
Piotr Janosz
d1ca1e768f Finished work on the collapsible sidebar for filters / table of contents in docs 2019-08-23 23:58:25 +02:00
Piotr Janosz
2255cc2ebc [WIP] Added accordion for table of contents / filters. Needs cleanup. 2019-08-23 23:58:25 +02:00
Piotr Janosz
6512c12f40 Refactored fadeIn => fadeInUp animation, removed export 2019-08-23 23:58:25 +02:00
Piotr Janosz
fc8d428d1d Created reusable fadeIn / fadeOut keyframes 2019-08-23 23:58:25 +02:00
Piotr Janosz
e07613818d Refactored docs components structure 2019-08-23 23:58:25 +02:00
Piotr Janosz
de59ae11bd Added website paths for docs 2019-08-23 23:58:25 +02:00
Piotr Janosz
026690c837 Fixed a typo 2019-08-23 23:58:25 +02:00
Piotr Janosz
c223a72f5b Fixed indicator on highlighted snippet 2019-08-23 23:58:25 +02:00
Piotr Janosz
c66cf83ef1 Added types for hits in tools and autocomplete 2019-08-23 23:58:25 +02:00
Piotr Janosz
30cf9ac857 Added rendering featured links in tools 2019-08-23 23:58:25 +02:00
Piotr Janosz
b99b9d5435 [WIP] Added filtered hits by section in tools 2019-08-23 23:58:25 +02:00
Piotr Janosz
81b9ab2b6e Consolidated community links 2019-08-23 23:58:25 +02:00
Piotr Janosz
78a60a9973 Consolidated step links in one file 2019-08-23 23:58:25 +02:00
Piotr Janosz
fca6f838d5 Fixed mobile / tablet padding for newsletter widget 2019-08-23 23:58:25 +02:00
Piotr Janosz
4a39eb7931 Fixed community links opening in a new tab, newsletter widget appearing in mdx view. 2019-08-23 23:58:25 +02:00
Piotr Janosz
00ab5f0afb End of day whitespace fix 2019-08-23 23:58:24 +02:00
Piotr Janosz
34dfd73aab Cleaned up siteWrap for docs and elsewhere. Converted the other sitewrap to function component. 2019-08-23 23:58:24 +02:00
Piotr Janosz
9e0e12a468 Fixed styles for autocomplete wrapper: added indicator for highlighted suggestion 2019-08-23 23:58:24 +02:00
Piotr Janosz
1bdcb4f737 Fixed hamburger menu not appearing at 800px. Laid groundwork for docs header fixes / reusability tomorrow 2019-08-23 23:58:24 +02:00
Piotr Janosz
5e5ecdcf32 [WIP] block body scroll on mobile search 2019-08-23 23:56:40 +02:00
Piotr Janosz
b316217394 Added scroll to top arrow for docs pages 2019-08-23 23:56:40 +02:00
Piotr Janosz
d96e307e2c Updated links for docs home with correct values 2019-08-23 23:56:40 +02:00
Piotr Janosz
a7944bb3c5 Fixed hover styles for step links 2019-08-23 23:56:40 +02:00
Piotr Janosz
2dc3885691 Added min height to section, docs layout 2019-08-23 23:56:40 +02:00
Piotr Janosz
027ab98a3e Adjusted filter margin on mobile / tablet 2019-08-23 23:56:40 +02:00
Piotr Janosz
1a5736a498 [WIP] Filtering for tools upgrades 2019-08-23 23:56:40 +02:00
Piotr Janosz
73f4c036c6 Added algolia constants to configs 2019-08-23 23:56:40 +02:00
Piotr Janosz
6cbadcf8e9 Introduced constant variables for algolia search 2019-08-23 23:56:40 +02:00
Piotr Janosz
6a38f231b1 Extracted content wrapper 2019-08-23 23:56:40 +02:00
Piotr Janosz
02d63daba5 Removed docs page template 2019-08-23 23:56:40 +02:00
Piotr Janosz
99074b3c34 Created reusable columns component 2019-08-23 23:56:18 +02:00
Piotr Janosz
bb33609164 Created a reusable page wrapper for docs pages 2019-08-23 23:56:18 +02:00
Piotr Janosz
27832741e4 Removed 'Loading' paragraph from icon loading state 2019-08-23 23:56:18 +02:00
Piotr Janosz
0cffdc9868 Fixed community maintained filter (custom label prop for filters). Fixed tools content display [WIP]. 2019-08-23 23:56:18 +02:00
Piotr Janosz
6055d44120 Fixed topics filter for guides 2019-08-23 23:56:18 +02:00
Piotr Janosz
984305d483 Small cleanup for docs 2019-08-23 23:56:18 +02:00
Piotr Janosz
7934624afc Connected guides to algolia 2019-08-23 23:56:18 +02:00
Piotr Janosz
e7db5aa4f3 Fixed filters, connected to algolia 2019-08-23 23:56:18 +02:00
Piotr Janosz
e922299a55 Added ellipsis to search placeholders 2019-08-23 23:56:18 +02:00
Piotr Janosz
58cbc7a05f Added helpful comments, removed Formular Mono from inputs 2019-08-23 23:56:18 +02:00
Piotr Janosz
43648a2382 Changed algolia creds 2019-08-23 23:56:18 +02:00
Piotr Janosz
c1abaa3293 Small cleanup of autocomplete component 2019-08-23 23:56:18 +02:00
Piotr Janosz
9f77879198 Added current refinement to wrapper props to get the correct zindex value for header search over docs search 2019-08-23 23:56:18 +02:00
Piotr Janosz
79279e5614 [WIP] Fixed reusable zIndex values. Added overlay for search in docs. 2019-08-23 23:56:18 +02:00
Piotr Janosz
d100897b20 Finished responsive styling for search input / autosuggest 2019-08-23 23:56:18 +02:00
Piotr Janosz
bfaaefaf0a Fixed font size and appearance of logo / docs for docs header 2019-08-23 23:56:17 +02:00
Piotr Janosz
520c6fa426 Hide section titles in autosuggest if returned hits are an empty list 2019-08-23 23:56:17 +02:00
Piotr Janosz
d95b520512 Added link tag to search suggestions 2019-08-23 23:56:17 +02:00
Piotr Janosz
10f8637802 Styling for search input home 2019-08-23 23:56:17 +02:00
Piotr Janosz
b327cc0f52 Fixed responsive bugs for docs page and template 2019-08-23 23:56:17 +02:00
Piotr Janosz
88acdaff90 Using the reusable Link component from react-shared for components with links in docs 2019-08-23 23:56:17 +02:00
Piotr Janosz
d5039809de Styled whitespace for docs pages 2019-08-23 23:56:17 +02:00
Piotr Janosz
2746b73416 Styled guides for responsive breakpoints 2019-08-23 23:56:17 +02:00
Piotr Janosz
fdd1d20c5b Using reusable Link for feature link. Added responsive styles for it. 2019-08-23 23:56:17 +02:00
Piotr Janosz
e2b4670016 Refactored some stuff 2019-08-23 23:56:17 +02:00
Piotr Janosz
336adc6974 Styled resource for different screen widths 2019-08-23 23:56:17 +02:00
Piotr Janosz
7c72ac52e1 Removed unnecessary wrapper 2019-08-23 23:56:17 +02:00
Piotr Janosz
d165bb2bb2 [WIP] styling search components 2019-08-23 23:56:17 +02:00
Piotr Janosz
12dea02fab Fixed styles for desktop snippet highlightig in autocomplete 2019-08-23 23:56:17 +02:00
Piotr Janosz
5181ee172b Fixed font weights for search input 2019-08-23 23:56:17 +02:00
Piotr Janosz
def0d9307e [WIP] Styling search: font weight for titles 2019-08-23 23:56:17 +02:00
Piotr Janosz
45e572388b [WIP] Tweak search: removed unnecessary code 2019-08-23 23:56:17 +02:00
Piotr Janosz
4898de8d41 [WIP] Tweaking search visually and logically 2019-08-23 23:56:17 +02:00
Piotr Janosz
1aa2270d97 [WIP styling mobile nav menu for docs] 2019-08-23 23:56:17 +02:00
Piotr Janosz
5abc9a8066 Using the reusable Link from react-shared for mobile nav menu 2019-08-23 23:56:17 +02:00
Piotr Janosz
a8deb6cc74 [WIP] Refactoring mobileNav to support docs 2019-08-23 23:56:17 +02:00
Piotr Janosz
87bcb46f43 [WIP] Refactored original header in anticipation for changes to docs header 2019-08-23 23:55:20 +02:00
Piotr Janosz
3d904aac67 Made separator margin for mobile a prop 2019-08-23 23:55:20 +02:00
Piotr Janosz
ace63fe83a Fixed docs whitespace for mobile / tablet 2019-08-23 23:55:20 +02:00
Piotr Janosz
33320fd758 Extracted get started links from home 2019-08-23 23:55:20 +02:00
Piotr Janosz
be5b4b7702 Fixed footer link wrapper margin on tablet 2019-08-23 23:55:20 +02:00
Piotr Janosz
5c55064c0f Refactored footer a tiny bit to fix styles on tablet + use es6 instead of lodash 2019-08-23 23:55:20 +02:00
Piotr Janosz
71ad8dcec0 Extracted a common Spearator (hr) component to reuse in docs. Adjusted styling for toc on mobile and tablet 2019-08-23 23:55:20 +02:00
Piotr Janosz
09fd8bc521 [WIP] Added overflow prop to section new layout. Fixed mobile layout for docs page. 2019-08-23 23:55:20 +02:00
Piotr Janosz
ace0150fcb Cleanup for table of contents. Added containerId default prop to link in react-shared 2019-08-23 23:55:20 +02:00
Piotr Janosz
e627d3ce01 [WIP] table of contents adjustments 2019-08-23 23:55:20 +02:00
Piotr Janosz
a65f981f55 Styled react-scroll links in table of contents 2019-08-23 23:55:20 +02:00
Piotr Janosz
dbebb3818d [WIP] responsive tweaks to docs page template 2019-08-23 23:55:20 +02:00
Piotr Janosz
2027b74c5f Added a boolean isCommunity flag to resource to simplify adding labels 2019-08-23 23:55:20 +02:00
Piotr Janosz
5e921fdd08 Fixed styles for community maintained tag 2019-08-23 23:55:20 +02:00
Piotr Janosz
6eda017719 Fixed heading size for other pages than home in docs 2019-08-23 23:55:20 +02:00
Piotr Janosz
9b9960c7b9 Extracted mdx-mapped headings to a separate file. Applied correct sizing to headings 2019-08-23 23:55:20 +02:00
Piotr Janosz
9df09e2464 Added min-width to notification icon 2019-08-23 23:55:20 +02:00
Piotr Janosz
5dacc58a4e Renamed tutorial steps => ordered list (to match other component names) 2019-08-23 23:55:20 +02:00
Piotr Janosz
fcb18e8d34 Fixed line height for lists in docs 2019-08-23 23:55:20 +02:00
Piotr Janosz
9af95a9461 Fixed line-height for notifications (mobile) 2019-08-23 23:55:20 +02:00
Piotr Janosz
bef662a6e1 Restored analytics for was_this_helpful 2019-08-23 23:55:20 +02:00
Piotr Janosz
04f24f32e2 Added responsive styles for helpful cta 2019-08-23 23:55:20 +02:00
Piotr Janosz
65743882bb Updated styles for unordered list 2019-08-23 23:55:20 +02:00
Piotr Janosz
9e82b51eb5 Created two demo pages to test the components 2019-08-23 23:55:20 +02:00
Piotr Janosz
a20c40ca90 Further responsive styling of docs home 2019-08-23 23:55:20 +02:00
Piotr Janosz
745bdda1a3 Adjusted icon sizes 2019-08-23 23:55:20 +02:00
Piotr Janosz
3c7e538202 Fixed styles for community links 2019-08-23 23:55:20 +02:00
Piotr Janosz
786419fee0 Fixed responsive styles for docs home: shortcut links 2019-08-23 23:55:20 +02:00
Piotr Janosz
739651b917 Changed loader thickness for docs 2019-08-23 23:55:20 +02:00
Piotr Janosz
e374469818 [WIP] restyling search input in the header 2019-08-23 23:55:20 +02:00
Piotr Janosz
2ecd9672c2 Refactored autocomplete into a function component 2019-08-23 23:55:20 +02:00
Piotr Janosz
68a4ad2e51 Restyled search autocomplete 2019-08-23 23:55:20 +02:00
Piotr Janosz
b2e2c27775 Updated ToC / usage doc 2019-08-23 23:55:20 +02:00
Piotr Janosz
8e45d5e137 [WIP] Created table of contents 2019-08-23 23:55:19 +02:00
Piotr Janosz
1ded7cd4f1 Figured out how to export ToC via mdx-loader 2019-08-23 23:55:19 +02:00
Piotr Janosz
8bd2411a89 Fixed icon color for help callout 2019-08-23 23:55:19 +02:00
Piotr Janosz
907fba7d0f Hooked up analytics to helpful cta 2019-08-23 23:55:19 +02:00
Piotr Janosz
bb5afc43b9 Added state to helpful_cta 2019-08-23 23:55:19 +02:00
Piotr Janosz
a243c9d685 Fixed styling for help callout 2019-08-23 23:55:19 +02:00
Piotr Janosz
829eeb2374 Refactored unnecessary Hero props 2019-08-23 23:55:19 +02:00
Piotr Janosz
338de4ffa1 Fixed colors for resource tags 2019-08-23 23:55:19 +02:00
Piotr Janosz
c7fbd6c64c Added temp mapping content to section in tools 2019-08-23 23:55:19 +02:00
Piotr Janosz
95b7ae3146 Fixed rendering tools page 2019-08-23 23:55:19 +02:00
Piotr Janosz
ded48fd453 Updated docs homepage icons 2019-08-23 23:55:19 +02:00
Piotr Janosz
cbe2cf8a85 Updated styling for the loader in mdx docs 2019-08-23 23:55:19 +02:00
Piotr Janosz
a12dc5c81b [WIP] Updated react-syntax-highlighter. Added loading state to docs. Replaced search placeholder text. 2019-08-23 23:55:19 +02:00
Piotr Janosz
db062154d1 Changed tabs => code_tabs. Changed notification signature. Removed old unused code (docs view duplicate) 2019-08-23 23:55:19 +02:00
Piotr Janosz
ac3a6426e8 Correctly parsing tabbed code snippets from mdx 2019-08-23 23:55:19 +02:00
Piotr Janosz
f1f5b57254 [WIP] Refactoring complex code components 2019-08-23 23:55:19 +02:00
Piotr Janosz
3403e8af9b Added inline code / link to mapped mdx components. Changed font size for search input in docs. 2019-08-23 23:55:19 +02:00
Piotr Janosz
19286db952 Parsing language passed in to code in mdx. Renamed boolean prop run => canRun 2019-08-23 23:55:19 +02:00
Piotr Janosz
40234e5b4a Fixed styling for copy / run code buttons in code snippet 2019-08-23 23:55:19 +02:00
Piotr Janosz
a9f046609c Removed some whitespace 2019-08-23 23:55:19 +02:00
Piotr Janosz
f2e2672e81 Renamed coreConcepts icon. Restyled how copy button and tabs appear in code 2019-08-23 23:55:19 +02:00
Piotr Janosz
784f2674a9 Updated icons for docs 2019-08-23 23:55:19 +02:00
Piotr Janosz
93399165e7 Updated some icons. Fixed styling for Code [WIP] 2019-08-23 23:55:19 +02:00
Piotr Janosz
7422485817 [WIP] new docs icons. Some need replacement as they render badly 2019-08-23 23:55:19 +02:00
Piotr Janosz
2ef19f31db [WIP] Async docs page loading 2019-08-23 23:53:44 +02:00
Piotr Janosz
8154209eab [WIP] docs view 2019-08-23 23:53:44 +02:00
Piotr Janosz
d56fb374a7 Created a reusable newsletter signup form and widget 2019-08-23 23:53:44 +02:00
Piotr Janosz
7bad1d2921 Refactored newsletter form into a stateless component 2019-08-23 23:53:44 +02:00
Piotr Janosz
37dd494abd Changed global form style for inputs to Formular 2019-08-23 23:53:44 +02:00
Piotr Janosz
a9748e1b52 [WIP] started working on the newsletter signups 2019-08-23 23:53:44 +02:00
Piotr Janosz
cc33101923 Fixed note styling 2019-08-23 23:53:43 +02:00
Piotr Janosz
31fbbb52a8 Small refactoring imporvements to docs components 2019-08-23 23:53:43 +02:00
Piotr Janosz
d2c5665a30 Refactored autocomplete, chapter links, filter, filters. 2019-08-23 23:53:43 +02:00
Piotr Janosz
06744ee7fb Refactored resource and tag components 2019-08-23 23:53:43 +02:00
Piotr Janosz
3e1db453ff Refactored rating_bar 2019-08-23 23:53:43 +02:00
Piotr Janosz
ec76186c23 Removed suprflous code from table, tutorial steps, unordered list 2019-08-23 23:53:43 +02:00
Piotr Janosz
fcf975a65c Refactored tutorial_steps. 2019-08-23 23:53:43 +02:00
Piotr Janosz
e6d2c7db88 Refactored Table components 2019-08-23 23:53:43 +02:00
Piotr Janosz
d012268953 Fixed small errors 2019-08-23 23:53:43 +02:00
Piotr Janosz
70b797cb6d Refactored siteWrap into a function component 2019-08-23 23:53:43 +02:00
Piotr Janosz
28d7cf38c8 Small refactoring of search input 2019-08-23 23:53:43 +02:00
Piotr Janosz
6094fa7b6d Changed import order in docs home. 2019-08-23 23:53:43 +02:00
Piotr Janosz
8f3b7ee522 Refactored search_input and shortcut_link components 2019-08-23 23:53:43 +02:00
Piotr Janosz
74f6fb7408 Refactored Note / Notification components 2019-08-23 23:53:43 +02:00
Piotr Janosz
4ccb735282 Cleaned up helpful_cta, hero, newsletter_signup components. 2019-08-23 23:53:43 +02:00
Piotr Janosz
b94631c84a Refactored help callout 2019-08-23 23:53:43 +02:00
Piotr Janosz
2544e4fd65 Fixed margin forget started buttons in docs home 2019-08-23 23:53:43 +02:00
Piotr Janosz
7454a7a6f3 [WIP] Refactoring of docs pages components. 2019-08-23 23:53:43 +02:00
Piotr Janosz
13e262b9cf [WIP] refactoring docs header 2019-08-23 23:53:43 +02:00
Piotr Janosz
b4db9d8b7d Refactored community and feature links 2019-08-23 23:53:43 +02:00
Piotr Janosz
14ad5ced78 Refactored community link props 2019-08-23 23:53:43 +02:00
Piotr Janosz
b2e592bb41 Refactored docs home 2019-08-23 23:53:43 +02:00
Piotr Janosz
1a3281a959 Refactored and renamed callout => notificatin 2019-08-23 23:53:43 +02:00
Piotr Janosz
6701c58a10 Refactored runnable code snippet 2019-08-23 23:53:43 +02:00
Piotr Janosz
80fd0db2eb (WIP) refactoring code tabs, adding runnable code. 2019-08-23 23:53:43 +02:00
Piotr Janosz
7ca8c5c16d Cleaned up code and tabs components in docs 2019-08-23 23:53:43 +02:00
Fred Carlsen
3ed7cc5cab Added more components to MDX render 2019-08-23 23:53:43 +02:00
Fred Carlsen
0987ae05a8 Update page template 2019-08-23 23:53:43 +02:00
Fred Carlsen
3154149d37 Import more custom components to MDX 2019-08-23 23:53:43 +02:00
Fred Carlsen
6f46109617 Fit code to MDX 2019-08-23 23:53:42 +02:00
Fred Carlsen
b0896408d2 Add discord link 2019-08-23 23:53:42 +02:00
Fred Carlsen
243b478b99 Cleanup 2019-08-23 23:53:42 +02:00
Fred Carlsen
fabbad2b2c Tweak view to export metadata as object from mdx 2019-08-23 23:53:42 +02:00
Piotr Janosz
1948ffe7bd Updated and saved react / react-dom versions to 16.8.6 2019-08-23 23:53:42 +02:00
Fred Carlsen
67baee60f8 MDX module declaration 2019-08-23 23:53:42 +02:00
Fred Carlsen
8f4c4715e2 Improve loading 2019-08-23 23:53:42 +02:00
Fred Carlsen
3e7cbe6015 Fix link on docs template example 2019-08-23 23:53:42 +02:00
Fred Carlsen
0053bde668 Fix react dependencies across all packages 2019-08-23 23:53:42 +02:00
Fred Carlsen
363dd31768 Ignore custom SSL certs 2019-08-23 23:53:42 +02:00
Fred Carlsen
f841737adc Add MDX provider 2019-08-23 23:53:42 +02:00
Fred Carlsen
9adaa7972e Add view template + mdx example 2019-08-23 23:53:42 +02:00
Piotr Janosz
ec387f9bb7 Added node version manager config file to gitignore 2019-08-23 23:53:42 +02:00
Fred Carlsen
aa657776fc Tweak tools page 2019-08-23 23:53:42 +02:00
Fred Carlsen
f12632a1f2 Tweak search 2019-08-23 23:53:42 +02:00
Fred Carlsen
4f8164dc43 Pass filter groups as props 2019-08-23 23:53:42 +02:00
Fred Carlsen
88303d8855 Cleanup 2019-08-23 23:53:42 +02:00
Fred Carlsen
4e8ddafa64 Upgrade react to 16.8 2019-08-23 23:53:42 +02:00
Fred Carlsen
1ebe9d2bba Add prettier 2019-08-23 23:53:25 +02:00
Fred Carlsen
fbae619725 Add key 2019-08-23 23:53:25 +02:00
Fred Carlsen
8c5f4c3de7 WIP search 2019-08-23 23:53:25 +02:00
Fred Carlsen
154841157f Add chapter links 2019-08-23 23:53:04 +02:00
Fred Carlsen
6a20d06194 Add get started link 2019-08-23 23:53:04 +02:00
Fred Carlsen
245e118016 Fix search box icon 2019-08-23 23:53:04 +02:00
Fred Carlsen
fcc9d6749c Add tools page 2019-08-23 23:53:04 +02:00
Fred Carlsen
9e091c5015 Format code 2019-08-23 23:52:46 +02:00
Fred Carlsen
01247319c3 Prettier 2019-08-23 23:52:46 +02:00
Fred Carlsen
1d3d5f7e32 WIP guides page 2019-08-23 23:52:46 +02:00
Fred Carlsen
49f2cef5ac WIP components 2019-08-23 23:52:45 +02:00
Fred Carlsen
926d165321 More WIP components 2019-08-23 23:52:45 +02:00
Fred Carlsen
86218445cd Fix dependencies 2019-08-23 23:52:45 +02:00
Matthew Cadier Kim
6e0f695699 Remove pipeline package
* Remove entire readme for the pipelines package.

* remove pipeline everywhere

* bump circle ci
2019-08-23 23:52:32 +02:00
Xianny
7b9ff7776d Prune fields from EthBalanceChecker (#1876)
Remove forbidden fields from EthBalanceChecker
2019-08-23 23:52:32 +02:00
Fabio Berger
e0f3f53d42 Update Python artifact 2019-08-23 23:52:32 +02:00
Fabio Berger
2e911ee709 Add artifact to Python package 2019-08-23 23:52:32 +02:00
Fred Carlsen
43afed6654 Add mdx loader 2019-08-23 23:52:32 +02:00
Fred Carlsen
0dda8328af Use custom cert if server.key/.crt file exits in website dir 2019-08-23 23:52:31 +02:00
Fred Carlsen
48052fc3e4 WIP docs 2019-08-23 23:52:31 +02:00
Fred Carlsen
5ac5fed513 Prefix methods 2019-08-23 23:51:38 +02:00
Fred Carlsen
60521e8167 Prefix methods 2019-08-23 23:51:38 +02:00
Fred Carlsen
510568d4f1 Change to hash for triggering contact modals 2019-08-23 23:51:37 +02:00
Fred Carlsen
3e3ec3134d Added close button to contact modal 2019-08-23 23:51:37 +02:00
Fred Carlsen
c22374893e Remove unused vars 2019-08-23 23:51:37 +02:00
Fred Carlsen
013eaeeb07 Fix svg errors 2019-08-23 23:51:37 +02:00
Fred Carlsen
b97b6867d8 Add modal links 2019-08-23 23:51:37 +02:00
fabioberger
87f31ec532 Update yarn.lock 2019-08-23 23:38:41 +02:00
fabioberger
9b12695443 Fix rebase issue 2019-08-23 23:34:04 +02:00
Xianny
cbb40c1c2b Remove generated wrappers from contract-wrappers (#2086) 2019-08-23 10:22:50 -07:00
fabioberger
b0e56fc27b Bump version of ts-doc-gen 2019-08-23 19:13:27 +02:00
fabioberger
d15532227d Update yarn.lock 2019-08-23 19:12:04 +02:00
fabioberger
c3f98e95ad Remove 0x.js from packages getting MD docs generated for them 2019-08-23 19:12:04 +02:00
fabioberger
e92e99d6ea Add missing devDep 2019-08-23 19:12:04 +02:00
fabioberger
f6b67f6c98 Remove absolute paths from docs 2019-08-23 19:11:16 +02:00
fabioberger
108861b6ca Update ts-doc-gen to version that removes absolute paths from docs 2019-08-23 19:11:16 +02:00
fabioberger
80d93e8d75 Output reference docs with mdx file extension 2019-08-23 19:10:29 +02:00
fabioberger
1634cd53be Update ts-doc-gen dep 2019-08-23 19:10:29 +02:00
fabioberger
577df3749d Remove temporary artifact 2019-08-23 19:08:30 +02:00
fabioberger
73c53b3da6 Use .mdx extension for packages 2019-08-23 19:08:30 +02:00
fabioberger
9af996a907 Upgrade circleCI yarn 2019-08-23 19:08:30 +02:00
fabioberger
bd2e4a8076 Store contract-wrappers node_modules as artifacts 2019-08-23 19:08:30 +02:00
fabioberger
ceaa6a592c Update ts-doc-gen 2019-08-23 19:07:17 +02:00
fabioberger
b503fecccb Add ignore compiler errors in Typedoc json command for now 2019-08-23 19:06:40 +02:00
fabioberger
4161055cc7 Remove all localhost resolutions from yarn 2019-08-23 19:06:20 +02:00
fabioberger
b0c9a3bbe1 Remove excess comma 2019-08-23 19:06:19 +02:00
fabioberger
436bdde461 Temporarily ignore compiler errors since Typedoc is using Typescript 3.5.x and we are still on 3.0.1 but upgrading should happen in a separate PR 2019-08-23 19:06:19 +02:00
fabioberger
01853064b0 Fix ts-doc-gen version to 0.0.7 2019-08-23 19:06:19 +02:00
fabioberger
c1ccb5af0f Update Typedoc version 2019-08-23 19:05:38 +02:00
fabioberger
706f04ee27 Remove forced resolution of graceful-fs since new Lerna version depends on backward incompatible behavior to pinned version 2019-08-23 19:05:38 +02:00
fabioberger
549e35e972 Update yarn.lock 2019-08-23 19:05:38 +02:00
fabioberger
1ed66966a8 Prettierignore generated docs 2019-08-23 19:05:38 +02:00
fabioberger
326539f1f5 Update ts-docs-gen dep and re-generate the reference docs 2019-08-23 19:05:38 +02:00
fabioberger
67322ba39f Only upload MD docs if an actual publish 2019-08-23 19:04:36 +02:00
fabioberger
41fcc41bd1 Fix linter 2019-08-23 19:04:36 +02:00
fabioberger
7aacff62ca Add MD doc generation and S3 upload to publishing flow 2019-08-23 19:04:36 +02:00
fabioberger
4566ddb037 Split MD doc generation and S3 uploading 2019-08-23 19:04:36 +02:00
fabioberger
957e6b1500 Add Doc MD generation & S3 upload commands and generate the MD docs for the current version 2019-08-23 19:04:36 +02:00
fabioberger
5945635d1d Remove doc commands from sol-tracing-utils because we don't gen docs for this package 2019-08-23 19:01:16 +02:00
F. Eugene Aumson
045fc0914b abi-gen: inline @0x/abi-gen-templates (#2082)
* abi-gen: inline @0x/abi-gen-templates

And use those inlines by default, relieving caller of having to specify
--template and --partials all the time.

Simplify abi-gen usage in all package.json's, omitting --template and
--partials to defer to the defaults.

* abi-gen: Update CHANGELOG.json

* contract_wrappers.py: be a user of abi-gen
2019-08-22 12:23:15 -04:00
Jacob Evans
72442871aa Remove accidental env 2019-08-22 18:45:20 +10:00
Jacob Evans
bbd3c03969 Publish
- @0x/contracts-asset-proxy@2.2.6
 - @0x/contracts-coordinator@2.0.11
 - @0x/contracts-dev-utils@0.0.8
 - @0x/contracts-erc1155@1.1.13
 - @0x/contracts-erc20@2.2.12
 - @0x/contracts-erc721@2.1.13
 - @0x/contracts-exchange-forwarder@3.0.10
 - @0x/contracts-exchange-libs@3.0.6
 - @0x/contracts-exchange@2.1.12
 - @0x/contracts-extensions@4.0.6
 - @0x/contracts-multisig@3.1.12
 - @0x/contracts-test-utils@3.1.14
 - @0x/contracts-utils@3.2.2
 - 0x.js@7.0.0
 - @0x/abi-gen-templates@2.4.2
 - @0x/abi-gen-wrappers@5.3.0
 - @0x/abi-gen@4.1.1
 - @0x/assert@2.1.4
 - @0x/asset-buyer@6.1.12
 - @0x/asset-swapper@1.0.2
 - @0x/base-contract@5.3.2
 - @0x/connect@5.0.17
 - @0x/contract-addresses@3.1.0
 - @0x/contract-artifacts@2.2.0
 - @0x/contract-wrappers@11.1.0
 - @0x/dev-utils@2.3.1
 - @0x/fill-scenarios@3.0.17
 - @0x/instant@1.0.29
 - @0x/json-schemas@4.0.0
 - @0x/migrations@4.3.0
 - @0x/monorepo-scripts@1.0.35
 - @0x/order-utils@8.3.0
 - @0x/python-contract-wrappers@1.0.4
 - @0x/sol-compiler@3.1.13
 - @0x/sol-coverage@3.0.10
 - @0x/sol-doc@2.0.17
 - @0x/sol-profiler@3.1.12
 - @0x/sol-trace@2.0.18
 - @0x/sol-tracing-utils@6.0.17
 - @0x/sra-spec@2.0.15
 - @0x/subproviders@5.0.2
 - @0x/testnet-faucets@1.0.85
 - @0x/web3-wrapper@6.0.11
 - @0x/website@0.0.88
2019-08-22 14:13:00 +10:00
Jacob Evans
a4405c3d39 Updated CHANGELOGS 2019-08-22 14:12:40 +10:00
Xianny
0fe4f587d8 update ethereumjs-blockstream 6.0.0 -> ^7.0.0 (#2089) 2019-08-21 18:39:07 -07:00
Francesco Agosti
d3c714bd17 Merge pull request #2085 from 0xProject/feature/cfl-page-fix
Fix small issue on mobile nav
2019-08-21 14:54:17 -07:00
fragosti
c399b7a7d5 Add Asset Swapper to footer 2019-08-21 14:30:55 -07:00
fragosti
b9234e94fb Fix small issue on mobile nav 2019-08-21 14:30:55 -07:00
Francesco Agosti
417bb87785 Merge pull request #2081 from 0xProject/feature/cfl-page
CFL page
2019-08-20 18:24:40 -07:00
fragosti
0233ae3134 Use Asset Swapper on CFL page 2019-08-20 17:48:57 -07:00
fragosti
eed0c5dd59 Distinguish between asset swapper page and docs 2019-08-20 17:39:15 -07:00
fragosti
2b3b167095 Fix path of asset swapper link in product dropdown 2019-08-20 17:30:15 -07:00
fragosti
5d91d19808 Disable jsx-curly-spacing on cfl page 2019-08-20 17:24:49 -07:00
fragosti
0f374ddee9 Change AssetBuyer to AssetSwapper on instant page 2019-08-20 17:08:03 -07:00
Chris Kalani
a65a9913cd Fixed up some design nits and updated copy 2019-08-20 16:51:06 -07:00
fragosti
1ead32c666 Asset-Swapper -> asset-swapper 2019-08-20 15:35:39 -07:00
fragosti
d1af9fc780 use asset-swapper instead of Asset-Swapper 2019-08-20 15:31:50 -07:00
fragosti
0f06737fb6 Fix install prompt on mobile layout 2019-08-20 15:01:59 -07:00
fragosti
1676231532 Rename variables to be compatible with new backend 2019-08-20 14:36:57 -07:00
fragosti
b1caf697c8 Update titles and descriptions 2019-08-20 13:52:50 -07:00
fragosti
51481065fe Fix jumping around of editor 2019-08-20 11:56:09 -07:00
fragosti
e367da710c Fix massive i 2019-08-20 11:47:05 -07:00
fragosti
f493d6524d Change to crypto algo-traders 2019-08-20 11:22:21 -07:00
fragosti
e1b85da2a7 Make terminal text selectable 2019-08-20 11:16:28 -07:00
F. Eugene Aumson
22c6548ed1 abi-gen/test-cli: rm expected-output; use git diff (#2079)
* abi-gen/test-cli: rm expected-output; use git diff

* abi-gen/test-cli: Simplify git diff test script

* Remove abi-gen/test-cli/output from .gitignore
2019-08-20 14:08:54 -04:00
Fabio B
afb32c087d Merge pull request #2017 from jangerritharms/fix/broken-validator-signatures
Fix broken validator signatures
2019-08-20 18:44:50 +02:00
Jan-Gerrit Harms
bbc1ed1c64 Update test to adhere to v2.1 Validator revert 2019-08-20 14:53:10 +02:00
Jan-Gerrit Harms
3a46f1a27a Merge branch 'development' into fix/broken-validator-signatures 2019-08-20 09:30:21 +02:00
Jacob Evans
90cd364780 Merge pull request #2078 from 0xProject/fix/isValidSignature-2.1
Update development to 2.1 isValidSignature with magic salt
2019-08-20 16:34:48 +10:00
Jacob Evans
6795e6f078 Update comments with bytes4 values 2019-08-20 16:15:44 +10:00
fragosti
cfb3404349 Fix dogfood link 2019-08-19 20:49:35 -07:00
fragosti
0212f3ee78 Run linter 2019-08-19 19:28:42 -07:00
fragosti
6b2995a4ee Remove didError state from CFLmetrics component 2019-08-19 19:24:37 -07:00
fragosti
09e7ac54d4 Replace hummingbot link 2019-08-19 19:18:58 -07:00
fragosti
f69009d4a8 Add CFL to mobile dropdown and remove extensions for desktop 2019-08-19 19:16:26 -07:00
fragosti
206802ae33 Make layout more responsive 2019-08-19 19:08:48 -07:00
fragosti
91d4138fb8 Fix react key error 2019-08-19 18:22:17 -07:00
fragosti
cb455f951a Add loading state to CFL metrics 2019-08-19 18:19:01 -07:00
fragosti
5f25d20cd0 Improve tooltip and copy 2019-08-19 17:54:10 -07:00
fragosti
1f0e2cd910 Add info tooltip 2019-08-19 17:46:11 -07:00
Jacob Evans
1749d02701 Add python linter exception 2019-08-20 10:30:09 +10:00
fragosti
55ace3179c Add disclaimer component 2019-08-19 17:00:41 -07:00
fragosti
7866d9ccb4 Implement CFL metrics MVP 2019-08-19 16:52:40 -07:00
Brandon Millman
51f73d07fa Merge pull request #2080 from 0xProject/feature/website/adding-michael
Adding Michael Zhu to the team page
2019-08-19 13:02:18 -07:00
Francesco Agosti
63d84674ab Merge pull request #2074 from 0xProject/feature/website/remove-faq
Removing the old FAQ page and all references
2019-08-19 12:36:59 -07:00
Chris Kalani
14066997b2 Adding Michael Zhu to the team page 2019-08-19 12:34:19 -07:00
F. Eugene Aumson
28561e765a Update README.md (#2077)
* Update README.md

* top-level README.md: explain Python dependency

* top-level README.md: suggest node v6 OR v8
2019-08-19 13:55:06 -04:00
Jacob Evans
453fbbdc5d Update python doc strings 2019-08-19 15:55:28 +10:00
Jacob Evans
1e1e5ec10d Catch revert in IWallet/IValidator and return false 2019-08-19 15:45:32 +10:00
Jacob Evans
2088b0e459 Update python doc string 2019-08-19 15:13:09 +10:00
Jacob Evans
58400d9e01 Update python docs string 2019-08-19 14:40:46 +10:00
Jacob Evans
ac9375f1d2 Updated generated-wrappers? 2019-08-19 14:10:50 +10:00
Jacob Evans
db061c9355 Update Whitelist.sol 2019-08-19 12:15:46 +10:00
Jacob Evans
d5ce6c464b Update Wallet signature test 2019-08-19 11:55:48 +10:00
Jacob Evans
b06205bb7f Fix lint errors 2019-08-19 11:36:35 +10:00
Jacob Evans
f528a3e1de Update Order-utils to check magic values 2019-08-19 11:14:35 +10:00
Jacob Evans
bddfdacfad Update Interfaces for IValidator and IWallet 2019-08-19 11:08:06 +10:00
Jacob Evans
d3cdd3f235 Update development to 2.1 isValidSignature with magic salt 2019-08-19 10:35:26 +10:00
Chris Kalani
41ae45ea40 Fixed build error 2019-08-16 14:17:12 -07:00
Chris Kalani
657e0895ea Removing the olf FAW page and all references 2019-08-16 13:56:03 -07:00
Jan-Gerrit Harms
b2592d1cc2 Removed the order-watcher files that were accidentally added 2019-08-16 14:02:32 +02:00
Jan-Gerrit Harms
aa3524c3b2 Merge branch 'development' into fix/broken-validator-signatures 2019-08-16 13:04:27 +02:00
fragosti
39deb1a05f Make it possible to show figure in hero on the bottom on mobile 2019-08-15 17:23:20 -07:00
fragosti
302d08e290 Make website mobile friendly 2019-08-15 17:01:50 -07:00
fragosti
05489dd7f1 Implement basic CFL landing page 2019-08-15 16:33:52 -07:00
Jan-Gerrit Harms
55bd076602 Merge branch 'development' into fix/broken-validator-signatures 2019-08-14 09:37:20 +02:00
Jan-Gerrit Harms
7a224fe08f Merge branch 'development' into fix/broken-validator-signatures 2019-08-13 19:49:24 +02:00
Jan-Gerrit Harms
3bdeb82097 Updated CHANGELOG of 0x.js and @0x/order-watcher 2019-08-09 09:58:29 +02:00
Jan-Gerrit Harms
f49ab3f919 Merge branch 'development' into fix/broken-validator-signatures 2019-08-09 09:47:42 +02:00
Jan-Gerrit Harms
42d5bdd3ab Explicitly check exchangeAddress definedness 2019-08-09 09:39:49 +02:00
Jan-Gerrit Harms
7228cbfe92 Pass exchangeAddress instead of SignatureOpts 2019-08-09 09:36:32 +02:00
Jan-Gerrit Harms
11e2fc5bc4 Added documentation for additional parameters 2019-07-30 15:18:08 +02:00
Jan-Gerrit Harms
3e88f820b8 Prettified changelog 2019-07-30 15:11:24 +02:00
Jan-Gerrit Harms
163750f8c2 Updated internal usages of isValidSignatureAsync 2019-07-30 14:52:35 +02:00
Jan-Gerrit Harms
4aabc5d791 Fixed merge conflict in changelog 2019-07-30 14:43:24 +02:00
Jan-Gerrit Harms
c9a7b9dcc1 Appended to changelog in the order-utils package 2019-07-30 14:35:11 +02:00
Jan-Gerrit Harms
98075b5653 Revert "Updated changelog"
This reverts commit 57ae5be916.
2019-07-30 14:32:27 +02:00
Jan-Gerrit Harms
57ae5be916 Updated changelog 2019-07-30 14:26:46 +02:00
Jan-Gerrit Harms
8caf62997f Forgot formatting again 2019-07-30 13:26:27 +02:00
Jan-Gerrit Harms
f8656ad376 Added integration tests and fixed another bug 2019-07-30 13:25:36 +02:00
Jan-Gerrit Harms
29c6c2a2ad Add exports to 0x.js 2019-07-30 10:15:41 +02:00
Jan-Gerrit Harms
f2db67ef02 Fixed prettier errors 2019-07-30 09:50:54 +02:00
Jan-Gerrit Harms
72b8ef33d9 Fixes #1998, still needs Integration testing 2019-07-29 21:39:21 +02:00
3183 changed files with 396010 additions and 147360 deletions

419
.circleci/config.yml Normal file
View File

@@ -0,0 +1,419 @@
version: 2
jobs:
build:
resource_class: medium+
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
environment:
CONTRACTS_COMMIT_HASH: '9ed05f5'
working_directory: ~/repo
steps:
- checkout
- run: echo 'export PATH=$HOME/CIRCLE_PROJECT_REPONAME/node_modules/.bin:$PATH' >> $BASH_ENV
# HACK(feuGeneA): commented out this hack as we're changing
# from a circleci-maintained container to a different
# container, and this hack may not apply anymore, as
# suggested by the non-existance of `/home/circleci/.bashrc`
# when running the command below.
# - run:
# # HACK(albrow): Without this, yarn commands will sometimes
# # fail with a "permission denied" error.
# name: Set npm path
# command: npm set prefix=/home/circleci/npm && echo 'export PATH=$HOME/circleci/npm/bin:$PATH' >> /home/circleci/.bashrc
- run:
name: install-yarn
command: npm install --global yarn@1.17.0
- run:
name: yarn
command: yarn --frozen-lockfile --ignore-engines install || yarn --frozen-lockfile --ignore-engines install
- setup_remote_docker
- run: yarn build:ci:no_website
- run: yarn build:ts
- save_cache:
key: repo-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo
- store_artifacts:
path: ~/repo/packages/abi-gen/test-cli/output
- store_artifacts:
path: ~/repo/packages/abi-gen-wrappers/generated_docs
build-website:
resource_class: medium+
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
working_directory: ~/repo
steps:
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- run: cd packages/website && yarn build:prod
test-contracts-ganache:
resource_class: medium+
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
working_directory: ~/repo
steps:
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- run: yarn wsrun test:circleci @0x/contracts-multisig @0x/contracts-utils @0x/contracts-exchange-libs @0x/contracts-erc20 @0x/contracts-erc721 @0x/contracts-erc1155 @0x/contracts-extensions @0x/contracts-asset-proxy @0x/contracts-exchange @0x/contracts-exchange-forwarder @0x/contracts-coordinator @0x/contracts-dev-utils
test-contracts-geth:
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
- image: 0xorg/devnet
working_directory: ~/repo
steps:
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
# HACK(albrow): we need to sleep 10 seconds to ensure the devnet is
# initialized
- run: sleep 10 && TEST_PROVIDER=geth yarn wsrun test:circleci @0x/contracts-multisig @0x/contracts-utils @0x/contracts-exchange-libs @0x/contracts-erc20 @0x/contracts-erc721 @0x/contracts-erc1155 @0x/contracts-extensions @0x/contracts-asset-proxy @0x/contracts-exchange @0x/contracts-exchange-forwarder @0x/contracts-coordinator @0x/contracts-dev-utils
test-publish:
resource_class: medium+
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
- image: 0xorg/verdaccio
working_directory: ~/repo
steps:
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- run: yarn test:publish:circleci
test-doc-generation:
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
working_directory: ~/repo
steps:
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- run: yarn test:generate_docs:circleci
test-rest:
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
working_directory: ~/repo
steps:
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- run: yarn wsrun test:circleci @0x/contracts-test-utils
- run: yarn wsrun test:circleci @0x/abi-gen
- run: yarn wsrun test:circleci @0x/asset-buyer
- run: yarn wsrun test:circleci @0x/contract-artifacts
- run: yarn wsrun test:circleci @0x/assert
- run: yarn wsrun test:circleci @0x/base-contract
- run: yarn wsrun test:circleci @0x/connect
- run: yarn wsrun test:circleci @0x/contract-wrappers
- run: yarn wsrun test:circleci @0x/dev-utils
- run: yarn wsrun test:circleci @0x/json-schemas
- run: yarn wsrun test:circleci @0x/order-utils
- run: yarn wsrun test:circleci @0x/sol-compiler
- run: yarn wsrun test:circleci @0x/sol-tracing-utils
- run: yarn wsrun test:circleci @0x/sol-doc
- run: yarn wsrun test:circleci @0x/subproviders
- run: yarn wsrun test:circleci @0x/web3-wrapper
- run: yarn wsrun test:circleci @0x/utils
- run: yarn wsrun test:circleci @0x/instant
- save_cache:
key: coverage-abi-gen-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/abi-gen/coverage/lcov.info
- save_cache:
key: coverage-assert-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/assert/coverage/lcov.info
- save_cache:
key: coverage-asset-buyer-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/asset-buyer/coverage/lcov.info
- save_cache:
key: coverage-base-contract-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/base-contract/coverage/lcov.info
- save_cache:
key: coverage-connect-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/connect/coverage/lcov.info
- save_cache:
key: coverage-contract-wrappers-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/contract-wrappers/coverage/lcov.info
- save_cache:
key: coverage-dev-utils-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/dev-utils/coverage/lcov.info
- save_cache:
key: coverage-json-schemas-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/json-schemas/coverage/lcov.info
- save_cache:
key: coverage-order-utils-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/order-utils/coverage/lcov.info
- save_cache:
key: coverage-sol-compiler-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/sol-compiler/coverage/lcov.info
- save_cache:
key: coverage-sol-tracing-utils-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/sol-tracing-utils/coverage/lcov.info
- save_cache:
key: coverage-sol-doc-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/sol-doc/coverage/lcov.info
- save_cache:
key: coverage-subproviders-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/subproviders/coverage/lcov.info
- save_cache:
key: coverage-web3-wrapper-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/packages/web3-wrapper/coverage/lcov.info
test-python:
working_directory: ~/repo
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
- image: 0xorg/ganache-cli:2.2.2
- image: 0xorg/launch-kit-backend:74bcc39
environment:
RPC_URL: http://localhost:8545
NETWORK_ID: 50
WHITELIST_ALL_TOKENS: True
command: |
sh -c "until printf 'POST /\r\nContent-Length: 26\r\n\r\n{\"method\":\"net_listening\"}' | nc localhost 8545 | grep true; do continue; done; node_modules/.bin/forever ts/lib/index.js"
steps:
- checkout
- restore_cache:
key: installed-py-{{ .Branch }}-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- run:
command: |
cd python-packages
python -m ensurepip
./pre_install
./install
- save_cache:
key: installed-py-{{ .Branch }}-{{ .Environment.CIRCLE_SHA1 }}
paths:
- '/usr/local/bin'
- '/usr/local/lib/python3.7/site-packages'
- run:
command: |
cd python-packages
./parallel_without_sra_client coverage run setup.py test
./build_docs
- save_cache:
key: coverage-python-contract-addresses-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/python-packages/contract_addresses/.coverage
- save_cache:
key: coverage-python-contract-artifacts-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/python-packages/contract_artifacts/.coverage
- save_cache:
key: coverage-python-contract-demo-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/python-packages/contract_demo/.coverage
- save_cache:
key: coverage-python-json-schemas-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/python-packages/json_schemas/.coverage
- save_cache:
key: coverage-python-order-utils-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/python-packages/order_utils/.coverage
- save_cache:
key: coverage-python-sra-client-{{ .Environment.CIRCLE_SHA1 }}
paths:
- ~/repo/python-packages/sra_client/.coverage
- store_artifacts:
path: ~/repo/python-packages/contract_wrappers/src/zero_ex/contract_wrappers/*/__init__.py
- store_artifacts:
path: ~/repo/python-packages/contract_addresses/build
- store_artifacts:
path: ~/repo/python-packages/contract_artifacts/build
- store_artifacts:
path: ~/repo/python-packages/contract_wrappers/build
- store_artifacts:
path: ~/repo/python-packages/json_schemas/build
- store_artifacts:
path: ~/repo/python-packages/middlewares/build
- store_artifacts:
path: ~/repo/python-packages/order_utils/build
- store_artifacts:
path: ~/repo/python-packages/sra_client/build
test-rest-python:
working_directory: ~/repo
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
steps:
- checkout
- restore_cache:
key: installed-py-{{ .Branch }}-{{ .Environment.CIRCLE_SHA1 }}
- run:
command: |
cd python-packages/order_utils
python -m ensurepip
python -m pip install .
- save_cache:
key: installed-py-{{ .Branch }}-{{ .Environment.CIRCLE_SHA1 }}
paths:
- '/usr/local/bin'
- '/usr/local/lib/python3.7/site-packages'
- '.eggs'
- '.mypy_cache'
- '.pytest_cache'
- '.tox'
- run:
command: |
cd python-packages/order_utils
tox
static-tests-python:
working_directory: ~/repo
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
steps:
- checkout
- restore_cache:
key: installed-py-{{ .Branch }}-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- run:
command: |
python -m ensurepip
cd python-packages
./pre_install
./install
./lint
static-tests:
working_directory: ~/repo
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
steps:
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- run: yarn lerna run lint
- run: yarn prettier:ci
- run: yarn deps_versions:ci
- run: yarn diff_md_docs:ci
- run: cd packages/0x.js && yarn build:umd:prod
- run: yarn bundlewatch
submit-coverage:
docker:
- image: nikolaik/python-nodejs:python3.7-nodejs8
working_directory: ~/repo
steps:
- restore_cache:
keys:
- repo-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-abi-gen-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-assert-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-asset-buyer-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-base-contract-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-connect-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-contract-wrappers-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-dev-utils-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-json-schemas-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-order-utils-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-sol-compiler-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-sol-tracing-utils-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-sol-doc-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-subproviders-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-web3-wrapper-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-contracts-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-python-json-schemas-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-python-contract-addresses-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-python-contract-artifacts-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-python-contract-demo-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-python-sra-client-{{ .Environment.CIRCLE_SHA1 }}
- restore_cache:
keys:
- coverage-python-order-utils-{{ .Environment.CIRCLE_SHA1 }}
- run: yarn report_coverage
workflows:
version: 2
main:
jobs:
- build
- build-website:
requires:
- build
- test-contracts-ganache:
requires:
- build
# TODO(albrow): Tests always fail on Geth right now because our fork
# is outdated. Uncomment once we have updated our Geth fork.
# - test-contracts-geth:
# requires:
# - build
- test-rest:
requires:
- build
- static-tests:
requires:
- build
- test-publish:
requires:
- build
- test-doc-generation:
requires:
- build
- submit-coverage:
requires:
- test-rest
- test-python
- static-tests-python:
requires:
- test-python
- test-python:
requires:
- build
# skip python tox run for now, as we don't yet have multiple test environments to support.
#- test-rest-python

4
.gitattributes vendored
View File

@@ -2,3 +2,7 @@
# Automatically collapse generated files in GitHub.
*.svg linguist-generated=true
packages/contract-artifacts/artifacts/*json linguist-generated=true
packages/abi-gen-wrappers/src/generated-wrappers/*.ts linguist-generated=true
packages/contract-wrappers/src/generated-wrappers/*.ts linguist-generated=true

18
.github/CODEOWNERS vendored
View File

@@ -1,18 +0,0 @@
# See https://help.github.com/articles/about-codeowners/
# for more info about CODEOWNERS file
# It uses the same pattern rule for gitignore file
# https://git-scm.com/docs/gitignore#_pattern_format
# Dev tools & setup
.github/ @dekz
packages/contract-addresses/ @dekz @dextracker @kyu-c
packages/contract-artifacts/ @dekz
packages/protocol-utils/ @dekz
# Protocol/smart contracts
contracts/ @dekz @dextracker

View File

@@ -1,91 +0,0 @@
## 0x Contribution Guide
We welcome contributions from anyone on the internet and are grateful for even the smallest contributions. This document will help get you setup to start contributing back to 0x.
### Getting started
1. Fork `0xproject/0x-tools`
2. Clone your fork
3. Follow the [installation & build steps](https://github.com/0xProject/0x-tools#install-dependencies) in the repo's top-level README.
4. Setup the recommended [Development Tooling](#development-tooling).
5. Open a [draft PR](https://github.blog/2019-02-14-introducing-draft-pull-requests/) against the `development` branch and describe the change you are intending to undertake in the PR description. (see [our branch naming conventions](#branch-structure))
Before making the PR "Ready for review", make sure:
- It passes our linter checks (`yarn lint`)
- It is properly formatted with Prettier (`yarn prettier`)
- It passes our continuous integration tests (See: [Enabling code coverage checks on your fork](#fix-submit-coverage-ci-failure) for instructions on getting the `submit-coverage` test to pass on forks)
- You've created/updated the corresponding [CHANGELOG](#CHANGELOGs) entries.
- Your changes have sufficient test coverage (e.g regression tests have been added for bug fixes)
### Branch structure
We have two main branches:
- `master` represents the most recently released (published on npm) version of the codebase.
- `development` represents the current development state of the codebase.
ALL PRs should be opened against `development`.
Branch names should be prefixed with `fix`, `feature` or `refactor`.
- e.g `fix/missing-import`
- If the PR only edits a single package, add it's name too
- e.g `fix/subproviders/missing-import`
### CHANGELOGs
At 0x we use [Semantic Versioning](http://semver.org/) for all our published packages. If a change you make corresponds to a semver bump, you must modify the package's `CHANGELOG.json` file accordingly.
Each CHANGELOG entry that corresponds to a published package will have a `timestamp`. If no entry exists without a `timestamp`, you must first create a new one:
```
{
"version": "1.0.1", <- The updated package version
"changes": [
{
"note": "", <- Describe your change
"PR": 100 <- Your PR number
}
]
},
```
If an entry without a `timestamp` already exists, this means other changes have been introduced by other collaborators since the last publish. Add your changes to the list of notes and adjust the version if your PR introduces a greater semver change (i.e current changes required a patch bump, but your changes require a major version bump).
### Development Tooling
We strongly recommend you use the [VSCode](https://code.visualstudio.com/) text editor since most of our code is written in TypeScript and it offers amazing support for the language.
#### Linter
We use [ESLint](https://eslint.org/docs/latest/) to keep our code-style consistent.
Use `yarn lint` to lint the entire monorepo, and `PKG={PACKAGE_NAME} yarn lint` to lint a specific package.
Integrate it into your text editor:
- VSCode: [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)
- Atom: [ESLint](https://atom.io/packages/eslint)
#### Auto-formatter
We 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:
- VSCode: [prettier-vscode](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
- Atom: [prettier-atom](https://atom.io/packages/prettier-atom)
## Unenforced coding conventions
A few of our coding conventions are not yet enforced by the linter/auto-formatter. Be careful to follow these conventions in your PR's.
1. Unused anonymous function parameters should be named with an underscore + number (e.g \_1, \_2, etc...)
1. There should be a new-line between methods in a class and between test cases.
1. If a string literal has the same value in two or more places, it should be a single constant referenced in both places.
1. Do not import from a project's `index.ts` (e.g import { Token } from '../src';). Always import from the source file itself.
1. Generic error variables should be named `err` instead of `e` or `error`.
1. If you _must_ cast a variable to any - try to type it back as fast as possible. (e.g., `const cw = ((zeroEx as any)._contractWrappers as ContractWrappers);`). This ensures subsequent code is type-safe.
1. Our enum conventions coincide with the recommended TypeScript conventions, using capitalized keys, and all-caps snake-case values. Eg `GetStats = 'GET_STATS'`
1. All public, exported methods/functions/classes must have associated Javadoc-style comments.

View File

@@ -1,2 +1,39 @@
documentation: ['docs']
liquidity integrations: ['contracts/zero-ex/contracts/src/transformers']
python: ['python-packages']
contracts: ['contracts']
@0x/sol-doc: ['packages/sol-doc']
@0x/sol-resolver: ['packages/sol-resolver']
@0x/contracts-gen: ['packages/contracts-gen']
@0x/sra-spec: ['packages/sra-spec']
@0x/subproviders: ['packages/subproviders']
@0x/contract-addresses: ['packages/contract-addresses']
@0x/migrations: ['packages/migrations']
@0x/web3-wrapper: ['packages/web3-wrapper']
@0x/sol-compiler: ['packages/sol-compiler']
@0x/types: ['packages/types']
@0x/instant: ['packages/instant']
@0x/abi-gen-templates: ['packages/abi-gen-templates']
@0x/abi-gen: ['packages/abi-gen']
@0x/website: ['packages/website']
@0x/sol-coverage: ['packages/sol-coverage']
@0x/sol-profiler: ['packages/sol-profiler']
@0x/sol-trace: ['packages/sol-trace']
@0x/sol-tracing-utils: ['packages/sol-tracing-utils']
@0x/utils: ['packages/utils']
@0x/tslint-config: ['packages/tslint-config']
@0x/asset-buyer: ['packages/asset-buyer']
@0x/order-utils: ['packages/order-utils']
@0x/assert: ['packages/assert']
@0x/base-contract: ['packages/base-contract']
@0x/typescript-typings: ['packages/typescript-typings']
0x.js: ['packages/0x.js']
@0x/abi-gen-wrappers: ['packages/abi-gen-wrappers']
@0x/contract-artifacts: ['packages/contract-artifacts']
@0x/dev-utils: ['packages/dev-utils']
@0x/contract-wrappers: ['packages/contract-wrappers']
@0x/json-schemas: ['packages/json-schemas']
@0x/ethereum-types: ['ethereum-types']
@0x/connect: ['packages/connect']
@0x/fill-scenarios: ['packages/fill-scenarios']
@0x/dev-tools-pages: ['packages/dev-tools-pages']
@0x/testnet-faucets: ['packages/testnet-faucets']
@0x/monorepo-scripts: ['packages/monorepo-scripts']

View File

@@ -1,7 +0,0 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: monthly
target-branch: "development"

19
.github/stale.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 30
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 30
# Issues with these labels will never be considered stale
exemptLabels:
- pinned
- security
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: >
This issue has been automatically closed because no activity occured in 7 days after being marked as stale. If it's still relevant - feel free to reopen. Thank you
for your contributions.

View File

@@ -1,137 +0,0 @@
name: Continuous Integration
on:
push:
branches:
- main
- development
pull_request:
jobs:
build:
name: Build and test
runs-on: ubuntu-latest
env:
ARBITRUM_RPC_URL: ${{ secrets.ARBITRUM_RPC_URL }}
AVALANCHE_RPC_URL: ${{ secrets.AVALANCHE_RPC_URL }}
BSC_RPC_URL: ${{ secrets.BSC_RPC_URL }}
FANTOM_RPC_URL: ${{ secrets.FANTOM_RPC_URL }}
MAINNET_RPC_URL: ${{ secrets.MAINNET_RPC_URL }}
OPTIMISM_RPC_URL: ${{ secrets.OPTIMISM_RPC_URL }}
POLYGON_RPC_URL: ${{ secrets.POLYGON_RPC_URL }}
steps:
- uses: actions/checkout@v3
with:
submodules: recursive
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: '16'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Build solution
run: yarn build
- name: Lint typescript
run: yarn lint:ts
- name: Lint solidity
run: yarn lint:contracts
- name: Run prettier
run: yarn prettier:ci
- name: Check dependent packages have consistent versions
run: yarn deps_versions:ci
- name: Check diff in docs
run: yarn diff_md_docs:ci
- name: Check for broken links in markdown files
run: yarn test:links
- name: Test doc generation
run: yarn test:generate_docs:ci
- name: Test @0x/contracts-*
run: |
yarn wsrun \
-p @0x/contracts-multisig \
-p @0x/contracts-utils \
-p @0x/contracts-exchange-libs \
-p @0x/contracts-erc721 \
-p @0x/contracts-erc1155 \
-p @0x/contracts-asset-proxy \
-p @0x/contracts-broker \
-p @0x/contracts-zero-ex \
-m --serial -c test:ci
- name: Test local @0x/contracts-*
run: |
yarn wsrun \
-p @0x/contracts-test-utils \
-p @0x/contract-addresses \
-p @0x/contract-artifacts \
-p @0x/contract-wrappers-test \
-p @0x/order-utils \
-m --serial -c test:ci
- name: Add foundry
uses: foundry-rs/foundry-toolchain@v1
with:
version: nightly
- name: Run Forge build for erc20
working-directory: contracts/erc20
run: |
forge --version
forge build --sizes
- name: Run Forge tests for erc20
working-directory: contracts/erc20
run: |
forge test -vvv --gas-report
- name: Run Forge coverage for erc20
working-directory: contracts/erc20
run: |
forge coverage --report summary --report lcov
- name: Upload the coverage report to Coveralls
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
base-path: ./contracts/erc20/
path-to-lcov: ./contracts/erc20/lcov.info
- name: Run Forge build for zero-ex
working-directory: contracts/zero-ex
run: |
forge --version
forge build --sizes
- name: Run Forge tests for zero-ex
working-directory: contracts/zero-ex
run: |
forge test -vvv --gas-report
- name: Run Forge coverage for zero-ex
working-directory: contracts/zero-ex
run: |
forge coverage --report summary --report lcov
- name: Upload the coverage report to Coveralls
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
base-path: ./contracts/zero-ex/
path-to-lcov: ./contracts/zero-ex/lcov.info
- name: Check coverage threshold
uses: VeryGoodOpenSource/very_good_coverage@v2
with:
path: ./contracts/zero-ex/lcov.info
min_coverage: 6.98
exclude: '**/tests'

View File

@@ -1,53 +0,0 @@
name: publish
on:
workflow_dispatch:
inputs:
ci_status:
description: 'required CI status'
default: 'success'
required: true
prerelease:
description: 'prerelease name'
required: false
jobs:
publish:
runs-on: ubuntu-latest
steps:
- name: 'check successful status'
run: |
REF_STATUS=$(curl -s \
'https://api.github.com/repos/${{ github.repository }}/commits/${{ github.ref }}/status' \
| jq .state)
[[ "${REF_STATUS}" == '"${{ github.event.inputs.ci_status }}"' ]] || \
(echo "::error ::${{ github.ref }} does not have a successful CI status" && false)
- uses: actions/checkout@v2
with:
ref: ${{ github.ref }}
fetch-depth: 0
- uses: actions/setup-node@v1
with:
node-version: 16
- uses: actions/setup-python@v2
- name: 'configure git'
run: |
git config --global user.email "github-actions@github.com"
git config --global user.name "Github Actions"
- name: 'install dependencies'
run: |
yarn -D
- name: 'build and publish'
run: |
echo '//registry.npmjs.org/:_authToken=${NPM_TOKEN}' > .npmrc
npm run run:publish:gha
env:
NPM_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}
GITHUB_TOKEN: ${{ github.token }}
PUBLISH_PRERELEASE: ${{ github.event.inputs.prerelease }}
- name: 'merge into main branch'
if: github.event.inputs.prerelease == '' # unless it's a prerelease
run: |
git checkout main && \
git merge ${{ github.ref }} && \
git push

View File

@@ -1,40 +0,0 @@
name: "Close stale issues and PRs"
on:
schedule:
- cron: "0 8 * * 1-5" # This is in UTC.
# Do a dry-run (debug-only: true) whenever this workflow itself is changed.
pull_request:
paths:
- .github/workflows/stale.yml
types:
- opened
- synchronize
permissions:
issues: write
pull-requests: write
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v7
with:
ascending: true # Spend API operations budget on older, more-likely-to-get-closed issues first
close-issue-message: "" # Leave no comment when closing
close-pr-message: "" # Leave no comment when closing
days-before-issue-stale: 30
days-before-pr-stale: 30
days-before-close: 14
debug-only: ${{ github.event_name == 'pull_request' }} # Dry-run when true.
exempt-issue-labels: bug,enhancement,feature,question
# No actual changes get made in debug-only mode, so we can raise the operations ceiling.
operations-per-run: ${{ github.event_name == 'pull_request' && 100 || 30}}
stale-issue-label: stale
stale-issue-message: "This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions."
stale-pr-label: stale
stale-pr-message: "This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions."
# Time immemorial when in debug-only mode (ie. on pull requests).
# `STALEBOT_START_DATE` otherwise.
# You can use this as a killswitch by setting `STALEBOT_START_DATE` in the far future.
start-date: ${{ github.event_name == 'pull_request' && '1970-01-01T00:00:00Z' || secrets.STALEBOT_START_DATE }} # ISO 8601 or RFC 2822

95
.gitignore vendored
View File

@@ -15,6 +15,9 @@ pids
*.db
*.sqlite
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
@@ -72,38 +75,84 @@ generated_docs/
TODO.md
# IDE file
# VSCode file
.vscode
.idea
*~
.\#*
\#*\#
packages/website/public/bundle*
packages/dev-tools-pages/public/bundle*
# server cli
packages/testnet-faucets/server/
# generated contract artifacts/
generated-artifacts/
contracts/coordinator/generated-artifacts/
contracts/exchange/generated-artifacts/
contracts/asset-proxy/generated-artifacts/
contracts/multisig/generated-artifacts/
contracts/utils/generated-artifacts/
contracts/exchange-libs/generated-artifacts/
contracts/erc20/generated-artifacts/
contracts/erc721/generated-artifacts/
contracts/erc1155/generated-artifacts/
contracts/extensions/generated-artifacts/
contracts/exchange-forwarder/generated-artifacts/
contracts/dev-utils/generated-artifacts/
packages/sol-tracing-utils/test/fixtures/artifacts/
python-packages/contract_artifacts/src/zero_ex/contract_artifacts/artifacts/
# generated contract wrappers
generated-wrappers/
packages/python-contract-wrappers/generated/
contracts/coordinator/generated-wrappers/
contracts/exchange/generated-wrappers/
contracts/asset-proxy/generated-wrappers/
contracts/multisig/generated-wrappers/
contracts/utils/generated-wrappers/
contracts/exchange-libs/generated-wrappers/
contracts/erc20/generated-wrappers/
contracts/erc721/generated-wrappers/
contracts/erc1155/generated-wrappers/
contracts/extensions/generated-wrappers/
contracts/exchange-forwarder/generated-wrappers/
contracts/dev-utils/generated-wrappers/
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc20_token/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/asset_proxy_owner/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/coordinator/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/coordinator_registry/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dummy_erc20_token/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dummy_erc721_token/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/dutch_auction/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc20_proxy/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc721_proxy/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/erc721_token/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/eth_balance_checker/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/forwarder/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/i_asset_proxy/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/i_validator/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/i_wallet/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/multi_asset_proxy/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/order_validator/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/weth9/__init__.py
python-packages/contract_wrappers/src/zero_ex/contract_wrappers/zrx_token/__init__.py
# forge std-lib
contracts/zero-ex/contracts/deps/forge-std
# solc-bin in sol-compiler
packages/sol-compiler/solc_bin/
# foundry artifacts
foundry-artifacts/
# python stuff
.eggs
.mypy_cache
.tox
python-packages/*/build
python-packages/*/dist
__pycache__
python-packages/*/src/*.egg-info
python-packages/*/.coverage
# foundry cache
cache/
#foundry output artifacts
out/
# typechain wrappers
contracts/zero-ex/typechain-wrappers/
# python keeps package-local copies of json schemas
python-packages/json_schemas/src/zero_ex/json_schemas/schemas
# Doc README copy
packages/*/docs/README.md
.DS_Store
# the snapshot that gets built for migrations sure does have a ton of files
packages/migrations/0x_ganache_snapshot*
# Tool MDX files authoritatively live on S3
packages/website/mdx/tools/*

6
.gitmodules vendored
View File

@@ -1,6 +0,0 @@
[submodule "contracts/zero-ex/contracts/deps/forge-std"]
path = contracts/zero-ex/contracts/deps/forge-std
url = https://github.com/foundry-rs/forge-std
[submodule "contracts/erc20/lib/forge-std"]
path = contracts/erc20/lib/forge-std
url = https://github.com/foundry-rs/forge-std

View File

@@ -1,4 +0,0 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged --no-stash

View File

@@ -1,10 +1,42 @@
lib
deps
.nyc_output
generated-artifacts/
generated-wrappers/
foundry-artifacts/
out/
cache/
/contracts/coordinator/generated-wrappers
/contracts/coordinator/generated-artifacts
/contracts/exchange/generated-wrappers
/contracts/exchange/generated-artifacts
/contracts/asset-proxy/generated-wrappers
/contracts/asset-proxy/generated-artifacts
/contracts/multisig/generated-wrappers
/contracts/multisig/generated-artifacts
/contracts/utils/generated-wrappers
/contracts/utils/generated-artifacts
/contracts/exchange-libs/generated-wrappers
/contracts/exchange-libs/generated-artifacts
/contracts/erc20/generated-wrappers
/contracts/erc20/generated-artifacts
/contracts/erc721/generated-wrappers
/contracts/erc721/generated-artifacts
/contracts/erc1155/generated-wrappers
/contracts/erc1155/generated-artifacts
/contracts/extensions/generated-wrappers
/contracts/extensions/generated-artifacts
/contracts/exchange-forwarder/generated-wrappers
/contracts/exchange-forwarder/generated-artifacts
/contracts/dev-utils/generated-wrappers
/contracts/dev-utils/generated-artifacts
/packages/abi-gen/test-cli/output
/packages/json-schemas/schemas
/python-packages/json_schemas/src/zero_ex/json_schemas/schemas
/packages/sra-spec/public/
/packages/dev-tools-pages/ts/**/data.json
package.json
packages
scripts/postpublish_utils.js
packages/sol-coverage/test/fixtures/artifacts
.pytest_cache
.mypy_cache
.tox
packages/abi-gen/test-cli/fixtures/artifacts/AbiGenDummy.json
packages/abi-gen/test-cli/fixtures/artifacts/LibDummy.json
packages/abi-gen/test-cli/fixtures/artifacts/TestLibDummy.json
packages/*/docs
packages/website/mdx/tools

View File

@@ -1,20 +1,6 @@
{
"printWidth": 120,
"tabWidth": 4,
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": true,
"arrowParens": "avoid",
"overrides": [
{
"files": "**/*.sol",
"options": {
"printWidth": 120,
"tabWidth": 4,
"useTabs": false,
"singleQuote": false,
"bracketSpacing": false
}
}
]
"printWidth": 120,
"trailingComma": all,
"singleQuote": true
}

View File

@@ -1,23 +0,0 @@
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Build documentation in the docs/ directory with Sphinx
sphinx:
configuration: docs/conf.py
# Build documentation with MkDocs
#mkdocs:
# configuration: mkdocs.yml
# Optionally build your docs in additional formats such as PDF
#formats:
# - pdf
# Optionally set the version of Python and requirements required to build your docs
python:
version: 3.7
install:
- requirements: docs/requirements.txt

View File

@@ -1,17 +0,0 @@
{
"extends": "solhint:recommended",
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error",
"avoid-low-level-calls": "off",
"avoid-tx-origin": "warn",
"code-complexity": "off",
"const-name-snakecase": "error",
"function-max-lines": ["error", 350],
"max-line-length": ["error", 120],
"no-inline-assembly": "off",
"quotes": ["error", "double"],
"no-empty-blocks": "off",
"compiler-version": "off"
}
}

View File

@@ -1,9 +0,0 @@
contracts/erc20/src/ZRXToken.sol
node_modules/
lib
deps
generated-artifacts/
generated-wrappers/
foundry-artifacts/
out/
cache/

39
CODEOWNERS Normal file
View File

@@ -0,0 +1,39 @@
# See https://help.github.com/articles/about-codeowners/
# for more info about CODEOWNERS file
# It uses the same pattern rule for gitignore file
# https://git-scm.com/docs/gitignore#_pattern_format
# Website
packages/asset-buyer/ @BMillman19 @fragosti @steveklebanoff
packages/instant/ @BMillman19 @fragosti @steveklebanoff
packages/website/ @BMillman19 @fragosti @fabioberger @steveklebanoff
# Dev tools & setup
.circleci/ @LogvinovLeon
packages/abi-gen/ @feuGeneA
packages/base-contract/ @xianny
packages/connect/ @fragosti
packages/abi-gen-templates/ @feuGeneA @xianny
packages/contract-addresses/ @albrow
packages/contract-artifacts/ @albrow
packages/dev-utils/ @LogvinovLeon @fabioberger
packages/devnet/ @albrow
packages/ethereum-types/ @LogvinovLeon
packages/monorepo-scripts/ @fabioberger
packages/order-utils/ @fabioberger @LogvinovLeon
packages/python-contract-wrappers/ @feuGeneA
packages/sol-compiler/ @LogvinovLeon
packages/sol-coverage/ @LogvinovLeon
packages/sol-profiler/ @LogvinovLeon
packages/sol-trace/ @LogvinovLeon
packages/sol-tracing-utils/ @LogvinovLeon
packages/sol-resolver/ @LogvinovLeon
packages/subproviders/ @fabioberger @dekz
packages/verdaccio/ @albrow
packages/web3-wrapper/ @LogvinovLeon @fabioberger
python-packages/ @feuGeneA
packages/utils/ @hysz
# Protocol/smart contracts
contracts/ @abandeali1 @hysz

105
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,105 @@
## 0x Contribution Guide
We welcome contributions from anyone on the internet and are grateful for even the smallest contributions. This document will help get you setup to start contributing back to 0x.
### Getting started
1. Fork `0xproject/0x-monorepo`
2. Clone your fork
3. Follow the [installation & build steps](https://github.com/0xProject/0x-monorepo#install-dependencies) in the repo's top-level README.
4. Setup the recommended [Development Tooling](#development-tooling).
5. Open a PR with the `[WIP]` flag against the `development` branch and describe the change you are intending to undertake in the PR description. (see [our branch naming conventions](#branch-structure))
Before removing the `[WIP]` tag and submitting the PR for review, make sure:
- It passes our linter checks (`yarn lint`)
- It is properly formatted with Prettier (`yarn prettier`)
- It passes our continuous integration tests (See: [Enabling code coverage checks on your fork](#enabling-code-coverage-checks-on-your-fork) for instructions on getting the `submit-coverage` test to pass on forks)
- You've created/updated the corresponding [CHANGELOG](#CHANGELOGs) entries.
- Your changes have sufficient test coverage (e.g regression tests have been added for bug fixes)
### Branch structure
We have two main branches:
- `master` represents the most recently released (published on npm) version of the codebase.
- `development` represents the current development state of the codebase.
ALL PRs should be opened against `development`.
Branch names should be prefixed with `fix`, `feature` or `refactor`.
- e.g `fix/broken-wiki-link`
- If the PR only edits a single package, add it's name too
- e.g `fix/website/broken-wiki-link`
### CHANGELOGs
At 0x we use [Semantic Versioning](http://semver.org/) for all our published packages. If a change you make corresponds to a semver bump, you must modify the package's `CHANGELOG.json` file accordingly.
Each CHANGELOG entry that corresponds to a published package will have a `timestamp`. If no entry exists without a `timestamp`, you must first create a new one:
```
{
"version": "1.0.1", <- The updated package version
"changes": [
{
"note": "", <- Describe your change
"PR": 100 <- Your PR number
}
]
},
```
If an entry without a `timestamp` already exists, this means other changes have been introduced by other collaborators since the last publish. Add your changes to the list of notes and adjust the version if your PR introduces a greater semver change (i.e current changes required a patch bump, but your changes require a major version bump).
### Development Tooling
We strongly recommend you use the [VSCode](https://code.visualstudio.com/) text editor since most of our code is written in TypeScript and it offers amazing support for the language.
#### Linter
We use [TSLint](https://palantir.github.io/tslint/) with [custom configs](https://github.com/0xProject/0x-monorepo/tree/development/packages/tslint-config) to keep our code-style consistent.
Use `yarn:lint` to lint the entire monorepo, and `PKG={PACKAGE_NAME} yarn lint` to lint a specific package.
If you want to change a rule, or add a custom rule, please make these changes to our [tslint-config](https://github.com/0xProject/0x-monorepo/tree/development/packages/tslint-config) package. All other packages have it as a dependency.
Integrate it into your text editor:
- VSCode: [vscode-tslint](https://marketplace.visualstudio.com/items?itemName=eg2.tslint)
- Atom: [linter-tslint](https://atom.io/packages/linter-tslint)
#### Auto-formatter
We 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:
- VSCode: [prettier-vscode](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
- Atom: [prettier-atom](https://atom.io/packages/prettier-atom)
## Unenforced coding conventions
A few of our coding conventions are not yet enforced by the linter/auto-formatter. Be careful to follow these conventions in your PR's.
1. Unused anonymous function parameters should be named with an underscore + number (e.g \_1, \_2, etc...)
1. There should be a new-line between methods in a class and between test cases.
1. If a string literal has the same value in two or more places, it should be a single constant referenced in both places.
1. Do not import from a project's `index.ts` (e.g import { Token } from '../src';). Always import from the source file itself.
1. Generic error variables should be named `err` instead of `e` or `error`.
1. If you _must_ cast a variable to any - try to type it back as fast as possible. (e.g., `const cw = ((zeroEx as any)._contractWrappers as ContractWrappers);`). This ensures subsequent code is type-safe.
1. Our enum conventions coincide with the recommended TypeScript conventions, using capitalized keys, and all-caps snake-case values. Eg `GetStats = 'GET_STATS'`
1. All public, exported methods/functions/classes must have associated Javadoc-style comments.
### Fix `submit-coverage` CI failure
If you simply fork the repo and then create a PR from it, your PR will fail the `submit-coverage` check on CI. This is because the 0x CircleCI configuration sets the `COVERALLS_REPO_TOKEN` environment variable to the token for `0xProject/0x-monorepo`, but when running the check against your fork the token needs to match your repo's name `your-username/0x-monorepo`.
To facilitate this check, after creating your fork, but before creating the branch for your PR, do the following:
1. Log in to [coveralls.io](https://coveralls.io/), go to `Add Repos`, and enable your fork. Then go to the settings for that repo, and copy the `Repo Token` identifier.
2. Log in to [CircleCI](https://circleci.com/login), go to `Add Projects`, click the `Set Up Project` button corresponding to your fork, and then click `Start Building`. (Aside from step 3 below, no actual set up is needed, since it will use the `.circleci/config.yml` file in 0x-monorepo, so you can ignore all of the instruction/explanation given on the page with the `Start Building` button.)
3. In CircleCI, configure your project to add an environment variable, with name `COVERALLS_REPO_TOKEN`, and for the value paste in the `Repo Token` you copied in step 1.
Now, when you push to your branch, CircleCI will automatically run all of the checks in your own instance, and the coverage check will work since it has the proper `Repo Token`, and the PR will magically refer to your own checks rather than running them in the 0x CircleCI instance.

View File

@@ -2,13 +2,15 @@
<!--- Before submitting please check to see if this issue was already reported -->
<!--- Prefix your issue title with the package name it relates to (e.g., `0x.js: ` or `general:`) -->
## Expected Behavior
<!--- If you're describing a bug, tell us what should happen -->
<!--- If you're suggesting a package change/improvement, tell us how it should work -->
<!--- If you're suggesting a contract or protocol change/improvement, visit our ZEIPs repo https://github.com/0xProject/ZEIPs -->
<!--- If you're suggesting a contract or protocol change/improvement, visit our ZEIPs repo -->
## Current Behavior
@@ -47,9 +49,10 @@
| Package | Version |
| ------: | :------ |
<!-- For example:
| `protocol-utils` | 2.0.4 |
| `Exchange Contract` | v3 |
| `0x.js` | 2.0.4 |
| `Exchange Contract` | v2 |
-->
| Network |
@@ -58,6 +61,6 @@
<!-- For example:
| mainnet |
| goerli |
| development |
| kovan |
| testrpc |
-->

View File

@@ -1,4 +1,4 @@
Copyright 2020 ZeroEx Labs
Copyright 2017 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

View File

@@ -20,6 +20,7 @@
<!--- The following points should be used to indicate the progress of your PR. Put an `x` in all the boxes that apply right now, and come back over time and check them off as you make progress. If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
- [ ] Prefix PR title with `[WIP]` if necessary.
- [ ] Add tests to cover changes as needed.
- [ ] Update documentation as needed.
- [ ] Add new entries to the relevant CHANGELOG.jsons.

110
README.md
View File

@@ -2,41 +2,105 @@
---
[0x][website-url] is an open protocol that facilitates trustless, low friction exchange of Ethereum-based assets. For more information on how it works, check out the [0x protocol specification](https://protocol.0x.org/).
[0x][website-url] is an open protocol that facilitates trustless, low friction exchange of Ethereum-based assets. For more information on how it works, check out the [0x protocol specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md).
This repository is a monorepo including the 0x protocol smart contracts and numerous developer tools. Each public sub-package is independently published to NPM.
[website-url]: https://0x.org
[![Coverage Status](https://coveralls.io/repos/github/0xProject/protocol/badge.svg?branch=development)](https://coveralls.io/github/0xProject/protocol?branch=development)
[![CircleCI](https://circleci.com/gh/0xProject/0x-monorepo.svg?style=svg&circle-token=61bf7cd8c9b4e11b132089dfcffdd1be277d1e0c)](https://circleci.com/gh/0xProject/0x-monorepo)
[![Coverage Status](https://coveralls.io/repos/github/0xProject/0x-monorepo/badge.svg?branch=development)](https://coveralls.io/github/0xProject/0x-monorepo?branch=development)
[![Discord](https://img.shields.io/badge/chat-discord.chat-yellow.svg?style=flat)](https://discordapp.com/invite/d3FTX3M)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
## Packages
Visit our [developer portal](https://0x.org/docs/) for a comprehensive list of core & community maintained packages. All packages maintained with this monorepo are listed below.
Visit our [developer portal](https://0x.org/docs/tools/order-utils) for a comprehensive list of core & community maintained packages. All packages maintained with this monorepo are listed below.
### Python Packages
| Package | Version | Description |
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| [`0x-contract-addresses`](/python-packages/contract_addresses) | [![PyPI](https://img.shields.io/pypi/v/0x-contract-addresses.svg)](https://pypi.org/project/0x-contract-addresses/) | A tiny utility library for getting known deployed contract addresses for a particular network |
| [`0x-contract-artifacts`](/python-packages/contract_artifacts) | [![PyPI](https://img.shields.io/pypi/v/0x-contract-artifacts.svg)](https://pypi.org/project/0x-contract-artifacts/) | 0x smart contract compilation artifacts |
| [`0x-contract-wrappers`](/python-packages/contract_wrappers) | [![PyPI](https://img.shields.io/pypi/v/0x-contract-wrappers.svg)](https://pypi.org/project/0x-contract-wrappers/) | 0x smart contract wrappers |
| [`0x-json-schemas`](/python-packages/json_schemas) | [![PyPI](https://img.shields.io/pypi/v/0x-json-schemas.svg)](https://pypi.org/project/0x-json-schemas/) | 0x-related JSON schemas |
| [`0x-order-utils`](/python-packages/order_utils) | [![PyPI](https://img.shields.io/pypi/v/0x-order-utils.svg)](https://pypi.org/project/0x-order-utils/) | A set of utilities for generating, parsing, signing and validating 0x orders |
| [`0x-sra-client`](/python-packages/sra_client) | [![PyPI](https://img.shields.io/pypi/v/0x-sra-client.svg)](https://pypi.org/project/0x-sra-client/) | A Python client for interacting with servers conforming to the Standard Relayer API specification |
### Solidity Packages
These packages are all under development. See [/contracts/README.md](/contracts/README.md) for a list of deployed packages.
| Package | Version | Description |
| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| [`@0x/contracts-zero-ex`](/contracts/zero-ex) | [![npm](https://img.shields.io/npm/v/@0x/contracts-zero-ex.svg)](https://www.npmjs.com/package/@0x/contracts-zero-ex) | The contracts used for settling trades within the protocol |
| [`@0x/contracts-erc20`](/contracts/erc20) | [![npm](https://img.shields.io/npm/v/@0x/contracts-erc20.svg)](https://www.npmjs.com/package/@0x/contracts-erc20) | Implementations of various ERC20 tokens |
| [`@0x/contracts-test-utils`](/contracts/test-utils) | [![npm](https://img.shields.io/npm/v/@0x/contracts-test-utils.svg)](https://www.npmjs.com/package/@0x/contracts-test-utils) | TypeScript/Javascript shared utilities used for testing contracts |
| [`@0x/contracts-utils`](/contracts/utils) | [![npm](https://img.shields.io/npm/v/@0x/contracts-utils.svg)](https://www.npmjs.com/package/@0x/contracts-utils) | Generic libraries and utilities used throughout all of the contracts |
| Package | Version | Description |
| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`@0x/contracts-asset-proxy`](/contracts/asset-proxy) | [![npm](https://img.shields.io/npm/v/@0x/contracts-asset-proxy.svg)](https://www.npmjs.com/package/@0x/contracts-asset-proxy) | [`AssetProxy`](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#assetproxy) contracts used within the protocol |
| [`@0x/contracts-erc20`](/contracts/erc20) | [![npm](https://img.shields.io/npm/v/@0x/contracts-erc20.svg)](https://www.npmjs.com/package/@0x/contracts-erc20) | Implementations of various ERC20 tokens |
| [`@0x/contracts-erc721`](/contracts/erc721) | [![npm](https://img.shields.io/npm/v/@0x/contracts-erc721.svg)](https://www.npmjs.com/package/@0x/contracts-erc721) | Implementations of various ERC721 tokens |
| [`@0x/contracts-erc1155`](/contracts/erc1155) | [![npm](https://img.shields.io/npm/v/@0x/contracts-erc1155.svg)](https://www.npmjs.com/package/@0x/contracts-erc1155) | Implementations of various ERC1155 tokens |
| [`@0x/contracts-exchange`](/contracts/exchange) | [![npm](https://img.shields.io/npm/v/@0x/contracts-exchange.svg)](https://www.npmjs.com/package/@0x/contracts-exchange) | The [`Exchange`](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#exchange) contract used for settling trades within the protocol |
| [`@0x/contracts-exchange-forwarder`](/contracts/exchange-forwarder) | [![npm](https://img.shields.io/npm/v/@0x/contracts-exchange-forwarder.svg)](https://www.npmjs.com/package/@0x/contracts-exchange-forwarder) | A [`Forwarder`](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/forwarder-specification.md) contract used to simplify UX for interacting with the protocol |
| [`@0x/contracts-exchange-libs`](/contracts/exchange-libs) | [![npm](https://img.shields.io/npm/v/@0x/contracts-exchange-libs.svg)](https://www.npmjs.com/package/@0x/contracts-exchange-libs) | Protocol specific libraries used within the [`Exchange`](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#exchange) contract |
| [`@0x/contracts-extensions`](/contracts/extensions) | [![npm](https://img.shields.io/npm/v/@0x/contracts-extensions.svg)](https://www.npmjs.com/package/@0x/contracts-extensions) | Contracts that interact with and extend the functionality of the core protocol |
| [`@0x/contracts-multisig`](/contracts/multisig) | [![npm](https://img.shields.io/npm/v/@0x/contracts-multisig.svg)](https://www.npmjs.com/package/@0x/contracts-multisig) | Various implementations of multisignature wallets, including the [`AssetProxyOwner`](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#assetproxyowner) contract that has permissions to upgrade the protocol |
| [`@0x/contracts-test-utils`](/contracts/test-utils) | [![npm](https://img.shields.io/npm/v/@0x/contracts-test-utils.svg)](https://www.npmjs.com/package/@0x/contracts-test-utils) | TypeScript/Javascript shared utilities used for testing contracts |
| [`@0x/contracts-utils`](/contracts/utils) | [![npm](https://img.shields.io/npm/v/@0x/contracts-utils.svg)](https://www.npmjs.com/package/@0x/contracts-utils) | Generic libraries and utilities used throughout all of the contracts |
| [`@0x/contracts-coordinator`](/contracts/coordinator) | [![npm](https://img.shields.io/npm/v/@0x/contracts-coordinator.svg)](https://www.npmjs.com/package/@0x/contracts-coordinator) | A contract that allows users to execute 0x transactions with permission from a Coordinator |
| [`@0x/contracts-dev-utils`](/contracts/dev-utils) | [![npm](https://img.shields.io/npm/v/@0x/contracts-dev-utils.svg)](https://www.npmjs.com/package/@0x/contracts-dev-utils) | A contract contains utility functions for developers (such as validating many orders using a single eth_call) |
### TypeScript/Javascript Packages
#### 0x-specific packages
| Package | Version | Description |
| -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| [`@0x/protocol-utils`](/packages/protocol-utils) | [![npm](https://img.shields.io/npm/v/@0x/protocol-utils.svg)](https://www.npmjs.com/package/@0x/protocol-utils) | A set of utilities for generating, parsing, signing and validating 0x orders |
| [`@0x/contract-addresses`](/packages/contract-addresses) | [![npm](https://img.shields.io/npm/v/@0x/contract-addresses.svg)](https://www.npmjs.com/package/@0x/contract-addresses) | A tiny utility library for getting known deployed contract addresses for a particular network. |
| [`@0x/contract-wrappers`](/packages/contract-wrappers) | [![npm](https://img.shields.io/npm/v/@0x/contract-wrappers.svg)](https://www.npmjs.com/package/@0x/contract-wrappers) | JS/TS wrappers for interacting with the 0x smart contracts |
| [`@0x/contract-artifacts`](/packages/contract-artifacts) | [![npm](https://img.shields.io/npm/v/@0x/contract-artifacts.svg)](https://www.npmjs.com/package/@0x/contract-artifacts) | 0x smart contract compilation artifacts | |
| Package | Version | Description |
| -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| [`0x.js`](/packages/0x.js) | [![npm](https://img.shields.io/npm/v/0x.js.svg)](https://www.npmjs.com/package/0x.js) | An aggregate package combining many smaller utility packages for interacting with the 0x protocol |
| [`@0x/contract-addresses`](/packages/contract-addresses) | [![npm](https://img.shields.io/npm/v/@0x/contract-addresses.svg)](https://www.npmjs.com/package/@0x/contract-addresses) | A tiny utility library for getting known deployed contract addresses for a particular network. |
| [`@0x/contract-wrappers`](/packages/contract-wrappers) | [![npm](https://img.shields.io/npm/v/@0x/contract-wrappers.svg)](https://www.npmjs.com/package/@0x/contract-wrappers) | JS/TS wrappers for interacting with the 0x smart contracts |
| [`@0x/order-utils`](/packages/order-utils) | [![npm](https://img.shields.io/npm/v/@0x/order-utils.svg)](https://www.npmjs.com/package/@0x/order-utils) | A set of utilities for generating, parsing, signing and validating 0x orders |
| [`@0x/json-schemas`](/packages/json-schemas) | [![npm](https://img.shields.io/npm/v/@0x/json-schemas.svg)](https://www.npmjs.com/package/@0x/json-schemas) | 0x-related JSON schemas | |
| [`@0x/migrations`](/packages/migrations) | [![npm](https://img.shields.io/npm/v/@0x/migrations.svg)](https://www.npmjs.com/package/@0x/migrations) | Migration tool for deploying 0x smart contracts on private testnets |
| [`@0x/contract-artifacts`](/packages/contract-artifacts) | [![npm](https://img.shields.io/npm/v/@0x/contract-artifacts.svg)](https://www.npmjs.com/package/@0x/contract-artifacts) | 0x smart contract compilation artifacts |
| [`@0x/abi-gen-wrappers`](/packages/abi-gen-wrappers) | [![npm](https://img.shields.io/npm/v/@0x/abi-gen-wrappers.svg)](https://www.npmjs.com/package/@0x/abi-gen-wrappers) | Low-level 0x smart contract wrappers generated using `@0x/abi-gen` |
| [`@0x/sra-spec`](/packages/sra-spec) | [![npm](https://img.shields.io/npm/v/@0x/sra-spec.svg)](https://www.npmjs.com/package/@0x/sra-spec) | OpenAPI specification for the Standard Relayer API |
| [`@0x/connect`](/packages/connect) | [![npm](https://img.shields.io/npm/v/@0x/connect.svg)](https://www.npmjs.com/package/@0x/connect) | An HTTP/WS client for interacting with the Standard Relayer API |
| [`@0x/asset-buyer`](/packages/asset-buyer) | [![npm](https://img.shields.io/npm/v/@0x/asset-buyer.svg)](https://www.npmjs.com/package/@0x/asset-buyer) | Convenience package for discovering and buying assets with Ether |
| [`@0x/asset-swapper`](/packages/asset-swapper) | [![npm](https://img.shields.io/npm/v/@0x/asset-swapper.svg)](https://www.npmjs.com/package/@0x/asset-swapper) | Convenience package for discovering and performing swaps for any ERC20 Assets |
#### Ethereum tooling
| Package | Version | Description |
| -------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`@0x/web3-wrapper`](/packages/web3-wrapper) | [![npm](https://img.shields.io/npm/v/@0x/web3-wrapper.svg)](https://www.npmjs.com/package/@0x/web3-wrapper) | An Ethereum JSON RPC client |
| [`@0x/sol-compiler`](/packages/sol-compiler) | [![npm](https://img.shields.io/npm/v/@0x/sol-compiler.svg)](https://www.npmjs.com/package/@0x/sol-compiler) | A wrapper around solc-js that adds smart re-compilation, ability to compile an entire project, Solidity version specific compilation, standard input description support and much more. |
| [`@0x/sol-coverage`](/packages/sol-coverage) | [![npm](https://img.shields.io/npm/v/@0x/sol-coverage.svg)](https://www.npmjs.com/package/@0x/sol-coverage) | A solidity test coverage tool |
| [`@0x/sol-profiler`](/packages/sol-profiler) | [![npm](https://img.shields.io/npm/v/@0x/sol-profiler.svg)](https://www.npmjs.com/package/@0x/sol-profiler) | A solidity gas cost profiler |
| [`@0x/sol-trace`](/packages/sol-trace) | [![npm](https://img.shields.io/npm/v/@0x/sol-trace.svg)](https://www.npmjs.com/package/@0x/sol-trace) | A solidity stack trace tool |
| [`@0x/sol-resolver`](/packages/sol-resolver) | [![npm](https://img.shields.io/npm/v/@0x/sol-resolver.svg)](https://www.npmjs.com/package/@0x/sol-resolver) | Import resolver for smart contracts dependencies |
| [`@0x/subproviders`](/packages/subproviders) | [![npm](https://img.shields.io/npm/v/@0x/subproviders.svg)](https://www.npmjs.com/package/@0x/subproviders) | Web3 provider middlewares (e.g. LedgerSubprovider) |
| [`@0x/sol-doc`](/packages/sol-doc) | [![npm](https://img.shields.io/npm/v/@0x/sol-doc.svg)](https://www.npmjs.com/package/@0x/sol-doc) | Solidity documentation generator |
#### Utilities
| Package | Version | Description |
| -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| [`@0x/abi-gen`](/packages/abi-gen) | [![npm](https://img.shields.io/npm/v/@0x/abi-gen.svg)](https://www.npmjs.com/package/@0x/abi-gen) | Tool to generate TS wrappers from smart contract ABIs |
| [`@0x/tslint-config`](/packages/tslint-config) | [![npm](https://img.shields.io/npm/v/@0x/tslint-config.svg)](https://www.npmjs.com/package/@0x/tslint-config) | Custom TSLint rules used by the 0x core team |
| [`@0x/types`](/packages/types) | [![npm](https://img.shields.io/npm/v/@0x/types.svg)](https://www.npmjs.com/package/@0x/types) | Shared type declarations |
| [`@0x/typescript-typings`](/packages/typescript-typings) | [![npm](https://img.shields.io/npm/v/@0x/typescript-typings.svg)](https://www.npmjs.com/package/@0x/typescript-typings) | Repository of types for external packages |
| [`@0x/utils`](/packages/utils) | [![npm](https://img.shields.io/npm/v/@0x/utils.svg)](https://www.npmjs.com/package/@0x/utils) | Shared utilities |
| [`@0x/assert`](/packages/assert) | [![npm](https://img.shields.io/npm/v/@0x/assert.svg)](https://www.npmjs.com/package/@0x/assert) | Type and schema assertions used by our packages |
| [`@0x/base-contract`](/packages/base-contract) | [![npm](https://img.shields.io/npm/v/@0x/base-contract.svg)](https://www.npmjs.com/package/@0x/base-contract) | BaseContract used by auto-generated `abi-gen` wrapper contracts |
| [`@0x/dev-utils`](/packages/dev-utils) | [![npm](https://img.shields.io/npm/v/@0x/dev-utils.svg)](https://www.npmjs.com/package/@0x/dev-utils) | Dev utils to be shared across 0x packages |
| [`@0x/fill-scenarios`](/packages/fill-scenarios) | [![npm](https://img.shields.io/npm/v/@0x/fill-scenarios.svg)](https://www.npmjs.com/package/@0x/fill-scenarios) | 0x order fill scenario generator |
#### Private Packages
| Package | Description |
| -------------------------------------------------- | -------------------------------------------------------------------------------- |
| [`@0x/instant`](/packages/instant) | A free and flexible way to offer simple crypto purchasing in any app or website. |
| [`@0x/testnet-faucets`](/packages/testnet-faucets) | A faucet micro-service that dispenses test ERC20 tokens or Ether |
| [`@0x/website`](/packages/website) | 0x website |
## Usage
@@ -53,7 +117,7 @@ You can include those by prepending the `@0x/typescript-typings` package to your
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.
#### Read our [contribution guidelines](.github/CONTRIBUTING.md).
#### Read our [contribution guidelines](./CONTRIBUTING.md).
### Install dependencies
@@ -69,6 +133,8 @@ Then install dependencies
yarn install
```
You will also need to have Python 3 installed, in order to build and run the tests of `abi-gen`'s command-line interface, which is integrated with the yarn build, yarn test, and yarn lint commands described below. More specifically, your local pip should resolve to the Python 3 version of pip, not a Python 2.x version.
### Build
To build all packages:
@@ -80,7 +146,7 @@ yarn build
To build a specific package:
```bash
PKG=@0x/protocol-utils yarn build
PKG=@0x/web3-wrapper yarn build
```
To build all contracts packages:
@@ -103,7 +169,7 @@ To watch a specific package and all it's dependent packages:
PKG=[NPM_PACKAGE_NAME] yarn watch
e.g
PKG=@0x/protocol-utils yarn watch
PKG=@0x/web3-wrapper yarn watch
```
### Clean
@@ -117,7 +183,7 @@ yarn clean
Clean a specific package
```bash
PKG=@0x/protocol-utils yarn clean
PKG=0x.js yarn clean
```
### Rebuild
@@ -131,7 +197,7 @@ yarn rebuild
To re-build (clean & build) a specific package & it's deps:
```bash
PKG=@0x/protocol-utils yarn rebuild
PKG=0x.js yarn rebuild
```
### Lint
@@ -145,7 +211,7 @@ yarn lint
Lint a specific package:
```bash
PKG=@0x/protocol-utils yarn lint
PKG=0x.js yarn lint
```
### Run Tests
@@ -159,7 +225,7 @@ yarn test
Run a specific package's test:
```bash
PKG=@0x/protocol-utils yarn test
PKG=@0x/web3-wrapper yarn test
```
Run all contracts packages tests:

21
contracts/.solhint.json Normal file
View File

@@ -0,0 +1,21 @@
{
"extends": "default",
"rules": {
"avoid-low-level-calls": false,
"avoid-tx-origin": "warn",
"bracket-align": false,
"code-complexity": false,
"compiler-fixed": false,
"const-name-snakecase": "error",
"expression-indent": "error",
"function-max-lines": false,
"func-order": "error",
"indent": ["error", 4],
"max-line-length": ["warn", 160],
"no-inline-assembly": false,
"quotes": ["error", "double"],
"separate-by-one-line-in-contract": "error",
"space-after-comma": "error",
"statement-indent": "error"
}
}

View File

@@ -1,3 +1,16 @@
#### Deployed Contract Packages
| Contract | Package | Version | Git Tag |
| --------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| AssetProxyOwner | [`@0x/contracts-multisig`](/contracts/multisig) | [v1.0.2](https://www.npmjs.com/package/@0x/contracts-multisig/v/1.0.2) | [@0x/contracts-multisig@1.0.2](https://github.com/0xProject/0x-monorepo/releases/tag/@0x/contracts-multisig@1.0.2) |
| ERC20Proxy | [`@0x/contracts-asset-proxy`](/contracts/asset-proxy) | [v1.0.1](https://www.npmjs.com/package/@0x/contracts-asset-proxy/v/1.0.1) | [@0x/contracts-asset-proxy@1.0.1](https://github.com/0xProject/0x-monorepo/releases/tag/@0x/contracts-asset-proxy@1.0.1) |
| ERC721Proxy | [`@0x/contracts-asset-proxy`](/contracts/asset-proxy) | [v1.0.1](https://www.npmjs.com/package/@0x/contracts-asset-proxy/v/1.0.1) | [@0x/contracts-asset-proxy@1.0.1](https://github.com/0xProject/0x-monorepo/releases/tag/@0x/contracts-asset-proxy@1.0.1) |
| Exchange | [`@0x/contracts-exchange`](/contracts/exchange) | [v1.0.1](https://www.npmjs.com/package/@0x/contracts-exchange/v/1.0.1) | [@0x/contracts-exchange@1.0.1](https://github.com/0xProject/0x-monorepo/releases/tag/@0x/contracts-exchange@1.0.1) |
| DutchAuction | [`@0x/contracts-extensions`](/contracts/extensions) | [v1.0.2](https://www.npmjs.com/package/@0x/contracts-extensions/v/1.0.2) | [@0x/contracts-extensions@1.0.2](https://github.com/0xProject/0x-monorepo/releases/tag/@0x/contracts-extensions@1.0.2) |
| Forwarder | [`@0x/contracts-exchange-forwarder`](/contracts/exchange-forwarder) | [v1.0.1](https://www.npmjs.com/package/@0x/contracts-exchange-forwarder/v/1.0.1) | [@0x/contracts-exchange-forwarder@1.0.1](https://github.com/0xProject/0x-monorepo/releases/tag/@0x/contracts-exchange-forwarder@1.0.1) |
| MultiAssetProxy | [`@0x/contracts-asset-proxy`](/contracts/asset-proxy) | [v1.0.1](https://www.npmjs.com/package/@0x/contracts-asset-proxy/v/1.0.1) | [@0x/contracts-asset-proxy@1.0.1](https://github.com/0xProject/0x-monorepo/releases/tag/@0x/contracts-asset-proxy@1.0.1) |
| ZRXToken | [`@0x/contracts-erc20`](/contracts/erc20) | [v1.0.1](https://www.npmjs.com/package/@0x/contracts-erc20/v/1.0.1) | [@0x/contracts-erc20@1.0.1](https://github.com/0xProject/0x-monorepo/releases/tag/@0x/contracts-erc20@1.0.1) |
#### Development
Building solidity files will update the contract artifact in `{package-name}/generated-artifacts/{contract}.json`, but does not automatically update the `contract-artifacts` or `contract-wrappers` packages, which are generated from the artifact JSON. See `contract-artifacts/README.md` for instructions on updating these packages.
Building solidity files will update the contract artifact in `{package-name}/generated-artifacts/{contract}.json`, but does not automatically update the `abi-gen-wrappers` package, which are generated from the artifact JSON. To ensure consistency, clean and rebuild `abi-gen-wrappers` after any changes to the artifact JSON.

48
contracts/TESTING.md Normal file
View File

@@ -0,0 +1,48 @@
# Contracts testing options
## Revert stack traces
If you want to see helpful stack traces (incl. line number, code snippet) for smart contract reverts, run the tests with:
```
yarn test:trace
```
**Note:** This currently slows down the test runs and is therefore not enabled by default.
## Backing Ethereum node
By default, our tests run against an in-process [Ganache](https://github.com/trufflesuite/ganache-core) instance. In order to run the tests against [Geth](https://github.com/ethereum/go-ethereum), first follow the instructions in the README for the devnet package to start the devnet Geth node. Then run:
```bash
TEST_PROVIDER=geth yarn test
```
## Code coverage
In order to see the Solidity code coverage output generated by `@0x/sol-coverage`, run:
```
yarn test:coverage
```
## Gas profiler
In order to profile the gas costs for a specific smart contract call/transaction, you can run the tests in `profiler` mode.
**Note:** Traces emitted by ganache have incorrect gas costs so we recommend using Geth for profiling.
```
TEST_PROVIDER=geth yarn test:profiler
```
You'll see a warning that you need to explicitly enable and disable the profiler before and after the block of code you want to profile.
```typescript
import { profiler } from './utils/profiler';
profiler.start();
// Some call to a smart contract
profiler.stop();
```
Without explicitly starting and stopping the profiler, the profiler output will be too busy, and therefore unusable.

View File

@@ -0,0 +1,252 @@
[
{
"timestamp": 1567521715,
"version": "2.2.7",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1566446343,
"version": "2.2.6",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1565296576,
"version": "2.2.5",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "2.2.4",
"changes": [
{
"note": "Updated calls to <contract wrapper>.deployFrom0xArtifactAsync to include artifact dependencies.",
"pr": 1995
}
],
"timestamp": 1564607468
},
{
"timestamp": 1563957393,
"version": "2.2.3",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1563193019,
"version": "2.2.2",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1563047529,
"version": "2.2.1",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "2.2.0",
"changes": [
{
"note": "Add `LibAssetProxyIds` contract",
"pr": 1835
},
{
"note": "Updated ERC1155 Asset Proxy. Less optimization. More explicit handling of edge cases.",
"pr": 1852
},
{
"note": "Implement StaticCallProxy",
"pr": 1863
}
],
"timestamp": 1563006338
},
{
"timestamp": 1558712885,
"version": "2.1.5",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1557961111,
"version": "2.1.4",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1557799313,
"version": "2.1.3",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "2.1.2",
"changes": [
{
"note": "Update tests to use contract-built-in `awaitTransactionSuccessAsync`",
"pr": 1797
}
],
"timestamp": 1557507213
},
{
"version": "2.1.1",
"changes": [
{
"note": "Dependencies updated"
}
],
"timestamp": 1554997931
},
{
"version": "2.1.0",
"changes": [
{
"note": "Run Web3ProviderEngine without excess block polling",
"pr": 1695
}
],
"timestamp": 1553183790
},
{
"version": "2.0.0",
"changes": [
{
"note": "Do not reexport external dependencies",
"pr": 1682
},
{
"note": "Add ERC1155Proxy",
"pr": 1661
},
{
"note": "Bumped solidity version to ^0.5.5",
"pr": 1701
},
{
"note": "Integration testing for ERC1155Proxy",
"pr": 1673
}
],
"timestamp": 1553091633
},
{
"timestamp": 1551479279,
"version": "1.0.9",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1551299797,
"version": "1.0.8",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1551220833,
"version": "1.0.7",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1551130135,
"version": "1.0.6",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1549733923,
"version": "1.0.5",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "1.0.4",
"changes": [
{
"note": "Dependencies updated"
}
],
"timestamp": 1549547375
},
{
"version": "1.0.3",
"changes": [
{
"note": "Fake publish to enable pinning"
}
],
"timestamp": 1549504360
},
{
"timestamp": 1549452781,
"version": "1.0.2",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1549373905,
"version": "1.0.1",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "1.0.0",
"changes": [
{
"note": "Move all AssetProxy contracts out of contracts-protocol to new package",
"pr": 1539
}
]
}
]

View File

@@ -0,0 +1,111 @@
<!--
changelogUtils.file is auto-generated using the monorepo-scripts package. Don't edit directly.
Edit the package's CHANGELOG.json file only.
-->
CHANGELOG
## v2.2.7 - _September 3, 2019_
* Dependencies updated
## v2.2.6 - _August 22, 2019_
* Dependencies updated
## v2.2.5 - _August 8, 2019_
* Dependencies updated
## v2.2.4 - _July 31, 2019_
* Updated calls to <contract wrapper>.deployFrom0xArtifactAsync to include artifact dependencies. (#1995)
## v2.2.3 - _July 24, 2019_
* Dependencies updated
## v2.2.2 - _July 15, 2019_
* Dependencies updated
## v2.2.1 - _July 13, 2019_
* Dependencies updated
## v2.2.0 - _July 13, 2019_
* Add `LibAssetProxyIds` contract (#1835)
* Updated ERC1155 Asset Proxy. Less optimization. More explicit handling of edge cases. (#1852)
* Implement StaticCallProxy (#1863)
## v2.1.5 - _May 24, 2019_
* Dependencies updated
## v2.1.4 - _May 15, 2019_
* Dependencies updated
## v2.1.3 - _May 14, 2019_
* Dependencies updated
## v2.1.2 - _May 10, 2019_
* Update tests to use contract-built-in `awaitTransactionSuccessAsync` (#1797)
## v2.1.1 - _April 11, 2019_
* Dependencies updated
## v2.1.0 - _March 21, 2019_
* Run Web3ProviderEngine without excess block polling (#1695)
## v2.0.0 - _March 20, 2019_
* Do not reexport external dependencies (#1682)
* Add ERC1155Proxy (#1661)
* Bumped solidity version to ^0.5.5 (#1701)
* Integration testing for ERC1155Proxy (#1673)
## v1.0.9 - _March 1, 2019_
* Dependencies updated
## v1.0.8 - _February 27, 2019_
* Dependencies updated
## v1.0.7 - _February 26, 2019_
* Dependencies updated
## v1.0.6 - _February 25, 2019_
* Dependencies updated
## v1.0.5 - _February 9, 2019_
* Dependencies updated
## v1.0.4 - _February 7, 2019_
* Dependencies updated
## v1.0.3 - _February 7, 2019_
* Fake publish to enable pinning
## v1.0.2 - _February 6, 2019_
* Dependencies updated
## v1.0.1 - _February 5, 2019_
* Dependencies updated
## v1.0.0 - _Invalid date_
* Move all AssetProxy contracts out of contracts-protocol to new package (#1539)

View File

@@ -0,0 +1,47 @@
[
{
"name": "MultiAssetProxy",
"version": "1.0.0",
"changes": [
{
"note": "Add MultiAssetProxy implementation",
"pr": 1224,
"networks": {
"3": "0xab8fbd189c569ccdee3a4d929bb7f557be4028f6",
"4": "0xb34cde0ad3a83d04abebc0b66e75196f22216621",
"42": "0xf6313a772c222f51c28f2304c0703b8cf5428fd8"
}
}
]
},
{
"name": "ERC20Proxy",
"version": "1.0.0",
"changes": [
{
"note": "protocol v2 deploy",
"networks": {
"1": "0x2240dab907db71e64d3e0dba4800c83b5c502d4e",
"3": "0xb1408f4c245a23c31b98d2c626777d4c0d766caa",
"4": "0x3e809c563c15a295e832e37053798ddc8d6c8dab",
"42": "0xf1ec01d6236d3cd881a0bf0130ea25fe4234003e"
}
}
]
},
{
"name": "ERC721Proxy",
"version": "1.0.0",
"changes": [
{
"note": "protocol v2 deploy",
"networks": {
"1": "0x208e41fb445f1bb1b6780d58356e81405f3e6127",
"3": "0xe654aac058bfbf9f83fcaee7793311dd82f6ddb4",
"4": "0x8e1ff02637cb5e39f2fa36c14706aa348b065b09",
"42": "0x2a9127c745688a165106c11cd4d647d2220af821"
}
}
]
}
]

View File

@@ -0,0 +1,73 @@
## AssetProxy
This package contains the implementations of all of the [`AssetProxy`](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#assetproxy) contracts available within the 0x protocol. These contracts are responsible for decoding the `assetData` sent to them and performing the actual transfer of assets. Addresses of the deployed contracts can be found in this 0x [guide](https://0x.org/docs/guides/0x-cheat-sheet) or the [DEPLOYS](./DEPLOYS.json) file within this package.
## Installation
**Install**
```bash
npm install @0x/contracts-asset-proxy --save
```
## Bug bounty
A bug bounty for the 2.0.0 contracts is ongoing! Instructions can be found [here](https://0x.org/docs/guides/bug-bounty-program).
## 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.
For proposals regarding the 0x protocol's smart contract architecture, message format, or additional functionality, go to the [0x Improvement Proposals (ZEIPs)](https://github.com/0xProject/ZEIPs) repository and follow the contribution guidelines provided therein.
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
### Install Dependencies
If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them:
```bash
yarn config set workspaces-experimental true
```
Then install dependencies
```bash
yarn install
```
### Build
To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory:
```bash
PKG=@0x/contracts-asset-proxy yarn build
```
Or continuously rebuild on change:
```bash
PKG=@0x/contracts-asset-proxy yarn watch
```
### Clean
```bash
yarn clean
```
### Lint
```bash
yarn lint
```
### Run Tests
```bash
yarn test
```
#### Testing options
Contracts testing options like coverage, profiling, revert traces or backing node choosing - are described [here](../TESTING.md).

View File

@@ -0,0 +1,38 @@
{
"artifactsDir": "./generated-artifacts",
"contractsDir": "./contracts",
"useDockerisedSolc": false,
"isOfflineMode": false,
"compilerSettings": {
"evmVersion": "constantinople",
"optimizer": {
"enabled": true,
"runs": 1000000,
"details": { "yul": true, "deduplicate": true, "cse": true, "constantOptimizer": true }
},
"outputSelection": {
"*": {
"*": [
"abi",
"devdoc",
"evm.bytecode.object",
"evm.bytecode.sourceMap",
"evm.deployedBytecode.object",
"evm.deployedBytecode.sourceMap"
]
}
}
},
"contracts": [
"src/ERC1155Proxy.sol",
"src/ERC20Proxy.sol",
"src/ERC721Proxy.sol",
"src/MixinAuthorizable.sol",
"src/MultiAssetProxy.sol",
"src/StaticCallProxy.sol",
"src/interfaces/IAssetData.sol",
"src/interfaces/IAssetProxy.sol",
"src/interfaces/IAuthorizable.sol",
"test/TestStaticCallTarget.sol"
]
}

View File

@@ -0,0 +1,97 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/SafeMath.sol";
import "@0x/contracts-erc1155/contracts/src/interfaces/IERC1155.sol";
import "./MixinAuthorizable.sol";
import "./interfaces/IAssetProxy.sol";
contract ERC1155Proxy is
MixinAuthorizable,
SafeMath,
IAssetProxy
{
using LibBytes for bytes;
// Id of this proxy.
bytes4 constant internal PROXY_ID = bytes4(keccak256("ERC1155Assets(address,uint256[],uint256[],bytes)"));
/// @dev Transfers batch of ERC1155 assets. Either succeeds or throws.
/// @param assetData Byte array encoded with ERC1155 token address, array of ids, array of values, and callback data.
/// @param from Address to transfer assets from.
/// @param to Address to transfer assets to.
/// @param amount Amount that will be multiplied with each element of `assetData.values` to scale the
/// values that will be transferred.
function transferFrom(
bytes calldata assetData,
address from,
address to,
uint256 amount
)
external
onlyAuthorized
{
// Decode params from `assetData`
// solhint-disable indent
(
address erc1155TokenAddress,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) = abi.decode(
assetData.sliceDestructive(4, assetData.length),
(address, uint256[], uint256[], bytes)
);
// solhint-enable indent
// Scale values up by `amount`
uint256 length = values.length;
uint256[] memory scaledValues = new uint256[](length);
for (uint256 i = 0; i != length; i++) {
// We write the scaled values to an unused location in memory in order
// to avoid copying over `ids` or `data`. This is possible if they are
// identical to `values` and the offsets for each are pointing to the
// same location in the ABI encoded calldata.
scaledValues[i] = safeMul(values[i], amount);
}
// Execute `safeBatchTransferFrom` call
// Either succeeds or throws
IERC1155(erc1155TokenAddress).safeBatchTransferFrom(
from,
to,
ids,
scaledValues,
data
);
}
/// @dev Gets the proxy id associated with the proxy address.
/// @return Proxy id.
function getProxyId()
external
pure
returns (bytes4)
{
return PROXY_ID;
}
}

View File

@@ -0,0 +1,184 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "./MixinAuthorizable.sol";
contract ERC20Proxy is
MixinAuthorizable
{
// Id of this proxy.
bytes4 constant internal PROXY_ID = bytes4(keccak256("ERC20Token(address)"));
// solhint-disable-next-line payable-fallback
function ()
external
{
assembly {
// The first 4 bytes of calldata holds the function selector
let selector := and(calldataload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
// `transferFrom` will be called with the following parameters:
// assetData Encoded byte array.
// from Address to transfer asset from.
// to Address to transfer asset to.
// amount Amount of asset to transfer.
// bytes4(keccak256("transferFrom(bytes,address,address,uint256)")) = 0xa85e59e4
if eq(selector, 0xa85e59e400000000000000000000000000000000000000000000000000000000) {
// To lookup a value in a mapping, we load from the storage location keccak256(k, p),
// where k is the key left padded to 32 bytes and p is the storage slot
let start := mload(64)
mstore(start, and(caller, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(start, 32), authorized_slot)
// Revert if authorized[msg.sender] == false
if iszero(sload(keccak256(start, 64))) {
// Revert with `Error("SENDER_NOT_AUTHORIZED")`
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(64, 0x0000001553454e4445525f4e4f545f415554484f52495a454400000000000000)
mstore(96, 0)
revert(0, 100)
}
// `transferFrom`.
// The function is marked `external`, so no abi decodeding is done for
// us. Instead, we expect the `calldata` memory to contain the
// following:
//
// | Area | Offset | Length | Contents |
// |----------|--------|---------|-------------------------------------|
// | Header | 0 | 4 | function selector |
// | Params | | 4 * 32 | function parameters: |
// | | 4 | | 1. offset to assetData (*) |
// | | 36 | | 2. from |
// | | 68 | | 3. to |
// | | 100 | | 4. amount |
// | Data | | | assetData: |
// | | 132 | 32 | assetData Length |
// | | 164 | ** | assetData Contents |
//
// (*): offset is computed from start of function parameters, so offset
// by an additional 4 bytes in the calldata.
//
// (**): see table below to compute length of assetData Contents
//
// WARNING: The ABIv2 specification allows additional padding between
// the Params and Data section. This will result in a larger
// offset to assetData.
// Asset data itself is encoded as follows:
//
// | Area | Offset | Length | Contents |
// |----------|--------|---------|-------------------------------------|
// | Header | 0 | 4 | function selector |
// | Params | | 1 * 32 | function parameters: |
// | | 4 | 12 + 20 | 1. token address |
// We construct calldata for the `token.transferFrom` ABI.
// The layout of this calldata is in the table below.
//
// | Area | Offset | Length | Contents |
// |----------|--------|---------|-------------------------------------|
// | Header | 0 | 4 | function selector |
// | Params | | 3 * 32 | function parameters: |
// | | 4 | | 1. from |
// | | 36 | | 2. to |
// | | 68 | | 3. amount |
/////// Read token address from calldata ///////
// * The token address is stored in `assetData`.
//
// * The "offset to assetData" is stored at offset 4 in the calldata (table 1).
// [assetDataOffsetFromParams = calldataload(4)]
//
// * Notes that the "offset to assetData" is relative to the "Params" area of calldata;
// add 4 bytes to account for the length of the "Header" area (table 1).
// [assetDataOffsetFromHeader = assetDataOffsetFromParams + 4]
//
// * The "token address" is offset 32+4=36 bytes into "assetData" (tables 1 & 2).
// [tokenOffset = assetDataOffsetFromHeader + 36 = calldataload(4) + 4 + 36]
let token := calldataload(add(calldataload(4), 40))
/////// Setup Header Area ///////
// This area holds the 4-byte `transferFrom` selector.
// Any trailing data in transferFromSelector will be
// overwritten in the next `mstore` call.
mstore(0, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
/////// Setup Params Area ///////
// We copy the fields `from`, `to` and `amount` in bulk
// from our own calldata to the new calldata.
calldatacopy(4, 36, 96)
/////// Call `token.transferFrom` using the calldata ///////
let success := call(
gas, // forward all gas
token, // call address of token contract
0, // don't send any ETH
0, // pointer to start of input
100, // length of input
0, // write output over input
32 // output size should be 32 bytes
)
/////// Check return data. ///////
// If there is no return data, we assume the token incorrectly
// does not return a bool. In this case we expect it to revert
// on failure, which was handled above.
// If the token does return data, we require that it is a single
// nonzero 32 bytes value.
// So the transfer succeeded if the call succeeded and either
// returned nothing, or returned a non-zero 32 byte value.
success := and(success, or(
iszero(returndatasize),
and(
eq(returndatasize, 32),
gt(mload(0), 0)
)
))
if success {
return(0, 0)
}
// Revert with `Error("TRANSFER_FAILED")`
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(64, 0x0000000f5452414e534645525f4641494c454400000000000000000000000000)
mstore(96, 0)
revert(0, 100)
}
// Revert if undefined function is called
revert(0, 0)
}
}
/// @dev Gets the proxy id associated with the proxy address.
/// @return Proxy id.
function getProxyId()
external
pure
returns (bytes4)
{
return PROXY_ID;
}
}

View File

@@ -0,0 +1,171 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "./MixinAuthorizable.sol";
contract ERC721Proxy is
MixinAuthorizable
{
// Id of this proxy.
bytes4 constant internal PROXY_ID = bytes4(keccak256("ERC721Token(address,uint256)"));
// solhint-disable-next-line payable-fallback
function ()
external
{
assembly {
// The first 4 bytes of calldata holds the function selector
let selector := and(calldataload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
// `transferFrom` will be called with the following parameters:
// assetData Encoded byte array.
// from Address to transfer asset from.
// to Address to transfer asset to.
// amount Amount of asset to transfer.
// bytes4(keccak256("transferFrom(bytes,address,address,uint256)")) = 0xa85e59e4
if eq(selector, 0xa85e59e400000000000000000000000000000000000000000000000000000000) {
// To lookup a value in a mapping, we load from the storage location keccak256(k, p),
// where k is the key left padded to 32 bytes and p is the storage slot
let start := mload(64)
mstore(start, and(caller, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(start, 32), authorized_slot)
// Revert if authorized[msg.sender] == false
if iszero(sload(keccak256(start, 64))) {
// Revert with `Error("SENDER_NOT_AUTHORIZED")`
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(64, 0x0000001553454e4445525f4e4f545f415554484f52495a454400000000000000)
mstore(96, 0)
revert(0, 100)
}
// `transferFrom`.
// The function is marked `external`, so no abi decodeding is done for
// us. Instead, we expect the `calldata` memory to contain the
// following:
//
// | Area | Offset | Length | Contents |
// |----------|--------|---------|-------------------------------------|
// | Header | 0 | 4 | function selector |
// | Params | | 4 * 32 | function parameters: |
// | | 4 | | 1. offset to assetData (*) |
// | | 36 | | 2. from |
// | | 68 | | 3. to |
// | | 100 | | 4. amount |
// | Data | | | assetData: |
// | | 132 | 32 | assetData Length |
// | | 164 | ** | assetData Contents |
//
// (*): offset is computed from start of function parameters, so offset
// by an additional 4 bytes in the calldata.
//
// (**): see table below to compute length of assetData Contents
//
// WARNING: The ABIv2 specification allows additional padding between
// the Params and Data section. This will result in a larger
// offset to assetData.
// Asset data itself is encoded as follows:
//
// | Area | Offset | Length | Contents |
// |----------|--------|---------|-------------------------------------|
// | Header | 0 | 4 | function selector |
// | Params | | 2 * 32 | function parameters: |
// | | 4 | 12 + 20 | 1. token address |
// | | 36 | | 2. tokenId |
// We construct calldata for the `token.transferFrom` ABI.
// The layout of this calldata is in the table below.
//
// | Area | Offset | Length | Contents |
// |----------|--------|---------|-------------------------------------|
// | Header | 0 | 4 | function selector |
// | Params | | 3 * 32 | function parameters: |
// | | 4 | | 1. from |
// | | 36 | | 2. to |
// | | 68 | | 3. tokenId |
// There exists only 1 of each token.
// require(amount == 1, "INVALID_AMOUNT")
if sub(calldataload(100), 1) {
// Revert with `Error("INVALID_AMOUNT")`
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(64, 0x0000000e494e56414c49445f414d4f554e540000000000000000000000000000)
mstore(96, 0)
revert(0, 100)
}
/////// Setup Header Area ///////
// This area holds the 4-byte `transferFrom` selector.
// Any trailing data in transferFromSelector will be
// overwritten in the next `mstore` call.
mstore(0, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
/////// Setup Params Area ///////
// We copy the fields `from` and `to` in bulk
// from our own calldata to the new calldata.
calldatacopy(4, 36, 64)
// Copy `tokenId` field from our own calldata to the new calldata.
let assetDataOffset := calldataload(4)
calldatacopy(68, add(assetDataOffset, 72), 32)
/////// Call `token.transferFrom` using the calldata ///////
let token := calldataload(add(assetDataOffset, 40))
let success := call(
gas, // forward all gas
token, // call address of token contract
0, // don't send any ETH
0, // pointer to start of input
100, // length of input
0, // write output to null
0 // output size is 0 bytes
)
if success {
return(0, 0)
}
// Revert with `Error("TRANSFER_FAILED")`
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(64, 0x0000000f5452414e534645525f4641494c454400000000000000000000000000)
mstore(96, 0)
revert(0, 100)
}
// Revert if undefined function is called
revert(0, 0)
}
}
/// @dev Gets the proxy id associated with the proxy address.
/// @return Proxy id.
function getProxyId()
external
pure
returns (bytes4)
{
return PROXY_ID;
}
}

View File

@@ -0,0 +1,172 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "@0x/contracts-utils/contracts/src/Ownable.sol";
import "./mixins/MAssetProxyDispatcher.sol";
import "./interfaces/IAssetProxy.sol";
contract MixinAssetProxyDispatcher is
Ownable,
MAssetProxyDispatcher
{
// Mapping from Asset Proxy Id's to their respective Asset Proxy
mapping (bytes4 => address) public assetProxies;
/// @dev Registers an asset proxy to its asset proxy id.
/// Once an asset proxy is registered, it cannot be unregistered.
/// @param assetProxy Address of new asset proxy to register.
function registerAssetProxy(address assetProxy)
external
onlyOwner
{
// Ensure that no asset proxy exists with current id.
bytes4 assetProxyId = IAssetProxy(assetProxy).getProxyId();
address currentAssetProxy = assetProxies[assetProxyId];
require(
currentAssetProxy == address(0),
"ASSET_PROXY_ALREADY_EXISTS"
);
// Add asset proxy and log registration.
assetProxies[assetProxyId] = assetProxy;
emit AssetProxyRegistered(
assetProxyId,
assetProxy
);
}
/// @dev Gets an asset proxy.
/// @param assetProxyId Id of the asset proxy.
/// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId)
external
view
returns (address)
{
return assetProxies[assetProxyId];
}
/// @dev Forwards arguments to assetProxy and calls `transferFrom`. Either succeeds or throws.
/// @param assetData Byte array encoded for the asset.
/// @param from Address to transfer token from.
/// @param to Address to transfer token to.
/// @param amount Amount of token to transfer.
function dispatchTransferFrom(
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{
// Do nothing if no amount should be transferred.
if (amount > 0 && from != to) {
// Ensure assetData length is valid
require(
assetData.length > 3,
"LENGTH_GREATER_THAN_3_REQUIRED"
);
// Lookup assetProxy. We do not use `LibBytes.readBytes4` for gas efficiency reasons.
bytes4 assetProxyId;
assembly {
assetProxyId := and(mload(
add(assetData, 32)),
0xFFFFFFFF00000000000000000000000000000000000000000000000000000000
)
}
address assetProxy = assetProxies[assetProxyId];
// Ensure that assetProxy exists
require(
assetProxy != address(0),
"ASSET_PROXY_DOES_NOT_EXIST"
);
// We construct calldata for the `assetProxy.transferFrom` ABI.
// The layout of this calldata is in the table below.
//
// | Area | Offset | Length | Contents |
// | -------- |--------|---------|-------------------------------------------- |
// | Header | 0 | 4 | function selector |
// | Params | | 4 * 32 | function parameters: |
// | | 4 | | 1. offset to assetData (*) |
// | | 36 | | 2. from |
// | | 68 | | 3. to |
// | | 100 | | 4. amount |
// | Data | | | assetData: |
// | | 132 | 32 | assetData Length |
// | | 164 | ** | assetData Contents |
assembly {
/////// Setup State ///////
// `cdStart` is the start of the calldata for `assetProxy.transferFrom` (equal to free memory ptr).
let cdStart := mload(64)
// `dataAreaLength` is the total number of words needed to store `assetData`
// As-per the ABI spec, this value is padded up to the nearest multiple of 32,
// and includes 32-bytes for length.
let dataAreaLength := and(add(mload(assetData), 63), 0xFFFFFFFFFFFE0)
// `cdEnd` is the end of the calldata for `assetProxy.transferFrom`.
let cdEnd := add(cdStart, add(132, dataAreaLength))
/////// Setup Header Area ///////
// This area holds the 4-byte `transferFromSelector`.
// bytes4(keccak256("transferFrom(bytes,address,address,uint256)")) = 0xa85e59e4
mstore(cdStart, 0xa85e59e400000000000000000000000000000000000000000000000000000000)
/////// Setup Params Area ///////
// Each parameter is padded to 32-bytes. The entire Params Area is 128 bytes.
// Notes:
// 1. The offset to `assetData` is the length of the Params Area (128 bytes).
// 2. A 20-byte mask is applied to addresses to zero-out the unused bytes.
mstore(add(cdStart, 4), 128)
mstore(add(cdStart, 36), and(from, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(cdStart, 68), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(cdStart, 100), amount)
/////// Setup Data Area ///////
// This area holds `assetData`.
let dataArea := add(cdStart, 132)
// solhint-disable-next-line no-empty-blocks
for {} lt(dataArea, cdEnd) {} {
mstore(dataArea, mload(assetData))
dataArea := add(dataArea, 32)
assetData := add(assetData, 32)
}
/////// Call `assetProxy.transferFrom` using the constructed calldata ///////
let success := call(
gas, // forward all gas
assetProxy, // call address of asset proxy
0, // don't send any ETH
cdStart, // pointer to start of input
sub(cdEnd, cdStart), // length of input
cdStart, // write output over input
512 // reserve 512 bytes for output
)
if iszero(success) {
revert(cdStart, returndatasize())
}
}
}
}
}

View File

@@ -0,0 +1,117 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "@0x/contracts-utils/contracts/src/Ownable.sol";
import "./mixins/MAuthorizable.sol";
contract MixinAuthorizable is
Ownable,
MAuthorizable
{
/// @dev Only authorized addresses can invoke functions with this modifier.
modifier onlyAuthorized {
require(
authorized[msg.sender],
"SENDER_NOT_AUTHORIZED"
);
_;
}
mapping (address => bool) public authorized;
address[] public authorities;
/// @dev Authorizes an address.
/// @param target Address to authorize.
function addAuthorizedAddress(address target)
external
onlyOwner
{
require(
!authorized[target],
"TARGET_ALREADY_AUTHORIZED"
);
authorized[target] = true;
authorities.push(target);
emit AuthorizedAddressAdded(target, msg.sender);
}
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
function removeAuthorizedAddress(address target)
external
onlyOwner
{
require(
authorized[target],
"TARGET_NOT_AUTHORIZED"
);
delete authorized[target];
for (uint256 i = 0; i < authorities.length; i++) {
if (authorities[i] == target) {
authorities[i] = authorities[authorities.length - 1];
authorities.length -= 1;
break;
}
}
emit AuthorizedAddressRemoved(target, msg.sender);
}
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
/// @param index Index of target in authorities array.
function removeAuthorizedAddressAtIndex(
address target,
uint256 index
)
external
onlyOwner
{
require(
authorized[target],
"TARGET_NOT_AUTHORIZED"
);
require(
index < authorities.length,
"INDEX_OUT_OF_BOUNDS"
);
require(
authorities[index] == target,
"AUTHORIZED_ADDRESS_MISMATCH"
);
delete authorized[target];
authorities[index] = authorities[authorities.length - 1];
authorities.length -= 1;
emit AuthorizedAddressRemoved(target, msg.sender);
}
/// @dev Gets all authorized addresses.
/// @return Array of authorized addresses.
function getAuthorizedAddresses()
external
view
returns (address[] memory)
{
return authorities;
}
}

View File

@@ -0,0 +1,335 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "./MixinAssetProxyDispatcher.sol";
import "./MixinAuthorizable.sol";
contract MultiAssetProxy is
MixinAssetProxyDispatcher,
MixinAuthorizable
{
// Id of this proxy.
bytes4 constant internal PROXY_ID = bytes4(keccak256("MultiAsset(uint256[],bytes[])"));
// solhint-disable-next-line payable-fallback
function ()
external
{
// NOTE: The below assembly assumes that clients do some input validation and that the input is properly encoded according to the AbiV2 specification.
// It is technically possible for inputs with very large lengths and offsets to cause overflows. However, this would make the calldata prohibitively
// expensive and we therefore do not check for overflows in these scenarios.
assembly {
// The first 4 bytes of calldata holds the function selector
let selector := and(calldataload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
// `transferFrom` will be called with the following parameters:
// assetData Encoded byte array.
// from Address to transfer asset from.
// to Address to transfer asset to.
// amount Amount of asset to transfer.
// bytes4(keccak256("transferFrom(bytes,address,address,uint256)")) = 0xa85e59e4
if eq(selector, 0xa85e59e400000000000000000000000000000000000000000000000000000000) {
// To lookup a value in a mapping, we load from the storage location keccak256(k, p),
// where k is the key left padded to 32 bytes and p is the storage slot
mstore(0, caller)
mstore(32, authorized_slot)
// Revert if authorized[msg.sender] == false
if iszero(sload(keccak256(0, 64))) {
// Revert with `Error("SENDER_NOT_AUTHORIZED")`
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(64, 0x0000001553454e4445525f4e4f545f415554484f52495a454400000000000000)
mstore(96, 0)
revert(0, 100)
}
// `transferFrom`.
// The function is marked `external`, so no abi decoding is done for
// us. Instead, we expect the `calldata` memory to contain the
// following:
//
// | Area | Offset | Length | Contents |
// |----------|--------|---------|-------------------------------------|
// | Header | 0 | 4 | function selector |
// | Params | | 4 * 32 | function parameters: |
// | | 4 | | 1. offset to assetData (*) |
// | | 36 | | 2. from |
// | | 68 | | 3. to |
// | | 100 | | 4. amount |
// | Data | | | assetData: |
// | | 132 | 32 | assetData Length |
// | | 164 | ** | assetData Contents |
//
// (*): offset is computed from start of function parameters, so offset
// by an additional 4 bytes in the calldata.
//
// (**): see table below to compute length of assetData Contents
//
// WARNING: The ABIv2 specification allows additional padding between
// the Params and Data section. This will result in a larger
// offset to assetData.
// Load offset to `assetData`
let assetDataOffset := add(calldataload(4), 4)
// Load length in bytes of `assetData`
let assetDataLength := calldataload(assetDataOffset)
// Asset data itself is encoded as follows:
//
// | Area | Offset | Length | Contents |
// |----------|-------------|---------|-------------------------------------|
// | Header | 0 | 4 | assetProxyId |
// | Params | | 2 * 32 | function parameters: |
// | | 4 | | 1. offset to amounts (*) |
// | | 36 | | 2. offset to nestedAssetData (*) |
// | Data | | | amounts: |
// | | 68 | 32 | amounts Length |
// | | 100 | a | amounts Contents |
// | | | | nestedAssetData: |
// | | 100 + a | 32 | nestedAssetData Length |
// | | 132 + a | b | nestedAssetData Contents (offsets) |
// | | 132 + a + b | | nestedAssetData[0, ..., len] |
// Assert that the length of asset data:
// 1. Must be at least 68 bytes (see table above)
// 2. Must be a multiple of 32 (excluding the 4-byte selector)
if or(lt(assetDataLength, 68), mod(sub(assetDataLength, 4), 32)) {
// Revert with `Error("INVALID_ASSET_DATA_LENGTH")`
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(64, 0x00000019494e56414c49445f41535345545f444154415f4c454e475448000000)
mstore(96, 0)
revert(0, 100)
}
// End of asset data in calldata
// assetDataOffset
// + 32 (assetData len)
let assetDataEnd := add(assetDataOffset, add(assetDataLength, 32))
if gt(assetDataEnd, calldatasize()) {
// Revert with `Error("INVALID_ASSET_DATA_END")`
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(64, 0x00000016494e56414c49445f41535345545f444154415f454e44000000000000)
mstore(96, 0)
revert(0, 100)
}
// In order to find the offset to `amounts`, we must add:
// assetDataOffset
// + 32 (assetData len)
// + 4 (assetProxyId)
let amountsOffset := calldataload(add(assetDataOffset, 36))
// In order to find the offset to `nestedAssetData`, we must add:
// assetDataOffset
// + 32 (assetData len)
// + 4 (assetProxyId)
// + 32 (amounts offset)
let nestedAssetDataOffset := calldataload(add(assetDataOffset, 68))
// In order to find the start of the `amounts` contents, we must add:
// assetDataOffset
// + 32 (assetData len)
// + 4 (assetProxyId)
// + amountsOffset
// + 32 (amounts len)
let amountsContentsStart := add(assetDataOffset, add(amountsOffset, 68))
// Load number of elements in `amounts`
let amountsLen := calldataload(sub(amountsContentsStart, 32))
// In order to find the start of the `nestedAssetData` contents, we must add:
// assetDataOffset
// + 32 (assetData len)
// + 4 (assetProxyId)
// + nestedAssetDataOffset
// + 32 (nestedAssetData len)
let nestedAssetDataContentsStart := add(assetDataOffset, add(nestedAssetDataOffset, 68))
// Load number of elements in `nestedAssetData`
let nestedAssetDataLen := calldataload(sub(nestedAssetDataContentsStart, 32))
// Revert if number of elements in `amounts` differs from number of elements in `nestedAssetData`
if sub(amountsLen, nestedAssetDataLen) {
// Revert with `Error("LENGTH_MISMATCH")`
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(64, 0x0000000f4c454e4754485f4d49534d4154434800000000000000000000000000)
mstore(96, 0)
revert(0, 100)
}
// Copy `transferFrom` selector, offset to `assetData`, `from`, and `to` from calldata to memory
calldatacopy(
0, // memory can safely be overwritten from beginning
0, // start of calldata
100 // length of selector (4) and 3 params (32 * 3)
)
// Overwrite existing offset to `assetData` with our own
mstore(4, 128)
// Load `amount`
let amount := calldataload(100)
// Calculate number of bytes in `amounts` contents
let amountsByteLen := mul(amountsLen, 32)
// Initialize `assetProxyId` and `assetProxy` to 0
let assetProxyId := 0
let assetProxy := 0
// Loop through `amounts` and `nestedAssetData`, calling `transferFrom` for each respective element
for {let i := 0} lt(i, amountsByteLen) {i := add(i, 32)} {
// Calculate the total amount
let amountsElement := calldataload(add(amountsContentsStart, i))
let totalAmount := mul(amountsElement, amount)
// Revert if `amount` != 0 and multiplication resulted in an overflow
if iszero(or(
iszero(amount),
eq(div(totalAmount, amount), amountsElement)
)) {
// Revert with `Error("UINT256_OVERFLOW")`
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(64, 0x0000001055494e543235365f4f564552464c4f57000000000000000000000000)
mstore(96, 0)
revert(0, 100)
}
// Write `totalAmount` to memory
mstore(100, totalAmount)
// Load offset to `nestedAssetData[i]`
let nestedAssetDataElementOffset := calldataload(add(nestedAssetDataContentsStart, i))
// In order to find the start of the `nestedAssetData[i]` contents, we must add:
// assetDataOffset
// + 32 (assetData len)
// + 4 (assetProxyId)
// + nestedAssetDataOffset
// + 32 (nestedAssetData len)
// + nestedAssetDataElementOffset
// + 32 (nestedAssetDataElement len)
let nestedAssetDataElementContentsStart := add(
assetDataOffset,
add(
nestedAssetDataOffset,
add(nestedAssetDataElementOffset, 100)
)
)
// Load length of `nestedAssetData[i]`
let nestedAssetDataElementLenStart := sub(nestedAssetDataElementContentsStart, 32)
let nestedAssetDataElementLen := calldataload(nestedAssetDataElementLenStart)
// Revert if the `nestedAssetData` does not contain a 4 byte `assetProxyId`
if lt(nestedAssetDataElementLen, 4) {
// Revert with `Error("LENGTH_GREATER_THAN_3_REQUIRED")`
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(64, 0x0000001e4c454e4754485f475245415445525f5448414e5f335f524551554952)
mstore(96, 0x4544000000000000000000000000000000000000000000000000000000000000)
revert(0, 100)
}
// Load AssetProxy id
let currentAssetProxyId := and(
calldataload(nestedAssetDataElementContentsStart),
0xffffffff00000000000000000000000000000000000000000000000000000000
)
// Only load `assetProxy` if `currentAssetProxyId` does not equal `assetProxyId`
// We do not need to check if `currentAssetProxyId` is 0 since `assetProxy` is also initialized to 0
if sub(currentAssetProxyId, assetProxyId) {
// Update `assetProxyId`
assetProxyId := currentAssetProxyId
// To lookup a value in a mapping, we load from the storage location keccak256(k, p),
// where k is the key left padded to 32 bytes and p is the storage slot
mstore(132, assetProxyId)
mstore(164, assetProxies_slot)
assetProxy := sload(keccak256(132, 64))
}
// Revert if AssetProxy with given id does not exist
if iszero(assetProxy) {
// Revert with `Error("ASSET_PROXY_DOES_NOT_EXIST")`
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(32, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(64, 0x0000001a41535345545f50524f58595f444f45535f4e4f545f45584953540000)
mstore(96, 0)
revert(0, 100)
}
// Copy `nestedAssetData[i]` from calldata to memory
calldatacopy(
132, // memory slot after `amounts[i]`
nestedAssetDataElementLenStart, // location of `nestedAssetData[i]` in calldata
add(nestedAssetDataElementLen, 32) // `nestedAssetData[i].length` plus 32 byte length
)
// call `assetProxy.transferFrom`
let success := call(
gas, // forward all gas
assetProxy, // call address of asset proxy
0, // don't send any ETH
0, // pointer to start of input
add(164, nestedAssetDataElementLen), // length of input
0, // write output over memory that won't be reused
0 // don't copy output to memory
)
// Revert with reason given by AssetProxy if `transferFrom` call failed
if iszero(success) {
returndatacopy(
0, // copy to memory at 0
0, // copy from return data at 0
returndatasize() // copy all return data
)
revert(0, returndatasize())
}
}
// Return if no `transferFrom` calls reverted
return(0, 0)
}
// Revert if undefined function is called
revert(0, 0)
}
}
/// @dev Gets the proxy id associated with the proxy address.
/// @return Proxy id.
function getProxyId()
external
pure
returns (bytes4)
{
return PROXY_ID;
}
}

View File

@@ -0,0 +1,83 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
// solhint-disable no-unused-vars
contract StaticCallProxy {
using LibBytes for bytes;
// Id of this proxy.
bytes4 constant internal PROXY_ID = bytes4(keccak256("StaticCall(address,bytes,bytes32)"));
/// @dev Makes a staticcall to a target address and verifies that the data returned matches the expected return data.
/// @param assetData Byte array encoded with staticCallTarget, staticCallData, and expectedCallResultHash
/// @param from This value is ignored.
/// @param to This value is ignored.
/// @param amount This value is ignored.
function transferFrom(
bytes calldata assetData,
address from,
address to,
uint256 amount
)
external
view
{
// Decode params from `assetData`
(
address staticCallTarget,
bytes memory staticCallData,
bytes32 expectedReturnDataHash
) = abi.decode(
assetData.sliceDestructive(4, assetData.length),
(address, bytes, bytes32)
);
// Execute staticcall
(bool success, bytes memory returnData) = staticCallTarget.staticcall(staticCallData);
// Revert with returned data if staticcall is unsuccessful
if (!success) {
assembly {
revert(add(returnData, 32), mload(returnData))
}
}
// Revert if hash of return data is not as expected
bytes32 returnDataHash = keccak256(returnData);
require(
expectedReturnDataHash == returnDataHash,
"UNEXPECTED_STATIC_CALL_RESULT"
);
}
/// @dev Gets the proxy id associated with the proxy address.
/// @return Proxy id.
function getProxyId()
external
pure
returns (bytes4)
{
return PROXY_ID;
}
}

View File

@@ -0,0 +1,58 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// solhint-disable
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
// @dev Interface of the asset proxy's assetData.
// The asset proxies take an ABI encoded `bytes assetData` as argument.
// This argument is ABI encoded as one of the methods of this interface.
interface IAssetData {
function ERC20Token(address tokenAddress)
external;
function ERC721Token(
address tokenAddress,
uint256 tokenId
)
external;
function ERC1155Assets(
address tokenAddress,
uint256[] calldata tokenIds,
uint256[] calldata tokenValues,
bytes calldata callbackData
)
external;
function MultiAsset(
uint256[] calldata amounts,
bytes[] calldata nestedAssetData
)
external;
function StaticCall(
address callTarget,
bytes calldata staticCallData,
bytes32 callResultHash
)
external;
}

View File

@@ -0,0 +1,45 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "./IAuthorizable.sol";
contract IAssetProxy {
/// @dev Transfers assets. Either succeeds or throws.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param from Address to transfer asset from.
/// @param to Address to transfer asset to.
/// @param amount Amount of asset to transfer.
function transferFrom(
bytes calldata assetData,
address from,
address to,
uint256 amount
)
external;
/// @dev Gets the proxy id associated with the proxy address.
/// @return Proxy id.
function getProxyId()
external
pure
returns (bytes4);
}

View File

@@ -0,0 +1,37 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
contract IAssetProxyDispatcher {
/// @dev Registers an asset proxy to its asset proxy id.
/// Once an asset proxy is registered, it cannot be unregistered.
/// @param assetProxy Address of new asset proxy to register.
function registerAssetProxy(address assetProxy)
external;
/// @dev Gets an asset proxy.
/// @param assetProxyId Id of the asset proxy.
/// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId)
external
view
returns (address);
}

View File

@@ -0,0 +1,52 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "@0x/contracts-utils/contracts/src/interfaces/IOwnable.sol";
contract IAuthorizable is
IOwnable
{
/// @dev Authorizes an address.
/// @param target Address to authorize.
function addAuthorizedAddress(address target)
external;
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
function removeAuthorizedAddress(address target)
external;
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
/// @param index Index of target in authorities array.
function removeAuthorizedAddressAtIndex(
address target,
uint256 index
)
external;
/// @dev Gets all authorized addresses.
/// @return Array of authorized addresses.
function getAuthorizedAddresses()
external
view
returns (address[] memory);
}

View File

@@ -0,0 +1,40 @@
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
contract LibAssetProxyIds {
// AssetProxy Ids are equiavalent the first 4 bytes of the keccak256 hash of the function signature assigned to each AssetProxy.
// ERC20Token(address)
bytes4 constant public ERC20_PROXY_ID = 0xf47261b0;
// ERC721Token(address,uint256)
bytes4 constant public ERC721_PROXY_ID = 0x02571792;
// ERC1155Assets(address,uint256[],uint256[],bytes)
bytes4 constant public ERC1155_PROXY_ID = 0xa7cb5fb7;
// MultiAsset(uint256[],bytes[])
bytes4 constant public MULTI_ASSET_PROXY_ID = 0x94cfcdd7;
// StaticCall(address,bytes,bytes32)
bytes4 constant public STATIC_CALL_PROXY_ID = 0xc339d10a;
}

View File

@@ -0,0 +1,45 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "../interfaces/IAssetProxyDispatcher.sol";
contract MAssetProxyDispatcher is
IAssetProxyDispatcher
{
// Logs registration of new asset proxy
event AssetProxyRegistered(
bytes4 id, // Id of new registered AssetProxy.
address assetProxy // Address of new registered AssetProxy.
);
/// @dev Forwards arguments to assetProxy and calls `transferFrom`. Either succeeds or throws.
/// @param assetData Byte array encoded for the asset.
/// @param from Address to transfer token from.
/// @param to Address to transfer token to.
/// @param amount Amount of token to transfer.
function dispatchTransferFrom(
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal;
}

View File

@@ -0,0 +1,41 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "../interfaces/IAuthorizable.sol";
contract MAuthorizable is
IAuthorizable
{
// Event logged when a new address is authorized.
event AuthorizedAddressAdded(
address indexed target,
address indexed caller
);
// Event logged when a currently authorized address is unauthorized.
event AuthorizedAddressRemoved(
address indexed target,
address indexed caller
);
/// @dev Only authorized addresses can invoke functions with this modifier.
modifier onlyAuthorized { revert(); _; }
}

View File

@@ -0,0 +1,82 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
contract TestStaticCallTarget {
using LibBytes for bytes;
uint256 internal _state;
function updateState()
external
{
_state++;
}
function assertEvenNumber(uint256 target)
external
pure
{
require(
target % 2 == 0,
"TARGET_NOT_EVEN"
);
}
function isOddNumber(uint256 target)
external
pure
returns (bool isOdd)
{
isOdd = target % 2 == 1;
return isOdd;
}
function noInputFunction()
external
pure
{
assert(msg.data.length == 4 && msg.data.readBytes4(0) == bytes4(keccak256("noInputFunction()")));
}
function dynamicInputFunction(bytes calldata a)
external
pure
{
bytes memory abiEncodedData = abi.encodeWithSignature("dynamicInputFunction(bytes)", a);
assert(msg.data.equals(abiEncodedData));
}
function returnComplexType(uint256 a, uint256 b)
external
view
returns (bytes memory result)
{
result = abi.encodePacked(
address(this),
a,
b
);
return result;
}
}

View File

@@ -0,0 +1,89 @@
{
"name": "@0x/contracts-asset-proxy",
"version": "2.2.7",
"engines": {
"node": ">=6.12"
},
"description": "Smart contract components of 0x protocol",
"main": "lib/src/index.js",
"directories": {
"test": "test"
},
"scripts": {
"build": "yarn pre_build && tsc -b",
"build:ci": "yarn build",
"pre_build": "run-s compile generate_contract_wrappers",
"test": "yarn run_mocha",
"rebuild_and_test": "run-s build test",
"test:coverage": "SOLIDITY_COVERAGE=true run-s build run_mocha coverage:report:text coverage:report:lcov",
"test:profiler": "SOLIDITY_PROFILER=true run-s build run_mocha profiler:report:html",
"test:trace": "SOLIDITY_REVERT_TRACE=true run-s build run_mocha",
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe 'lib/test/**/*.js' --timeout 100000 --bail --exit",
"compile": "sol-compiler",
"watch": "sol-compiler -w",
"clean": "shx rm -rf lib generated-artifacts generated-wrappers",
"generate_contract_wrappers": "abi-gen --abis ${npm_package_config_abis} --output generated-wrappers --backend ethers",
"lint": "tslint --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"fix": "tslint --fix --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"coverage:report:text": "istanbul report text",
"coverage:report:html": "istanbul report html && open coverage/index.html",
"profiler:report:html": "istanbul report html && open coverage/index.html",
"coverage:report:lcov": "istanbul report lcov",
"test:circleci": "yarn test",
"contracts:gen": "contracts-gen",
"lint-contracts": "solhint -c ../.solhint.json contracts/**/**/**/**/*.sol"
},
"config": {
"abis": "./generated-artifacts/@(ERC1155Proxy|ERC20Proxy|ERC721Proxy|IAssetData|IAssetProxy|IAuthorizable|MixinAuthorizable|MultiAssetProxy|StaticCallProxy|TestStaticCallTarget).json",
"abis:comment": "This list is auto-generated by contracts-gen. Don't edit manually."
},
"repository": {
"type": "git",
"url": "https://github.com/0xProject/0x-monorepo.git"
},
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/0xProject/0x-monorepo/issues"
},
"homepage": "https://github.com/0xProject/0x-monorepo/contracts/protocol/README.md",
"devDependencies": {
"@0x/abi-gen": "^4.2.0",
"@0x/contracts-gen": "^1.0.14",
"@0x/contracts-test-utils": "^3.1.15",
"@0x/dev-utils": "^2.3.2",
"@0x/sol-compiler": "^3.1.14",
"@0x/tslint-config": "^3.0.1",
"@types/lodash": "4.14.104",
"@types/mocha": "^5.2.7",
"@types/node": "*",
"chai": "^4.0.1",
"chai-as-promised": "^7.1.0",
"chai-bignumber": "^3.0.0",
"dirty-chai": "^2.0.1",
"make-promises-safe": "^1.1.0",
"mocha": "^6.2.0",
"npm-run-all": "^4.1.2",
"shx": "^0.2.2",
"solhint": "^1.4.1",
"tslint": "5.11.0",
"typescript": "3.0.1"
},
"dependencies": {
"@0x/base-contract": "^5.3.3",
"@0x/contracts-erc1155": "^1.1.14",
"@0x/contracts-erc20": "^2.2.13",
"@0x/contracts-erc721": "^2.1.14",
"@0x/contracts-utils": "^3.2.3",
"@0x/order-utils": "^8.3.1",
"@0x/types": "^2.4.2",
"@0x/typescript-typings": "^4.2.5",
"@0x/utils": "^4.5.1",
"@0x/web3-wrapper": "^6.0.12",
"ethereum-types": "^2.1.5",
"ethereumjs-util": "^5.1.1",
"lodash": "^4.17.11"
},
"publishConfig": {
"access": "public"
}
}

View File

@@ -0,0 +1,29 @@
/*
* -----------------------------------------------------------------------------
* Warning: This file is auto-generated by contracts-gen. Don't edit manually.
* -----------------------------------------------------------------------------
*/
import { ContractArtifact } from 'ethereum-types';
import * as ERC1155Proxy from '../generated-artifacts/ERC1155Proxy.json';
import * as ERC20Proxy from '../generated-artifacts/ERC20Proxy.json';
import * as ERC721Proxy from '../generated-artifacts/ERC721Proxy.json';
import * as IAssetData from '../generated-artifacts/IAssetData.json';
import * as IAssetProxy from '../generated-artifacts/IAssetProxy.json';
import * as IAuthorizable from '../generated-artifacts/IAuthorizable.json';
import * as MixinAuthorizable from '../generated-artifacts/MixinAuthorizable.json';
import * as MultiAssetProxy from '../generated-artifacts/MultiAssetProxy.json';
import * as StaticCallProxy from '../generated-artifacts/StaticCallProxy.json';
import * as TestStaticCallTarget from '../generated-artifacts/TestStaticCallTarget.json';
export const artifacts = {
ERC1155Proxy: ERC1155Proxy as ContractArtifact,
ERC20Proxy: ERC20Proxy as ContractArtifact,
ERC721Proxy: ERC721Proxy as ContractArtifact,
MixinAuthorizable: MixinAuthorizable as ContractArtifact,
MultiAssetProxy: MultiAssetProxy as ContractArtifact,
StaticCallProxy: StaticCallProxy as ContractArtifact,
IAssetData: IAssetData as ContractArtifact,
IAssetProxy: IAssetProxy as ContractArtifact,
IAuthorizable: IAuthorizable as ContractArtifact,
TestStaticCallTarget: TestStaticCallTarget as ContractArtifact,
};

View File

@@ -0,0 +1,3 @@
export * from './artifacts';
export * from './wrappers';
export * from '../test/utils';

View File

@@ -0,0 +1,15 @@
/*
* -----------------------------------------------------------------------------
* Warning: This file is auto-generated by contracts-gen. Don't edit manually.
* -----------------------------------------------------------------------------
*/
export * from '../generated-wrappers/erc1155_proxy';
export * from '../generated-wrappers/erc20_proxy';
export * from '../generated-wrappers/erc721_proxy';
export * from '../generated-wrappers/i_asset_data';
export * from '../generated-wrappers/i_asset_proxy';
export * from '../generated-wrappers/i_authorizable';
export * from '../generated-wrappers/mixin_authorizable';
export * from '../generated-wrappers/multi_asset_proxy';
export * from '../generated-wrappers/static_call_proxy';
export * from '../generated-wrappers/test_static_call_target';

View File

@@ -0,0 +1,216 @@
import {
chaiSetup,
constants,
expectTransactionFailedAsync,
provider,
txDefaults,
web3Wrapper,
} from '@0x/contracts-test-utils';
import { BlockchainLifecycle } from '@0x/dev-utils';
import { RevertReason } from '@0x/types';
import { BigNumber } from '@0x/utils';
import * as chai from 'chai';
import * as _ from 'lodash';
import { artifacts, MixinAuthorizableContract } from '../src';
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
describe('Authorizable', () => {
let owner: string;
let notOwner: string;
let address: string;
let authorizable: MixinAuthorizableContract;
before(async () => {
await blockchainLifecycle.startAsync();
});
after(async () => {
await blockchainLifecycle.revertAsync();
});
before(async () => {
const accounts = await web3Wrapper.getAvailableAddressesAsync();
[owner, address, notOwner] = _.slice(accounts, 0, 3);
authorizable = await MixinAuthorizableContract.deployFrom0xArtifactAsync(
artifacts.MixinAuthorizable,
provider,
txDefaults,
artifacts,
);
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('addAuthorizedAddress', () => {
it('should throw if not called by owner', async () => {
return expectTransactionFailedAsync(
authorizable.addAuthorizedAddress.sendTransactionAsync(notOwner, { from: notOwner }),
RevertReason.OnlyContractOwner,
);
});
it('should allow owner to add an authorized address', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const isAuthorized = await authorizable.authorized.callAsync(address);
expect(isAuthorized).to.be.true();
});
it('should throw if owner attempts to authorize a duplicate address', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
return expectTransactionFailedAsync(
authorizable.addAuthorizedAddress.sendTransactionAsync(address, { from: owner }),
RevertReason.TargetAlreadyAuthorized,
);
});
});
describe('removeAuthorizedAddress', () => {
it('should throw if not called by owner', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddress.sendTransactionAsync(address, {
from: notOwner,
}),
RevertReason.OnlyContractOwner,
);
});
it('should allow owner to remove an authorized address', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await authorizable.removeAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const isAuthorized = await authorizable.authorized.callAsync(address);
expect(isAuthorized).to.be.false();
});
it('should throw if owner attempts to remove an address that is not authorized', async () => {
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddress.sendTransactionAsync(address, {
from: owner,
}),
RevertReason.TargetNotAuthorized,
);
});
});
describe('removeAuthorizedAddressAtIndex', () => {
it('should throw if not called by owner', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const index = new BigNumber(0);
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, {
from: notOwner,
}),
RevertReason.OnlyContractOwner,
);
});
it('should throw if index is >= authorities.length', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const index = new BigNumber(1);
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, {
from: owner,
}),
RevertReason.IndexOutOfBounds,
);
});
it('should throw if owner attempts to remove an address that is not authorized', async () => {
const index = new BigNumber(0);
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, {
from: owner,
}),
RevertReason.TargetNotAuthorized,
);
});
it('should throw if address at index does not match target', async () => {
const address1 = address;
const address2 = notOwner;
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address1,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address2,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const address1Index = new BigNumber(0);
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address2, address1Index, {
from: owner,
}),
RevertReason.AuthorizedAddressMismatch,
);
});
it('should allow owner to remove an authorized address', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const index = new BigNumber(0);
await authorizable.removeAuthorizedAddressAtIndex.awaitTransactionSuccessAsync(
address,
index,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const isAuthorized = await authorizable.authorized.callAsync(address);
expect(isAuthorized).to.be.false();
});
});
describe('getAuthorizedAddresses', () => {
it('should return all authorized addresses', async () => {
const initial = await authorizable.getAuthorizedAddresses.callAsync();
expect(initial).to.have.length(0);
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const afterAdd = await authorizable.getAuthorizedAddresses.callAsync();
expect(afterAdd).to.have.length(1);
expect(afterAdd).to.include(address);
await authorizable.removeAuthorizedAddress.awaitTransactionSuccessAsync(
address,
{ from: owner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
const afterRemove = await authorizable.getAuthorizedAddresses.callAsync();
expect(afterRemove).to.have.length(0);
});
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,19 @@
import { env, EnvVars } from '@0x/dev-utils';
import { coverage, profiler, provider } from '@0x/contracts-test-utils';
import { providerUtils } from '@0x/utils';
before('start web3 provider', () => {
providerUtils.startProviderEngine(provider);
});
after('generate coverage report', async () => {
if (env.parseBoolean(EnvVars.SolidityCoverage)) {
const coverageSubprovider = coverage.getCoverageSubproviderSingleton();
await coverageSubprovider.writeCoverageAsync();
}
if (env.parseBoolean(EnvVars.SolidityProfiler)) {
const profilerSubprovider = profiler.getProfilerSubproviderSingleton();
await profilerSubprovider.writeProfilerOutputAsync();
}
provider.stop();
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,242 @@
import {
chaiSetup,
constants,
expectTransactionFailedAsync,
expectTransactionFailedWithoutReasonAsync,
provider,
txDefaults,
web3Wrapper,
} from '@0x/contracts-test-utils';
import { BlockchainLifecycle } from '@0x/dev-utils';
import { assetDataUtils } from '@0x/order-utils';
import { AssetProxyId, RevertReason } from '@0x/types';
import { AbiEncoder, BigNumber } from '@0x/utils';
import * as chai from 'chai';
import * as ethUtil from 'ethereumjs-util';
import { artifacts, IAssetProxyContract, StaticCallProxyContract, TestStaticCallTargetContract } from '../src';
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
describe('StaticCallProxy', () => {
const amount = constants.ZERO_AMOUNT;
let fromAddress: string;
let toAddress: string;
let staticCallProxy: IAssetProxyContract;
let staticCallTarget: TestStaticCallTargetContract;
before(async () => {
await blockchainLifecycle.startAsync();
});
after(async () => {
await blockchainLifecycle.revertAsync();
});
before(async () => {
const accounts = await web3Wrapper.getAvailableAddressesAsync();
[fromAddress, toAddress] = accounts.slice(0, 2);
const staticCallProxyWithoutTransferFrom = await StaticCallProxyContract.deployFrom0xArtifactAsync(
artifacts.StaticCallProxy,
provider,
txDefaults,
artifacts,
);
staticCallProxy = new IAssetProxyContract(staticCallProxyWithoutTransferFrom.address, provider, txDefaults);
staticCallTarget = await TestStaticCallTargetContract.deployFrom0xArtifactAsync(
artifacts.TestStaticCallTarget,
provider,
txDefaults,
artifacts,
);
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('general', () => {
it('should revert if undefined function is called', async () => {
const undefinedSelector = '0x01020304';
await expectTransactionFailedWithoutReasonAsync(
web3Wrapper.sendTransactionAsync({
from: fromAddress,
to: staticCallProxy.address,
value: constants.ZERO_AMOUNT,
data: undefinedSelector,
}),
);
});
it('should have an id of 0xc339d10a', async () => {
const proxyId = await staticCallProxy.getProxyId.callAsync();
const expectedProxyId = AssetProxyId.StaticCall;
expect(proxyId).to.equal(expectedProxyId);
});
});
describe('transferFrom', () => {
it('should revert if assetData lies outside the bounds of calldata', async () => {
const staticCallData = staticCallTarget.noInputFunction.getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
const txData = staticCallProxy.transferFrom.getABIEncodedTransactionData(
assetData,
fromAddress,
toAddress,
amount,
);
const offsetToAssetData = '0000000000000000000000000000000000000000000000000000000000000080';
const txDataEndBuffer = ethUtil.toBuffer((txData.length - 2) / 2 - 4);
const paddedTxDataEndBuffer = ethUtil.setLengthLeft(txDataEndBuffer, 32);
const invalidOffsetToAssetData = ethUtil.bufferToHex(paddedTxDataEndBuffer).slice(2);
const newAssetData = '0000000000000000000000000000000000000000000000000000000000000304';
const badTxData = `${txData.replace(offsetToAssetData, invalidOffsetToAssetData)}${newAssetData}`;
await expectTransactionFailedWithoutReasonAsync(
web3Wrapper.sendTransactionAsync({
to: staticCallProxy.address,
from: fromAddress,
data: badTxData,
}),
);
});
it('should revert if the length of assetData is less than 100 bytes', async () => {
const staticCallData = constants.NULL_BYTES;
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.slice(0, -128);
const assetDataByteLen = (assetData.length - 2) / 2;
expect((assetDataByteLen - 4) % 32).to.equal(0);
await expectTransactionFailedWithoutReasonAsync(
staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount),
);
});
it('should revert if the offset to `staticCallData` points to outside of assetData', async () => {
const staticCallData = staticCallTarget.noInputFunction.getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
const offsetToStaticCallData = '0000000000000000000000000000000000000000000000000000000000000060';
const assetDataEndBuffer = ethUtil.toBuffer((assetData.length - 2) / 2 - 4);
const paddedAssetDataEndBuffer = ethUtil.setLengthLeft(assetDataEndBuffer, 32);
const invalidOffsetToStaticCallData = ethUtil.bufferToHex(paddedAssetDataEndBuffer).slice(2);
const newStaticCallData = '0000000000000000000000000000000000000000000000000000000000000304';
const badAssetData = `${assetData.replace(
offsetToStaticCallData,
invalidOffsetToStaticCallData,
)}${newStaticCallData}`;
await expectTransactionFailedWithoutReasonAsync(
staticCallProxy.transferFrom.sendTransactionAsync(badAssetData, fromAddress, toAddress, amount),
);
});
it('should revert if the callTarget attempts to write to state', async () => {
const staticCallData = staticCallTarget.updateState.getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await expectTransactionFailedWithoutReasonAsync(
staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount),
);
});
it('should revert with data provided by the callTarget if the staticcall reverts', async () => {
const staticCallData = staticCallTarget.assertEvenNumber.getABIEncodedTransactionData(new BigNumber(1));
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await expectTransactionFailedAsync(
staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount),
RevertReason.TargetNotEven,
);
});
it('should revert if the hash of the output is different than expected expected', async () => {
const staticCallData = staticCallTarget.isOddNumber.getABIEncodedTransactionData(new BigNumber(0));
const trueAsBuffer = ethUtil.toBuffer('0x0000000000000000000000000000000000000000000000000000000000000001');
const expectedResultHash = ethUtil.bufferToHex(ethUtil.sha3(trueAsBuffer));
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await expectTransactionFailedAsync(
staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount),
RevertReason.UnexpectedStaticCallResult,
);
});
it('should be successful if a function call with no inputs and no outputs is successful', async () => {
const staticCallData = staticCallTarget.noInputFunction.getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
});
it('should be successful if the staticCallTarget is not a contract and no return value is expected', async () => {
const staticCallData = '0x0102030405060708';
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(toAddress, staticCallData, expectedResultHash);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
});
it('should be successful if a function call with one static input returns the correct value', async () => {
const staticCallData = staticCallTarget.isOddNumber.getABIEncodedTransactionData(new BigNumber(1));
const trueAsBuffer = ethUtil.toBuffer('0x0000000000000000000000000000000000000000000000000000000000000001');
const expectedResultHash = ethUtil.bufferToHex(ethUtil.sha3(trueAsBuffer));
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
});
it('should be successful if a function with one dynamic input is successful', async () => {
const dynamicInput = '0x0102030405060708';
const staticCallData = staticCallTarget.dynamicInputFunction.getABIEncodedTransactionData(dynamicInput);
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
});
it('should be successful if a function call returns a complex type', async () => {
const a = new BigNumber(1);
const b = new BigNumber(2);
const staticCallData = staticCallTarget.returnComplexType.getABIEncodedTransactionData(a, b);
const abiEncoder = new AbiEncoder.DynamicBytes({
name: '',
type: 'bytes',
});
const aHex = '0000000000000000000000000000000000000000000000000000000000000001';
const bHex = '0000000000000000000000000000000000000000000000000000000000000002';
const expectedResults = `${staticCallTarget.address}${aHex}${bHex}`;
const offset = '0000000000000000000000000000000000000000000000000000000000000020';
const encodedExpectedResultWithOffset = `0x${offset}${abiEncoder.encode(expectedResults).slice(2)}`;
const expectedResultHash = ethUtil.bufferToHex(
ethUtil.sha3(ethUtil.toBuffer(encodedExpectedResultWithOffset)),
);
const assetData = assetDataUtils.encodeStaticCallAssetData(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
});
});
});

View File

@@ -0,0 +1,403 @@
import { artifacts as erc1155Artifacts, ERC1155MintableContract, Erc1155Wrapper } from '@0x/contracts-erc1155';
import {
constants,
ERC1155FungibleHoldingsByOwner,
ERC1155HoldingsByOwner,
ERC1155NonFungibleHoldingsByOwner,
LogDecoder,
txDefaults,
} from '@0x/contracts-test-utils';
import { assetDataUtils } from '@0x/order-utils';
import { BigNumber } from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wrapper';
import { Provider, TransactionReceiptWithDecodedLogs } from 'ethereum-types';
import * as _ from 'lodash';
import { artifacts, ERC1155ProxyContract, IAssetProxyContract } from '../../src';
export class ERC1155ProxyWrapper {
private readonly _tokenOwnerAddresses: string[];
private readonly _fungibleTokenIds: string[];
private readonly _nonFungibleTokenIds: string[];
private readonly _nfts: Array<{ id: BigNumber; tokenId: BigNumber }>;
private readonly _contractOwnerAddress: string;
private readonly _web3Wrapper: Web3Wrapper;
private readonly _provider: Provider;
private readonly _logDecoder: LogDecoder;
private readonly _dummyTokenWrappers: Erc1155Wrapper[];
private readonly _assetProxyInterface: IAssetProxyContract;
private _proxyContract?: ERC1155ProxyContract;
private _proxyIdIfExists?: string;
private _initialTokenIdsByOwner: ERC1155HoldingsByOwner = { fungible: {}, nonFungible: {} };
constructor(provider: Provider, tokenOwnerAddresses: string[], contractOwnerAddress: string) {
this._web3Wrapper = new Web3Wrapper(provider);
this._provider = provider;
const allArtifacts = _.merge(artifacts, erc1155Artifacts);
this._logDecoder = new LogDecoder(this._web3Wrapper, allArtifacts);
this._dummyTokenWrappers = [];
this._assetProxyInterface = new IAssetProxyContract(constants.NULL_ADDRESS, provider);
this._tokenOwnerAddresses = tokenOwnerAddresses;
this._contractOwnerAddress = contractOwnerAddress;
this._fungibleTokenIds = [];
this._nonFungibleTokenIds = [];
this._nfts = [];
}
/**
* @dev Deploys dummy ERC1155 contracts
* @return An array of ERC1155 wrappers; one for each deployed contract.
*/
public async deployDummyContractsAsync(): Promise<Erc1155Wrapper[]> {
// tslint:disable-next-line:no-unused-variable
for (const i of _.times(constants.NUM_DUMMY_ERC1155_CONTRACTS_TO_DEPLOY)) {
const erc1155Contract = await ERC1155MintableContract.deployFrom0xArtifactAsync(
erc1155Artifacts.ERC1155Mintable,
this._provider,
txDefaults,
artifacts,
);
const erc1155Wrapper = new Erc1155Wrapper(erc1155Contract, this._provider, this._contractOwnerAddress);
this._dummyTokenWrappers.push(erc1155Wrapper);
}
return this._dummyTokenWrappers;
}
/**
* @dev Deploys the ERC1155 proxy
* @return Deployed ERC1155 proxy contract instance
*/
public async deployProxyAsync(): Promise<ERC1155ProxyContract> {
this._proxyContract = await ERC1155ProxyContract.deployFrom0xArtifactAsync(
artifacts.ERC1155Proxy,
this._provider,
txDefaults,
artifacts,
);
this._proxyIdIfExists = await this._proxyContract.getProxyId.callAsync();
return this._proxyContract;
}
/**
* @dev Gets the ERC1155 proxy id
*/
public getProxyId(): string {
this._validateProxyContractExistsOrThrow();
return this._proxyIdIfExists as string;
}
/**
* @dev generates abi-encoded tx data for transferring erc1155 fungible/non-fungible tokens.
* @param from source address
* @param to destination address
* @param contractAddress address of erc155 contract
* @param tokensToTransfer array of erc1155 tokens to transfer
* @param valuesToTransfer array of corresponding values for each erc1155 token to transfer
* @param valueMultiplier each value in `valuesToTransfer` is multiplied by this
* @param receiverCallbackData callback data if `to` is a contract
* @param authorizedSender sender of `transferFrom` transaction
* @param extraData extra data to append to `transferFrom` transaction. Optional.
* @return abi encoded tx data.
*/
public getTransferFromAbiEncodedTxData(
from: string,
to: string,
contractAddress: string,
tokensToTransfer: BigNumber[],
valuesToTransfer: BigNumber[],
valueMultiplier: BigNumber,
receiverCallbackData: string,
authorizedSender: string,
assetData_?: string,
): string {
this._validateProxyContractExistsOrThrow();
const assetData =
assetData_ === undefined
? assetDataUtils.encodeERC1155AssetData(
contractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
: assetData_;
const data = this._assetProxyInterface.transferFrom.getABIEncodedTransactionData(
assetData,
from,
to,
valueMultiplier,
);
return data;
}
/**
* @dev transfers erc1155 fungible/non-fungible tokens.
* @param txData: abi-encoded tx data
* @param authorizedSender sender of `transferFrom` transaction
*/
public async transferFromRawAsync(
txData: string,
authorizedSender: string,
): Promise<TransactionReceiptWithDecodedLogs> {
const txHash = await this._web3Wrapper.sendTransactionAsync({
to: (this._proxyContract as ERC1155ProxyContract).address,
data: txData,
from: authorizedSender,
gas: 300000,
});
const txReceipt = await this._logDecoder.getTxWithDecodedLogsAsync(txHash);
return txReceipt;
}
/**
* @dev transfers erc1155 fungible/non-fungible tokens.
* @param from source address
* @param to destination address
* @param contractAddress address of erc155 contract
* @param tokensToTransfer array of erc1155 tokens to transfer
* @param valuesToTransfer array of corresponding values for each erc1155 token to transfer
* @param valueMultiplier each value in `valuesToTransfer` is multiplied by this
* @param receiverCallbackData callback data if `to` is a contract
* @param authorizedSender sender of `transferFrom` transaction
* @param extraData extra data to append to `transferFrom` transaction. Optional.
* @return tranasction hash.
*/
public async transferFromAsync(
from: string,
to: string,
contractAddress: string,
tokensToTransfer: BigNumber[],
valuesToTransfer: BigNumber[],
valueMultiplier: BigNumber,
receiverCallbackData: string,
authorizedSender: string,
assetData_?: string,
): Promise<TransactionReceiptWithDecodedLogs> {
this._validateProxyContractExistsOrThrow();
const assetData =
assetData_ === undefined
? assetDataUtils.encodeERC1155AssetData(
contractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
: assetData_;
const data = this._assetProxyInterface.transferFrom.getABIEncodedTransactionData(
assetData,
from,
to,
valueMultiplier,
);
const txHash = await this._web3Wrapper.sendTransactionAsync({
to: (this._proxyContract as ERC1155ProxyContract).address,
data,
from: authorizedSender,
gas: 300000,
});
const txReceipt = await this._logDecoder.getTxWithDecodedLogsAsync(txHash);
return txReceipt;
}
/**
* @dev For each deployed ERC1155 contract, this function mints a set of fungible/non-fungible
* tokens for each token owner address (`_tokenOwnerAddresses`).
* @return Balances of each token owner, across all ERC1155 contracts and tokens.
*/
public async setBalancesAndAllowancesAsync(): Promise<ERC1155HoldingsByOwner> {
this._validateDummyTokenContractsExistOrThrow();
this._validateProxyContractExistsOrThrow();
this._initialTokenIdsByOwner = {
fungible: {},
nonFungible: {},
};
const fungibleHoldingsByOwner: ERC1155FungibleHoldingsByOwner = {};
const nonFungibleHoldingsByOwner: ERC1155NonFungibleHoldingsByOwner = {};
// Set balances accordingly
for (const dummyWrapper of this._dummyTokenWrappers) {
const dummyAddress = dummyWrapper.getContract().address;
// tslint:disable-next-line:no-unused-variable
for (const i of _.times(constants.NUM_ERC1155_FUNGIBLE_TOKENS_MINT)) {
// Create a fungible token
const tokenId = await dummyWrapper.mintFungibleTokensAsync(
this._tokenOwnerAddresses,
constants.INITIAL_ERC1155_FUNGIBLE_BALANCE,
);
const tokenIdAsString = tokenId.toString();
this._fungibleTokenIds.push(tokenIdAsString);
// Mint tokens for each owner for this token
for (const tokenOwnerAddress of this._tokenOwnerAddresses) {
// tslint:disable-next-line:no-unused-variable
if (fungibleHoldingsByOwner[tokenOwnerAddress] === undefined) {
fungibleHoldingsByOwner[tokenOwnerAddress] = {};
}
if (fungibleHoldingsByOwner[tokenOwnerAddress][dummyAddress] === undefined) {
fungibleHoldingsByOwner[tokenOwnerAddress][dummyAddress] = {};
}
fungibleHoldingsByOwner[tokenOwnerAddress][dummyAddress][tokenIdAsString] =
constants.INITIAL_ERC1155_FUNGIBLE_BALANCE;
await dummyWrapper.setApprovalForAllAsync(
tokenOwnerAddress,
(this._proxyContract as ERC1155ProxyContract).address,
true,
);
}
}
// Non-fungible tokens
// tslint:disable-next-line:no-unused-variable
for (const j of _.times(constants.NUM_ERC1155_NONFUNGIBLE_TOKENS_MINT)) {
const [tokenId, nftIds] = await dummyWrapper.mintNonFungibleTokensAsync(this._tokenOwnerAddresses);
const tokenIdAsString = tokenId.toString();
this._nonFungibleTokenIds.push(tokenIdAsString);
_.each(this._tokenOwnerAddresses, async (tokenOwnerAddress: string, i: number) => {
if (nonFungibleHoldingsByOwner[tokenOwnerAddress] === undefined) {
nonFungibleHoldingsByOwner[tokenOwnerAddress] = {};
}
if (nonFungibleHoldingsByOwner[tokenOwnerAddress][dummyAddress] === undefined) {
nonFungibleHoldingsByOwner[tokenOwnerAddress][dummyAddress] = {};
}
if (nonFungibleHoldingsByOwner[tokenOwnerAddress][dummyAddress][tokenIdAsString] === undefined) {
nonFungibleHoldingsByOwner[tokenOwnerAddress][dummyAddress][tokenIdAsString] = [];
}
this._nfts.push({ id: nftIds[i], tokenId });
nonFungibleHoldingsByOwner[tokenOwnerAddress][dummyAddress][tokenIdAsString].push(nftIds[i]);
await dummyWrapper.setApprovalForAllAsync(
tokenOwnerAddress,
(this._proxyContract as ERC1155ProxyContract).address,
true,
);
});
}
}
this._initialTokenIdsByOwner = {
fungible: fungibleHoldingsByOwner,
nonFungible: nonFungibleHoldingsByOwner,
};
return this._initialTokenIdsByOwner;
}
/**
* @dev For each deployed ERC1155 contract, this function quieries the set of fungible/non-fungible
* tokens for each token owner address (`_tokenOwnerAddresses`).
* @return Balances of each token owner, across all ERC1155 contracts and tokens.
*/
public async getBalancesAsync(): Promise<ERC1155HoldingsByOwner> {
this._validateDummyTokenContractsExistOrThrow();
this._validateBalancesAndAllowancesSetOrThrow();
const tokenHoldingsByOwner: ERC1155FungibleHoldingsByOwner = {};
const nonFungibleHoldingsByOwner: ERC1155NonFungibleHoldingsByOwner = {};
for (const dummyTokenWrapper of this._dummyTokenWrappers) {
const tokenContract = dummyTokenWrapper.getContract();
const tokenAddress = tokenContract.address;
// Construct batch balance call
const tokenOwners: string[] = [];
const tokenIds: BigNumber[] = [];
for (const tokenOwnerAddress of this._tokenOwnerAddresses) {
for (const tokenId of this._fungibleTokenIds) {
tokenOwners.push(tokenOwnerAddress);
tokenIds.push(new BigNumber(tokenId));
}
for (const nft of this._nfts) {
tokenOwners.push(tokenOwnerAddress);
tokenIds.push(nft.id);
}
}
const balances = await dummyTokenWrapper.getBalancesAsync(tokenOwners, tokenIds);
// Parse out balances into fungible / non-fungible token holdings
let i = 0;
for (const tokenOwnerAddress of this._tokenOwnerAddresses) {
// Fungible tokens
for (const tokenId of this._fungibleTokenIds) {
if (tokenHoldingsByOwner[tokenOwnerAddress] === undefined) {
tokenHoldingsByOwner[tokenOwnerAddress] = {};
}
if (tokenHoldingsByOwner[tokenOwnerAddress][tokenAddress] === undefined) {
tokenHoldingsByOwner[tokenOwnerAddress][tokenAddress] = {};
}
tokenHoldingsByOwner[tokenOwnerAddress][tokenAddress][tokenId] = balances[i++];
}
// Non-fungible tokens
for (const nft of this._nfts) {
if (nonFungibleHoldingsByOwner[tokenOwnerAddress] === undefined) {
nonFungibleHoldingsByOwner[tokenOwnerAddress] = {};
}
if (nonFungibleHoldingsByOwner[tokenOwnerAddress][tokenAddress] === undefined) {
nonFungibleHoldingsByOwner[tokenOwnerAddress][tokenAddress] = {};
}
if (
nonFungibleHoldingsByOwner[tokenOwnerAddress][tokenAddress][nft.tokenId.toString()] ===
undefined
) {
nonFungibleHoldingsByOwner[tokenOwnerAddress][tokenAddress][nft.tokenId.toString()] = [];
}
const isOwner = balances[i++];
if (isOwner.isEqualTo(1)) {
nonFungibleHoldingsByOwner[tokenOwnerAddress][tokenAddress][nft.tokenId.toString()].push(
nft.id,
);
}
}
}
}
const holdingsByOwner = {
fungible: tokenHoldingsByOwner,
nonFungible: nonFungibleHoldingsByOwner,
};
return holdingsByOwner;
}
/**
* @dev Checks if proxy is approved to transfer tokens on behalf of `userAddress`.
* @param userAddress owner of ERC1155 tokens.
* @param contractAddress address of ERC1155 contract.
* @return True iff the proxy is approved for all. False otherwise.
*/
public async isProxyApprovedForAllAsync(userAddress: string, contractAddress: string): Promise<boolean> {
this._validateProxyContractExistsOrThrow();
const tokenContract = this._getContractFromAddress(contractAddress);
const operator = (this._proxyContract as ERC1155ProxyContract).address;
const didApproveAll = await tokenContract.isApprovedForAll.callAsync(userAddress, operator);
return didApproveAll;
}
public getFungibleTokenIds(): BigNumber[] {
const fungibleTokenIds = _.map(this._fungibleTokenIds, (tokenIdAsString: string) => {
return new BigNumber(tokenIdAsString);
});
return fungibleTokenIds;
}
public getNonFungibleTokenIds(): BigNumber[] {
const nonFungibleTokenIds = _.map(this._nonFungibleTokenIds, (tokenIdAsString: string) => {
return new BigNumber(tokenIdAsString);
});
return nonFungibleTokenIds;
}
public getTokenOwnerAddresses(): string[] {
return this._tokenOwnerAddresses;
}
public getContractWrapper(contractAddress: string): Erc1155Wrapper {
const tokenWrapper = _.find(this._dummyTokenWrappers, (wrapper: Erc1155Wrapper) => {
return wrapper.getContract().address === contractAddress;
});
if (tokenWrapper === undefined) {
throw new Error(`Contract: ${contractAddress} was not deployed through ERC1155ProxyWrapper`);
}
return tokenWrapper;
}
private _getContractFromAddress(tokenAddress: string): ERC1155MintableContract {
const tokenContractIfExists = _.find(this._dummyTokenWrappers, c => c.getContract().address === tokenAddress);
if (tokenContractIfExists === undefined) {
throw new Error(`Token: ${tokenAddress} was not deployed through ERC1155ProxyWrapper`);
}
return tokenContractIfExists.getContract();
}
private _validateDummyTokenContractsExistOrThrow(): void {
if (this._dummyTokenWrappers === undefined) {
throw new Error('Dummy ERC1155 tokens not yet deployed, please call "deployDummyTokensAsync"');
}
}
private _validateProxyContractExistsOrThrow(): void {
if (this._proxyContract === undefined) {
throw new Error('ERC1155 proxy contract not yet deployed, please call "deployProxyAsync"');
}
}
private _validateBalancesAndAllowancesSetOrThrow(): void {
if (
_.keys(this._initialTokenIdsByOwner.fungible).length === 0 ||
_.keys(this._initialTokenIdsByOwner.nonFungible).length === 0
) {
throw new Error(
'Dummy ERC1155 balances and allowances not yet set, please call "setBalancesAndAllowancesAsync"',
);
}
}
}

View File

@@ -0,0 +1,173 @@
import { artifacts as erc20Artifacts, DummyERC20TokenContract } from '@0x/contracts-erc20';
import { constants, ERC20BalancesByOwner, txDefaults } from '@0x/contracts-test-utils';
import { assetDataUtils } from '@0x/order-utils';
import { BigNumber } from '@0x/utils';
import { ZeroExProvider } from 'ethereum-types';
import * as _ from 'lodash';
import { artifacts, ERC20ProxyContract } from '../../src';
export class ERC20Wrapper {
private readonly _tokenOwnerAddresses: string[];
private readonly _contractOwnerAddress: string;
private readonly _provider: ZeroExProvider;
private readonly _dummyTokenContracts: DummyERC20TokenContract[];
private _proxyContract?: ERC20ProxyContract;
private _proxyIdIfExists?: string;
/**
* Instanitates an ERC20Wrapper
* @param provider Web3 provider to use for all JSON RPC requests
* @param tokenOwnerAddresses Addresses that we want to endow as owners for dummy ERC20 tokens
* @param contractOwnerAddress Desired owner of the contract
* Instance of ERC20Wrapper
*/
constructor(provider: ZeroExProvider, tokenOwnerAddresses: string[], contractOwnerAddress: string) {
this._dummyTokenContracts = [];
this._provider = provider;
this._tokenOwnerAddresses = tokenOwnerAddresses;
this._contractOwnerAddress = contractOwnerAddress;
}
public async deployDummyTokensAsync(
numberToDeploy: number,
decimals: BigNumber,
): Promise<DummyERC20TokenContract[]> {
for (let i = 0; i < numberToDeploy; i++) {
this._dummyTokenContracts.push(
await DummyERC20TokenContract.deployFrom0xArtifactAsync(
erc20Artifacts.DummyERC20Token,
this._provider,
txDefaults,
artifacts,
constants.DUMMY_TOKEN_NAME,
constants.DUMMY_TOKEN_SYMBOL,
decimals,
constants.DUMMY_TOKEN_TOTAL_SUPPLY,
),
);
}
return this._dummyTokenContracts;
}
public async deployProxyAsync(): Promise<ERC20ProxyContract> {
this._proxyContract = await ERC20ProxyContract.deployFrom0xArtifactAsync(
artifacts.ERC20Proxy,
this._provider,
txDefaults,
artifacts,
);
this._proxyIdIfExists = await this._proxyContract.getProxyId.callAsync();
return this._proxyContract;
}
public getProxyId(): string {
this._validateProxyContractExistsOrThrow();
return this._proxyIdIfExists as string;
}
public async setBalancesAndAllowancesAsync(): Promise<void> {
this._validateDummyTokenContractsExistOrThrow();
this._validateProxyContractExistsOrThrow();
for (const dummyTokenContract of this._dummyTokenContracts) {
for (const tokenOwnerAddress of this._tokenOwnerAddresses) {
await dummyTokenContract.setBalance.awaitTransactionSuccessAsync(
tokenOwnerAddress,
constants.INITIAL_ERC20_BALANCE,
{ from: this._contractOwnerAddress },
constants.AWAIT_TRANSACTION_MINED_MS,
);
await dummyTokenContract.approve.awaitTransactionSuccessAsync(
(this._proxyContract as ERC20ProxyContract).address,
constants.INITIAL_ERC20_ALLOWANCE,
{ from: tokenOwnerAddress },
constants.AWAIT_TRANSACTION_MINED_MS,
);
}
}
}
public async getBalanceAsync(userAddress: string, assetData: string): Promise<BigNumber> {
const tokenContract = this._getTokenContractFromAssetData(assetData);
const balance = new BigNumber(await tokenContract.balanceOf.callAsync(userAddress));
return balance;
}
public async setBalanceAsync(userAddress: string, assetData: string, amount: BigNumber): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(assetData);
await tokenContract.setBalance.awaitTransactionSuccessAsync(
userAddress,
amount,
{ from: this._contractOwnerAddress },
constants.AWAIT_TRANSACTION_MINED_MS,
);
}
public async getProxyAllowanceAsync(userAddress: string, assetData: string): Promise<BigNumber> {
const tokenContract = this._getTokenContractFromAssetData(assetData);
const proxyAddress = (this._proxyContract as ERC20ProxyContract).address;
const allowance = new BigNumber(await tokenContract.allowance.callAsync(userAddress, proxyAddress));
return allowance;
}
public async setAllowanceAsync(userAddress: string, assetData: string, amount: BigNumber): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(assetData);
const proxyAddress = (this._proxyContract as ERC20ProxyContract).address;
await tokenContract.approve.awaitTransactionSuccessAsync(
proxyAddress,
amount,
{ from: userAddress },
constants.AWAIT_TRANSACTION_MINED_MS,
);
}
public async getBalancesAsync(): Promise<ERC20BalancesByOwner> {
this._validateDummyTokenContractsExistOrThrow();
const balancesByOwner: ERC20BalancesByOwner = {};
const balances: BigNumber[] = [];
const balanceInfo: Array<{ tokenOwnerAddress: string; tokenAddress: string }> = [];
for (const dummyTokenContract of this._dummyTokenContracts) {
for (const tokenOwnerAddress of this._tokenOwnerAddresses) {
balances.push(await dummyTokenContract.balanceOf.callAsync(tokenOwnerAddress));
balanceInfo.push({
tokenOwnerAddress,
tokenAddress: dummyTokenContract.address,
});
}
}
_.forEach(balances, (balance, balanceIndex) => {
const tokenAddress = balanceInfo[balanceIndex].tokenAddress;
const tokenOwnerAddress = balanceInfo[balanceIndex].tokenOwnerAddress;
if (balancesByOwner[tokenOwnerAddress] === undefined) {
balancesByOwner[tokenOwnerAddress] = {};
}
const wrappedBalance = new BigNumber(balance);
balancesByOwner[tokenOwnerAddress][tokenAddress] = wrappedBalance;
});
return balancesByOwner;
}
public addDummyTokenContract(dummy: DummyERC20TokenContract): void {
if (this._dummyTokenContracts !== undefined) {
this._dummyTokenContracts.push(dummy);
}
}
public addTokenOwnerAddress(address: string): void {
this._tokenOwnerAddresses.push(address);
}
public getTokenOwnerAddresses(): string[] {
return this._tokenOwnerAddresses;
}
public getTokenAddresses(): string[] {
const tokenAddresses = _.map(this._dummyTokenContracts, dummyTokenContract => dummyTokenContract.address);
return tokenAddresses;
}
private _getTokenContractFromAssetData(assetData: string): DummyERC20TokenContract {
const erc20ProxyData = assetDataUtils.decodeERC20AssetData(assetData);
const tokenAddress = erc20ProxyData.tokenAddress;
const tokenContractIfExists = _.find(this._dummyTokenContracts, c => c.address === tokenAddress);
if (tokenContractIfExists === undefined) {
throw new Error(`Token: ${tokenAddress} was not deployed through ERC20Wrapper`);
}
return tokenContractIfExists;
}
private _validateDummyTokenContractsExistOrThrow(): void {
if (this._dummyTokenContracts === undefined) {
throw new Error('Dummy ERC20 tokens not yet deployed, please call "deployDummyTokensAsync"');
}
}
private _validateProxyContractExistsOrThrow(): void {
if (this._proxyContract === undefined) {
throw new Error('ERC20 proxy contract not yet deployed, please call "deployProxyAsync"');
}
}
}

View File

@@ -0,0 +1,235 @@
import { artifacts as erc721Artifacts, DummyERC721TokenContract } from '@0x/contracts-erc721';
import { constants, ERC721TokenIdsByOwner, txDefaults } from '@0x/contracts-test-utils';
import { generatePseudoRandomSalt } from '@0x/order-utils';
import { BigNumber } from '@0x/utils';
import { ZeroExProvider } from 'ethereum-types';
import * as _ from 'lodash';
import { artifacts, ERC721ProxyContract } from '../../src';
export class ERC721Wrapper {
private readonly _tokenOwnerAddresses: string[];
private readonly _contractOwnerAddress: string;
private readonly _provider: ZeroExProvider;
private readonly _dummyTokenContracts: DummyERC721TokenContract[];
private _proxyContract?: ERC721ProxyContract;
private _proxyIdIfExists?: string;
private _initialTokenIdsByOwner: ERC721TokenIdsByOwner = {};
constructor(provider: ZeroExProvider, tokenOwnerAddresses: string[], contractOwnerAddress: string) {
this._provider = provider;
this._dummyTokenContracts = [];
this._tokenOwnerAddresses = tokenOwnerAddresses;
this._contractOwnerAddress = contractOwnerAddress;
}
public async deployDummyTokensAsync(): Promise<DummyERC721TokenContract[]> {
// tslint:disable-next-line:no-unused-variable
for (const i of _.times(constants.NUM_DUMMY_ERC721_TO_DEPLOY)) {
this._dummyTokenContracts.push(
await DummyERC721TokenContract.deployFrom0xArtifactAsync(
erc721Artifacts.DummyERC721Token,
this._provider,
txDefaults,
artifacts,
constants.DUMMY_TOKEN_NAME,
constants.DUMMY_TOKEN_SYMBOL,
),
);
}
return this._dummyTokenContracts;
}
public async deployProxyAsync(): Promise<ERC721ProxyContract> {
this._proxyContract = await ERC721ProxyContract.deployFrom0xArtifactAsync(
artifacts.ERC721Proxy,
this._provider,
txDefaults,
artifacts,
);
this._proxyIdIfExists = await this._proxyContract.getProxyId.callAsync();
return this._proxyContract;
}
public getProxyId(): string {
this._validateProxyContractExistsOrThrow();
return this._proxyIdIfExists as string;
}
public async setBalancesAndAllowancesAsync(): Promise<void> {
this._validateDummyTokenContractsExistOrThrow();
this._validateProxyContractExistsOrThrow();
this._initialTokenIdsByOwner = {};
for (const dummyTokenContract of this._dummyTokenContracts) {
for (const tokenOwnerAddress of this._tokenOwnerAddresses) {
// tslint:disable-next-line:no-unused-variable
for (const i of _.times(constants.NUM_ERC721_TOKENS_TO_MINT)) {
const tokenId = generatePseudoRandomSalt();
await this.mintAsync(dummyTokenContract.address, tokenId, tokenOwnerAddress);
if (this._initialTokenIdsByOwner[tokenOwnerAddress] === undefined) {
this._initialTokenIdsByOwner[tokenOwnerAddress] = {
[dummyTokenContract.address]: [],
};
}
if (this._initialTokenIdsByOwner[tokenOwnerAddress][dummyTokenContract.address] === undefined) {
this._initialTokenIdsByOwner[tokenOwnerAddress][dummyTokenContract.address] = [];
}
this._initialTokenIdsByOwner[tokenOwnerAddress][dummyTokenContract.address].push(tokenId);
await this.approveProxyAsync(dummyTokenContract.address, tokenId);
}
}
}
}
public async doesTokenExistAsync(tokenAddress: string, tokenId: BigNumber): Promise<boolean> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const owner = await tokenContract.ownerOf.callAsync(tokenId);
const doesExist = owner !== constants.NULL_ADDRESS;
return doesExist;
}
public async approveProxyAsync(tokenAddress: string, tokenId: BigNumber): Promise<void> {
const proxyAddress = (this._proxyContract as ERC721ProxyContract).address;
await this.approveAsync(proxyAddress, tokenAddress, tokenId);
}
public async approveProxyForAllAsync(tokenAddress: string, tokenId: BigNumber, isApproved: boolean): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const tokenOwner = await this.ownerOfAsync(tokenAddress, tokenId);
const proxyAddress = (this._proxyContract as ERC721ProxyContract).address;
await tokenContract.setApprovalForAll.awaitTransactionSuccessAsync(
proxyAddress,
isApproved,
{ from: tokenOwner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
}
public async approveAsync(to: string, tokenAddress: string, tokenId: BigNumber): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const tokenOwner = await this.ownerOfAsync(tokenAddress, tokenId);
await tokenContract.approve.awaitTransactionSuccessAsync(
to,
tokenId,
{ from: tokenOwner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
}
public async transferFromAsync(
tokenAddress: string,
tokenId: BigNumber,
currentOwner: string,
userAddress: string,
): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
await tokenContract.transferFrom.awaitTransactionSuccessAsync(
currentOwner,
userAddress,
tokenId,
{ from: currentOwner },
constants.AWAIT_TRANSACTION_MINED_MS,
);
}
public async mintAsync(tokenAddress: string, tokenId: BigNumber, userAddress: string): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
await tokenContract.mint.awaitTransactionSuccessAsync(
userAddress,
tokenId,
{ from: this._contractOwnerAddress },
constants.AWAIT_TRANSACTION_MINED_MS,
);
}
public async burnAsync(tokenAddress: string, tokenId: BigNumber, owner: string): Promise<void> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
await tokenContract.burn.awaitTransactionSuccessAsync(
owner,
tokenId,
{ from: this._contractOwnerAddress },
constants.AWAIT_TRANSACTION_MINED_MS,
);
}
public async ownerOfAsync(tokenAddress: string, tokenId: BigNumber): Promise<string> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const owner = await tokenContract.ownerOf.callAsync(tokenId);
return owner;
}
public async isOwnerAsync(userAddress: string, tokenAddress: string, tokenId: BigNumber): Promise<boolean> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const tokenOwner = await tokenContract.ownerOf.callAsync(tokenId);
const isOwner = tokenOwner === userAddress;
return isOwner;
}
public async isProxyApprovedForAllAsync(userAddress: string, tokenAddress: string): Promise<boolean> {
this._validateProxyContractExistsOrThrow();
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const operator = (this._proxyContract as ERC721ProxyContract).address;
const didApproveAll = await tokenContract.isApprovedForAll.callAsync(userAddress, operator);
return didApproveAll;
}
public async isProxyApprovedAsync(tokenAddress: string, tokenId: BigNumber): Promise<boolean> {
this._validateProxyContractExistsOrThrow();
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const approvedAddress = await tokenContract.getApproved.callAsync(tokenId);
const proxyAddress = (this._proxyContract as ERC721ProxyContract).address;
const isProxyAnApprovedOperator = approvedAddress === proxyAddress;
return isProxyAnApprovedOperator;
}
public async getBalancesAsync(): Promise<ERC721TokenIdsByOwner> {
this._validateDummyTokenContractsExistOrThrow();
this._validateBalancesAndAllowancesSetOrThrow();
const tokenIdsByOwner: ERC721TokenIdsByOwner = {};
const tokenOwnerAddresses: string[] = [];
const tokenInfo: Array<{ tokenId: BigNumber; tokenAddress: string }> = [];
for (const dummyTokenContract of this._dummyTokenContracts) {
for (const tokenOwnerAddress of this._tokenOwnerAddresses) {
const initialTokenOwnerIds = this._initialTokenIdsByOwner[tokenOwnerAddress][
dummyTokenContract.address
];
for (const tokenId of initialTokenOwnerIds) {
tokenOwnerAddresses.push(await dummyTokenContract.ownerOf.callAsync(tokenId));
tokenInfo.push({
tokenId,
tokenAddress: dummyTokenContract.address,
});
}
}
}
_.forEach(tokenOwnerAddresses, (tokenOwnerAddress, ownerIndex) => {
const tokenAddress = tokenInfo[ownerIndex].tokenAddress;
const tokenId = tokenInfo[ownerIndex].tokenId;
if (tokenIdsByOwner[tokenOwnerAddress] === undefined) {
tokenIdsByOwner[tokenOwnerAddress] = {
[tokenAddress]: [],
};
}
if (tokenIdsByOwner[tokenOwnerAddress][tokenAddress] === undefined) {
tokenIdsByOwner[tokenOwnerAddress][tokenAddress] = [];
}
tokenIdsByOwner[tokenOwnerAddress][tokenAddress].push(tokenId);
});
return tokenIdsByOwner;
}
public getTokenOwnerAddresses(): string[] {
return this._tokenOwnerAddresses;
}
public getTokenAddresses(): string[] {
const tokenAddresses = _.map(this._dummyTokenContracts, dummyTokenContract => dummyTokenContract.address);
return tokenAddresses;
}
private _getTokenContractFromAssetData(tokenAddress: string): DummyERC721TokenContract {
const tokenContractIfExists = _.find(this._dummyTokenContracts, c => c.address === tokenAddress);
if (tokenContractIfExists === undefined) {
throw new Error(`Token: ${tokenAddress} was not deployed through ERC20Wrapper`);
}
return tokenContractIfExists;
}
private _validateDummyTokenContractsExistOrThrow(): void {
if (this._dummyTokenContracts === undefined) {
throw new Error('Dummy ERC721 tokens not yet deployed, please call "deployDummyTokensAsync"');
}
}
private _validateProxyContractExistsOrThrow(): void {
if (this._proxyContract === undefined) {
throw new Error('ERC721 proxy contract not yet deployed, please call "deployProxyAsync"');
}
}
private _validateBalancesAndAllowancesSetOrThrow(): void {
if (_.keys(this._initialTokenIdsByOwner).length === 0) {
throw new Error(
'Dummy ERC721 balances and allowances not yet set, please call "setBalancesAndAllowancesAsync"',
);
}
}
}

View File

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

View File

@@ -0,0 +1,18 @@
{
"extends": "../../tsconfig",
"compilerOptions": { "outDir": "lib", "rootDir": ".", "resolveJsonModule": true },
"include": ["./src/**/*", "./test/**/*", "./generated-wrappers/**/*"],
"files": [
"generated-artifacts/ERC1155Proxy.json",
"generated-artifacts/ERC20Proxy.json",
"generated-artifacts/ERC721Proxy.json",
"generated-artifacts/IAssetData.json",
"generated-artifacts/IAssetProxy.json",
"generated-artifacts/IAuthorizable.json",
"generated-artifacts/MixinAuthorizable.json",
"generated-artifacts/MultiAssetProxy.json",
"generated-artifacts/StaticCallProxy.json",
"generated-artifacts/TestStaticCallTarget.json"
],
"exclude": ["./deploy/solc/solc_bin"]
}

View File

@@ -0,0 +1,6 @@
{
"extends": ["@0x/tslint-config"],
"rules": {
"custom-no-magic-numbers": false
}
}

View File

@@ -0,0 +1,156 @@
[
{
"timestamp": 1567521715,
"version": "2.0.12",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1566446343,
"version": "2.0.11",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1565296576,
"version": "2.0.10",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "2.0.9",
"changes": [
{
"note": "Updated calls to <contract wrapper>.deployFrom0xArtifactAsync to include artifact dependencies.",
"pr": 1995
}
],
"timestamp": 1564607468
},
{
"timestamp": 1563957393,
"version": "2.0.8",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1563193019,
"version": "2.0.7",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1563047529,
"version": "2.0.6",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1563006338,
"version": "2.0.5",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1558712885,
"version": "2.0.4",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1557961111,
"version": "2.0.3",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1557799313,
"version": "2.0.2",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1557507213,
"version": "2.0.1",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"version": "2.0.0",
"changes": [
{
"note": "Make `decodeOrdersFromFillData`, `getCoordinatorApprovalHash`, and `getTransactionHash` public",
"pr": 1729
},
{
"note": "Make `assertValidTransactionOrdersApproval` internal",
"pr": 1729
}
],
"timestamp": 1554997931
},
{
"version": "1.1.0",
"changes": [
{
"note": "Run Web3ProviderEngine without excess block polling",
"pr": 1695
}
],
"timestamp": 1553183790
},
{
"version": "1.0.0",
"changes": [
{
"note": "Created Coordinator package"
},
{
"note": "Use separate EIP712 domains for transactions and approvals",
"pr": 1705
},
{
"note": "Add `SignatureType.Invalid`",
"pr": 1705
},
{
"note": "Set `evmVersion` to `constantinople`",
"pr": 1707
}
],
"timestamp": 1553091633
}
]

View File

@@ -0,0 +1,70 @@
<!--
changelogUtils.file is auto-generated using the monorepo-scripts package. Don't edit directly.
Edit the package's CHANGELOG.json file only.
-->
CHANGELOG
## v2.0.12 - _September 3, 2019_
* Dependencies updated
## v2.0.11 - _August 22, 2019_
* Dependencies updated
## v2.0.10 - _August 8, 2019_
* Dependencies updated
## v2.0.9 - _July 31, 2019_
* Updated calls to <contract wrapper>.deployFrom0xArtifactAsync to include artifact dependencies. (#1995)
## v2.0.8 - _July 24, 2019_
* Dependencies updated
## v2.0.7 - _July 15, 2019_
* Dependencies updated
## v2.0.6 - _July 13, 2019_
* Dependencies updated
## v2.0.5 - _July 13, 2019_
* Dependencies updated
## v2.0.4 - _May 24, 2019_
* Dependencies updated
## v2.0.3 - _May 15, 2019_
* Dependencies updated
## v2.0.2 - _May 14, 2019_
* Dependencies updated
## v2.0.1 - _May 10, 2019_
* Dependencies updated
## v2.0.0 - _April 11, 2019_
* Make `decodeOrdersFromFillData`, `getCoordinatorApprovalHash`, and `getTransactionHash` public (#1729)
* Make `assertValidTransactionOrdersApproval` internal (#1729)
## v1.1.0 - _March 21, 2019_
* Run Web3ProviderEngine without excess block polling (#1695)
## v1.0.0 - _March 20, 2019_
* Created Coordinator package
* Use separate EIP712 domains for transactions and approvals (#1705)
* Add `SignatureType.Invalid` (#1705)
* Set `evmVersion` to `constantinople` (#1707)

View File

@@ -0,0 +1,73 @@
## Coordinator
This package contains a contract that allows users to call arbitrary functions on the Exchange contract with permission from one or more Coordinators. Addresses of the deployed contracts can be found in this 0x [guide](https://0x.org/docs/guides/0x-cheat-sheet) or the [DEPLOYS](./DEPLOYS.json) file within this package.
## Installation
**Install**
```bash
npm install @0x/contracts-coordinator --save
```
## Bug bounty
A bug bounty for the 2.0.0 contracts is ongoing! Instructions can be found [here](https://0x.org/docs/guides/bug-bounty-program).
## 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.
For proposals regarding the 0x protocol's smart contract architecture, message format, or additional functionality, go to the [0x Improvement Proposals (ZEIPs)](https://github.com/0xProject/ZEIPs) repository and follow the contribution guidelines provided therein.
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
### Install Dependencies
If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them:
```bash
yarn config set workspaces-experimental true
```
Then install dependencies
```bash
yarn install
```
### Build
To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory:
```bash
PKG=@0x/contracts-coordinator yarn build
```
Or continuously rebuild on change:
```bash
PKG=@0x/contracts-coordinator yarn watch
```
### Clean
```bash
yarn clean
```
### Lint
```bash
yarn lint
```
### Run Tests
```bash
yarn test
```
#### Testing options
Contracts testing options like coverage, profiling, revert traces or backing node choosing - are described [here](../TESTING.md).

View File

@@ -0,0 +1,26 @@
{
"artifactsDir": "./generated-artifacts",
"contractsDir": "./contracts",
"useDockerisedSolc": false,
"compilerSettings": {
"evmVersion": "constantinople",
"optimizer": {
"enabled": true,
"runs": 1000000,
"details": { "yul": true, "deduplicate": true, "cse": true, "constantOptimizer": true }
},
"outputSelection": {
"*": {
"*": [
"abi",
"devdoc",
"evm.bytecode.object",
"evm.bytecode.sourceMap",
"evm.deployedBytecode.object",
"evm.deployedBytecode.sourceMap"
]
}
}
},
"contracts": ["src/Coordinator.sol", "src/registry/CoordinatorRegistry.sol"]
}

View File

@@ -0,0 +1,39 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental "ABIEncoderV2";
import "./libs/LibConstants.sol";
import "./MixinSignatureValidator.sol";
import "./MixinCoordinatorApprovalVerifier.sol";
import "./MixinCoordinatorCore.sol";
// solhint-disable no-empty-blocks
contract Coordinator is
LibConstants,
MixinSignatureValidator,
MixinCoordinatorApprovalVerifier,
MixinCoordinatorCore
{
constructor (address _exchange)
public
LibConstants(_exchange)
{}
}

View File

@@ -0,0 +1,203 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental "ABIEncoderV2";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeSelectors.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibAddressArray.sol";
import "./libs/LibCoordinatorApproval.sol";
import "./libs/LibZeroExTransaction.sol";
import "./mixins/MSignatureValidator.sol";
import "./mixins/MCoordinatorApprovalVerifier.sol";
// solhint-disable avoid-tx-origin
contract MixinCoordinatorApprovalVerifier is
LibExchangeSelectors,
LibCoordinatorApproval,
LibZeroExTransaction,
MSignatureValidator,
MCoordinatorApprovalVerifier
{
using LibBytes for bytes;
using LibAddressArray for address[];
/// @dev Validates that the 0x transaction has been approved by all of the feeRecipients
/// that correspond to each order in the transaction's Exchange calldata.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param txOrigin Required signer of Ethereum transaction calling this function.
/// @param transactionSignature Proof that the transaction has been signed by the signer.
/// @param approvalExpirationTimeSeconds Array of expiration times in seconds for which each corresponding approval signature expires.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each order in the transaction's Exchange calldata.
function assertValidCoordinatorApprovals(
LibZeroExTransaction.ZeroExTransaction memory transaction,
address txOrigin,
bytes memory transactionSignature,
uint256[] memory approvalExpirationTimeSeconds,
bytes[] memory approvalSignatures
)
public
view
{
// Get the orders from the the Exchange calldata in the 0x transaction
LibOrder.Order[] memory orders = decodeOrdersFromFillData(transaction.data);
// No approval is required for non-fill methods
if (orders.length > 0) {
// Revert if approval is invalid for transaction orders
assertValidTransactionOrdersApproval(
transaction,
orders,
txOrigin,
transactionSignature,
approvalExpirationTimeSeconds,
approvalSignatures
);
}
}
/// @dev Decodes the orders from Exchange calldata representing any fill method.
/// @param data Exchange calldata representing a fill method.
/// @return The orders from the Exchange calldata.
function decodeOrdersFromFillData(bytes memory data)
public
pure
returns (LibOrder.Order[] memory orders)
{
bytes4 selector = data.readBytes4(0);
if (
selector == FILL_ORDER_SELECTOR ||
selector == FILL_ORDER_NO_THROW_SELECTOR ||
selector == FILL_OR_KILL_ORDER_SELECTOR
) {
// Decode single order
(LibOrder.Order memory order) = abi.decode(
data.slice(4, data.length),
(LibOrder.Order)
);
orders = new LibOrder.Order[](1);
orders[0] = order;
} else if (
selector == BATCH_FILL_ORDERS_SELECTOR ||
selector == BATCH_FILL_ORDERS_NO_THROW_SELECTOR ||
selector == BATCH_FILL_OR_KILL_ORDERS_SELECTOR ||
selector == MARKET_BUY_ORDERS_SELECTOR ||
selector == MARKET_BUY_ORDERS_NO_THROW_SELECTOR ||
selector == MARKET_SELL_ORDERS_SELECTOR ||
selector == MARKET_SELL_ORDERS_NO_THROW_SELECTOR
) {
// Decode all orders
// solhint-disable indent
(orders) = abi.decode(
data.slice(4, data.length),
(LibOrder.Order[])
);
} else if (selector == MATCH_ORDERS_SELECTOR) {
// Decode left and right orders
(LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder) = abi.decode(
data.slice(4, data.length),
(LibOrder.Order, LibOrder.Order)
);
// Create array of orders
orders = new LibOrder.Order[](2);
orders[0] = leftOrder;
orders[1] = rightOrder;
}
return orders;
}
/// @dev Validates that the feeRecipients of a batch of order have approved a 0x transaction.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param orders Array of order structs containing order specifications.
/// @param txOrigin Required signer of Ethereum transaction calling this function.
/// @param transactionSignature Proof that the transaction has been signed by the signer.
/// @param approvalExpirationTimeSeconds Array of expiration times in seconds for which each corresponding approval signature expires.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each order.
function assertValidTransactionOrdersApproval(
LibZeroExTransaction.ZeroExTransaction memory transaction,
LibOrder.Order[] memory orders,
address txOrigin,
bytes memory transactionSignature,
uint256[] memory approvalExpirationTimeSeconds,
bytes[] memory approvalSignatures
)
internal
view
{
// Verify that Ethereum tx signer is the same as the approved txOrigin
require(
tx.origin == txOrigin,
"INVALID_ORIGIN"
);
// Hash 0x transaction
bytes32 transactionHash = getTransactionHash(transaction);
// Create empty list of approval signers
address[] memory approvalSignerAddresses = new address[](0);
uint256 signaturesLength = approvalSignatures.length;
for (uint256 i = 0; i != signaturesLength; i++) {
// Create approval message
uint256 currentApprovalExpirationTimeSeconds = approvalExpirationTimeSeconds[i];
CoordinatorApproval memory approval = CoordinatorApproval({
txOrigin: txOrigin,
transactionHash: transactionHash,
transactionSignature: transactionSignature,
approvalExpirationTimeSeconds: currentApprovalExpirationTimeSeconds
});
// Ensure approval has not expired
require(
// solhint-disable-next-line not-rely-on-time
currentApprovalExpirationTimeSeconds > block.timestamp,
"APPROVAL_EXPIRED"
);
// Hash approval message and recover signer address
bytes32 approvalHash = getCoordinatorApprovalHash(approval);
address approvalSignerAddress = getSignerAddress(approvalHash, approvalSignatures[i]);
// Add approval signer to list of signers
approvalSignerAddresses = approvalSignerAddresses.append(approvalSignerAddress);
}
// Ethereum transaction signer gives implicit signature of approval
approvalSignerAddresses = approvalSignerAddresses.append(tx.origin);
uint256 ordersLength = orders.length;
for (uint256 i = 0; i != ordersLength; i++) {
// Do not check approval if the order's senderAddress is null
if (orders[i].senderAddress == address(0)) {
continue;
}
// Ensure feeRecipient of order has approved this 0x transaction
address approverAddress = orders[i].feeRecipientAddress;
bool isOrderApproved = approvalSignerAddresses.contains(approverAddress);
require(
isOrderApproved,
"INVALID_APPROVAL_SIGNATURE"
);
}
}
}

View File

@@ -0,0 +1,65 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental "ABIEncoderV2";
import "./libs/LibZeroExTransaction.sol";
import "./libs/LibConstants.sol";
import "./mixins/MCoordinatorApprovalVerifier.sol";
import "./interfaces/ICoordinatorCore.sol";
contract MixinCoordinatorCore is
LibConstants,
MCoordinatorApprovalVerifier,
ICoordinatorCore
{
/// @dev Executes a 0x transaction that has been signed by the feeRecipients that correspond to each order in the transaction's Exchange calldata.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param txOrigin Required signer of Ethereum transaction calling this function.
/// @param transactionSignature Proof that the transaction has been signed by the signer.
/// @param approvalExpirationTimeSeconds Array of expiration times in seconds for which each corresponding approval signature expires.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each order in the transaction's Exchange calldata.
function executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
address txOrigin,
bytes memory transactionSignature,
uint256[] memory approvalExpirationTimeSeconds,
bytes[] memory approvalSignatures
)
public
{
// Validate that the 0x transaction has been approves by each feeRecipient
assertValidCoordinatorApprovals(
transaction,
txOrigin,
transactionSignature,
approvalExpirationTimeSeconds,
approvalSignatures
);
// Execute the transaction
EXCHANGE.executeTransaction(
transaction.salt,
transaction.signerAddress,
transaction.data,
transactionSignature
);
}
}

View File

@@ -0,0 +1,118 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "./mixins/MSignatureValidator.sol";
contract MixinSignatureValidator is
MSignatureValidator
{
using LibBytes for bytes;
/// @dev Recovers the address of a signer given a hash and signature.
/// @param hash Any 32 byte hash.
/// @param signature Proof that the hash has been signed by signer.
function getSignerAddress(bytes32 hash, bytes memory signature)
public
pure
returns (address signerAddress)
{
require(
signature.length > 0,
"LENGTH_GREATER_THAN_0_REQUIRED"
);
// Pop last byte off of signature byte array.
uint8 signatureTypeRaw = uint8(signature.popLastByte());
// Ensure signature is supported
require(
signatureTypeRaw < uint8(SignatureType.NSignatureTypes),
"SIGNATURE_UNSUPPORTED"
);
SignatureType signatureType = SignatureType(signatureTypeRaw);
// Always illegal signature.
// This is always an implicit option since a signer can create a
// signature array with invalid type or length. We may as well make
// it an explicit option. This aids testing and analysis. It is
// also the initialization value for the enum type.
if (signatureType == SignatureType.Illegal) {
revert("SIGNATURE_ILLEGAL");
// Always invalid signature.
// Like Illegal, this is always implicitly available and therefore
// offered explicitly. It can be implicitly created by providing
// a correctly formatted but incorrect signature.
} else if (signatureType == SignatureType.Invalid) {
require(
signature.length == 0,
"LENGTH_0_REQUIRED"
);
revert("SIGNATURE_INVALID");
// Signature using EIP712
} else if (signatureType == SignatureType.EIP712) {
require(
signature.length == 65,
"LENGTH_65_REQUIRED"
);
uint8 v = uint8(signature[0]);
bytes32 r = signature.readBytes32(1);
bytes32 s = signature.readBytes32(33);
signerAddress = ecrecover(
hash,
v,
r,
s
);
return signerAddress;
// Signed using web3.eth_sign
} else if (signatureType == SignatureType.EthSign) {
require(
signature.length == 65,
"LENGTH_65_REQUIRED"
);
uint8 v = uint8(signature[0]);
bytes32 r = signature.readBytes32(1);
bytes32 s = signature.readBytes32(33);
signerAddress = ecrecover(
keccak256(abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
hash
)),
v,
r,
s
);
return signerAddress;
}
// Anything else is illegal (We do not return false because
// the signature may actually be valid, just not in a format
// that we currently support. In this case returning false
// may lead the caller to incorrectly believe that the
// signature was invalid.)
revert("SIGNATURE_UNSUPPORTED");
}
}

View File

@@ -0,0 +1,52 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental "ABIEncoderV2";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "../libs/LibZeroExTransaction.sol";
contract ICoordinatorApprovalVerifier {
/// @dev Validates that the 0x transaction has been approved by all of the feeRecipients
/// that correspond to each order in the transaction's Exchange calldata.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param txOrigin Required signer of Ethereum transaction calling this function.
/// @param transactionSignature Proof that the transaction has been signed by the signer.
/// @param approvalExpirationTimeSeconds Array of expiration times in seconds for which each corresponding approval signature expires.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each order in the transaction's Exchange calldata.
function assertValidCoordinatorApprovals(
LibZeroExTransaction.ZeroExTransaction memory transaction,
address txOrigin,
bytes memory transactionSignature,
uint256[] memory approvalExpirationTimeSeconds,
bytes[] memory approvalSignatures
)
public
view;
/// @dev Decodes the orders from Exchange calldata representing any fill method.
/// @param data Exchange calldata representing a fill method.
/// @return The orders from the Exchange calldata.
function decodeOrdersFromFillData(bytes memory data)
public
pure
returns (LibOrder.Order[] memory orders);
}

View File

@@ -0,0 +1,41 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental "ABIEncoderV2";
import "../libs/LibZeroExTransaction.sol";
contract ICoordinatorCore {
/// @dev Executes a 0x transaction that has been signed by the feeRecipients that correspond to each order in the transaction's Exchange calldata.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param txOrigin Required signer of Ethereum transaction calling this function.
/// @param transactionSignature Proof that the transaction has been signed by the signer.
/// @param approvalExpirationTimeSeconds Array of expiration times in seconds for which each corresponding approval signature expires.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each order in the transaction's Exchange calldata.
function executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
address txOrigin,
bytes memory transactionSignature,
uint256[] memory approvalExpirationTimeSeconds,
bytes[] memory approvalSignatures
)
public;
}

View File

@@ -0,0 +1,31 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
contract ISignatureValidator {
/// @dev Recovers the address of a signer given a hash and signature.
/// @param hash Any 32 byte hash.
/// @param signature Proof that the hash has been signed by signer.
function getSignerAddress(bytes32 hash, bytes memory signature)
public
pure
returns (address signerAddress);
}

View File

@@ -0,0 +1,35 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
contract ITransactions {
/// @dev Executes an exchange method call in the context of signer.
/// @param salt Arbitrary number to ensure uniqueness of transaction hash.
/// @param signerAddress Address of transaction signer.
/// @param data AbiV2 encoded calldata.
/// @param signature Proof of signer transaction by signer.
function executeTransaction(
uint256 salt,
address signerAddress,
bytes calldata data,
bytes calldata signature
)
external;
}

View File

@@ -0,0 +1,34 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "../interfaces/ITransactions.sol";
contract LibConstants {
// solhint-disable-next-line var-name-mixedcase
ITransactions internal EXCHANGE;
constructor (address _exchange)
public
{
EXCHANGE = ITransactions(_exchange);
}
}

View File

@@ -0,0 +1,98 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental "ABIEncoderV2";
import "./LibEIP712Domain.sol";
contract LibCoordinatorApproval is
LibEIP712Domain
{
// Hash for the EIP712 Coordinator approval message
// keccak256(abi.encodePacked(
// "CoordinatorApproval(",
// "address txOrigin,",
// "bytes32 transactionHash,",
// "bytes transactionSignature,",
// "uint256 approvalExpirationTimeSeconds",
// ")"
// ));
bytes32 constant internal EIP712_COORDINATOR_APPROVAL_SCHEMA_HASH = 0x2fbcdbaa76bc7589916958ae919dfbef04d23f6bbf26de6ff317b32c6cc01e05;
struct CoordinatorApproval {
address txOrigin; // Required signer of Ethereum transaction that is submitting approval.
bytes32 transactionHash; // EIP712 hash of the transaction.
bytes transactionSignature; // Signature of the 0x transaction.
uint256 approvalExpirationTimeSeconds; // Timestamp in seconds for which the approval expires.
}
/// @dev Calculated the EIP712 hash of the Coordinator approval mesasage using the domain separator of this contract.
/// @param approval Coordinator approval message containing the transaction hash, transaction signature, and expiration of the approval.
/// @return EIP712 hash of the Coordinator approval message with the domain separator of this contract.
function getCoordinatorApprovalHash(CoordinatorApproval memory approval)
public
view
returns (bytes32 approvalHash)
{
approvalHash = hashEIP712CoordinatorMessage(hashCoordinatorApproval(approval));
return approvalHash;
}
/// @dev Calculated the EIP712 hash of the Coordinator approval mesasage with no domain separator.
/// @param approval Coordinator approval message containing the transaction hash, transaction signature, and expiration of the approval.
/// @return EIP712 hash of the Coordinator approval message with no domain separator.
function hashCoordinatorApproval(CoordinatorApproval memory approval)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = EIP712_COORDINATOR_APPROVAL_SCHEMA_HASH;
bytes memory transactionSignature = approval.transactionSignature;
address txOrigin = approval.txOrigin;
bytes32 transactionHash = approval.transactionHash;
uint256 approvalExpirationTimeSeconds = approval.approvalExpirationTimeSeconds;
// Assembly for more efficiently computing:
// keccak256(abi.encodePacked(
// EIP712_COORDINATOR_APPROVAL_SCHEMA_HASH,
// approval.txOrigin,
// approval.transactionHash,
// keccak256(approval.transactionSignature)
// approval.approvalExpirationTimeSeconds,
// ));
assembly {
// Compute hash of transaction signature
let transactionSignatureHash := keccak256(add(transactionSignature, 32), mload(transactionSignature))
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, schemaHash) // hash of schema
mstore(add(memPtr, 32), txOrigin) // txOrigin
mstore(add(memPtr, 64), transactionHash) // transactionHash
mstore(add(memPtr, 96), transactionSignatureHash) // transactionSignatureHash
mstore(add(memPtr, 128), approvalExpirationTimeSeconds) // approvalExpirationTimeSeconds
// Compute hash
result := keccak256(memPtr, 160)
}
return result;
}
}

View File

@@ -0,0 +1,131 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "./LibConstants.sol";
contract LibEIP712Domain is
LibConstants
{
// EIP191 header for EIP712 prefix
string constant internal EIP191_HEADER = "\x19\x01";
// EIP712 Domain Name value for the Coordinator
string constant internal EIP712_COORDINATOR_DOMAIN_NAME = "0x Protocol Coordinator";
// EIP712 Domain Version value for the Coordinator
string constant internal EIP712_COORDINATOR_DOMAIN_VERSION = "1.0.0";
// EIP712 Domain Name value for the Exchange
string constant internal EIP712_EXCHANGE_DOMAIN_NAME = "0x Protocol";
// EIP712 Domain Version value for the Exchange
string constant internal EIP712_EXCHANGE_DOMAIN_VERSION = "2";
// Hash of the EIP712 Domain Separator Schema
bytes32 constant internal EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256(abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"address verifyingContract",
")"
));
// Hash of the EIP712 Domain Separator data for the Coordinator
// solhint-disable-next-line var-name-mixedcase
bytes32 public EIP712_COORDINATOR_DOMAIN_HASH;
// Hash of the EIP712 Domain Separator data for the Exchange
// solhint-disable-next-line var-name-mixedcase
bytes32 public EIP712_EXCHANGE_DOMAIN_HASH;
constructor ()
public
{
EIP712_COORDINATOR_DOMAIN_HASH = keccak256(abi.encodePacked(
EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
keccak256(bytes(EIP712_COORDINATOR_DOMAIN_NAME)),
keccak256(bytes(EIP712_COORDINATOR_DOMAIN_VERSION)),
uint256(address(this))
));
EIP712_EXCHANGE_DOMAIN_HASH = keccak256(abi.encodePacked(
EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
keccak256(bytes(EIP712_EXCHANGE_DOMAIN_NAME)),
keccak256(bytes(EIP712_EXCHANGE_DOMAIN_VERSION)),
uint256(address(EXCHANGE))
));
}
/// @dev Calculates EIP712 encoding for a hash struct in the EIP712 domain
/// of this contract.
/// @param hashStruct The EIP712 hash struct.
/// @return EIP712 hash applied to this EIP712 Domain.
function hashEIP712CoordinatorMessage(bytes32 hashStruct)
internal
view
returns (bytes32 result)
{
return hashEIP712Message(EIP712_COORDINATOR_DOMAIN_HASH, hashStruct);
}
/// @dev Calculates EIP712 encoding for a hash struct in the EIP712 domain
/// of the Exchange contract.
/// @param hashStruct The EIP712 hash struct.
/// @return EIP712 hash applied to the Exchange EIP712 Domain.
function hashEIP712ExchangeMessage(bytes32 hashStruct)
internal
view
returns (bytes32 result)
{
return hashEIP712Message(EIP712_EXCHANGE_DOMAIN_HASH, hashStruct);
}
/// @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
/// @param eip712DomainHash Hash of the domain domain separator data.
/// @param hashStruct The EIP712 hash struct.
/// @return EIP712 hash applied to the Exchange EIP712 Domain.
function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct)
internal
pure
returns (bytes32 result)
{
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}

View File

@@ -0,0 +1,95 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental "ABIEncoderV2";
import "./LibEIP712Domain.sol";
contract LibZeroExTransaction is
LibEIP712Domain
{
// Hash for the EIP712 0x transaction schema
// keccak256(abi.encodePacked(
// "ZeroExTransaction(",
// "uint256 salt,",
// "address signerAddress,",
// "bytes data",
// ")"
// ));
bytes32 constant internal EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = 0x213c6f636f3ea94e701c0adf9b2624aa45a6c694f9a292c094f9a81c24b5df4c;
struct ZeroExTransaction {
uint256 salt; // Arbitrary number to ensure uniqueness of transaction hash.
address signerAddress; // Address of transaction signer.
bytes data; // AbiV2 encoded calldata.
}
/// @dev Calculates the EIP712 hash of a 0x transaction using the domain separator of the Exchange contract.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @return EIP712 hash of the transaction with the domain separator of this contract.
function getTransactionHash(ZeroExTransaction memory transaction)
public
view
returns (bytes32 transactionHash)
{
// Hash the transaction with the domain separator of the Exchange contract.
transactionHash = hashEIP712ExchangeMessage(hashZeroExTransaction(transaction));
return transactionHash;
}
/// @dev Calculates EIP712 hash of the 0x transaction with no domain separator.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @return EIP712 hash of the transaction with no domain separator.
function hashZeroExTransaction(ZeroExTransaction memory transaction)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH;
bytes memory data = transaction.data;
uint256 salt = transaction.salt;
address signerAddress = transaction.signerAddress;
// Assembly for more efficiently computing:
// keccak256(abi.encodePacked(
// EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH,
// transaction.salt,
// uint256(transaction.signerAddress),
// keccak256(transaction.data)
// ));
assembly {
// Compute hash of data
let dataHash := keccak256(add(data, 32), mload(data))
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, schemaHash) // hash of schema
mstore(add(memPtr, 32), salt) // salt
mstore(add(memPtr, 64), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress
mstore(add(memPtr, 96), dataHash) // hash of data
// Compute hash
result := keccak256(memPtr, 128)
}
return result;
}
}

View File

@@ -0,0 +1,46 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental "ABIEncoderV2";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "../interfaces/ICoordinatorApprovalVerifier.sol";
contract MCoordinatorApprovalVerifier is
ICoordinatorApprovalVerifier
{
/// @dev Validates that the feeRecipients of a batch of order have approved a 0x transaction.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param orders Array of order structs containing order specifications.
/// @param txOrigin Required signer of Ethereum transaction calling this function.
/// @param transactionSignature Proof that the transaction has been signed by the signer.
/// @param approvalExpirationTimeSeconds Array of expiration times in seconds for which each corresponding approval signature expires.
/// @param approvalSignatures Array of signatures that correspond to the feeRecipients of each order.
function assertValidTransactionOrdersApproval(
LibZeroExTransaction.ZeroExTransaction memory transaction,
LibOrder.Order[] memory orders,
address txOrigin,
bytes memory transactionSignature,
uint256[] memory approvalExpirationTimeSeconds,
bytes[] memory approvalSignatures
)
internal
view;
}

View File

@@ -0,0 +1,35 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "../interfaces/ISignatureValidator.sol";
contract MSignatureValidator is
ISignatureValidator
{
// Allowed signature types.
enum SignatureType {
Illegal, // 0x00, default value
Invalid, // 0x01
EIP712, // 0x02
EthSign, // 0x03
NSignatureTypes // 0x04, number of signature types. Always leave at end.
}
}

View File

@@ -0,0 +1,32 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "./MixinCoordinatorRegistryCore.sol";
// solhint-disable no-empty-blocks
contract CoordinatorRegistry is
MixinCoordinatorRegistryCore
{
constructor ()
public
MixinCoordinatorRegistryCore()
{}
}

View File

@@ -0,0 +1,48 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "./interfaces/ICoordinatorRegistryCore.sol";
// solhint-disable no-empty-blocks
contract MixinCoordinatorRegistryCore is
ICoordinatorRegistryCore
{
// mapping from `coordinatorOperator` -> `coordinatorEndpoint`
mapping (address => string) internal coordinatorEndpoints;
/// @dev Called by a Coordinator operator to set the endpoint of their Coordinator.
/// @param coordinatorEndpoint endpoint of the Coordinator.
function setCoordinatorEndpoint(string calldata coordinatorEndpoint) external {
address coordinatorOperator = msg.sender;
coordinatorEndpoints[coordinatorOperator] = coordinatorEndpoint;
emit CoordinatorEndpointSet(coordinatorOperator, coordinatorEndpoint);
}
/// @dev Gets the endpoint for a Coordinator.
/// @param coordinatorOperator operator of the Coordinator endpoint.
function getCoordinatorEndpoint(address coordinatorOperator)
external
view
returns (string memory coordinatorEndpoint)
{
return coordinatorEndpoints[coordinatorOperator];
}
}

View File

@@ -0,0 +1,41 @@
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
// solhint-disable no-empty-blocks
contract ICoordinatorRegistryCore
{
/// @dev Emitted when a Coordinator endpoint is set.
event CoordinatorEndpointSet(
address coordinatorOperator,
string coordinatorEndpoint
);
/// @dev Called by a Coordinator operator to set the endpoint of their Coordinator.
/// @param coordinatorEndpoint endpoint of the Coordinator.
function setCoordinatorEndpoint(string calldata coordinatorEndpoint) external;
/// @dev Gets the endpoint for a Coordinator.
/// @param coordinatorOperator operator of the Coordinator endpoint.
function getCoordinatorEndpoint(address coordinatorOperator)
external
view
returns (string memory coordinatorEndpoint);
}

View File

@@ -0,0 +1,90 @@
{
"name": "@0x/contracts-coordinator",
"version": "2.0.12",
"engines": {
"node": ">=6.12"
},
"description": "Smart contract extensions of 0x protocol",
"main": "lib/src/index.js",
"directories": {
"test": "test"
},
"scripts": {
"build": "yarn pre_build && tsc -b",
"build:ci": "yarn build",
"pre_build": "run-s compile generate_contract_wrappers",
"test": "yarn run_mocha",
"rebuild_and_test": "run-s build test",
"test:coverage": "SOLIDITY_COVERAGE=true run-s build run_mocha coverage:report:text coverage:report:lcov",
"test:profiler": "SOLIDITY_PROFILER=true run-s build run_mocha profiler:report:html",
"test:trace": "SOLIDITY_REVERT_TRACE=true run-s build run_mocha",
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe 'lib/test/**/*.js' --timeout 100000 --bail --exit",
"compile": "sol-compiler",
"watch": "sol-compiler -w",
"clean": "shx rm -rf lib generated-artifacts generated-wrappers",
"generate_contract_wrappers": "abi-gen --abis ${npm_package_config_abis} --output generated-wrappers --backend ethers",
"lint": "tslint --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"fix": "tslint --fix --format stylish --project . --exclude ./generated-wrappers/**/* --exclude ./generated-artifacts/**/* --exclude **/lib/**/* && yarn lint-contracts",
"coverage:report:text": "istanbul report text",
"coverage:report:html": "istanbul report html && open coverage/index.html",
"profiler:report:html": "istanbul report html && open coverage/index.html",
"coverage:report:lcov": "istanbul report lcov",
"test:circleci": "yarn test",
"contracts:gen": "contracts-gen",
"lint-contracts": "solhint -c ../.solhint.json contracts/**/**/**/**/*.sol"
},
"config": {
"abis": "./generated-artifacts/@(Coordinator|CoordinatorRegistry).json",
"abis:comment": "This list is auto-generated by contracts-gen. Don't edit manually."
},
"repository": {
"type": "git",
"url": "https://github.com/0xProject/0x-monorepo.git"
},
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/0xProject/0x-monorepo/issues"
},
"homepage": "https://github.com/0xProject/0x-monorepo/contracts/extensions/README.md",
"devDependencies": {
"@0x/abi-gen": "^4.2.0",
"@0x/contracts-gen": "^1.0.14",
"@0x/contracts-test-utils": "^3.1.15",
"@0x/dev-utils": "^2.3.2",
"@0x/sol-compiler": "^3.1.14",
"@0x/tslint-config": "^3.0.1",
"@types/lodash": "4.14.104",
"@types/mocha": "^5.2.7",
"@types/node": "*",
"chai": "^4.0.1",
"chai-as-promised": "^7.1.0",
"chai-bignumber": "^3.0.0",
"dirty-chai": "^2.0.1",
"make-promises-safe": "^1.1.0",
"mocha": "^6.2.0",
"npm-run-all": "^4.1.2",
"shx": "^0.2.2",
"solhint": "^1.4.1",
"tslint": "5.11.0",
"typescript": "3.0.1"
},
"dependencies": {
"@0x/base-contract": "^5.3.3",
"@0x/contracts-asset-proxy": "^2.2.7",
"@0x/contracts-erc20": "^2.2.13",
"@0x/contracts-exchange": "^2.1.13",
"@0x/contracts-exchange-libs": "^3.0.7",
"@0x/contracts-utils": "^3.2.3",
"@0x/order-utils": "^8.3.1",
"@0x/types": "^2.4.2",
"@0x/typescript-typings": "^4.2.5",
"@0x/utils": "^4.5.1",
"@0x/web3-wrapper": "^6.0.12",
"ethereum-types": "^2.1.5",
"ethereumjs-util": "^5.1.1",
"lodash": "^4.17.11"
},
"publishConfig": {
"access": "public"
}
}

View File

@@ -0,0 +1,13 @@
/*
* -----------------------------------------------------------------------------
* Warning: This file is auto-generated by contracts-gen. Don't edit manually.
* -----------------------------------------------------------------------------
*/
import { ContractArtifact } from 'ethereum-types';
import * as Coordinator from '../generated-artifacts/Coordinator.json';
import * as CoordinatorRegistry from '../generated-artifacts/CoordinatorRegistry.json';
export const artifacts = {
Coordinator: Coordinator as ContractArtifact,
CoordinatorRegistry: CoordinatorRegistry as ContractArtifact,
};

View File

@@ -0,0 +1,3 @@
export * from './artifacts';
export * from './wrappers';
export * from '../test/utils';

View File

@@ -0,0 +1,7 @@
/*
* -----------------------------------------------------------------------------
* Warning: This file is auto-generated by contracts-gen. Don't edit manually.
* -----------------------------------------------------------------------------
*/
export * from '../generated-wrappers/coordinator';
export * from '../generated-wrappers/coordinator_registry';

View File

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

View File

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

View File

@@ -0,0 +1,19 @@
import { env, EnvVars } from '@0x/dev-utils';
import { coverage, profiler, provider } from '@0x/contracts-test-utils';
import { providerUtils } from '@0x/utils';
before('start web3 provider', () => {
providerUtils.startProviderEngine(provider);
});
after('generate coverage report', async () => {
if (env.parseBoolean(EnvVars.SolidityCoverage)) {
const coverageSubprovider = coverage.getCoverageSubproviderSingleton();
await coverageSubprovider.writeCoverageAsync();
}
if (env.parseBoolean(EnvVars.SolidityProfiler)) {
const profilerSubprovider = profiler.getProfilerSubproviderSingleton();
await profilerSubprovider.writeProfilerOutputAsync();
}
provider.stop();
});

View File

@@ -0,0 +1,80 @@
import { addressUtils, chaiSetup, constants, provider, txDefaults, web3Wrapper } from '@0x/contracts-test-utils';
import { BlockchainLifecycle } from '@0x/dev-utils';
import { transactionHashUtils } from '@0x/order-utils';
import { BigNumber } from '@0x/utils';
import * as chai from 'chai';
import { artifacts, CoordinatorContract, hashUtils } from '../src';
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
describe('Libs tests', () => {
let coordinatorContract: CoordinatorContract;
const exchangeAddress = addressUtils.generatePseudoRandomAddress();
before(async () => {
await blockchainLifecycle.startAsync();
});
after(async () => {
await blockchainLifecycle.revertAsync();
});
before(async () => {
coordinatorContract = await CoordinatorContract.deployFrom0xArtifactAsync(
artifacts.Coordinator,
provider,
txDefaults,
artifacts,
exchangeAddress,
);
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('getTransactionHash', () => {
it('should return the correct transaction hash', async () => {
const tx = {
verifyingContractAddress: exchangeAddress,
salt: new BigNumber(0),
signerAddress: constants.NULL_ADDRESS,
data: '0x1234',
};
const expectedTxHash = transactionHashUtils.getTransactionHashHex(tx);
const txHash = await coordinatorContract.getTransactionHash.callAsync(tx);
expect(expectedTxHash).to.eq(txHash);
});
});
describe('getApprovalHash', () => {
it('should return the correct approval hash', async () => {
const signedTx = {
verifyingContractAddress: exchangeAddress,
salt: new BigNumber(0),
signerAddress: constants.NULL_ADDRESS,
data: '0x1234',
signature: '0x5678',
};
const approvalExpirationTimeSeconds = new BigNumber(0);
const txOrigin = constants.NULL_ADDRESS;
const approval = {
txOrigin,
transactionHash: transactionHashUtils.getTransactionHashHex(signedTx),
transactionSignature: signedTx.signature,
approvalExpirationTimeSeconds,
};
const expectedApprovalHash = hashUtils.getApprovalHashHex(
signedTx,
coordinatorContract.address,
txOrigin,
approvalExpirationTimeSeconds,
);
const approvalHash = await coordinatorContract.getCoordinatorApprovalHash.callAsync(approval);
expect(expectedApprovalHash).to.eq(approvalHash);
});
});
});

View File

@@ -0,0 +1,729 @@
import {
addressUtils,
chaiSetup,
constants as devConstants,
expectContractCallFailedAsync,
getLatestBlockTimestampAsync,
provider,
TransactionFactory,
txDefaults,
web3Wrapper,
} from '@0x/contracts-test-utils';
import { BlockchainLifecycle } from '@0x/dev-utils';
import { transactionHashUtils } from '@0x/order-utils';
import { RevertReason, SignatureType, SignedOrder } from '@0x/types';
import { BigNumber } from '@0x/utils';
import * as chai from 'chai';
import * as ethUtil from 'ethereumjs-util';
import { ApprovalFactory, artifacts, constants, CoordinatorContract, exchangeDataEncoder } from '../src';
chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
describe('Mixins tests', () => {
let transactionSignerAddress: string;
let approvalSignerAddress1: string;
let approvalSignerAddress2: string;
let mixins: CoordinatorContract;
let transactionFactory: TransactionFactory;
let approvalFactory1: ApprovalFactory;
let approvalFactory2: ApprovalFactory;
let defaultOrder: SignedOrder;
const exchangeAddress = addressUtils.generatePseudoRandomAddress();
before(async () => {
await blockchainLifecycle.startAsync();
});
after(async () => {
await blockchainLifecycle.revertAsync();
});
before(async () => {
mixins = await CoordinatorContract.deployFrom0xArtifactAsync(
artifacts.Coordinator,
provider,
txDefaults,
artifacts,
exchangeAddress,
);
const accounts = await web3Wrapper.getAvailableAddressesAsync();
[transactionSignerAddress, approvalSignerAddress1, approvalSignerAddress2] = accounts.slice(0, 3);
defaultOrder = {
exchangeAddress: devConstants.NULL_ADDRESS,
makerAddress: devConstants.NULL_ADDRESS,
takerAddress: devConstants.NULL_ADDRESS,
senderAddress: mixins.address,
feeRecipientAddress: approvalSignerAddress1,
makerAssetData: devConstants.NULL_BYTES,
takerAssetData: devConstants.NULL_BYTES,
makerAssetAmount: devConstants.ZERO_AMOUNT,
takerAssetAmount: devConstants.ZERO_AMOUNT,
makerFee: devConstants.ZERO_AMOUNT,
takerFee: devConstants.ZERO_AMOUNT,
expirationTimeSeconds: devConstants.ZERO_AMOUNT,
salt: devConstants.ZERO_AMOUNT,
signature: devConstants.NULL_BYTES,
};
const transactionSignerPrivateKey =
devConstants.TESTRPC_PRIVATE_KEYS[accounts.indexOf(transactionSignerAddress)];
const approvalSignerPrivateKey1 = devConstants.TESTRPC_PRIVATE_KEYS[accounts.indexOf(approvalSignerAddress1)];
const approvalSignerPrivateKey2 = devConstants.TESTRPC_PRIVATE_KEYS[accounts.indexOf(approvalSignerAddress2)];
transactionFactory = new TransactionFactory(transactionSignerPrivateKey, exchangeAddress);
approvalFactory1 = new ApprovalFactory(approvalSignerPrivateKey1, mixins.address);
approvalFactory2 = new ApprovalFactory(approvalSignerPrivateKey2, mixins.address);
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
describe('getSignerAddress', () => {
it('should return the correct address using the EthSign signature type', async () => {
const data = devConstants.NULL_BYTES;
const transaction = transactionFactory.newSignedTransaction(data, SignatureType.EthSign);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
const signerAddress = await mixins.getSignerAddress.callAsync(transactionHash, transaction.signature);
expect(transaction.signerAddress).to.eq(signerAddress);
});
it('should return the correct address using the EIP712 signature type', async () => {
const data = devConstants.NULL_BYTES;
const transaction = transactionFactory.newSignedTransaction(data, SignatureType.EIP712);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
const signerAddress = await mixins.getSignerAddress.callAsync(transactionHash, transaction.signature);
expect(transaction.signerAddress).to.eq(signerAddress);
});
it('should revert with with the Illegal signature type', async () => {
const data = devConstants.NULL_BYTES;
const transaction = transactionFactory.newSignedTransaction(data);
const illegalSignatureByte = ethUtil.toBuffer(SignatureType.Illegal).toString('hex');
transaction.signature = `${transaction.signature.slice(
0,
transaction.signature.length - 2,
)}${illegalSignatureByte}`;
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expectContractCallFailedAsync(
mixins.getSignerAddress.callAsync(transactionHash, transaction.signature),
RevertReason.SignatureIllegal,
);
});
it('should revert with with the Invalid signature type', async () => {
const data = devConstants.NULL_BYTES;
const transaction = transactionFactory.newSignedTransaction(data);
const invalidSignatureByte = ethUtil.toBuffer(SignatureType.Invalid).toString('hex');
transaction.signature = `0x${invalidSignatureByte}`;
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expectContractCallFailedAsync(
mixins.getSignerAddress.callAsync(transactionHash, transaction.signature),
RevertReason.SignatureInvalid,
);
});
it("should revert with with a signature type that doesn't exist", async () => {
const data = devConstants.NULL_BYTES;
const transaction = transactionFactory.newSignedTransaction(data);
const invalidSignatureByte = '04';
transaction.signature = `${transaction.signature.slice(
0,
transaction.signature.length - 2,
)}${invalidSignatureByte}`;
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expectContractCallFailedAsync(
mixins.getSignerAddress.callAsync(transactionHash, transaction.signature),
RevertReason.SignatureUnsupported,
);
});
});
describe('decodeOrdersFromFillData', () => {
for (const fnName of constants.SINGLE_FILL_FN_NAMES) {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedSignedOrders = decodedOrders.map(order => ({
...order,
exchangeAddress: devConstants.NULL_ADDRESS,
signature: devConstants.NULL_BYTES,
}));
expect(orders).to.deep.eq(decodedSignedOrders);
});
}
for (const fnName of constants.BATCH_FILL_FN_NAMES) {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedSignedOrders = decodedOrders.map(order => ({
...order,
exchangeAddress: devConstants.NULL_ADDRESS,
signature: devConstants.NULL_BYTES,
}));
expect(orders).to.deep.eq(decodedSignedOrders);
});
}
for (const fnName of constants.MARKET_FILL_FN_NAMES) {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedSignedOrders = decodedOrders.map(order => ({
...order,
exchangeAddress: devConstants.NULL_ADDRESS,
signature: devConstants.NULL_BYTES,
}));
expect(orders).to.deep.eq(decodedSignedOrders);
});
}
for (const fnName of [constants.CANCEL_ORDER, constants.BATCH_CANCEL_ORDERS, constants.CANCEL_ORDERS_UP_TO]) {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const emptyArray: any[] = [];
expect(emptyArray).to.deep.eq(decodedOrders);
});
}
it('should decode an empty array for invalid data', async () => {
const data = '0x0123456789';
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const emptyArray: any[] = [];
expect(emptyArray).to.deep.eq(decodedOrders);
});
it('should revert if data is less than 4 bytes long', async () => {
const data = '0x010203';
await expectContractCallFailedAsync(
mixins.decodeOrdersFromFillData.callAsync(data),
RevertReason.LibBytesGreaterOrEqualTo4LengthRequired,
);
});
});
describe('Single order approvals', () => {
for (const fnName of constants.SINGLE_FILL_FN_NAMES) {
it(`Should be successful: function=${fnName}, caller=tx_signer, senderAddress=[verifier], approval_sig=[approver1], expiration=[valid]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: transactionSignerAddress },
);
});
it(`Should be successful: function=${fnName}, caller=tx_signer, senderAddress=[null], approval_sig=[approver1], expiration=[valid]`, async () => {
const order = {
...defaultOrder,
senderAddress: devConstants.NULL_ADDRESS,
};
const orders = [order];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: transactionSignerAddress },
);
});
it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[], expiration=[]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[],
[],
{
from: approvalSignerAddress1,
},
);
});
it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[approver1], expiration=[invalid]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: approvalSignerAddress1 },
);
});
it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[], expiration=[]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[],
[],
{
from: approvalSignerAddress1,
},
);
});
it(`Should revert: function=${fnName}, caller=tx_signer, senderAddress=[verifier], approval_sig=[invalid], expiration=[valid]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
const signature = `${approval.signature.slice(0, 4)}FFFFFFFF${approval.signature.slice(12)}`;
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[signature],
{ from: transactionSignerAddress },
),
RevertReason.InvalidApprovalSignature,
);
});
it(`Should revert: function=${fnName}, caller=tx_signer, senderAddress=[verifier], approval_sig=[approver1], expiration=[invalid]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).minus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: transactionSignerAddress },
),
RevertReason.ApprovalExpired,
);
});
it(`Should revert: function=${fnName}, caller=approver2, senderAddress=[verifier], approval_sig=[approver1], expiration=[valid]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: approvalSignerAddress2 },
),
RevertReason.InvalidOrigin,
);
});
}
});
describe('Batch order approvals', () => {
for (const fnName of [
...constants.BATCH_FILL_FN_NAMES,
...constants.MARKET_FILL_FN_NAMES,
constants.MATCH_ORDERS,
]) {
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver1], approval_sig=[approver1], expiration=[valid]`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: transactionSignerAddress },
);
});
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[null,null], feeRecipient=[approver1,approver1], approval_sig=[approver1], expiration=[valid]`, async () => {
const orders = [defaultOrder, defaultOrder].map(order => ({
...order,
senderAddress: devConstants.NULL_ADDRESS,
}));
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: transactionSignerAddress },
);
});
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[null,null], feeRecipient=[approver1,approver1], approval_sig=[], expiration=[]`, async () => {
const orders = [defaultOrder, defaultOrder].map(order => ({
...order,
senderAddress: devConstants.NULL_ADDRESS,
}));
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
[],
{ from: transactionSignerAddress },
);
});
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[verifier,null], feeRecipient=[approver1,approver1], approval_sig=[approver1], expiration=[valid]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, senderAddress: devConstants.NULL_ADDRESS }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval.signature],
{ from: transactionSignerAddress },
);
});
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver2], approval_sig=[approver1,approver2], expiration=[valid,valid]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval1 = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
const approval2 = approvalFactory2.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds, approvalExpirationTimeSeconds],
[approval1.signature, approval2.signature],
{ from: transactionSignerAddress },
);
});
it(`Should be successful: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver1], approval_sig=[], expiration=[]`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[],
[],
{ from: approvalSignerAddress1 },
);
});
it(`Should revert: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver2], approval_sig=[approver2], expiration=[valid]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval2 = approvalFactory2.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval2.signature],
{ from: approvalSignerAddress1 },
),
RevertReason.InvalidOrigin,
);
});
it(`Should revert: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver1], approval_sig=[], expiration=[]`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
[],
{ from: transactionSignerAddress },
),
RevertReason.InvalidApprovalSignature,
);
});
it(`Should revert: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver1], approval_sig=[invalid], expiration=[valid]`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
const signature = `${approval.signature.slice(0, 4)}FFFFFFFF${approval.signature.slice(12)}`;
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[signature],
{ from: transactionSignerAddress },
),
RevertReason.InvalidApprovalSignature,
);
});
it(`Should revert: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver2], approval_sig=[valid,invalid], expiration=[valid,valid]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval1 = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
const approval2 = approvalFactory2.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
const approvalSignature2 = `${approval2.signature.slice(0, 4)}FFFFFFFF${approval2.signature.slice(12)}`;
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds, approvalExpirationTimeSeconds],
[approval1.signature, approvalSignature2],
{ from: transactionSignerAddress },
),
RevertReason.InvalidApprovalSignature,
);
});
it(`Should revert: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver2], approval_sig=[invalid], expiration=[valid]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval2 = approvalFactory2.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
const approvalSignature2 = `${approval2.signature.slice(0, 4)}FFFFFFFF${approval2.signature.slice(12)}`;
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[approvalExpirationTimeSeconds],
[approvalSignature2],
{ from: approvalSignerAddress1 },
),
RevertReason.InvalidApprovalSignature,
);
});
it(`Should revert: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver2], approval_sig=[valid,valid], expiration=[valid,invalid]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds1 = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approvalExpirationTimeSeconds2 = new BigNumber(currentTimestamp).minus(constants.TIME_BUFFER);
const approval1 = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds1,
);
const approval2 = approvalFactory2.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds2,
);
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds1, approvalExpirationTimeSeconds2],
[approval1.signature, approval2.signature],
{ from: transactionSignerAddress },
),
RevertReason.ApprovalExpired,
);
});
it(`Should revert: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver2], approval_sig=[valid], expiration=[invalid]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).minus(constants.TIME_BUFFER);
const approval2 = approvalFactory2.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval2.signature],
{ from: approvalSignerAddress1 },
),
RevertReason.ApprovalExpired,
);
});
it(`Should revert: function=${fnName} caller=approver2, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver1], approval_sig=[valid], expiration=[valid]`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = transactionFactory.newSignedTransaction(data);
const currentTimestamp = await getLatestBlockTimestampAsync();
const approvalExpirationTimeSeconds = new BigNumber(currentTimestamp).plus(constants.TIME_BUFFER);
const approval1 = approvalFactory1.newSignedApproval(
transaction,
transactionSignerAddress,
approvalExpirationTimeSeconds,
);
expectContractCallFailedAsync(
mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approvalExpirationTimeSeconds],
[approval1.signature],
{ from: approvalSignerAddress2 },
),
RevertReason.InvalidOrigin,
);
});
}
});
describe('cancels', () => {
it('should allow the tx signer to call `cancelOrder` without approval', async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(constants.CANCEL_ORDER, orders);
const transaction = transactionFactory.newSignedTransaction(data);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
[],
{ from: transactionSignerAddress },
);
});
it('should allow the tx signer to call `batchCancelOrders` without approval', async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(constants.BATCH_CANCEL_ORDERS, orders);
const transaction = transactionFactory.newSignedTransaction(data);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
[],
{ from: transactionSignerAddress },
);
});
it('should allow the tx signer to call `cancelOrdersUpTo` without approval', async () => {
const orders: SignedOrder[] = [];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(constants.CANCEL_ORDERS_UP_TO, orders);
const transaction = transactionFactory.newSignedTransaction(data);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
[],
{ from: transactionSignerAddress },
);
});
});
});
// tslint:disable:max-file-line-count

View File

@@ -0,0 +1,38 @@
import { signingUtils } from '@0x/contracts-test-utils';
import { SignatureType, SignedZeroExTransaction } from '@0x/types';
import { BigNumber } from '@0x/utils';
import * as ethUtil from 'ethereumjs-util';
import { hashUtils, SignedCoordinatorApproval } from './index';
export class ApprovalFactory {
private readonly _privateKey: Buffer;
private readonly _verifyingContractAddress: string;
constructor(privateKey: Buffer, verifyingContractAddress: string) {
this._privateKey = privateKey;
this._verifyingContractAddress = verifyingContractAddress;
}
public newSignedApproval(
transaction: SignedZeroExTransaction,
txOrigin: string,
approvalExpirationTimeSeconds: BigNumber,
signatureType: SignatureType = SignatureType.EthSign,
): SignedCoordinatorApproval {
const approvalHashBuff = hashUtils.getApprovalHashBuffer(
transaction,
this._verifyingContractAddress,
txOrigin,
approvalExpirationTimeSeconds,
);
const signatureBuff = signingUtils.signMessage(approvalHashBuff, this._privateKey, signatureType);
const signedApproval = {
txOrigin,
transaction,
approvalExpirationTimeSeconds,
signature: ethUtil.addHexPrefix(signatureBuff.toString('hex')),
};
return signedApproval;
}
}

View File

@@ -0,0 +1,12 @@
import { BigNumber } from '@0x/utils';
export const constants = {
SINGLE_FILL_FN_NAMES: ['fillOrder', 'fillOrKillOrder', 'fillOrderNoThrow'],
BATCH_FILL_FN_NAMES: ['batchFillOrders', 'batchFillOrKillOrders', 'batchFillOrdersNoThrow'],
MARKET_FILL_FN_NAMES: ['marketBuyOrders', 'marketBuyOrdersNoThrow', 'marketSellOrders', 'marketSellOrdersNoThrow'],
MATCH_ORDERS: 'matchOrders',
CANCEL_ORDER: 'cancelOrder',
BATCH_CANCEL_ORDERS: 'batchCancelOrders',
CANCEL_ORDERS_UP_TO: 'cancelOrdersUpTo',
TIME_BUFFER: new BigNumber(1000),
};

View File

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

View File

@@ -0,0 +1,47 @@
import { IExchangeContract } from '@0x/contracts-exchange';
import { constants as devConstants, provider } from '@0x/contracts-test-utils';
import { SignedOrder } from '@0x/types';
import { constants } from './index';
export const exchangeDataEncoder = {
encodeOrdersToExchangeData(fnName: string, orders: SignedOrder[]): string {
const exchangeInstance = new IExchangeContract(devConstants.NULL_ADDRESS, provider);
let data;
if (constants.SINGLE_FILL_FN_NAMES.indexOf(fnName) !== -1) {
data = (exchangeInstance as any)[fnName].getABIEncodedTransactionData(
orders[0],
orders[0].takerAssetAmount,
orders[0].signature,
);
} else if (constants.BATCH_FILL_FN_NAMES.indexOf(fnName) !== -1) {
data = (exchangeInstance as any)[fnName].getABIEncodedTransactionData(
orders,
orders.map(order => order.takerAssetAmount),
orders.map(order => order.signature),
);
} else if (constants.MARKET_FILL_FN_NAMES.indexOf(fnName) !== -1) {
data = (exchangeInstance as any)[fnName].getABIEncodedTransactionData(
orders,
orders.map(order => order.takerAssetAmount).reduce((prev, curr) => prev.plus(curr)),
orders.map(order => order.signature),
);
} else if (fnName === constants.MATCH_ORDERS) {
data = exchangeInstance.matchOrders.getABIEncodedTransactionData(
orders[0],
orders[1],
orders[0].signature,
orders[1].signature,
);
} else if (fnName === constants.CANCEL_ORDER) {
data = exchangeInstance.cancelOrder.getABIEncodedTransactionData(orders[0]);
} else if (fnName === constants.BATCH_CANCEL_ORDERS) {
data = exchangeInstance.batchCancelOrders.getABIEncodedTransactionData(orders);
} else if (fnName === constants.CANCEL_ORDERS_UP_TO) {
data = exchangeInstance.cancelOrdersUpTo.getABIEncodedTransactionData(devConstants.ZERO_AMOUNT);
} else {
throw new Error(`Error: ${fnName} not a supported function`);
}
return data;
},
};

View File

@@ -0,0 +1,33 @@
import { eip712Utils } from '@0x/order-utils';
import { SignedZeroExTransaction } from '@0x/types';
import { BigNumber, signTypedDataUtils } from '@0x/utils';
import * as _ from 'lodash';
export const hashUtils = {
getApprovalHashBuffer(
transaction: SignedZeroExTransaction,
verifyingContractAddress: string,
txOrigin: string,
approvalExpirationTimeSeconds: BigNumber,
): Buffer {
const typedData = eip712Utils.createCoordinatorApprovalTypedData(
transaction,
verifyingContractAddress,
txOrigin,
approvalExpirationTimeSeconds,
);
const hashBuffer = signTypedDataUtils.generateTypedDataHash(typedData);
return hashBuffer;
},
getApprovalHashHex(
transaction: SignedZeroExTransaction,
verifyingContractAddress: string,
txOrigin: string,
approvalExpirationTimeSeconds: BigNumber,
): string {
const hashHex = `0x${hashUtils
.getApprovalHashBuffer(transaction, verifyingContractAddress, txOrigin, approvalExpirationTimeSeconds)
.toString('hex')}`;
return hashHex;
},
};

View File

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

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