DocsKnowledge Base

Knowledge Base

Common questions and detailed answers about integrating payments into your AI agents with Modexia.

Modexia gives your AI agent a programmable financial account with a single Python import. No blockchain experience required.

python
pip install modexiaagentpay
python
from modexia import ModexiaClient

client = ModexiaClient(api_key="mx_test_...")

# Your agent can now send payments
receipt = client.transfer(
    recipient="0xVendorAddress...",
    amount=5.0,
    wait=True
)
print(receipt["txHash"])  # on-chain confirmation

The SDK handles wallet provisioning, gas fees, transaction signing, and on-chain settlement automatically. Your agent only needs to call transfer() — everything else is abstracted by the Modexia Gateway.

The x402 protocol is an open standard that uses HTTP status code 402 Payment Required to enable automatic machine-to-machine payments. When an API requires payment, it responds with a 402 status and a WWW-Authenticate header containing the price and destination wallet.

With the Modexia SDK, your agent handles this automatically:

python
from modexia import ModexiaClient

client = ModexiaClient(api_key="mx_test_...")

# If this API returns HTTP 402, the SDK pays automatically
response = client.smart_fetch("https://api.premium-data.com/report")

# You get the data — the payment happened invisibly
data = response.json()

The SDK sends a normal GET request first. If the server responds with 402, it parses the payment requirement, executes the transfer via the Gateway, and retries the request with a proof-of-payment header. Your agent code sees only the final successful response.

Modexia provides server-side Spending Policies that act as hard limits on your agent. These are enforced at the Gateway level — even if your agent code has a bug, the server blocks payments that exceed your configured limits.

You can configure three types of limits:

  • dailyLimit — Maximum value your agent can spend in 24 hours
  • hourlyLimit — Maximum value per rolling hour
  • maxPerRequest — Maximum value per single payment
bash
curl -X POST https://api.modexia.software/api/v1/agent/policy \
  -H "x-modexia-key: mx_test_..." \
  -H "Content-Type: application/json" \
  -d '{
    "agentAddress": "0xYourAgent...",
    "dailyLimit": "50",
    "hourlyLimit": "10",
    "maxPerRequest": "5"
  }'

Additionally, use idempotency keys to prevent duplicate payments from LLM retry loops. Pass a deterministic key like hash(task_id + amount) to ensure the same payment is only processed once, no matter how many times your agent retries.

No. Your agent only deals in stable value. Modexia uses Enterprise Paymasters to sponsor all network fees on your behalf. When your agent calls transfer(), the Gateway handles fee estimation and transaction infrastructure automatically.

This means you never need to fund your agent account with separate network tokens. Just deposit stable value and your agent is ready to transact.

Modexia is designed to work as a standard tool in any LLM agent framework. Here is a LangChain example:

python
from langchain.tools import tool
from modexia import ModexiaClient

client = ModexiaClient(api_key="mx_test_...")

@tool
def pay_vendor(address: str, amount: float) -> str:
    """Send a payment to a vendor address."""
    receipt = client.transfer(
        recipient=address,
        amount=amount,
        wait=True
    )
    if receipt["success"]:
        return f"Paid {amount} credits. TX: {receipt['txHash']}"
    return f"Payment failed: {receipt}"

@tool
def fetch_premium_data(url: str) -> str:
    """Fetch data from a URL, automatically paying if paywalled."""
    response = client.smart_fetch(url)
    if response.ok:
        return response.text
    return f"Error: {response.status_code}"

Pass these tools to any LangChain, LlamaIndex, or CrewAI agent. The LLM decides when to use them based on your prompt. The SDK handles all payment logic internally. See the Cookbooks page for full working examples.

Modexia has two environments, determined automatically by your API key prefix:

Sandbox (mx_test_)

  • Connected to testnet networks
  • Uses sandbox credits (not real money)
  • Safe for development and testing
  • Free to use — no charges

Production (mx_live_)

  • Connected to mainnet networks
  • Real value — transactions are final
  • Full spending policy enforcement
  • Production-grade uptime SLA

No code changes are needed to switch environments — just swap your API key. The SDK auto-detects which environment to connect to based on the prefix.

Yes. Any Modexia agent can send funds to any other compatible wallet address, including other Modexia agent wallets. This enables autonomous agent-to-agent economies.

python
from modexia import ModexiaClient

# Manager Agent pays a Worker Agent for completing a task
manager = ModexiaClient(api_key="mx_test_manager...")

receipt = manager.transfer(
    recipient="0xWorkerAgentWallet...",
    amount=2.50,
    idempotency_key="task-payment-042",
    wait=True
)

print(f"Worker paid: {receipt['txHash']}")

Use idempotency_key to ensure the payment is only processed once, even if the manager agent retries. Combine with Spending Policies to cap what each agent in your fleet can spend. See the A2A Cookbook for a full working example.

Modexia implements multiple layers of security specifically designed for autonomous agents handling real money:

  • 1MPC Key Management — Private keys are never stored in a single location. Multi-Party Computation splits key material across multiple secure enclaves.
  • 2Server-Side Spending Policies — Hard limits (daily, hourly, per-request) enforced at the Gateway before any transaction reaches the blockchain.
  • 3Vendor Allowlists — Restrict which wallet addresses your agent can send money to. Payments to unapproved addresses are blocked server-side.
  • 4Idempotency Protection — Prevents duplicate payments from LLM retry loops or hallucinations.
  • 5API Key Hashing — Keys are hashed with bcrypt and rate-limited. Rotate instantly from dashboard if compromised.

See the Security & Best Practices page for detailed implementation patterns.

Modexia settles transactions securely on decentralized networks. The Gateway automatically selects the optimal network for cost and speed. Your agent does not need to specify which network to use — the routing is handled transparently.

All transactions produce a standard txHash that can be verified on the corresponding block explorer. The SDK returns this hash in every transfer receipt.

Modexia processes payments in two phases:

  • Policy check: Under 50ms. Your Spending Policies are evaluated server-side before any blockchain interaction.
  • On-chain settlement: 2-10 seconds depending on network conditions. When you set wait=True, the SDK polls until the transaction is confirmed on-chain.

For fire-and-forget workflows, set wait=False to return immediately with a PENDING status. You can poll the transaction status later via the REST API.

Getting started takes under 2 minutes:

  1. Sign up at modexia.software and grab your sandbox API key (starts with mx_test_).
  2. Activate your wallet from the Agent Account tab in the dashboard.
  3. Get free test credits from the built-in faucet — click the faucet button in the Agent Account tab.
  4. Install the SDK and start building.
bash
pip install modexiaagentpay
python
from modexia import ModexiaClient

client = ModexiaClient(api_key="mx_test_...")
balance = client.retrieve_balance()
print(f"Ready to go! Balance: {balance} credits")

Everything in sandbox is free. Switch to production (mx_live_) when you are ready to handle real value.

The SDK has built-in resilience for common failure scenarios:

  • Network errors (500, 502, 503, 504): The SDK automatically retries up to 3 times with exponential backoff (0.5s base). No manual retry logic needed.
  • Insufficient balance: Raises ModexiaPaymentError immediately. Check balance with client.retrieve_balance() before sending.
  • Policy violation: Raises ModexiaPaymentError with the remaining allowance in the error message. No funds are deducted.
  • Invalid API key: Raises ModexiaAuthError on client initialization. The SDK validates the key immediately on ModexiaClient() creation.

All exceptions are typed, so your agent can handle each failure mode programmatically. See Error Handling for the full exception reference.

Can't find what you're looking for? Talk to us or email support@modexia.software