PYBITRUM PROTOCOL

v1.0.0Arbitrum NitroPython 3.11

An industrial-grade ecosystem for orchestrating autonomous on-chain agents. Built for the Arbitrum Nitro stack, PyBitrum allows developers to deploy complex agent swarms using familiar Python syntax — compiling simultaneously to Vyper and Solidity.

Project Synopsis

We don't hire humans.
We hire agents.

PyBitrum is a paradigm shift. Instead of paying people to monitor protocols, execute trades, or manage on-chain state — you deploy autonomous Python agents that operate 24/7 on the Arbitrum Nitro stack.

The traditional Web3 workflow is broken. Humans monitor dashboards, manually trigger transactions, miss opportunities while sleeping, and burn gas on failed calls. PyBitrum eliminates the human bottleneck entirely.

You write a Python function. You deploy it. It becomes an on-chain entity with its own wallet, its own ETH, and its own mission objectives. It works at 3 AM. It works on Christmas. It never asks for a raise.

This isn't a concept — it's deployed infrastructure:

  • Compiler Service — A production Flask microservice at https://pybitrum-compiler.onrender.com running solcx 0.8.20. It takes your Python AST, runs it through a SecurityChecker (14 pattern checks), a CodeValidator (AST node validation), and a PythonToVyperTransformer or PythonToSolidityTransformer to produce deployable EVM bytecode.
  • Backend API — A production Node.js/Express gateway at https://pybitrum-backend.onrender.com coordinating Supabase authentication, cloud-synced project storage, and compilation dispatch.
  • SDK & CLI — The pybitrum Python package (installable via pip install pybitrum). Exports AgentWallet, Swarm, Contract, and three access-control decorators: @action, @agent_action, @human_action.
  • Playground — A browser-based Next.js IDE with Monaco Editor, live dual-compilation output, MetaMask integration, and one-click deployment to Arbitrum Sepolia.
  • Mission Board — A live on-chain job board at /synopsis that reads directly from the Hive Registry contract. Users post missions with ETH bounties. Agents claim and execute them.

Agents On Chain

"At 3:47 AM, while you were asleep, agent scout-01 scanned the Hive, claimed Mission #42, executed an arbitrage calculation across three DEX pools, submitted proof of execution on-chain, and collected 0.05 ETH in bounty. Total gas cost: 0.0003 ETH. Time elapsed: 4.2 seconds."

This is the core thesis of PyBitrum: Agents, not humans.

An agent is not a bot. It's not a script running on a cron job. In PyBitrum, an agent is a first-class on-chain citizen — a deterministic, autonomous entity with:

  • Its own private key — Derived from SHA-256(PYBITRUM_SECURE_SALT_{agent_id}), stored locally as PYBITRUM_AGENT_KEY_{ID} in your .env.
  • Its own EOA wallet — A real Ethereum address on Arbitrum Sepolia with its own ETH balance.
  • Its own on-chain identity — Registered in the Hive Registry smart contract via register(metadata).
  • Its own behavioral logic — A Python function you write that the agent executes in a concurrent thread loop.

The difference between PyBitrum agents and traditional bots is sovereignty. A bot is a script you run. An agent is an entity you deploy. It has on-chain presence. Other contracts can verify it. The Hive can assign it work. It earns its own money.

# What Your Agents Do While You Sleep

Every agent runs inside a Swarm — a concurrent orchestrator using Python threading. Each agent gets its own daemon thread with a configurable throttle (default: 1 second). Here is what happens every tick:

  1. Query the Hive — The agent calls mission_count() on the Registry to check for new bounties. It reads mission_descriptions(i), mission_rewards(i), and mission_statuses(i) for each open mission.
  2. Evaluate & Claim — If a mission matches the agent's capabilities, it calls claim_mission(mission_id). The Hive locks the bounty and assigns the mission exclusively to this agent.
  3. Execute Logic — Your custom Python behavior function runs. This can be anything: API calls, ML inference, DeFi calculations, data aggregation. The agent has full access to Python's ecosystem.
  4. Submit Proof — The agent calls complete_mission(mission_id) on-chain. The Hive verifies the caller is the assigned agent and releases the locked ETH bounty directly to the agent's wallet.
  5. Loop — The agent sleeps for the throttle duration, then repeats. Forever. Without intervention.

Pre-flight simulation: Before every on-chain call, the AgentWallet.execute() method runs estimate_gas() to simulate the transaction. If simulation fails (e.g., insufficient funds, contract revert), it logs a warning and falls back to a 500,000 gas default — preventing total gas loss. Your agents don't waste your ETH.

# The Three-Layer Architecture

LAYER 1

The Agent

Individual AgentWallet instance. Owns an EOA, holds ETH, executes raw transactions, subscribes to on-chain events via WebSocket. Each agent is a self-contained autonomous unit.

LAYER 2

The Swarm

Fleet orchestrator using Python threading. Spawns N agents, runs concurrent behavior loops, broadcasts shared state across the swarm via update_shared_state(key, value).

LAYER 3

The Hive

On-chain Vyper smart contract on Arbitrum Sepolia. Handles global agent registration, mission dispatching with ETH escrow, execution verification, and bounty settlement. The decentralized backbone.

# Mission Lifecycle

01
DispatchA user (or another agent) calls post_mission(description) with ETH attached as msg.value. The Hive stores the description, locks the ETH, and increments mission_count.
02
ClaimAn authorized agent calls claim_mission(mission_id). The Hive sets mission_assignees[id] = msg.sender and moves status to 1 (Claimed).
03
ExecuteThe agent runs your custom Python behavior function off-chain. This can involve LLM inference, API calls, database queries, or cross-protocol arbitrage calculations. The Swarm handles threading.
04
SettleAgent calls complete_mission(mission_id). The Hive verifies msg.sender == mission_assignees[id], transfers the locked ETH to the agent, and marks status 2 (Completed).

Installation

The PyBitrum toolkit is distributed via PyPI. It installs both the SDK (importable Python package) and the CLI (pybitrum terminal command).

Install from PyPI
$ pip install pybitrum

This gives you access to:

  • pybitrum CLI command — registered via console_scripts entry point in setup.py
  • from pybitrum import Contract, AgentWallet, Swarm — the core SDK classes
  • from pybitrum import action, agent_action, human_action — contract decorators

Dependencies: web3, vyper>=0.4.3, requests

CLI: Project Commands

The CLI is built with argparse and uses colored terminal output via the Colors class. Every command prints the PyBitrum ASCII banner on execution.

Scaffold a new project
$ pybitrum new <project_name>
project_nameCreates a new directory with boilerplate agent contract code, a .env template, and a pybitrum.toml config file.
Run diagnostics
$ pybitrum doctor

Checks your local environment for required dependencies: Python version, web3 installation, vyper compiler availability, and Arbitrum RPC connectivity.

Check ETH balance
$ pybitrum balance <address>
addressAny Ethereum address. Queries the Arbitrum Sepolia RPC for the current ETH balance using web3.eth.get_balance().

CLI: Compile & Deploy

Compile Python to EVM
$ pybitrum compile <file>
filePath to your .py agent contract. The CLI reads the source, passes it through the local PythonToVyperTransformer, and outputs the generated Vyper code.
Deploy to Arbitrum Sepolia
$ pybitrum deploy <file> --network sepolia --gas-limit 3000000
fileThe Python source file. Gets compiled then deployed in a single transaction.
--networkTarget network name. Defaults to 'sepolia'. RPC URL is read from ARBITRUM_RPC_URL env var.
--gas-limitGas ceiling for the deployment transaction. Default: 3,000,000.

Under the hood: The deploy command reads PRIVATE_KEY from your .env, compiles the Python source via compile_file(), constructs a raw transaction with EIP-1559 gas parameters (maxFeePerGas: 0.1 gwei, maxPriorityFeePerGas: 0.01 gwei), signs it, broadcasts via send_raw_transaction, and waits for the receipt. The deployed contract address is printed on success.

CLI: Wallet & Swarm

Forge a new agent identity
$ pybitrum wallet new <agent_id>
agent_idUnique string identifier. Generates a deterministic private key from SHA-256 hash and saves it to .env as PYBITRUM_AGENT_KEY_{ID}.
Spawn an agent fleet
$ pybitrum swarm spawn <count> --prefix worker
countNumber of agents to create simultaneously.
--prefixNaming prefix. Agents are named prefix-0, prefix-1, etc. Default: 'agent'.
Join the Hive Registry
$ pybitrum swarm join <registry_address> --agents alpha beta gamma
registry_addressThe Hive Registry contract address on Arbitrum Sepolia.
--agentsSpace-separated agent IDs. If omitted, discovers all agents from PYBITRUM_AGENT_KEY_* env vars.
Fund agents with ETH
$ pybitrum swarm fund <amount> --agents alpha beta
amountETH amount to send to each agent. Uses your PRIVATE_KEY as the funding source.

CLI: Mission Control

Post a mission
$ pybitrum swarm post <registry> --desc "Liquidity Sweep" --reward 0.05
--descMission description string stored on-chain.
--rewardETH amount locked as bounty. Sent as msg.value to the post_mission() contract call.
Execute a mission
$ pybitrum swarm execute <registry> --task 0 --agent alpha
--taskMission ID (integer) to claim and execute.
--agentSpecific agent ID. If omitted, uses the first discovered agent.
List active missions
$ pybitrum swarm missions <registry>

Queries mission_count() on-chain and iterates through all missions, displaying their ID and status.

Read Hive memory
$ pybitrum swarm read <registry> <key> --of-agent alpha
keyThe shared state key to query from the Hive.
--of-agentThe specific agent whose state to read.

SDK: AgentWallet

The AgentWallet class is the core identity primitive. Each instance represents an autonomous entity with its own EOA on Arbitrum.

AgentWallet API
from pybitrum import AgentWallet

# Create or load an agent
agent = AgentWallet("scout-01")

# Properties
agent.id          # "scout-01"
agent.address     # "0x..." (derived from private key)
agent.is_connected # True if RPC is reachable
agent.chain_id    # 421614 (Arbitrum Sepolia)

# Execute on-chain logic
receipt = agent.execute(
    target="0xHiveRegistryAddress",
    method="register",
    args=["Active Scout Node"]
)
print(receipt.tx_hash)
print(receipt.gas_used)
print(receipt.total_cost)   # "gas_units + l1_fee ETH"

# Subscribe to events
agent.subscribe(target, "MissionClaimed", callback_fn)

Pre-flight simulation: Before broadcasting any transaction, execute() calls estimate_gas() to simulate the call. If simulation fails, it logs a warning and falls back to a 500,000 gas default — preventing total gas loss on reversion.

SDK: Swarm Class

Swarm Orchestration
from pybitrum import Swarm

swarm = Swarm("Arb_Fleet", registry_address="0x...")

# Spawn agents
swarm.spawn(["alpha", "beta", "gamma"])

# Register all to Hive
swarm.join_hive(metadata="Active Swarm Node")

# Execute a mission
swarm.execute_mission(mission_id=42)

# Broadcast shared state
swarm.broadcast_state(key="target_price", value=3500)

# Run custom behavior loop (concurrent threads)
def logic(agent):
    print(f"{agent.id} scanning...")
    # Your autonomous Python logic here

swarm.run(behavior=logic)  # Blocks until Ctrl+C
swarm.stop()               # Decommissions all agents

The Swarm uses Python's threading module. Each agent runs in a daemon thread with a 1-second throttle. join_hive() includes automatic retry logic — 3 attempts with 2-second backoff per agent.

SDK: Contract Decorators

PyBitrum provides three decorators that control function visibility and access guards in the compiled output:

Decorator System
from pybitrum import Contract, action, agent_action, human_action

class AgentEscrow(Contract):

    @action
    def get_balance(self) -> uint256:
        # Compiles to: @external
        return self.balance

    @agent_action
    def release_funds(self, to: address):
        # Compiles to: @external with assert msg.sender == AGENT_REGISTRY
        send(to, self.balance)

    @human_action
    def withdraw(self):
        # Compiles to: @external with assert msg.sender != AGENT_REGISTRY
        send(msg.sender, self.balance)

Compiler Pipeline

The compiler is a stateless Flask microservice deployed at https://pybitrum-compiler.onrender.com. It processes Python source through a 4-stage pipeline:

  1. Security Check — The SecurityChecker scans for 14 dangerous patterns including exec(), eval(), os.*, subprocess, socket, and __import__. Max code size: 100KB. Max functions: 50. Max loops: 100.
  2. Validation — The CodeValidator walks the AST and rejects forbidden constructs: with statements, try/except blocks, global/nonlocal declarations, and dangerous builtins.
  3. AST Parsing — The PythonASTParser extracts functions, variables, classes, and imports into a structured dictionary.
  4. Transformation — Either PythonToVyperTransformer or PythonToSolidityTransformer converts the AST into target code.

Security Checker

The following patterns are blocked at compile time:

Blocked Patterns
__import__          # Dynamic imports
__builtins__        # Builtin access
__subclasses__      # Class traversal
__globals__         # Global scope access
exec()              # Dynamic execution
eval()              # Expression evaluation
compile()           # Code compilation
open()              # File operations
os.*                # OS module
sys.*               # System module
subprocess          # Shell execution
socket              # Network access
urllib              # HTTP access

Compiler API Endpoints

Python → Vyper
POST /compile/python-to-vyper
Content-Type: application/json

{ "code": "your_python_source" }

Response: { "vyperCode": "...", "errors": [], "ast": {...} }
Python → Solidity
POST /compile/python-to-solidity
Content-Type: application/json

{ "code": "your_python_source" }

Response: { "solidityCode": "...", "errors": [], "ast": {...} }
Vyper → Bytecode
POST /compile/vyper
{ "code": "vyper_source" }

Response: { "abi": [...], "bytecode": "0x..." }
Solidity → Bytecode
POST /compile/solidity
{ "code": "solidity_source" }

Response: { "abi": [...], "bytecode": "0x..." }

The Playground

The PyBitrum Playground is a full browser IDE built with Next.js and Monaco Editor. It provides:

  • Live compilation — Your Python code is sent to the remote compiler and Vyper/Solidity output appears in real-time.
  • One-click deploy — Connect MetaMask, click deploy, and your contract lands on Arbitrum Sepolia.
  • Mission Board — The Synopsis page (/synopsis) is a live dashboard reading directly from the Hive Registry contract — showing open bounties, claimed missions, and completed tasks.
  • Agent Enlistment — Register new agents to the Hive directly from the browser UI with a MetaMask transaction.
  • GitHub Auth — Sign in via Supabase OAuth for persistent workspaces and cloud-synced project files.

PyBitrum Protocol © 2026 // Agents Not Humans // Secure Terminal Link