

# Using Ethereum APIs with Amazon Managed Blockchain (AMB)
JSON-RPC and API

Amazon Managed Blockchain (AMB) provides API operations for creating and managing token accessors, nodes, and networks for AMB Access Ethereum. For more information, see the * [AMB Access API Reference Guide](https://docs.aws.amazon.com/managed-blockchain/latest/APIReference/Welcome.html) *.

The following section provides a list and reference of the Ethereum (JSON-RPC and Consensus) API methods that Amazon Managed Blockchain (AMB) supports. It also includes code examples that implement API calls from clients using either HTTP or WebSocket (JSON-RPC API only) connections.

You use the Ethereum API from a client to query smart contract data and submit transactions to an Ethereum node on Amazon Managed Blockchain (AMB). You use the Ethereum Consensus API from a client to query the Beacon chain, its configuration, and the node health. For more information, see [Viewing node details](ethereum-nodes.md#ethereum-node-information).

**Execution and consensus client support**

The Ethereum Merge transitioned the Ethereum blockchain to a proof-of-stake consensus, and it resulted in a new modular design for Ethereum. After the Merge, the original Ethereum stack forked into two distinct layers: the execution layer and the consensus layer. There are many different client implementations for both of these layers; however, Amazon Managed Blockchain (AMB) provides a fully managed Ethereum node that uses the *GoEthereum (Geth)* execution client and the *Lighthouse* consensus client. 

**Topics**
+ [

# Supported JSON-RPC methods
](supported-json-rpc.md)
+ [

# Supported Consensus API methods
](supported-consensus-apis.md)

# Supported JSON-RPC methods


Amazon Managed Blockchain (AMB) Access Ethereum supports the following Ethereum JSON-RPC API methods. Each supported API call has a brief description of its utility. Unique considerations for using the JSON-RPC method with an Ethereum node in Amazon Managed Blockchain (AMB) are indicated where applicable.

**Note**  
Ethereum API calls to an Ethereum node in Amazon Managed Blockchain (AMB) can be authenticated by using the [Signature Version 4 (SigV4) signing process](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). This means that only authorized IAM principals in the AWS account that created the node can interact with it using the Ethereum APIs. AWS credentials (an access key ID and secret access key) must be provided with the call.
Token based access can also be used to make Ethereum API calls to an Ethereum node as a convenient alternative to the Signature Version 4 (SigV4) signing process. If you prioritize security and auditability over convenience, use the SigV4 signing process instead. However, if you use token based access to make Ethereum APIs calls, any security benefits that are provided by using the SigV4 signing process is negated.
JSON-RPC batch requests aren't supported on Amazon Managed Blockchain (AMB) Access Ethereum.
WebSocket calls have a 512 KB payload quota. Some calls might exceed this quota and cause a "message response is too large" error. For this reason, we recommend you use HTTP for these requests instead of WebSocket connections.
If your HTTP response is larger than 5.9 MB, you will get an error. To correct this, you must set both compression headers as `Accept: application/gzip` and `Accept-Encoding: gzip`. The compressed response your client then receives contains the following headers: ` Content-Type: application/json` and `Content-Encoding: gzip`.
For historic data that requires archival nodes, use Amazon Managed Blockchain (AMB) Query. For more information, see the *[AMB Query Developer Guide](https://docs.aws.amazon.com/managed-blockchain/latest/ambq-dg)*.

**Topics**
+ [

# Making JSON-RPC API calls to an Ethereum node in Amazon Managed Blockchain (AMB)
](json-rpc-api-examples.md)

**The block identifier parameter**

Some methods have an extra block identifier parameter. The following options are possible values for this parameter:
+ A hexadecimal string value that represents an integer block number.
+ `"earliest"` – String for the genesis block.
+ `"latest"` – String for the latest mined block.
+ `"pending"` – String for the pending state transactions.


| Method | Description | Considerations | 
| --- | --- | --- | 
| [debug\$1traceBlock](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug#debugtraceblock) | Returns the full stack trace of all the invoked opcodes for all the transactions that were included in the block provided as a parameter in RLP format. | Only data for the most recent 128 blocks is supported. Archival data is not supported. | 
| [debug\$1traceBlockByHash](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug#debugtraceblockbyhash) | Returns the full stack trace of all the transactions that were included in a specified block by its hash. | Only data for the most recent 128 blocks is supported. Archival data is not supported. | 
| [debug\$1traceBlockByNumber](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug#debugtraceblockbynumber) | Returns the full stack trace of all the transactions that were included in the specified block number. | Only data for the most recent 128 blocks is supported. Archival data is not supported. | 
| [debug\$1traceCall](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug#debugtracecall) | Returns the full stack trace after running an eth\$1call within the context of the given block execution. The method is also used to simulate the outcomes of transactions and supports custom tracers. | Only data for the most recent 128 blocks is supported. Archival data is not supported. | 
| [debug\$1traceTransaction](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug#debugtracetransaction) | Attempts to return all traces for a given transaction. |  | 
| [eth\$1blockNumber](https://eth.wiki/json-rpc/API#eth_blocknumber) | Returns the number of the most recent block. |  | 
| [eth\$1call](https://eth.wiki/json-rpc/API#eth_call) | Immediately runs a new message call without creating a transaction on the blockchain. | eth\$1call consumes 0 gas, but has a gas parameter for messages that require it. Only data for the most recent 128 blocks is supported. Archival data is not supported. | 
| eth\$1chainId | Returns an integer value for the currently configured Chain Id value that's introduced in [EIP-155](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md). Returns None if no Chain Id is available. |  | 
| eth\$1createAccessList | This method creates an [EIP2930](https://eips.ethereum.org/EIPS/eip-2930) type accessList based on a given Transaction. The accessList contains all the storage slots and addresses read and written by the transaction, except for the sender account and the precompiles. This method uses the same transaction call object and blockNumberOrTag object as eth\$1call. | An accessList can be used to unstuck contracts that became inaccessible due to gas cost increases. | 
| [eth\$1estimateGas](https://eth.wiki/json-rpc/API#eth_estimategas) | Estimates and returns the gas that's required for a transaction without adding the transaction to the blockchain. |  | 
| eth\$1feeHistory | Returns a collection of historical gas information. |  | 
| [eth\$1gasPrice](https://eth.wiki/json-rpc/API#eth_gasprice) | Returns the current price per gas in Wei. |  | 
| [eth\$1getBalance](https://eth.wiki/json-rpc/API#eth_getbalance) | Returns the balance of an account for the specified account address and block identifier. | Only data for the most recent 128 blocks is supported. Archival data is not supported. | 
| [eth\$1getBlockByHash](https://eth.wiki/json-rpc/API#eth_getblockbyhash) | Returns information about the block specified using the block hash. |  | 
| [eth\$1getBlockByNumber](https://eth.wiki/json-rpc/API#eth_getblockbynumber) | Returns information about the block specified using the block number. |  | 
| [eth\$1getBlockTransactionCountByHash](https://eth.wiki/json-rpc/API#eth_getblocktransactioncountbyhash) | Returns the number of transactions in the block specified using the block hash. |  | 
| [eth\$1getBlockTransactionCountByNumber](https://eth.wiki/json-rpc/API#eth_getblocktransactioncountbynumber) | Returns the number of transactions in the block specified using the block number. |  | 
| [eth\$1getCode](https://eth.wiki/json-rpc/API#eth_getcode) | Returns the code at the specified account address and block identifier. | Only data for the most recent 128 blocks is supported. Archival data is not supported. | 
| [eth\$1getFilterChanges](https://eth.wiki/json-rpc/API#eth_getfilterchanges) | Polls the specified filter ID, retuning an array of logs that occurred since the last poll. | Filters are ephemeral. If AMB Access needs to manage or maintain node instances for availability and performance, and an instance is replaced, filters might be deleted. We recommend that you write your application code to handle the occasional deletion of filters. | 
| [eth\$1getFilterLogs](https://eth.wiki/json-rpc/API#eth_getfilterlogs) | Returns an array of all logs for the specified filter ID. | Filters are ephemeral. If AMB Access needs to manage or maintain node instances for availability and performance, and an instance is replaced, filters might be deleted. We recommend that you write your application code to handle the occasional deletion of filters. | 
| [eth\$1getLogs](https://eth.wiki/json-rpc/API#eth_getlogs) | Returns an array of all logs for a specified filter object. | Filters are ephemeral. If AMB Access needs to manage or maintain node instances for availability and performance, and an instance is replaced, filters might be deleted. We recommend that you write your application code to handle the occasional deletion of filters. | 
| eth\$1getProof | Experimental – Returns the account and storage values of the specified account, including the Merkle proof. |  | 
| [eth\$1getStorageAt](https://eth.wiki/json-rpc/API#eth_getstorageat) | Returns the value of the specified storage position for the specified account address and block identifier. | Only data for the most recent 128 blocks is supported. Archival data is not supported. | 
| [eth\$1getTransactionByBlockHashAndIndex](https://eth.wiki/json-rpc/API#eth_gettransactionbyblockhashandindex) | Returns information about a transaction using the specified block hash and transaction index position. |  | 
| [eth\$1getTransactionByBlockNumberAndIndex](https://eth.wiki/json-rpc/API#eth_gettransactionbyblocknumberandindex) | Returns information about a transaction using the specified block number and transaction index position. |  | 
| [eth\$1getTransactionByHash](https://eth.wiki/json-rpc/API#eth_gettransactionbyhash) | Returns information about the transaction with the specified transaction hash. |  | 
| [eth\$1getTransactionCount](https://eth.wiki/json-rpc/API#eth_gettransactioncount) | Returns the number of transactions sent from the specified address and block identifier. |  | 
| [eth\$1getTransactionReceipt](https://eth.wiki/json-rpc/API#eth_gettransactionreceipt) | Returns the receipt of the transaction using the specified transaction hash. |  | 
| [eth\$1getUncleByBlockHashAndIndex](https://eth.wiki/json-rpc/API#eth_getunclebyblockhashandindex) | Returns information about the uncle block specified using the block hash and uncle index position. |  | 
| [eth\$1getUncleByBlockNumberAndIndex](https://eth.wiki/json-rpc/API#eth_getunclebyblocknumberandindex) | Returns information about the uncle block specified using the block number and uncle index position. |  | 
| [eth\$1getUncleCountByBlockHash](https://eth.wiki/json-rpc/API#eth_getunclecountbyblockhash) | Returns the number of counts in the uncle specified using the uncle hash. |  | 
| [eth\$1getUncleCountByBlockNumber](https://eth.wiki/json-rpc/API#eth_getunclecountbyblocknumber) | Returns the number of counts in the uncle specified using the uncle number. |  | 
| [eth\$1getWork](https://eth.wiki/json-rpc/API#eth_getwork) | Returns the hash of the current block, the seedHash, and the boundary condition (also called the "target") to be met. |  | 
| eth\$1maxPriorityFeePerGas | Returns the fee per gas that's an estimate of how much you can pay as a priority fee, or "tip," to get a transaction included in the current block. | Generally you use the value that's returned from this method to set the maxFeePerGas in the subsequent transaction that you're submitting. | 
| [eth\$1newBlockFilter](https://eth.wiki/json-rpc/API#eth_newblockfilter) | Creates a filter in the node to notify when a new block arrives. Use eth\$1getFilterChanges to check for state changes. |  | 
| [eth\$1newFilter](https://eth.wiki/json-rpc/API#eth_newfilter) | Creates a filter object with the specified filter options (such as from block, to block, contract address, or topics). |  | 
| [eth\$1newPendingTransactionFilter](https://eth.wiki/json-rpc/API#eth_newpendingtransactionfilter) | Creates a filter in the node to notify when new pending transactions arrive. Use <code>eth\$1getFilterChanges</code> to check for state changes. |  | 
| [eth\$1protocolVersion](https://eth.wiki/json-rpc/API#eth_protocolversion) | Returns the current Ethereum protocol version. |  | 
| [eth\$1sendRawTransaction](https://eth.wiki/json-rpc/API#eth_sendrawtransaction) | Creates a new message call transaction or a contract creation for signed transactions.  | AMB Access supports raw transactions only. You must create and sign transactions before sending them. For more information, see [How to create raw transactions in Ethereum](https://medium.com/blockchain-musings/how-to-create-raw-transactions-in-ethereum-part-1-1df91abdba7c). | 
| [eth\$1subscribe](https://geth.ethereum.org/docs/interacting-with-geth/rpc/pubsub) | Experimental for publication subscription – Creates a subscription for specified events and returns a subscription ID.  | Available only when using WebSocket connections. Subscriptions are coupled to each connection. When the connection closes, the subscription is removed. | 
| [eth\$1syncing](https://eth.wiki/json-rpc/API#eth_syncing) | Returns an object with sync status data or false when not syncing. |  | 
| [eth\$1uninstallFilter](https://eth.wiki/json-rpc/API#eth_uninstallfilter) | Uninstalls the filter with the specified filter ID. |  | 
| [eth\$1unsubscribe](https://geth.ethereum.org/docs/interacting-with-geth/rpc/pubsub#cancel-subscriptions) | Experimental for publication subscription – Cancels the subscription with the specified subscription ID. |  | 
| [net\$1listening](https://eth.wiki/json-rpc/API#net_listening) | Returns true if the client is actively listening for network connections. |  | 
| [net\$1peerCount](https://eth.wiki/json-rpc/API#net_peercount) | Returns the number of peers currently connected to the client. |  | 
| [net\$1version](https://eth.wiki/json-rpc/API#net_version) | Returns the current network ID. |  | 
| [txpool\$1inspect](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-txpool#txpool-inspect) | Lists a textual summary of all the transactions that are currently pending inclusion in the next blocks, and those that are queued (being scheduled for future execution only). |  | 
| [txpool\$1status](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-txpool#txpool-status) | Provides a count of all transactions currently pending inclusion in the next blocks, and those that are queued (being scheduled for future execution only). |  | 
| [web3\$1clientVersion](https://eth.wiki/json-rpc/API#web3_clientversion) | Returns the current client version. |  | 
| [web3\$1sha3](https://eth.wiki/json-rpc/API#web3_sha3) | Returns Keccak-256 (not the standardized SHA3-256) of the given data. |  | 

# Making JSON-RPC API calls to an Ethereum node in Amazon Managed Blockchain (AMB)
Examples using the JSON-RPC API

The following examples demonstrate ways to make Ethereum JSON-RPC API calls to an Ethereum node in Amazon Managed Blockchain (AMB).

**Topics**
+ [

## Using Signature Version 4 to make JSON-RPC API calls to an Ethereum node
](#json-rpc-api-sigv4-examples)
+ [

## Using token based access to make JSON-RPC API calls to an Ethereum node
](#json-rpc-api-tba-examples)

## Using Signature Version 4 to make JSON-RPC API calls to an Ethereum node
Examples using Sig V4

The following sections demonstrate ways to make JSON-RPC API calls to an Ethereum node on Amazon Managed Blockchain (AMB) using the Signature Version 4 signing process.

**Important**  
The Signature Version 4 signing process requires the credentials that are associated with an AWS account. Some examples in this section export these sensitive credentials to the shell environment of the client. Only use these examples on a client that run in a trusted context. Do not use these examples in an untrusted context, such as in a web browser or mobile app. Never embed client credentials in user-facing applications. To expose an Ethereum node in AMB Access to anonymous users visiting from trusted web domains, you can set up a separate endpoint in [Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) that's backed by a Lambda function that forwards requests to your node using the proper IAM credentials.

**Topics**
+ [

### Endpoint format for making JSON-RPC API calls over WebSocket and HTTP connections using Signature Version 4
](#json-rpc-sigv4-api-endpoints)
+ [

### Using web3.js to make JSON-RPC API calls
](#json-rpc-web3-sigv4-examples)
+ [

### Making JSON-RPC API call using AWS SDK for JavaScript with a WebSocket connection to an Ethereum node in Amazon Managed Blockchain (AMB)
](#json-rpc-connect-to-node-websockets-awsjssdk)
+ [

### Making JSON-RPC API calls using awscurl over HTTP
](#sigv4-connect-to-node-http)

### Endpoint format for making JSON-RPC API calls over WebSocket and HTTP connections using Signature Version 4


**Example**  
An Ethereum node created using AMB Access Ethereum hosts one endpoint for WebSocket connections and another for HTTP connections. These endpoints conform to the following patterns.  
The node ID is case sensitive and must be lowercase where indicated, or a signature mismatch error occurs.
**WebSocket endpoint format**  
  

```
wss://your-node-id-lowercase.wss.ethereum.managedblockchain.us-east-1.amazonaws.com/
```
For example: `wss://nd-6eaj5va43jggnpxouzp7y47e4y.wss.ethereum.managedblockchain.us-east-1.amazonaws.com/`  
**HTTP endpoint format**  

```
https://your-node-id-lowercase.ethereum.managedblockchain.us-east-1.amazonaws.com/
```
For example, `https://nd-6eaj5va43jggnpxouzp7y47e4y.ethereum.managedblockchain.us-east-1.amazonaws.com/`

### Using web3.js to make JSON-RPC API calls


[Web3.js](https://web3js.readthedocs.io/en/v1.3.0/) is a popular collection of JavaScript libraries available using the Node package manager (npm). You can run the following examples to send a JSON-RPC API call to Ethereum using a Javascript file for Node.js. The examples demonstrate an HTTP connection and a WebSocket connection to an Ethereum node.

Both HTTP and WebSocket connection types rely on a local connection provider library to open the Signature Version 4 authenticated connection to the Ethereum node. You install the provider for the connection locally by copying the source code to a file on your client. Then, reference the library files in the script that makes the Ethereum API call.

#### Prerequisites


**Example**  
Running the example scripts requires the following prerequisites. Prerequisites for both HTTP and WebSocket connections are included.  

1. You must have node version manager (nvm) and Node.js installed on your machine. If you use an Amazon EC2 instance as your Ethereum client, see [Tutorial: Setting Up Node.js on an Amazon EC2 Instance](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-up-node-on-ec2-instance.html) for more information.

1. Type `node --version` and verify that you are using Node version 14 or later. If necessary, you can use the `nvm install 14` command followed by the `nvm use 14` command to install version 14.

1. The environment variables `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` must contain the credentials that are associated with the same AWS account that created the node. The environment variables `AMB_HTTP_ENDPOINT` and `AMB_WS_ENDPOINT` must contain your Ethereum node's HTTP and WebSocket endpoints respectively.

   Export these variables as strings on your client using the following commands. Replace the values with appropriate values from your IAM user account.

   ```
   export AWS_ACCESS_KEY_ID="AKIAIOSFODNN7EXAMPLE"
   ```

   ```
   export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
   ```

   ```
   export AMB_HTTP_ENDPOINT="https://nd-6eaj5va43jggnpxouzp7y47e4y.ethereum.managedblockchain.us-east-1.amazonaws.com/"
   ```

   ```
   export AMB_WS_ENDPOINT="wss://nd-6eaj5va43jggnpxouzp7y47e4y.wss.ethereum.managedblockchain.us-east-1.amazonaws.com/"
   ```

**Example**  

**To make an Ethereum API call using web3.js over HTTP to your Ethereum node in the AMB Access**

1. This example script uses the ECMAScript (ES) module. Therefore, add the `"type": "module"` line to your `package.json` file. The example `package.json` snippet that follows shows the contents required to successfully run this example.

   ```
   {
     "type": "module",
     "dependencies": {
    "@aws-crypto/sha256-js": "^4.0.0",
    "@aws-sdk/credential-providers": "^3.352.0",
    "@aws-sdk/fetch-http-handler": "^3.353.0",
    "@aws-sdk/protocol-http": "^3.347.0",
    "@aws-sdk/signature-v4": "^3.347.0",
    "@aws-sdk/types": "^3.347.0",
    "web3": "^1.10.0",
    "xhr2": "^0.2.1"
    }
   }
   ```

1. Use node package manager (npm) to install the requisite dependencies. 

   ```
   npm install
   ```

1. Copy the contents of the example that follows, and then use your preferred text editor to save it to a file that's named `awsHttpSigV4-v2.js` on your client machine in the same directory where you run your script.

   **Contents of awsHttpSigV4-v2.js**

   ```
   /////////////////////////////////////////////////////
   // Authored by Rafia Tapia
   // Senior Blockchain Solutions Architect, AWS
   // licensed under GNU Lesser General Public License
   // https://github.com/ethereum/web3.js
   /////////////////////////////////////////////////////
   import HttpProvider from 'web3-providers-http';
   import XHR2 from 'xhr2';
   import { fromEnv} from '@aws-sdk/credential-providers';
   import sigv4 from '@aws-sdk/signature-v4';
   import http from '@aws-sdk/protocol-http';
   import crypto from "@aws-crypto/sha256-js";
   export default class AWSHttpSigV4_v2Provider extends HttpProvider {
     constructor(connectionStr) {
       super(connectionStr);
     }
     send(payload, callback) {
       const self = this;
       /* ******************** XHR2 *************************** */
       const request = new XHR2(); // eslint-disable-line
       request.timeout = self.timeout;
       request.open('POST', self.host, true);
       request.setRequestHeader('Content-Type', 'application/json');
       request.onreadystatechange = () => {
         if (request.readyState === 4 && request.timeout !== 1) {
           let result = request.responseText; // eslint-disable-line
           let error = null; // eslint-disable-line
           try {
             result = JSON.parse(result);
           } catch (jsonError) {
             let message;
             if (!!result && !!result.error && !!result.error.message) {
               message = `[aws-ethjs-provider-http] ${result.error.message}`;
             } else {
               message = `[aws-ethjs-provider-http] Invalid JSON RPC response from host provider ${self.host}: ` +
                 `${JSON.stringify(result, null, 2)}`;
             }
             error = new Error(message);
           }
           self.connected = true;
           callback(error, result);
         }
       };
       request.ontimeout = () => {
         self.connected = false;
         callback(`[aws-ethjs-provider-http] CONNECTION TIMEOUT: http request timeout after ${self.timeout} ` +
           `ms. (i.e. your connect has timed out for whatever reason, check your provider).`, null);
       };
       /* ******************** END XHR2 *************************** */
       const strPayload = JSON.stringify(payload);
       const region = process.env.AWS_DEFAULT_REGION || 'us-east-1';
       try {
         const urlparser=new URL(self.host)
         let signerV4 = new sigv4.SignatureV4({ credentials: fromEnv(), region: region, service: "managedblockchain", sha256: crypto.Sha256 });
         let requestOptions={
           protocol:urlparser.protocol,
           hostname:urlparser.hostname,
           method: 'POST',
           body:strPayload,
           headers:{'host':urlparser.host},
           path:urlparser.pathname
         }
         const newReq = new http.HttpRequest(requestOptions);
         signerV4.sign(newReq,{signingDate:new Date(),}).then(signedHttpRequest => {
           request.setRequestHeader('authorization', signedHttpRequest.headers['authorization']);
           request.setRequestHeader('x-amz-date', signedHttpRequest.headers['x-amz-date']);
           request.setRequestHeader('x-amz-content-sha256', signedHttpRequest.headers['x-amz-content-sha256']);
           request.send(strPayload);
         }).catch(sigError => {
           console.log(sigError);
         });
       } catch (error) {
         callback(`[aws-ethjs-provider-http] CONNECTION ERROR: Couldn't connect to node '${self.host}': ` +
           `${JSON.stringify(error, null, 2)}`, null);
       }
     }
   }
   ```

1. Copy the contents of the following example, and then use your preferred text editor to save it to a file that's named `web3-example-http.js` in the same directory where you saved the provider from the previous step. The example script runs the `getNodeInfo` Ethereum method. You can modify the script to include other methods and their parameters.

   **Contents of web3-example-http.js**

   ```
   import AWSHttpSigV4_v2Provider from './awsHttpSigV4-v2.js';
   const endpoint = process.env.AMB_HTTP_ENDPOINT
   const web3 = new Web3(new AWSHttpSigV4_v2Provider(endpoint));
   web3.eth.getNodeInfo().then(console.log);
   ```

1. Run the script to call the Ethereum API method over HTTP on your Ethereum node.

   ```
   node web3-example-http.js
   ```

   The output is similar to the following.

   ```
   Geth/v1.9.24-stable-cc05b050/linux-amd64/go1.15.5
   ```

**To make an Ethereum API call using web3.js over WebSocket to your Ethereum node in the AMB Access**

1. The following example `package.json` snippet that follows shows the *dependencies* required to successfully run the example.

   ```
   "@aws-sdk/credential-providers": "^3.352.0",
   "@aws-sdk/fetch-http-handler": "^3.353.0",
   "@aws-sdk/protocol-http": "^3.347.0",
   "@aws-sdk/signature-v4": "^3.347.0",
   "@aws-sdk/types": "^3.347.0",
   "web3": "^1.10.0",
   "websocket": "^1.0.34"1*"
   ```

1. Use node package manager (npm) to install the requisite dependencies. 

   ```
   npm install
   ```

1. Copy the contents of the example that follows, and then use a text editor of your choosing to save it to a file that's named `web3-example-ws.js` in the same directory on your client where you run your script.

   **Contents of web3-example-ws.js**

   ```
   // Authored by Rafia Tapia
   // Senior Blockchain Solutions Architect, AWS
   // licensed under GNU Lesser General Public License
   // https://github.com/ethereum/web3.js
   /////////////////////////////////////////////////////
    
   import Web3 from 'web3';
   import WebsocketProvider from 'web3-providers-ws';
   import { fromEnv } from '@aws-sdk/credential-providers';
   import sigv4 from '@aws-sdk/signature-v4';
   import http from '@aws-sdk/protocol-http';
   import crypto from "@aws-crypto/sha256-js";
    
   const endpoint = process.env.AMB_WS_ENDPOINT
   const region = process.env.AWS_DEFAULT_REGION || 'us-east-1';
   const urlparser = new URL(endpoint);
   let signerV4 = new sigv4.SignatureV4({ credentials: fromEnv(), region: region, service: "managedblockchain", sha256: crypto.Sha256 });
   let reqOptions = {
       protocol: "HTTPS",
       hostname: urlparser.hostname,
       method: 'GET',
       body: "",
       headers: { 'host': urlparser.host },
       path: urlparser.pathname
    
   };
   const newReq = new http.HttpRequest(reqOptions);
   signerV4.sign(newReq, { signingDate: new Date(), }).then(signedHttpRequest => {
       const options = {
           headers: {
               'Authorization': signedHttpRequest.headers['authorization'],
               "X-Amz-Date": signedHttpRequest.headers['x-amz-date'],
               "X-Amz-Content-Sha256": signedHttpRequest.headers['x-amz-content-sha256'],
               'host':signedHttpRequest.headers['host']
           }
       };
       const web3 = new Web3(new WebsocketProvider(endpoint, options));
       web3.eth.getNodeInfo().then(console.log).then(() => {
           web3.currentProvider.connection.close();
       });
    
   }).catch(sigError => {
       console.log(sigError);
   })
   ```

1. Run the script to call the Ethereum API method over WebSocket on your Ethereum node.

   ```
   node web3-example-ws.js
   ```

   The output is similar to following.

   ```
   Geth/v1.9.24-stable-cc05b050/linux-amd64/go1.15.5
   ```

### Making JSON-RPC API call using AWS SDK for JavaScript with a WebSocket connection to an Ethereum node in Amazon Managed Blockchain (AMB)
JSON-RPC calls over WebSocket

The following example uses a JavaScript file for Node.js to open a WebSocket connection to the Ethereum node endpoint in AMB Access and sends an Ethereum JSON-RPC API call.

Running the example script requires the following:
+ Node.js is installed on your machine. If you are using an Amazon EC2 instance, see [Tutorial: Setting Up Node.js on an Amazon EC2 Instance](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-up-node-on-ec2-instance.html).
+ The following example `package.json` snippet that follows shows the *dependencies* required to successfully run the example. 

  ```
  "@aws-sdk/credential-providers": "^3.352.0",
  "@aws-sdk/fetch-http-handler": "^3.353.0",
  "@aws-sdk/protocol-http": "^3.347.0",
  "@aws-sdk/signature-v4": "^3.347.0",
  "@aws-sdk/types": "^3.347.0",
  "web3": "^1.10.0",
  "websocket-client": "^1.0.0",
  "ws": "^8.14.2"
  ```
+ Use node package manager (npm) to install the requisite dependencies. 

**Example To make an Ethereum API call over WebSocket to your Ethereum node on AMB Access**  

1. Copy the contents of the following script and save it to a file on your machine (for example, `ws-ethereum-example.js`). 

   The example calls the Ethereum JSON-RPC method `eth_subscribe` along with the `newHeads` parameter. You can replace this method and its parameters with any method that's listed in [Supported JSON-RPC methods](supported-json-rpc.md).

   **Contents of ws-ethereum-example.js**

   ```
   // Authored by Rafia Tapia
   // Senior Blockchain Solutions Architect, AWS
   // licensed under GNU Lesser General Public License
   // https://github.com/ethereum/web3.js
   /////////////////////////////////////////////////////
    
   import Web3 from 'web3';
   import { fromEnv } from '@aws-sdk/credential-providers';
   import sigv4 from '@aws-sdk/signature-v4';
   import http from '@aws-sdk/protocol-http';
   import crypto from "@aws-crypto/sha256-js";
   import WebSocket from 'ws';
    
   const endpoint = process.env.AMB_WS_ENDPOINT
   const region = process.env.AWS_DEFAULT_REGION || 'us-east-1';
   const urlparser = new URL(endpoint);
   let signerV4 = new sigv4.SignatureV4({ credentials: fromEnv(), region: region, service: "managedblockchain", sha256: crypto.Sha256 });
   let reqOptions = {
       protocol: "HTTPS",
       hostname: urlparser.hostname,
       method: 'GET',
       body: "",
       headers: { 'host': urlparser.host },
       path: urlparser.pathname
    
   };
   const newReq = new http.HttpRequest(reqOptions);
   signerV4.sign(newReq, { signingDate: new Date(), }).then(signedHttpRequest => {
       let payload = {
           jsonrpc: '2.0',
           method: 'eth_subscribe',
           params: ["newHeads"],
           id: 67
       }
       const ws = new WebSocket(endpoint, { headers: signedHttpRequest.headers });
       ws.onopen = async () => {
           ws.send(JSON.stringify(payload));
           console.log('Sent request');
       }
       ws.onerror = (error) => {
           console.error(`WebSocket error: ${error.message}`)
       }
       ws.onmessage = (e) => {
           console.log(e.data)
       }
   }).catch(sigError => {
       console.log(sigError);
   })
   ```

1. Run the following command to call the Ethereum API method over WebSocket on your Ethereum node.

   ```
   node ws-ethereum-example.js
   ```

   The `eth_subscribe` method with the `newHeads` parameter generates a notification each time a new header is appended to the chain. Output is similar to the following example. The WebSocket connection remains open and additional notifications appear until you cancel the command.

   ```
   sent request
   {"id":67,"jsonrpc":"2.0","result":"0xabcd123456789efg0h123ijk45l6m7n8"}
   ```

### Making JSON-RPC API calls using awscurl over HTTP
Using awscurl over HTTP

**Example**  
The example that follows uses [awscurl](https://pypi.org/project/awscurl/0.6/), which sends a signed HTTP request based on the current credentials you have set for the AWS CLI. If you construct your own HTTP requests, see [Signing AWS requests with Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html) in the *AWS General Reference*.  
Replace `your-node-id-lowercase` with the ID of a node in your account (for example, `nd-6eaj5va43jggnpxouzp7y47e4y`). The example calls the `web3_clientVersion` method, which takes an empty parameter block. You can replace this method and its parameters with any method that's listed in [Supported JSON-RPC methods](supported-json-rpc.md).  

```
awscurl --service managedblockchain \
-X POST -d '{"jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 67}' \
https://your-node-id-lowercase.ethereum.managedblockchain.us-east-1.amazonaws.com
```
The command returns output similar to the following.  

```
{"jsonrpc":"2.0","id":67,"result":"Geth/v1.9.22-stable-c71a7e26/linux-amd64/go1.15.5"}
```

## Using token based access to make JSON-RPC API calls to an Ethereum node
Example using Accessor tokens

You can use Accessor tokens to make Ethereum API calls to an Ethereum node as a convenient alternative to the Signature Version 4 (SigV4) signing process. You must provide a `BILLING_TOKEN` from one of the Accessor tokens that you create as a query parameter with the call. For more information on creating and managing Accessor tokens, see the topic on [Using token based access](https://docs.aws.amazon.com/managed-blockchain/latest/ethereum-dev/ethereum-tokens.html).

**Important**  
If you prioritize security and auditability over convenience, use the SigV4 signing process instead.
You can access the Ethereum APIs using Signature Version 4 (SigV4) and token based access. However, if you choose to use token based access, then any security benefits that are provided by using SigV4 are negated.
Never embed Accessor tokens in user-facing applications. 

The following examples demonstrate ways to make Ethereum JSON-RPC API calls to an Ethereum node on Amazon Managed Blockchain (AMB) using token based access.

**Topics**
+ [

### Endpoint format for WebSocket and HTTP connections using token based access
](#json-rpc-api-tba-endpoints)
+ [

### Using wscat to connect and JSON-RPC API calls to your Ethereum node over WebSocket connection using token based access
](#json-rpc-api-tba-wscat)
+ [

### Using awscurl to make JSON-RPC API calls to your Ethereum node over HTTP using token based access
](#json-rpc-api-tba-curl)

### Endpoint format for WebSocket and HTTP connections using token based access


**Example**  
Each Ethereum node hosts one endpoint for WebSocket connections and another for HTTP connections. For token based access, these endpoints conform to the following patterns:   
The node ID is case sensitive and must be lowercase where indicated, or a signature mismatch error occurs.
**WebSocket endpoint format**  

```
wss://your-node-id-lowercase.wss.t.ethereum.managedblockchain.us-east-1.amazonaws.com?billingtoken=your-billing-token
```
For example, `nd-6eaj5va43jggnpxouzp7y47e4y.wss.t.ethereum.managedblockchain.us-east-1.amazonaws.com?billingtoken=n-MWY63ZJZU5HGNCMBQER7IN6OIU`  
**HTTP endpoint format**  

```
https://your-node-id-lowercase.t.ethereum.managedblockchain.us-east-1.amazonaws.com?billingtoken=your-billing-token
```
For example, `https://nd-6eaj5va43jggnpxouzp7y47e4y.t.ethereum.managedblockchain.us-east-1.amazonaws.com?billingtoken=n-MWY63ZJZU5HGNCMBQER7IN6OIU`

### Using wscat to connect and JSON-RPC API calls to your Ethereum node over WebSocket connection using token based access


**Example**  
This section describes how you can use a third party utility, [ wscat](https://www.npmjs.com/package/wscat), to connect to your node using a token.  
After installing wscat, use the following command to open a WebSocket connection to your ethereum node.  

```
wscat --connect wss://your-node-id.wss.t.ethereum.managedblockchain.us-east-1.amazonaws.com?billingtoken=your-billing-token
```
This opens an active WebSocket connection to your node as shown in the following example response:  

```
Connected (press CTRL+C to quit)
>
```
JSON-RPC calls can now be executed as follows,  

```
{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id": 1}
```
A reply should arrive back with the same id.  

```
> {"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id": 1}
< {"jsonrpc":"2.0","id":1,"result":"0x9798e5
```
For subscriptions, calls can be executed in the following format,  

```
> {"jsonrpc":"2.0","method":"eth_subscribe","params":["newHeads"],"id": 1}
< {"id":1,"jsonrpc":"2.0","result":"0x4742411a16a232389a5877d4184e57b9"}
```
You should continuously get subscription messages that correspond to new blocks roughly every 15 seconds. To stop the messages, unsubscribe by using the subscription ID from the initial response.  

```
> {"jsonrpc":"2.0","method":"eth_unsubscribe","params":["0x4742411a16a232389a5877d4184e57b9"],"id": 1}
< {"id":1,"jsonrpc":"2.0","result":true}
```

### Using awscurl to make JSON-RPC API calls to your Ethereum node over HTTP using token based access


**Example**  
The following example uses [awscurl](https://pypi.org/project/awscurl/0.6/), which sends a signed HTTP request based on the credentials that you set for the AWS CLI.  

```
awscurl -X POST -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id": 1}' 'https://your-node-id.t.ethereum.managedblockchain.us-east-1.amazonaws.com?billingtoken=your-billing-token'
```
Example Reply (Contents may differ):  

```
{"jsonrpc":"2.0","id":1,"result":"0x9798d2"}
```

# Supported Consensus API methods


Amazon Managed Blockchain (AMB) Access Ethereum supports the following Ethereum Consensus API methods. Each supported API has a brief description of its utility. Unique considerations for using the Consensus method with an Ethereum node in Amazon Managed Blockchain (AMB) are indicated where applicable.

**Note**  
The Consensus API doesn't support WebSocket connections.
Any methods that aren't listed are not supported.
Ethereum API calls to an Ethereum node in Amazon Managed Blockchain (AMB) can be authenticated by using the [Signature Version 4 (SigV4) signing process](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). This means that only authorized IAM principals in the AWS account that created the node can interact with it using the Ethereum APIs. AWS credentials (an access key ID and secret access key) must be provided with the call.
Token based access can also be used to make Ethereum API calls to an Ethereum node as a convenient alternative to the Signature Version 4 (SigV4) signing process. If you prioritize security and auditability over convenience, use the SigV4 signing process instead. However, if you use token based access to make Ethereum APIs calls, any security benefits that are provided by using the SigV4 signing process is negated.

**Topics**
+ [

# Making Consensus API calls to an Ethereum node in Amazon Managed Blockchain (AMB)
](consensus-api-examples.md)

State related APIs are supported only for the following states:
+ `/eth/v1/beacon/states/head`
+ `/eth/v1/beacon/states/finalized`
+ `/eth/v1/beacon/states/justified`
+ `/eth/v1/beacon/states/genesis`


| Method | Description | 
| --- | --- | 
| /eth/v1/beacon/genesis | Returns the details of the chain's genesis block. | 
| /eth/v1/beacon/states/\$1state\$1id\$1/root | Calculates the HashTreeRoot for the state with a given state\$1id. If the state\$1id is root, the same value will be returned. | 
| /eth/v1/beacon/states/\$1state\$1id\$1/fork | Gets the fork object for the requested state\$1id. | 
| /eth/v1/beacon/states/\$1state\$1id\$1/finality\$1checkpoints | Returns the finality checkpoints for a state with a given state\$1id. In case finality is not yet achieved, the checkpoint returns epoch 0 and ZERO\$1HASH as root. | 
| /eth/v1/beacon/states/\$1state\$1id\$1/committees | Returns the committees for a given state\$1id. | 
| /eth/v1/beacon/headers | Returns the block headers matching a given query. | 
| /eth/v1/beacon/headers/headers/\$1block\$1id\$1 | Returns the block header for a given block\$1id. | 
| /eth/v2/beacon/blocks/\$1block\$1id\$1 | Returns the block details for a given block\$1id. | 
| /eth/v1/beacon/blocks/\$1block\$1id\$1/root | Returns the hashTreeRoot of a BeaconBlock/BeaconBlockHeader for a given block\$1id. | 
| /eth/v1/beacon/blocks/\$1block\$1id\$1/attestations | Returns the attestations of a block using its block\$1id. | 
| /eth/v1/config/fork\$1schedule | Returns all the forks; past, present, and future, of which this node is aware. | 
| /eth/v1/config/spec | Returns the configuration specification used for this node. | 
| /eth/v1/config/deposit\$1contract | Returns the Eth1 deposit contract address and chain ID. | 
| /eth/v2/debug/beacon/heads | Returns all the possible chain heads (leaves of the fork choice tree). | 
| /eth/v1/node/identity | Returns data about the node's network presence. | 
| /eth/v1/node/peers | Returns data about the node's network peers. | 
| /eth/v1/node/peers/\$1peer\$1id\$1 | Returns data about a peer given the peer\$1id. | 
| /eth/v1/node/peer\$1count | Returns the number of known peers. | 
| /eth/v1/node/version | Requests the Beacon node identify information about its implementation in a format similar to a [HTTP User-Agent](https://datatracker.ietf.org/doc/html/rfc7231#section-5.5.3) field. | 
| /eth/v1/node/syncing | Requests the Beacon node to describe if it's currently syncing, and if it's, what block it's up to. | 
| /eth/v1/node/health | Returns the Beacon node's health status in HTTP status codes. This is useful information for load balancers. | 

# Making Consensus API calls to an Ethereum node in Amazon Managed Blockchain (AMB)
Examples making Consensus API calls

The following examples demonstrate ways to make Ethereum Consensus API calls to an Ethereum node in Amazon Managed Blockchain (AMB).

**Topics**
+ [

## Using Consensus API calls signed using Signature Version 4 to an Ethereum node
](#consensus-api-sigv4-examples)
+ [

## Using token based access to make Consensus API calls to an Ethereum node
](#consensus-api-tba-examples)

## Using Consensus API calls signed using Signature Version 4 to an Ethereum node
Examples using Sig V4

The following sections demonstrate ways to make Consensus API calls to an Ethereum node on Amazon Managed Blockchain (AMB) using the Signature Version 4 signing process.

**Important**  
The Signature Version 4 signing process requires the credentials that are associated with an AWS account. Some examples in this section export these sensitive credentials to the shell environment of the client. Only use these examples on a client that run in a trusted context. Do not use these examples in an untrusted context, such as in a web browser or mobile app. Never embed client credentials in user-facing applications. To expose an Ethereum node in AMB Access to anonymous users visiting from trusted web domains, you can set up a separate endpoint in [Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) that are backed by a Lambda function that forwards requests to your node using the proper IAM credentials.

**Topics**
+ [

### Endpoint format for making Consensus API calls over HTTP
](#consensus-sigv4-api-endpoints)
+ [

### Making Consensus API calls using AWS SDK for JavaScript over HTTP
](#consensus-sigv4-connect-to-node-http-awsjssdk)
+ [

### Using awscurl to make Consensus API calls over HTTP
](#consensus-sigv4-connect-to-node-http)

### Endpoint format for making Consensus API calls over HTTP


An Ethereum node that's created using AMB Access Ethereum hosts one endpoint for HTTP connections. This endpoint conforms to the following patterns.

**Note**  
The node ID is case sensitive and must be lowercase where indicated, or a signature mismatch error occurs.

**HTTP endpoint format**

```
https://your-node-id-lowercase.ethereum.managedblockchain.us-east-1.amazonaws.com/<followed by HTTP path of the Consensus API>
```

For example: `https://nd-6eaj5va43jggnpxouzp7y47e4y.ethereum.managedblockchain.us-east-1.amazonaws.com/eth/v1/beacon/genesis`

### Making Consensus API calls using AWS SDK for JavaScript over HTTP
SDK for JavaScript over HTTP

The following example uses a JavaScript file for Node.js to make Consensus API calls by sending HTTP requests to the Ethereum node endpoint in Amazon Managed Blockchain (AMB).

Running the example script requires the following:
+ Node.js is installed on your machine. If you use an Amazon EC2 instance, see [Tutorial: Setting Up Node.js on an Amazon EC2 Instance](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-up-node-on-ec2-instance.html).
+ The Node package manager (npm) is used to install the AWS SDK for JavaScript. The script uses classes from these packages.

  ```
  npm install aws-sdk
  ```
+ The environment variables `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` must contain the credentials that are associated with the same account that created the node.

  Otherwise, the alternative is that the \$1/.aws/credentials file is populated.

**Example — Make a Consensus API call using AWS SDK for JavaScript with an HTTP connection to an Ethereum node in Amazon Managed Blockchain (AMB)**  

1. Copy the contents of the script that follows and save it to a file on your machine (for example, `consensus-ethereum-example.js`).

   **Contents of consensus-ethereum-example.js**

   ```
   const AWS = require('aws-sdk');
   const REGION = process.env.AWS_DEFAULT_REGION || 'us-east-1';
   
   async function signedManagedBlockchainRequest(endpoint, credentials, host) {
       const awsRequest = new AWS.HttpRequest(new AWS.Endpoint(endpoint), REGION);
       awsRequest.method = 'GET';
       awsRequest.headers['host'] = host;
       const signer = new AWS.Signers.V4(awsRequest, 'managedblockchain');
       signer.addAuthorization(credentials, new Date());
   
       return awsRequest
   }
   
   /**
    * Sends Consensus API requests to AMB Ethereum node.
    * @param {*} nodeId - Node ID
    * @param {*} consensusApi - Consensus API to invoke, such as "/eth/v1/beacon/genesis".
    * @param {*} credentials - AWS credentials.
    * @returns A promise with invocation result.
    */
   async function sendRequest(nodeId, consensusApi, credentials) {
       const host = `${nodeId}.ethereum.managedblockchain.${REGION}.amazonaws.com`
       const endpoint = `https://${host}${consensusApi}`;
       request = await signedManagedBlockchainRequest(endpoint, credentials, host)
       const client = new AWS.HttpClient();
       return  await  new Promise((resolve, reject) => {
           client.handleRequest(request, null, response => {
               let data = []
               response.on('data', chunk => {
                   data.push(chunk);
               });
               response.on('end', () => {
               var responseBody = Buffer.concat(data);
                   resolve(responseBody.toString('utf8'))
               });
           })
       });
   }
   
   const nodeId = process.env.NODE_ID;
   new AWS.CredentialProviderChain()
       .resolvePromise()
       .then(credentials => sendRequest(nodeId, '/eth/v1/beacon/states/finalized/root', credentials))
       .then(console.log)
       .catch(err => console.error('ERROR: ' + err))
   ```

1. Run the script to call the Consensus API method over HTTP on your Ethereum node.

   ```
   NODE_ID=nd-6eaj5va43jggnpxouzp7y47e4y AWS_DEFAULT_REGION=us-east-1 node consensus-ethereum-example.js
   ```

### Using awscurl to make Consensus API calls over HTTP
Using awscurl with HTTP

The following example uses [awscurl](https://pypi.org/project/awscurl/0.6/), which sends a signed HTTP request based on the credentials that you set for the AWS CLI. If you make your own HTTP requests, see [Signing AWS requests with Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html) in the *AWS General Reference*.

This example calls the ` /eth/v1/beacon/genesis` method, which takes an empty parameter block. You can replace this method and its parameters with any method listed in [Supported Consensus API methods](https://docs.aws.amazon.com/managed-blockchain/latest/ethereum-dev/supported-consensus-apis.html). Replace `your-node-id-lowercase` with the ID of a node in your account (for example, `nd-6eaj5va43jggnpxouzp7y47e4y`).

```
awscurl --service managedblockchain \
-X GET 'https://your-node-id-lowercase.ethereum.managedblockchain.us-east-1.amazonaws.com/eth/v1/beacon/genesis'
```

The command returns output similar to the following.

```
{"data":{"genesis_time":"1606824023","genesis_validators_root":"0x4b363db94e286120d76eb905340fdd4e54bfe9f06bf33ff6cf5ad27f511bfe95","genesis_fork_version":"0x00000000"}}
```

## Using token based access to make Consensus API calls to an Ethereum node
Example using Accessor tokens

You can use Accessor tokens to make Ethereum API calls to an Ethereum node as a convenient alternative to the Signature Version 4 (SigV4) signing process. You must provide a `BILLING_TOKEN` from one of the Accessor tokens that you create as a query parameter with the call. For more information on creating and managing Accessor tokens, see the topic on [Using token based access](https://docs.aws.amazon.com/managed-blockchain/latest/ethereum-dev/ethereum-tokens.html).

**Important**  
If you prioritize security and auditability over convenience, use the SigV4 signing process instead.
You can access the Ethereum APIs using Signature Version 4 (SigV4) and token based access. However, if you choose to use token based access, then any security benefits that are provided by using SigV4 are negated.
Never embed Accessor tokens in user-facing applications. 

The following examples demonstrate ways to make Ethereum Consensus API calls to an Ethereum node on Amazon Managed Blockchain (AMB) using token based access.

**Topics**
+ [

### Endpoint format for making Consensus API calls over HTTP using token based access
](#consensus-tba-api-endpoints)
+ [

### Making Consensus API calls using AWS SDK for JavaScript over HTTP using token based access
](#consensus-tba-connect-to-node-http-awsjssdk)
+ [

### Using awscurl to make Consensus API calls over HTTP using token based access
](#consensus-tba-connect-to-node-http)

### Endpoint format for making Consensus API calls over HTTP using token based access


An Ethereum node that's created using AMB Access Ethereum hosts one endpoint for HTTP connections. This endpoint conforms to the following patterns.

**Note**  
The node ID is case sensitive and must be lowercase where indicated, or a signature mismatch error occurs.

**HTTP endpoint format**

```
https://your-node-id-lowercase.t.ethereum.managedblockchain.us-east-1.amazonaws.com/<followed by HTTP path of the Consensus API>?billingtoken=your-billing-token
```

For example: `https://nd-6eaj5va43jggnpxouzp7y47e4y.t.ethereum.managedblockchain.us-east-1.amazonaws.com/eth/v1/beacon/genesis?billingtoken=n-MWY63ZJZU5HGNCMBQER7IN6OIU`

### Making Consensus API calls using AWS SDK for JavaScript over HTTP using token based access
SDK for JavaScript over HTTP

The following example uses a JavaScript file for Node.js to make Consensus API calls using token based access by sending HTTP requests to the Ethereum node endpoint in Amazon Managed Blockchain (AMB).

Running the example script requires the following:
+ Node.js is installed on your machine. If you use an Amazon EC2 instance, see [Tutorial: Setting Up Node.js on an Amazon EC2 Instance](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-up-node-on-ec2-instance.html).
+ The Node package manager (npm) is used to install the AWS SDK for JavaScript. The script uses classes from these packages.

  ```
  npm install aws-sdk
  ```
+ The environment variables `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` must contain the credentials that are associated with the same account that created the node.

  Otherwise, the alternative is that the \$1/.aws/credentials file is populated.

**Example — Make a Consensus API call using AWS SDK for JavaScript with an HTTP connection using token based access to an Ethereum node in Amazon Managed Blockchain (AMB)**  

1. Copy the contents of the script that follows and save it to a file on your machine (for example, `consensus-ethereum-example.js`).

   **Contents of consensus-ethereum-example.js**

   ```
   const AWS = require('aws-sdk');
   const REGION = process.env.AWS_DEFAULT_REGION || 'us-east-1';
   
   function getManagedBlockchainClient(){
       const endpoint = `https://managedblockchain.${REGION}.amazonaws.com`;
       const client = new AWS.ManagedBlockchain();
       client.setEndpoint(endpoint);
       return client;
   }
   
   async function getAccessTokenFromManagedBlockChain() {
       const client = getManagedBlockchainClient();
       const accessorType = { AccessorType : "BILLING_TOKEN"};
       const networkType = { NetworkType : "ETHEREUM_MAINNET"};
       const tokenResponse = await new Promise((resolve, reject) => {
           client.createAccessor( accessorType, networkType, (err, data) => {
               if (err) {
                   console.error(err);
                   reject(err.message);
               }
               else {
   		resolve(data);
   	    }
           });
       });
       return tokenResponse;
   }
   
   async function deleteAccessTokenFromManagedBlockChain(accessorId) {
       const client = getManagedBlockchainClient();
       const id = { AccessorId : accessorId };
       const tokenResponse = await new Promise((resolve, reject) => {
           client.deleteAccessor( id, (err, data) => {
               if (err) {
                   console.error(err);
                   reject(err.message);
               }
               else resolve(data);
           });
       });
   }
   
   function getManagedBlockchainRequest(endpoint, host) {
   
       const awsRequest = new AWS.HttpRequest(new AWS.Endpoint(endpoint), REGION);
       awsRequest.method = "GET";
       awsRequest.headers['host'] = host;
       awsRequest.headers['Content-Type'] = 'application/json'
   
       return awsRequest
   }
   
   /**
    * Sends Consensus API requests to AMB Ethereum node.
    * @param {*} nodeId - Node ID
    * @param {*} consensusApi - Consensus API to invoke, such as "/eth/v1/beacon/genesis".
    * @param {*} credentials - AWS credentials.
    * @returns A promise with invocation result.
    */
   async function sendRequest(nodeId, consensusApi) {
       const token = await getAccessTokenFromManagedBlockChain();
   
       const host = `${nodeId}.t.ethereum.managedblockchain.${REGION}.amazonaws.com`;
       const endpoint = `https://${host}${consensusApi}?billingtoken=${token.BillingToken}`;
       request = getManagedBlockchainRequest(endpoint, host)
       const client = new AWS.HttpClient();
   
       const promise =  await  new Promise((resolve, reject) => {
           client.handleRequest(request, null, response => {
               let data = []
               response.on('data', chunk => {
                   data.push(chunk);
               });
               response.on('end', () => {
               var responseBody = Buffer.concat(data);
                   resolve(responseBody.toString('utf8'))
               });
           })
       });
       deleteAccessTokenFromManagedBlockChain(token.AccessorId);
       return promise;
   }
   
   const nodeId = process.env.NODE_ID;
   new AWS.CredentialProviderChain()
       .resolvePromise()
       .then(() => sendRequest(nodeId, '/eth/v1/beacon/states/finalized/root'))
       .then(console.log)
       .catch(err => console.error('ERROR: ' + err))
   ```

1. Run the script to call the Consensus API method over HTTP on your Ethereum node.

   ```
   NODE_ID=nd-6eaj5va43jggnpxouzp7y47e4y AWS_DEFAULT_REGION=us-east-1 node consensus-ethereum-example.js
   ```

### Using awscurl to make Consensus API calls over HTTP using token based access
Using awscurl with HTTP

The following example uses [awscurl](https://pypi.org/project/awscurl/0.6/), which sends a signed HTTP request based on the credentials that you set for the AWS CLI.

This example calls the ` /eth/v1/beacon/genesis` method, which takes an empty parameter block. You can replace this method and its parameters with any method listed in [Supported Consensus API methods](https://docs.aws.amazon.com/managed-blockchain/latest/ethereum-dev/supported-consensus-apis.html). Replace `your-node-id-lowercase` with the ID of a node in your account (for example, `nd-6eaj5va43jggnpxouzp7y47e4y`).

```
awscurl --service managedblockchain \
-X GET 'https://your-node-id-lowercase.t.ethereum.managedblockchain.us-east-1.amazonaws.com/eth/v1/beacon/genesis?billingtoken=your-billing-token'
```

The command returns output similar to the following.

```
{"data":{"root":"0x71ef3f7c2470a7564af6eb8232855b602401cc9acdfc02c9fdf699e643cf8ba4"}}
```