Initial commit

This commit is contained in:
Kirill Fedoseev 2020-08-13 12:42:19 +07:00
commit f46a9d54ef
55 changed files with 27824 additions and 0 deletions

15
.dockerignore Normal file
View File

@ -0,0 +1,15 @@
node_modules
deploy/node_modules
.git
.gitignore
.dockerignore
deploy/.env
deploy/*.config
deploy/*.env
docker-compose.yml
Dockerfile
Dockerfile.dev
*.log
flats
contracts.sublime-project
contracts.sublime-workspace

15
.editorconfig Normal file
View File

@ -0,0 +1,15 @@
# EditorConfig is awesome: http://EditorConfig.org
root = true
[*]
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
[*.ts]
indent_style = tab
[{package.json}]
indent_style = space
indent_size = 4

1
.eslintignore Normal file
View File

@ -0,0 +1 @@
node_modules

30
.eslintrc Normal file
View File

@ -0,0 +1,30 @@
{
"extends": [
"plugin:node/recommended",
"airbnb-base",
"plugin:prettier/recommended"
],
"plugins": ["node"],
"env": {
"node" : true,
"mocha" : true
},
"globals" : {
"artifacts": false,
"contract": false,
"assert": false,
"web3": false
},
"rules": {
"no-plusplus": "off",
"no-await-in-loop": "off",
"no-shadow": "off",
"prefer-destructuring": "off",
"no-use-before-define": ["error", { "functions": false }],
"no-restricted-syntax": "off",
"node/no-unpublished-require": "off",
"func-names": "off",
"no-loop-func": "off",
"import/no-extraneous-dependencies": "off"
}
}

1
.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
*.sol linguist-language=Solidity

73
.github/workflows/main.yml vendored Normal file
View File

@ -0,0 +1,73 @@
name: amb-mediators
on: [push]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/setup-node@v1
with:
node-version: 10
- uses: actions/checkout@v2
- uses: actions/cache@v2
id: npm-cache
with:
path: node_modules
key: ${{ runner.os }}-node_modules-${{ hashFiles('**/package-lock.json') }}
- run: npm install
if: ${{ !steps.npm-cache.outputs.cache-hit }}
- run: npm run lint
test:
runs-on: ubuntu-latest
steps:
- uses: actions/setup-node@v1
with:
node-version: 10
- uses: actions/checkout@v2
- uses: actions/cache@v2
id: npm-cache
with:
path: node_modules
key: ${{ runner.os }}-node_modules-${{ hashFiles('**/package-lock.json') }}
- run: npm install
if: ${{ !steps.npm-cache.outputs.cache-hit }}
- run: npm run test
gasreport:
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/develop'
steps:
- uses: actions/setup-node@v1
with:
node-version: 10
- uses: actions/checkout@v2
- uses: actions/cache@v2
id: npm-cache
with:
path: node_modules
key: ${{ runner.os }}-node_modules-${{ hashFiles('**/package-lock.json') }}
- run: npm install
if: ${{ !steps.npm-cache.outputs.cache-hit }}
- run: npm run test:gasreport:ci
env:
CC_SECRET: ${{ secrets.CC_SECRET }}
coverage:
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/develop'
steps:
- uses: actions/setup-node@v1
with:
node-version: 10
- uses: actions/checkout@v2
- uses: actions/cache@v2
id: npm-cache
with:
path: node_modules
key: ${{ runner.os }}-node_modules-${{ hashFiles('**/package-lock.json') }}
- run: npm install
if: ${{ !steps.npm-cache.outputs.cache-hit }}
- run: npm run coverage
- name: Coveralls
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}

11
.gitignore vendored Normal file
View File

@ -0,0 +1,11 @@
node_modules
build
flats
.node*
.idea
coverage
*.sublime-*
.0x-artifacts
deploy/.env
deploy/*.config
deploy/*.env

1
.nvmrc Normal file
View File

@ -0,0 +1 @@
10.18

14
.prettierrc Normal file
View File

@ -0,0 +1,14 @@
{
"semi": false,
"singleQuote": true,
"printWidth": 120,
"bracketSpacing": true,
"overrides": [
{
"files": "*.sol",
"options": {
"singleQuote": false
}
}
]
}

16
.solhint.json Normal file
View File

@ -0,0 +1,16 @@
{
"extends": "solhint:recommended",
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error",
"mark-callable-contracts": "off",
"avoid-low-level-calls": "off",
"no-inline-assembly": "off",
"multiple-sends": "off",
"bracket-align": "off",
"no-complex-fallback": "off",
"no-empty-blocks": "off",
"no-simple-event-func-name": "off",
"compiler-version": ["error", "0.4.24"]
}
}

73
CODE_OF_CONDUCT.md Normal file
View File

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

28
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,28 @@
## Contributing
Thank your for contributing to this project! We welcome collaborators and expect users to follow our [code of conduct](CODE_OF_CONDUCT.md) when submitting code or comments.
1. Fork the repo ( https://github.com/poanetwork/amb-mediators/fork ).
2. Create your feature branch (`git checkout -b my-new-feature`).
3. Write tests that cover your work.
4. Commit your changes (`git commit -am 'Add some feature'`).
5. Push to your branch (`git push origin my-new-feature`).
6. Create a new PR (Pull Request).
### General
* Commits should be one logical change that still allows all tests to pass. We prefer smaller commits if there could be two levels of logic grouping. The goal is to provide future contributors (including your future self) the reasoning behind your changes and allow them to cherry-pick, patch or port those changes in isolation to other branches or forks.
* If during your PR you reveal a pre-existing bug and know how to fix it:
1. If you can isolate the bug, fix it in a separate PR.
2. If the fix depends on your other commits, add it in a separate commit to the same PR.
In either case, try to write a regression test that fails because of the bug but passes with your fix.
### Issues
Creating and discussing [Issues](https://github.com/poanetwork/amb-mediators/issues) provides significant value to the project. If you find a bug you can report it in an Issue.
### Pull Requests
All pull requests should include:
* A clear, readable description of the purpose of the PR
* A clear, readable description of changes
* Any additional concerns or comments (optional)

31
Dockerfile Normal file
View File

@ -0,0 +1,31 @@
FROM node:10 as contracts
WORKDIR /contracts
COPY package.json .
COPY package-lock.json .
RUN npm install
COPY truffle-config.js truffle-config.js
COPY ./contracts ./contracts
RUN npm run compile
COPY flatten.sh flatten.sh
RUN bash flatten.sh
FROM node:10
WORKDIR /contracts
COPY package.json .
COPY package-lock.json .
RUN npm install --only=prod
COPY --from=contracts /contracts/build ./build
COPY --from=contracts /contracts/flats ./flats
COPY deploy.sh deploy.sh
COPY ./deploy ./deploy
ENV PATH="/contracts/:${PATH}"
ENV NOFLAT=true

33
Dockerfile.dev Normal file
View File

@ -0,0 +1,33 @@
FROM node:10
RUN apt-get update
RUN apt-get install -y netcat
RUN apt-get clean
WORKDIR /contracts
COPY package.json .
COPY package-lock.json .
RUN npm install
COPY ./scripts ./scripts
COPY truffle-config.js truffle-config.js
COPY ./contracts ./contracts
RUN npm run compile
COPY flatten.sh flatten.sh
RUN bash flatten.sh
COPY .eslintignore .eslintignore
COPY .eslintrc .eslintrc
COPY .prettierrc .prettierrc
COPY deploy.sh deploy.sh
COPY ./deploy ./deploy
COPY .solhint.json .solhint.json
COPY codechecks.yml codechecks.yml
COPY ./test ./test
ENV PATH="/contracts/:${PATH}"
ENV NOFLAT=true

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

96
README.md Normal file
View File

@ -0,0 +1,96 @@
[![Join the chat at https://gitter.im/poanetwork/poa-bridge](https://badges.gitter.im/poanetwork/poa-bridge.svg)](https://gitter.im/poanetwork/poa-bridge?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://github.com/poanetwork/amb-mediators/workflows/amb-mediators/badge.svg?branch=master)](https://github.com/poanetwork/amb-mediators/workflows/amb-mediators/badge.svg?branch=master)
[![Coverage Status](https://coveralls.io/repos/github/poanetwork/amb-mediators/badge.svg?branch=master)](https://coveralls.io/github/poanetwork/amb-mediators?branch=master)
# AMB Mediators Smart Contracts
These contracts provide the functionality for mediators intended to work on top of the AMB bridge.
## Usage
There are two ways to deploy contracts:
* install and use NodeJS
* use Docker to deploy
### Deployment with NodeJS
#### Install Dependencies
```bash
npm install
```
#### Deploy
Please read the [README.md](deploy/README.md) in the `deploy` folder for instructions and .env file configuration
#### Test
```bash
npm test
```
#### Run coverage tests
```bash
npm run coverage
```
The results can be found in the `coverage` directory.
#### Flatten
Fattened contracts can be used to verify the contract code in a block explorer like BlockScout or Etherscan.
The following command will prepare flattened version of the contracts:
```bash
npm run flatten
```
The flattened contracts can be found in the `flats` directory.
### Deployment in the Docker environment
[Docker](https://www.docker.com/community-edition) and [Docker Compose](https://docs.docker.com/compose/install/) can be used to deploy contracts without NodeJS installed on the system.
If you are on Linux, we recommend you [create a docker group and add your user to it](https://docs.docker.com/install/linux/linux-postinstall/), so that you can use the CLI without `sudo`.
#### Prepare the docker container
```bash
docker-compose up --build
```
_Note: The container must be rebuilt every time the code in a contract or deployment script is changed._
#### Deploy the contracts
1. Create the `.env` file in the `deploy` directory as described in the deployment [README.md](deploy/README.md).
2. Run deployment process:
```bash
docker-compose run amb-mediators deploy.sh
```
or with Linux:
```bash
./deploy.sh
```
#### Copy flatten sources (if needed)
1. Discover the container name:
```bash
docker-compose images amb-mediators
```
2. In the following command, use the container name to copy the flattened contracts code to the current working directory. The contracts will be located in the `flats` directory.
```bash
docker cp name-of-your-container:/contracts/flats ./
```
#### Test contract and run coverage (if needed)
```bash
$ docker-compose run dev bash
$ npm test
$ npm run coverage
```
#### Shutdown the container
If the container is no longer needed, it can be shutdown:
```bash
docker-compose down
```
## Contributing
See the [CONTRIBUTING](CONTRIBUTING.md) document for contribution, testing and pull request protocol.
## License
[![License: GPL v3.0](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
This project is licensed under the GNU General Public License v3.0. See the [LICENSE](LICENSE) file for details.

6
codechecks.yml Normal file
View File

@ -0,0 +1,6 @@
checks:
- name: eth-gas-reporter/codechecks
settings:
branches:
- develop
- master

24
contracts/Migrations.sol Normal file
View File

@ -0,0 +1,24 @@
pragma solidity 0.4.24;
contract Migrations {
address public owner;
// solhint-disable-next-line var-name-mixedcase
uint256 public last_completed_migration;
modifier restricted() {
if (msg.sender == owner) _;
}
constructor() public {
owner = msg.sender;
}
function setCompleted(uint256 completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}

View File

@ -0,0 +1,39 @@
pragma solidity 0.4.24;
import "tokenbridge-contracts/contracts/upgradeable_contracts/Initializable.sol";
import "tokenbridge-contracts/contracts/upgradeable_contracts/VersionableBridge.sol";
import "tokenbridge-contracts/contracts/upgradeable_contracts/BasicAMBMediator.sol";
/**
* @title BasicAMBENSMirror
* @dev Commong mediator functionality for mirroring existing ENS records intended to work on top of AMB bridge.
*/
contract BasicAMBENSMirror is Initializable, BasicAMBMediator, VersionableBridge {
event BridgeENSNode(bytes32 indexed node, address owner);
/**
* @dev Tells the bridge interface version that this contract supports.
* @return major value of the version
* @return minor value of the version
* @return patch value of the version
*/
function getBridgeInterfacesVersion()
external
pure
returns (
uint64 major,
uint64 minor,
uint64 patch
)
{
return (1, 0, 0);
}
/**
* @dev Tells the bridge mode that this contract supports.
* @return _data 4 bytes representing the bridge mode
*/
function getBridgeMode() external pure returns (bytes4 _data) {
return 0xa10d4bc8; // bytes4(keccak256(abi.encodePacked("ens-mirror-amb")))
}
}

View File

@ -0,0 +1,126 @@
pragma solidity 0.4.24;
import "../interfaces/IENS.sol";
import "tokenbridge-contracts/contracts/upgradeability/EternalStorage.sol";
import "openzeppelin-solidity/contracts/AddressUtils.sol";
/**
* @title ENSBridgeRegistry
* @dev The ENS registry contract intended to work as a part of the Home ENS mediator.
*/
contract ENSBridgeRegistry is IENS, EternalStorage {
bytes32 internal constant ENS_DEFAULT_RESOLVER = 0xc2b77c5d2423030ffea534cdaba0e27c8f03374d963a21220c21e226d43586da; // keccak256(abi.encodePacked("ensDefaultResolver"))
// Permits modifications only by the owner of the specified node.
modifier authorised(bytes32 _node) {
address _owner = owner(_node);
require(_owner == msg.sender || isApprovedForAll(_owner, msg.sender));
_;
}
/**
* @dev Sets the resolver address for the specified node.
* @param _node The node to update.
* @param _resolver The address of the resolver.
*/
function setResolver(bytes32 _node, address _resolver) external authorised(_node) {
_setResolver(_node, _resolver);
}
/**
* @dev Sets the TTL for the specified node.
* @param _node The node to update.
* @param _ttl The TTL in seconds.
*/
function setTTL(bytes32 _node, uint64 _ttl) external authorised(_node) {
_setTTL(_node, _ttl);
}
/**
* @dev Enable or disable approval for a third party ("operator") to manage
* all of `msg.sender`'s ENS records. Emits the ApprovalForAll event.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operator is approved, false to revoke approval.
*/
function setApprovalForAll(address _operator, bool _approved) external {
boolStorage[keccak256(abi.encodePacked("ensApproved", msg.sender, _operator))] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Returns the address that owns the specified node.
* @param _node The specified node.
* @return address of the owner.
*/
function owner(bytes32 _node) public view returns (address) {
return addressStorage[keccak256(abi.encodePacked("ensOwner", _node))];
}
/**
* @dev Returns the address of the resolver for the specified node.
* @param _node The specified node.
* @return address of the resolver.
*/
function resolver(bytes32 _node) public view returns (address) {
return addressStorage[keccak256(abi.encodePacked("ensResolver", _node))];
}
/**
* @dev Returns the TTL of a node, and any records associated with it.
* @param _node The specified node.
* @return ttl of the node.
*/
function ttl(bytes32 _node) external view returns (uint64) {
return uint64(uintStorage[keccak256(abi.encodePacked("ensTTL", _node))]);
}
/**
* @dev Returns whether a record has been imported to the registry.
* @param _node The specified node.
* @return Bool if record exists
*/
function recordExists(bytes32 _node) public view returns (bool) {
return owner(_node) != address(0x0);
}
/**
* @dev Query if an address is an authorized operator for another address.
* @param _owner The address that owns the records.
* @param _operator The address that acts on behalf of the owner.
* @return True if `operator` is an approved operator for `owner`, false otherwise.
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("ensApproved", _owner, _operator))];
}
/**
* @dev Internal function for transferring ownership of a node to a new address.
* @param _node The node to transfer ownership of.
* @param _owner The address of the new owner.
*/
function _setOwner(bytes32 _node, address _owner) internal {
addressStorage[keccak256(abi.encodePacked("ensOwner", _node))] = _owner;
emit Transfer(_node, _owner);
}
/**
* @dev Internal function for setting the resolver address for the specified node.
* @param _node The node to update.
* @param _resolver The address of the resolver.
*/
function _setResolver(bytes32 _node, address _resolver) internal {
require(AddressUtils.isContract(_resolver) || _resolver == address(0));
addressStorage[keccak256(abi.encodePacked("ensResolver", _node))] = _resolver;
emit NewResolver(_node, _resolver);
}
/**
* @dev Internal function for setting the TTL for the specified node.
* @param _node The node to update.
* @param _ttl The TTL in seconds.
*/
function _setTTL(bytes32 _node, uint64 _ttl) internal {
uintStorage[keccak256(abi.encodePacked("ensTTL", _node))] = uint256(_ttl);
emit NewTTL(_node, _ttl);
}
}

View File

@ -0,0 +1,79 @@
pragma solidity 0.4.24;
import "../interfaces/IENS.sol";
import "./BasicAMBENSMirror.sol";
import "./HomeAMBENSMirror.sol";
import "openzeppelin-solidity/contracts/AddressUtils.sol";
/**
* @title ForeignAMBENSMirror
* @dev Foreign mediator functionality for mirroring existing ENS records intended to work on top of AMB bridge.
*/
contract ForeignAMBENSMirror is BasicAMBENSMirror {
bytes32 internal constant ENS_REGISTRY = 0xbf73a8f25960de5ebfb3a8385bf0b70b6598db027255cebc160e88c4507ca172; // keccak256(abi.encodePacked("ensRegistry"))
/**
* @dev Stores the initial parameters of the mediator.
* @param _bridgeContract the address of the AMB bridge contract.
* @param _mediatorContract the address of the mediator contract on the other network.
* @param _requestGasLimit the gas limit for the message execution.
* @param _owner address of the owner of the mediator contract.
* @param _ensRegistry address of the ens registry contract.
*/
function initialize(
address _bridgeContract,
address _mediatorContract,
uint256 _requestGasLimit,
address _owner,
address _ensRegistry
) external onlyRelevantSender returns (bool) {
require(!isInitialized());
require(_owner != address(0));
require(AddressUtils.isContract(_ensRegistry));
_setBridgeContract(_bridgeContract);
_setMediatorContractOnOtherSide(_mediatorContract);
_setRequestGasLimit(_requestGasLimit);
setOwner(_owner);
addressStorage[ENS_REGISTRY] = _ensRegistry;
setInitialize();
return isInitialized();
}
/**
* @dev Retrieves the address of the associated ENS registry contract, from where all records should mirrored.
* @return address of the ENS registry contract.
*/
function ensRegistry() public view returns (IENS) {
return IENS(addressStorage[ENS_REGISTRY]);
}
/**
* @dev Performes an AMB request for updating the ENS record on the other side.
* @param _node ENS record namehash identifier.
*/
function bridgeENSNode(bytes32 _node) external {
address owner = ensRegistry().owner(_node);
require(owner != address(0));
uint64 ttl = ensRegistry().ttl(_node);
IENSAddrResolver resolver = IENSAddrResolver(ensRegistry().resolver(_node));
address addr;
if (address(resolver) != address(0)) {
addr = resolver.addr(_node);
}
bytes memory data = abi.encodeWithSelector(
HomeAMBENSMirror(address(this)).updateENSNode.selector,
_node,
owner,
addr,
ttl
);
bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), data, requestGasLimit());
emit BridgeENSNode(_node, owner);
}
}

View File

@ -0,0 +1,66 @@
pragma solidity 0.4.24;
import "../interfaces/IENS.sol";
import "./BasicAMBENSMirror.sol";
import "./ENSBridgeRegistry.sol";
/**
* @title HomeAMBENSMirror
* @dev Home mediator functionality for mirroring existing ENS records intended to work on top of AMB bridge.
*/
contract HomeAMBENSMirror is BasicAMBENSMirror, ENSBridgeRegistry {
/**
* @dev Stores the initial parameters of the mediator.
* @param _bridgeContract the address of the AMB bridge contract.
* @param _mediatorContract the address of the mediator contract on the other network.
* @param _owner address of the owner of the mediator contract.
* @param _resolverContract address of public resolver contract.
*/
function initialize(
address _bridgeContract,
address _mediatorContract,
address _owner,
address _resolverContract
) external onlyRelevantSender returns (bool) {
require(!isInitialized());
require(_owner != address(0));
require(AddressUtils.isContract(_resolverContract));
_setBridgeContract(_bridgeContract);
_setMediatorContractOnOtherSide(_mediatorContract);
setOwner(_owner);
addressStorage[ENS_DEFAULT_RESOLVER] = _resolverContract;
setInitialize();
return isInitialized();
}
/**
* @dev Updates mirrored ENS record parameters came from other side.
* Can only be called by mediator on the other side.
* @param _node ENS record namehash identifier.
* @param _owner ENS record owner address.
* @param _addr ENS record associated address.
* @param _ttl ENS record time-to-live parameter.
*/
function updateENSNode(
bytes32 _node,
address _owner,
address _addr,
uint64 _ttl
) external onlyMediator {
// node associated address will be only updated when new node is bridged
// for subsequent updates, address should be updated manually using setAddr
if (!recordExists(_node)) {
address _resolver = addressStorage[ENS_DEFAULT_RESOLVER];
_setOwner(_node, address(this));
_setResolver(_node, _resolver);
_setTTL(_node, _ttl);
IENSAddrResolver(_resolver).setAddr(_node, _addr);
}
_setOwner(_node, _owner);
emit BridgeENSNode(_node, _owner);
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,37 @@
pragma solidity 0.4.24;
interface IENS {
// Logged when the ownership of a node is transferred to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
// Logged when an operator is added or removed.
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function setResolver(bytes32 node, address resolver) external;
function setTTL(bytes32 node, uint64 ttl) external;
function setApprovalForAll(address operator, bool approved) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
function recordExists(bytes32 node) external view returns (bool);
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
interface IENSAddrResolver {
function addr(bytes32 node) external view returns (address);
function setAddr(bytes32 node, address addr) external;
}

View File

@ -0,0 +1,5 @@
pragma solidity 0.4.24;
import "tokenbridge-contracts/contracts/mocks/AMBMock.sol";
contract AMBMockStub is AMBMock {}

138
contracts/mocks/ENSMock.sol Normal file
View File

@ -0,0 +1,138 @@
pragma solidity 0.4.24;
/**
* The ENS registry contract.
*/
contract ENSMock {
// Logged when the ownership of a node is transferred to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping(bytes32 => Record) public records;
/**
* @dev Constructs a new ENS registrar.
*/
constructor() public {
records[0x0].owner = msg.sender;
}
/**
* @dev Sets the record for a node.
* @param node The node to update.
* @param owner The address of the new owner.
* @param resolver The address of the resolver.
* @param ttl The TTL in seconds.
*/
function setRecord(
bytes32 node,
address owner,
address resolver,
uint64 ttl
) external {
setOwner(node, owner);
_setResolverAndTTL(node, resolver, ttl);
}
/**
* @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) public {
_setOwner(node, owner);
emit Transfer(node, owner);
}
/**
* @dev Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) public {
emit NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* @dev Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) public {
emit NewTTL(node, ttl);
records[node].ttl = ttl;
}
/**
* @dev Returns the address that owns the specified node.
* @param node The specified node.
* @return address of the owner.
*/
function owner(bytes32 node) public view returns (address) {
address addr = records[node].owner;
if (addr == address(this)) {
return address(0x0);
}
return addr;
}
/**
* @dev Returns the address of the resolver for the specified node.
* @param node The specified node.
* @return address of the resolver.
*/
function resolver(bytes32 node) public view returns (address) {
return records[node].resolver;
}
/**
* @dev Returns the TTL of a node, and any records associated with it.
* @param node The specified node.
* @return ttl of the node.
*/
function ttl(bytes32 node) public view returns (uint64) {
return records[node].ttl;
}
/**
* @dev Returns whether a record has been imported to the registry.
* @param node The specified node.
* @return Bool if record exists
*/
function recordExists(bytes32 node) public view returns (bool) {
return records[node].owner != address(0x0);
}
function _setOwner(bytes32 node, address owner) internal {
records[node].owner = owner;
}
function _setResolverAndTTL(
bytes32 node,
address resolver,
uint64 ttl
) internal {
if (resolver != records[node].resolver) {
records[node].resolver = resolver;
emit NewResolver(node, resolver);
}
if (ttl != records[node].ttl) {
records[node].ttl = ttl;
emit NewTTL(node, ttl);
}
}
}

View File

@ -0,0 +1,5 @@
pragma solidity 0.4.24;
import "tokenbridge-contracts/contracts/upgradeability/EternalStorageProxy.sol";
contract EternalStorageProxyStub is EternalStorageProxy {}

32
deploy.sh Executable file
View File

@ -0,0 +1,32 @@
#!/bin/bash
if [ -f /.dockerenv ]; then
# the script is run within the container
echo "Bridge contract deployment started"
npm run deploy
if [ -f bridgeDeploymentResults.json ]; then
cat bridgeDeploymentResults.json
echo
fi
exit 0
fi
which docker-compose > /dev/null
if [ "$?" == "1" ]; then
echo "docker-compose is needed to use this type of deployment"
exit 1
fi
if [ ! -f ./deploy/.env ]; then
echo "The .env file not found in the 'deploy' directory"
exit 3
fi
docker-compose images amb-mediators >/dev/null 2>/dev/null
if [ "$?" == "1" ]; then
echo "Docker image 'amb-mediators' not found"
exit 2
fi
docker-compose run amb-mediators deploy.sh "$@"

18
deploy/.eslintrc Normal file
View File

@ -0,0 +1,18 @@
{
"extends": [
"plugin:node/recommended",
"airbnb-base",
"plugin:prettier/recommended"
],
"plugins": ["node"],
"rules": {
"no-var": "error",
"consistent-return": "off",
"global-require": "off",
"no-console": "off",
"no-plusplus": "off",
"no-use-before-define": ["error", { "functions": false }],
"import/no-extraneous-dependencies": "off",
"node/no-unpublished-require": "off"
}
}

91
deploy/README.md Normal file
View File

@ -0,0 +1,91 @@
# How to Deploy AMB mediators contracts
In order to deploy mediators contracts you must run `npm install` to install all dependencies. For more information, see the [project README](../README.md).
1. Compile the source contracts.
```
cd ..
npm run compile
```
2. Create a `.env` file.
```
cd deploy
cp env-examples/.env.amb-ens-mirroring .env
```
3. If necessary, deploy and configure a multi-sig wallet contract to manage the mediators contracts after deployment. We have not audited any wallets for security, but have used https://github.com/gnosis/MultiSigWallet/ with success.
4. Adjust the parameters in the `.env` file depending on the desired bridge mode. See below for comments related to each parameter.
5. Add funds to the deployment accounts in both the Home and Foreign networks.
6. Run `npm run deploy`.
## `AMB_ENS_MIRRORING` Bridge Mode Configuration Example.
This example of an `.env` file for the `AMB-ENS-MIRRORING` bridge mode includes comments describing each parameter.
```bash
# The type of bridge. Defines set of contracts to be deployed.
BRIDGE_MODE=AMB_ENS_MIRRORING
# The private key hex value of the account responsible for contracts
# deployments and initial configuration. The account's balance must contain
# funds from both networks.
DEPLOYMENT_ACCOUNT_PRIVATE_KEY=67..14
# Extra gas added to the estimated gas of a particular deployment/configuration transaction
# E.g. if estimated gas returns 100000 and the parameter is 0.2,
# the transaction gas limit will be (100000 + 100000 * 0.2) = 120000
DEPLOYMENT_GAS_LIMIT_EXTRA=0.2
# The "gasPrice" parameter set in every deployment/configuration transaction on
# Home network (in Wei).
HOME_DEPLOYMENT_GAS_PRICE=10000000000
# The "gasPrice" parameter set in every deployment/configuration transaction on
# Foreign network (in Wei).
FOREIGN_DEPLOYMENT_GAS_PRICE=10000000000
# The timeout limit to wait for receipt of the deployment/configuration
# transaction.
GET_RECEIPT_INTERVAL_IN_MILLISECONDS=3000
# The RPC channel to a Home node able to handle deployment/configuration
# transactions.
HOME_RPC_URL=https://core.poa.network
# Address on Home network with permissions to change parameters of the bridge contract.
# For extra security we recommended using a multi-sig wallet contract address here.
HOME_BRIDGE_OWNER=0x
# Address on Home network with permissions to upgrade the bridge contract
HOME_UPGRADEABLE_ADMIN=0x
# The RPC channel to a Foreign node able to handle deployment/configuration
# transactions.
FOREIGN_RPC_URL=https://mainnet.infura.io
# Address on Foreign network with permissions to change parameters of the bridge contract.
# For extra security we recommended using a multi-sig wallet contract address here.
FOREIGN_BRIDGE_OWNER=0x
# Address on Foreign network with permissions to upgrade the bridge contract and the
# bridge validator contract.
FOREIGN_UPGRADEABLE_ADMIN=0x
# The address of the existing AMB bridge in the Home network that will be used to pass messages
# to the Foreign network.
HOME_AMB_BRIDGE=0x
# The address of the existing AMB bridge in the Foreign network that will be used to pass messages
# to the Home network.
FOREIGN_AMB_BRIDGE=0x
# The gas limit that will be used in the execution of the message passed to the mediator contract
# in the Home network.
FOREIGN_MEDIATOR_REQUEST_GAS_LIMIT=2000000
# The address of the existing ENS registry contract in the Foreign network from where all ENS records will be synced.
FOREIGN_ENS_REGISTRY_ADDRESS=0x
# The api url of an explorer to verify all the deployed contracts in Home network. Supported explorers: Blockscout, Etherscan
#HOME_EXPLORER_URL=https://blockscout.com/poa/core/api
# The api key of the explorer api, if required, used to verify all the deployed contracts in Home network.
#HOME_EXPLORER_API_KEY=
# The api url of an explorer to verify all the deployed contracts in Foreign network. Supported explorers: Blockscout, Etherscan
#FOREIGN_EXPLORER_URL=https://api.etherscan.io/api
# The api key of the explorer api, if required, used to verify all the deployed contracts in Foreign network.
#FOREIGN_EXPLORER_API_KEY=
```

57
deploy/deploy.js Normal file
View File

@ -0,0 +1,57 @@
const fs = require('fs')
const path = require('path')
const { BRIDGE_MODE } = require('./src/loadEnv')
const deployResultsPath = path.join(__dirname, './bridgeDeploymentResults.json')
function writeDeploymentResults(data) {
fs.writeFileSync(deployResultsPath, JSON.stringify(data, null, 4))
console.log('Contracts Deployment have been saved to `bridgeDeploymentResults.json`')
}
async function deployAMBEnsMirroring() {
const preDeploy = require('./src/amb_ens_mirroring/preDeploy')
const deployHome = require('./src/amb_ens_mirroring/home')
const deployForeign = require('./src/amb_ens_mirroring/foreign')
const initializeHome = require('./src/amb_ens_mirroring/initializeHome')
const initializeForeign = require('./src/amb_ens_mirroring/initializeForeign')
await preDeploy()
const { homeBridgeMediator, publicResolver } = await deployHome()
const { foreignBridgeMediator } = await deployForeign()
await initializeHome({
homeBridge: homeBridgeMediator.address,
foreignBridge: foreignBridgeMediator.address,
publicResolver: publicResolver.address
})
await initializeForeign({
foreignBridge: foreignBridgeMediator.address,
homeBridge: homeBridgeMediator.address
})
console.log('\nDeployment has been completed.\n\n')
console.log(`[ Home ] Bridge Mediator: ${homeBridgeMediator.address}`)
console.log(`[ Foreign ] Bridge Mediator: ${foreignBridgeMediator.address}`)
writeDeploymentResults({
homeBridge: {
homeBridgeMediator,
publicResolver
},
foreignBridge: {
foreignBridgeMediator
}
})
}
async function main() {
console.log(`Bridge mode: ${BRIDGE_MODE}`)
switch (BRIDGE_MODE) {
case 'AMB_ENS_MIRRORING':
await deployAMBEnsMirroring()
break
default:
throw new Error('Invalid BRIDGE_MODE. Please specify on of [AMB_ENS_MIRRORING]')
}
}
main().catch(e => console.log('Error:', e))

View File

@ -0,0 +1,25 @@
BRIDGE_MODE=AMB_ENS_MIRRORING
DEPLOYMENT_ACCOUNT_PRIVATE_KEY=67..14
DEPLOYMENT_GAS_LIMIT_EXTRA=0.2
HOME_DEPLOYMENT_GAS_PRICE=10000000000
FOREIGN_DEPLOYMENT_GAS_PRICE=10000000000
GET_RECEIPT_INTERVAL_IN_MILLISECONDS=3000
HOME_RPC_URL=https://core.poa.network
HOME_BRIDGE_OWNER=0x
HOME_UPGRADEABLE_ADMIN=0x
HOME_AMB_BRIDGE=0x
FOREIGN_RPC_URL=https://mainnet.infura.io
FOREIGN_BRIDGE_OWNER=0x
FOREIGN_UPGRADEABLE_ADMIN=0x
FOREIGN_MEDIATOR_REQUEST_GAS_LIMIT=1000000
FOREIGN_AMB_BRIDGE=0x
FOREIGN_ENS_REGISTRY_ADDRESS=0x
#HOME_EXPLORER_URL=https://blockscout.com/poa/core/api
#HOME_EXPLORER_API_KEY=
#FOREIGN_EXPLORER_URL=https://api.etherscan.io/api
#FOREIGN_EXPLORER_API_KEY=

View File

@ -0,0 +1,44 @@
const { web3Foreign, FOREIGN_RPC_URL } = require('../web3')
const { deployContract, privateKeyToAddress, upgradeProxy } = require('../deploymentUtils')
const { EternalStorageProxy, ForeignAMBENSMirror } = require('../loadContracts')
const { DEPLOYMENT_ACCOUNT_PRIVATE_KEY } = require('../loadEnv')
const DEPLOYMENT_ACCOUNT_ADDRESS = privateKeyToAddress(DEPLOYMENT_ACCOUNT_PRIVATE_KEY)
async function deployForeign() {
let nonce = await web3Foreign.eth.getTransactionCount(DEPLOYMENT_ACCOUNT_ADDRESS)
console.log('\n[Foreign] Deploying Bridge Mediator storage\n')
const foreignBridgeStorage = await deployContract(EternalStorageProxy, [], {
from: DEPLOYMENT_ACCOUNT_ADDRESS,
network: 'foreign',
nonce
})
nonce++
console.log('[Foreign] Bridge Mediator Storage: ', foreignBridgeStorage.options.address)
console.log('\n[Foreign] Deploying Bridge Mediator implementation\n')
const foreignBridgeImplementation = await deployContract(ForeignAMBENSMirror, [], {
from: DEPLOYMENT_ACCOUNT_ADDRESS,
network: 'foreign',
nonce
})
nonce++
console.log('[Foreign] Bridge Mediator Implementation: ', foreignBridgeImplementation.options.address)
console.log('\n[Foreign] Hooking up Mediator storage to Mediator implementation')
await upgradeProxy({
proxy: foreignBridgeStorage,
implementationAddress: foreignBridgeImplementation.options.address,
version: '1',
nonce,
url: FOREIGN_RPC_URL
})
console.log('\nForeign part of ENS Mirror bridge deployed\n')
return {
foreignBridgeMediator: { address: foreignBridgeStorage.options.address }
}
}
module.exports = deployForeign

View File

@ -0,0 +1,52 @@
const { web3Home, HOME_RPC_URL } = require('../web3')
const { deployContract, privateKeyToAddress, upgradeProxy } = require('../deploymentUtils')
const { DEPLOYMENT_ACCOUNT_PRIVATE_KEY } = require('../loadEnv')
const { EternalStorageProxy, HomeAMBENSMirror, PublicResolver } = require('../loadContracts')
const DEPLOYMENT_ACCOUNT_ADDRESS = privateKeyToAddress(DEPLOYMENT_ACCOUNT_PRIVATE_KEY)
async function deployHome() {
let nonce = await web3Home.eth.getTransactionCount(DEPLOYMENT_ACCOUNT_ADDRESS)
console.log('\n[Home] Deploying Bridge Mediator storage\n')
const homeBridgeStorage = await deployContract(EternalStorageProxy, [], {
from: DEPLOYMENT_ACCOUNT_ADDRESS,
nonce
})
nonce++
console.log('[Home] Bridge Mediator Storage: ', homeBridgeStorage.options.address)
console.log('\n[Home] Deploying Bridge Mediator implementation\n')
const homeBridgeImplementation = await deployContract(HomeAMBENSMirror, [], {
from: DEPLOYMENT_ACCOUNT_ADDRESS,
nonce
})
nonce++
console.log('[Home] Bridge Mediator Implementation: ', homeBridgeImplementation.options.address)
console.log('\n[Home] Deploying PublicResolver\n')
const resolver = await deployContract(PublicResolver, [homeBridgeStorage.options.address], {
from: DEPLOYMENT_ACCOUNT_ADDRESS,
nonce
})
nonce++
console.log('[Home] PublicResolver: ', resolver.options.address)
console.log('\n[Home] Hooking up Mediator storage to Mediator implementation')
await upgradeProxy({
proxy: homeBridgeStorage,
implementationAddress: homeBridgeImplementation.options.address,
version: '1',
nonce,
url: HOME_RPC_URL
})
console.log('\nHome part of ENS Mirror bridge deployed\n')
return {
homeBridgeMediator: { address: homeBridgeStorage.options.address },
publicResolver: { address: resolver.options.address }
}
}
module.exports = deployHome

View File

@ -0,0 +1,80 @@
const Web3Utils = require('web3').utils
const assert = require('assert')
const { web3Home, web3Foreign, FOREIGN_RPC_URL, deploymentPrivateKey } = require('../web3')
const { EternalStorageProxy, ForeignAMBENSMirror } = require('../loadContracts')
const {
privateKeyToAddress,
sendRawTxForeign,
assertStateWithRetry,
transferProxyOwnership
} = require('../deploymentUtils')
const {
FOREIGN_BRIDGE_OWNER,
FOREIGN_UPGRADEABLE_ADMIN,
FOREIGN_AMB_BRIDGE,
FOREIGN_MEDIATOR_REQUEST_GAS_LIMIT,
DEPLOYMENT_ACCOUNT_PRIVATE_KEY,
FOREIGN_ENS_REGISTRY_ADDRESS
} = require('../loadEnv')
const DEPLOYMENT_ACCOUNT_ADDRESS = privateKeyToAddress(DEPLOYMENT_ACCOUNT_PRIVATE_KEY)
async function initializeMediator({
contract,
params: { bridgeContract, mediatorContract, requestGasLimit, owner, ensRegistry }
}) {
console.log(`
AMB contract: ${bridgeContract},
Mediator contract: ${mediatorContract},
MEDIATOR_REQUEST_GAS_LIMIT : ${requestGasLimit},
OWNER: ${owner},
ENS_REGISTRY_ADDRESS: ${ensRegistry}
`)
return contract.methods.initialize(bridgeContract, mediatorContract, requestGasLimit, owner, ensRegistry).encodeABI()
}
async function initialize({ homeBridge, foreignBridge }) {
let nonce = await web3Foreign.eth.getTransactionCount(DEPLOYMENT_ACCOUNT_ADDRESS)
const contract = new web3Home.eth.Contract(ForeignAMBENSMirror.abi, foreignBridge)
console.log('\n[Foreign] Initializing Bridge Mediator with following parameters:')
const initializeData = await initializeMediator({
contract,
params: {
bridgeContract: FOREIGN_AMB_BRIDGE,
mediatorContract: homeBridge,
requestGasLimit: FOREIGN_MEDIATOR_REQUEST_GAS_LIMIT,
owner: FOREIGN_BRIDGE_OWNER,
ensRegistry: FOREIGN_ENS_REGISTRY_ADDRESS
}
})
const txInitialize = await sendRawTxForeign({
data: initializeData,
nonce,
to: foreignBridge,
privateKey: deploymentPrivateKey,
url: FOREIGN_RPC_URL
})
if (txInitialize.status) {
assert.strictEqual(Web3Utils.hexToNumber(txInitialize.status), 1, 'Transaction Failed')
} else {
await assertStateWithRetry(contract.methods.isInitialized().call, true)
}
nonce++
console.log('\n[Foreign] Transferring bridge mediator proxy ownership to upgradeability admin')
const proxy = new web3Foreign.eth.Contract(EternalStorageProxy.abi, foreignBridge)
await transferProxyOwnership({
proxy,
newOwner: FOREIGN_UPGRADEABLE_ADMIN,
nonce,
url: FOREIGN_RPC_URL
})
}
module.exports = initialize

View File

@ -0,0 +1,73 @@
const Web3Utils = require('web3').utils
const assert = require('assert')
const { web3Home, HOME_RPC_URL, deploymentPrivateKey } = require('../web3')
const { EternalStorageProxy, HomeAMBENSMirror } = require('../loadContracts')
const {
privateKeyToAddress,
sendRawTxHome,
assertStateWithRetry,
transferProxyOwnership
} = require('../deploymentUtils')
const {
HOME_AMB_BRIDGE,
HOME_BRIDGE_OWNER,
HOME_UPGRADEABLE_ADMIN,
DEPLOYMENT_ACCOUNT_PRIVATE_KEY
} = require('../loadEnv')
const DEPLOYMENT_ACCOUNT_ADDRESS = privateKeyToAddress(DEPLOYMENT_ACCOUNT_PRIVATE_KEY)
async function initializeMediator({ contract, params: { bridgeContract, mediatorContract, owner, resolverContract } }) {
console.log(`
AMB contract: ${bridgeContract},
Mediator contract: ${mediatorContract},
OWNER: ${owner},
PUBLIC_RESOLVER: ${resolverContract}
`)
return contract.methods.initialize(bridgeContract, mediatorContract, owner, resolverContract).encodeABI()
}
async function initialize({ homeBridge, foreignBridge, publicResolver }) {
let nonce = await web3Home.eth.getTransactionCount(DEPLOYMENT_ACCOUNT_ADDRESS)
const mediatorContract = new web3Home.eth.Contract(HomeAMBENSMirror.abi, homeBridge)
console.log('\n[Home] Initializing Bridge Mediator with following parameters:')
const initializeMediatorData = await initializeMediator({
contract: mediatorContract,
params: {
bridgeContract: HOME_AMB_BRIDGE,
mediatorContract: foreignBridge,
owner: HOME_BRIDGE_OWNER,
resolverContract: publicResolver
}
})
const txInitializeMediator = await sendRawTxHome({
data: initializeMediatorData,
nonce,
to: homeBridge,
privateKey: deploymentPrivateKey,
url: HOME_RPC_URL
})
if (txInitializeMediator.status) {
assert.strictEqual(Web3Utils.hexToNumber(txInitializeMediator.status), 1, 'Transaction Failed')
} else {
await assertStateWithRetry(mediatorContract.methods.isInitialized().call, true)
}
nonce++
console.log('\n[Home] Transferring bridge mediator proxy ownership to upgradeability admin')
const mediatorProxy = new web3Home.eth.Contract(EternalStorageProxy.abi, homeBridge)
await transferProxyOwnership({
proxy: mediatorProxy,
newOwner: HOME_UPGRADEABLE_ADMIN,
nonce,
url: HOME_RPC_URL
})
}
module.exports = initialize

View File

@ -0,0 +1,22 @@
const { web3Home, web3Foreign } = require('../web3')
const { HOME_AMB_BRIDGE, FOREIGN_AMB_BRIDGE, FOREIGN_ENS_REGISTRY_ADDRESS } = require('../loadEnv')
const { isContract } = require('../deploymentUtils')
async function preDeploy() {
const isHomeAMBAContract = await isContract(web3Home, HOME_AMB_BRIDGE)
if (!isHomeAMBAContract) {
throw new Error(`HOME_AMB_BRIDGE should be a contract address`)
}
const isForeignAMBAContract = await isContract(web3Foreign, FOREIGN_AMB_BRIDGE)
if (!isForeignAMBAContract) {
throw new Error(`FOREIGN_AMB_BRIDGE should be a contract address`)
}
const isENSRegistry = await isContract(web3Foreign, FOREIGN_ENS_REGISTRY_ADDRESS)
if (!isENSRegistry) {
throw new Error(`FOREIGN_ENS_REGISTRY_ADDRESS should be a contract address`)
}
}
module.exports = preDeploy

15
deploy/src/constants.js Normal file
View File

@ -0,0 +1,15 @@
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'
const EXPLORER_TYPES = {
ETHERSCAN: 'etherscan',
BLOCKSCOUT: 'blockscout'
}
const REQUEST_STATUS = {
OK: 'OK'
}
module.exports = {
ZERO_ADDRESS,
EXPLORER_TYPES,
REQUEST_STATUS
}

View File

@ -0,0 +1,268 @@
/* eslint-disable no-param-reassign */
const BigNumber = require('bignumber.js')
const Web3 = require('web3')
const Tx = require('ethereumjs-tx')
const Web3Utils = require('web3').utils
const fetch = require('node-fetch')
const assert = require('assert')
const promiseRetry = require('promise-retry')
const {
web3Home,
web3Foreign,
deploymentPrivateKey,
FOREIGN_RPC_URL,
HOME_RPC_URL,
GAS_LIMIT_EXTRA,
HOME_DEPLOYMENT_GAS_PRICE,
FOREIGN_DEPLOYMENT_GAS_PRICE,
GET_RECEIPT_INTERVAL_IN_MILLISECONDS,
HOME_EXPLORER_URL,
FOREIGN_EXPLORER_URL,
HOME_EXPLORER_API_KEY,
FOREIGN_EXPLORER_API_KEY
} = require('./web3')
const verifier = require('./utils/verifier')
async function deployContract(contractJson, args, { from, network, nonce }) {
let web3
let url
let gasPrice
let apiUrl
let apiKey
if (network === 'foreign') {
web3 = web3Foreign
url = FOREIGN_RPC_URL
gasPrice = FOREIGN_DEPLOYMENT_GAS_PRICE
apiUrl = FOREIGN_EXPLORER_URL
apiKey = FOREIGN_EXPLORER_API_KEY
} else {
web3 = web3Home
url = HOME_RPC_URL
gasPrice = HOME_DEPLOYMENT_GAS_PRICE
apiUrl = HOME_EXPLORER_URL
apiKey = HOME_EXPLORER_API_KEY
}
const options = {
from
}
const instance = new web3.eth.Contract(contractJson.abi, options)
const result = await instance
.deploy({
data: contractJson.bytecode,
arguments: args
})
.encodeABI()
const tx = await sendRawTx({
data: result,
nonce: Web3Utils.toHex(nonce),
to: null,
privateKey: deploymentPrivateKey,
url,
gasPrice
})
if (Web3Utils.hexToNumber(tx.status) !== 1 && !tx.contractAddress) {
throw new Error('Tx failed')
}
instance.options.address = tx.contractAddress
instance.deployedBlockNumber = tx.blockNumber
if (apiUrl) {
let constructorArguments
if (args.length) {
constructorArguments = result.substring(contractJson.bytecode.length)
}
await verifier({ artifact: contractJson, constructorArguments, address: tx.contractAddress, apiUrl, apiKey })
}
return instance
}
async function sendRawTxHome(options) {
return sendRawTx({
...options,
gasPrice: HOME_DEPLOYMENT_GAS_PRICE
})
}
async function sendRawTxForeign(options) {
return sendRawTx({
...options,
gasPrice: FOREIGN_DEPLOYMENT_GAS_PRICE
})
}
async function sendRawTx({ data, nonce, to, privateKey, url, gasPrice, value }) {
try {
const txToEstimateGas = {
from: privateKeyToAddress(Web3Utils.bytesToHex(privateKey)),
value,
to,
data
}
const estimatedGas = BigNumber(await sendNodeRequest(url, 'eth_estimateGas', txToEstimateGas))
const blockData = await sendNodeRequest(url, 'eth_getBlockByNumber', ['latest', false])
const blockGasLimit = BigNumber(blockData.gasLimit)
if (estimatedGas.isGreaterThan(blockGasLimit)) {
throw new Error(
`estimated gas greater (${estimatedGas.toString()}) than the block gas limit (${blockGasLimit.toString()})`
)
}
let gas = estimatedGas.multipliedBy(BigNumber(1 + GAS_LIMIT_EXTRA))
if (gas.isGreaterThan(blockGasLimit)) {
gas = blockGasLimit
} else {
gas = gas.toFixed(0)
}
const rawTx = {
nonce,
gasPrice: Web3Utils.toHex(gasPrice),
gasLimit: Web3Utils.toHex(gas),
to,
data,
value
}
const tx = new Tx(rawTx)
tx.sign(privateKey)
const serializedTx = tx.serialize()
const txHash = await sendNodeRequest(url, 'eth_sendRawTransaction', `0x${serializedTx.toString('hex')}`)
console.log('pending txHash', txHash)
return await getReceipt(txHash, url)
} catch (e) {
console.error(e)
}
}
async function sendNodeRequest(url, method, signedData) {
if (!Array.isArray(signedData)) {
signedData = [signedData]
}
const request = await fetch(url, {
headers: {
'Content-type': 'application/json'
},
method: 'POST',
body: JSON.stringify({
jsonrpc: '2.0',
method,
params: signedData,
id: 1
})
})
const json = await request.json()
if (typeof json.error === 'undefined' || json.error === null) {
if (method === 'eth_sendRawTransaction') {
assert.strictEqual(json.result.length, 66, `Tx wasn't sent ${json}`)
}
return json.result
}
throw new Error(`web3 RPC failed: ${JSON.stringify(json.error)}`)
}
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function getReceipt(txHash, url) {
await timeout(GET_RECEIPT_INTERVAL_IN_MILLISECONDS)
let receipt = await sendNodeRequest(url, 'eth_getTransactionReceipt', txHash)
if (receipt === null || receipt.blockNumber === null) {
receipt = await getReceipt(txHash, url)
}
return receipt
}
function add0xPrefix(s) {
if (s.indexOf('0x') === 0) {
return s
}
return `0x${s}`
}
function privateKeyToAddress(privateKey) {
return new Web3().eth.accounts.privateKeyToAccount(add0xPrefix(privateKey)).address
}
async function upgradeProxy({ proxy, implementationAddress, version, nonce, url }) {
const data = await proxy.methods.upgradeTo(version, implementationAddress).encodeABI()
const sendTx = getSendTxMethod(url)
const result = await sendTx({
data,
nonce,
to: proxy.options.address,
privateKey: deploymentPrivateKey,
url
})
if (result.status) {
assert.strictEqual(Web3Utils.hexToNumber(result.status), 1, 'Transaction Failed')
} else {
await assertStateWithRetry(proxy.methods.implementation().call, implementationAddress)
}
}
async function transferProxyOwnership({ proxy, newOwner, nonce, url }) {
const data = await proxy.methods.transferProxyOwnership(newOwner).encodeABI()
const sendTx = getSendTxMethod(url)
const result = await sendTx({
data,
nonce,
to: proxy.options.address,
privateKey: deploymentPrivateKey,
url
})
if (result.status) {
assert.strictEqual(Web3Utils.hexToNumber(result.status), 1, 'Transaction Failed')
} else {
await assertStateWithRetry(proxy.methods.proxyOwner().call, newOwner)
}
}
async function transferOwnership({ contract, newOwner, nonce, url }) {
const data = await contract.methods.transferOwnership(newOwner).encodeABI()
const sendTx = getSendTxMethod(url)
const result = await sendTx({
data,
nonce,
to: contract.options.address,
privateKey: deploymentPrivateKey,
url
})
if (result.status) {
assert.strictEqual(Web3Utils.hexToNumber(result.status), 1, 'Transaction Failed')
} else {
await assertStateWithRetry(contract.methods.owner().call, newOwner)
}
}
async function assertStateWithRetry(fn, expected) {
return promiseRetry(async retry => {
const value = await fn()
if (value !== expected && value.toString() !== expected) {
retry(`Transaction Failed. Expected: ${expected} Actual: ${value}`)
}
})
}
function getSendTxMethod(url) {
return url === HOME_RPC_URL ? sendRawTxHome : sendRawTxForeign
}
async function isContract(web3, address) {
const code = await web3.eth.getCode(address)
return code !== '0x' && code !== '0x0'
}
module.exports = {
deployContract,
sendRawTxHome,
sendRawTxForeign,
privateKeyToAddress,
upgradeProxy,
transferProxyOwnership,
transferOwnership,
assertStateWithRetry,
isContract
}

View File

@ -0,0 +1,10 @@
/* eslint import/no-dynamic-require: 0 */
const buildPath = 'contracts'
module.exports = {
EternalStorageProxy: require(`../../build/${buildPath}/EternalStorageProxy.json`),
ForeignAMBENSMirror: require(`../../build/${buildPath}/ForeignAMBENSMirror.json`),
HomeAMBENSMirror: require(`../../build/${buildPath}/HomeAMBENSMirror.json`),
PublicResolver: require(`../../build/${buildPath}/PublicResolver.json`)
}

48
deploy/src/loadEnv.js Normal file
View File

@ -0,0 +1,48 @@
const path = require('path')
require('dotenv').config({
path: path.join(__dirname, '..', '.env')
})
const { isAddress, toBN } = require('web3').utils
const envalid = require('envalid')
const bigNumValidator = envalid.makeValidator(x => toBN(x))
const validateAddress = address => {
if (isAddress(address)) {
return address
}
throw new Error(`Invalid address: ${address}`)
}
const addressValidator = envalid.makeValidator(validateAddress)
const { BRIDGE_MODE } = process.env
let validations = {
DEPLOYMENT_ACCOUNT_PRIVATE_KEY: envalid.str(),
DEPLOYMENT_GAS_LIMIT_EXTRA: envalid.num(),
HOME_DEPLOYMENT_GAS_PRICE: bigNumValidator(),
FOREIGN_DEPLOYMENT_GAS_PRICE: bigNumValidator(),
GET_RECEIPT_INTERVAL_IN_MILLISECONDS: bigNumValidator(),
HOME_RPC_URL: envalid.str(),
HOME_BRIDGE_OWNER: addressValidator(),
HOME_UPGRADEABLE_ADMIN: addressValidator(),
FOREIGN_RPC_URL: envalid.str(),
FOREIGN_BRIDGE_OWNER: addressValidator(),
FOREIGN_UPGRADEABLE_ADMIN: addressValidator(),
HOME_AMB_BRIDGE: addressValidator(),
FOREIGN_AMB_BRIDGE: addressValidator()
}
switch (BRIDGE_MODE) {
case 'AMB_ENS_MIRRORING':
validations = {
...validations,
FOREIGN_MEDIATOR_REQUEST_GAS_LIMIT: bigNumValidator(),
FOREIGN_ENS_REGISTRY_ADDRESS: addressValidator()
}
break
default:
throw new Error('Invalid BRIDGE_MODE. Please specify on of [AMB_ENS_MIRRORING]')
}
module.exports = envalid.cleanEnv(process.env, validations)

View File

@ -0,0 +1,118 @@
const axios = require('axios')
const querystring = require('querystring')
const fs = require('fs')
const path = require('path')
const promiseRetry = require('promise-retry')
const { EXPLORER_TYPES, REQUEST_STATUS } = require('../constants')
const basePath = path.join(__dirname, '..', '..', '..', 'flats')
const flat = async contractPath => {
const pathArray = contractPath.split('/')
const name = pathArray[pathArray.length - 1]
const module = pathArray[pathArray.length - 2]
const flatName = name.replace('.sol', '_flat.sol')
const filePath = path.join(basePath, module, flatName)
return fs.readFileSync(filePath).toString()
}
const sendRequest = (url, queries) => axios.post(url, querystring.stringify(queries))
const sendVerifyRequestEtherscan = async (contractPath, options) => {
const contract = await flat(contractPath)
const postQueries = {
apikey: options.apiKey,
module: 'contract',
action: 'verifysourcecode',
contractaddress: options.address,
sourceCode: contract,
codeformat: 'solidity-single-file',
contractname: options.contractName,
compilerversion: options.compiler,
optimizationUsed: options.optimizationUsed ? 1 : 0,
runs: options.runs,
constructorArguements: options.constructorArguments,
evmversion: options.evmVersion
}
return sendRequest(options.apiUrl, postQueries)
}
const sendVerifyRequestBlockscout = async (contractPath, options) => {
const contract = await flat(contractPath)
const postQueries = {
module: 'contract',
action: 'verify',
addressHash: options.address,
contractSourceCode: contract,
name: options.contractName,
compilerVersion: options.compiler,
optimization: options.optimizationUsed,
optimizationRuns: options.runs,
constructorArguments: options.constructorArguments,
evmVersion: options.evmVersion
}
return sendRequest(options.apiUrl, postQueries)
}
const getExplorerType = apiUrl =>
apiUrl && apiUrl.includes('etherscan') ? EXPLORER_TYPES.ETHERSCAN : EXPLORER_TYPES.BLOCKSCOUT
const verifyContract = async (contract, params, type) => {
try {
let result
if (type === EXPLORER_TYPES.ETHERSCAN) {
result = await sendVerifyRequestEtherscan(contract, params)
} else {
result = await sendVerifyRequestBlockscout(contract, params)
}
if (result.data.message === REQUEST_STATUS.OK) {
console.log(`${params.address} verified in ${type}`)
return true
}
} catch (e) {
return false
}
return false
}
const verifier = async ({ artifact, address, constructorArguments, apiUrl, apiKey }) => {
const type = getExplorerType(apiUrl)
let metadata
try {
metadata = JSON.parse(artifact.metadata)
} catch (e) {
console.log('Error on decoding values from artifact')
}
const contract = artifact.sourcePath
const params = {
address,
contractName: artifact.contractName,
constructorArguments,
compiler: `v${artifact.compiler.version.replace('.Emscripten.clang', '')}`,
optimizationUsed: metadata.settings.optimizer.enabled,
runs: metadata.settings.optimizer.runs,
evmVersion: metadata.settings.evmVersion,
apiUrl,
apiKey
}
try {
await promiseRetry(async retry => {
const verified = await verifyContract(contract, params, type)
if (!verified) {
retry()
}
})
} catch (e) {
console.log(`It was not possible to verify ${address} in ${type}`)
}
}
module.exports = verifier

40
deploy/src/web3.js Normal file
View File

@ -0,0 +1,40 @@
const Web3 = require('web3')
const env = require('./loadEnv')
const {
HOME_RPC_URL,
FOREIGN_RPC_URL,
GET_RECEIPT_INTERVAL_IN_MILLISECONDS,
DEPLOYMENT_ACCOUNT_PRIVATE_KEY,
HOME_EXPLORER_URL,
FOREIGN_EXPLORER_URL,
HOME_EXPLORER_API_KEY,
FOREIGN_EXPLORER_API_KEY
} = env
const homeProvider = new Web3.providers.HttpProvider(HOME_RPC_URL)
const web3Home = new Web3(homeProvider)
const foreignProvider = new Web3.providers.HttpProvider(FOREIGN_RPC_URL)
const web3Foreign = new Web3(foreignProvider)
const { HOME_DEPLOYMENT_GAS_PRICE, FOREIGN_DEPLOYMENT_GAS_PRICE } = env
const GAS_LIMIT_EXTRA = env.DEPLOYMENT_GAS_LIMIT_EXTRA
const deploymentPrivateKey = Buffer.from(DEPLOYMENT_ACCOUNT_PRIVATE_KEY, 'hex')
module.exports = {
web3Home,
web3Foreign,
deploymentPrivateKey,
HOME_RPC_URL,
FOREIGN_RPC_URL,
GAS_LIMIT_EXTRA,
HOME_DEPLOYMENT_GAS_PRICE,
FOREIGN_DEPLOYMENT_GAS_PRICE,
GET_RECEIPT_INTERVAL_IN_MILLISECONDS,
HOME_EXPLORER_URL,
FOREIGN_EXPLORER_URL,
HOME_EXPLORER_API_KEY,
FOREIGN_EXPLORER_API_KEY
}

12
docker-compose.yml Normal file
View File

@ -0,0 +1,12 @@
version: "3.3"
services:
amb-mediators:
build: .
command: "true"
env_file: ./deploy/.env
dev:
build:
context: .
dockerfile: Dockerfile.dev
command: "true"
env_file: ./deploy/.env

14
flatten.sh Executable file
View File

@ -0,0 +1,14 @@
#!/usr/bin/env bash
if [ -d flats ]; then
rm -rf flats
fi
mkdir -p flats/amb_ens_mirroring
FLATTENER=./node_modules/.bin/truffle-flattener
echo "Flattening contracts related to ENS mirroring on top of AMB bridge"
${FLATTENER} contracts/amb_ens_mirroring/HomeAMBENSMirror.sol > flats/amb_ens_mirroring/HomeAMBENSMirror_flat.sol
${FLATTENER} contracts/amb_ens_mirroring/ForeignAMBENSMirror.sol > flats/amb_ens_mirroring/ForeignAMBENSMirror_flat.sol
cp contracts/amb_ens_mirroring/PublicResolver.sol.flat flats/amb_ens_mirroring/PublicResolver_flat.sol

21757
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

65
package.json Normal file
View File

@ -0,0 +1,65 @@
{
"name": "amb-mediators",
"version": "0.0.1",
"description": "Contracts for mediators intended to work on top of AMB",
"main": "index.js",
"scripts": {
"test": "scripts/test.sh",
"test:gasreport": "GASREPORT=true npm run test",
"test:gasreport:ci": "npm run test:gasreport && npx codechecks",
"compile": "truffle compile && cp contracts/amb_ens_mirroring/PublicResolver.json build/contracts/PublicResolver.json",
"flatten": "bash flatten.sh",
"lint": "npm run lint:js && npm run lint:sol",
"lint:js": "eslint .",
"lint:js:fix": "eslint . --fix",
"lint:sol": "solhint --max-warnings 0 \"contracts/**/*.sol\"",
"lint:sol:prettier:fix": "prettier --write \"contracts/**/*.sol\"",
"coverage": "SOLIDITY_COVERAGE=true scripts/test.sh",
"deploy": "if test \"$NOFLAT\" != \"true\" ; then npm run flatten; fi && cd deploy && node deploy.js"
},
"author": "POA network",
"license": "GPLv3",
"dependencies": {
"axios": "^0.19.0",
"bignumber.js": "^7.2.1",
"dotenv": "^5.0.1",
"envalid": "^4.1.4",
"ethereumjs-tx": "^1.3.4",
"node-fetch": "^2.1.2",
"promise-retry": "^1.1.1",
"querystring": "^0.2.0",
"web3": "^1.2.11"
},
"devDependencies": {
"@0x/sol-coverage": "^4.0.10",
"@0x/sol-trace": "^3.0.10",
"@0x/subproviders": "^6.1.1",
"@codechecks/client": "^0.1.9",
"@truffle/contract": "^4.2.17",
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"chai-bn": "^0.1.1",
"eslint": "^6.3.0",
"eslint-config-airbnb-base": "^14.0.0",
"eslint-config-prettier": "^6.2.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-node": "^10.0.0",
"eslint-plugin-prettier": "^3.0.1",
"eth-gas-reporter": "^0.2.11",
"ethereumjs-abi": "0.6.8",
"ethereumjs-util": "5.2.0",
"ganache-cli": "^6.6.0",
"istanbul": "^0.4.5",
"openzeppelin-solidity": "1.12.0",
"prettier": "^1.18.2",
"prettier-plugin-solidity": "^1.0.0-alpha.32",
"solhint": "^2.2.0",
"solhint-plugin-prettier": "0.0.3",
"tokenbridge-contracts": "git+https://github.com/poanetwork/tokenbridge-contracts.git",
"truffle": "^5.0.35",
"truffle-flattener": "^1.4.2"
},
"engines": {
"node": ">=10.0.0"
}
}

62
scripts/test.sh Executable file
View File

@ -0,0 +1,62 @@
#!/usr/bin/env bash
# Exit script as soon as a command fails.
set -o errexit
node_modules/.bin/truffle version
# Executes cleanup function at script exit.
trap cleanup EXIT
cleanup() {
# Kill the ganache instance that we started (if we started one and if it's still running).
if [ -n "$ganache_pid" ] && ps -p $ganache_pid > /dev/null; then
kill -9 $ganache_pid
fi
}
if [ "$SOLIDITY_COVERAGE" = true ]; then
ganache_port=8555
else
ganache_port=8545
fi
ganache_running() {
nc -z localhost "$ganache_port"
}
start_ganache() {
# We define 10 accounts with balance 1M ether, needed for high-value tests.
local accounts=(
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501200,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501201,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501202,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501203,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501204,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501205,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501206,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501207,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501208,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501209,1000000000000000000000000"
--account="0x19fba401d77e4113b15095e9aa7117bcd25adcfac7f6111f8298894eef443600,1000000000000000000000000"
)
if [ "$SOLIDITY_COVERAGE" != true ]; then
node_modules/.bin/ganache-cli --gasLimit 0xfffffffffff "${accounts[@]}" > /dev/null &
fi
ganache_pid=$!
}
if [ "$SOLIDITY_COVERAGE" != true ]; then
if ganache_running; then
echo "Using existing ganache instance"
else
echo "Starting our own ganache instance"
start_ganache
fi
fi
if [ "$SOLIDITY_COVERAGE" = true ]; then
node --max-old-space-size=4096 node_modules/.bin/truffle test 2>/dev/null; istanbul report lcov
else
node_modules/.bin/truffle test --network ganache "$@"
fi

View File

@ -0,0 +1,178 @@
const ForeignAMBENSMirror = artifacts.require('ForeignAMBENSMirror.sol')
const HomeAMBENSMirror = artifacts.require('HomeAMBENSMirror.sol')
const AMBMock = artifacts.require('AMBMock.sol')
const ENSMock = artifacts.require('ENSMock.sol')
const truffleContract = require('@truffle/contract')
const { expect } = require('chai')
const { getEvents, expectEventInLogs, ether, strip0x } = require('../helpers/helpers')
const { ZERO_ADDRESS, toBN } = require('../setup')
const PublicResolver = truffleContract(require('../../contracts/amb_ens_mirroring/PublicResolver.json'))
const ZERO = toBN(0)
const maxGasPerTx = ether('1')
const namehash = '0xe2a7126166fa5a6bef227712b773ab8ff63540a3b062b25629c2c4ad856e2293'
contract('ForeignAMBENSMirror', async accounts => {
let contract
let ambBridgeContract
let otherSideMediator
let ens
let resolver
const owner = accounts[0]
const user = accounts[1]
const user2 = accounts[2]
beforeEach(async () => {
contract = await ForeignAMBENSMirror.new()
ambBridgeContract = await AMBMock.new()
await ambBridgeContract.setMaxGasPerTx(maxGasPerTx)
otherSideMediator = await HomeAMBENSMirror.new()
ens = await ENSMock.new()
PublicResolver.setProvider(web3.currentProvider)
PublicResolver.defaults({ from: owner })
resolver = await PublicResolver.new(ens.address)
})
describe('initialize', () => {
it('should initialize parameters', async () => {
// Given
expect(await contract.isInitialized()).to.be.equal(false)
expect(await contract.bridgeContract()).to.be.equal(ZERO_ADDRESS)
expect(await contract.mediatorContractOnOtherSide()).to.be.equal(ZERO_ADDRESS)
expect(await contract.requestGasLimit()).to.be.bignumber.equal(ZERO)
expect(await contract.owner()).to.be.equal(ZERO_ADDRESS)
expect(await contract.ensRegistry()).to.be.equal(ZERO_ADDRESS)
// When
// not valid bridge address
await contract.initialize(ZERO_ADDRESS, otherSideMediator.address, maxGasPerTx, owner, ens.address).should.be
.rejected
// maxGasPerTx > bridge maxGasPerTx
await contract.initialize(ambBridgeContract.address, otherSideMediator.address, ether('2'), owner, ens.address)
.should.be.rejected
// not valid owner
await contract.initialize(
ambBridgeContract.address,
otherSideMediator.address,
maxGasPerTx,
ZERO_ADDRESS,
ens.address
).should.be.rejected
// not valid ens registry
await contract.initialize(ambBridgeContract.address, otherSideMediator.address, maxGasPerTx, owner, owner).should
.be.rejected
await contract.initialize(ambBridgeContract.address, otherSideMediator.address, maxGasPerTx, owner, ens.address)
.should.be.fulfilled
// already initialized
await contract.initialize(ambBridgeContract.address, otherSideMediator.address, maxGasPerTx, owner, ens.address)
.should.be.rejected
// Then
expect(await contract.isInitialized()).to.be.equal(true)
expect(await contract.bridgeContract()).to.be.equal(ambBridgeContract.address)
expect(await contract.mediatorContractOnOtherSide()).to.be.equal(otherSideMediator.address)
expect(await contract.requestGasLimit()).to.be.bignumber.equal(maxGasPerTx)
expect(await contract.owner()).to.be.equal(owner)
expect(await contract.ensRegistry()).to.be.equal(ens.address)
})
})
describe('getBridgeMode', () => {
it('should return mediator mode and interface', async function() {
const bridgeModeHash = '0xa10d4bc8' // 4 bytes of keccak256('ens-mirror-amb')
expect(await contract.getBridgeMode()).to.be.equal(bridgeModeHash)
const { major, minor, patch } = await contract.getBridgeInterfacesVersion()
major.should.be.bignumber.gte(ZERO)
minor.should.be.bignumber.gte(ZERO)
patch.should.be.bignumber.gte(ZERO)
})
})
describe('bridgeENSNode', () => {
beforeEach(async () => {
await contract.initialize(ambBridgeContract.address, otherSideMediator.address, maxGasPerTx, owner, ens.address)
.should.be.fulfilled
})
it('should make a bridge request for existing record', async () => {
await ens.setRecord(namehash, user, resolver.address, 100).should.be.fulfilled
await resolver.methods['setAddr(bytes32,address)'](namehash, user2, { from: user }).should.be.fulfilled
expect(await ens.owner(namehash)).to.be.equal(user)
expect(await ens.resolver(namehash)).to.be.equal(resolver.address)
expect(await resolver.addr(namehash)).to.be.equal(user2)
expect(await ens.ttl(namehash)).to.be.bignumber.equal('100')
const { logs } = await contract.bridgeENSNode(namehash).should.be.fulfilled
const events = await getEvents(ambBridgeContract, { event: 'MockedEvent' })
expect(events.length).to.be.equal(1)
const encodedData = strip0x(events[0].returnValues.encodedData)
const calldata = encodedData.slice(2 * (4 + 20 + 8 + 20 + 20 + 4 + 1 + 1 + 1 + 2 + 2)) // remove AMB header
expect(calldata.slice(0, 8)).to.be.equal('e2a8b775')
const args = web3.eth.abi.decodeParameters(['bytes32', 'address', 'address', 'uint64'], calldata.slice(8))
expect(args[0]).to.be.equal(namehash)
expect(args[1]).to.be.equal(user)
expect(args[2]).to.be.equal(user2)
expect(args[3]).to.be.equal('100')
expectEventInLogs(logs, 'BridgeENSNode', { node: namehash, owner: user })
})
it('should not make a bridge request for unknown record', async () => {
await contract.bridgeENSNode(namehash).should.be.rejected
})
it('should make a bridge request for existing record without address', async () => {
await ens.setRecord(namehash, user, resolver.address, 0).should.be.fulfilled
expect(await ens.owner(namehash)).to.be.equal(user)
expect(await ens.resolver(namehash)).to.be.equal(resolver.address)
expect(await resolver.addr(namehash)).to.be.equal(ZERO_ADDRESS)
expect(await ens.ttl(namehash)).to.be.bignumber.equal('0')
const { logs } = await contract.bridgeENSNode(namehash).should.be.fulfilled
const events = await getEvents(ambBridgeContract, { event: 'MockedEvent' })
expect(events.length).to.be.equal(1)
const encodedData = strip0x(events[0].returnValues.encodedData)
const calldata = encodedData.slice(2 * (4 + 20 + 8 + 20 + 20 + 4 + 1 + 1 + 1 + 2 + 2)) // remove AMB header
expect(calldata.slice(0, 8)).to.be.equal('e2a8b775')
const args = web3.eth.abi.decodeParameters(['bytes32', 'address', 'address', 'uint64'], calldata.slice(8))
expect(args[0]).to.be.equal(namehash)
expect(args[1]).to.be.equal(user)
expect(args[2]).to.be.equal(ZERO_ADDRESS)
expect(args[3]).to.be.equal('0')
expectEventInLogs(logs, 'BridgeENSNode', { node: namehash, owner: user })
})
it('should make a bridge request for existing record without resolver', async () => {
await ens.setOwner(namehash, user).should.be.fulfilled
expect(await ens.owner(namehash)).to.be.equal(user)
expect(await ens.resolver(namehash)).to.be.equal(ZERO_ADDRESS)
expect(await ens.ttl(namehash)).to.be.bignumber.equal('0')
const { logs } = await contract.bridgeENSNode(namehash).should.be.fulfilled
const events = await getEvents(ambBridgeContract, { event: 'MockedEvent' })
expect(events.length).to.be.equal(1)
const encodedData = strip0x(events[0].returnValues.encodedData)
const calldata = encodedData.slice(2 * (4 + 20 + 8 + 20 + 20 + 4 + 1 + 1 + 1 + 2 + 2)) // remove AMB header
expect(calldata.slice(0, 8)).to.be.equal('e2a8b775')
const args = web3.eth.abi.decodeParameters(['bytes32', 'address', 'address', 'uint64'], calldata.slice(8))
expect(args[0]).to.be.equal(namehash)
expect(args[1]).to.be.equal(user)
expect(args[2]).to.be.equal(ZERO_ADDRESS)
expect(args[3]).to.be.equal('0')
expectEventInLogs(logs, 'BridgeENSNode', { node: namehash, owner: user })
})
})
})

View File

@ -0,0 +1,279 @@
const ForeignAMBENSMirror = artifacts.require('ForeignAMBENSMirror.sol')
const HomeAMBENSMirror = artifacts.require('HomeAMBENSMirror.sol')
const AMBMock = artifacts.require('AMBMock.sol')
const ENSMock = artifacts.require('ENSMock.sol')
const truffleContract = require('@truffle/contract')
const { expect } = require('chai')
const { ether, strip0x } = require('../helpers/helpers')
const { ZERO_ADDRESS, toBN } = require('../setup')
const PublicResolver = truffleContract(require('../../contracts/amb_ens_mirroring/PublicResolver.json'))
const ZERO = toBN(0)
const maxGasPerTx = ether('1')
const namehash = '0xe2a7126166fa5a6bef227712b773ab8ff63540a3b062b25629c2c4ad856e2293'
const exampleMessageId = '0xf308b922ab9f8a7128d9d7bc9bce22cd88b2c05c8213f0e2d8104d78e0a9ecbb'
contract('HomeAMBENSMirror', async accounts => {
let contract
let ambBridgeContract
let otherSideAMBBridgeContract
let otherSideMediator
let ens
let resolver
let otherSideResolver
const owner = accounts[0]
const user = accounts[1]
const user2 = accounts[2]
beforeEach(async () => {
contract = await HomeAMBENSMirror.new()
ambBridgeContract = await AMBMock.new()
await ambBridgeContract.setMaxGasPerTx(maxGasPerTx)
otherSideAMBBridgeContract = await AMBMock.new()
await otherSideAMBBridgeContract.setMaxGasPerTx(maxGasPerTx)
otherSideMediator = await ForeignAMBENSMirror.new()
ens = await ENSMock.new()
PublicResolver.setProvider(web3.currentProvider)
PublicResolver.defaults({ from: owner })
resolver = await PublicResolver.new(contract.address)
otherSideResolver = await PublicResolver.new(ens.address)
await otherSideMediator.initialize(
otherSideAMBBridgeContract.address,
contract.address,
maxGasPerTx,
owner,
ens.address
)
})
async function bridgeENSNode(namehash) {
const { receipt } = await otherSideMediator.bridgeENSNode(namehash).should.be.fulfilled
const encodedData = strip0x(
web3.eth.abi.decodeParameters(
['bytes'],
receipt.rawLogs.find(log => log.address === otherSideAMBBridgeContract.address).data
)[0]
)
const data = `0x${encodedData.slice(2 * (4 + 20 + 8 + 20 + 20 + 4 + 1 + 1 + 1 + 2 + 2))}` // remove AMB header
const res = await ambBridgeContract.executeMessageCall(
contract.address,
otherSideMediator.address,
data,
exampleMessageId,
2000000
).should.be.fulfilled
expect(await ambBridgeContract.messageCallStatus(exampleMessageId)).to.be.equal(true)
return res
}
describe('initialize', () => {
it('should initialize parameters', async () => {
// Given
expect(await contract.isInitialized()).to.be.equal(false)
expect(await contract.bridgeContract()).to.be.equal(ZERO_ADDRESS)
expect(await contract.mediatorContractOnOtherSide()).to.be.equal(ZERO_ADDRESS)
expect(await contract.owner()).to.be.equal(ZERO_ADDRESS)
// When
// not valid bridge address
await contract.initialize(ZERO_ADDRESS, otherSideMediator.address, owner, resolver.address).should.be.rejected
// not valid owner
await contract.initialize(ambBridgeContract.address, otherSideMediator.address, ZERO_ADDRESS, resolver.address)
.should.be.rejected
// not valid ens registry
await contract.initialize(ambBridgeContract.address, otherSideMediator.address, owner, owner).should.be.rejected
await contract.initialize(ambBridgeContract.address, otherSideMediator.address, owner, resolver.address).should.be
.fulfilled
// already initialized
await contract.initialize(ambBridgeContract.address, otherSideMediator.address, owner, resolver.address).should.be
.rejected
// Then
expect(await contract.isInitialized()).to.be.equal(true)
expect(await contract.bridgeContract()).to.be.equal(ambBridgeContract.address)
expect(await contract.mediatorContractOnOtherSide()).to.be.equal(otherSideMediator.address)
expect(await contract.owner()).to.be.equal(owner)
})
})
describe('getBridgeMode', () => {
it('should return mediator mode and interface', async function() {
const bridgeModeHash = '0xa10d4bc8' // 4 bytes of keccak256('ens-mirror-amb')
expect(await contract.getBridgeMode()).to.be.equal(bridgeModeHash)
const { major, minor, patch } = await contract.getBridgeInterfacesVersion()
major.should.be.bignumber.gte(ZERO)
minor.should.be.bignumber.gte(ZERO)
patch.should.be.bignumber.gte(ZERO)
})
})
describe('updateENSNode', () => {
beforeEach(async () => {
await contract.initialize(ambBridgeContract.address, otherSideMediator.address, owner, resolver.address).should.be
.fulfilled
})
it('should bridge a new record', async () => {
await ens.setRecord(namehash, user, otherSideResolver.address, 100).should.be.fulfilled
await otherSideResolver.methods['setAddr(bytes32,address)'](namehash, user2, { from: user }).should.be.fulfilled
const { receipt } = await bridgeENSNode(namehash)
expect(await contract.recordExists(namehash)).to.be.equal(true)
expect(await contract.owner(namehash)).to.be.equal(user)
expect(await contract.resolver(namehash)).to.be.equal(resolver.address)
expect(await resolver.addr(namehash)).to.be.equal(user2)
expect(await contract.ttl(namehash)).to.be.bignumber.equal('100')
const log = receipt.rawLogs.find(
log => log.topics[0] === '0x83ced268742277db095b8ecd5e26e9debf1cf75808df747d282285a5abfaac11'
)
expect(log.topics[1]).to.be.equal(namehash)
expect(log.data.includes(strip0x(user).toLowerCase())).to.be.equal(true)
})
it('should update existing record', async () => {
await ens.setRecord(namehash, user, otherSideResolver.address, 100).should.be.fulfilled
await otherSideResolver.methods['setAddr(bytes32,address)'](namehash, user2, { from: user }).should.be.fulfilled
await bridgeENSNode(namehash)
expect(await contract.recordExists(namehash)).to.be.equal(true)
expect(await contract.owner(namehash)).to.be.equal(user)
expect(await contract.resolver(namehash)).to.be.equal(resolver.address)
expect(await resolver.addr(namehash)).to.be.equal(user2)
expect(await contract.ttl(namehash)).to.be.bignumber.equal('100')
await ens.setOwner(namehash, owner).should.be.fulfilled
await ens.setTTL(namehash, 200).should.be.fulfilled
await otherSideResolver.methods['setAddr(bytes32,address)'](namehash, user, { from: owner }).should.be.fulfilled
const { receipt } = await bridgeENSNode(namehash)
expect(await contract.recordExists(namehash)).to.be.equal(true)
expect(await contract.owner(namehash)).to.be.equal(owner)
expect(await contract.resolver(namehash)).to.be.equal(resolver.address)
expect(await resolver.addr(namehash)).to.be.equal(user2)
expect(await contract.ttl(namehash)).to.be.bignumber.equal('100')
const log = receipt.rawLogs.find(
log => log.topics[0] === '0x83ced268742277db095b8ecd5e26e9debf1cf75808df747d282285a5abfaac11'
)
expect(log.topics[1]).to.be.equal(namehash)
expect(log.data.includes(strip0x(owner).toLowerCase())).to.be.equal(true)
})
it('should allow to be called only by the mediator', async () => {
await contract.updateENSNode(namehash, user, user2, 100).should.be.rejected
await ens.setRecord(namehash, user, otherSideResolver.address, 100).should.be.fulfilled
const { receipt } = await otherSideMediator.bridgeENSNode(namehash).should.be.fulfilled
const encodedData = strip0x(
web3.eth.abi.decodeParameters(
['bytes'],
receipt.rawLogs.find(log => log.address === otherSideAMBBridgeContract.address).data
)[0]
)
const data = `0x${encodedData.slice(2 * (4 + 20 + 8 + 20 + 20 + 4 + 1 + 1 + 1 + 2 + 2))}` // remove AMB header
await ambBridgeContract.executeMessageCall(contract.address, resolver.address, data, exampleMessageId, 2000000)
.should.be.fulfilled
expect(await ambBridgeContract.messageCallStatus(exampleMessageId)).to.be.equal(false)
})
})
describe('ENSBridgeRegistry', () => {
beforeEach(async () => {
await contract.initialize(ambBridgeContract.address, otherSideMediator.address, owner, resolver.address).should.be
.fulfilled
})
it('should return correct values for unknown node', async () => {
expect(await contract.owner(namehash)).to.be.equal(ZERO_ADDRESS)
expect(await contract.resolver(namehash)).to.be.equal(ZERO_ADDRESS)
expect(await contract.ttl(namehash)).to.be.bignumber.equal('0')
})
it('should allow to change resolver', async () => {
await ens.setRecord(namehash, user, otherSideResolver.address, 100).should.be.fulfilled
await bridgeENSNode(namehash)
expect(await contract.resolver(namehash)).to.be.equal(resolver.address)
await contract.setResolver(namehash, otherSideResolver.address, { from: user2 }).should.be.rejected
await contract.setResolver(namehash, otherSideResolver.address, { from: owner }).should.be.rejected
await contract.setResolver(namehash, owner, { from: user }).should.be.rejected
await contract.setResolver(namehash, otherSideResolver.address, { from: user }).should.be.fulfilled
expect(await contract.resolver(namehash)).to.be.equal(otherSideResolver.address)
await contract.setResolver(namehash, ZERO_ADDRESS, { from: user }).should.be.fulfilled
expect(await contract.resolver(namehash)).to.be.equal(ZERO_ADDRESS)
})
it('should allow to change ttl', async () => {
await ens.setRecord(namehash, user, otherSideResolver.address, 100).should.be.fulfilled
await bridgeENSNode(namehash)
expect(await contract.ttl(namehash)).to.be.bignumber.equal('100')
await contract.setTTL(namehash, '200', { from: user2 }).should.be.rejected
await contract.setTTL(namehash, '200', { from: owner }).should.be.rejected
await contract.setTTL(namehash, '200', { from: user }).should.be.fulfilled
expect(await contract.ttl(namehash)).to.be.bignumber.equal('200')
})
it('should allow to set operator', async () => {
expect(await contract.isApprovedForAll(owner, user)).to.be.equal(false)
expect(await contract.isApprovedForAll(owner, user2)).to.be.equal(false)
await contract.setApprovalForAll(user, true).should.be.fulfilled
expect(await contract.isApprovedForAll(owner, user)).to.be.equal(true)
expect(await contract.isApprovedForAll(owner, user2)).to.be.equal(false)
await contract.setApprovalForAll(user2, true).should.be.fulfilled
expect(await contract.isApprovedForAll(owner, user)).to.be.equal(true)
expect(await contract.isApprovedForAll(owner, user2)).to.be.equal(true)
await contract.setApprovalForAll(user, false).should.be.fulfilled
expect(await contract.isApprovedForAll(owner, user)).to.be.equal(false)
expect(await contract.isApprovedForAll(owner, user2)).to.be.equal(true)
await contract.setApprovalForAll(user2, false).should.be.fulfilled
expect(await contract.isApprovedForAll(owner, user)).to.be.equal(false)
expect(await contract.isApprovedForAll(owner, user2)).to.be.equal(false)
})
it('should allow to change values by operator', async () => {
await ens.setRecord(namehash, user, otherSideResolver.address, 100).should.be.fulfilled
await bridgeENSNode(namehash)
expect(await contract.resolver(namehash)).to.be.equal(resolver.address)
expect(await contract.ttl(namehash)).to.be.bignumber.equal('100')
await contract.setResolver(namehash, otherSideResolver.address).should.be.rejected
await contract.setTTL(namehash, 200).should.be.rejected
await contract.setApprovalForAll(owner, true, { from: user }).should.be.fulfilled
await contract.setResolver(namehash, otherSideResolver.address).should.be.fulfilled
await contract.setTTL(namehash, 200).should.be.fulfilled
expect(await contract.resolver(namehash)).to.be.equal(otherSideResolver.address)
expect(await contract.ttl(namehash)).to.be.bignumber.equal('200')
})
})
})

5
test/coverage.test.js Normal file
View File

@ -0,0 +1,5 @@
after(async () => {
if (process.env.SOLIDITY_COVERAGE === 'true') {
await global.coverageSubprovider.writeCoverageAsync()
}
})

61
test/helpers/helpers.js Normal file
View File

@ -0,0 +1,61 @@
const { expect } = require('chai')
const { BN } = require('../setup')
// strips leading "0x" if present
function strip0x(input) {
return input.replace(/^0x/, '')
}
const getEvents = (truffleInstance, filter, fromBlock = 0, toBlock = 'latest') =>
truffleInstance.contract.getPastEvents(filter.event, { fromBlock, toBlock })
function ether(n) {
return new BN(web3.utils.toWei(n, 'ether'))
}
function expectEventInLogs(logs, eventName, eventArgs = {}) {
const events = logs.filter(e => e.event === eventName)
expect(events.length > 0).to.equal(true, `There is no '${eventName}'`)
const exception = []
const event = events.find(e => {
for (const [k, v] of Object.entries(eventArgs)) {
try {
contains(e.args, k, v)
} catch (error) {
exception.push(error)
return false
}
}
return true
})
if (event === undefined) {
throw exception[0]
}
return event
}
function contains(args, key, value) {
expect(key in args).to.equal(true, `Unknown event argument '${key}'`)
if (value === null) {
expect(args[key]).to.equal(null)
} else if (isBN(args[key])) {
expect(args[key]).to.be.bignumber.equal(value)
} else {
expect(args[key]).to.be.equal(value)
}
}
function isBN(object) {
return BN.isBN(object) || object instanceof BN
}
module.exports = {
strip0x,
getEvents,
ether,
expectEventInLogs
}

15
test/setup.js Normal file
View File

@ -0,0 +1,15 @@
const { BN } = web3.utils
require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bn')(BN))
require('chai/register-should')
exports.BN = BN
exports.toBN = web3.utils.toBN
exports.ERROR_MSG = 'VM Exception while processing transaction: revert'
exports.ERROR_MSG_OPCODE = 'VM Exception while processing transaction: invalid opcode'
exports.ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'
exports.F_ADDRESS = '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF'
exports.INVALID_ARGUMENTS = 'Invalid number of arguments to Solidity function'

118
truffle-config.js Normal file
View File

@ -0,0 +1,118 @@
const { CoverageSubprovider, Web3ProviderEngine } = require('@0x/sol-coverage')
const { TruffleArtifactAdapter } = require('@0x/sol-trace')
const { GanacheSubprovider } = require('@0x/subproviders')
const contractsBuildDirectory = './build/contracts'
const evmVersion = 'byzantium'
const mochaOptions =
process.env.GASREPORT === 'true'
? {
reporter: 'eth-gas-reporter',
reporterOptions: {
currency: 'USD',
gasPrice: 1
}
}
: {}
const projectRoot = ''
const solcVersion = '0.4.24+commit.e67f0147'
const defaultFromAddress = '0x5409ed021d9299bf6814279a6a1411a7e866a631'
const isVerbose = true
const artifactAdapter = new TruffleArtifactAdapter(projectRoot, solcVersion)
const provider = new Web3ProviderEngine()
if (process.env.SOLIDITY_COVERAGE === 'true') {
global.coverageSubprovider = new CoverageSubprovider(artifactAdapter, defaultFromAddress, {
isVerbose,
ignoreFilesGlobs: ['**/Migrations.sol', '**/node_modules/**', '**/mocks/**', '**/interfaces/**']
})
provider.addProvider(global.coverageSubprovider)
const ganacheSubprovider = new GanacheSubprovider({
accounts: [
{
secretKey: '0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501200',
balance: '1000000000000000000000000'
},
{
secretKey: '0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501201',
balance: '1000000000000000000000000'
},
{
secretKey: '0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501202',
balance: '1000000000000000000000000'
},
{
secretKey: '0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501203',
balance: '1000000000000000000000000'
},
{
secretKey: '0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501204',
balance: '1000000000000000000000000'
},
{
secretKey: '0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501205',
balance: '1000000000000000000000000'
},
{
secretKey: '0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501206',
balance: '1000000000000000000000000'
},
{
secretKey: '0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501207',
balance: '1000000000000000000000000'
},
{
secretKey: '0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501208',
balance: '1000000000000000000000000'
},
{
secretKey: '0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501209',
balance: '1000000000000000000000000'
},
{
secretKey: '0x19fba401d77e4113b15095e9aa7117bcd25adcfac7f6111f8298894eef443600',
balance: '1000000000000000000000000'
}
],
port: 8545,
gasLimit: 10000000
})
provider.addProvider(ganacheSubprovider)
provider.start(err => {
if (err !== undefined) {
process.exit(1)
}
})
provider.send = provider.sendAsync.bind(provider)
}
module.exports = {
contracts_build_directory: contractsBuildDirectory,
networks: {
development: {
provider,
network_id: '*',
gas: 10000000
},
ganache: {
host: '127.0.0.1',
port: 8545,
network_id: '*', // eslint-disable-line camelcase
gasPrice: 100000000000,
gas: 10000000
}
},
compilers: {
solc: {
version: '0.4.24',
settings: {
optimizer: {
enabled: true,
runs: 200
},
evmVersion
}
}
},
mocha: mochaOptions
}