API Reference¶
Complete reference for all public classes and methods.
Core¶
ErgoNode¶
ergo_agent.core.node.ErgoNode(node_url=PUBLIC_NODE_URL, explorer_url=PUBLIC_EXPLORER_URL, api_key=None, timeout=15.0)
¶
Synchronous client for the Ergo blockchain. Uses the public Explorer API by default — no node required.
Usage
node = ErgoNode() # uses public API node = ErgoNode(node_url="http://localhost:9053", api_key="secret")
Functions¶
get_height()
¶
Return current blockchain height.
get_network_info()
¶
Return full network state info.
get_balance(address)
¶
Return the ERG and token balance for an address.
Returns:
| Name | Type | Description |
|---|---|---|
Balance |
Balance
|
structured balance with ERG float and token list. |
get_unspent_boxes(address, limit=50)
¶
Return unspent boxes (UTXOs) for an address.
get_transaction_history(address, offset=0, limit=20)
¶
Get recent transaction history for an address.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
address
|
str
|
Ergo address |
required |
offset
|
int
|
pagination offset |
0
|
limit
|
int
|
max transactions to return (default 20) |
20
|
Returns:
| Type | Description |
|---|---|
list[Transaction]
|
list[Transaction]: recent transactions, newest first |
get_mempool_transactions(address)
¶
Return pending (unconfirmed) transactions for an address.
get_oracle_pool_box(oracle_pool_nft_id)
¶
Fetch the live oracle pool box by its NFT ID. Used to read ERG/USD price and other data feeds.
The price is stored in register R4 as nanoERG per 1 USD cent.
submit_transaction(signed_tx)
¶
Submit a signed transaction to the network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signed_tx
|
dict[str, Any]
|
signed transaction as a dict (ErgoTransaction format) |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
transaction ID |
close()
¶
Close the underlying HTTP client.
Wallet¶
ergo_agent.core.wallet.Wallet(address, _private_key_hex=None, _node_wallet=False, read_only=False)
¶
Ergo wallet — holds the private key material and signs transactions.
Usage
wallet = Wallet.from_mnemonic("word1 word2 ...") wallet = Wallet.from_node(node, wallet_password="secret") # uses node's built-in wallet wallet = Wallet.read_only(address="9f...") # no signing, query only
Attributes¶
address = address
instance-attribute
¶
Functions¶
read_only(address)
classmethod
¶
Read-only wallet -- can query balances and build transactions, but cannot sign. Useful for monitoring agents.
from_node_wallet(node_address)
classmethod
¶
Use the Ergo node's built-in wallet for signing. The node handles key storage and signing -- this SDK just triggers it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_address
|
str
|
the address from the node's loaded wallet |
required |
from_mnemonic(mnemonic, passphrase='')
classmethod
¶
Create a wallet from a BIP39 mnemonic phrase.
Not yet implemented. Requires ergo-lib (sigma-rust) Python bindings for proper BIP32/44 key derivation (path m/44'/429'/0'/0/0).
For now, use Wallet.from_node_wallet() or Wallet.read_only() instead.
sign_transaction(unsigned_tx, node=None)
¶
Sign an unsigned transaction.
If using a node wallet, the node signs it. If using local keys, signs with the private key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unsigned_tx
|
dict[str, Any]
|
the unsigned transaction dict |
required |
node
|
Any | None
|
ErgoNode instance (required for node_wallet mode) |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, Any]
|
signed transaction ready for submission |
TransactionBuilder¶
ergo_agent.core.builder.TransactionBuilder(node, wallet)
¶
Fluent builder for Ergo unsigned transactions.
Usage (simple transfer): tx = ( TransactionBuilder(node, wallet) .send(to="9f...", amount_erg=1.5) .with_fee(0.001) .build() )
Usage (contract interaction with context extensions): tx = ( TransactionBuilder(node, wallet) .with_input(pool_box, extension={"0": key_image_hex, "1": proof_hex}) .add_output_raw(ergo_tree=..., value_nanoerg=..., tokens=[...], registers={...}) .build() )
The builder: - Validates all destination addresses (checksum + network byte) - Supports explicit input boxes (for spending contract UTXOs) - Supports context extensions on inputs (for getVar() in ErgoScript) - Automatically selects additional wallet UTXOs if explicit inputs aren't enough - Converts addresses to ErgoTree hex (P2PK direct, P2S/P2SH via API) - Calculates change output - Returns an unsigned tx dict ready for signing
Functions¶
send(to, amount_erg)
¶
Add a simple ERG transfer output.
send_token(to, token_id, amount)
¶
Add a token transfer output (also sends minimum ERG dust to the box).
add_output_raw(ergo_tree, value_nanoerg, tokens=None, registers=None)
¶
Add a raw output box (for custom contract interactions like DEX swaps).
with_input(box, extension=None)
¶
Add an explicit input box (for spending contract boxes like PoolBoxes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
box
|
Box | str
|
a Box object or a box ID string. If a string, the box will be fetched from the node when build() is called. |
required |
extension
|
dict[str, str] | None
|
context extension variables for this input. Keys are variable IDs (as strings, e.g. "0", "1"), values are serialized hex strings. These correspond to getVarT calls in ErgoScript. |
None
|
Example
builder.with_input(pool_box, extension={ "0": key_image_group_element_hex, "1": avl_tree_insert_proof_hex, })
build()
¶
Build the unsigned transaction dict.
Supports three input modes: 1. Auto-selection only (default): selects wallet UTXOs to cover outputs + fee 2. Explicit only: uses only with_input() boxes 3. Mixed: explicit inputs first, then auto-selects wallet UTXOs for the remainder
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, Any]
|
unsigned transaction in Ergo API format |
Address Utilities¶
ergo_agent.core.address
¶
Ergo address utilities: validation, encoding, ErgoTree resolution.
Ergo uses a custom Base58 encoding with Blake2b-256 checksums. Address format: network_byte + content_bytes + checksum (4 bytes)
Network types
- 0x01 = mainnet P2PK
- 0x02 = mainnet P2SH
- 0x03 = mainnet P2S
- 0x10 = testnet P2PK etc.
Reference: https://docs.ergoplatform.com/dev/wallet/address/
Classes¶
AddressError
¶
Bases: Exception
Raised for invalid Ergo addresses.
Functions¶
is_valid_address(address)
¶
Check if an Ergo address is valid without raising exceptions.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if valid, False otherwise |
validate_address(address)
¶
Validate an Ergo address (checksum + network byte check).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
address
|
str
|
Ergo address string (Base58 encoded) |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if valid |
Raises:
| Type | Description |
|---|---|
AddressError
|
if the address is malformed or has a bad checksum |
is_mainnet_address(address)
¶
Check if address is a mainnet address.
is_p2pk_address(address)
¶
Check if address is a P2PK (pay-to-public-key) address.
get_address_type(address)
¶
Return a human-readable address type.
address_to_ergo_tree(address, node_url='https://api.ergoplatform.com')
¶
Convert an Ergo address to its ErgoTree hex representation.
Uses the Ergo node/explorer API for reliable conversion. For P2PK addresses, the ErgoTree has a known format that can be derived directly. For P2S/P2SH we must use the API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
address
|
str
|
valid Ergo address |
required |
node_url
|
str
|
Ergo node or explorer API URL |
'https://api.ergoplatform.com'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
ErgoTree hex string |
Data Models¶
ergo_agent.core.models.Box
¶
ergo_agent.core.models.Balance
¶
ergo_agent.core.models.Token
¶
ergo_agent.core.models.SwapQuote
¶
ergo_agent.core.models.Transaction
¶
Bases: BaseModel
A submitted or confirmed transaction.
DeFi¶
OracleReader¶
ergo_agent.defi.oracle.OracleReader(node)
¶
Read live prices from the Ergo Oracle Pool v2.
Usage
oracle = OracleReader(node) price = oracle.get_erg_usd_price() # e.g. 0.87 print(f"ERG/USD: ${price:.2f}")
Functions¶
get_erg_usd_price()
¶
Return the current ERG/USD price from the oracle pool.
The oracle R4 value is nanoERG per 1 USD. We convert: price_usd = NANOERG_PER_ERG / nanoERG_per_USD
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
ERG price in USD (e.g. 0.31 means 1 ERG = $0.31) |
get_erg_usd_nanoerg_per_usd()
¶
Return the raw oracle value: nanoERG per 1 USD. This is the value used directly in ErgoScript contracts.
get_oracle_box_id(pair='erg_usd')
¶
Return the current oracle pool box ID. Used when adding an oracle box as a data input to a transaction.
SpectrumDEX¶
ergo_agent.defi.spectrum.SpectrumDEX(node, api_url=SPECTRUM_API, timeout=15.0)
¶
Adapter for Spectrum Finance DEX on Ergo.
Usage
dex = SpectrumDEX(node) markets = dex.get_pools() quote = dex.get_quote(token_in="ERG", token_out="SigUSD", amount_erg=10.0) print(f"You get: {quote.token_out_amount} SigUSD")
Functions¶
get_pools(offset=0, limit=100)
¶
Fetch active Spectrum markets (trading pairs).
Returns:
| Type | Description |
|---|---|
list[Market]
|
list[Market]: sorted by volume descending |
get_erg_price_in_sigusd()
¶
Convenience: get ERG/USD price from DEX pool directly. Note: use OracleReader for the canonical on-chain oracle price.
get_quote(token_in, token_out, amount_erg=None, amount_token=None)
¶
Get a swap quote for a given input.
This uses the Spectrum API's last price data to estimate the output. Note: for exact on-chain output, pool box reserves should be read directly. The API price gives a good approximation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_in
|
str
|
input token (name or ID, use "ERG" for native ERG) |
required |
token_out
|
str
|
output token (name or ID) |
required |
amount_erg
|
float | None
|
if token_in is ERG, specify amount in ERG |
None
|
amount_token
|
int | None
|
if token_in is a token, specify raw amount |
None
|
Returns:
| Type | Description |
|---|---|
SwapQuote
|
SwapQuote with expected output amount and price impact |
build_swap_order(token_in, token_out, amount_erg, return_address, min_output=None, max_slippage_pct=1.0)
¶
Build a Spectrum DEX swap order dict for TransactionBuilder.add_output_raw().
On Ergo's eUTXO model, DEX swaps work via order boxes: 1. User creates an order box containing ERG + order parameters 2. Spectrum off-chain bots detect this box and execute the swap 3. User receives output tokens in a new box at their address
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_in
|
str
|
input token name (e.g. "ERG") |
required |
token_out
|
str
|
output token name (e.g. "SigUSD") |
required |
amount_erg
|
float
|
amount of ERG to swap |
required |
return_address
|
str
|
address to receive output tokens |
required |
min_output
|
int | None
|
minimum acceptable output amount (auto-calculated if None) |
None
|
max_slippage_pct
|
float
|
max slippage for auto min_output calculation |
1.0
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict with 'ergo_tree', 'value_nanoerg', 'tokens', 'registers' |
dict[str, Any]
|
ready for TransactionBuilder.add_output_raw() |
close()
¶
Tools¶
ErgoToolkit¶
ergo_agent.tools.toolkit.ErgoToolkit(node, wallet, safety=None)
¶
Unified AI agent toolkit for the Ergo blockchain.
All methods are safe to call directly from an LLM's tool-calling loop. Every state-changing action is validated by the SafetyConfig before execution.
Functions¶
get_wallet_balance()
¶
Get the current ERG and token balance of the agent's wallet.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict with 'erg' (float), 'tokens' (list), and 'summary' (str) |
get_erg_price()
¶
Get the current ERG/USD price from the Ergo Oracle Pool.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict with 'erg_usd' (float) and 'source' (str) |
get_swap_quote(token_in, token_out, amount_erg=None, amount_token=None)
¶
Get a swap quote from Spectrum DEX without executing it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_in
|
str
|
Input token (e.g. "ERG", "SigUSD") |
required |
token_out
|
str
|
Output token (e.g. "SigUSD", "ERG") |
required |
amount_erg
|
float | None
|
Amount in ERG if token_in is ERG |
None
|
amount_token
|
int | None
|
Raw token amount if token_in is a token |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict with expected output, price impact, and fee info |
get_mempool_status()
¶
Check for pending transactions from this wallet.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict with pending transaction count and tx IDs |
get_safety_status()
¶
Get current safety limits and usage status.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict with remaining daily budget, rate limit status, etc. |
send_erg(to, amount_erg)
¶
Send ERG to an address.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
to
|
str
|
Destination Ergo address |
required |
amount_erg
|
float
|
Amount to send in ERG |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict with tx_id (or dry_run confirmation) |
swap_erg_for_token(token_out, amount_erg, max_slippage_pct=1.0)
¶
Swap ERG for a token on Spectrum DEX.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_out
|
str
|
Token to receive (e.g. "SigUSD") |
required |
amount_erg
|
float
|
Amount of ERG to spend |
required |
max_slippage_pct
|
float
|
Maximum acceptable price impact (default 1%) |
1.0
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict with quote info and tx_id (or dry_run confirmation) |
execute_tool(tool_name, tool_input)
¶
Execute a tool by name with given inputs. Used by LLM frameworks to dispatch tool calls.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
JSON-encoded result |
to_openai_tools()
¶
Generate OpenAI function-calling tool definitions.
to_anthropic_tools()
¶
Generate Anthropic tool-use definitions.
to_langchain_tools()
¶
Generate LangChain BaseTool instances.
SafetyConfig¶
ergo_agent.tools.safety.SafetyConfig(max_erg_per_tx=10.0, max_erg_per_day=50.0, allowed_contracts=(lambda: ['spectrum', 'sigmausd'])(), rate_limit_per_hour=20, dry_run=False, _action_timestamps=deque(), _daily_spend_log=list())
dataclass
¶
Configuration for agent spending limits and operational boundaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_erg_per_tx
|
float
|
Hard cap on ERG per single transaction |
10.0
|
max_erg_per_day
|
float
|
Rolling 24h cap on total ERG spent |
50.0
|
allowed_contracts
|
list[str]
|
Whitelist of allowed interaction targets. Use protocol names ("spectrum", "sigmausd", "rosen") or raw Ergo addresses. |
(lambda: ['spectrum', 'sigmausd'])()
|
rate_limit_per_hour
|
int
|
Max number of state-changing actions per hour |
20
|
dry_run
|
bool
|
If True, build transactions but never submit them |
False
|
Functions¶
validate_send(amount_erg, destination)
¶
Validate a send action. Raises SafetyViolation if any limit is exceeded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amount_erg
|
float
|
amount to send in ERG |
required |
destination
|
str
|
target address or protocol name |
required |
validate_rate_limit()
¶
Check that the agent hasn't exceeded the hourly action rate.
record_action(erg_spent=0.0)
¶
Record a completed action for rate limiting and daily spend tracking.
get_status()
¶
Return current safety status for agent awareness.
ergo_agent.tools.safety.SafetyViolation
¶
Bases: Exception
Raised when an agent action violates the configured safety rules.