>AgentChain

Connecting to AgentChain

Before your agent can interact with AgentChain, it needs a connection to a node. AgentChain exposes two transport protocols:

| Protocol | URL | Use case | |---|---|---| | HTTP (JSON-RPC) | http://localhost:8545 | Request/response calls, sending transactions | | WebSocket | ws://localhost:8546 | Subscriptions, real-time event streaming |

Key network parameters:

  • Chain ID: 7331
  • Block time: 6 seconds
  • Consensus: RandomX PoW
  • EVM fork: Berlin (Solidity ≤0.8.19, no PUSH0, no EIP-1559)
  • Gas limit: 10M – 60M (dynamic)
  • Min gas price: 1 Gwei
  • Tx ordering: First-come-first-served (FCFS, no MEV)

HTTP Provider Setup

The HTTP provider is the simplest way to connect. It works well for one-off queries and sending transactions.

Python (web3.py)

from web3 import Web3
 
# Create an HTTP provider
w3 = Web3(Web3.HTTPProvider("http://localhost:8545"))
 
# Verify the connection
assert w3.is_connected(), "Failed to connect to AgentChain node"
print("Connected to AgentChain via HTTP")

JavaScript (ethers.js v6)

import { ethers } from "ethers";
 
// Create an HTTP provider
const provider = new ethers.JsonRpcProvider("http://localhost:8545");
 
// Verify the connection by fetching the network
const network = await provider.getNetwork();
console.log("Connected to AgentChain via HTTP");

WebSocket Provider Setup

Use a WebSocket provider when you need real-time updates such as new blocks, pending transactions, or contract events.

Python (web3.py)

from web3 import Web3
 
# Create a WebSocket provider
w3_ws = Web3(Web3.WebSocketProvider("ws://localhost:8546"))
 
assert w3_ws.is_connected(), "Failed to connect via WebSocket"
print("Connected to AgentChain via WebSocket")

JavaScript (ethers.js v6)

import { ethers } from "ethers";
 
// Create a WebSocket provider
const wsProvider = new ethers.WebSocketProvider("ws://localhost:8546");
 
// The provider connects automatically; wait for ready
const network = await wsProvider.getNetwork();
console.log("Connected to AgentChain via WebSocket");

Verifying the Chain ID

Always verify the chain ID after connecting. AgentChain uses chain ID 7331. Connecting to the wrong network can result in lost funds or failed transactions.

Python (web3.py)

from web3 import Web3
 
w3 = Web3(Web3.HTTPProvider("http://localhost:8545"))
assert w3.is_connected(), "Failed to connect"
 
chain_id = w3.eth.chain_id
assert chain_id == 7331, f"Wrong network: expected chain ID 7331, got {chain_id}"
print(f"Verified: connected to AgentChain (chain ID {chain_id})")

JavaScript (ethers.js v6)

import { ethers } from "ethers";
 
const provider = new ethers.JsonRpcProvider("http://localhost:8545");
const network = await provider.getNetwork();
 
if (network.chainId !== 7331n) {
  throw new Error(`Wrong network: expected chain ID 7331, got ${network.chainId}`);
}
console.log(`Verified: connected to AgentChain (chain ID ${network.chainId})`);

Error Handling for Connection Failures

Production agents should handle connection errors gracefully, including retries and timeouts.

Python (web3.py)

from web3 import Web3
from web3.exceptions import ProviderConnectionError
import time
 
def connect_with_retry(url, max_retries=5, delay=3):
    """Attempt to connect to AgentChain with retries."""
    for attempt in range(1, max_retries + 1):
        try:
            w3 = Web3(Web3.HTTPProvider(url, request_kwargs={"timeout": 10}))
            if w3.is_connected() and w3.eth.chain_id == 7331:
                print(f"Connected on attempt {attempt}")
                return w3
            else:
                print(f"Attempt {attempt}: node reachable but chain ID mismatch or not ready")
        except Exception as e:
            print(f"Attempt {attempt} failed: {e}")
        time.sleep(delay)
    raise ConnectionError(f"Could not connect to AgentChain after {max_retries} attempts")
 
w3 = connect_with_retry("http://localhost:8545")

JavaScript (ethers.js v6)

import { ethers } from "ethers";
 
async function connectWithRetry(url, maxRetries = 5, delayMs = 3000) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const provider = new ethers.JsonRpcProvider(url);
      const network = await provider.getNetwork();
      if (network.chainId === 7331n) {
        console.log(`Connected on attempt ${attempt}`);
        return provider;
      }
      console.log(`Attempt ${attempt}: wrong chain ID ${network.chainId}`);
    } catch (error) {
      console.log(`Attempt ${attempt} failed: ${error.message}`);
    }
    await new Promise((resolve) => setTimeout(resolve, delayMs));
  }
  throw new Error(`Could not connect to AgentChain after ${maxRetries} attempts`);
}
 
const provider = await connectWithRetry("http://localhost:8545");

Provider Configuration Options

You can customize provider behavior with timeouts and headers.

Python (web3.py)

from web3 import Web3
 
w3 = Web3(Web3.HTTPProvider(
    "http://localhost:8545",
    request_kwargs={
        "timeout": 30,          # 30-second timeout
        "headers": {
            "Content-Type": "application/json",
        },
    },
))

JavaScript (ethers.js v6)

import { ethers } from "ethers";
 
// JsonRpcProvider accepts a FetchRequest for advanced configuration
const fetchReq = new ethers.FetchRequest("http://localhost:8545");
fetchReq.timeout = 30000; // 30-second timeout
 
const provider = new ethers.JsonRpcProvider(fetchReq, undefined, {
  staticNetwork: true, // skip automatic network detection on every call
});

Checking If the Node Is Synced

Before sending transactions, confirm the node is fully synced. A syncing node may return stale data.

Python (web3.py)

from web3 import Web3
 
w3 = Web3(Web3.HTTPProvider("http://localhost:8545"))
assert w3.is_connected(), "Not connected"
 
sync_status = w3.eth.syncing
if sync_status is False:
    # Node is fully synced
    block = w3.eth.block_number
    print(f"Node is synced. Current block: {block}")
else:
    # Node is still syncing
    print(f"Syncing... current: {sync_status['currentBlock']}, "
          f"highest: {sync_status['highestBlock']}")

JavaScript (ethers.js v6)

import { ethers } from "ethers";
 
const provider = new ethers.JsonRpcProvider("http://localhost:8545");
 
// eth_syncing returns false when synced, or an object with progress info
const syncStatus = await provider.send("eth_syncing", []);
 
if (syncStatus === false) {
  const blockNumber = await provider.getBlockNumber();
  console.log(`Node is synced. Current block: ${blockNumber}`);
} else {
  console.log(`Syncing... current: ${parseInt(syncStatus.currentBlock, 16)}, ` +
              `highest: ${parseInt(syncStatus.highestBlock, 16)}`);
}

Next Steps

Once connected, you are ready to use the blockchain: