### Application.start/2 Source: https://hexdocs.pm/ethereumex/Ethereumex.Application.html Callback implementation for starting the Ethereumex OTP application. ```APIDOC ## start(type, args) ### Description Callback implementation for `Application.start/2` used to configure and start the :ethereumex OTP application. ### Parameters - **type** (term) - Required - The start type. - **args** (term) - Required - The arguments passed to the application. ``` -------------------------------- ### eth_call Example - Smart Contract Interaction Source: https://hexdocs.pm/ethereumex/readme.html Detailed example of how to use `eth_call` to interact with smart contracts, including ABI encoding. ```APIDOC ## eth_call Example - Read only smart contract calls To call a smart contract using the JSON-RPC interface, you need to properly encode the `data` attribute, which includes the contract method signature and arguments. ### Dependencies Ensure you have the `ethereumex` and `ex_abi` libraries in your project: ```elixir defp deps do [ ..., {:ethereumex, "~> 0.9"}, {:ex_abi, "~> 0.5"} ... ] end ``` ### Encoding Contract Calls Load the ABI and encode the method call. The address needs to be converted to bytes. ```elixir # Example ABI encoding for a balanceOf(address) function address = "0x407d73d8a49eeb85d32cf465507dd71d507100c1" |> String.slice(2..-1) |> Base.decode16!(case: :mixed) contract_address = "0xC28980830dD8b9c68a45384f5489ccdAF19D53cC" abi_encoded_data = ABI.encode("balanceOf(address)", [address]) |> Base.encode16(case: :lower) ``` ### Executing `eth_call` Use `eth_call` with the encoded data and target contract address. ```elixir balance_bytes = Ethereumex.HttpClient.eth_call(%{ data: "0x" <> abi_encoded_data, to: contract_address }) ``` ### Decoding the Result Convert the returned balance (in bytes) into a readable integer. ```elixir balance_bytes |> String.slice(2..-1) |> Base.decode16!(case: :lower) |> TypeDecoder.decode_raw([{:uint, 256}]) |> List.first ``` ``` -------------------------------- ### Run Parity for Testing Source: https://hexdocs.pm/ethereumex/readme.html Start the Parity client to be used during testing. ```bash $ make run ``` -------------------------------- ### Setup Parity for Testing Source: https://hexdocs.pm/ethereumex/readme.html Download and initialize the password file for Parity before running tests. ```bash $ make setup ``` -------------------------------- ### Start WebSocket Connection Source: https://hexdocs.pm/ethereumex/Ethereumex.WebsocketServer.html Starts the WebSocket connection using `start_link/1`. Accepts a keyword list of options for configuration, such as the WebSocket endpoint URL and process name. ```elixir @spec start_link(keyword()) :: {:ok, pid()} | {:error, term()} ``` -------------------------------- ### Smart Contract Calls with eth_call Source: https://hexdocs.pm/ethereumex/Ethereumex.html Detailed example of how to perform read-only smart contract calls using `eth_call`, including ABI encoding and data formatting. ```APIDOC ## Smart Contract Calls with `eth_call` This section details how to execute read-only smart contract calls using the `eth_call` JSON-RPC method. ### Prerequisites Ensure you have the `ethereumex` and `ex_abi` libraries added to your project dependencies: ```elixir defp deps do [ {:ethereumex, "~> 0.9"}, {:ex_abi, "~> 0.5"} ] end ``` ### Encoding Contract Calls To call a smart contract method, you need to properly encode the method signature and arguments. This often involves using the `ABI` module. **Example:** ```elixir # Address needs to be decoded from hex address = "0x407d73d8a49eeb85d32cf465507dd71d507100c1" |> String.slice(2..-1) |> Base.decode16!(case: :mixed) contract_address = "0xC28980830dD8b9c68a45384f5489ccdAF19D53cC" # Encode the function call (e.g., balanceOf(address)) abi_encoded_data = ABI.encode("balanceOf(address)", [address]) |> Base.encode16(case: :lower) # Execute the call using eth_call balance_bytes = Ethereumex.HttpClient.eth_call(%{ data: "0x" <> abi_encoded_data, to: contract_address }) # Decode the result (e.g., uint256) balance_bytes |> String.slice(2..-1) |> Base.decode16!(case: :lower) |> TypeDecoder.decode_raw([{:uint, 256}]) |> List.first ``` ``` -------------------------------- ### Standard Ethereum JSON-RPC Methods Source: https://hexdocs.pm/ethereumex/Ethereumex.html A comprehensive list of standard Ethereum JSON-RPC methods supported by Ethereumex, including web3, net, and eth modules. Examples demonstrate basic usage. ```APIDOC ## Standard Ethereum JSON-RPC Methods This section lists the available standard Ethereum JSON-RPC methods. ### Available Methods * `web3_clientVersion` * `web3_sha3` * `net_version` * `net_peerCount` * `net_listening` * `eth_protocolVersion` * `eth_syncing` * `eth_coinbase` * `eth_chainId` * `eth_mining` * `eth_hashrate` * `eth_gasPrice` * `eth_accounts` * `eth_blockNumber` * `eth_getBalance` * `eth_getStorageAt` * `eth_getTransactionCount` * `eth_getBlockTransactionCountByHash` * `eth_getBlockTransactionCountByNumber` * `eth_getUncleCountByBlockHash` * `eth_getUncleCountByBlockNumber` * `eth_getCode` * `eth_sign` * `eth_sendTransaction` * `eth_sendRawTransaction` * `eth_call` * `eth_estimateGas` * `eth_getBlockByHash` * `eth_getBlockByNumber` * `eth_getTransactionByHash` * `eth_getTransactionByBlockHashAndIndex` * `eth_getTransactionByBlockNumberAndIndex` * `eth_getTransactionReceipt` * `eth_getUncleByBlockHashAndIndex` * `eth_getUncleByBlockNumberAndIndex` * `eth_getCompilers` * `eth_compileLLL` * `eth_compileSolidity` * `eth_compileSerpent` * `eth_newFilter` * `eth_newBlockFilter` * `eth_newPendingTransactionFilter` * `eth_uninstallFilter` * `eth_getFilterChanges` * `eth_getFilterLogs` * `eth_getLogs` * `eth_getProof` * `eth_getWork` * `eth_submitWork` * `eth_submitHashrate` * `db_putString` * `db_getString` * `db_putHex` * `db_getHex` * `shh_post` * `shh_version` * `shh_newIdentity` * `shh_hasIdentity` * `shh_newGroup` * `shh_addToGroup` * `shh_newFilter` * `shh_uninstallFilter` * `shh_getFilterChanges` * `shh_getMessages` ### Examples ```iex # Get the client version Ethereumex.HttpClient.web3_client_version() # => {:ok, "Parity//v1.7.2-beta-9f47909-20170918/x86_64-macos/rustc1.19.0"} # Specify a custom URL Ethereumex.HttpClient.web3_client_version(url: "http://localhost:8545") # => {:ok, "Parity//v1.7.2-beta-9f47909-20170918/x86_64-macos/rustc1.19.0"} # Example of an invalid parameter Ethereumex.HttpClient.web3_sha3("wrong_param") # => {:error, %{"code" => -32602, "message" => "Invalid params: invalid format."}} # Get the balance of an Ethereum address Ethereumex.HttpClient.eth_get_balance("0x407d73d8a49eeb85d32cf465507dd71d507100c1") # => {:ok, "0x0"} ``` **Note:** All method names are converted to snake_case. For example, `shh_getMessages` corresponds to `Ethereumex.HttpClient.shh_get_messages/1`. ``` -------------------------------- ### Subscribe to Events Specification Source: https://hexdocs.pm/ethereumex/Ethereumex.WebsocketClient.html Function specification and examples for subscribing to Ethereum events. ```elixir @spec subscribe(Ethereumex.WebsocketServer.event_type(), map() | nil) :: {:ok, String.t()} | {:error, term()} # Subscribe to new blocks iex> subscribe(:newHeads) {:ok, "0x9cef478923ff08bf67fde6c64013158d"} # Subscribe to specific logs iex> subscribe(:logs, %{address: "0x8320fe7702b96808f7bbc0d4a888ed1468216cfd"}) {:ok, "0x4a8a4c0517381924f9838102c5a4dcb7"} ``` -------------------------------- ### Logs Notification Format Source: https://hexdocs.pm/ethereumex/Ethereumex.WebsocketServer.html Example structure of a notification message received for log events. This includes the subscription ID and the log details. ```json # Logs notification %{ "jsonrpc" => "2.0", "method" => "eth_subscription", "params" => %{ "subscription" => "0x4a8a4c0517381924f9838102c5a4dcb7", "result" => %{ "address" => "0x8320fe7702b96808f7bbc0d4a888ed1468216cfd", "topics" => ["0xd78a0cb8bb633d06981248b816e7bd33c2a35a6089241d099fa519e361cab902"], "data" => "0x000000000000000000000000000000000000000000000000000000000000000a" } } } ``` -------------------------------- ### New Headers Notification Format Source: https://hexdocs.pm/ethereumex/Ethereumex.WebsocketServer.html Example structure of a notification message received when a new block header event occurs. This message is automatically forwarded to the subscriber process. ```json # New headers notification %{ "jsonrpc" => "2.0", "method" => "eth_subscription", "params" => %{ "subscription" => "0x9cef478923ff08bf67fde6c64013158d", "result" => %{ "number" => "0x1b4", "hash" => "0x8216c5785ac562ff41e2dcfdf5785ac562ff41e2dcfdf829c5a142f1fccd7d", "parentHash" => "0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5" } } } ``` -------------------------------- ### Unsubscribe from Events Specification Source: https://hexdocs.pm/ethereumex/Ethereumex.WebsocketClient.html Function specification and examples for unsubscribing from event subscriptions. ```elixir @spec unsubscribe(String.t() | [String.t()]) :: {:ok, boolean()} | {:error, term()} # Unsubscribe from a single subscription iex> unsubscribe("0x9cef478923ff08bf67fde6c64013158d") {:ok, true} # Unsubscribe from multiple subscriptions at once iex> unsubscribe(["0x9cef478923ff08bf67fde6c64013158d", "0x4a8a4c0517381924f9838102c5a4dcb7"]) {:ok, true} ``` -------------------------------- ### Run development tasks Source: https://hexdocs.pm/ethereumex/index.html Commands for setting up and testing the project environment. ```bash $ make setup ``` ```bash $ make run ``` ```bash $ make test ``` -------------------------------- ### Run Project Tests Source: https://hexdocs.pm/ethereumex/readme.html Execute the project's test suite. ```bash $ make test ``` -------------------------------- ### Configure Dependencies for Smart Contract Interaction Source: https://hexdocs.pm/ethereumex/index.html Add ethereumex and ex_abi to your mix.exs file to enable ABI encoding for smart contract calls. ```elixir defp deps do [ ... {:ethereumex, "~> 0.9"}, {:ex_abi, "~> 0.5"} ... ] end ``` -------------------------------- ### Execute Basic JSON-RPC Requests Source: https://hexdocs.pm/ethereumex/index.html Demonstrates standard client calls, including configuration overrides and error handling. ```elixir iex> Ethereumex.HttpClient.web3_client_version {:ok, "Parity//v1.7.2-beta-9f47909-20170918/x86_64-macos/rustc1.19.0"} # Using the url option will overwrite the configuration iex> Ethereumex.HttpClient.web3_client_version(url: "http://localhost:8545") {:ok, "Parity//v1.7.2-beta-9f47909-20170918/x86_64-macos/rustc1.19.0"} iex> Ethereumex.HttpClient.web3_sha3("wrong_param") {:error, %{"code" => -32602, "message" => "Invalid params: invalid format."}} iex> Ethereumex.HttpClient.eth_get_balance("0x407d73d8a49eeb85d32cf465507dd71d507100c1") {:ok, "0x0"} ``` -------------------------------- ### Add Ethereumex dependency Source: https://hexdocs.pm/ethereumex/index.html Include the library and a JSON encoder in your mix.exs file. ```elixir def deps do [ {:ethereumex, "~> 0.14.0"}, # json library is configurable {:jason, "~> 1.4"} ] end ``` -------------------------------- ### IPC Client Usage Source: https://hexdocs.pm/ethereumex/Ethereumex.html Instructions on how to use the IpcClient for interacting with the Ethereum node via Inter-Process Communication. ```APIDOC ## IPC Client Usage To use the IPC client, replace `HttpClient` with `IpcClient` in your examples. **Example:** ```iex # Assuming IpcClient is configured # Ethereumex.IpcClient.web3_client_version() ``` ``` -------------------------------- ### Standard JSON-RPC Methods Source: https://hexdocs.pm/ethereumex/index.html Overview of available JSON-RPC methods provided by the Ethereumex client, including web3, net, eth, db, and shh namespaces. ```APIDOC ## JSON-RPC Methods ### Description Ethereumex supports a wide range of standard Ethereum JSON-RPC methods. All methods are accessed via `Ethereumex.HttpClient` or `Ethereumex.IpcClient` using snake_case naming conventions (e.g., `eth_getBalance` becomes `eth_get_balance/1`). ### Available Namespaces - **web3**: `web3_clientVersion`, `web3_sha3` - **net**: `net_version`, `net_peerCount`, `net_listening` - **eth**: `eth_protocolVersion`, `eth_syncing`, `eth_coinbase`, `eth_chainId`, `eth_gasPrice`, `eth_accounts`, `eth_blockNumber`, `eth_getBalance`, `eth_call`, `eth_sendTransaction`, etc. - **db**: `db_putString`, `db_getString`, `db_putHex`, `db_getHex` - **shh**: `shh_post`, `shh_version`, `shh_newIdentity`, etc. ### Request Example ```elixir # Get balance of an address Ethereumex.HttpClient.eth_get_balance("0x407d73d8a49eeb85d32cf465507dd71d507100c1") ``` ### Response Example ```elixir {:ok, "0x0"} ``` ``` -------------------------------- ### Configure Ethereumex HTTP URL Source: https://hexdocs.pm/ethereumex/readme.html Set the Ethereum JSON-RPC host URL in your `config/config.exs` file for HTTP connections. ```elixir config :ethereumex, url: "http://localhost:8545" ``` -------------------------------- ### Standard Ethereum JSON-RPC Methods Source: https://hexdocs.pm/ethereumex/readme.html A comprehensive list of standard Ethereum JSON-RPC methods supported by Ethereumex, including web3, net, and eth modules. ```APIDOC ## Standard Ethereum JSON-RPC Methods This section lists the available standard Ethereum JSON-RPC methods that can be called using the Ethereumex client. ### Available Methods * `web3_clientVersion` * `web3_sha3` * `net_version` * `net_peerCount` * `net_listening` * `eth_protocolVersion` * `eth_syncing` * `eth_coinbase` * `eth_chainId` * `eth_mining` * `eth_hashrate` * `eth_gasPrice` * `eth_accounts` * `eth_blockNumber` * `eth_getBalance` * `eth_getStorageAt` * `eth_getTransactionCount` * `eth_getBlockTransactionCountByHash` * `eth_getBlockTransactionCountByNumber` * `eth_getUncleCountByBlockHash` * `eth_getUncleCountByBlockNumber` * `eth_getCode` * `eth_sign` * `eth_sendTransaction` * `eth_sendRawTransaction` * `eth_call` * `eth_estimateGas` * `eth_getBlockByHash` * `eth_getBlockByNumber` * `eth_getTransactionByHash` * `eth_getTransactionByBlockHashAndIndex` * `eth_getTransactionByBlockNumberAndIndex` * `eth_getTransactionReceipt` * `eth_getUncleByBlockHashAndIndex` * `eth_getUncleByBlockNumberAndIndex` * `eth_getCompilers` * `eth_compileLLL` * `eth_compileSolidity` * `eth_compileSerpent` * `eth_newFilter` * `eth_newBlockFilter` * `eth_newPendingTransactionFilter` * `eth_uninstallFilter` * `eth_getFilterChanges` * `eth_getFilterLogs` * `eth_getLogs` * `eth_getProof` * `eth_getWork` * `eth_submitWork` * `eth_submitHashrate` * `db_putString` * `db_getString` * `db_putHex` * `db_getHex` * `shh_post` * `shh_version` * `shh_newIdentity` * `shh_hasIdentity` * `shh_newGroup` * `shh_addToGroup` * `shh_newFilter` * `shh_uninstallFilter` * `shh_getFilterChanges` * `shh_getMessages` ### Examples ```elixir # Get the client version Ethereumex.HttpClient.web3_client_version() # => {:ok, "Parity//v1.7.2-beta-9f47909-20170918/x86_64-macos/rustc1.19.0"} # Using a specific URL Ethereumex.HttpClient.web3_client_version(url: "http://localhost:8545") # => {:ok, "Parity//v1.7.2-beta-9f47909-20170918/x86_64-macos/rustc1.19.0"} # Example of an invalid parameter Ethereumex.HttpClient.web3_sha3("wrong_param") # => {:error, %{"code" => -32602, "message" => "Invalid params: invalid format."}} # Get the balance of an Ethereum address Ethereumex.HttpClient.eth_get_balance("0x407d73d8a49eeb85d32cf465507dd71d507100c1") # => {:ok, "0x0"} ``` **Note:** Method names in the `Ethereumex` library are in snake_case. For example, `shh_getMessages` corresponds to `Ethereumex.HttpClient.shh_get_messages/1`. ``` -------------------------------- ### Custom and Batch Requests Source: https://hexdocs.pm/ethereumex/index.html How to execute non-standard JSON-RPC methods and perform batch requests for efficiency. ```APIDOC ## Custom and Batch Requests ### Custom Requests Use `Ethereumex.HttpClient.request/3` to call methods not explicitly defined in the library (e.g., parity-specific methods). ### Batch Requests Use `Ethereumex.HttpClient.batch_request/1` to send multiple JSON-RPC calls in a single request. ### Request Example (Custom) ```elixir Ethereumex.HttpClient.request("personal_listAccounts", [], []) ``` ### Request Example (Batch) ```elixir requests = [ {:web3_client_version, []}, {:net_version, []} ] Ethereumex.HttpClient.batch_request(requests) ``` ``` -------------------------------- ### Batch Requests Source: https://hexdocs.pm/ethereumex/Ethereumex.html Demonstrates how to send multiple JSON-RPC requests simultaneously using `batch_request/1` or `batch_request/2`. ```APIDOC ## Batch Requests Send multiple JSON-RPC requests in a single call using `Ethereumex.HttpClient.batch_request/1` or `Ethereumex.HttpClient.batch_request/2`. ### Example: ```iex requests = [ {:web3_client_version, []}, {:net_version, []}, {:web3_sha3, ["0x68656c6c6f20776f726c64"]} ] Ethereumex.HttpClient.batch_request(requests) # => { # :ok, # [ # {:ok, "Parity//v1.7.2-beta-9f47909-20170918/x86_64-macos/rustc1.19.0"}, # {:ok, "42"}, # {:ok, "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad"} # ] # } ``` ``` -------------------------------- ### Prepare Smart Contract Call Data Source: https://hexdocs.pm/ethereumex/index.html Encode contract method signatures and arguments using the ABI package before executing a call. ```elixir address = "0xF742d4cE7713c54dD701AA9e92101aC42D63F895" |> String.slice(2..-1) |> Base.decode16!(case: :mixed) contract_address = "0xC28980830dD8b9c68a45384f5489ccdAF19D53cC" abi_encoded_data = ABI.encode("balanceOf(address)", [address]) |> Base.encode16(case: :lower) ``` -------------------------------- ### Configure Ethereumex IPC Client Source: https://hexdocs.pm/ethereumex/readme.html Set the client type to :ipc and specify the IPC socket path in `config/config.exs` to use Inter-Process Communication. ```elixir config :ethereumex, client_type: :ipc ``` ```elixir config :ethereumex, ipc_path: "/path/to/ipc" ``` -------------------------------- ### Configure HTTP Request Options Source: https://hexdocs.pm/ethereumex/readme.html Customize HTTP request timeouts and headers in `config/config.exs`. These can be overridden in client calls. ```elixir config :ethereumex, http_options: [pool_timeout: 5000, receive_timeout: 15_000], http_headers: [{"Content-Type", "application/json"}] ``` -------------------------------- ### Subscribe to New Block Headers Source: https://hexdocs.pm/ethereumex/Ethereumex.WebsocketServer.html Initiate a subscription to receive real-time notifications for new block headers. The `subscribe/1` function returns a subscription ID upon success. ```elixir # Subscribe to new block headers {:ok, subscription_id} = WebsocketServer.subscribe(%{ jsonrpc: "2.0", method: "eth_subscribe", params: ["newHeads"], id: 1 }) ``` -------------------------------- ### Ethereumex.Client.BaseClient Source: https://hexdocs.pm/ethereumex/api-reference.html The Base Client module provides the core functionality for executing Ethereum JSON-RPC requests. ```APIDOC ## Ethereumex.Client.BaseClient ### Description The Base Client exposes the Ethereum Client RPC functionality, allowing users to interact with Ethereum nodes via standard JSON-RPC methods. ### Method Various (JSON-RPC over HTTP) ### Endpoint Configured via Ethereumex application settings ``` -------------------------------- ### Ethereumex.Client.BaseClient Source: https://hexdocs.pm/ethereumex/Ethereumex.Client.BaseClient.html The Base Client exposes the Ethereum Client RPC functionality. It uses a macro to allow exposed functions to be used in different behaviors (HTTP or IPC). ```APIDOC ## Ethereumex.Client.BaseClient ### Description The Base Client exposes the Ethereum Client RPC functionality. We use a macro so that exposed functions can be used in different behaviours (HTTP or IPC). ### Method N/A (This is a client class, not a specific endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Ethereumex.Counter Functions Source: https://hexdocs.pm/ethereumex/Ethereumex.Counter.html This section details the available functions for the Ethereumex.Counter module. ```APIDOC ## Ethereumex.Counter API ### Description An application-wide RPC2Ethereum client request counter. ### Functions #### get(key) ##### Description Retrieves the current count for a given key. ##### Method GET (conceptual) ##### Endpoint N/A (Local function call) ##### Parameters ###### Path Parameters - **key** (atom) - Required - The key to retrieve the count for. ##### Response ###### Success Response (200) - **count** (integer) - The current count for the specified key. #### increment(key, method) ##### Description Increments the count for a given key by one. ##### Method POST (conceptual) ##### Endpoint N/A (Local function call) ##### Parameters ###### Path Parameters - **key** (atom) - Required - The key to increment the count for. - **method** (String.t()) - Required - The method associated with the increment. ##### Response ###### Success Response (200) - **new_count** (integer) - The new count after incrementing. #### increment(key, count, method) ##### Description Increments the count for a given key by a specified amount. ##### Method POST (conceptual) ##### Endpoint N/A (Local function call) ##### Parameters ###### Path Parameters - **key** (atom) - Required - The key to increment the count for. - **count** (integer) - Required - The amount to increment the count by. - **method** (String.t()) - Required - The method associated with the increment. ##### Response ###### Success Response (200) - **new_count** (integer) - The new count after incrementing. #### setup() ##### Description Initializes the counter. ##### Method PUT (conceptual) ##### Endpoint N/A (Local function call) ##### Response ###### Success Response (200) - **status** (:ok) - Indicates successful setup. ``` -------------------------------- ### WebSocket Subscription Methods Source: https://hexdocs.pm/ethereumex/Ethereumex.html Methods for subscribing to and unsubscribing from real-time Ethereum events via WebSockets. ```APIDOC ## WebSocket Subscription Methods These methods allow for real-time event subscriptions. ### `eth_subscribe` **Description:** Subscribe to real-time events. ### `eth_unsubscribe` **Description:** Unsubscribe from events. ``` -------------------------------- ### Configure custom JSON library Source: https://hexdocs.pm/ethereumex/index.html Override the default JSON library with a custom module. ```elixir config :ethereumex, json_module: MyCustomJson ``` -------------------------------- ### Ethereumex.WebsocketClient Source: https://hexdocs.pm/ethereumex/api-reference.html WebSocket-based client implementation for real-time Ethereum blockchain interactions. ```APIDOC ## Ethereumex.WebsocketClient ### Description WebSocket-based Ethereum JSON-RPC client implementation with real-time subscription support. ### Method WebSocket (WSS/WS) ### Endpoint Configured via Ethereumex application settings ``` -------------------------------- ### Batch Requests Source: https://hexdocs.pm/ethereumex/readme.html How to send multiple JSON-RPC requests in a single batch to improve efficiency. ```APIDOC ## Batch Requests To send multiple requests in a single batch, use the `Ethereumex.HttpClient.batch_request/1` or `Ethereumex.HttpClient.batch_request/2` methods. ### Parameters * **requests** (list of tuples) - Required - A list where each element is a tuple of `{method_name, [params]}`. * **options** (keyword) - Optional - Additional options, such as `url`. ### Request Example ```elixir requests = [ {:web3_client_version, []}, {:net_version, []}, {:web3_sha3, ["0x68656c6c6f20776f726c64"]} ] Ethereumex.HttpClient.batch_request(requests) # => { # :ok, # [ # {:ok, "Parity//v1.7.2-beta-9f47909-20170918/x86_64-macos/rustc1.19.0"}, # {:ok, "42"}, # {:ok, "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad"} # ] # } ``` ``` -------------------------------- ### Manage real-time subscriptions Source: https://hexdocs.pm/ethereumex/index.html Subscribe to blockchain events and handle notifications in your process. ```elixir # Subscribe to new block headers iex> {:ok, subscription_id} = Ethereumex.WebsocketClient.subscribe(:newHeads) {:ok, "0x9cef478923ff08bf67fde6c64013158d"} # Subscribe to logs/events from specific contracts iex> filter = %{ ...> address: "0x8320fe7702b96808f7bbc0d4a888ed1468216cfd", ...> topics: ["0xd78a0cb8bb633d06981248b816e7bd33c2a35a6089241d099fa519e361cab902"] ...> } iex> {:ok, subscription_id} = Ethereumex.WebsocketClient.subscribe(:logs, filter) {:ok, "0x4a8a4c0517381924f9838102c5a4dcb7"} # Subscribe to pending transactions iex> {:ok, subscription_id} = Ethereumex.WebsocketClient.subscribe(:newPendingTransactions) {:ok, "0x1234567890abcdef1234567890abcdef"} # Receive notifications in your process receive do %{ "method" => "eth_subscription", "params" => %{ "subscription" => subscription_id, "result" => result } } -> handle_notification(result) end # Unsubscribe when done iex> Ethereumex.WebsocketClient.unsubscribe(subscription_id) {:ok, true} ``` -------------------------------- ### Custom JSON-RPC Requests Source: https://hexdocs.pm/ethereumex/readme.html How to make custom JSON-RPC requests to Ethereum nodes that support non-standard methods. ```APIDOC ## Custom Requests Many Ethereum implementations support additional JSON-RPC API methods beyond the standard. You can use the `Ethereumex.HttpClient.request/3` method to call these custom methods. ### Parameters * **method** (string) - Required - The name of the custom JSON-RPC method. * **params** (list) - Required - A list of parameters for the method. * **options** (keyword) - Optional - Additional options, such as `url`. ### Request Example ```elixir # Example: Calling parity's personal_listAccounts method Ethereumex.HttpClient.request("personal_listAccounts", [], []) # => {:ok, # ["0x71cf0b576a95c347078ec2339303d13024a26910", # "0x7c12323a4fff6df1a25d38319d5692982f48ec2e"]} ``` ``` -------------------------------- ### Format Batch Requests Source: https://hexdocs.pm/ethereumex/Ethereumex.WebsocketClient.html Specification for formatting batch requests. ```elixir @spec format_batch([map()]) :: [ok: map() | nil | binary(), error: any()] ``` -------------------------------- ### Execute Batch JSON-RPC Requests Source: https://hexdocs.pm/ethereumex/index.html Send multiple requests in a single batch to reduce network overhead. ```elixir requests = [ {:web3_client_version, []}, {:net_version, []}, {:web3_sha3, ["0x68656c6c6f20776f726c64"]} ] Ethereumex.HttpClient.batch_request(requests) { :ok, [ {:ok, "Parity//v1.7.2-beta-9f47909-20170918/x86_64-macos/rustc1.19.0"}, {:ok, "42"}, {:ok, "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad"} ] } ``` -------------------------------- ### Ethereumex.WebsocketServer Source: https://hexdocs.pm/ethereumex/Ethereumex.WebsocketServer.html Manages a persistent WebSocket connection to an Ethereum node, handling JSON-RPC calls and subscriptions. ```APIDOC ## Ethereumex.WebsocketServer ### Description WebSocket client implementation for Ethereum JSON-RPC API. This module manages a persistent WebSocket connection to an Ethereum node and handles the complete request-response cycle for JSON-RPC calls, including subscriptions. It maintains state of ongoing requests, subscriptions, and matches responses to their original callers. ### Features * Standard JSON-RPC requests via WebSocket * Real-time event subscriptions (newHeads, logs, newPendingTransactions) * Automatic reconnection with exponential backoff * Batch request support * Concurrent request handling ## Standard Requests ### POST /api/jsonrpc ### Description Sends a standard JSON-RPC request over the WebSocket connection and waits for a response. ### Method POST ### Endpoint (Implicitly handled by the `post/1` function) ### Parameters #### Request Body - **encoded_request** (binary) - Required - The JSON-RPC request payload as a binary string. ### Request Example ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest"], "id": 1 } ``` ### Response #### Success Response (200) - **result** (term) - The result of the JSON-RPC call. #### Error Response - **error** (term) - The error details if the request fails. #### Response Example ```json { "jsonrpc": "2.0", "result": { "number": "0x1b4", "hash": "0x8216c5785ac562ff41e2dcfdf829c5a142f1fccd7d", "parentHash": "0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5" }, "id": 1 } ``` ## Subscriptions ### POST /api/subscribe ### Description Subscribes to real-time Ethereum events via WebSocket. ### Method POST ### Endpoint (Implicitly handled by the `subscribe/1` function) ### Parameters #### Request Body - **request** (map) - Required - A map containing the subscription details, including `jsonrpc`, `method`, `params`, and `id`. ### Request Example ```elixir WebsocketServer.subscribe(%{ jsonrpc: "2.0", method: "eth_subscribe", params: ["newHeads"], id: 1 }) ``` ### Response #### Success Response (200) - **subscription_id** (term) - The ID of the newly created subscription. #### Response Example ```elixir {:ok, "0x9cef478923ff08bf67fde6c64013158d"} ``` ## Unsubscriptions ### POST /api/unsubscribe ### Description Unsubscribes from an existing Ethereum event subscription. ### Method POST ### Endpoint (Implicitly handled by the `unsubscribe/1` function) ### Parameters #### Request Body - **request** (map) - Required - A map containing the unsubscription details, including `jsonrpc`, `method`, `params` (with the subscription ID), and `id`. ### Request Example ```elixir WebsocketServer.unsubscribe(%{ jsonrpc: "2.0", method: "eth_unsubscribe", params: ["0x9cef478923ff08bf67fde6c64013158d"], id: 3 }) ``` ### Response #### Success Response (200) - **true** (boolean) - Indicates successful unsubscription. #### Response Example ```elixir {:ok, true} ``` ## Connection Management ### POST /api/start_link ### Description Starts the WebSocket connection to the Ethereum node. ### Method POST ### Endpoint (Implicitly handled by the `start_link/1` function) ### Parameters #### Options - **:url** (String.t()) - Optional - WebSocket endpoint URL. Defaults to `Config.websocket_url()`. - **:name** (atom()) - Optional - Process name. Defaults to `ethereumex.websocket_server`. ### Request Example ```elixir WebsocketServer.start_link(url: "ws://localhost:8546") ``` ### Response #### Success Response (200) - **pid** (pid()) - The process ID of the started WebSocket server. #### Error Response - **error** (term) - The error details if the connection fails to start. #### Response Example ```elixir {:ok, #PID<0.123.456>} ``` ## Subscription Notifications ### Description When a subscribed event occurs, the notification is automatically forwarded to the subscriber process as a message. ### Event Types - `:newHeads` - `:logs` - `:newPendingTransactions` ### Notification Format ```json { "jsonrpc": "2.0", "method": "eth_subscription", "params": { "subscription": "", "result": } } ``` ### Example Notification (New Headers) ```json { "jsonrpc": "2.0", "method": "eth_subscription", "params": { "subscription": "0x9cef478923ff08bf67fde6c64013158d", "result": { "number": "0x1b4", "hash": "0x8216c5785ac562ff41e2dcfdf829c5a142f1fccd7d", "parentHash": "0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5" } } } ``` ### Example Notification (Logs) ```json { "jsonrpc": "2.0", "method": "eth_subscription", "params": { "subscription": "0x4a8a4c0517381924f9838102c5a4dcb7", "result": { "address": "0x8320fe7702b96808f7bbc0d4a888ed1468216cfd", "topics": ["0xd78a0cb8bb633d06981248b816e7bd33c2a35a6089241d099fa519e361cab902"], "data": "0x000000000000000000000000000000000000000000000000000000000000000a" } } } ``` ## Error Handling ### Description Details on how the WebSocket server handles various error conditions. ### Connection Failures * Automatically retried with exponential backoff. * Up to `@max_reconnect_attempts` attempts. * Initial delay of `@backoff_initial_delay` ms, doubling each attempt. * Reconnection attempts are logged. ### Request Timeouts * Requests time out after `@request_timeout` ms. ### Invalid Responses * Invalid JSON responses are handled gracefully. * Unmatched responses are safely ignored. ### Subscription Errors * Errors related to subscriptions are propagated to the subscriber. ``` -------------------------------- ### Configure HTTP transport Source: https://hexdocs.pm/ethereumex/index.html Set the node URL and optional HTTP request parameters in your configuration. ```elixir config :ethereumex, url: "http://localhost:8545" ``` ```elixir config :ethereumex, http_options: [pool_timeout: 5000, receive_timeout: 15_000], http_headers: [{"Content-Type", "application/json"}] ``` -------------------------------- ### subscribe Source: https://hexdocs.pm/ethereumex/Ethereumex.WebsocketServer.html Subscribes to Ethereum events via WebSocket. The request should be a map containing an ID, method 'eth_subscribe', and parameters for the subscription. Returns {:ok, subscription_id} on success or {:error, reason} on failure. Times out after 5000ms. ```APIDOC ## POST /eth_subscribe ### Description Subscribes to Ethereum events via WebSocket. ### Method POST ### Endpoint /eth_subscribe ### Request Body - **id** (integer) - Required - A unique request identifier. - **method** (string) - Required - Must be "eth_subscribe". - **params** (map) - Required - Parameters for the subscription, including the event type. ### Request Example ```json { "id": 1, "method": "eth_subscribe", "params": { "event": "logs", "address": "0x..." } } ``` ### Response #### Success Response (200) - **id** (integer) - The request identifier. - **result** (string) - The subscription ID. #### Response Example ```json { "id": 1, "result": "0x12345abcde" } ``` #### Error Response - **id** (integer) - The request identifier. - **error** (object) - Contains error details. - **code** (integer) - Error code. - **message** (string) - Error message. #### Error Response Example ```json { "id": 1, "error": { "code": -32602, "message": "Invalid params" } } ``` ``` -------------------------------- ### Configure WebSocket transport Source: https://hexdocs.pm/ethereumex/index.html Set the client type to WebSocket and provide the connection URL. ```elixir config :ethereumex, websocket_url: "ws://localhost:8545", client_type: :websocket ``` -------------------------------- ### Custom JSON-RPC Requests Source: https://hexdocs.pm/ethereumex/Ethereumex.html How to send custom JSON-RPC requests to the Ethereum node using the `request/3` method for non-standard API calls. ```APIDOC ## Custom JSON-RPC Requests For interacting with non-standard or extended JSON-RPC methods, use the `Ethereumex.HttpClient.request/3` function. ### Example: Calling `personal_listAccounts` (Parity specific) ```iex Ethereumex.HttpClient.request("personal_listAccounts", [], []) # => {:ok, # ["0x71cf0b576a95c347078ec2339303d13024a26910", # "0x7c12323a4fff6df1a25d38319d5692982f48ec2e"]} ``` ``` -------------------------------- ### Subscribe to Logs with Filter Source: https://hexdocs.pm/ethereumex/Ethereumex.WebsocketServer.html Subscribe to log events filtered by specific criteria, such as an address. This allows for real-time monitoring of contract interactions. ```elixir # Subscribe to logs with filter {:ok, subscription_id} = WebsocketServer.subscribe(%{ jsonrpc: "2.0", method: "eth_subscribe", params: ["logs", %{address: "0x123..."}], id: 2 }) ``` -------------------------------- ### Ethereumex.WebsocketServer.State Type Source: https://hexdocs.pm/ethereumex/Ethereumex.WebsocketServer.State.html Defines the structure of the server state, including connection details, pending requests, and subscriptions. ```APIDOC ## Ethereumex.WebsocketServer.State (ethereumex v0.14.0) ### Description Server state containing: * url: WebSocket endpoint URL * requests: Map of pending requests with their corresponding sender PIDs * subscription requests: Map of pending subscription requests with their corresponding sender PIDs * unsubscription requests: Map of pending unsubscription requests with their corresponding sender PIDs * subscriptions: Map of subscription IDs to subscriber PIDs ### Type Definition ```elixir @type t() :: %Ethereumex.WebsocketServer.State{ reconnect_attempts: non_neg_integer(), requests: %{required(Ethereumex.WebsocketServer.request_id()) => pid()}, subscription_requests: %{ required(Ethereumex.WebsocketServer.request_id()) => pid() }, subscriptions: %{ required(Ethereumex.WebsocketServer.subscription_id()) => pid() }, unsubscription_requests: %{ required(Ethereumex.WebsocketServer.request_id()) => pid() }, url: String.t() } ``` ``` -------------------------------- ### Execute standard RPC calls Source: https://hexdocs.pm/ethereumex/index.html Perform standard JSON-RPC requests using the WebSocket client. ```elixir iex> Ethereumex.WebsocketClient.eth_block_number() {:ok, "0x1234"} ``` -------------------------------- ### Ethereumex WebSocket Receive Notifications Source: https://hexdocs.pm/ethereumex/readme.html Handle incoming notifications from WebSocket subscriptions by receiving messages in your process. The `handle_notification/1` function should be defined to process the results. ```elixir # Receive notifications in your process receive do %{ "method" => "eth_subscription", "params" => %{ "subscription" => subscription_id, "result" => result }} -> handle_notification(result) end ``` -------------------------------- ### unsubscribe Source: https://hexdocs.pm/ethereumex/Ethereumex.WebsocketServer.html Unsubscribes from an existing Ethereum event subscription. The request should be a map containing an ID, method 'eth_unsubscribe', and a list of subscription IDs to unsubscribe from. Returns {:ok, true} on success or {:error, reason} on failure. Times out after 5000ms. ```APIDOC ## POST /eth_unsubscribe ### Description Unsubscribes from an existing Ethereum event subscription. ### Method POST ### Endpoint /eth_unsubscribe ### Request Body - **id** (integer) - Required - A unique request identifier. - **method** (string) - Required - Must be "eth_unsubscribe". - **params** (array) - Required - A list containing the subscription IDs to unsubscribe from. ### Request Example ```json { "id": 2, "method": "eth_unsubscribe", "params": ["0x12345abcde"] } ``` ### Response #### Success Response (200) - **id** (integer) - The request identifier. - **result** (boolean) - True if unsubscribe was successful. #### Response Example ```json { "id": 2, "result": true } ``` #### Error Response - **id** (integer) - The request identifier. - **error** (object) - Contains error details. - **code** (integer) - Error code. - **message** (string) - Error message. #### Error Response Example ```json { "id": 2, "error": { "code": -32602, "message": "Invalid subscription ID" } } ``` ```