# EVM JSON-RPC

## Ethereum-Compatible API for Goliath Network

The Goliath EVM Gateway provides a fully Ethereum-compatible JSON-RPC interface, allowing seamless integration with existing Ethereum tools, libraries, and applications. This API enables developers to interact with Goliath using familiar Web3 tooling.

## 🌐 Overview

### Key Features

* **Full Ethereum Compatibility**: Support for all standard Ethereum JSON-RPC methods
* **High Performance**: Sub-second response times with 100,000+ TPS capacity
* **WebSocket Support**: Real-time event subscriptions and updates
* **Low Latency**: Optimized for fast transaction processing
* **Reliable Infrastructure**: 99.99% uptime SLA

### Endpoints

| Network     | HTTP Endpoint                                                        | WebSocket Endpoint                 |
| ----------- | -------------------------------------------------------------------- | ---------------------------------- |
| **Testnet** | [`https://rpc.testnet.goliath.net`](https://rpc.testnet.goliath.net) | `wss://rpc.testnet.goliath.net/ws` |
| **Mainnet** | [`https://rpc.goliath.net`](https://rpc.goliath.net)                 | `wss://rpc.goliath.net`            |

## 🔧 Quick Start

### Using curl

```bash
curl -X POST https://rpc.testnet.goliath.net \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "eth_blockNumber",
    "params": [],
    "id": 1
  }'
```

### Using Web3.js

```javascript
const Web3 = require('web3');
const web3 = new Web3('https://rpc.testnet.goliath.net');

// Get latest block number
const blockNumber = await web3.eth.getBlockNumber();
console.log('Latest block:', blockNumber);

// Get account balance
const balance = await web3.eth.getBalance('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0');
console.log('Balance:', web3.utils.fromWei(balance, 'ether'), 'XCN');
```

### Using Ethers.js

```javascript
const { ethers } = require('ethers');
const provider = new ethers.JsonRpcProvider('https://rpc.testnet.goliath.net');

// Get network info
const network = await provider.getNetwork();
console.log('Connected to:', network.name, 'Chain ID:', network.chainId);

// Get gas price
const gasPrice = await provider.getFeeData();
console.log('Gas price:', ethers.formatUnits(gasPrice.gasPrice, 'gwei'), 'Gwei');
```

## 📚 Core Methods

### Network Information

#### eth\_chainId

Returns the chain ID of the network.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_chainId",
  "params": [],
  "id": 1
}
```

**Response (Mainnet):**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": "0x147"  // 327 in decimal for mainnet
}
```

**Response (Testnet):**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": "0x22c5"  // 8901 in decimal for testnet
}
```

#### net\_version

Returns the network ID.

```json
{
  "jsonrpc": "2.0",
  "method": "net_version",
  "params": [],
  "id": 1
}
```

### Block Methods

#### eth\_blockNumber

Returns the number of the most recent block.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_blockNumber",
  "params": [],
  "id": 1
}
```

#### eth\_getBlockByNumber

Returns information about a block by block number.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_getBlockByNumber",
  "params": ["latest", true],
  "id": 1
}
```

Parameters:

* `block number`: Block number or "latest", "earliest", "pending"
* `boolean`: If true, returns full transaction objects

#### eth\_getBlockByHash

Returns information about a block by hash.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_getBlockByHash",
  "params": ["0x...", true],
  "id": 1
}
```

### Account Methods

#### eth\_getBalance

Returns the balance of an account.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_getBalance",
  "params": ["0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0", "latest"],
  "id": 1
}
```

#### eth\_getTransactionCount

Returns the number of transactions sent from an address (nonce).

```json
{
  "jsonrpc": "2.0",
  "method": "eth_getTransactionCount",
  "params": ["0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0", "latest"],
  "id": 1
}
```

#### eth\_getCode

Returns the code at an address (for smart contracts).

```json
{
  "jsonrpc": "2.0",
  "method": "eth_getCode",
  "params": ["0x...", "latest"],
  "id": 1
}
```

### Transaction Methods

#### eth\_sendRawTransaction

Submits a signed transaction to the network.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_sendRawTransaction",
  "params": ["0xf86c..."],
  "id": 1
}
```

#### eth\_getTransactionByHash

Returns information about a transaction by hash.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_getTransactionByHash",
  "params": ["0x..."],
  "id": 1
}
```

#### eth\_getTransactionReceipt

Returns the receipt of a transaction by hash.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_getTransactionReceipt",
  "params": ["0x..."],
  "id": 1
}
```

### Smart Contract Methods

#### eth\_call

Executes a call without creating a transaction.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_call",
  "params": [
    {
      "to": "0x...",
      "data": "0x..."
    },
    "latest"
  ],
  "id": 1
}
```

#### eth\_estimateGas

Estimates the gas needed for a transaction.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_estimateGas",
  "params": [
    {
      "from": "0x...",
      "to": "0x...",
      "value": "0x...",
      "data": "0x..."
    }
  ],
  "id": 1
}
```

{% hint style="info" %}
**Important:** On Goliath, `eth_estimateGas` returns \~587,000 for transfers to addresses that do not yet exist (lazy account creation), compared to \~21,000 for existing addresses. Always call this method before submitting transactions rather than hardcoding a gas limit. See [Lazy Account Creation](https://github.com/Onyx-Protocol/goliath-docs/blob/main/apis/developer-guide/smart-contracts/lazy-create-gas.md).
{% endhint %}

### Gas and Fee Methods

#### eth\_gasPrice

Returns the current gas price in wei.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_gasPrice",
  "params": [],
  "id": 1
}
```

#### eth\_maxPriorityFeePerGas

Returns the current max priority fee per gas.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_maxPriorityFeePerGas",
  "params": [],
  "id": 1
}
```

### Event and Log Methods

#### eth\_getLogs

Returns logs matching the filter criteria.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_getLogs",
  "params": [
    {
      "fromBlock": "0x1",
      "toBlock": "latest",
      "address": "0x...",
      "topics": ["0x..."]
    }
  ],
  "id": 1
}
```

#### eth\_newFilter

Creates a filter for logs.

```json
{
  "jsonrpc": "2.0",
  "method": "eth_newFilter",
  "params": [
    {
      "fromBlock": "latest",
      "address": "0x...",
      "topics": ["0x..."]
    }
  ],
  "id": 1
}
```

## 🌐 WebSocket Subscriptions

### Subscribing to Events

```javascript
const WebSocket = require('ws');
const ws = new WebSocket('wss://rpc.testnet.goliath.net/ws');

ws.on('open', () => {
  // Subscribe to new blocks
  ws.send(JSON.stringify({
    jsonrpc: '2.0',
    method: 'eth_subscribe',
    params: ['newHeads'],
    id: 1
  }));
});

ws.on('message', (data) => {
  const response = JSON.parse(data);
  console.log('New block:', response.params.result);
});
```

### Subscription Types

| Type                  | Description                |
| --------------------- | -------------------------- |
| `newHeads`            | New block headers          |
| `logs`                | Smart contract events      |
| `pendingTransactions` | Pending transaction hashes |
| `syncing`             | Sync status updates        |

## ⛽ Gas Optimization

### Gas Price Recommendations

| Priority     | Gas Price | Confirmation Time |
| ------------ | --------- | ----------------- |
| **Low**      | 0.5 Gwei  | 10-30 seconds     |
| **Standard** | 1 Gwei    | 3-10 seconds      |
| **Fast**     | 2 Gwei    | < 3 seconds       |
| **Instant**  | 5 Gwei    | Next block        |

### Gas Limits

| Operation                    | Gas Limit     | Cost (XCN) |
| ---------------------------- | ------------- | ---------- |
| **Simple Transfer**          | 21,000        | \~0.000021 |
| **Transfer to New Address**  | **\~587,000** | \~0.000587 |
| **ERC-20 Transfer**          | 65,000        | \~0.000065 |
| **Smart Contract Deploy**    | 500,000+      | \~0.0005+  |
| **Complex DeFi Interaction** | 300,000+      | \~0.0003+  |

{% hint style="warning" %}
**Lazy Account Creation:** Sending XCN or tokens to an address that does not yet exist on Goliath triggers automatic account creation ("lazy-create"), which requires \~587,000 gas instead of 21,000. Always use `eth_estimateGas` rather than hardcoding gas limits. See the [Lazy Account Creation Guide](https://github.com/Onyx-Protocol/goliath-docs/blob/main/apis/developer-guide/smart-contracts/lazy-create-gas.md) for full details.
{% endhint %}

## 🔒 Rate Limits

### Public Endpoints

| Limit Type                | Value     |
| ------------------------- | --------- |
| **Requests per second**   | 100       |
| **Requests per minute**   | 3,000     |
| **WebSocket connections** | 10 per IP |
| **Batch request size**    | 100 calls |

### Enterprise Limits

Contact us for enterprise-grade limits with:

* Unlimited requests
* Dedicated infrastructure
* Custom SLAs
* Priority support

## 🆘 Error Codes

| Code     | Message              | Description          |
| -------- | -------------------- | -------------------- |
| `-32700` | Parse error          | Invalid JSON         |
| `-32600` | Invalid request      | Invalid method       |
| `-32601` | Method not found     | Method doesn't exist |
| `-32602` | Invalid params       | Invalid parameters   |
| `-32603` | Internal error       | Server error         |
| `-32000` | Execution reverted   | Smart contract error |
| `-32001` | Resource not found   | Block/tx not found   |
| `-32002` | Resource unavailable | Node syncing         |
| `-32003` | Transaction rejected | Invalid transaction  |
| `-32004` | Method not supported | Unsupported method   |
| `-32005` | Rate limit exceeded  | Too many requests    |

## 📚 Advanced Features

### Batch Requests

Send multiple requests in a single call:

```json
[
  {
    "jsonrpc": "2.0",
    "method": "eth_blockNumber",
    "params": [],
    "id": 1
  },
  {
    "jsonrpc": "2.0",
    "method": "eth_gasPrice",
    "params": [],
    "id": 2
  }
]
```

### Custom RPC Methods

Goliath extends the standard Ethereum RPC with:

| Method                    | Description           |
| ------------------------- | --------------------- |
| `goliath_getNodeInfo`     | Node information      |
| `goliath_getNetworkStats` | Network statistics    |
| `goliath_getValidators`   | Active validators     |
| `goliath_getFeeSchedule`  | Current fee structure |

## 🔧 Integration Examples

### MetaMask Configuration

**Mainnet:**

```javascript
await window.ethereum.request({
  method: 'wallet_addEthereumChain',
  params: [{
    chainId: '0x147',
    chainName: 'Goliath Mainnet',
    nativeCurrency: {
      name: 'XCN',
      symbol: 'XCN',
      decimals: 18
    },
    rpcUrls: ['https://rpc.goliath.net'],
    blockExplorerUrls: ['https://explorer.goliath.net']
  }]
});
```

**Testnet:**

```javascript
await window.ethereum.request({
  method: 'wallet_addEthereumChain',
  params: [{
    chainId: '0x22c5',
    chainName: 'Goliath Testnet',
    nativeCurrency: {
      name: 'XCN',
      symbol: 'XCN',
      decimals: 18
    },
    rpcUrls: ['https://rpc.testnet.goliath.net'],
    blockExplorerUrls: ['https://testnet.explorer.goliath.net']
  }]
});
```

### Hardhat Configuration

```javascript
module.exports = {
  networks: {
    goliathMainnet: {
      url: "https://rpc.goliath.net",
      chainId: 327,
      accounts: [process.env.PRIVATE_KEY]
    },
    goliathTestnet: {
      url: "https://rpc.testnet.goliath.net",
      chainId: 8901,
      accounts: [process.env.PRIVATE_KEY]
    }
  }
};
```

## 🎯 Best Practices

### Connection Management

1. **Use connection pooling** for high-volume applications
2. **Implement retry logic** with exponential backoff
3. **Cache responses** when appropriate
4. **Monitor rate limits** to avoid throttling

### Error Handling

```javascript
try {
  const result = await web3.eth.call(transaction);
} catch (error) {
  if (error.code === -32000) {
    console.error('Transaction reverted:', error.message);
  } else if (error.code === -32005) {
    console.error('Rate limit exceeded, retry later');
  } else {
    console.error('Unexpected error:', error);
  }
}
```

## 🤝 Support

* [**Telegram**](https://t.me/Onyx): Developer support channel
* [**GitHub**](https://github.com/Onyx-Protocol): Report issues and bugs
* **Enterprise**: Contact for dedicated support

***

*The Goliath EVM Gateway provides seamless Ethereum compatibility with enterprise-grade performance and reliability.*
