## JSON-RPC-Endpoint > Source: https://docs.bnbchain.org/bnb-smart-chain/developers/json_rpc/json-rpc-endpoint/ --- title: JSON-RPC-Endpoint - BSC Develop --- # JSON-RPC-Endpoint JSON-RPC endpoints refers to the network location where a program could transfer its RPC requests to access server data. Once you connect a decentralized application to an RPC endpoint, you can access the functionalities of different operations, which could enable real-time usage of blockchain data. BNB Chain provides several RPC endpoints for connectinto both its Minent and Testnet. In this section, we list the JSON-RPC endpoints that can be used for connecting to BNB Smart Chain. ## One-click adding BSC network Visit the [ChainList](https://chainlist.org/chain/56) and connect to your wallet, it will add alive RPC endpoints. ## RPC Endpoints for BNB Smart Chain *The rate limit of BSC endpoint on Testnet and Mainnet is **10K/5min**.* `eth_getLogs` is disabled on below Mainnet endpoints, please use 3rd party endpoints from **[here](https://chainlist.org/chain/56)**. If you need to pull logs frequently, we recommend using WebSockets to push new logs to you when they are available. ### BSC Mainnet (ChainID 0x38, 56 in decimal) * https://bsc-dataseed.bnbchain.org * https://bsc-dataseed.nariox.org * https://bsc-dataseed.defibit.io * https://bsc-dataseed.ninicoin.io * https://bsc.nodereal.io * https://bsc-dataseed-public.bnbchain.org * https://rpc-bnb.blockmachine.io You could find more endpoints from **[here](https://chainlist.org/chain/56)**. ### BSC Testnet (ChainID 0x61, 97 in decimal) * https://bsc-testnet-dataseed.bnbchain.org * https://bsc-testnet.bnbchain.org * https://bsc-prebsc-dataseed.bnbchain.org ### RPC Providers * **Moralis:** * **NodeReal:** * **Ankr:** * **Chainstack:** * **GetBlock:** * **QuickNode:** * **BlockVision:** * **4EVERLAND:** * **NOWNodes:** * **dRPC:** * **All That Node:** * **Alchemy:** * **Blockmachine:** ### Starting HTTP JSON-RPC You can start the HTTP JSON-RPC with the --http flag ```bash ## mainnet geth attach https://bsc-dataseed.bnbchain.org ## testnet geth attach https://bsc-testnet-dataseed.bnbchain.org ``` ## JSON-RPC API List BSC (BNB Smart Chain) is EVM-compatible and strives to be as compatible as possible with the Go-Ethereum API. However, BSC also has unique features, such as faster finality and the storage of blob data on the execution layer, which require their own specialized APIs. ### Geth(Go-Ethereum) API BSC is nearly fully compatible with the Geth APIs. Any exceptions or incompatibilities are explicitly listed. If you're looking for detailed usage of a specific API, you will most likely find the answer in the following link: [Geth JSON-RPC API documentation](https://geth.ethereum.org/docs/interacting-with-geth/rpc). ### Finality Ethereum's PoS consensus protocol, known as "Gasper," is built on LMD-GHOST (a fork choice rule) and Casper FFG (a finality gadget). Similarly, BSC's consensus protocol, called "Parlia," is constructed on top of a difficulty-based fork choice mechanism with FFG, as described in [BEP-126](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP126.md). To further enhance BSC's throughput, validators are allowed to produce multiple consecutive blocks, as explained in [BEP-341](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-341.md). These differences result in BSC having a unique finality process compared to Ethereum. For more details, please refer to the the following doc: [BSC Finality API](bsc-api-list.md#finality-api). ### Blob Bsc implement EIP-4844, which support Shard Blob Transactions, as described in [BEP-336](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-336.md). For more details, please refer to the the following doc: [BSC Blob API](bsc-api-list.md#blob-api). ### Other BSC API Bsc implement some others apis, as described in: [BSC API](bsc-api-list.md#others). ## One-click adding BSC network Visit the [ChainList](https://chainlist.org/chain/56) and connect to your wallet, it will add alive RPC endpoints. ## RPC Endpoints for BNB Smart Chain *The rate limit of BSC endpoint on Testnet and Mainnet is **10K/5min**.* `eth_getLogs` is disabled on below Mainnet endpoints, please use 3rd party endpoints from **[here](https://chainlist.org/chain/56)**. If you need to pull logs frequently, we recommend using WebSockets to push new logs to you when they are available. ### BSC Mainnet (ChainID 0x38, 56 in decimal) * https://bsc-dataseed.bnbchain.org * https://bsc-dataseed.nariox.org * https://bsc-dataseed.defibit.io * https://bsc-dataseed.ninicoin.io * https://bsc.nodereal.io * https://bsc-dataseed-public.bnbchain.org * https://rpc-bnb.blockmachine.io You could find more endpoints from **[here](https://chainlist.org/chain/56)**. ### BSC Testnet (ChainID 0x61, 97 in decimal) * https://bsc-testnet-dataseed.bnbchain.org * https://bsc-testnet.bnbchain.org * https://bsc-prebsc-dataseed.bnbchain.org ### RPC Providers * **Moralis:** * **NodeReal:** * **Ankr:** * **Chainstack:** * **GetBlock:** * **QuickNode:** * **BlockVision:** * **4EVERLAND:** * **NOWNodes:** * **dRPC:** * **All That Node:** * **Alchemy:** * **Blockmachine:** ### Starting HTTP JSON-RPC You can start the HTTP JSON-RPC with the --http flag ```bash ## mainnet geth attach https://bsc-dataseed.bnbchain.org ## testnet geth attach https://bsc-testnet-dataseed.bnbchain.org ``` ## JSON-RPC API List BSC (BNB Smart Chain) is EVM-compatible and strives to be as compatible as possible with the Go-Ethereum API. However, BSC also has unique features, such as faster finality and the storage of blob data on the execution layer, which require their own specialized APIs. ### Geth(Go-Ethereum) API BSC is nearly fully compatible with the Geth APIs. Any exceptions or incompatibilities are explicitly listed. If you're looking for detailed usage of a specific API, you will most likely find the answer in the following link: [Geth JSON-RPC API documentation](https://geth.ethereum.org/docs/interacting-with-geth/rpc). ### Finality Ethereum's PoS consensus protocol, known as "Gasper," is built on LMD-GHOST (a fork choice rule) and Casper FFG (a finality gadget). Similarly, BSC's consensus protocol, called "Parlia," is constructed on top of a difficulty-based fork choice mechanism with FFG, as described in [BEP-126](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP126.md). To further enhance BSC's throughput, validators are allowed to produce multiple consecutive blocks, as explained in [BEP-341](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-341.md). These differences result in BSC having a unique finality process compared to Ethereum. For more details, please refer to the the following doc: [BSC Finality API](bsc-api-list.md#finality-api). ### Blob Bsc implement EIP-4844, which support Shard Blob Transactions, as described in [BEP-336](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-336.md). For more details, please refer to the the following doc: [BSC Blob API](bsc-api-list.md#blob-api). ### Other BSC API Bsc implement some others apis, as described in: [BSC API](bsc-api-list.md#others). ## One-click adding BSC network Visit the [ChainList](https://chainlist.org/chain/56) and connect to your wallet, it will add alive RPC endpoints. ## RPC Endpoints for BNB Smart Chain *The rate limit of BSC endpoint on Testnet and Mainnet is **10K/5min**.* `eth_getLogs` is disabled on below Mainnet endpoints, please use 3rd party endpoints from **[here](https://chainlist.org/chain/56)**. If you need to pull logs frequently, we recommend using WebSockets to push new logs to you when they are available. ### BSC Mainnet (ChainID 0x38, 56 in decimal) * https://bsc-dataseed.bnbchain.org * https://bsc-dataseed.nariox.org * https://bsc-dataseed.defibit.io * https://bsc-dataseed.ninicoin.io * https://bsc.nodereal.io * https://bsc-dataseed-public.bnbchain.org * https://rpc-bnb.blockmachine.io You could find more endpoints from **[here](https://chainlist.org/chain/56)**. ### BSC Testnet (ChainID 0x61, 97 in decimal) * https://bsc-testnet-dataseed.bnbchain.org * https://bsc-testnet.bnbchain.org * https://bsc-prebsc-dataseed.bnbchain.org ### RPC Providers * **Moralis:** * **NodeReal:** * **Ankr:** * **Chainstack:** * **GetBlock:** * **QuickNode:** * **BlockVision:** * **4EVERLAND:** * **NOWNodes:** * **dRPC:** * **All That Node:** * **Alchemy:** * **Blockmachine:** ### Starting HTTP JSON-RPC You can start the HTTP JSON-RPC with the --http flag ```bash ## mainnet geth attach https://bsc-dataseed.bnbchain.org ## testnet geth attach https://bsc-testnet-dataseed.bnbchain.org ``` ## JSON-RPC API List BSC (BNB Smart Chain) is EVM-compatible and strives to be as compatible as possible with the Go-Ethereum API. However, BSC also has unique features, such as faster finality and the storage of blob data on the execution layer, which require their own specialized APIs. ### Geth(Go-Ethereum) API BSC is nearly fully compatible with the Geth APIs. Any exceptions or incompatibilities are explicitly listed. If you're looking for detailed usage of a specific API, you will most likely find the answer in the following link: [Geth JSON-RPC API documentation](https://geth.ethereum.org/docs/interacting-with-geth/rpc). ### Finality Ethereum's PoS consensus protocol, known as "Gasper," is built on LMD-GHOST (a fork choice rule) and Casper FFG (a finality gadget). Similarly, BSC's consensus protocol, called "Parlia," is constructed on top of a difficulty-based fork choice mechanism with FFG, as described in [BEP-126](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP126.md). To further enhance BSC's throughput, validators are allowed to produce multiple consecutive blocks, as explained in [BEP-341](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-341.md). These differences result in BSC having a unique finality process compared to Ethereum. For more details, please refer to the the following doc: [BSC Finality API](bsc-api-list.md#finality-api). ### Blob Bsc implement EIP-4844, which support Shard Blob Transactions, as described in [BEP-336](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-336.md). For more details, please refer to the the following doc: [BSC Blob API](bsc-api-list.md#blob-api). ### Other BSC API Bsc implement some others apis, as described in: [BSC API](bsc-api-list.md#others). ## One-click adding BSC network Visit the [ChainList](https://chainlist.org/chain/56) and connect to your wallet, it will add alive RPC endpoints. ## RPC Endpoints for BNB Smart Chain *The rate limit of BSC endpoint on Testnet and Mainnet is **10K/5min**.* `eth_getLogs` is disabled on below Mainnet endpoints, please use 3rd party endpoints from **[here](https://chainlist.org/chain/56)**. If you need to pull logs frequently, we recommend using WebSockets to push new logs to you when they are available. ### BSC Mainnet (ChainID 0x38, 56 in decimal) * https://bsc-dataseed.bnbchain.org * https://bsc-dataseed.nariox.org * https://bsc-dataseed.defibit.io * https://bsc-dataseed.ninicoin.io * https://bsc.nodereal.io * https://bsc-dataseed-public.bnbchain.org * https://rpc-bnb.blockmachine.io You could find more endpoints from **[here](https://chainlist.org/chain/56)**. ### BSC Testnet (ChainID 0x61, 97 in decimal) * https://bsc-testnet-dataseed.bnbchain.org * https://bsc-testnet.bnbchain.org * https://bsc-prebsc-dataseed.bnbchain.org ### RPC Providers * **Moralis:** * **NodeReal:** * **Ankr:** * **Chainstack:** * **GetBlock:** * **QuickNode:** * **BlockVision:** * **4EVERLAND:** * **NOWNodes:** * **dRPC:** * **All That Node:** * **Alchemy:** * **Blockmachine:** ### Starting HTTP JSON-RPC You can start the HTTP JSON-RPC with the --http flag ```bash ## mainnet geth attach https://bsc-dataseed.bnbchain.org ## testnet geth attach https://bsc-testnet-dataseed.bnbchain.org ``` ## JSON-RPC API List BSC (BNB Smart Chain) is EVM-compatible and strives to be as compatible as possible with the Go-Ethereum API. However, BSC also has unique features, such as faster finality and the storage of blob data on the execution layer, which require their own specialized APIs. ### Geth(Go-Ethereum) API BSC is nearly fully compatible with the Geth APIs. Any exceptions or incompatibilities are explicitly listed. If you're looking for detailed usage of a specific API, you will most likely find the answer in the following link: [Geth JSON-RPC API documentation](https://geth.ethereum.org/docs/interacting-with-geth/rpc). ### Finality Ethereum's PoS consensus protocol, known as "Gasper," is built on LMD-GHOST (a fork choice rule) and Casper FFG (a finality gadget). Similarly, BSC's consensus protocol, called "Parlia," is constructed on top of a difficulty-based fork choice mechanism with FFG, as described in [BEP-126](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP126.md). To further enhance BSC's throughput, validators are allowed to produce multiple consecutive blocks, as explained in [BEP-341](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-341.md). These differences result in BSC having a unique finality process compared to Ethereum. For more details, please refer to the the following doc: [BSC Finality API](bsc-api-list.md#finality-api). ### Blob Bsc implement EIP-4844, which support Shard Blob Transactions, as described in [BEP-336](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-336.md). For more details, please refer to the the following doc: [BSC Blob API](bsc-api-list.md#blob-api). ### Other BSC API Bsc implement some others apis, as described in: [BSC API](bsc-api-list.md#others). ## One-click adding BSC network Visit the [ChainList](https://chainlist.org/chain/56) and connect to your wallet, it will add alive RPC endpoints. ## RPC Endpoints for BNB Smart Chain *The rate limit of BSC endpoint on Testnet and Mainnet is **10K/5min**.* `eth_getLogs` is disabled on below Mainnet endpoints, please use 3rd party endpoints from **[here](https://chainlist.org/chain/56)**. If you need to pull logs frequently, we recommend using WebSockets to push new logs to you when they are available. ### BSC Mainnet (ChainID 0x38, 56 in decimal) * https://bsc-dataseed.bnbchain.org * https://bsc-dataseed.nariox.org * https://bsc-dataseed.defibit.io * https://bsc-dataseed.ninicoin.io * https://bsc.nodereal.io * https://bsc-dataseed-public.bnbchain.org * https://rpc-bnb.blockmachine.io You could find more endpoints from **[here](https://chainlist.org/chain/56)**. ### BSC Testnet (ChainID 0x61, 97 in decimal) * https://bsc-testnet-dataseed.bnbchain.org * https://bsc-testnet.bnbchain.org * https://bsc-prebsc-dataseed.bnbchain.org ### RPC Providers * **Moralis:** * **NodeReal:** * **Ankr:** * **Chainstack:** * **GetBlock:** * **QuickNode:** * **BlockVision:** * **4EVERLAND:** * **NOWNodes:** * **dRPC:** * **All That Node:** * **Alchemy:** * **Blockmachine:** ### Starting HTTP JSON-RPC You can start the HTTP JSON-RPC with the --http flag ```bash ## mainnet geth attach https://bsc-dataseed.bnbchain.org ## testnet geth attach https://bsc-testnet-dataseed.bnbchain.org ``` ## JSON-RPC API List BSC (BNB Smart Chain) is EVM-compatible and strives to be as compatible as possible with the Go-Ethereum API. However, BSC also has unique features, such as faster finality and the storage of blob data on the execution layer, which require their own specialized APIs. ### Geth(Go-Ethereum) API BSC is nearly fully compatible with the Geth APIs. Any exceptions or incompatibilities are explicitly listed. If you're looking for detailed usage of a specific API, you will most likely find the answer in the following link: [Geth JSON-RPC API documentation](https://geth.ethereum.org/docs/interacting-with-geth/rpc). ### Finality Ethereum's PoS consensus protocol, known as "Gasper," is built on LMD-GHOST (a fork choice rule) and Casper FFG (a finality gadget). Similarly, BSC's consensus protocol, called "Parlia," is constructed on top of a difficulty-based fork choice mechanism with FFG, as described in [BEP-126](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP126.md). To further enhance BSC's throughput, validators are allowed to produce multiple consecutive blocks, as explained in [BEP-341](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-341.md). These differences result in BSC having a unique finality process compared to Ethereum. For more details, please refer to the the following doc: [BSC Finality API](bsc-api-list.md#finality-api). ### Blob Bsc implement EIP-4844, which support Shard Blob Transactions, as described in [BEP-336](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-336.md). For more details, please refer to the the following doc: [BSC Blob API](bsc-api-list.md#blob-api). ### Other BSC API Bsc implement some others apis, as described in: [BSC API](bsc-api-list.md#others). ## One-click adding BSC network Visit the [ChainList](https://chainlist.org/chain/56) and connect to your wallet, it will add alive RPC endpoints. ## RPC Endpoints for BNB Smart Chain *The rate limit of BSC endpoint on Testnet and Mainnet is **10K/5min**.* `eth_getLogs` is disabled on below Mainnet endpoints, please use 3rd party endpoints from **[here](https://chainlist.org/chain/56)**. If you need to pull logs frequently, we recommend using WebSockets to push new logs to you when they are available. ### BSC Mainnet (ChainID 0x38, 56 in decimal) * https://bsc-dataseed.bnbchain.org * https://bsc-dataseed.nariox.org * https://bsc-dataseed.defibit.io * https://bsc-dataseed.ninicoin.io * https://bsc.nodereal.io * https://bsc-dataseed-public.bnbchain.org * https://rpc-bnb.blockmachine.io You could find more endpoints from **[here](https://chainlist.org/chain/56)**. ### BSC Testnet (ChainID 0x61, 97 in decimal) * https://bsc-testnet-dataseed.bnbchain.org * https://bsc-testnet.bnbchain.org * https://bsc-prebsc-dataseed.bnbchain.org ### RPC Providers * **Moralis:** * **NodeReal:** * **Ankr:** * **Chainstack:** * **GetBlock:** * **QuickNode:** * **BlockVision:** * **4EVERLAND:** * **NOWNodes:** * **dRPC:** * **All That Node:** * **Alchemy:** * **Blockmachine:** ### Starting HTTP JSON-RPC You can start the HTTP JSON-RPC with the --http flag ```bash ## mainnet geth attach https://bsc-dataseed.bnbchain.org ## testnet geth attach https://bsc-testnet-dataseed.bnbchain.org ``` ## JSON-RPC API List BSC (BNB Smart Chain) is EVM-compatible and strives to be as compatible as possible with the Go-Ethereum API. However, BSC also has unique features, such as faster finality and the storage of blob data on the execution layer, which require their own specialized APIs. ### Geth(Go-Ethereum) API BSC is nearly fully compatible with the Geth APIs. Any exceptions or incompatibilities are explicitly listed. If you're looking for detailed usage of a specific API, you will most likely find the answer in the following link: [Geth JSON-RPC API documentation](https://geth.ethereum.org/docs/interacting-with-geth/rpc). ### Finality Ethereum's PoS consensus protocol, known as "Gasper," is built on LMD-GHOST (a fork choice rule) and Casper FFG (a finality gadget). Similarly, BSC's consensus protocol, called "Parlia," is constructed on top of a difficulty-based fork choice mechanism with FFG, as described in [BEP-126](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP126.md). To further enhance BSC's throughput, validators are allowed to produce multiple consecutive blocks, as explained in [BEP-341](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-341.md). These differences result in BSC having a unique finality process compared to Ethereum. For more details, please refer to the the following doc: [BSC Finality API](bsc-api-list.md#finality-api). ### Blob Bsc implement EIP-4844, which support Shard Blob Transactions, as described in [BEP-336](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-336.md). For more details, please refer to the the following doc: [BSC Blob API](bsc-api-list.md#blob-api). ### Other BSC API Bsc implement some others apis, as described in: [BSC API](bsc-api-list.md#others). ## BNB Agent SDK Architecture > Source: https://docs.bnbchain.org/developer-kit/bnbagent-sdk/architecture/ --- title: BNB Agent SDK Architecture --- # Architecture This document describes the high-level architecture of the BNB Agent SDK. If you want to familiarize yourself with the codebase, this is a good place to start. ## Bird's Eye View BNB Agent SDK is a Python toolkit for building **on-chain AI agents** on BNB Chain. It provides wallet management, a plugin module system, off-chain storage abstraction, and built-in support for the following protocols: - **ERC-8004** — On-chain identity registry for AI agents (register, discover, resolve endpoints). - **ERC-8183 Protocol** — a three-layer agentic commerce stack: - **AgenticCommerce** (ERC-8183 kernel) — job lifecycle + escrow (create / setBudget / fund / submit / complete / reject / claimRefund). - **EvaluatorRouter** — routing layer that doubles as `job.evaluator` and `job.hook`. Binds `jobId → policy` on `registerJob`, pulls verdicts on the permissionless `settle`. - **OptimisticPolicy** — reference UMA-style policy. Silence past the dispute window is implicit approval; a client can raise a dispute that the whitelisted voters resolve by `voteReject` reaching quorum. The SDK is organized as a **plugin system**: each protocol is a self-contained module that can be used independently or composed via the `BNBAgent` facade. New protocols can be added as modules without modifying the SDK core. Wallet signing and off-chain storage are abstracted behind provider interfaces, making the SDK backend-agnostic. ``` ┌─────────────┐ │ BNBAgent │ optional facade (main.py) │ from_env() │ └──────┬──────┘ │ discovers & initializes ┌────────────┼────────────┐ │ │ │ ┌─────▼─────┐ ┌───▼────┐ ┌────▼─────┐ │ erc8004 │ │ erc8183 │ │ wallets │ │ Identity │ │ v1 │ │ Signing │ └─────┬─────┘ └───┬────┘ └────┬─────┘ │ │ │ └────┬──────┘ │ │ │ ┌──────▼──────┐ ┌──────▼──────┐ │ core │ │ storage_ │ │ (infra) │ │ providers │ └─────────────┘ └─────────────┘ ``` Arrows point **downward** — upper layers depend on lower layers, never the reverse. `erc8183` depends on `erc8004` (for agent discovery). Both protocol modules depend on `core` for transaction management. ## Code Map ### `bnbagent/` — Main Package | File | Purpose | |------|---------| | `__init__.py` | Tier 1 public API (re-exports from subpackages) | | `main.py` | `BNBAgent` — optional high-level facade over the module system | | `config.py` | `BNBAgentConfig`, `NetworkConfig`, `NETWORKS` registry, `resolve_network()` | | `constants.py` | Global constants (`SCAN_API_URL`) | | `exceptions.py` | `BNBAgentError` hierarchy | ### `bnbagent/core/` — Internal Infrastructure Not part of the public API. Provides shared plumbing for protocol modules. | File | Purpose | |------|---------| | `module.py` | `BNBAgentModule` ABC and `ModuleInfo` dataclass | | `registry.py` | `ModuleRegistry` — discovery (built-in + entry points), dependency validation, topological initialization | | `contract_mixin.py` | `ContractClientMixin` — shared base for `CommerceClient`, `RouterClient`, `PolicyClient`, `MinimalERC20Client` (tx signing, nonce management, retry with backoff) | | `nonce_manager.py` | `NonceManager` — per-account thread-safe nonce tracking with chain re-sync | | `multicall.py` | `multicall_read()` — Multicall3 batch view helper | | `paymaster.py` | `Paymaster` — ERC-4337 gas sponsorship client | | `abi_loader.py` | ABI file loading from bundled JSON | ### `bnbagent/erc8004/` — ERC-8004 Identity Registry | File | Purpose | |------|---------| | `agent.py` | `ERC8004Agent` — high-level SDK: `register_agent()`, `get_agent_info()`, `get_all_agents()` | | `contract.py` | `ContractInterface` — low-level web3 contract calls | | `models.py` | `AgentEndpoint` dataclass | | `constants.py` | `get_erc8004_config()` — per-network contract addresses | | `module.py` | `ERC8004Module` plugin | ### `bnbagent/erc8183/` — ERC-8183 Protocol High-level facade over three contracts. Most callers only touch `ERC8183Client`. | File | Purpose | |------|---------| | `client.py` | `ERC8183Client` — facade over Commerce / Router / Policy; floor-based `fund` approval; cached `payment_token` / `token_decimals` / `token_symbol`; high-level wrappers for `create_job`, `register_job`, `set_budget`, `fund`, `submit`, `settle`, `dispute`, `vote_reject`, `claim_refund` | | `commerce.py` | `CommerceClient` — low-level wrapper for `AgenticCommerceUpgradeable` | | `router.py` | `RouterClient` — low-level wrapper for `EvaluatorRouterUpgradeable` | | `policy.py` | `PolicyClient` — low-level wrapper for `OptimisticPolicy` (dispute / voteReject / check / voter admin) | | `../erc20/client.py` | `MinimalERC20Client` — used by `ERC8183Client` for ERC-20 reads (decimals/symbol/balanceOf/allowance/approve) | | `types.py` | `JobStatus`, `Verdict`, `REASON_APPROVED`, `REASON_REJECTED`, `Job` dataclass | | `config.py` | `ERC8183Config` — unified config (wallet_provider + storage + contract overrides) | | `negotiation.py` | `NegotiationHandler`, structured description schema, quote expiry | | `schema.py` | `DeliverableManifest`, `JobDescription`, `SCHEMA_VERSION` — on-chain description and off-chain deliverable JSON | | `constants.py` | `get_erc8183_config()` — per-network defaults | | `module.py` | `ERC8183Module` plugin | ### `bnbagent/erc8183/server/` — FastAPI Integration | File | Purpose | |------|---------| | `routes.py` | `create_erc8183_app()` FastAPI factory; `ERC8183State`; `/erc8183/job/{id}`, `/erc8183/negotiate`, `/erc8183/status`, `/erc8183/health`; funded-job background poll loop when `on_job` is provided | | `job_ops.py` | `ERC8183JobOps` — async wrapper over `ERC8183Client`; incremental scan for newly funded jobs; `submit_result` for deliverable submission | ### `bnbagent/wallets/` — Wallet Providers | File | Purpose | |------|---------| | `wallet_provider.py` | `WalletProvider` ABC — `address`, `sign_transaction()`, `sign_message()` | | `evm_wallet_provider.py` | `EVMWalletProvider` — Keystore V3 encryption (scrypt + AES-128-CTR) | | `mpc_wallet_provider.py` | `MPCWalletProvider` — stub for future MPC signer support | | `turnkey/` | `TurnkeyWalletProvider` — remote signing via Turnkey's AWS Nitro enclave (P-256 API key stamping; optional `bnbagent[turnkey]` extra) | ### `bnbagent/storage/` — Storage Providers | File | Purpose | |------|---------| | `storage_provider.py` | `StorageProvider` ABC — async `upload()`, `download()`, `exists()`, `compute_hash()` | | `local_storage_provider.py` | `LocalStorageProvider` — filesystem (`file://` URLs); owns its own `from_env()` | | `ipfs_storage_provider.py` | `IPFSStorageProvider` — IPFS pinning via HTTP API (Pinata-compatible); owns its own `from_env()` | | `sync_utils.py` | `upload_sync()` — synchronous bridge | ### `examples/` | Directory | Role | What it demonstrates | |-----------|------|----------------------| | `client/` | Client | 5 stand-alone scripts — happy / dispute-reject / stalemate-expire / never-submit / cancel-open | | `voter/` | Voter | `voteReject` script + `Disputed` event watcher | | `agent-server/` | Provider | FastAPI agent with funded-job poll loop and a public `/negotiate` quote endpoint | ### `tests/` — Test Suite `pytest` + `pytest-mock` + `pytest-asyncio`. Tests mock web3 and external services; no live chain calls in CI. ## Public API **Tier 1** — importable directly from `bnbagent`: ```python from bnbagent import ( BNBAgent, BNBAgentConfig, NetworkConfig, BNBAgentError, ERC8004Agent, AgentEndpoint, WalletProvider, EVMWalletProvider, ERC8183Client, JobStatus, Verdict, ) ``` **Tier 2** — import from subpackages: ## Bird's Eye View BNB Agent SDK is a Python toolkit for building **on-chain AI agents** on BNB Chain. It provides wallet management, a plugin system, off-chain storage abstraction, and built-in support for the following protocols: - **ERC-8004** — On-chain identity registry for AI agents (register, discover, resolve endpoints). - **ERC-8183 Protocol** — a three-layer agentic commerce stack: - **AgenticCommerce** (ERC-8183 kernel) — job lifecycle + escrow (create / setBudget / fund / submit / complete / reject / claimRefund). - **EvaluatorRouter** — routing layer that doubles as `job.evaluator` and `job.hook`. Binds `jobId → policy` on `registerJob`, pulls verdicts on the permissionless `settle`. - **OptimisticPolicy** — reference UMA-style policy. Silence past the dispute window is implicit approval; a client can raise a dispute that the whitelisted voters resolve by `voteReject` reaching quorum. The SDK is organized as a **plugin system**: each protocol is a self-contained module that can be used independently or composed via the `BNBAgent` facade. New protocols can be added as modules without modifying the SDK core. Wallet signing and off-chain storage are abstracted behind provider interfaces, making the SDK backend-agnostic. ``` ┌─────────────┐ │ BNBAgent │ optional facade (main.py) │ from_env() │ └──────┬──────┘ │ discovers & initializes ┌────────────┼────────────┐ │ │ │ ┌─────▼─────┐ ┌───▼────┐ ┌────▼─────┐ │ erc8004 │ │ erc8183 │ │ wallets │ │ Identity │ │ v1 │ │ Signing │ └─────┬─────┘ └───┬────┘ └────┬─────┘ │ │ │ └────┬──────┘ │ │ │ ┌──────▼──────┐ ┌──────▼──────┐ │ core │ │ storage_ │ │ (infra) │ │ providers │ └─────────────┘ └─────────────┘ ``` Arrows point **downward** — upper layers depend on lower layers, never the reverse. `erc8183` depends on `erc8004` (for agent discovery). Both protocol modules depend on `core` for transaction management. ## Code Map ### `bnbagent/` — Main Package | File | Purpose | |------|---------| | `__init__.py` | Tier 1 public API (re-exports from subpackages) | | `main.py` | `BNBAgent` — optional high-level facade over the module system | | `config.py` | `BNBAgentConfig`, `NetworkConfig`, `NETWORKS` registry, `resolve_network()` | | `constants.py` | Global constants (`SCAN_API_URL`) | | `exceptions.py` | `BNBAgentError` hierarchy | ### `bnbagent/core/` — Internal Infrastructure Not part of the public API. Provides shared plumbing for protocol modules. | File | Purpose | |------|---------| | `module.py` | `BNBAgentModule` ABC and `ModuleInfo` dataclass | | `registry.py` | `ModuleRegistry` — discovery (built-in + entry points), dependency validation, topological initialization | | `contract_mixin.py` | `ContractClientMixin` — shared base for `CommerceClient`, `RouterClient`, `PolicyClient`, `MinimalERC20Client` (tx signing, nonce management, retry with backoff) | | `nonce_manager.py` | `NonceManager` — per-account thread-safe nonce tracking with chain re-sync | | `multicall.py` | `multicall_read()` — Multicall3 batch view helper | | `paymaster.py` | `Paymaster` — ERC-4337 gas sponsorship client | | `abi_loader.py` | ABI file loading from bundled JSON | ### `bnbagent/erc8004/` — ERC-8004 Identity Registry | File | Purpose | |------|---------| | `agent.py` | `ERC8004Agent` — high-level SDK: `register_agent()`, `get_agent_info()`, `get_all_agents()` | | `contract.py` | `ContractInterface` — low-level web3 contract calls | | `models.py` | `AgentEndpoint` dataclass | | `constants.py` | `get_erc8004_config()` — per-network contract addresses | | `module.py` | `ERC8004Module` plugin | ### `bnbagent/erc8183/` — ERC-8183 Protocol High-level facade over three contracts. Most callers only touch `ERC8183Client`. | File | Purpose | |------|---------| | `client.py` | `ERC8183Client` — facade over Commerce / Router / Policy; floor-based `fund` approval; cached `payment_token` / `token_decimals` / `token_symbol`; high-level wrappers for `create_job`, `register_job`, `set_budget`, `fund`, `submit`, `settle`, `dispute`, `vote_reject`, `claim_refund` | | `commerce.py` | `CommerceClient` — low-level wrapper for `AgenticCommerceUpgradeable` | | `router.py` | `RouterClient` — low-level wrapper for `EvaluatorRouterUpgradeable` | | `policy.py` | `PolicyClient` — low-level wrapper for `OptimisticPolicy` (dispute / voteReject / check / voter admin) | | `../erc20/client.py` | `MinimalERC20Client` — used by `ERC8183Client` for ERC-20 reads (decimals/symbol/balanceOf/allowance/approve) | | `types.py` | `JobStatus`, `Verdict`, `REASON_APPROVED`, `REASON_REJECTED`, `Job` dataclass | | `config.py` | `ERC8183Config` — unified config (wallet_provider + storage + contract overrides) | | `negotiation.py` | `NegotiationHandler`, structured description schema, quote expiry | | `schema.py` | `DeliverableManifest`, `JobDescription`, `SCHEMA_VERSION` — on-chain description and off-chain deliverable JSON | | `constants.py` | `get_erc8183_config()` — per-network defaults | | `module.py` | `ERC8183Module` plugin | ### `bnbagent/erc8183/server/` — FastAPI Integration | File | Purpose | |------|---------| | `routes.py` | `create_erc8183_app()` FastAPI factory; `ERC8183State`; `/erc8183/job/{id}`, `/erc8183/negotiate`, `/erc8183/status`, `/erc8183/health`; funded-job background poll loop when `on_job` is provided | | `job_ops.py` | `ERC8183JobOps` — async wrapper over `ERC8183Client`; incremental scan for newly funded jobs; `submit_result` for deliverable submission | ### `bnbagent/wallets/` — Wallet Providers | File | Purpose | |------|---------| | `wallet_provider.py` | `WalletProvider` ABC — `address`, `sign_transaction()`, `sign_message()` | | `evm_wallet_provider.py` | `EVMWalletProvider` — Keystore V3 encryption (scrypt + AES-128-CTR) | | `mpc_wallet_provider.py` | `MPCWalletProvider` — stub for future MPC signer support | | `turnkey/` | `TurnkeyWalletProvider` — remote signing via Turnkey's AWS Nitro enclave (P-256 API key stamping; optional `bnbagent[turnkey]` extra) | ### `bnbagent/storage/` — Storage Providers | File | Purpose | |------|---------| | `storage_provider.py` | `StorageProvider` ABC — async `upload()`, `download()`, `exists()`, `compute_hash()` | | `local_storage_provider.py` | `LocalStorageProvider` — filesystem (`file://` URLs); owns its own `from_env()` | | `ipfs_storage_provider.py` | `IPFSStorageProvider` — IPFS pinning via HTTP API (Pinata-compatible); owns its own `from_env()` | | `sync_utils.py` | `upload_sync()` — synchronous bridge | ### `examples/` | Directory | Role | What it demonstrates | |-----------|------|----------------------| | `client/` | Client | 5 stand-alone scripts — happy / dispute-reject / stalemate-expire / never-submit / cancel-open | | `voter/` | Voter | `voteReject` script + `Disputed` event watcher | | `agent-server/` | Provider | FastAPI agent with funded-job poll loop and a public `/negotiate` quote endpoint | ### `tests/` — Test Suite `pytest` + `pytest-mock` + `pytest-asyncio`. Tests mock web3 and external services; no live chain calls in CI. ## Public API **Tier 1** — importable directly from `bnbagent`: ```python from bnbagent import ( BNBAgent, BNBAgentConfig, NetworkConfig, BNBAgentError, ERC8004Agent, AgentEndpoint, WalletProvider, EVMWalletProvider, ERC8183Client, JobStatus, Verdict, ) ``` **Tier 2** — import from subpackages: ## BNB Agent SDK Configuration > Source: https://docs.bnbchain.org/developer-kit/bnbagent-sdk/configuration/ --- title: BNB Agent SDK Configuration --- ## Configuration Reference ### Environment Variables | Variable | Required | Default | Description | |----------|----------|---------|-------------| | `PRIVATE_KEY` | Recommended | Auto-generate | Agent wallet private key. If provided, encrypted to `~/.bnbagent/wallets/` on first run, then removable. | | `WALLET_PASSWORD` | Yes | — | Password to encrypt / decrypt the keystore. | | `WALLET_ADDRESS` | No | Auto-select | Select a specific keystore when multiple exist. | | `NETWORK` | No | `bsc-testnet` | Network name. | | `RPC_URL` | No | Network default | Custom RPC endpoint. | | `ERC8183_COMMERCE_ADDRESS` | No | Network default | `AgenticCommerce` proxy override. | | `ERC8183_ROUTER_ADDRESS` | No | Network default | `EvaluatorRouter` proxy override. | | `ERC8183_POLICY_ADDRESS` | No | Network default | Policy contract override (defaults to `OptimisticPolicy`). | | `ERC8183_AGENT_URL` | If LocalStorageProvider | — | Agent's public base URL including `/erc8183`. Required when storage returns `file://` URLs; the SDK rewrites them to `{ERC8183_AGENT_URL}/job/{id}/response`. | | `ERC8183_SERVICE_PRICE` | No | `1000000000000000000` (1 unit) | Minimum acceptable budget, in raw units. | | `ERC8183_FUNDED_POLL_INTERVAL` | No | `30` | Seconds between funded-job poll passes (agent-server). | | `ERC8183_NEGOTIATE_RATE_LIMIT` | No | `120` | Max `/negotiate` requests per window per client IP. | | `ERC8183_NEGOTIATE_RATE_WINDOW` | No | `60` | Sliding-window length for `/negotiate` rate limit, in seconds. | | `ERC8183_MAX_RESPONSE_BYTES` | No | `5242880` (5 MB) | Cap on `response_content` size in `submit_result`. | | `ERC8183_MAX_METADATA_BYTES` | No | `262144` (256 KB) | Cap on serialised metadata size in `submit_result`. | | `ERC8004_REGISTRY_ADDRESS` | No | Network default | ERC-8004 Identity Registry override. | | `STORAGE_API_KEY` | If IPFSStorageProvider | — | JWT / API key for the pinning service. | | `STORAGE_GATEWAY_URL` | No | Pinata default | Custom IPFS gateway. | | `STORAGE_LOCAL_PATH` | No | `.agent-data` | Directory for local storage. | | `TURNKEY_API_PUBLIC_KEY` | If `WALLET_KIND=turnkey` | — | Turnkey P-256 API public key (dashboard → API keys). | | `TURNKEY_API_PRIVATE_KEY` | If `WALLET_KIND=turnkey` | — | Turnkey P-256 API private key. A client credential — never leaves this process. | | `TURNKEY_ORG_ID` | If `WALLET_KIND=turnkey` | — | Turnkey organization id (dashboard → settings). | | `TURNKEY_SIGN_WITH` | If `WALLET_KIND=turnkey` | — | The wallet account's Ethereum address (`0x` + 40 hex chars), not a Turnkey wallet id or private-key id. | | `TURNKEY_API_BASE_URL` | No | `https://api.turnkey.com` | Turnkey API host override. | Commerce settlement assets are resolved at runtime from the deployed kernel — not configured via env vars in these docs. See [Networks & contracts](networks.md) for where deployments are maintained upstream. See [.env.example](https://github.com/bnb-chain/bnbagent-sdk/blob/main/.env.example) in the repository for the full surface with inline comments. [← BNB Agent SDK overview](index.md) --- ## Configuration Reference ### Environment Variables | Variable | Required | Default | Description | |----------|----------|---------|-------------| | `PRIVATE_KEY` | Recommended | Auto-generate | Agent wallet private key. If provided, encrypted to `~/.bnbagent/wallets/` on first run, then removable. | | `WALLET_PASSWORD` | Yes | — | Password to encrypt / decrypt the keystore. | | `WALLET_ADDRESS` | No | Auto-select | Select a specific keystore when multiple exist. | | `NETWORK` | No | `bsc-testnet` | Network name. | | `RPC_URL` | No | Network default | Custom RPC endpoint. | | `ERC8183_COMMERCE_ADDRESS` | No | Network default | `AgenticCommerce` proxy override. | | `ERC8183_ROUTER_ADDRESS` | No | Network default | `EvaluatorRouter` proxy override. | | `ERC8183_POLICY_ADDRESS` | No | Network default | Policy contract override (defaults to `OptimisticPolicy`). | | `ERC8183_AGENT_URL` | If LocalStorageProvider | — | Agent's public base URL including `/erc8183`. Required when storage returns `file://` URLs; the SDK rewrites them to `{ERC8183_AGENT_URL}/job/{id}/response`. | | `ERC8183_SERVICE_PRICE` | No | `1000000000000000000` (1 unit) | Minimum acceptable budget, in raw units. | | `ERC8183_FUNDED_POLL_INTERVAL` | No | `30` | Seconds between funded-job poll passes (agent-server). | | `ERC8183_NEGOTIATE_RATE_LIMIT` | No | `120` | Max `/negotiate` requests per window per client IP. | | `ERC8183_NEGOTIATE_RATE_WINDOW` | No | `60` | Sliding-window length for `/negotiate` rate limit, in seconds. | | `ERC8183_MAX_RESPONSE_BYTES` | No | `5242880` (5 MB) | Cap on `response_content` size in `submit_result`. | | `ERC8183_MAX_METADATA_BYTES` | No | `262144` (256 KB) | Cap on serialised metadata size in `submit_result`. | | `ERC8004_REGISTRY_ADDRESS` | No | Network default | ERC-8004 Identity Registry override. | | `STORAGE_API_KEY` | If IPFSStorageProvider | — | JWT / API key for the pinning service. | | `STORAGE_GATEWAY_URL` | No | Pinata default | Custom IPFS gateway. | | `STORAGE_LOCAL_PATH` | No | `.agent-data` | Directory for local storage. | | `TURNKEY_API_PUBLIC_KEY` | If `WALLET_KIND=turnkey` | — | Turnkey P-256 API public key (dashboard → API keys). | | `TURNKEY_API_PRIVATE_KEY` | If `WALLET_KIND=turnkey` | — | Turnkey P-256 API private key. A client credential — never leaves this process. | | `TURNKEY_ORG_ID` | If `WALLET_KIND=turnkey` | — | Turnkey organization id (dashboard → settings). | | `TURNKEY_SIGN_WITH` | If `WALLET_KIND=turnkey` | — | The wallet account's Ethereum address (`0x` + 40 hex chars), not a Turnkey wallet id or private-key id. | | `TURNKEY_API_BASE_URL` | No | `https://api.turnkey.com` | Turnkey API host override. | Commerce settlement assets are resolved at runtime from the deployed kernel — not configured via env vars in these docs. See [Networks & contracts](networks.md) for where deployments are maintained upstream. See [.env.example](https://github.com/bnb-chain/bnbagent-sdk/blob/main/.env.example) in the repository for the full surface with inline comments. [← BNB Agent SDK overview](index.md) ## BNB Agent SDK Quickstart > Source: https://docs.bnbchain.org/developer-kit/bnbagent-sdk/quickstart/ --- title: BNB Agent SDK Quickstart --- ## Quick Start: Register an Agent (ERC-8004) Register your AI agent on-chain with a unique identity. This is a one-time setup. ### Prerequisites - Python 3.10+ - A private key (generate one or use an existing wallet) ```python import os from dotenv import load_dotenv from bnbagent import ERC8004Agent, AgentEndpoint, EVMWalletProvider load_dotenv() wallet = EVMWalletProvider( password=os.getenv("WALLET_PASSWORD"), private_key=os.getenv("PRIVATE_KEY"), # only needed on first run ) sdk = ERC8004Agent(network="bsc-testnet", wallet_provider=wallet) agent_uri = sdk.generate_agent_uri( name="my-ai-agent", description="AI agent for document processing", endpoints=[ AgentEndpoint( name="ERC-8183", endpoint="https://my-agent.example.com/erc8183/status", version="0.1.0", ), ], ) result = sdk.register_agent(agent_uri=agent_uri) print(f"Agent registered! ID: {result['agentId']}, TX: {result['transactionHash']}") ``` --- --- ## Quick Start: Run an ERC-8183 Agent Server Set up an agent server that accepts jobs, processes work, and gets paid. ### Prerequisites - `pip install "bnbagent[server,ipfs]"` - A `.env` file with your credentials (see [examples/agent-server/.env.example](https://github.com/bnb-chain/bnbagent-sdk/tree/main/examples/agent-server/.env.example)) ### Option 1: Standalone App (`create_erc8183_app`) ```python # agent.py from bnbagent.erc8183.server import create_erc8183_app def execute_job(job: dict) -> str: """Called automatically for each FUNDED job. Return the deliverable string.""" return f"Processed: {job['description']}" app = create_erc8183_app(on_job=execute_job) # Routes at /erc8183/negotiate, /erc8183/status, /erc8183/job/{id}, etc. ``` ```bash # .env WALLET_PASSWORD=your-secure-password PRIVATE_KEY= # first run only; encrypted to ~/.bnbagent/wallets/ ERC8183_AGENT_URL=http://localhost:8003/erc8183 # required for LocalStorageProvider (default) ERC8183_SERVICE_PRICE=1000000000000000000 # 1 token (18 decimals) # To use IPFS instead, swap to IPFSStorageProvider in your service code and set: # STORAGE_API_KEY=your-pinning-service-jwt # Optional knobs (see env-var table below for full reference): # ERC8183_FUNDED_POLL_INTERVAL=30 # default poll cadence (s) # ERC8183_NEGOTIATE_RATE_LIMIT=120 # /negotiate per-IP request budget # ERC8183_NEGOTIATE_RATE_WINDOW=60 # rate-limit window (s) # ERC8183_MAX_RESPONSE_BYTES=5242880 # response_content cap (5 MB) # ERC8183_MAX_METADATA_BYTES=262144 # metadata cap (256 KB) ``` ```bash uvicorn agent:app --port 8003 ``` `create_erc8183_app()` handles: wallet keystore, periodic on-chain poll for newly FUNDED jobs assigned to this provider, on-chain verification, calling your handler, uploading the deliverable to storage, and submitting on-chain. Jobs with `budget < service_price` are rejected with HTTP 402. Settle is permissionless — run a separate operator script to call `router.settle(jobId)` once the dispute window elapses. ### Option 2: Mount on Existing App (sub-app) ```python from contextlib import asynccontextmanager from fastapi import FastAPI from bnbagent.erc8183.server import create_erc8183_app def execute_job(job: dict) -> str: return f"Processed: {job['description']}" erc8183_app = create_erc8183_app(on_job=execute_job, prefix="") @asynccontextmanager async def lifespan(app: FastAPI): await erc8183_app.state.startup() yield app = FastAPI(lifespan=lifespan) app.mount("/erc8183", erc8183_app) ``` Starlette does not propagate lifespan events into mounted sub-apps; call `erc8183_app.state.startup()` from your parent lifespan to launch the funded-job poll loop. ### Endpoints | Method | Path | Description | |--------|------|-------------| | `POST` | `/erc8183/negotiate` | Price negotiation (off-chain). Returns a structured quote. Rate-limited per client IP. | | `GET` | `/erc8183/job/{id}` | Job details from the Commerce kernel. | | `GET` | `/erc8183/job/{id}/response` | Stored deliverable for a submitted job. | | `GET` | `/erc8183/job/{id}/verify` | Verify a job is `FUNDED`, assigned to this provider, not expired, budget ok. | | `GET` | `/erc8183/status` | Agent wallet, service price, decimals, network info. | | `GET` | `/erc8183/health` | Liveness check. | ### `on_job` Callback ```python # Sync or async, with or without per-job metadata: def on_job(job: dict) -> str: ... async def on_job(job: dict) -> str: ... def on_job(job: dict) -> tuple[str, dict]: ... async def on_job(job: dict) -> tuple[str, dict]: ... ``` `job` contains: `jobId`, `description`, `budget`, `client`, `provider`, `evaluator`, `status` (always `FUNDED`), `expiredAt`, `hook`. ### Settle `router.settle(jobId)` is permissionless — any party can finalise a submitted job once its dispute window elapses. The SDK does not run an in-server settle loop; operators are expected to run a separate script that polls verdicts and calls `ERC8183Client.settle(jobId)` when ready. --- --- ## Quick Start: Use `ERC8183Client` from a Client `ERC8183Client` is the high-level facade over the ERC-8183 contract stack. Most callers only use the top-level methods; the sub-clients `erc8183.commerce`, `erc8183.router`, `erc8183.policy` are exposed for advanced use. ```python from bnbagent.erc8183 import ERC8183Client, JobStatus from bnbagent.wallets import EVMWalletProvider wallet = EVMWalletProvider(password="your-password", private_key="") erc8183 = ERC8183Client(wallet, network="bsc-testnet") # Settlement-asset helpers (decimals / balance resolved from network presets). print("decimals:", erc8183.token_decimals()) print("balance:", erc8183.token_balance()) # Happy-path lifecycle. budget = 1 * (10 ** erc8183.token_decimals()) expired_at = int(time.time()) + 65 * 60 res = erc8183.create_job(provider=provider_addr, expired_at=expired_at, description="task") job_id = res["jobId"] erc8183.register_job(job_id) # bind default policy (OptimisticPolicy) erc8183.set_budget(job_id, budget) erc8183.fund(job_id, budget) # floor-based auto-approve (default cap from SDK) # ... provider submits ... erc8183.settle(job_id) # permissionless; anyone can call assert erc8183.get_job_status(job_id) == JobStatus.COMPLETED ``` ### `fund(job_id, amount, approve_floor=None)` - **`approve_floor=None`** (default) — Approve `max(amount, 100 * 10**decimals)`. Residual allowance stays bounded (≤100 tokens), but small budgets don't repeatedly re-approve. Saves gas across job streams. - **`approve_floor=0`** — Approve exactly `amount` (most conservative). - **`approve_floor=X`** — Approve `max(amount, X)` (custom floor). If the current allowance already covers `amount`, no approve is sent at all. ### Disputes ```python erc8183.dispute(job_id) # client only; within dispute window erc8183.vote_reject(job_id) # whitelisted voter only; after dispute erc8183.claim_refund(job_id) # anyone, after expiredAt, no settlement reached ``` See [examples/client/](https://github.com/bnb-chain/bnbagent-sdk/tree/main/examples/client/) for the five canonical flows (happy, dispute-reject, stalemate-expire, never-submit, cancel-open). --- ## Quick Start: Use a Turnkey Wallet (Remote Signing) For remote enclave signing (keys held in Turnkey's AWS Nitro enclave, the agent holds only a local P-256 API key), use `TurnkeyWalletProvider` instead of `EVMWalletProvider`. Install the optional extra first: ```bash pip install "bnbagent[turnkey]" ``` ```python from bnbagent.wallets import TurnkeyWalletProvider # env: TURNKEY_API_PUBLIC_KEY / TURNKEY_API_PRIVATE_KEY / TURNKEY_ORG_ID / # TURNKEY_SIGN_WITH (the wallet account's 0x ADDRESS, not a wallet id) wallet = TurnkeyWalletProvider.from_env(expected_chain_id=97) # Use it anywhere a WalletProvider is accepted: from bnbag ## Quick Start: Register an Agent (ERC-8004) Register your AI agent on-chain with a unique identity. This is a one-time setup. ### Prerequisites - Python 3.10+ - A private key (generate one or use an existing wallet) ```python import os from dotenv import load_dotenv from bnbagent import ERC8004Agent, AgentEndpoint, EVMWalletProvider load_dotenv() wallet = EVMWalletProvider( password=os.getenv("WALLET_PASSWORD"), private_key=os.getenv("PRIVATE_KEY"), # only needed on first run ) sdk = ERC8004Agent(network="bsc-testnet", wallet_provider=wallet) agent_uri = sdk.generate_agent_uri( name="my-ai-agent", description="AI agent for document processing", endpoints=[ AgentEndpoint( name="ERC-8183", endpoint="https://my-agent.example.com/erc8183/status", version="0.1.0", ), ], ) result = sdk.register_agent(agent_uri=agent_uri) print(f"Agent registered! ID: {result['agentId']}, TX: {result['transactionHash']}") ``` ## Quick Start: Run an ERC-8183 Agent Server Set up an agent server that accepts jobs, processes work, and gets paid. ### Prerequisites - `pip install "bnbagent[server,ipfs]"` - A `.env` file with your credentials (see [examples/agent-server/.env.example](https://github.com/bnb-chain/bnbagent-sdk/tree/main/examples/agent-server/.env.example)) ### Option 1: Standalone App (`create_erc8183_app`) ```python # agent.py from bnbagent.erc8183.server import create_erc8183_app def execute_job(job: dict) -> str: """Called automatically for each FUNDED job. Return the deliverable string.""" return f"Processed: {job['description']}" app = create_erc8183_app(on_job=execute_job) # Routes at /erc8183/negotiate, /erc8183/status, /erc8183/job/{id}, etc. ``` ```bash # .env WALLET_PASSWORD=your-secure-password PRIVATE_KEY= # first run only; encrypted to ~/.bnbagent/wallets/ ERC8183_AGENT_URL=http://localhost:8003/erc8183 # required for LocalStorageProvider (default) ERC8183_SERVICE_PRICE=1000000000000000000 # 1 token (18 decimals) # To use IPFS instead, swap to IPFSStorageProvider in your service code and set: # STORAGE_API_KEY=your-pinning-service-jwt # Optional knobs (see env-var table below for full reference): # ERC8183_FUNDED_POLL_INTERVAL=30 # default poll cadence (s) # ERC8183_NEGOTIATE_RATE_LIMIT=120 # /negotiate per-IP request budget # ERC8183_NEGOTIATE_RATE_WINDOW=60 # rate-limit window (s) # ERC8183_MAX_RESPONSE_BYTES=5242880 # response_content cap (5 MB) # ERC8183_MAX_METADATA_BYTES=262144 # metadata cap (256 KB) ``` ```bash uvicorn agent:app --port 8003 ``` `create_erc8183_app()` handles: wallet keystore, periodic on-chain poll for newly FUNDED jobs assigned to this provider, on-chain verification, calling your handler, uploading the deliverable to storage, and submitting on-chain. Jobs with `budget < service_price` are rejected with HTTP 402. Settle is permissionless — run a separate operator script to call `router.settle(jobId)` once the dispute window elapses. ### Option 2: Mount on Existing App (sub-app) ```python from contextlib import asynccontextmanager from fastapi import FastAPI from bnbagent.erc8183.server import create_erc8183_app def execute_job(job: dict) -> str: return f"Processed: {job['description']}" erc8183_app = create_erc8183_app(on_job=execute_job, prefix="") @asynccontextmanager async def lifespan(app: FastAPI): await erc8183_app.state.startup() yield app = FastAPI(lifespan=lifespan) app.mount("/erc8183", erc8183_app) ``` Starlette does not propagate lifespan events into mounted sub-apps; call `erc8183_app.state.startup()` from your parent lifespan to launch the funded-job poll loop. ### Endpoints | Method | Path | Description | |--------|------|-------------| | `POST` | `/erc8183/negotiate` | Price negotiation (off-chain). Returns a structured quote. Rate-limited per client IP. | | `GET` | `/erc8183/job/{id}` | Job details from the Commerce kernel. | | `GET` | `/erc8183/job/{id}/response` | Stored deliverable for a submitted job. | | `GET` | `/erc8183/job/{id}/verify` | Verify a job is `FUNDED`, assigned to this provider, not expired, budget ok. | | `GET` | `/erc8183/status` | Agent wallet, service price, decimals, network info. | | `GET` | `/erc8183/health` | Liveness check. | ### `on_job` Callback ```python # Sync or async, with or without per-job metadata: def on_job(job: dict) -> str: ... async def on_job(job: dict) -> str: ... def on_job(job: dict) -> tuple[str, dict]: ... async def on_job(job: dict) -> tuple[str, dict]: ... ``` `job` contains: `jobId`, `description`, `budget`, `client`, `provider`, `evaluator`, `status` (always `FUNDED`), `expiredAt`, `hook`. ### Settle `router.settle(jobId)` is permissionless — any party can finalise a submitted job once its dispute window elapses. The SDK does not run an in-server settle loop; operators are expected to run a separate script that polls verdicts and calls `ERC8183Client.settle(jobId)` when ready. ## Quick Start: Use `ERC8183Client` from a Client `ERC8183Client` is the high-level facade over the ERC-8183 contract stack. Most callers only use the top-level methods; the sub-clients `erc8183.commerce`, `erc8183.router`, `erc8183.policy` are exposed for advanced use. ```python from bnbagent.erc8183 import ERC8183Client, JobStatus from bnbagent.wallets import EVMWalletProvider wallet = EVMWalletProvider(password="your-password", private_key="") erc8183 = ERC8183Client(wallet, network="bsc-testnet") # Settlement-asset helpers (decimals / balance resolved from network presets). print("decimals:", erc8183.token_decimals()) print("balance:", erc8183.token_balance()) # Happy-path lifecycle. budget = 1 * (10 ** erc8183.token_decimals()) expired_at = int(time.time()) + 65 * 60 res = erc8183.create_job(provider=provider_addr, expired_at=expired_at, description="task") job_id = res["jobId"] erc8183.register_job(job_id) # bind default policy (OptimisticPolicy) erc8183.set_budget(job_id, budget) erc8183.fund(job_id, budget) # floor-based auto-approve (default cap from SDK) # ... provider submits ... erc8183.settle(job_id) # permissionless; anyone can call assert erc8183.get_job_status(job_id) == JobStatus.COMPLETED ``` ### `fund(job_id, amount, approve_floor=None)` - **`approve_floor=None`** (default) — Approve `max(amount, 100 * 10**decimals)`. Residual allowance stays bounded (≤100 tokens), but small budgets don't repeatedly re-approve. Saves gas across job streams. - **`approve_floor=0`** — Approve exactly `amount` (most conservative). - **`approve_floor=X`** — Approve `max(amount, X)` (custom floor). If the current allowance already covers `amount`, no approve is sent at all. ### Disputes ```python erc8183.dispute(job_id) # client only; within dispute window erc8183.vote_reject(job_id) # whitelisted voter only; after dispute erc8183.claim_refund(job_id) # anyone, after expiredAt, no settlement reached ``` See [examples/client/](https://github.com/bnb-chain/bnbagent-sdk/tree/main/examples/client/) for the five canonical flows (happy, dispute-reject, stalemate-expire, never-submit, cancel-open). ## Quick Start: Use a Turnkey Wallet (Remote Signing) For remote enclave signing (keys held in Turnkey's AWS Nitro enclave, the agent holds only a local P-256 API key), use `TurnkeyWalletProvider` instead of `EVMWalletProvider`. Install the optional extra first: ```bash pip install "bnbagent[turnkey]" ``` ```python from bnbagent.wallets import TurnkeyWalletProvider # env: TURNKEY_API_PUBLIC_KEY / TURNKEY_API_PRIVATE_KEY / TURNKEY_ORG_ID / # TURNKEY_SIGN_WITH (the wallet account's 0x ADDRESS, not a wallet id) wallet = TurnkeyWalletProvider.from_env(expected_chain_id=97) # Use it anywhere a WalletProvider is accepted: from bnbag ## BNB Agent Studio > Source: https://docs.bnbchain.org/developer-kit/bnbchain-studio/ Scaffold, run, and deploy a **two-layer blockchain seller** on BNB Chain. BNB Agent Studio (`bnbagent-studio`) lets you describe what you want in Claude Code or Cursor; the studio emits a working agent project that **you own**, then helps you develop, debug, and deploy it. ## Quickstart > Source: https://docs.bnbchain.org/developer-kit/bnbchain-studio/quickstart/ End-to-end path from zero to a running two-layer seller on BSC testnet. Steps 1–2 are one-time machine setup; step 3 is where you spend most of your time — talking to your AI tool, which drives `bag` for you. ## Demo > Source: https://docs.bnbchain.org/developer-kit/bnbchain-studio/demo/ This walkthrough follows the full BNB Agent Studio path for a single example: a **weather-forecast seller** on BSC testnet. You install the CLI, scaffold the agent with your AI IDE, set up a wallet, fund it, activate an LLM, run locally, negotiate a sale, register on-chain, and deploy. ## BNB Chain > Source: https://docs.bnbchain.org/ BNB Chain is a leading blockchain ecosystem designed to support the growing demands of the decentralized web (Web3). It offers speed, scalability, and affordability for developers and users. BNB Chain is composed of three blockchains: BNB Smart Chain (BSC), opBNB, and BNB Greenfield. Key features include Ethereum compatibility, a massive user base, the strongest ecosystem, a thriving DeFi ecosystem, community-driven growth, and diversified asset APIs. Use cases include DeFi, LSD and restaking, gaming and NFTs, DApps, data storage, and AI with blockchain technology. Quick start guides are available for BNB Smart Chain, opBNB, and BNB Greenfield. ## Announcement > Source: https://docs.bnbchain.org/announce/ Announcements for BNB Chain upgrades and network changes. - Pasteur Upgrade of BSC — 3 BEPs on BSC — 2026 Jul 21st - Token Recovery Tool: Phase 3 — Self-Service Recovery — 1 July 2026 - BNB Beacon Chain Token Recovery Tool: Sunset Plan — 2026 Mar 4th - Mendel Upgrade of BSC — Nine BEPs on BSC Testnet/Mainnet — 2026 Feb 6th ## Altai Upgrade of Greenfield > Source: https://docs.bnbchain.org/announce/altai-gnfd/ Hardfork upgrade. Testnet on Sep 21, 2024 at block 12,513,708; Mainnet on Sep 23, 2024 at block 11,917,971. Validators should upgrade to greenfield v1.9.1. Storage providers need no action. A hotfix release addresses MetaMask extension compatibility issues with EIP712 signatures; Go-SDK v1.7.3 and Js-SDK v2.2.0-alpha are recommended. ## Bohr Upgrade of BSC > Source: https://docs.bnbchain.org/announce/bohr-bsc/ Hardfork. Testnet on 2024-08-20; Mainnet on 2024-09-26. Requires BSC node v1.4.14. Includes BEP-341 (validators can produce consecutive blocks), BEP-402 (complete missing fields in block header to generate signature), BEP-404 (clear miner history when switching validator sets), and BEP-410 (add agent for validators). BEP-341 takes effect after a governance vote. ## Feynman Upgrade of BSC > Source: https://docs.bnbchain.org/announce/feynman-bsc/ Hardfork. Testnet March 11 2024; Mainnet April 18 2024. Requires BSC node v1.3.13. Advances BNB Chain Fusion (BEP-333). Deploys BEP-294 (triple voting power for BSC validators), BEP-297 (governance functionality, activated after 10M BNB migrated), and BEP-299 (token migration after Beacon Chain halts). Cross-chain re-delegation will be enabled after governance opening. ## Final Sunset Hardfork of BC Testnet > Source: https://docs.bnbchain.org/announce/final-sunset-bc-testnet/ Hardfork on August 1 2024 6:00:00 AM UTC. BC node must be upgraded to v0.10.23 and app.toml should include FinalSunsetHeight = 56218686. After Final Sunset, cross-chain communication between Beacon Chain and BSC completely stops; validators will shut down and the chain will no longer accept transactions or propose blocks. ## Fjord Upgrade of opBNB > Source: https://docs.bnbchain.org/announce/fjord-opbnb/ Hardfork. Testnet Sep 10 2024; Mainnet Sep 24 2024. Requires op-node and op-geth v0.5.0. Changes L1 fee calculation to use a FastLZ-based compression estimator. Adds operator flags such as --wait-node-sync and --compression-algo. ## Haber Upgrade of BSC > Source: https://docs.bnbchain.org/announce/haber-bsc/ Hardfork. Testnet May 29 2024; Mainnet June 20 2024. Requires BSC node v1.4.8. Adds BEP-381 precompile for secp256r1 curve at address 0x100 and BEP-336 enabling blob-carrying transactions. ## Haber Upgrade of opBNB > Source: https://docs.bnbchain.org/announce/haber-opbnb/ Hardfork. Testnet May 30 2024; Mainnet June 20 2024. Requires opBNB node v0.4.2. Adds EIP-7212 secp256r1 curve precompile and switches DA data submission from calldata to BSC blobs. Node operators need L1 endpoints that persist blob data for more than 18 days when syncing from genesis or far behind. ## Mongolian Upgrade of Greenfield > Source: https://docs.bnbchain.org/announce/mongolian-greenfield/ Hardfork. Testnet July 31 2024 block 10,780,238; Mainnet August 8 2024 block 10,314,605. Validators upgrade to greenfield v1.9.0; SPs upgrade to greenfield-storage-provider v1.9.0. Adds support for creating policies by cross-chain. ## Pasteur Upgrade of BSC > Source: https://docs.bnbchain.org/announce/pasteur-bsc/ Hardfork. Testnet 2026-07-21 02:30:00 AM UTC; Mainnet 2026-08-25 02:30:00 AM UTC. Requires BSC node v1.7.7. Includes BEP-682 (reject duplicate validators in CometBFT light block validation), BEP-695 (staking and governance security hardening), and BEP-675 (builder-proposed block with validator blind signing, enabled after activation via RPC). Deprecated flags and config fields must be reviewed before upgrade. ## Second Sunset Hardfork of BC Testnet > Source: https://docs.bnbchain.org/announce/second-sunset-bc-testnet/ Hardfork on June 21 2024 6:00:00 AM UTC. Requires BC node v0.10.21 with SecondSunsetHeight = 54554742. All TimeLocks and AtomicSwaps on BC testnet will be automatically refunded; BSC delegations will be automatically undelegated and refunded after the unbonding period. ## Second Sunset Hardfork of BC > Source: https://docs.bnbchain.org/announce/second-sunset-bc/ Hardfork on July 14 2024 6:00:00 AM UTC. Requires BC node v0.10.22 with SecondSunsetHeight = 378062790. All TimeLocks and AtomicSwaps on BC will be automatically refunded; BSC delegations will be automatically undelegated and refunded after the unbonding period. ## BNB Beacon Chain Token Recovery Tool: Phase 2 > Source: https://docs.bnbchain.org/announce/token-recovery-sunset-phase2/ Effective 1 May 2026, the token recovery tool enters Phase 2 of its sunset plan. Requests are batch-processed with recovery times up to one month. Users should submit recovery requests before 1 July 2026, when the hosted tool is discontinued. Only BEP2 tokens mirrored to BEP20 tokens on BSC are eligible. ## BNB Beacon Chain Token Recovery Tool: Phase 3 — Self-Service Recovery > Source: https://docs.bnbchain.org/announce/token-recovery-sunset-phase3/ Effective 1 July 2026, the hosted token recovery tool is discontinued. Users must use the open-source Token Recover Self-Service Tool. The local web app allows recovery of BEP2 and BEP8 tokens from BNB Beacon Chain to BSC without third-party custody. Requires Node.js 24+, a Beacon Chain address and wallet, a BSC wallet with a small amount of BNB for gas. The guided flow includes generating a signed message, obtaining a Merkle proof approval, and submitting the recovery transaction to contract 0x0000000000000000000000000000000000003000. ## BNB Beacon Chain Token Recovery Tool: Sunset Plan > Source: https://docs.bnbchain.org/announce/token-recovery-sunset-plan/ # BNB Beacon Chain Token Recovery Tool: Sunset Plan
Notice
The official [BNB Beacon Chain Token Recovery Tool](https://www.bnbchain.org/en/token-recovery), which allows asset migration from BNB Beacon Chain to BNB Smart Chain, is entering its sunset phase. As the tool phases out, BNB Beacon Chain asset holders are urged to act promptly for faster processing times. For the full announcement, see the [BNB Chain blog post](https://www.bnbchain.org/en/blog/bnb-beacon-chain-token-recovery-tool-sunset-plan). ## Actions for BNB Beacon Chain Asset Holders BNB Beacon Chain asset holders should migrate their tokens to BNB Smart Chain using the [Token Recovery Tool](https://www.bnbchain.org/en/token-recovery) as soon as possible for faster processing times. ### What Can Be Recovered? Only BEP2 tokens (on BNB Beacon Chain) that are mirrored to BEP20 tokens (on BNB Smart Chain) are eligible for recovery. Tokens that were never mirrored are ineligible for recovery. Permissionless mirroring (BEP84) is permanently disabled and will not be re-enabled. ### How to Recover Visit the [Token Recovery Tool](https://www.bnbchain.org/en/token-recovery) to recover your assets. For step-by-step instructions, refer to the [Token Recovery dApp guide](../bc-fusion/post-fusion/token-recovery.md). ## Sunset Timeline The sunset will occur in three phases, with recovery times increasing with each phase: | Phase | Period | Processing | | ----- | ------ | ---------- | | **Phase 1** | Now till 30 April 2026 | The tool operates normally with recovery requests processed within a **7-day SLA**. | | **Phase 2** | 1 May – 30 June 2026 | Recovery requests will be batch-processed with recovery times extended to a **1-month SLA**. | | **Phase 3** | 1 July 2026 onwards | Recovery process will be manual and require user transaction signing. The hosted tool will be discontinued. See the [Phase 3 self-service announcement](./token-recovery-sunset-phase3.md). | ## Act Now To avoid delays and complications, BNB Beacon Chain asset holders are encouraged to take action as soon as possible before the recovery tool phases out. Start migrating using the [Token Recovery Tool](https://www.bnbchain.org/en/token-recovery). ## Veld Upgrade of Greenfield > Source: https://docs.bnbchain.org/announce/veld-greenfield/ # Veld Upgrade of Greenfield
Hardfork
## Upgrade Timeline - Testnet: June 25 2024 07:00:00 AM UTC Blockheight: 9,581,218 - Mainnet: July 8 2024 07:00:00 AM UTC Blockheight: 9,269,910 ## Validators and SPs should complete upgrading to the latest version before hardfork: For Validators: greenfield [v1.8.0](https://github.com/bnb-chain/greenfield/releases/tag/v1.8.0) For SPs: greenfield-storage-provider [v1.8.0](https://github.com/bnb-chain/greenfield-storage-provider/releases/tag/v1.8.0) ## New features introduced: No new feature is introduced. ## Bug fixing * [#621](https://github.com/bnb-chain/greenfield/pull/621) fix: add bucket status to bucket migration related events * [#625](https://github.com/bnb-chain/greenfield/pull/625) fix: discontinued bucket can't be migrated * [#626](https://github.com/bnb-chain/greenfield/pull/626) fix: principal value supports group name * [#632](https://github.com/bnb-chain/greenfield/pull/632) fix: ignore register channel error ## Wright Upgrade of opBNB > Source: https://docs.bnbchain.org/announce/wright-opbnb/ # Wright Upgrade of opBNB
Hardfork
## Upgrade Timeline The Wright upgrade will happen at: - Testnet: August 15 2024, 06:00:00 AM UTC - Mainnet: August 27 2024 06:00:00 AM UTC ## Upgrade opBNB op-geth to v0.4.5 Before Hardfork op-geth need to be upgraded before the hardfork time. - https://github.com/bnb-chain/op-geth/releases/tag/v0.4.5 op-node upgrade is optional but recommended. - https://github.com/bnb-chain/opbnb/releases/tag/v0.4.4 ## Key Highlight: [gasless feature support](https://github.com/bnb-chain/op-geth/pull/130) To support gasless transactions on opBNB, the following features have been introduced: - The base fee is set to 0. - The bundle feature is supported. - When the gas price is set to 0, the L1 fee will also be set to 0. Combined with these features and a sponsor (paymaster), users can send transactions without holding BNB to pay gas fees. ## BSC > Source: https://docs.bnbchain.org/faq/bsc/ # BNB Smart Chain FAQs FAQs for BNB Smart Chain. New questions are added here by the FAQ pipeline. Existing articles: - [Recovering Tokens Sent to Wrong Chain or Address](../../bnb-smart-chain/faq/recovering-tokens-sent-to-wrong-chain-or-address.md) - [Tokens Not Showing in Wallet](../../bnb-smart-chain/faq/tokens-not-showing-in-wallet.md) - [Transfer NEXO from Tangem into BSC](../../bnb-smart-chain/faq/transfer-nexo-from-tangem-into-bsc.md) - [Lorentz Hard Fork Upgrade](../../bnb-smart-chain/faq/lorentz-hard-fork-upgrade.md) ## FAQ > Source: https://docs.bnbchain.org/faq/ # FAQ Support FAQs for BNB Chain, grouped by network. - [BNB Smart Chain](./bsc/index.md) - [opBNB](./opbnb/index.md) ## opBNB > Source: https://docs.bnbchain.org/faq/opbnb/ # opBNB FAQs FAQs for opBNB. New questions are added here by the FAQ pipeline. Existing articles: - [Protocol FAQs](../../bnb-opbnb/faq/protocol-faqs.md) - [Gas and Fees FAQs](../../bnb-opbnb/faq/gas-and-fees-faqs.md) - [opBNB Bridge FAQs](../../bnb-opbnb/faq/opbnb-bridge-faqs.md) - [Cross Chain FAQs](../../bnb-opbnb/faq/cross-chain-faqs.md) - [Build on opBNB FAQs](../../bnb-opbnb/faq/build-on-opbnb-faqs.md)