├── .formatter.exs
├── .github
├── dependabot.yml
├── install_parity.sh
└── workflows
│ └── test.yml
├── .gitignore
├── LICENSE
├── README.md
├── assets
└── exw3_logo.jpg
├── config
└── config.exs
├── docker-compose.yml
├── lib
├── exw3.ex
└── exw3
│ ├── abi.ex
│ ├── address.ex
│ ├── client.ex
│ ├── contract.ex
│ ├── normalize.ex
│ ├── rpc.ex
│ └── utils.ex
├── mix.exs
├── mix.lock
├── parity.sh
└── test
├── examples
├── build
│ ├── AddressTester.abi
│ ├── AddressTester.bin
│ ├── ArrayTester.abi
│ ├── ArrayTester.bin
│ ├── Complex.abi
│ ├── Complex.bin
│ ├── EventTester.abi
│ ├── EventTester.bin
│ ├── SimpleStorage.abi
│ └── SimpleStorage.bin
└── contracts
│ ├── AddressTester.sol
│ ├── ArrayTester.sol
│ ├── Complex.sol
│ ├── EventTester.sol
│ └── SimpleStorage.sol
├── exw3
├── abi_test.exs
├── address_test.exs
├── client_test.exs
├── contract_test.exs
├── rpc_test.exs
└── utils_test.exs
├── exw3_test.exs
└── test_helper.exs
/.formatter.exs:
--------------------------------------------------------------------------------
1 | # Used by "mix format"
2 | [
3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
4 | ]
5 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: mix
4 | directory: "/"
5 | schedule:
6 | interval: monthly
7 | open-pull-requests-limit: 10
8 | - package-ecosystem: github-actions
9 | directory: "/"
10 | schedule:
11 | interval: monthly
12 | open-pull-requests-limit: 10
13 |
--------------------------------------------------------------------------------
/.github/install_parity.sh:
--------------------------------------------------------------------------------
1 | # Install Parity blockchain tests on Github action
2 | echo > passfile # just to be safe
3 |
4 | wget https://releases.parity.io/ethereum/v2.7.2/x86_64-unknown-linux-gnu/parity
5 |
6 | chmod 755 ./parity
7 | echo > passfile
8 |
9 | ./parity --chain dev 2>&1 &
10 |
11 | PARITY_PID=$!
12 | sleep 10
13 | kill -9 $(lsof -t -i:8545) # cleanup old zombie instances
14 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: test
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | pull_request:
8 | branches:
9 | - '*'
10 |
11 | jobs:
12 | test:
13 | runs-on: ubuntu-latest
14 | name: Test OTP ${{matrix.otp}} / Elixir ${{matrix.elixir}}
15 |
16 | strategy:
17 | matrix:
18 | otp: [22.x, 23.x, 24.x]
19 | elixir: [1.10.x, 1.11.x, 1.12.x]
20 |
21 | steps:
22 | - uses: actions/checkout@v3
23 |
24 | - uses: erlef/setup-beam@v1.11
25 | with:
26 | otp-version: ${{matrix.otp}}
27 | elixir-version: ${{matrix.elixir}}
28 |
29 | - uses: actions-rs/toolchain@v1
30 | with:
31 | toolchain: stable
32 |
33 | - name: Cache Dependencies
34 | uses: actions/cache@v3.0.8
35 | with:
36 | path: |
37 | deps
38 | _build/dev
39 | _build/test
40 | key: elixir-cache-${{secrets.CACHE_VERSION}}-${{matrix.elixir}}-otp-${{matrix.otp}}-${{runner.os}}-${{hashFiles('mix.lock')}}-${{github.ref}}
41 | restore-keys: |
42 | elixir-cache-${{secrets.CACHE_VERSION}}-${{matrix.elixir}}-otp-${{matrix.otp}}-${{runner.os}}-${{hashFiles('mix.lock')}}-
43 | elixir-cache-${{secrets.CACHE_VERSION}}-${{matrix.elixir}}-otp-${{matrix.otp}}-${{runner.os}}-
44 |
45 | - name: Install Dependencies
46 | run: mix deps.get
47 |
48 | - name: Install Parity Blockchain
49 | run: .github/install_parity.sh
50 |
51 | - name: Run Parity Blockchain
52 | run: ./parity --chain dev --unlock=0x00a329c0648769a73afac7f9381e08fb43dbea72 --reseal-min-period 0 --password passfile &
53 |
54 | - name: Test
55 | run: mix test
56 |
57 | - name: Dialyzer
58 | run: mix dialyzer --halt-exit-status
59 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # The directory Mix will write compiled artifacts to.
2 | /_build/
3 |
4 | # If you run "mix test --cover", coverage assets end up here.
5 | /cover/
6 |
7 | # The directory Mix downloads your dependencies sources to.
8 | /deps/
9 |
10 | # Where third-party dependencies like ExDoc output generated docs.
11 | /doc/
12 |
13 | # Ignore .fetch files in case you like to edit your project deps locally.
14 | /.fetch
15 |
16 | # If the VM crashes, it generates a dump, let's ignore it too.
17 | erl_crash.dump
18 |
19 | # Also ignore archive artifacts (built via "mix archive.build").
20 | *.ez
21 |
22 | # Ignore package tarball (built via "mix hex.build").
23 | exw3-*.tar
24 |
25 | # Temporary files, for example, from tests.
26 | /tmp/
27 |
28 | # Misc.
29 | .env*
30 | passfile
31 | docker/openethereum
32 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ExW3
2 |
3 | [](https://github.com/hswick/exw3/actions?query=workflow%3Atest)
4 | [](https://hex.pm/packages/exw3)
5 | [](https://hexdocs.pm/exw3/)
6 | [](https://hex.pm/packages/exw3)
7 | [](https://github.com/hswick/exw3/blob/master/LICENSE)
8 | [](https://github.com/hswick/exw3/commits/master)
9 |
10 |
11 |
12 |
13 |
14 | ## Installation
15 |
16 | The package can be installed by adding `:exw3` to your list of dependencies in `mix.exs`:
17 |
18 | ```elixir
19 | def deps do
20 | [
21 | {:exw3, "~> 0.6"}
22 | ]
23 | end
24 | ```
25 |
26 | ## Overview
27 |
28 | ExW3 is a wrapper around ethereumex to provide a high level, user friendly json rpc api. This library is focused on providing a handy abstraction for working with smart contracts, and any other relevant utilities.
29 |
30 | ## Usage
31 |
32 | Ensure you have an ethereum node to connect to at the specified url in your config. An easy local testnet to use is ganache-cli:
33 |
34 | ```bash
35 | $ ganache-cli
36 | ```
37 |
38 | Or you can use parity:
39 | Install Parity, then run it with
40 |
41 | ```bash
42 | $ echo > passfile
43 | parity --chain dev --unlock=0x00a329c0648769a73afac7f9381e08fb43dbea72 --reseal-min-period 0 --password passfile
44 | ```
45 |
46 | If Parity complains about password or missing account, try
47 |
48 | ```bash
49 | $ parity --chain dev --unlock=0x00a329c0648769a73afac7f9381e08fb43dbea72
50 | ```
51 |
52 | ### HTTP
53 |
54 | To use Ethereumex's HttpClient simply set your config like this:
55 |
56 | ```elixir
57 | config :ethereumex,
58 | client_type: :http,
59 | url: "http://localhost:8545"
60 | ```
61 |
62 | ### IPC
63 |
64 | If you want to use IpcClient set your config to something like this:
65 |
66 | ```elixir
67 | config :ethereumex,
68 | client_type: :ipc,
69 | ipc_path: "/.local/share/io.parity.ethereum/jsonrpc.ipc"
70 | ```
71 |
72 | Provide an absolute path to the ipc socket provided by whatever Ethereum client you are running. You don't need to include the home directory, as that will be prepended to the path provided.
73 |
74 | **NOTE:** Use of IPC is recommended, as it is more secure and significantly faster.
75 |
76 | Currently, ExW3 supports a handful of JSON RPC commands. Primarily the ones that get used the most. If ExW3 doesn't provide a specific command, you can always use the [Ethereumex](https://github.com/exthereum/ethereumex) commands.
77 |
78 | Check out the [documentation](https://hexdocs.pm/exw3/ExW3.html) for more details of the API.
79 |
80 | ### Example
81 |
82 | ```elixir
83 | iex(1)> accounts = ExW3.accounts()
84 | ["0x00a329c0648769a73afac7f9381e08fb43dbea72"]
85 | iex(2)> ExW3.balance(Enum.at(accounts, 0))
86 | 1606938044258990275541962092341162602522200978938292835291376
87 | iex(3)> ExW3.block_number()
88 | 1252
89 | iex(4)> simple_storage_abi = ExW3.Abi.load_abi("test/examples/build/SimpleStorage.abi")
90 | %{
91 | "get" => %{
92 | "constant" => true,
93 | "inputs" => [],
94 | "name" => "get",
95 | "outputs" => [%{"name" => "", "type" => "uint256"}],
96 | "payable" => false,
97 | "stateMutability" => "view",
98 | "type" => "function"
99 | },
100 | "set" => %{
101 | "constant" => false,
102 | "inputs" => [%{"name" => "_data", "type" => "uint256"}],
103 | "name" => "set",
104 | "outputs" => [],
105 | "payable" => false,
106 | "stateMutability" => "nonpayable",
107 | "type" => "function"
108 | }
109 | }
110 | iex(5)> ExW3.Contract.start_link
111 | {:ok, #PID<0.265.0>}
112 | iex(6)> ExW3.Contract.register(:SimpleStorage, abi: simple_storage_abi)
113 | :ok
114 | iex(7)> {:ok, address, tx_hash} = ExW3.Contract.deploy(:SimpleStorage, bin: ExW3.Abi.load_bin("test/examples/build/SimpleStorage.bin"), options: %{gas: 300_000, from: Enum.at(accounts, 0)})
115 | {:ok, "0x22018c2bb98387a39e864cf784e76cb8971889a5",
116 | "0x4ea539048c01194476004ef69f407a10628bed64e88ee8f8b17b4d030d0e7cb7"}
117 | iex(8)> ExW3.Contract.at(:SimpleStorage, address)
118 | :ok
119 | iex(9)> ExW3.Contract.call(:SimpleStorage, :get)
120 | {:ok, 0}
121 | iex(10)> ExW3.Contract.send(:SimpleStorage, :set, [1], %{from: Enum.at(accounts, 0), gas: 50_000})
122 | {:ok, "0x88838e84a401a1d6162290a1a765507c4a83f5e050658a83992a912f42149ca5"}
123 | iex(11)> ExW3.Contract.call(:SimpleStorage, :get)
124 | {:ok, 1}
125 | ```
126 |
127 | ## Address Type
128 |
129 | If you are familiar with web3.js you may find the way ExW3 handles addresses unintuitive. ExW3's ABI encoder interprets the address type as an uint160. If you are using an address as an option to a transaction like `:from` or `:to` this will work as expected. However, if one of your smart contracts is expecting an address type for an input parameter then you will need to do this:
130 |
131 | ```elixir
132 | a = ExW3.Utils.hex_to_integer("0x88838e84a401a1d6162290a1a765507c4a83f5e050658a83992a912f42149ca5")
133 | ```
134 |
135 | ## Events
136 |
137 | ExW3 allows the retrieval of event logs using filters or transaction receipts. In this example we will demonstrate a filter. Assume we have already deployed and registered a contract called EventTester.
138 |
139 | ```elixir
140 | # We can optionally specify extra parameters like `:fromBlock`, and `:toBlock`
141 | {:ok, filter_id} = ExW3.Contract.filter(:EventTester, "Simple", %{fromBlock: 42, toBlock: "latest"})
142 |
143 | # After some point that we think there are some new changes
144 | {:ok, changes} = ExW3.Contract.get_filter_changes(filter_id)
145 |
146 | # We can then uninstall the filter after we are done using it
147 | ExW3.Contract.uninstall_filter(filter_id)
148 | ```
149 |
150 | ## Indexed Events
151 |
152 | Ethereum allows a user to add topics to filters. This means the filter will only return events with the specific index parameters. For all of the extra options see [here](https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newfilter)
153 |
154 | If you have written your event in Solidity like this:
155 |
156 | ```
157 | event SimpleIndex(uint256 indexed num, bytes32 indexed data, uint256 otherNum);
158 | ```
159 |
160 | You can add a filter on which logs will be returned back to the RPC client based on the indexed fields.
161 |
162 | ExW3 allows for 2 ways of specifying these parameters (`:topics`) in two ways. The first, and probably more preferred way, is with a map:
163 |
164 | ```elixir
165 | indexed_filter_id = ExW3.Contract.filter(
166 | :EventTester,
167 | "SimpleIndex",
168 | %{
169 | topics: %{num: 46, data: "Hello, World!"},
170 | }
171 | )
172 | ```
173 |
174 | The other option is a list (mapped version is an abstraction over this). The downside here is this is order dependent. Any values you don't want to specify must be represented with a `nil`. This approach has been included because it is the implementation of the JSON RPC spec.
175 |
176 | ```elixir
177 | indexed_filter_id = ExW3.Contract.filter(
178 | :EventTester,
179 | "SimpleIndex",
180 | %{
181 | topics: [nil, "Hello, World!"]
182 | }
183 | )
184 | ```
185 |
186 | Here we are skipping the `num` topic, and only filtering on the `data` parameter.
187 |
188 | NOTE!!! These two approaches are mutually exclusive, and for almost all cases you should prefer the map.
189 |
190 | ## Continuous Event Handling
191 |
192 | In many cases, you will want some process to continuously listen for events. We can implement this functionality using a recursive function. Since Elixir uses tail call optimization, we won't have to worry about blowing up the stack.
193 |
194 | ```elixir
195 | def listen_for_event do
196 | {:ok, changes} = ExW3.Contract.get_filter_changes(filter_id) # Get our changes from the blockchain
197 | handle_changes(changes) # Some function to deal with the data. Good place to use pattern matching.
198 | :timer.sleep(1000) # Some delay in milliseconds. Recommended to save bandwidth, and not spam.
199 | listen_for_event() # Recurse
200 | end
201 | ```
202 |
203 | # Compiling Solidity
204 |
205 | To compile the test solidity contracts after making a change run this command:
206 |
207 | ```bash
208 | $ solc --abi --bin --overwrite -o test/examples/build test/examples/contracts/*.sol
209 | ```
210 |
211 | # Contributing
212 |
213 | ## Test
214 |
215 | The full test suite requires a running blockchain. You can run your own or start `openethereum` with `docker-compose`.
216 |
217 | ```bash
218 | $ docker-compose up
219 | $ mix test
220 | ```
221 |
222 | ## Copyright and License
223 |
224 | Copyright (c) 2018 Harley Swick
225 |
226 | Licensed under the Apache License, Version 2.0 (the "License");
227 | you may not use this file except in compliance with the License.
228 | You may obtain a copy of the License at [https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)
229 |
230 | Unless required by applicable law or agreed to in writing, software
231 | distributed under the License is distributed on an "AS IS" BASIS,
232 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
233 | See the License for the specific language governing permissions and
234 | limitations under the License.
235 |
--------------------------------------------------------------------------------
/assets/exw3_logo.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hswick/exw3/17074b213e8affcfddcef4ddc1179f16845ecb7a/assets/exw3_logo.jpg
--------------------------------------------------------------------------------
/config/config.exs:
--------------------------------------------------------------------------------
1 | # This file is responsible for configuring your application
2 | # and its dependencies with the aid of the Mix.Config module.
3 | use Mix.Config
4 |
5 | # This configuration is loaded before any dependency and is restricted
6 | # to this project. If another project depends on this project, this
7 | # file won't be loaded nor affect the parent project. For this reason,
8 | # if you want to provide default values for your application for third-
9 | # party users, it should be done in your mix.exs file.
10 |
11 | # Sample configuration:
12 | #
13 | # config :logger,
14 | # level: :info
15 | #
16 | # config :logger, :console,
17 | # format: "$date $time [$level] $metadata$message\n",
18 | # metadata: [:user_id]
19 |
20 | # It is also possible to import configuration files, relative to this
21 | # directory. For example, you can emulate configuration per environment
22 | # by uncommenting the line below and defining dev.exs, test.exs and such.
23 | # Configuration from the imported file will override the ones defined
24 | # here (which is why it is important to import them last).
25 | #
26 | # import_config "#{Mix.env}.exs"
27 | config :ethereumex,
28 | client_type: :ipc,
29 | url: "http://localhost:8545",
30 | ipc_path:
31 | System.get_env(
32 | "IPC_PATH",
33 | "#{System.user_home!()}/.local/share/io.parity.ethereum/jsonrpc.ipc"
34 | )
35 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: '3.8'
2 |
3 | services:
4 | openethereum:
5 | image: openethereum/openethereum:v3.3.0
6 | command: '--chain=dev --unlock=0x00a329c0648769a73afac7f9381e08fb43dbea72 --password=/home/openethereum/.local/share/openethereum/passfile --jsonrpc-interface=0.0.0.0'
7 | ports:
8 | - '8545:8545'
9 | - '8546:8546'
10 | volumes:
11 | - ./docker:/home/openethereum/.local/share
12 |
--------------------------------------------------------------------------------
/lib/exw3.ex:
--------------------------------------------------------------------------------
1 | defmodule ExW3 do
2 | defdelegate accounts(opts \\ []), to: ExW3.Rpc
3 | defdelegate block_number(opts \\ []), to: ExW3.Rpc
4 | defdelegate balance(account, opts \\ []), to: ExW3.Rpc
5 | defdelegate tx_receipt(tx_hash), to: ExW3.Rpc
6 | defdelegate block(block_number), to: ExW3.Rpc
7 | defdelegate new_filter(map), to: ExW3.Rpc
8 | defdelegate get_filter_changes(filter_id), to: ExW3.Rpc
9 | defdelegate get_logs(filter, opts \\ []), to: ExW3.Rpc
10 | defdelegate uninstall_filter(filter_id), to: ExW3.Rpc
11 | defdelegate mine(num_blocks \\ 1), to: ExW3.Rpc
12 | defdelegate personal_list_accounts(opts \\ []), to: ExW3.Rpc
13 | defdelegate personal_new_account(password, opts \\ []), to: ExW3.Rpc
14 | defdelegate personal_unlock_account(params, opts \\ []), to: ExW3.Rpc
15 | defdelegate personal_send_transaction(param_map, passphrase, opts \\ []), to: ExW3.Rpc
16 | defdelegate personal_sign_transaction(param_map, passphrase, opts \\ []), to: ExW3.Rpc
17 | defdelegate personal_sign(data, address, passphrase, opts \\ []), to: ExW3.Rpc
18 | defdelegate personal_ec_recover(data0, data1, opts \\ []), to: ExW3.Rpc
19 | defdelegate eth_sign(data0, data1, opts \\ []), to: ExW3.Rpc
20 | defdelegate eth_call(arguments), to: ExW3.Rpc
21 | defdelegate eth_send(arguments), to: ExW3.Rpc
22 | end
23 |
--------------------------------------------------------------------------------
/lib/exw3/abi.ex:
--------------------------------------------------------------------------------
1 | defmodule ExW3.Abi do
2 | @doc "Decodes event based on given data and provided signature"
3 | @spec decode_event(binary(), binary()) :: any()
4 | def decode_event(data, signature) do
5 | formatted_data =
6 | data
7 | |> String.slice(2..-1)
8 | |> Base.decode16!(case: :lower)
9 |
10 | fs = ABI.FunctionSelector.decode(signature)
11 |
12 | ABI.TypeDecoder.decode(formatted_data, fs)
13 | end
14 |
15 | @doc "Loads the abi at the file path and reformats it to a map"
16 | @spec load_abi(binary()) :: list() | {:error, atom()}
17 | def load_abi(file_path) do
18 | with {:ok, cwd} <- File.cwd(),
19 | {:ok, abi} <- File.read(Path.join([cwd, file_path])) do
20 | reformat_abi(Jason.decode!(abi))
21 | end
22 | end
23 |
24 | @doc "Loads the bin ar the file path"
25 | @spec load_bin(binary()) :: binary()
26 | def load_bin(file_path) do
27 | with {:ok, cwd} <- File.cwd(),
28 | {:ok, bin} <- File.read(Path.join([cwd, file_path])) do
29 | bin
30 | end
31 | end
32 |
33 | @doc "Decodes data based on given type signature"
34 | @spec decode_data(binary(), binary()) :: any()
35 | def decode_data(types_signature, data) do
36 | {:ok, trim_data} = String.slice(data, 2..String.length(data)) |> Base.decode16(case: :lower)
37 |
38 | ABI.decode(types_signature, trim_data) |> List.first()
39 | end
40 |
41 | @doc "Decodes output based on specified functions return signature"
42 | @spec decode_output(map(), binary(), binary()) :: list()
43 | def decode_output(abi, name, output) do
44 | {:ok, trim_output} =
45 | String.slice(output, 2..String.length(output)) |> Base.decode16(case: :lower)
46 |
47 | output_types = Enum.map(abi[name]["outputs"], fn x -> x["type"] end)
48 | types_signature = Enum.join(["(", Enum.join(output_types, ","), ")"])
49 | output_signature = "#{name}(#{types_signature})"
50 |
51 | outputs =
52 | ABI.decode(output_signature, trim_output)
53 | |> List.first()
54 | |> Tuple.to_list()
55 |
56 | outputs
57 | end
58 |
59 | @doc "Returns the type signature of a given function"
60 | @spec types_signature(map(), binary()) :: binary()
61 | def types_signature(abi, name) do
62 | input_types = Enum.map(abi[name]["inputs"], fn x -> x["type"] end)
63 | types_signature = Enum.join(["(", Enum.join(input_types, ","), ")"])
64 | types_signature
65 | end
66 |
67 | @doc "Returns the 4 character method id based on the hash of the method signature"
68 | @spec method_signature(map(), binary()) :: binary()
69 | def method_signature(abi, name) do
70 | if abi[name] do
71 | input_signature = ExKeccak.hash_256("#{name}#{types_signature(abi, name)}")
72 |
73 | # Take first four bytes
74 | <> = input_signature
75 | init
76 | else
77 | raise "#{name} method not found in the given abi"
78 | end
79 | end
80 |
81 | @doc "Encodes data into Ethereum hex string based on types signature"
82 | @spec encode_data(binary(), list()) :: binary()
83 | def encode_data(types_signature, data) do
84 | ABI.TypeEncoder.encode_raw(
85 | [List.to_tuple(data)],
86 | ABI.FunctionSelector.decode_raw(types_signature)
87 | )
88 | end
89 |
90 | @doc "Encodes list of options and returns them as a map"
91 | @spec encode_options(map(), list()) :: map()
92 | def encode_options(options, keys) do
93 | keys
94 | |> Enum.filter(fn option ->
95 | Map.has_key?(options, option)
96 | end)
97 | |> Enum.map(fn option ->
98 | {option, encode_option(options[option])}
99 | end)
100 | |> Enum.into(%{})
101 | end
102 |
103 | @doc "Encodes options into Ethereum JSON RPC hex string"
104 | @spec encode_option(integer()) :: binary()
105 | def encode_option(0), do: "0x0"
106 |
107 | def encode_option(nil), do: nil
108 |
109 | def encode_option(value) do
110 | "0x" <>
111 | (value
112 | |> :binary.encode_unsigned()
113 | |> Base.encode16(case: :lower)
114 | |> String.trim_leading("0"))
115 | end
116 |
117 | @doc "Encodes data and appends it to the encoded method id"
118 | @spec encode_method_call(map(), binary(), list()) :: binary()
119 | def encode_method_call(abi, name, input) do
120 | encoded_method_call =
121 | method_signature(abi, name) <> encode_data(types_signature(abi, name), input)
122 |
123 | encoded_method_call |> Base.encode16(case: :lower)
124 | end
125 |
126 | @doc "Encodes input from a method call based on function signature"
127 | @spec encode_input(map(), binary(), list()) :: binary()
128 | def encode_input(abi, name, input) do
129 | if abi[name]["inputs"] do
130 | input_types = Enum.map(abi[name]["inputs"], fn x -> x["type"] end)
131 | types_signature = Enum.join(["(", Enum.join(input_types, ","), ")"])
132 | input_signature = ExKeccak.hash_256("#{name}#{types_signature}")
133 |
134 | # Take first four bytes
135 | <> = input_signature
136 |
137 | encoded_input =
138 | init <>
139 | ABI.TypeEncoder.encode_raw(
140 | [List.to_tuple(input)],
141 | ABI.FunctionSelector.decode_raw(types_signature)
142 | )
143 |
144 | encoded_input |> Base.encode16(case: :lower)
145 | else
146 | raise "#{name} method not found with the given abi"
147 | end
148 | end
149 |
150 | defp reformat_abi(abi) do
151 | abi
152 | |> Enum.map(&map_abi/1)
153 | |> Map.new()
154 | end
155 |
156 | defp map_abi(x) do
157 | case {x["name"], x["type"]} do
158 | {nil, "constructor"} -> {:constructor, x}
159 | {nil, "fallback"} -> {:fallback, x}
160 | {name, _} -> {name, x}
161 | end
162 | end
163 | end
164 |
--------------------------------------------------------------------------------
/lib/exw3/address.ex:
--------------------------------------------------------------------------------
1 | defmodule ExW3.Address do
2 | @type t :: %__MODULE__{bytes: binary}
3 |
4 | defstruct ~w[bytes]a
5 |
6 | @spec from_bytes(binary) :: t
7 | def from_bytes(bytes) do
8 | %__MODULE__{bytes: bytes}
9 | end
10 |
11 | @spec from_hex(String.t()) :: t
12 | def from_hex(address) do
13 | case address do
14 | "0x" <> a ->
15 | from_hex(a)
16 |
17 | a ->
18 | bytes = a |> String.downcase() |> Base.decode16!(case: :lower)
19 | %__MODULE__{bytes: bytes}
20 | end
21 | end
22 |
23 | @spec to_bytes(t) :: binary
24 | def to_bytes(%__MODULE__{bytes: bytes}) do
25 | bytes
26 | end
27 |
28 | @spec to_string(t) :: String.t()
29 | def to_string(%__MODULE__{bytes: bytes}) do
30 | Base.encode16(bytes, case: :lower)
31 | end
32 |
33 | @spec to_hex(t) :: String.t()
34 | def to_hex(%__MODULE__{} = address) do
35 | "0x#{__MODULE__.to_string(address)}"
36 | end
37 |
38 | @spec to_checksum(t) :: String.t()
39 | def to_checksum(%__MODULE__{} = address) do
40 | address = address |> __MODULE__.to_string()
41 | address_hash = address |> ExKeccak.hash_256() |> Base.encode16(case: :lower)
42 |
43 | keccak_hash_list =
44 | address_hash
45 | |> String.split("", trim: true)
46 | |> Enum.map(fn x -> elem(Integer.parse(x, 16), 0) end)
47 |
48 | list_arr =
49 | for n <- 0..(String.length(address) - 1) do
50 | number = Enum.at(keccak_hash_list, n)
51 |
52 | cond do
53 | number >= 8 -> String.upcase(String.at(address, n))
54 | true -> String.downcase(String.at(address, n))
55 | end
56 | end
57 |
58 | "0x" <> List.to_string(list_arr)
59 | end
60 |
61 | @spec is_valid_checksum?(String.t()) :: boolean
62 | def is_valid_checksum?(hex_address) do
63 | address = hex_address |> __MODULE__.from_hex()
64 | __MODULE__.to_checksum(address) == hex_address
65 | end
66 | end
67 |
68 |
--------------------------------------------------------------------------------
/lib/exw3/client.ex:
--------------------------------------------------------------------------------
1 | defmodule ExW3.Client do
2 | @type argument :: term
3 | @type request_error :: Ethereumex.Client.Behaviour.error()
4 | @type error :: {:error, :invalid_client_type} | request_error
5 |
6 | @spec call_client(atom) :: {:ok, term} | error
7 | @spec call_client(atom, [argument]) :: {:ok, term} | error
8 | def call_client(method_name, arguments \\ []) do
9 | url_opt = extract_url_opt(arguments)
10 |
11 | case client_type(url_opt) do
12 | :http -> apply(Ethereumex.HttpClient, method_name, arguments)
13 | :ipc -> apply(Ethereumex.IpcClient, method_name, arguments)
14 | _ -> {:error, :invalid_client_type}
15 | end
16 | end
17 |
18 | defp extract_url_opt(arguments) do
19 | arguments
20 | |> List.last()
21 | |> case do
22 | last when is_list(last) -> Keyword.get(last, :url)
23 | _ -> nil
24 | end
25 | end
26 |
27 | defp client_type(nil), do: Application.get_env(:ethereumex, :client_type, :http)
28 | defp client_type("http://" <> _), do: :http
29 | defp client_type("https://" <> _), do: :http
30 | defp client_type(_), do: :invalid
31 | end
32 |
--------------------------------------------------------------------------------
/lib/exw3/contract.ex:
--------------------------------------------------------------------------------
1 | defmodule ExW3.Contract do
2 | use GenServer
3 |
4 | @doc "Begins the Contract process to manage all interactions with smart contracts"
5 | @spec start_link() :: {:ok, pid()}
6 | def start_link(_ \\ :ok) do
7 | GenServer.start_link(__MODULE__, %{filters: %{}}, name: ContractManager)
8 | end
9 |
10 | @doc "Deploys contracts with given arguments"
11 | @spec deploy(atom(), list()) :: {:ok, binary(), binary()}
12 | def deploy(name, args) do
13 | GenServer.call(ContractManager, {:deploy, {name, args}})
14 | end
15 |
16 | @doc "Registers the contract with the ContractManager process. Only :abi is required field."
17 | @spec register(atom(), list()) :: :ok
18 | def register(name, contract_info) do
19 | GenServer.cast(ContractManager, {:register, {name, contract_info}})
20 | end
21 |
22 | @doc "Uninstalls the filter, and deletes the data associated with the filter id"
23 | @spec uninstall_filter(binary()) :: :ok
24 | def uninstall_filter(filter_id) do
25 | GenServer.cast(ContractManager, {:uninstall_filter, filter_id})
26 | end
27 |
28 | @doc "Sets the address for the contract specified by the name argument"
29 | @spec at(atom(), binary()) :: :ok
30 | def at(name, address) do
31 | GenServer.cast(ContractManager, {:at, {name, address}})
32 | end
33 |
34 | @doc "Returns the current Contract GenServer's address"
35 | @spec address(atom()) :: {:ok, binary()}
36 | def address(name) do
37 | GenServer.call(ContractManager, {:address, name})
38 | end
39 |
40 | @doc "Use a Contract's method with an eth_call"
41 | @spec call(atom(), atom(), list(), any()) :: {:ok, any()}
42 | def call(contract_name, method_name, args \\ [], timeout \\ :infinity) do
43 | GenServer.call(ContractManager, {:call, {contract_name, method_name, args}}, timeout)
44 | end
45 |
46 | @doc "Use a Contract's method with an eth_sendTransaction"
47 | @spec send(atom(), atom(), list(), map()) :: {:ok, binary()}
48 | def send(contract_name, method_name, args, options) do
49 | GenServer.call(ContractManager, {:send, {contract_name, method_name, args, options}})
50 | end
51 |
52 | @doc "Returns a formatted transaction receipt for the given transaction hash(id)"
53 | @spec tx_receipt(atom(), binary()) :: map()
54 | def tx_receipt(contract_name, tx_hash) do
55 | GenServer.call(ContractManager, {:tx_receipt, {contract_name, tx_hash}})
56 | end
57 |
58 | @doc "Installs a filter on the Ethereum node. This also formats the parameters, and saves relevant information to format event logs."
59 | @spec filter(atom(), binary(), map()) :: {:ok, binary()}
60 | def filter(contract_name, event_name, event_data \\ %{}) do
61 | GenServer.call(
62 | ContractManager,
63 | {:filter, {contract_name, event_name, event_data}}
64 | )
65 | end
66 |
67 | @doc "Using saved information related to the filter id, event logs are formatted properly"
68 | @spec get_filter_changes(binary()) :: {:ok, list()}
69 | def get_filter_changes(filter_id) do
70 | GenServer.call(
71 | ContractManager,
72 | {:get_filter_changes, filter_id}
73 | )
74 | end
75 |
76 | def init(state) do
77 | {:ok, state}
78 | end
79 |
80 | defp data_signature_helper(name, fields) do
81 | non_indexed_types = Enum.map(fields, &Map.get(&1, "type"))
82 | Enum.join([name, "(", Enum.join(non_indexed_types, ","), ")"])
83 | end
84 |
85 | defp topic_types_helper(fields) do
86 | if length(fields) > 0 do
87 | Enum.map(fields, fn field ->
88 | "(#{field["type"]})"
89 | end)
90 | else
91 | []
92 | end
93 | end
94 |
95 | defp init_events(abi) do
96 | events =
97 | Enum.filter(abi, fn {_, v} ->
98 | v["type"] == "event"
99 | end)
100 |
101 | names_and_signature_types_map =
102 | Enum.map(events, fn {name, v} ->
103 | types = Enum.map(v["inputs"], &Map.get(&1, "type"))
104 | signature = Enum.join([name, "(", Enum.join(types, ","), ")"])
105 | encoded_event_signature = ExW3.Utils.keccak256(signature)
106 |
107 | indexed_fields =
108 | Enum.filter(v["inputs"], fn input ->
109 | input["indexed"]
110 | end)
111 |
112 | indexed_names =
113 | Enum.map(indexed_fields, fn field ->
114 | field["name"]
115 | end)
116 |
117 | non_indexed_fields =
118 | Enum.filter(v["inputs"], fn input ->
119 | !input["indexed"]
120 | end)
121 |
122 | non_indexed_names =
123 | Enum.map(non_indexed_fields, fn field ->
124 | field["name"]
125 | end)
126 |
127 | data_signature = data_signature_helper(name, non_indexed_fields)
128 |
129 | event_attributes = %{
130 | signature: data_signature,
131 | non_indexed_names: non_indexed_names,
132 | topic_types: topic_types_helper(indexed_fields),
133 | topic_names: indexed_names
134 | }
135 |
136 | {{encoded_event_signature, event_attributes}, {name, encoded_event_signature}}
137 | end)
138 |
139 | signature_types_map =
140 | Enum.map(names_and_signature_types_map, fn {signature_types, _} ->
141 | signature_types
142 | end)
143 |
144 | names_map =
145 | Enum.map(names_and_signature_types_map, fn {_, names} ->
146 | names
147 | end)
148 |
149 | [
150 | events: Enum.into(signature_types_map, %{}),
151 | event_names: Enum.into(names_map, %{})
152 | ]
153 | end
154 |
155 | def deploy_helper(bin, abi, args) do
156 | constructor_arg_data =
157 | if arguments = args[:args] do
158 | constructor_abi =
159 | Enum.find(abi, fn {_, v} ->
160 | v["type"] == "constructor"
161 | end)
162 |
163 | if constructor_abi do
164 | {_, constructor} = constructor_abi
165 | input_types = Enum.map(constructor["inputs"], fn x -> x["type"] end)
166 | types_signature = Enum.join(["(", Enum.join(input_types, ","), ")"])
167 |
168 | arg_count = Enum.count(arguments)
169 | input_types_count = Enum.count(input_types)
170 |
171 | if input_types_count != arg_count do
172 | raise "Number of provided arguments to constructor is incorrect. Was given #{
173 | arg_count
174 | } args, looking for #{input_types_count}."
175 | end
176 |
177 | bin <>
178 | (ExW3.Abi.encode_data(types_signature, arguments) |> Base.encode16(case: :lower))
179 | else
180 | # IO.warn("Could not find a constructor")
181 | bin
182 | end
183 | else
184 | bin
185 | end
186 |
187 | gas = ExW3.Abi.encode_option(args[:options][:gas])
188 | gasPrice = ExW3.Abi.encode_option(args[:options][:gas_price])
189 |
190 | tx = %{
191 | from: args[:options][:from],
192 | data: "0x#{constructor_arg_data}",
193 | gas: gas,
194 | gasPrice: gasPrice
195 | }
196 |
197 | {:ok, tx_hash} = ExW3.Rpc.eth_send([tx])
198 | {:ok, tx_receipt} = ExW3.Rpc.tx_receipt(tx_hash)
199 |
200 | {tx_receipt["contractAddress"], tx_hash}
201 | end
202 |
203 | def eth_call_helper(address, abi, method_name, args) do
204 | result =
205 | ExW3.Rpc.eth_call([
206 | %{
207 | to: address,
208 | data: "0x#{ExW3.Abi.encode_method_call(abi, method_name, args)}"
209 | }
210 | ])
211 |
212 | case result do
213 | {:ok, data} ->
214 | ([:ok] ++ ExW3.Abi.decode_output(abi, method_name, data)) |> List.to_tuple()
215 |
216 | {:error, err} ->
217 | {:error, err}
218 | end
219 | end
220 |
221 | def eth_send_helper(address, abi, method_name, args, options) do
222 | encoded_options =
223 | ExW3.Abi.encode_options(
224 | options,
225 | [:gas, :gasPrice, :value, :nonce]
226 | )
227 |
228 | gas = ExW3.Abi.encode_option(args[:options][:gas])
229 | gasPrice = ExW3.Abi.encode_option(args[:options][:gas_price])
230 |
231 | ExW3.Rpc.eth_send([
232 | Map.merge(
233 | %{
234 | to: address,
235 | data: "0x#{ExW3.Abi.encode_method_call(abi, method_name, args)}",
236 | gas: gas,
237 | gasPrice: gasPrice
238 | },
239 | Map.merge(options, encoded_options)
240 | )
241 | ])
242 | end
243 |
244 | defp register_helper(contract_info) do
245 | if contract_info[:abi] do
246 | contract_info ++ init_events(contract_info[:abi])
247 | else
248 | raise "ABI not provided upon initialization"
249 | end
250 | end
251 |
252 | # Options' checkers
253 |
254 | defp check_option(nil, error_atom), do: {:error, error_atom}
255 | defp check_option([], error_atom), do: {:error, error_atom}
256 | defp check_option([head | _tail], _atom) when head != nil, do: {:ok, head}
257 | defp check_option([_head | tail], atom), do: check_option(tail, atom)
258 | defp check_option(value, _atom), do: {:ok, value}
259 |
260 | # Casts
261 |
262 | def handle_cast({:at, {name, address}}, state) do
263 | contract_state = state[name]
264 | contract_state = Keyword.put(contract_state, :address, address)
265 | state = Map.put(state, name, contract_state)
266 | {:noreply, state}
267 | end
268 |
269 | def handle_cast({:register, {name, contract_info}}, state) do
270 | {:noreply, Map.put(state, name, register_helper(contract_info))}
271 | end
272 |
273 | def handle_cast({:uninstall_filter, filter_id}, state) do
274 | ExW3.uninstall_filter(filter_id)
275 | {:noreply, Map.put(state, :filters, Map.delete(state[:filters], filter_id))}
276 | end
277 |
278 | # Calls
279 |
280 | defp filter_topics_helper(event_signature, event_data, topic_types, topic_names) do
281 | topics =
282 | if is_map(event_data[:topics]) do
283 | Enum.map(topic_names, fn name ->
284 | event_data[:topics][String.to_atom(name)]
285 | end)
286 | else
287 | event_data[:topics]
288 | end
289 |
290 | if topics do
291 | formatted_topics =
292 | Enum.map(0..(length(topics) - 1), fn i ->
293 | topic = Enum.at(topics, i)
294 |
295 | if topic do
296 | if is_list(topic) do
297 | topic_type = Enum.at(topic_types, i)
298 |
299 | Enum.map(topic, fn t ->
300 | "0x" <> (ExW3.Abi.encode_data(topic_type, [t]) |> Base.encode16(case: :lower))
301 | end)
302 | else
303 | topic_type = Enum.at(topic_types, i)
304 | "0x" <> (ExW3.Abi.encode_data(topic_type, [topic]) |> Base.encode16(case: :lower))
305 | end
306 | else
307 | topic
308 | end
309 | end)
310 |
311 | [event_signature] ++ formatted_topics
312 | else
313 | [event_signature]
314 | end
315 | end
316 |
317 | def from_block_helper(event_data) do
318 | if event_data[:fromBlock] do
319 | new_from_block =
320 | if Enum.member?(["latest", "earliest", "pending"], event_data[:fromBlock]) do
321 | event_data[:fromBlock]
322 | else
323 | ExW3.Abi.encode_data("(uint256)", [event_data[:fromBlock]])
324 | end
325 |
326 | Map.put(event_data, :fromBlock, new_from_block)
327 | else
328 | event_data
329 | end
330 | end
331 |
332 | defp param_helper(event_data, key) do
333 | if event_data[key] do
334 | new_param =
335 | if Enum.member?(["latest", "earliest", "pending"], event_data[key]) do
336 | event_data[key]
337 | else
338 | "0x" <>
339 | (ExW3.Abi.encode_data("(uint256)", [event_data[key]])
340 | |> Base.encode16(case: :lower))
341 | end
342 |
343 | Map.put(event_data, key, new_param)
344 | else
345 | event_data
346 | end
347 | end
348 |
349 | defp event_data_format_helper(event_data) do
350 | event_data
351 | |> param_helper(:fromBlock)
352 | |> param_helper(:toBlock)
353 | |> Map.delete(:topics)
354 | end
355 |
356 | def get_event_attributes(state, contract_name, event_name) do
357 | contract_info = state[contract_name]
358 | contract_info[:events][contract_info[:event_names][event_name]]
359 | end
360 |
361 | defp extract_non_indexed_fields(data, names, signature) do
362 | Enum.zip(names, ExW3.Abi.decode_event(data, signature)) |> Enum.into(%{})
363 | end
364 |
365 | defp format_log_data(log, event_attributes) do
366 | non_indexed_fields =
367 | extract_non_indexed_fields(
368 | Map.get(log, "data"),
369 | event_attributes[:non_indexed_names],
370 | event_attributes[:signature]
371 | )
372 |
373 | indexed_fields =
374 | if length(log["topics"]) > 1 do
375 | [_head | tail] = log["topics"]
376 |
377 | decoded_topics =
378 | Enum.map(0..(length(tail) - 1), fn i ->
379 | topic_type = Enum.at(event_attributes[:topic_types], i)
380 | topic_data = Enum.at(tail, i)
381 |
382 | {decoded} = ExW3.Abi.decode_data(topic_type, topic_data)
383 |
384 | decoded
385 | end)
386 |
387 | Enum.zip(event_attributes[:topic_names], decoded_topics) |> Enum.into(%{})
388 | else
389 | %{}
390 | end
391 |
392 | new_data = Map.merge(indexed_fields, non_indexed_fields)
393 |
394 | Map.put(log, "data", new_data)
395 | end
396 |
397 | def handle_call({:filter, {contract_name, event_name, event_data}}, _from, state) do
398 | contract_info = state[contract_name]
399 |
400 | event_signature = contract_info[:event_names][event_name]
401 | topic_types = contract_info[:events][event_signature][:topic_types]
402 | topic_names = contract_info[:events][event_signature][:topic_names]
403 |
404 | topics = filter_topics_helper(event_signature, event_data, topic_types, topic_names)
405 |
406 | payload =
407 | Map.merge(
408 | %{address: contract_info[:address], topics: topics},
409 | event_data_format_helper(event_data)
410 | )
411 |
412 | filter_id = ExW3.Rpc.new_filter(payload)
413 |
414 | {:reply, {:ok, filter_id},
415 | Map.put(
416 | state,
417 | :filters,
418 | Map.put(state[:filters], filter_id, %{
419 | contract_name: contract_name,
420 | event_name: event_name
421 | })
422 | )}
423 | end
424 |
425 | def handle_call({:get_filter_changes, filter_id}, _from, state) do
426 | filter_info = Map.get(state[:filters], filter_id)
427 |
428 | event_attributes =
429 | get_event_attributes(state, filter_info[:contract_name], filter_info[:event_name])
430 |
431 | logs = ExW3.Rpc.get_filter_changes(filter_id)
432 |
433 | formatted_logs =
434 | if logs != [] do
435 | Enum.map(logs, fn log ->
436 | formatted_log =
437 | Enum.reduce(
438 | [
439 | ExW3.Normalize.transform_to_integer(log, [
440 | "blockNumber",
441 | "logIndex",
442 | "transactionIndex"
443 | ]),
444 | format_log_data(log, event_attributes)
445 | ],
446 | &Map.merge/2
447 | )
448 |
449 | formatted_log
450 | end)
451 | else
452 | logs
453 | end
454 |
455 | {:reply, {:ok, formatted_logs}, state}
456 | end
457 |
458 | def handle_call({:deploy, {name, args}}, _from, state) do
459 | contract_info = state[name]
460 |
461 | with {:ok, _} <- check_option(args[:options][:from], :missing_sender),
462 | {:ok, _} <- check_option(args[:options][:gas], :missing_gas),
463 | {:ok, bin} <- check_option([state[:bin], args[:bin]], :missing_binary) do
464 | {contract_addr, tx_hash} = deploy_helper(bin, contract_info[:abi], args)
465 | result = {:ok, contract_addr, tx_hash}
466 | {:reply, result, state}
467 | else
468 | err -> {:reply, err, state}
469 | end
470 | end
471 |
472 | def handle_call({:address, name}, _from, state) do
473 | {:reply, state[name][:address], state}
474 | end
475 |
476 | def handle_call({:call, {contract_name, method_name, args}}, _from, state) do
477 | contract_info = state[contract_name]
478 |
479 | with {:ok, address} <- check_option(contract_info[:address], :missing_address) do
480 | result = eth_call_helper(address, contract_info[:abi], Atom.to_string(method_name), args)
481 | {:reply, result, state}
482 | else
483 | err -> {:reply, err, state}
484 | end
485 | end
486 |
487 | def handle_call({:send, {contract_name, method_name, args, options}}, _from, state) do
488 | contract_info = state[contract_name]
489 |
490 | with {:ok, address} <- check_option(contract_info[:address], :missing_address),
491 | {:ok, _} <- check_option(options[:from], :missing_sender),
492 | {:ok, _} <- check_option(options[:gas], :missing_gas) do
493 | result =
494 | eth_send_helper(
495 | address,
496 | contract_info[:abi],
497 | Atom.to_string(method_name),
498 | args,
499 | options
500 | )
501 |
502 | {:reply, result, state}
503 | else
504 | err -> {:reply, err, state}
505 | end
506 | end
507 |
508 | def handle_call({:tx_receipt, {contract_name, tx_hash}}, _from, state) do
509 | contract_info = state[contract_name]
510 |
511 | {:ok, receipt} = ExW3.tx_receipt(tx_hash)
512 |
513 | events = contract_info[:events]
514 | logs = receipt["logs"]
515 |
516 | formatted_logs =
517 | Enum.map(logs, fn log ->
518 | topic = Enum.at(log["topics"], 0)
519 | event_attributes = Map.get(events, topic)
520 |
521 | if event_attributes do
522 | non_indexed_fields =
523 | Enum.zip(
524 | event_attributes[:non_indexed_names],
525 | ExW3.Abi.decode_event(log["data"], event_attributes[:signature])
526 | )
527 | |> Enum.into(%{})
528 |
529 | if length(log["topics"]) > 1 do
530 | [_head | tail] = log["topics"]
531 |
532 | decoded_topics =
533 | Enum.map(0..(length(tail) - 1), fn i ->
534 | topic_type = Enum.at(event_attributes[:topic_types], i)
535 | topic_data = Enum.at(tail, i)
536 |
537 | {decoded} = ExW3.Abi.decode_data(topic_type, topic_data)
538 |
539 | decoded
540 | end)
541 |
542 | indexed_fields =
543 | Enum.zip(event_attributes[:topic_names], decoded_topics) |> Enum.into(%{})
544 |
545 | Map.merge(indexed_fields, non_indexed_fields)
546 | else
547 | non_indexed_fields
548 | end
549 | else
550 | nil
551 | end
552 | end)
553 |
554 | {:reply, {:ok, {receipt, formatted_logs}}, state}
555 | end
556 | end
557 |
--------------------------------------------------------------------------------
/lib/exw3/normalize.ex:
--------------------------------------------------------------------------------
1 | defmodule ExW3.Normalize do
2 | @spec transform_to_integer(map(), list()) :: map()
3 | def transform_to_integer(map, keys) do
4 | for k <- keys, into: %{} do
5 | {:ok, v} = map |> Map.get(k) |> ExW3.Utils.hex_to_integer()
6 | {k, v}
7 | end
8 | end
9 | end
10 |
--------------------------------------------------------------------------------
/lib/exw3/rpc.ex:
--------------------------------------------------------------------------------
1 | defmodule ExW3.Rpc do
2 | import ExW3.Client
3 |
4 | @type invalid_hex_string_error :: ExW3.Utils.invalid_hex_string_error()
5 | @type request_error :: Ethereumex.Client.Behaviour.error()
6 | @type opts :: {:url, String.t()}
7 | @type hex_block_number :: String.t()
8 | @type latest :: String.t()
9 | @type earliest :: String.t()
10 | @type pending :: String.t()
11 |
12 | @doc "returns all available accounts"
13 | @spec accounts() :: list()
14 | @spec accounts([opts]) :: list()
15 | def accounts(opts \\ []) do
16 | case call_client(:eth_accounts, [opts]) do
17 | {:ok, accounts} -> accounts
18 | err -> err
19 | end
20 | end
21 |
22 | @doc "Returns the current block number"
23 | @spec block_number() :: {:ok, non_neg_integer} | {:error, ExW3.Utils.invalid_hex_string()}
24 | @spec block_number([opts]) :: {:ok, non_neg_integer} | {:error, ExW3.Utils.invalid_hex_string()}
25 | def block_number(opts \\ []) do
26 | case call_client(:eth_block_number, [opts]) do
27 | {:ok, hex_block_number} -> ExW3.Utils.hex_to_integer(hex_block_number)
28 | err -> err
29 | end
30 | end
31 |
32 | @doc "Returns current balance of account"
33 | @spec balance(binary()) :: integer() | {:error, any()}
34 | @spec balance(binary(), [opts]) :: integer() | {:error, any()}
35 | def balance(account, opts \\ []) do
36 | case call_client(:eth_get_balance, [account, "latest", opts]) do
37 | {:ok, hex_balance} ->
38 | {:ok, balance} = ExW3.Utils.hex_to_integer(hex_balance)
39 | balance
40 |
41 | err ->
42 | err
43 | end
44 | end
45 |
46 | @doc "Returns transaction receipt for specified transaction hash(id)"
47 | @spec tx_receipt(binary()) :: {:ok, map()} | {:error, any()}
48 | def tx_receipt(tx_hash) do
49 | case call_client(:eth_get_transaction_receipt, [tx_hash]) do
50 | {:ok, nil} ->
51 | {:error, :not_mined}
52 |
53 | {:ok, receipt} ->
54 | normalized_receipt =
55 | ExW3.Normalize.transform_to_integer(receipt, ~w(blockNumber cumulativeGasUsed gasUsed))
56 |
57 | {:ok, Map.merge(receipt, normalized_receipt)}
58 |
59 | err ->
60 | {:error, err}
61 | end
62 | end
63 |
64 | @doc "Returns block data for specified block number"
65 | @spec block(integer()) :: any() | {:error, any()}
66 | def block(block_number) do
67 | case call_client(:eth_get_block_by_number, [block_number, true]) do
68 | {:ok, block} -> block
69 | err -> err
70 | end
71 | end
72 |
73 | @doc "Creates a new filter, returns filter id. For more sophisticated use, prefer ExW3.Contract.filter."
74 | @spec new_filter(map()) :: binary() | {:error, any()}
75 | def new_filter(map) do
76 | case call_client(:eth_new_filter, [map]) do
77 | {:ok, filter_id} -> filter_id
78 | err -> err
79 | end
80 | end
81 |
82 | @doc "Gets event changes (logs) by filter. Unlike ExW3.Contract.get_filter_changes it does not return the data in a formatted way"
83 | @spec get_filter_changes(binary()) :: any()
84 | def get_filter_changes(filter_id) do
85 | case call_client(:eth_get_filter_changes, [filter_id]) do
86 | {:ok, changes} -> changes
87 | err -> err
88 | end
89 | end
90 |
91 | @type log_filter :: %{
92 | optional(:address) => String.t(),
93 | optional(:fromBlock) => hex_block_number | latest | earliest | pending,
94 | optional(:toBlock) => hex_block_number | latest | earliest | pending,
95 | optional(:topics) => [String.t()],
96 | optional(:blockhash) => String.t()
97 | }
98 |
99 | @spec get_logs(log_filter, [opts]) :: {:ok, list} | {:error, term} | request_error
100 | def get_logs(filter, opts \\ []) do
101 | with {:ok, _} = result <- call_client(:eth_get_logs, [filter, opts]) do
102 | result
103 | else
104 | err -> err
105 | end
106 | end
107 |
108 | @doc "Uninstalls filter from the ethereum node"
109 | @spec uninstall_filter(binary()) :: boolean() | {:error, any()}
110 | def uninstall_filter(filter_id) do
111 | case call_client(:eth_uninstall_filter, [filter_id]) do
112 | {:ok, result} -> result
113 | err -> err
114 | end
115 | end
116 |
117 | @doc "Mines number of blocks specified. Default is 1"
118 | @spec mine(integer()) :: any() | {:error, any()}
119 | def mine(num_blocks \\ 1) do
120 | for _ <- 0..(num_blocks - 1) do
121 | call_client(:request, ["evm_mine", [], []])
122 | end
123 | end
124 |
125 | @doc "Using the personal api, returns list of accounts."
126 | @spec personal_list_accounts(list()) :: {:ok, list()} | {:error, any()}
127 | def personal_list_accounts(opts \\ []) do
128 | call_client(:request, ["personal_listAccounts", [], opts])
129 | end
130 |
131 | @doc "Using the personal api, this method creates a new account with the passphrase, and returns new account address."
132 | @spec personal_new_account(binary(), list()) :: {:ok, binary()} | {:error, any()}
133 | def personal_new_account(password, opts \\ []) do
134 | call_client(:request, ["personal_newAccount", [password], opts])
135 | end
136 |
137 | @doc "Using the personal api, this method unlocks account using the passphrase provided, and returns a boolean."
138 | @spec personal_unlock_account(binary(), list()) :: {:ok, boolean()} | {:error, any()}
139 | ### E.g. ExW3.personal_unlock_account(["0x1234","Password",30], [])
140 | def personal_unlock_account(params, opts \\ []) do
141 | call_client(:request, ["personal_unlockAccount", params, opts])
142 | end
143 |
144 | @doc "Using the personal api, this method sends a transaction and signs it in one call, and returns a transaction id hash."
145 | @spec personal_send_transaction(map(), binary(), list()) :: {:ok, binary()} | {:error, any()}
146 | def personal_send_transaction(param_map, passphrase, opts \\ []) do
147 | call_client(:request, ["personal_sendTransaction", [param_map, passphrase], opts])
148 | end
149 |
150 | @doc "Using the personal api, this method signs a transaction, and returns the signed transaction."
151 | @spec personal_sign_transaction(map(), binary(), list()) :: {:ok, map()} | {:error, any()}
152 | def personal_sign_transaction(param_map, passphrase, opts \\ []) do
153 | call_client(:request, ["personal_signTransaction", [param_map, passphrase], opts])
154 | end
155 |
156 | @doc "Using the personal api, this method calculates an Ethereum specific signature, and returns that signature."
157 | @spec personal_sign(binary(), binary(), binary(), list()) :: {:ok, binary()} | {:error, any()}
158 | def personal_sign(data, address, passphrase, opts \\ []) do
159 | call_client(:request, ["personal_sign", [data, address, passphrase], opts])
160 | end
161 |
162 | @doc "Using the personal api, this method returns the address associated with the private key that was used to calculate the signature with personal_sign."
163 | @spec personal_ec_recover(binary(), binary(), []) :: {:ok, binary()} | {:error, any()}
164 | def personal_ec_recover(data0, data1, opts \\ []) do
165 | call_client(:request, ["personal_ecRecover", [data0, data1], opts])
166 | end
167 |
168 | @doc "Calculates an Ethereum specific signature and signs the data provided, using the accounts private key"
169 | @spec eth_sign(binary(), binary(), list()) :: {:ok, binary()} | {:error, any()}
170 | def eth_sign(data0, data1, opts \\ []) do
171 | call_client(:request, ["eth_sign", [data0, data1], opts])
172 | end
173 |
174 | @doc "Simple eth_call to client. Recommended to use ExW3.Contract.call instead."
175 | @spec eth_call(list()) :: any()
176 | def eth_call(arguments) do
177 | call_client(:eth_call, arguments)
178 | end
179 |
180 | @doc "Simple eth_send_transaction. Recommended to use ExW3.Contract.send instead."
181 | @spec eth_send(list()) :: any()
182 | def eth_send(arguments) do
183 | call_client(:eth_send_transaction, arguments)
184 | end
185 | end
186 |
--------------------------------------------------------------------------------
/lib/exw3/utils.ex:
--------------------------------------------------------------------------------
1 | defmodule ExW3.Utils do
2 | alias ExW3.Address
3 |
4 | @type invalid_hex_string :: :invalid_hex_string
5 | @type negative_integer :: :negative_integer
6 | @type non_integer :: :non_integer
7 | @type eth_hex :: String.t()
8 |
9 | @doc "Convert eth hex string to integer"
10 | @spec hex_to_integer(eth_hex) ::
11 | {:ok, non_neg_integer} | {:error, invalid_hex_string}
12 | def hex_to_integer(hex) do
13 | case hex do
14 | "0x" <> hex -> {:ok, String.to_integer(hex, 16)}
15 | _ -> {:error, :invalid_hex_string}
16 | end
17 | rescue
18 | ArgumentError ->
19 | {:error, :invalid_hex_string}
20 | end
21 |
22 | @doc "Convert an integer to eth hex string"
23 | @spec integer_to_hex(non_neg_integer) ::
24 | {:ok, eth_hex} | {:error, negative_integer | non_integer}
25 | def integer_to_hex(i) do
26 | case i do
27 | i when i < 0 -> {:error, :negative_integer}
28 | i -> {:ok, "0x" <> Integer.to_string(i, 16)}
29 | end
30 | rescue
31 | ArgumentError ->
32 | {:error, :non_integer}
33 | end
34 |
35 | @doc "Returns a 0x prepended 32 byte hash of the input string"
36 | @spec keccak256(String.t()) :: String.t()
37 | def keccak256(str) do
38 | "0x#{str |> ExKeccak.hash_256() |> Base.encode16(case: :lower)}"
39 | end
40 |
41 | @unit_map %{
42 | :noether => 0,
43 | :wei => 1,
44 | :kwei => 1_000,
45 | :Kwei => 1_000,
46 | :babbage => 1_000,
47 | :femtoether => 1_000,
48 | :mwei => 1_000_000,
49 | :Mwei => 1_000_000,
50 | :lovelace => 1_000_000,
51 | :picoether => 1_000_000,
52 | :gwei => 1_000_000_000,
53 | :Gwei => 1_000_000_000,
54 | :shannon => 1_000_000_000,
55 | :nanoether => 1_000_000_000,
56 | :nano => 1_000_000_000,
57 | :szabo => 1_000_000_000_000,
58 | :microether => 1_000_000_000_000,
59 | :micro => 1_000_000_000_000,
60 | :finney => 1_000_000_000_000_000,
61 | :milliether => 1_000_000_000_000_000,
62 | :milli => 1_000_000_000_000_000,
63 | :ether => 1_000_000_000_000_000_000,
64 | :kether => 1_000_000_000_000_000_000_000,
65 | :grand => 1_000_000_000_000_000_000_000,
66 | :mether => 1_000_000_000_000_000_000_000_000,
67 | :gether => 1_000_000_000_000_000_000_000_000_000,
68 | :tether => 1_000_000_000_000_000_000_000_000_000_000
69 | }
70 |
71 | @doc "Converts the value to whatever unit key is provided. See unit map for details."
72 | @spec to_wei(integer, atom) :: integer
73 | def to_wei(num, key) do
74 | if @unit_map[key] do
75 | num * @unit_map[key]
76 | else
77 | throw("#{key} not valid unit")
78 | end
79 | end
80 |
81 | @doc "Converts the value to whatever unit key is provided. See unit map for details."
82 | @spec from_wei(integer, atom) :: integer | float | no_return
83 | def from_wei(num, key) do
84 | if @unit_map[key] do
85 | num / @unit_map[key]
86 | else
87 | throw("#{key} not valid unit")
88 | end
89 | end
90 |
91 | @deprecated "Use ExW3.Address.to_checksum/1 instead."
92 | @doc "Returns a checksummed address conforming to EIP-55"
93 | @spec to_checksum_address(String.t()) :: String.t()
94 | def to_checksum_address(address) do
95 | address
96 | |> Address.from_hex()
97 | |> Address.to_checksum()
98 | end
99 |
100 | @deprecated "Use ExW3.Address.is_valid_checksum?/1 instead."
101 | @doc "Checks if the address is a valid checksummed address"
102 | @spec is_valid_checksum_address(String.t()) :: boolean
103 | def is_valid_checksum_address(address) do
104 | Address.is_valid_checksum?(address)
105 | end
106 |
107 | @doc "converts Ethereum style bytes to string"
108 | @spec bytes_to_string(binary()) :: binary()
109 | def bytes_to_string(bytes) do
110 | bytes
111 | |> Base.encode16(case: :lower)
112 | |> String.replace_trailing("0", "")
113 | |> Base.decode16!(case: :lower)
114 | end
115 |
116 | @doc "Converts an Ethereum address into a form that can be used by the ABI encoder"
117 | @spec format_address(binary()) :: integer()
118 | def format_address(address) do
119 | address
120 | |> String.slice(2..-1)
121 | |> Base.decode16!(case: :lower)
122 | |> :binary.decode_unsigned()
123 | end
124 |
125 | @deprecated "Use ExW3.Address.to_hex/1 instead."
126 | @doc "Converts bytes to Ethereum address"
127 | @spec to_address(binary()) :: binary()
128 | def to_address(bytes) do
129 | bytes
130 | |> Address.from_bytes()
131 | |> Address.to_hex()
132 | end
133 | end
134 |
--------------------------------------------------------------------------------
/mix.exs:
--------------------------------------------------------------------------------
1 | defmodule ExW3.MixProject do
2 | use Mix.Project
3 |
4 | @source_url "https://github.com/hswick/exw3"
5 | @version "0.6.1"
6 |
7 | def project do
8 | [
9 | app: :exw3,
10 | version: @version,
11 | elixir: "~> 1.10",
12 | build_embedded: Mix.env() == :prod,
13 | start_permanent: Mix.env() == :prod,
14 | deps: deps(),
15 | docs: docs(),
16 | package: package(),
17 | name: "exw3",
18 | dialyzer: [
19 | remove_defaults: [:unknown]
20 | ],
21 | preferred_cli_env: [
22 | docs: :docs,
23 | "hex.publish": :docs
24 | ]
25 | ]
26 | end
27 |
28 | def application do
29 | [applications: [:logger, :ex_abi, :ethereumex]]
30 | end
31 |
32 | defp deps do
33 | [
34 | {:ex_doc, ">= 0.0.0", only: :docs, runtime: false},
35 | {:ethereumex, "~> 0.7.0"},
36 | {:ex_keccak, "~> 0.2"},
37 | {:ex_abi, "~> 0.5.4"},
38 | {:dialyxir, "~> 1.0", only: [:dev], runtime: false},
39 | {:jason, "~> 1.2"}
40 | ]
41 | end
42 |
43 | defp package do
44 | [
45 | name: "exw3",
46 | description: "A high level Ethereum JSON RPC Client for Elixir",
47 | files: ["lib", "mix.exs", "README*", "LICENSE*"],
48 | maintainers: ["Harley Swick"],
49 | licenses: ["Apache-2.0"],
50 | links: %{"GitHub" => @source_url}
51 | ]
52 | end
53 |
54 | defp docs do
55 | [
56 | extras: [
57 | LICENSE: [title: "License"],
58 | "README.md": [title: "Overview"]
59 | ],
60 | main: "readme",
61 | assets: "assets",
62 | source_url: @source_url,
63 | source_ref: "v#{@version}",
64 | formatters: ["html"]
65 | ]
66 | end
67 | end
68 |
--------------------------------------------------------------------------------
/mix.lock:
--------------------------------------------------------------------------------
1 | %{
2 | "certifi": {:hex, :certifi, "2.8.0", "d4fb0a6bb20b7c9c3643e22507e42f356ac090a1dcea9ab99e27e0376d695eba", [:rebar3], [], "hexpm", "6ac7efc1c6f8600b08d625292d4bbf584e14847ce1b6b5c44d983d273e1097ea"},
3 | "dialyxir": {:hex, :dialyxir, "1.1.0", "c5aab0d6e71e5522e77beff7ba9e08f8e02bad90dfbeffae60eaf0cb47e29488", [:mix], [{:erlex, ">= 0.2.6", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "07ea8e49c45f15264ebe6d5b93799d4dd56a44036cf42d0ad9c960bc266c0b9a"},
4 | "earmark_parser": {:hex, :earmark_parser, "1.4.26", "f4291134583f373c7d8755566122908eb9662df4c4b63caa66a0eabe06569b0a", [:mix], [], "hexpm", "48d460899f8a0c52c5470676611c01f64f3337bad0b26ddab43648428d94aabc"},
5 | "erlex": {:hex, :erlex, "0.2.6", "c7987d15e899c7a2f34f5420d2a2ea0d659682c06ac607572df55a43753aa12e", [:mix], [], "hexpm", "2ed2e25711feb44d52b17d2780eabf998452f6efda104877a3881c2f8c0c0c75"},
6 | "ethereumex": {:hex, :ethereumex, "0.7.1", "9a376d072be0f318d2685fadf87877cf58884e382e00ccaee7834f3327ade0a8", [:mix], [{:httpoison, "~> 1.7", [hex: :httpoison, repo: "hexpm", optional: false]}, {:jason, "~> 1.2", [hex: :jason, repo: "hexpm", optional: false]}, {:poolboy, "~> 1.5", [hex: :poolboy, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "58ba04d235cfb6e8ced3fd79443ea1bde78f24cb6719538572fab89fdc8427b8"},
7 | "ex_abi": {:hex, :ex_abi, "0.5.9", "afdef4279eb24a36bef1d4a83df8a34997c2dddf3ffac48866bb1113f28ae55b", [:mix], [{:ex_keccak, "~> 0.3.0", [hex: :ex_keccak, repo: "hexpm", optional: false]}, {:jason, "~> 1.3", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "230f6dada9995336f1d1b739194d99307a1d079e045548bbca0b622c8c4dbf5b"},
8 | "ex_doc": {:hex, :ex_doc, "0.28.5", "3e52a6d2130ce74d096859e477b97080c156d0926701c13870a4e1f752363279", [:mix], [{:earmark_parser, "~> 1.4.19", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1", [hex: :makeup_erlang, repo: "hexpm", optional: false]}], "hexpm", "d2c4b07133113e9aa3e9ba27efb9088ba900e9e51caa383919676afdf09ab181"},
9 | "ex_keccak": {:hex, :ex_keccak, "0.3.0", "8c286f8c44c63c5f95e84053603f09cbef52d96314f2b751e56cf8836ceaea63", [:mix], [{:rustler, "~> 0.23", [hex: :rustler, repo: "hexpm", optional: false]}], "hexpm", "18352c5873ee4938363ae9802038b6a157177a080db40b6e4ab842255ae44b9b"},
10 | "hackney": {:hex, :hackney, "1.18.0", "c4443d960bb9fba6d01161d01cd81173089686717d9490e5d3606644c48d121f", [:rebar3], [{:certifi, "~>2.8.0", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "~>6.1.0", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "~>1.0.0", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "~>1.1", [hex: :mimerl, repo: "hexpm", optional: false]}, {:parse_trans, "3.3.1", [hex: :parse_trans, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "~>1.1.0", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}, {:unicode_util_compat, "~>0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "9afcda620704d720db8c6a3123e9848d09c87586dc1c10479c42627b905b5c5e"},
11 | "httpoison": {:hex, :httpoison, "1.8.0", "6b85dea15820b7804ef607ff78406ab449dd78bed923a49c7160e1886e987a3d", [:mix], [{:hackney, "~> 1.17", [hex: :hackney, repo: "hexpm", optional: false]}], "hexpm", "28089eaa98cf90c66265b6b5ad87c59a3729bea2e74e9d08f9b51eb9729b3c3a"},
12 | "idna": {:hex, :idna, "6.1.1", "8a63070e9f7d0c62eb9d9fcb360a7de382448200fbbd1b106cc96d3d8099df8d", [:rebar3], [{:unicode_util_compat, "~>0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "92376eb7894412ed19ac475e4a86f7b413c1b9fbb5bd16dccd57934157944cea"},
13 | "jason": {:hex, :jason, "1.3.0", "fa6b82a934feb176263ad2df0dbd91bf633d4a46ebfdffea0c8ae82953714946", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "53fc1f51255390e0ec7e50f9cb41e751c260d065dcba2bf0d08dc51a4002c2ac"},
14 | "makeup": {:hex, :makeup, "1.1.0", "6b67c8bc2882a6b6a445859952a602afc1a41c2e08379ca057c0f525366fc3ca", [:mix], [{:nimble_parsec, "~> 1.2.2 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "0a45ed501f4a8897f580eabf99a2e5234ea3e75a4373c8a52824f6e873be57a6"},
15 | "makeup_elixir": {:hex, :makeup_elixir, "0.16.0", "f8c570a0d33f8039513fbccaf7108c5d750f47d8defd44088371191b76492b0b", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "28b2cbdc13960a46ae9a8858c4bebdec3c9a6d7b4b9e7f4ed1502f8159f338e7"},
16 | "makeup_erlang": {:hex, :makeup_erlang, "0.1.1", "3fcb7f09eb9d98dc4d208f49cc955a34218fc41ff6b84df7c75b3e6e533cc65f", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "174d0809e98a4ef0b3309256cbf97101c6ec01c4ab0b23e926a9e17df2077cbb"},
17 | "metrics": {:hex, :metrics, "1.0.1", "25f094dea2cda98213cecc3aeff09e940299d950904393b2a29d191c346a8486", [:rebar3], [], "hexpm", "69b09adddc4f74a40716ae54d140f93beb0fb8978d8636eaded0c31b6f099f16"},
18 | "mimerl": {:hex, :mimerl, "1.2.0", "67e2d3f571088d5cfd3e550c383094b47159f3eee8ffa08e64106cdf5e981be3", [:rebar3], [], "hexpm", "f278585650aa581986264638ebf698f8bb19df297f66ad91b18910dfc6e19323"},
19 | "nimble_parsec": {:hex, :nimble_parsec, "1.2.3", "244836e6e3f1200c7f30cb56733fd808744eca61fd182f731eac4af635cc6d0b", [:mix], [], "hexpm", "c8d789e39b9131acf7b99291e93dae60ab48ef14a7ee9d58c6964f59efb570b0"},
20 | "parse_trans": {:hex, :parse_trans, "3.3.1", "16328ab840cc09919bd10dab29e431da3af9e9e7e7e6f0089dd5a2d2820011d8", [:rebar3], [], "hexpm", "07cd9577885f56362d414e8c4c4e6bdf10d43a8767abb92d24cbe8b24c54888b"},
21 | "poison": {:hex, :poison, "4.0.1", "bcb755a16fac91cad79bfe9fc3585bb07b9331e50cfe3420a24bcc2d735709ae", [:mix], [], "hexpm", "ba8836feea4b394bb718a161fc59a288fe0109b5006d6bdf97b6badfcf6f0f25"},
22 | "poolboy": {:hex, :poolboy, "1.5.2", "392b007a1693a64540cead79830443abf5762f5d30cf50bc95cb2c1aaafa006b", [:rebar3], [], "hexpm", "dad79704ce5440f3d5a3681c8590b9dc25d1a561e8f5a9c995281012860901e3"},
23 | "rustler": {:hex, :rustler, "0.23.0", "87162ffdf5a46b6aa03d624a77367070ff1263961ae35332c059225e136c4a87", [:mix], [{:jason, "~> 1.2", [hex: :jason, repo: "hexpm", optional: false]}, {:toml, "~> 0.5.2", [hex: :toml, repo: "hexpm", optional: false]}], "hexpm", "f5ab6f0ec564f5569009c0f5685b0e5b379fd72655e82a8dc5a3c24f9fdda36a"},
24 | "ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.6", "cf344f5692c82d2cd7554f5ec8fd961548d4fd09e7d22f5b62482e5aeaebd4b0", [:make, :mix, :rebar3], [], "hexpm", "bdb0d2471f453c88ff3908e7686f86f9be327d065cc1ec16fa4540197ea04680"},
25 | "telemetry": {:hex, :telemetry, "1.0.0", "0f453a102cdf13d506b7c0ab158324c337c41f1cc7548f0bc0e130bbf0ae9452", [:rebar3], [], "hexpm", "73bc09fa59b4a0284efb4624335583c528e07ec9ae76aca96ea0673850aec57a"},
26 | "toml": {:hex, :toml, "0.5.2", "e471388a8726d1ce51a6b32f864b8228a1eb8edc907a0edf2bb50eab9321b526", [:mix], [], "hexpm", "f1e3dabef71fb510d015fad18c0e05e7c57281001141504c6b69d94e99750a07"},
27 | "unicode_util_compat": {:hex, :unicode_util_compat, "0.7.0", "bc84380c9ab48177092f43ac89e4dfa2c6d62b40b8bd132b1059ecc7232f9a78", [:rebar3], [], "hexpm", "25eee6d67df61960cf6a794239566599b09e17e668d3700247bc498638152521"},
28 | }
29 |
--------------------------------------------------------------------------------
/parity.sh:
--------------------------------------------------------------------------------
1 | parity --chain dev --unlock=0x00a329c0648769a73afac7f9381e08fb43dbea72 --reseal-min-period 0 --password passfile --jsonrpc-apis "web3,eth,personal,pubsub,net,parity,parity_pubsub,traces,rpc,secretstore" --ipc-apis "web3,eth,personal,pubsub,net,parity,parity_pubsub,parity_accounts,traces,rpc,secretstore"
2 |
--------------------------------------------------------------------------------
/test/examples/build/AddressTester.abi:
--------------------------------------------------------------------------------
1 | [{"constant":true,"inputs":[{"name":"a","type":"address"}],"name":"get","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"pure","type":"function"}]
--------------------------------------------------------------------------------
/test/examples/build/AddressTester.bin:
--------------------------------------------------------------------------------
1 | 608060405234801561001057600080fd5b5060fa8061001f6000396000f300608060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063c2bc2efc146044575b600080fd5b348015604f57600080fd5b506082600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505060c4565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b60008190509190505600a165627a7a723058208484bae125ac44444f4a08d58fc40768b5a1ed1fe02d050df852087c40426ec00029
--------------------------------------------------------------------------------
/test/examples/build/ArrayTester.abi:
--------------------------------------------------------------------------------
1 | [{"constant":true,"inputs":[{"name":"ints","type":"uint256[5]"}],"name":"staticUint","outputs":[{"name":"","type":"uint256[5]"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"name":"ints","type":"uint256[]"}],"name":"dynamicUint","outputs":[{"name":"","type":"uint256[]"}],"payable":false,"stateMutability":"pure","type":"function"}]
--------------------------------------------------------------------------------
/test/examples/build/ArrayTester.bin:
--------------------------------------------------------------------------------
1 | 608060405234801561001057600080fd5b50610203806100206000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680635cfd038d146100515780635d4e0342146100df575b600080fd5b34801561005d57600080fd5b506100a16004803603810190808060a0019060058060200260405190810160405280929190826005602002808284378201915050505050919291929050505061019a565b6040518082600560200280838360005b838110156100cc5780820151818401526020810190506100b1565b5050505090500191505060405180910390f35b3480156100eb57600080fd5b50610143600480360381019080803590602001908201803590602001908080602002602001604051908101604052809392919081815260200183836020028082843782019150505050505091929192905050506101aa565b6040518080602001828103825283818151815260200191508051906020019060200280838360005b8381101561018657808201518184015260208101905061016b565b505050509050019250505060405180910390f35b6101a26101b4565b819050919050565b6060819050919050565b60a0604051908101604052806005906020820280388339808201915050905050905600a165627a7a72305820e9a75c1e663616419f7f77d68c69fd084a70e311442322069c67d3222bf1f1bc0029
--------------------------------------------------------------------------------
/test/examples/build/Complex.abi:
--------------------------------------------------------------------------------
1 | [{"constant":true,"inputs":[],"name":"getBroAndBroBro","outputs":[{"name":"bro","type":"uint256"},{"name":"broBro","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getBarFoo","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_foobar","type":"bytes32"}],"name":"setFooBar","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getBoth","outputs":[{"name":"","type":"uint256"},{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_barFoo","type":"bool"}],"name":"setBarFoo","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_fooboo","type":"uint256"}],"name":"getFooBoo","outputs":[{"name":"fooBoo","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"getFooBar","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_foo","type":"uint256"}],"name":"setFoo","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_foo","type":"uint256"},{"name":"_foobar","type":"bytes32"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"foo","type":"uint256"},{"indexed":false,"name":"person","type":"address"}],"name":"Bar","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"fooboo","type":"bool"},{"indexed":false,"name":"foo","type":"uint256"},{"indexed":false,"name":"foobar","type":"bytes32"}],"name":"FooBar","type":"event"}]
--------------------------------------------------------------------------------
/test/examples/build/Complex.bin:
--------------------------------------------------------------------------------
1 | 608060405234801561001057600080fd5b50604051604080610348833981018060405281019080805190602001909291908051906020019092919050505081600081905550806001816000191690555050506102e8806100606000396000f30060806040526004361061008e576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680631b85502e1461009057806354fcb8a6146100ca5780637b07059b146100f957806393affe511461012a5780639aa7c12014610164578063b17e413b14610193578063cfd91f2b146101d4578063dc80035d14610207575b005b34801561009c57600080fd5b506100a5610234565b6040518083815260200182600019166000191681526020019250505060405180910390f35b3480156100d657600080fd5b506100df610248565b604051808215151515815260200191505060405180910390f35b34801561010557600080fd5b50610128600480360381019080803560001916906020019092919050505061025f565b005b34801561013657600080fd5b5061013f61026d565b6040518083815260200182600019166000191681526020019250505060405180910390f35b34801561017057600080fd5b5061019160048036038101908080351515906020019092919050505061027e565b005b34801561019f57600080fd5b506101be6004803603810190808035906020019092919050505061029b565b6040518082815260200191505060405180910390f35b3480156101e057600080fd5b506101e96102a8565b60405180826000191660001916815260200191505060405180910390f35b34801561021357600080fd5b50610232600480360381019080803590602001909291905050506102b2565b005b600080602a60005401600154915091509091565b6000600260009054906101000a900460ff16905090565b806001816000191690555050565b600080600054600154915091509091565b80600260006101000a81548160ff02191690831515021790555050565b6000602a82019050919050565b6000600154905090565b80600081905550505600a165627a7a72305820011e5b9e0027011168cadc65c33ba8af814dfcfbf4a1b9683f48fa17bcb352500029
--------------------------------------------------------------------------------
/test/examples/build/EventTester.abi:
--------------------------------------------------------------------------------
1 | [{"constant":false,"inputs":[{"name":"data","type":"bytes32"}],"name":"simpleIndex","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"data","type":"bytes32"}],"name":"simple","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"num","type":"uint256"},{"indexed":false,"name":"data","type":"bytes32"}],"name":"Simple","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"num","type":"uint256"},{"indexed":true,"name":"data","type":"bytes32"},{"indexed":false,"name":"otherNum","type":"uint256"}],"name":"SimpleIndex","type":"event"}]
--------------------------------------------------------------------------------
/test/examples/build/EventTester.bin:
--------------------------------------------------------------------------------
1 | 608060405234801561001057600080fd5b5061016c806100206000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806320ea78c214610051578063501064b114610082575b600080fd5b34801561005d57600080fd5b5061008060048036038101908080356000191690602001909291905050506100b3565b005b34801561008e57600080fd5b506100b160048036038101908080356000191690602001909291905050506100f5565b005b8060001916602e7f19b371547290015adfae6dcaca963a36dc2d8e4e9e55ce823b829d747efde90f602a6040518082815260200191505060405180910390a350565b7f906950f44e189193819a60a8ce35a53a0aee725af98bc984839c89d8fa2e09dd602a826040518083815260200182600019166000191681526020019250505060405180910390a1505600a165627a7a72305820d27e753e48c6f5af0acc5f744c8d6c3626f9c09ee5d676abb371e596446cca7d0029
--------------------------------------------------------------------------------
/test/examples/build/SimpleStorage.abi:
--------------------------------------------------------------------------------
1 | [{"constant":false,"inputs":[{"name":"_data","type":"uint256"}],"name":"set","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]
--------------------------------------------------------------------------------
/test/examples/build/SimpleStorage.bin:
--------------------------------------------------------------------------------
1 | 608060405234801561001057600080fd5b5060df8061001f6000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b114604e5780636d4ce63c146078575b600080fd5b348015605957600080fd5b5060766004803603810190808035906020019092919050505060a0565b005b348015608357600080fd5b50608a60aa565b6040518082815260200191505060405180910390f35b8060008190555050565b600080549050905600a165627a7a72305820f2f37cc74bbe30fe8ae3f607794a9d1c1f383aecbdd50b87b8767480e245f8e30029
--------------------------------------------------------------------------------
/test/examples/contracts/AddressTester.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.18;
2 |
3 | contract AddressTester {
4 | function get(address a) public pure returns (address) {
5 | return a;
6 | }
7 | }
--------------------------------------------------------------------------------
/test/examples/contracts/ArrayTester.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.18;
2 |
3 | contract ArrayTester {
4 | function dynamicUint(uint[] ints) public pure returns (uint[]) {
5 | return ints;
6 | }
7 |
8 | function staticUint(uint[5] ints) public pure returns (uint[5]) {
9 | return ints;
10 | }
11 | }
--------------------------------------------------------------------------------
/test/examples/contracts/Complex.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.0;
2 |
3 | contract Complex {
4 |
5 | uint foo;
6 | bytes32 foobar;
7 | bool barFoo;
8 |
9 | event Bar(uint foo, address person);
10 | event FooBar(bool fooboo, uint foo, bytes32 foobar);
11 |
12 | constructor(uint _foo, bytes32 _foobar) public {
13 | foo = _foo;
14 | foobar = _foobar;
15 | }
16 |
17 | function getBoth() public view returns (uint, bytes32) {
18 | return (foo, foobar);
19 | }
20 |
21 | function getBarFoo() public view returns (bool) {
22 | return barFoo;
23 | }
24 |
25 | function getFooBar() public view returns (bytes32) {
26 | return foobar;
27 | }
28 |
29 | function getFooBoo(uint _fooboo) public pure returns (uint fooBoo) {
30 | fooBoo = _fooboo + 42;
31 | }
32 |
33 | function getBroAndBroBro() public view returns (uint bro, bytes32 broBro) {
34 | return (foo + 42, foobar);
35 | }
36 |
37 | function setFoo(uint _foo) public {
38 | foo = _foo;
39 | }
40 |
41 | function setFooBar(bytes32 _foobar) public {
42 | foobar = _foobar;
43 | }
44 |
45 | function setBarFoo(bool _barFoo) public {
46 | barFoo = _barFoo;
47 | }
48 |
49 | function() public payable { }
50 |
51 | }
--------------------------------------------------------------------------------
/test/examples/contracts/EventTester.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.18;
2 |
3 | contract EventTester {
4 |
5 | event Simple(uint256 num, bytes32 data);
6 |
7 | event SimpleIndex(uint256 indexed num, bytes32 indexed data, uint256 otherNum);
8 |
9 | function simple(bytes32 data) public {
10 | emit Simple(42, data);
11 | }
12 |
13 | function simpleIndex(bytes32 data) public {
14 | emit SimpleIndex(46, data, 42);
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/test/examples/contracts/SimpleStorage.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.0;
2 |
3 | contract SimpleStorage {
4 | uint data;
5 |
6 | function set(uint _data) public {
7 | data = _data;
8 | }
9 |
10 | function get() public view returns (uint) {
11 | return data;
12 | }
13 | }
--------------------------------------------------------------------------------
/test/exw3/abi_test.exs:
--------------------------------------------------------------------------------
1 | defmodule ExW3.AbiTest do
2 | use ExUnit.Case
3 |
4 | test ".load_abi/1 returns a map keyed by function & event name" do
5 | assert ExW3.Abi.load_abi("test/examples/build/SimpleStorage.abi") == %{
6 | "get" => %{
7 | "constant" => true,
8 | "inputs" => [],
9 | "name" => "get",
10 | "outputs" => [%{"name" => "", "type" => "uint256"}],
11 | "payable" => false,
12 | "stateMutability" => "view",
13 | "type" => "function"
14 | },
15 | "set" => %{
16 | "constant" => false,
17 | "inputs" => [%{"name" => "_data", "type" => "uint256"}],
18 | "name" => "set",
19 | "outputs" => [],
20 | "payable" => false,
21 | "stateMutability" => "nonpayable",
22 | "type" => "function"
23 | }
24 | }
25 | end
26 | end
27 |
--------------------------------------------------------------------------------
/test/exw3/address_test.exs:
--------------------------------------------------------------------------------
1 | defmodule ExW3.AddressTest do
2 | use ExUnit.Case
3 | alias ExW3.Address
4 |
5 | @bytes_address <<25, 154, 209, 226, 223, 37, 243, 29, 135, 172, 137, 205, 225, 158, 82, 44, 130, 62, 90, 166, 30>>
6 | @string_address "199ad1e2df25f31d87ac89cde19e522c823e5aa61e"
7 | @hex_address "0x199ad1e2df25f31d87ac89cde19e522c823e5aa61e"
8 | @checksum_address "0x199ad1E2dF25f31D87AC89cdE19E522c823E5AA61e"
9 |
10 | test ".from_bytes/1 returns an address struct" do
11 | address = Address.from_bytes(@bytes_address)
12 | assert address.bytes == @bytes_address
13 | end
14 |
15 | test ".from_hex/1 returns an address struct with and without the checksum" do
16 | address = Address.from_hex(@hex_address)
17 | assert address.bytes == @bytes_address
18 |
19 | from_checksum_address = Address.from_hex(@checksum_address)
20 | assert from_checksum_address.bytes == @bytes_address
21 | end
22 |
23 | test ".to_bytes/1 returns the bytes of the address struct" do
24 | address = %Address{bytes: @bytes_address}
25 | assert Address.to_bytes(address) == @bytes_address
26 | end
27 |
28 | test ".to_string/1 returns the hex encoded string without a 0x prefix" do
29 | address = %Address{bytes: @bytes_address}
30 | assert Address.to_string(address) == @string_address
31 | end
32 |
33 | test ".to_hex/1 returns the hex encoded string with a 0x prefix" do
34 | address = %Address{bytes: @bytes_address}
35 | assert Address.to_hex(address) == @hex_address
36 | end
37 |
38 | test ".to_checksum/1 returns the hex encoded string with a 0x prefix conforming to EIP-55" do
39 | address = %Address{bytes: @bytes_address}
40 | assert Address.to_checksum(address) == @checksum_address
41 | end
42 |
43 | test ".is_valid_checksum?/1 is true when it conforms to EIP-55" do
44 | assert Address.is_valid_checksum?(@checksum_address) == true
45 | assert Address.is_valid_checksum?(@hex_address) == false
46 | end
47 | end
48 |
--------------------------------------------------------------------------------
/test/exw3/client_test.exs:
--------------------------------------------------------------------------------
1 | defmodule ExW3.ClientTest do
2 | use ExUnit.Case
3 |
4 | test ".call_client/1 calls the JSON-RPC method with an empty list of arguments" do
5 | assert {:ok, hex} = ExW3.Client.call_client(:eth_block_number)
6 | assert "0x" <> _ = hex
7 | end
8 |
9 | test ".call_client/2 calls the JSON-RPC method with the given arguments" do
10 | assert {:ok, accounts} = ExW3.Client.call_client(:eth_accounts)
11 | assert Enum.count(accounts) > 0
12 | assert ["0x" <> _ = account] = accounts
13 |
14 | assert {:ok, balance} = ExW3.Client.call_client(:eth_get_balance, [account])
15 | assert "0x" <> _ = balance
16 | end
17 |
18 | test ".call_client/2 can specifiy a http url with & without params" do
19 | assert {:ok, accounts} =
20 | ExW3.Client.call_client(:eth_accounts, [[url: Ethereumex.Config.rpc_url()]])
21 |
22 | account = Enum.at(accounts, 0)
23 |
24 | assert {:ok, "0x" <> _} =
25 | ExW3.Client.call_client(:eth_get_balance, [
26 | account,
27 | "latest",
28 | [url: Ethereumex.Config.rpc_url()]
29 | ])
30 |
31 | assert ExW3.Client.call_client(:eth_get_balance, [account, "latest", [url: "unsupported"]]) ==
32 | {:error, :invalid_client_type}
33 |
34 | assert ExW3.Client.call_client(:eth_get_balance, [
35 | account,
36 | "latest",
37 | [url: "http://localhost:1234"]
38 | ]) ==
39 | {:error, :econnrefused}
40 |
41 | assert ExW3.Client.call_client(:eth_get_balance, [
42 | account,
43 | "latest",
44 | [url: "https://localhost:1234"]
45 | ]) ==
46 | {:error, :econnrefused}
47 | end
48 | end
49 |
--------------------------------------------------------------------------------
/test/exw3/contract_test.exs:
--------------------------------------------------------------------------------
1 | defmodule EXW3.ContractTest do
2 | use ExUnit.Case
3 | doctest ExW3.Contract
4 |
5 | @simple_storage_abi ExW3.Abi.load_abi("test/examples/build/SimpleStorage.abi")
6 |
7 | setup_all do
8 | start_supervised!(ExW3.Contract)
9 | :ok
10 | end
11 |
12 | test ".at assigns the address to the state of the registered contract" do
13 | ExW3.Contract.register(:SimpleStorage, abi: @simple_storage_abi)
14 |
15 | assert ExW3.Contract.address(:SimpleStorage) == nil
16 |
17 | accounts = ExW3.accounts()
18 |
19 | {:ok, address, _} =
20 | ExW3.Contract.deploy(
21 | :SimpleStorage,
22 | bin: ExW3.Abi.load_bin("test/examples/build/SimpleStorage.bin"),
23 | args: [],
24 | options: %{
25 | gas: 300_000,
26 | from: Enum.at(accounts, 0)
27 | }
28 | )
29 |
30 | assert ExW3.Contract.at(:SimpleStorage, address) == :ok
31 |
32 | state = :sys.get_state(ContractManager)
33 | contract_state = state[:SimpleStorage]
34 | assert Keyword.get(contract_state, :address) == address
35 | assert Keyword.get(contract_state, :abi) == @simple_storage_abi
36 | end
37 |
38 | test ".address returns the registered address for the contract" do
39 | ExW3.Contract.register(:SimpleStorage, abi: @simple_storage_abi)
40 |
41 | assert ExW3.Contract.address(:SimpleStorage) == nil
42 |
43 | accounts = ExW3.accounts()
44 |
45 | {:ok, address, _} =
46 | ExW3.Contract.deploy(
47 | :SimpleStorage,
48 | bin: ExW3.Abi.load_bin("test/examples/build/SimpleStorage.bin"),
49 | args: [],
50 | options: %{
51 | gas: 300_000,
52 | from: Enum.at(accounts, 0)
53 | }
54 | )
55 |
56 | assert ExW3.Contract.at(:SimpleStorage, address) == :ok
57 | assert ExW3.Contract.address(:SimpleStorage) == address
58 | end
59 | end
60 |
--------------------------------------------------------------------------------
/test/exw3/rpc_test.exs:
--------------------------------------------------------------------------------
1 | defmodule ExW3.RpcTest do
2 | use ExUnit.Case
3 |
4 | describe ".accounts" do
5 | test "returns a list from the eth_accounts JSON-RPC endpoint" do
6 | assert ExW3.accounts() |> is_list
7 | end
8 |
9 | test "can override the http endpoint" do
10 | assert ExW3.accounts(url: Ethereumex.Config.rpc_url()) |> is_list
11 | assert ExW3.accounts(url: "https://localhost:1234") == {:error, :econnrefused}
12 | end
13 | end
14 |
15 | describe ".block_number" do
16 | test "returns the integer block number from the eth_blockNumber JSON-RPC endpoint" do
17 | assert {:ok, bn} = ExW3.block_number()
18 | assert bn |> is_integer
19 | end
20 |
21 | test "can override the http endpoint" do
22 | assert {:ok, _} = ExW3.block_number(url: Ethereumex.Config.rpc_url())
23 | assert ExW3.block_number(url: "https://localhost:1234") == {:error, :econnrefused}
24 | end
25 | end
26 |
27 | describe ".balance" do
28 | test "returns the latest integer balance from the eth_getBalance JSON-RPC endpoint" do
29 | account = ExW3.accounts() |> Enum.at(0)
30 | assert ExW3.balance(account) |> is_integer
31 | end
32 |
33 | test "can override the http endpoint" do
34 | account = ExW3.accounts() |> Enum.at(0)
35 | assert ExW3.balance(account, url: Ethereumex.Config.rpc_url()) |> is_integer
36 | assert ExW3.balance(account, url: "https://localhost:1234") == {:error, :econnrefused}
37 | end
38 | end
39 | end
40 |
--------------------------------------------------------------------------------
/test/exw3/utils_test.exs:
--------------------------------------------------------------------------------
1 | defmodule ExW3.UtilsTest do
2 | use ExUnit.Case
3 | doctest ExW3.Utils
4 |
5 | describe ".hex_to_integer/1" do
6 | test "parses a hex encoded string to an integer" do
7 | assert ExW3.Utils.hex_to_integer("0x1") == {:ok, 1}
8 | assert ExW3.Utils.hex_to_integer("0x2") == {:ok, 2}
9 | assert ExW3.Utils.hex_to_integer("0x2a") == {:ok, 42}
10 | assert ExW3.Utils.hex_to_integer("0x2A") == {:ok, 42}
11 | end
12 |
13 | test "returns an error when the string is not a valid hexidecimal" do
14 | assert ExW3.Utils.hex_to_integer("0x") == {:error, :invalid_hex_string}
15 | assert ExW3.Utils.hex_to_integer("0a") == {:error, :invalid_hex_string}
16 | assert ExW3.Utils.hex_to_integer("0xZ") == {:error, :invalid_hex_string}
17 | end
18 | end
19 |
20 | describe ".integer_to_hex/1" do
21 | test "encodes an integer to hexadecimal" do
22 | assert ExW3.Utils.integer_to_hex(0) == {:ok, "0x0"}
23 | assert ExW3.Utils.integer_to_hex(1) == {:ok, "0x1"}
24 | assert ExW3.Utils.integer_to_hex(42) == {:ok, "0x2A"}
25 | end
26 |
27 | test "returns an error when the integer is negative" do
28 | assert ExW3.Utils.integer_to_hex(-1) == {:error, :negative_integer}
29 | end
30 |
31 | test "returns an error when the value is not an integer" do
32 | assert ExW3.Utils.integer_to_hex(1.1) == {:error, :non_integer}
33 | assert ExW3.Utils.integer_to_hex(nil) == {:error, :non_integer}
34 | end
35 | end
36 |
37 | describe ".keccak256/1" do
38 | test "returns a 0x prepended 32 byte hash of the input" do
39 | hex_hash = ExW3.Utils.keccak256("foo")
40 | assert "0x" <> hash = hex_hash
41 | assert hash == "41b1a0649752af1b28b3dc29a1556eee781e4a4c3a1f7f53f90fa834de098c4d"
42 |
43 | num_bytes = byte_size(hash)
44 | assert trunc(num_bytes / 2) == 32
45 | end
46 | end
47 |
48 | describe ".to_wei/2" do
49 | test "converts a unit to_wei" do
50 | assert ExW3.Utils.to_wei(1, :wei) == 1
51 | assert ExW3.Utils.to_wei(1, :kwei) == 1_000
52 | assert ExW3.Utils.to_wei(1, :Kwei) == 1_000
53 | assert ExW3.Utils.to_wei(1, :babbage) == 1_000
54 | assert ExW3.Utils.to_wei(1, :mwei) == 1_000_000
55 | assert ExW3.Utils.to_wei(1, :Mwei) == 1_000_000
56 | assert ExW3.Utils.to_wei(1, :lovelace) == 1_000_000
57 | assert ExW3.Utils.to_wei(1, :gwei) == 1_000_000_000
58 | assert ExW3.Utils.to_wei(1, :Gwei) == 1_000_000_000
59 | assert ExW3.Utils.to_wei(1, :shannon) == 1_000_000_000
60 | assert ExW3.Utils.to_wei(1, :szabo) == 1_000_000_000_000
61 | assert ExW3.Utils.to_wei(1, :finney) == 1_000_000_000_000_000
62 | assert ExW3.Utils.to_wei(1, :ether) == 1_000_000_000_000_000_000
63 | assert ExW3.Utils.to_wei(1, :kether) == 1_000_000_000_000_000_000_000
64 | assert ExW3.Utils.to_wei(1, :grand) == 1_000_000_000_000_000_000_000
65 | assert ExW3.Utils.to_wei(1, :mether) == 1_000_000_000_000_000_000_000_000
66 | assert ExW3.Utils.to_wei(1, :gether) == 1_000_000_000_000_000_000_000_000_000
67 | assert ExW3.Utils.to_wei(1, :tether) == 1_000_000_000_000_000_000_000_000_000_000
68 |
69 | assert ExW3.Utils.to_wei(1, :kwei) == ExW3.Utils.to_wei(1, :femtoether)
70 | assert ExW3.Utils.to_wei(1, :szabo) == ExW3.Utils.to_wei(1, :microether)
71 | assert ExW3.Utils.to_wei(1, :finney) == ExW3.Utils.to_wei(1, :milliether)
72 | assert ExW3.Utils.to_wei(1, :milli) == ExW3.Utils.to_wei(1, :milliether)
73 | assert ExW3.Utils.to_wei(1, :milli) == ExW3.Utils.to_wei(1000, :micro)
74 |
75 | {:ok, agent} = Agent.start_link(fn -> false end)
76 |
77 | try do
78 | ExW3.Utils.to_wei(1, :wei1)
79 | catch
80 | _ -> Agent.update(agent, fn _ -> true end)
81 | end
82 |
83 | assert Agent.get(agent, fn state -> state end)
84 | end
85 | end
86 |
87 | describe ".from_wei/2" do
88 | test "converts a unit from wei" do
89 | assert ExW3.Utils.from_wei(1_000_000_000_000_000_000, :wei) == 1_000_000_000_000_000_000
90 | assert ExW3.Utils.from_wei(1_000_000_000_000_000_000, :kwei) == 1_000_000_000_000_000
91 | assert ExW3.Utils.from_wei(1_000_000_000_000_000_000, :mwei) == 1_000_000_000_000
92 | assert ExW3.Utils.from_wei(1_000_000_000_000_000_000, :gwei) == 1_000_000_000
93 | assert ExW3.Utils.from_wei(1_000_000_000_000_000_000, :szabo) == 1_000_000
94 | assert ExW3.Utils.from_wei(1_000_000_000_000_000_000, :finney) == 1_000
95 | assert ExW3.Utils.from_wei(1_000_000_000_000_000_000, :ether) == 1
96 | assert ExW3.Utils.from_wei(1_000_000_000_000_000_000, :kether) == 0.001
97 | assert ExW3.Utils.from_wei(1_000_000_000_000_000_000, :grand) == 0.001
98 | assert ExW3.Utils.from_wei(1_000_000_000_000_000_000, :mether) == 0.000001
99 | assert ExW3.Utils.from_wei(1_000_000_000_000_000_000, :gether) == 0.000000001
100 | assert ExW3.Utils.from_wei(1_000_000_000_000_000_000, :tether) == 0.000000000001
101 | end
102 | end
103 |
104 | describe ".to_checksum_address/1" do
105 | test "returns checksum for all caps address" do
106 | assert ExW3.Utils.to_checksum_address(
107 | String.downcase("0x52908400098527886E0F7030069857D2E4169EE7")
108 | ) ==
109 | "0x52908400098527886E0F7030069857D2E4169EE7"
110 |
111 | assert ExW3.Utils.to_checksum_address(
112 | String.downcase("0x8617E340B3D01FA5F11F306F4090FD50E238070D")
113 | ) ==
114 | "0x8617E340B3D01FA5F11F306F4090FD50E238070D"
115 | end
116 |
117 | test "returns checksumfor all lowercase address" do
118 | assert ExW3.Utils.to_checksum_address(
119 | String.downcase("0xde709f2102306220921060314715629080e2fb77")
120 | ) ==
121 | "0xde709f2102306220921060314715629080e2fb77"
122 |
123 | assert ExW3.Utils.to_checksum_address(
124 | String.downcase("0x27b1fdb04752bbc536007a920d24acb045561c26")
125 | ) ==
126 | "0x27b1fdb04752bbc536007a920d24acb045561c26"
127 | end
128 |
129 | test "returns checksum for normal addresses" do
130 | assert ExW3.Utils.to_checksum_address(
131 | String.downcase("0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed")
132 | ) ==
133 | "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed"
134 |
135 | assert ExW3.Utils.to_checksum_address(
136 | String.downcase("0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359")
137 | ) ==
138 | "0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359"
139 |
140 | assert ExW3.Utils.to_checksum_address(
141 | String.downcase("0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB")
142 | ) ==
143 | "0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB"
144 |
145 | assert ExW3.Utils.to_checksum_address(
146 | String.downcase("0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb")
147 | ) ==
148 | "0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb"
149 | end
150 | end
151 |
152 | describe ".is_valid_checksum_address/1" do
153 | test "returns valid check for is_valid_checksum_address()" do
154 | assert ExW3.Utils.is_valid_checksum_address("0x52908400098527886E0F7030069857D2E4169EE7") ==
155 | true
156 |
157 | assert ExW3.Utils.is_valid_checksum_address("0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB") ==
158 | true
159 |
160 | assert ExW3.Utils.is_valid_checksum_address("0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb") ==
161 | true
162 |
163 | assert ExW3.Utils.is_valid_checksum_address("0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed") ==
164 | true
165 |
166 | assert ExW3.Utils.is_valid_checksum_address("0x27b1fdb04752bbc536007a920d24acb045561c26") ==
167 | true
168 |
169 | assert ExW3.Utils.is_valid_checksum_address("0xde709f2102306220921060314715629080e2fb77") ==
170 | true
171 |
172 | assert ExW3.Utils.is_valid_checksum_address("0x8617E340B3D01FA5F11F306F4090FD50E238070D") ==
173 | true
174 |
175 | assert ExW3.Utils.is_valid_checksum_address("0x52908400098527886E0F7030069857D2E4169EE7") ==
176 | true
177 | end
178 |
179 | test "returns invalid check for is_valid_checksum_address()" do
180 | assert ExW3.Utils.is_valid_checksum_address("0x2f015c60e0be116b1f0cd534704db9c92118fb6a") ==
181 | false
182 | end
183 | end
184 | end
185 |
--------------------------------------------------------------------------------
/test/exw3_test.exs:
--------------------------------------------------------------------------------
1 | defmodule ExW3Test do
2 | use ExUnit.Case
3 | doctest ExW3
4 |
5 | setup_all do
6 | start_supervised!(ExW3.Contract)
7 |
8 | %{
9 | simple_storage_abi: ExW3.Abi.load_abi("test/examples/build/SimpleStorage.abi"),
10 | array_tester_abi: ExW3.Abi.load_abi("test/examples/build/ArrayTester.abi"),
11 | event_tester_abi: ExW3.Abi.load_abi("test/examples/build/EventTester.abi"),
12 | complex_abi: ExW3.Abi.load_abi("test/examples/build/Complex.abi"),
13 | address_tester_abi: ExW3.Abi.load_abi("test/examples/build/AddressTester.abi"),
14 | accounts: ExW3.accounts()
15 | }
16 | end
17 |
18 | # Only works with ganache-cli
19 |
20 | # test "mines a block" do
21 | # block_number = ExW3.block_number()
22 | # ExW3.mine()
23 | # assert ExW3.block_number() == block_number + 1
24 | # end
25 |
26 | # test "mines multiple blocks" do
27 | # block_number = ExW3.block_number()
28 | # ExW3.mine(5)
29 | # assert ExW3.block_number() == block_number + 5
30 | # end
31 |
32 | test "starts a Contract GenServer for simple storage contract", context do
33 | ExW3.Contract.register(:SimpleStorage, abi: context[:simple_storage_abi])
34 |
35 | {:ok, address, _} =
36 | ExW3.Contract.deploy(
37 | :SimpleStorage,
38 | bin: ExW3.Abi.load_bin("test/examples/build/SimpleStorage.bin"),
39 | args: [],
40 | options: %{
41 | gas: 300_000,
42 | from: Enum.at(context[:accounts], 0)
43 | }
44 | )
45 |
46 | ExW3.Contract.at(:SimpleStorage, address)
47 |
48 | assert address == ExW3.Contract.address(:SimpleStorage)
49 |
50 | {:ok, data} = ExW3.Contract.call(:SimpleStorage, :get)
51 |
52 | assert data == 0
53 |
54 | ExW3.Contract.send(:SimpleStorage, :set, [1], %{
55 | from: Enum.at(context[:accounts], 0),
56 | gas: 50_000
57 | })
58 |
59 | {:ok, data} = ExW3.Contract.call(:SimpleStorage, :get)
60 |
61 | assert data == 1
62 | end
63 |
64 | test "starts a Contract GenServer for array tester contract", context do
65 | ExW3.Contract.register(:ArrayTester, abi: context[:array_tester_abi])
66 |
67 | {:ok, address, _} =
68 | ExW3.Contract.deploy(
69 | :ArrayTester,
70 | bin: ExW3.Abi.load_bin("test/examples/build/ArrayTester.bin"),
71 | options: %{
72 | gas: 300_000,
73 | from: Enum.at(context[:accounts], 0)
74 | }
75 | )
76 |
77 | ExW3.Contract.at(:ArrayTester, address)
78 |
79 | assert address == ExW3.Contract.address(:ArrayTester)
80 |
81 | arr = [1, 2, 3, 4, 5]
82 |
83 | {:ok, result} = ExW3.Contract.call(:ArrayTester, :staticUint, [arr])
84 |
85 | assert result == arr
86 |
87 | {:ok, result} = ExW3.Contract.call(:ArrayTester, :dynamicUint, [arr])
88 |
89 | assert result == arr
90 | end
91 |
92 | test "starts a Contract GenServer for event tester contract", context do
93 | ExW3.Contract.register(:EventTester, abi: context[:event_tester_abi])
94 |
95 | {:ok, address, _} =
96 | ExW3.Contract.deploy(
97 | :EventTester,
98 | bin: ExW3.Abi.load_bin("test/examples/build/EventTester.bin"),
99 | options: %{
100 | gas: 300_000,
101 | from: Enum.at(context[:accounts], 0)
102 | }
103 | )
104 |
105 | ExW3.Contract.at(:EventTester, address)
106 |
107 | assert address == ExW3.Contract.address(:EventTester)
108 |
109 | {:ok, tx_hash} =
110 | ExW3.Contract.send(:EventTester, :simple, ["Hello, World!"], %{
111 | from: Enum.at(context[:accounts], 0),
112 | gas: 30_000
113 | })
114 |
115 | {:ok, {receipt, logs}} = ExW3.Contract.tx_receipt(:EventTester, tx_hash)
116 |
117 | assert receipt |> is_map
118 |
119 | data =
120 | logs
121 | |> Enum.at(0)
122 | |> Map.get("data")
123 | |> ExW3.Utils.bytes_to_string()
124 |
125 | assert data == "Hello, World!"
126 |
127 | {:ok, tx_hash2} =
128 | ExW3.Contract.send(:EventTester, :simpleIndex, ["Hello, World!"], %{
129 | from: Enum.at(context[:accounts], 0),
130 | gas: 30_000
131 | })
132 |
133 | {:ok, {_receipt, logs}} = ExW3.Contract.tx_receipt(:EventTester, tx_hash2)
134 |
135 | otherNum =
136 | logs
137 | |> Enum.at(0)
138 | |> Map.get("otherNum")
139 |
140 | assert otherNum == 42
141 |
142 | num =
143 | logs
144 | |> Enum.at(0)
145 | |> Map.get("num")
146 |
147 | assert num == 46
148 |
149 | data =
150 | logs
151 | |> Enum.at(0)
152 | |> Map.get("data")
153 | |> ExW3.Utils.bytes_to_string()
154 |
155 | assert data == "Hello, World!"
156 | end
157 |
158 | test "Testing formatted get filter changes", context do
159 | ExW3.Contract.register(:EventTester, abi: context[:event_tester_abi])
160 |
161 | {:ok, address, _} =
162 | ExW3.Contract.deploy(
163 | :EventTester,
164 | bin: ExW3.Abi.load_bin("test/examples/build/EventTester.bin"),
165 | options: %{
166 | gas: 300_000,
167 | from: Enum.at(context[:accounts], 0)
168 | }
169 | )
170 |
171 | ExW3.Contract.at(:EventTester, address)
172 |
173 | # Test non indexed events
174 |
175 | {:ok, filter_id} = ExW3.Contract.filter(:EventTester, "Simple")
176 |
177 | {:ok, _tx_hash} =
178 | ExW3.Contract.send(
179 | :EventTester,
180 | :simple,
181 | ["Hello, World!"],
182 | %{from: Enum.at(context[:accounts], 0), gas: 30_000}
183 | )
184 |
185 | {:ok, change_logs} = ExW3.Contract.get_filter_changes(filter_id)
186 |
187 | event_log = Enum.at(change_logs, 0)
188 |
189 | assert event_log |> is_map
190 | log_data = Map.get(event_log, "data")
191 | assert log_data |> is_map
192 | assert Map.get(log_data, "num") == 42
193 | assert ExW3.Utils.bytes_to_string(Map.get(log_data, "data")) == "Hello, World!"
194 |
195 | ExW3.Contract.uninstall_filter(filter_id)
196 |
197 | # Test indexed events
198 |
199 | {:ok, indexed_filter_id} = ExW3.Contract.filter(:EventTester, "SimpleIndex")
200 |
201 | {:ok, _tx_hash} =
202 | ExW3.Contract.send(
203 | :EventTester,
204 | :simpleIndex,
205 | ["Hello, World!"],
206 | %{from: Enum.at(context[:accounts], 0), gas: 30_000}
207 | )
208 |
209 | {:ok, change_logs} = ExW3.Contract.get_filter_changes(indexed_filter_id)
210 |
211 | event_log = Enum.at(change_logs, 0)
212 |
213 | assert event_log |> is_map
214 | log_data = Map.get(event_log, "data")
215 | assert log_data |> is_map
216 | assert Map.get(log_data, "num") == 46
217 | assert ExW3.Utils.bytes_to_string(Map.get(log_data, "data")) == "Hello, World!"
218 | assert Map.get(log_data, "otherNum") == 42
219 | ExW3.Contract.uninstall_filter(indexed_filter_id)
220 |
221 | # Test Indexing Indexed Events
222 |
223 | {:ok, indexed_filter_id} =
224 | ExW3.Contract.filter(
225 | :EventTester,
226 | "SimpleIndex",
227 | %{
228 | topics: [nil, ["Hello, World", "Hello, World!"]],
229 | fromBlock: 1,
230 | toBlock: "latest"
231 | }
232 | )
233 |
234 | {:ok, _tx_hash} =
235 | ExW3.Contract.send(
236 | :EventTester,
237 | :simpleIndex,
238 | ["Hello, World!"],
239 | %{from: Enum.at(context[:accounts], 0), gas: 30_000}
240 | )
241 |
242 | {:ok, change_logs} = ExW3.Contract.get_filter_changes(indexed_filter_id)
243 |
244 | event_log = Enum.at(change_logs, 0)
245 | assert event_log |> is_map
246 | log_data = Map.get(event_log, "data")
247 | assert log_data |> is_map
248 | assert Map.get(log_data, "num") == 46
249 | assert ExW3.Utils.bytes_to_string(Map.get(log_data, "data")) == "Hello, World!"
250 | assert Map.get(log_data, "otherNum") == 42
251 |
252 | ExW3.Contract.uninstall_filter(indexed_filter_id)
253 |
254 | # Tests filter with map params
255 |
256 | {:ok, indexed_filter_id} =
257 | ExW3.Contract.filter(
258 | :EventTester,
259 | "SimpleIndex",
260 | %{
261 | topics: %{num: 46, data: "Hello, World!"}
262 | }
263 | )
264 |
265 | {:ok, _tx_hash} =
266 | ExW3.Contract.send(
267 | :EventTester,
268 | :simpleIndex,
269 | ["Hello, World!"],
270 | %{from: Enum.at(context[:accounts], 0), gas: 30_000}
271 | )
272 |
273 | # Demonstrating the delay capability
274 | {:ok, change_logs} = ExW3.Contract.get_filter_changes(indexed_filter_id)
275 |
276 | event_log = Enum.at(change_logs, 0)
277 | assert event_log |> is_map
278 | log_data = Map.get(event_log, "data")
279 | assert log_data |> is_map
280 | assert Map.get(log_data, "num") == 46
281 | assert ExW3.Utils.bytes_to_string(Map.get(log_data, "data")) == "Hello, World!"
282 | assert Map.get(log_data, "otherNum") == 42
283 |
284 | ExW3.Contract.uninstall_filter(indexed_filter_id)
285 | end
286 |
287 | test "starts a Contract GenServer for Complex contract", context do
288 | ExW3.Contract.register(:Complex, abi: context[:complex_abi])
289 |
290 | {:ok, address, _} =
291 | ExW3.Contract.deploy(
292 | :Complex,
293 | bin: ExW3.Abi.load_bin("test/examples/build/Complex.bin"),
294 | args: [42, "Hello, world!"],
295 | options: %{
296 | from: Enum.at(context[:accounts], 0),
297 | gas: 300_000
298 | }
299 | )
300 |
301 | ExW3.Contract.at(:Complex, address)
302 |
303 | assert address == ExW3.Contract.address(:Complex)
304 |
305 | {:ok, foo, foobar} = ExW3.Contract.call(:Complex, :getBoth)
306 |
307 | assert foo == 42
308 |
309 | assert ExW3.Utils.bytes_to_string(foobar) == "Hello, world!"
310 | end
311 |
312 | test "starts a Contract GenServer for AddressTester contract", context do
313 | ExW3.Contract.register(:AddressTester, abi: context[:address_tester_abi])
314 |
315 | {:ok, address, _} =
316 | ExW3.Contract.deploy(
317 | :AddressTester,
318 | bin: ExW3.Abi.load_bin("test/examples/build/AddressTester.bin"),
319 | options: %{
320 | from: Enum.at(context[:accounts], 0),
321 | gas: 300_000
322 | }
323 | )
324 |
325 | ExW3.Contract.at(:AddressTester, address)
326 |
327 | assert address == ExW3.Contract.address(:AddressTester)
328 |
329 | formatted_address =
330 | Enum.at(context[:accounts], 0)
331 | |> ExW3.Utils.format_address()
332 |
333 | {:ok, same_address} = ExW3.Contract.call(:AddressTester, :get, [formatted_address])
334 |
335 | assert %ExW3.Address{bytes: same_address} |> ExW3.Address.to_hex() == Enum.at(context[:accounts], 0)
336 | end
337 |
338 | test "returns proper error messages at contract deployment", context do
339 | ExW3.Contract.register(:SimpleStorage, abi: context[:simple_storage_abi])
340 |
341 | assert {:error, :missing_gas} ==
342 | ExW3.Contract.deploy(
343 | :SimpleStorage,
344 | bin: ExW3.Abi.load_bin("test/examples/build/SimpleStorage.bin"),
345 | args: [],
346 | options: %{
347 | from: Enum.at(context[:accounts], 0)
348 | }
349 | )
350 |
351 | assert {:error, :missing_sender} ==
352 | ExW3.Contract.deploy(
353 | :SimpleStorage,
354 | bin: ExW3.Abi.load_bin("test/examples/build/SimpleStorage.bin"),
355 | args: [],
356 | options: %{
357 | gas: 300_000
358 | }
359 | )
360 |
361 | assert {:error, :missing_binary} ==
362 | ExW3.Contract.deploy(
363 | :SimpleStorage,
364 | args: [],
365 | options: %{
366 | gas: 300_000,
367 | from: Enum.at(context[:accounts], 0)
368 | }
369 | )
370 | end
371 |
372 | test "return proper error messages at send and call", context do
373 | ExW3.Contract.register(:SimpleStorage, abi: context[:simple_storage_abi])
374 |
375 | {:ok, address, _} =
376 | ExW3.Contract.deploy(
377 | :SimpleStorage,
378 | bin: ExW3.Abi.load_bin("test/examples/build/SimpleStorage.bin"),
379 | args: [],
380 | options: %{
381 | gas: 300_000,
382 | from: Enum.at(context[:accounts], 0)
383 | }
384 | )
385 |
386 | assert {:error, :missing_address} == ExW3.Contract.call(:SimpleStorage, :get)
387 |
388 | assert {:error, :missing_address} ==
389 | ExW3.Contract.send(:SimpleStorage, :set, [1], %{
390 | from: Enum.at(context[:accounts], 0),
391 | gas: 50_000
392 | })
393 |
394 | ExW3.Contract.at(:SimpleStorage, address)
395 |
396 | assert {:error, :missing_sender} ==
397 | ExW3.Contract.send(:SimpleStorage, :set, [1], %{gas: 50_000})
398 |
399 | assert {:error, :missing_gas} ==
400 | ExW3.Contract.send(:SimpleStorage, :set, [1], %{from: Enum.at(context[:accounts], 0)})
401 | end
402 |
403 | test ".get_logs/1", context do
404 | ExW3.Contract.register(:EventTester, abi: context[:event_tester_abi])
405 |
406 | {:ok, address, _} =
407 | ExW3.Contract.deploy(
408 | :EventTester,
409 | bin: ExW3.Abi.load_bin("test/examples/build/EventTester.bin"),
410 | options: %{
411 | gas: 300_000,
412 | from: Enum.at(context[:accounts], 0)
413 | }
414 | )
415 |
416 | ExW3.Contract.at(:EventTester, address)
417 |
418 | {:ok, current_block} = ExW3.block_number()
419 | {:ok, from_block} = ExW3.Utils.integer_to_hex(current_block)
420 |
421 | {:ok, simple_tx_hash} =
422 | ExW3.Contract.send(:EventTester, :simple, ["Hello, World!"], %{
423 | from: Enum.at(context[:accounts], 0),
424 | gas: 30_000
425 | })
426 |
427 | {:ok, _} =
428 | ExW3.Contract.send(:EventTester, :simpleIndex, ["Hello, World!"], %{
429 | from: Enum.at(context[:accounts], 0),
430 | gas: 30_000
431 | })
432 |
433 | filter = %{
434 | fromBlock: from_block,
435 | toBlock: "latest",
436 | topics: [ExW3.Utils.keccak256("Simple(uint256,bytes32)")]
437 | }
438 |
439 | assert {:ok, logs} = ExW3.get_logs(filter)
440 | assert Enum.count(logs) == 1
441 |
442 | log = Enum.at(logs, 0)
443 | assert log["transactionHash"] == simple_tx_hash
444 | end
445 | end
446 |
--------------------------------------------------------------------------------
/test/test_helper.exs:
--------------------------------------------------------------------------------
1 | ExUnit.start()
2 |
--------------------------------------------------------------------------------