OrdianDocs
ordian.ai ↗

Code Examples

Complete working examples showing wallet setup, payment, and API calls. Copy-paste and run.

ℹ️ NoteAll examples use x402 client libraries to handle payment automatically. Make sure you've set up a wallet with USDC on Base before running these.

Node.js (fetch)

Install dependencies

install.sh
npm install @x402/fetch @x402/evm viem

Complete example: create inbox + send email

agent-mail.ts
import { x402Client, wrapFetchWithPayment } from "@x402/fetch";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";

// 1. Create signer from private key
const signer = privateKeyToAccount(
  process.env.EVM_PRIVATE_KEY as `0x${string}`
);

// 2. Create x402 client with EVM payment scheme
const client = new x402Client();
registerExactEvmScheme(client, { signer });

// 3. Wrap fetch — all 402 responses are handled automatically
const f = wrapFetchWithPayment(fetch, client);

const BASE = "https://mail-api.ordian.ai";

// 4. Create an inbox
const inboxRes = await f(`${BASE}/v1/inboxes`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ display_name: "My Agent" }),
});
const inbox = await inboxRes.json();
console.log("Inbox created:", inbox.address);

// 5. Send an email
const sendRes = await f(`${BASE}/v1/send`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    inbox_id: inbox.id,
    to: "recipient@example.com",
    subject: "Hello from my AI agent",
    text: "This email was sent autonomously via the Ordian Mail API.",
  }),
});
const result = await sendRes.json();
console.log("Email queued:", result.id);

Node.js (axios)

Install dependencies

install.sh
npm install @x402/axios @x402/evm viem axios

Complete example: create inbox + send email

agent-mail-axios.ts
import { x402Client, withPaymentInterceptor } from "@x402/axios";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
import axios from "axios";

// 1. Create signer
const signer = privateKeyToAccount(
  process.env.EVM_PRIVATE_KEY as `0x${string}`
);

// 2. Create x402 client with EVM payment scheme
const client = new x402Client();
registerExactEvmScheme(client, { signer });

// 3. Wrap axios with payment interceptor
const api = withPaymentInterceptor(
  axios.create({ baseURL: "https://mail-api.ordian.ai" }),
  client
);

// 4. Create an inbox
const { data: inbox } = await api.post("/v1/inboxes", {
  display_name: "My Agent",
});
console.log("Inbox created:", inbox.address);

// 5. Send an email
const { data: result } = await api.post("/v1/send", {
  inbox_id: inbox.id,
  to: "recipient@example.com",
  subject: "Hello from my AI agent",
  text: "This email was sent autonomously via the Ordian Mail API.",
});
console.log("Email queued:", result.id);

Node.js (CDP Server Wallet)

For production agents, use a CDP Server Wallet instead of a raw private key.

install.sh
npm install @x402/fetch @x402/evm @coinbase/cdp-sdk viem dotenv
agent-mail-cdp.ts
import { x402Client, wrapFetchWithPayment } from "@x402/fetch";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { CdpClient } from "@coinbase/cdp-sdk";
import { toAccount } from "viem/accounts";
import dotenv from "dotenv";

dotenv.config();

// 1. Create CDP wallet (requires CDP_API_KEY_ID, CDP_API_KEY_SECRET, CDP_WALLET_SECRET)
const cdp = new CdpClient();
const cdpAccount = await cdp.evm.createAccount();
const signer = toAccount(cdpAccount);

console.log("Fund this address with USDC on Base:", signer.address);

// 2. Create x402 client
const client = new x402Client();
registerExactEvmScheme(client, { signer });

const f = wrapFetchWithPayment(fetch, client);

// 3. Use the API (same as private key examples)
const inboxRes = await f("https://mail-api.ordian.ai/v1/inboxes", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ display_name: "My CDP Agent" }),
});
const inbox = await inboxRes.json();
console.log("Inbox:", inbox.address);

Python

Install dependencies

install.sh
pip install "x402[httpx,evm]" eth_account

Complete example (async with httpx)

agent_mail.py
import asyncio
import os
from eth_account import Account

from x402 import x402Client
from x402.http.clients import x402HttpxClient
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact.register import register_exact_evm_client

BASE = "https://mail-api.ordian.ai"


async def main():
    # 1. Create signer from private key
    account = Account.from_key(os.getenv("EVM_PRIVATE_KEY"))
    signer = EthAccountSigner(account)

    # 2. Create x402 client with EVM payment scheme
    client = x402Client()
    register_exact_evm_client(client, signer)

    # 3. Use httpx client — 402 payments are handled automatically
    async with x402HttpxClient(client) as http:
        # Create an inbox
        response = await http.post(
            f"{BASE}/v1/inboxes",
            json={"display_name": "My Python Agent"}
        )
        await response.aread()
        inbox = response.json()
        print(f"Inbox created: {inbox['address']}")

        # Send an email
        response = await http.post(
            f"{BASE}/v1/send",
            json={
                "inbox_id": inbox["id"],
                "to": "recipient@example.com",
                "subject": "Hello from Python",
                "text": "Sent autonomously via the Ordian Mail API.",
            }
        )
        await response.aread()
        result = response.json()
        print(f"Email queued: {result['id']}")


asyncio.run(main())

Sync example (with requests)

agent_mail_sync.py
import os
from eth_account import Account

from x402 import x402ClientSync
from x402.http.clients import x402_requests
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact.register import register_exact_evm_client

BASE = "https://mail-api.ordian.ai"

# 1. Create signer
account = Account.from_key(os.getenv("EVM_PRIVATE_KEY"))
signer = EthAccountSigner(account)

# 2. Create sync x402 client
client = x402ClientSync()
register_exact_evm_client(client, signer)

# 3. Use requests session
with x402_requests(client) as session:
    # Create an inbox
    response = session.post(
        f"{BASE}/v1/inboxes",
        json={"display_name": "My Python Agent"}
    )
    inbox = response.json()
    print(f"Inbox created: {inbox['address']}")

    # Send an email
    response = session.post(
        f"{BASE}/v1/send",
        json={
            "inbox_id": inbox["id"],
            "to": "recipient@example.com",
            "subject": "Hello from Python",
            "text": "Sent autonomously via the Ordian Mail API.",
        }
    )
    result = response.json()
    print(f"Email queued: {result['id']}")

curl (manual 402 flow)

Without an SDK, you handle the 402 flow manually. This is useful for understanding the protocol or debugging.

Step 1: Make a request and get payment requirements

step1.sh
curl -s -X POST https://mail-api.ordian.ai/v1/inboxes \
  -H "Content-Type: application/json" \
  -d '{"display_name": "My Agent"}' \
  | jq .

# Returns 402 with payment requirements:
# {
#   "x402Version": 1,
#   "accepts": [{
#     "scheme": "exact",
#     "network": "base",
#     "maxAmountRequired": "100000",
#     "payTo": "0x...",
#     "resource": "POST /v1/inboxes",
#     "description": "Create an agent inbox"
#   }],
#   "error": "X-PAYMENT header is required"
# }

Step 2: Sign the payment

Using the payment requirements from Step 1, your wallet signs an EIP-3009 transferWithAuthorization for the specified USDC amount. The x402 client libraries do this automatically — for curl, you'd need a helper script to produce the signed payload.

Step 3: Retry with payment header

step3.sh
curl -X POST https://mail-api.ordian.ai/v1/inboxes \
  -H "Content-Type: application/json" \
  -H "X-PAYMENT: <base64-encoded-signed-payment>" \
  -d '{"display_name": "My Agent"}'

# Returns 200 with the created inbox:
# {
#   "id": "550e8400-e29b-41d4-a716-446655440000",
#   "address": "agent-abc123@mail.ordian.ai",
#   "display_name": "My Agent"
# }
💡 TipFor anything beyond basic debugging, use a proper x402 client library. The manual flow requires signing EIP-3009 authorizations which is non-trivial to do in shell scripts.

Health check (free — no payment needed)

health.sh
curl https://mail-api.ordian.ai/health

More examples

Send with markdown body

send-markdown.ts
const res = await f("https://mail-api.ordian.ai/v1/send", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    inbox_id: inbox.id,
    to: "recipient@example.com",
    subject: "Weekly Report",
    text: "Fallback plain text",
    markdown: "# Weekly Report\n\n- **Revenue:** $12,400\n- **Users:** 340\n- **Uptime:** 99.9%",
  }),
});

Send with attachments

send-attachment.ts
import { readFileSync } from "fs";

const fileContent = readFileSync("./report.pdf");
const base64 = fileContent.toString("base64");

const res = await f("https://mail-api.ordian.ai/v1/send", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    inbox_id: inbox.id,
    to: "recipient@example.com",
    subject: "Monthly Report",
    text: "Please find the report attached.",
    attachments: [{
      filename: "report.pdf",
      content: base64,
      content_type: "application/pdf",
    }],
  }),
});

Read inbox messages

read-messages.ts
const messagesRes = await f(
  `https://mail-api.ordian.ai/v1/inboxes/${inbox.id}/messages?limit=10`
);
const messages = await messagesRes.json();

for (const msg of messages.data) {
  console.log(`From: ${msg.from_address}`);
  console.log(`Subject: ${msg.subject}`);
  console.log(`Body: ${msg.text_body?.slice(0, 100)}...`);
  console.log("---");
}

Register a webhook

webhook.ts
const webhookRes = await f("https://mail-api.ordian.ai/v1/webhooks", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    inbox_id: inbox.id,
    url: "https://my-agent.example.com/webhook",
    events: ["message.received"],
  }),
});
const webhook = await webhookRes.json();
console.log("Webhook secret:", webhook.secret); // Save this!

Check delivery status

check-status.ts
const statusRes = await f(
  `https://mail-api.ordian.ai/v1/messages/${result.id}/status`
);
const status = await statusRes.json();

console.log(`Status: ${status.status}`);
for (const event of status.events) {
  console.log(`  ${event.event} - ${event.diagnostic_code}`);
}

x402 package reference

Official x402 client packages:

  • @x402/fetch — wraps native fetch with automatic 402 handling
  • @x402/axios — adds payment interceptor to Axios
  • @x402/evm — EVM payment scheme (required by both fetch and axios clients)
  • x402 (Python) — Python SDK with httpx and requests support

See the x402 examples repo for additional examples including Go and MCP integrations.