Build Your First Agent

Follow this tutorial to build a simple on-chain Counter Agent. The agent consists of a Python smart contract that increments an on-chain counter, paired with an off-chain script that interacts with the contract on a schedule.

Project Setup

Initialize your project workspace directory using templates:

bash
mycelium init counter_agent --yes
cd counter_agent

Set up your local wallet credentials and keypair:

bash
mycelium newwallet --passphrase "securepass"

Fund your wallet using Friendbot to request test XLM:

bash
mycelium fund

Write the Smart Contract

Write your contract state and external methods in `contract.py`. Replace its content with the following:

contract.pypython
"""Simple on-chain counter contract with ownership constraints."""
count: uint256
owner: address

@external
def __init__():
    self.owner = msg_sender
    self.count = 0

@external
def increment():
    self.count = self.count + 1

@external
@view
def get_count() -> uint256:
    return self.count

@external
def reset():
    assert(msg_sender == self.owner, "Only owner can reset")
    self.count = 0

Write the Agent Execution Logic

Next, edit the off-chain script `agent.py` to trigger transaction requests using the Mycelium SDK:

agent.pypython
from mycelium import AgentContext, HiveClient

# Load the local wallet context
ctx = AgentContext(
    keypair_path=".mycelium/wallet.json",
    network_type="testnet",
    passphrase="securepass"
)

# Fetch the current value using a read-only transaction simulation
count = ctx.call_contract(
    contract_id=ctx.config.contract_id,
    function_name="get_count",
    args=[],
    read_only=True,
)
print(f"Current count: {count}")

# Dispatch an increment transaction (requires fee & signature)
tx = ctx.call_contract(
    contract_id=ctx.config.contract_id,
    function_name="increment",
    args=[],
)
print(f"Increment transaction successful! Hash: {tx.hash}")

Run Locally

Check the contract type signatures and syntax structures:

bash
mycelium check contract.py

Run contract calls in local simulation mode to test your logic:

bash
mycelium test

Execute the live agent loop:

bash
mycelium run
Mycelium v0.1.0-alpha ยท Stellar Testnet