Docs / OpacusPay

OpacusPay

Drop one <script> tag. Give your agents the ability to swap, bridge, pay, buy data, and auto-settle HTTP APIs — on Base and 0G.

1. What is OpacusPay?

OpacusPay is the on-chain payment layer for Opacus agents. It lets any app — including projects built with app.0G.ai — embed agent-to-agent payments, real token swaps, cross-chain bridges, and HTTP x402 micropayments without managing private keys or RPC connections.

Under the hood, OpacusPay uses a per-user custodial execution wallet derived from your session. Each user gets an isolated wallet — your funds are never mixed with another user's. All on-chain operations go through the Opacus runtime and are visible in Agentboard.

CapabilitySupported networksStatus
Token swap0G (Jaine DEX), Base (Aerodrome)✅ Live
USDC bridgeBase ↔ 0G✅ Live
Agent-to-agent payment (escrow)Base✅ Live
DA data purchase0G storage✅ Live
x402 HTTP auto-payBase & 0G✅ Live

2. Quick Start

<!-- Step 1: add one script tag to your page -->
<script src="https://opacus.xyz/agent-widget.js" data-opacus-app="my-0g-app"></script>

<!-- Step 2: listen for the connected event, then call any OpacusPay method -->
<script>
OpacusAgent.on('connected', async function(agent) {
  console.log('Wallet ready:', agent.agentId);

  // Swap 5 USDC.e → W0G on 0G network
  const swap = await OpacusAgent.execute('swap', {
    tokenIn: 'USDC',
    tokenOut: 'W0G',
    amountIn: 5,
    chain: '0g',
    execute: true
  });
  console.log(swap.transactionHash); // on-chain tx hash
});
</script>

OpacusAgent.init() is called automatically when data-opacus-app is present. The widget renders a floating "Connect Agent" button in the bottom-right corner. Users enter their Opacus API key once — the session is scoped to your appId and stored in sessionStorage.

3. OpacusPay Capabilities

3.1 Swap tokens

Execute real on-chain swaps using Jaine DEX (0G) or Aerodrome (Base). The Opacus runtime selects the best fee tier, quotes the price, approves the token, and submits the swap — returning the transaction hash.

// Swap 10 USDC.e for W0G on 0G network
const result = await OpacusAgent.execute('swap', {
  tokenIn: 'USDC',
  tokenOut: 'W0G',
  amountIn: 10,
  chain: '0g',   // '0g' | 'base'
  execute: true  // false = quote only
});
// result.transactionHash, result.amountOut, result.opacusFee

Supported pairs: USDC.e ↔ W0G on 0G (Jaine V3), USDC ↔ WETH on Base (Aerodrome). A platform fee (0.5 %–1 % depending on your plan, reduced by Kinetic Score tier) is deducted from the output.

3.2 Bridge USDC cross-chain

Move USDC between Base and 0G in one call. The bridge initiates on the source chain and completes on the destination chain via the Opacus relay.

// Bridge 20 USDC from Base → 0G
const bridge = await OpacusAgent.execute('bridge', {
  amount: 20,
  from: 'base',
  to: '0g',
  execute: true
});
// bridge.transactionHash, bridge.requestId

3.3 Pay an agent (escrow)

Lock USDC into the Opacus escrow contract on Base. The receiving agent can claim after the work is verified. Useful for agent-to-agent service payments or conditional transfers.

// Pay another agent 2 USDC for data analysis
await OpacusAgent.pay('agent_abc123', 2.00, 'Market analysis fee');

Fires the paid event on success: { toAgentId, amountUsdc, txHash }.

3.4 Buy DA data

Purchase a listing from the Opacus Data Market. The USDC payment is made and the file's 0G DA root hash is returned — ready for download from the 0G storage layer.

const purchase = await OpacusAgent.buyData('dm_abc123');
console.log(purchase.dataHash);   // 0G DA root hash
console.log(purchase.accessUrl);  // direct download URL

3.5 x402 HTTP auto-pay

Make HTTP requests that automatically pay USDC micropayments when the server responds with 402 Payment Required. This is the x402 protocol — designed for agent-accessible APIs.

// Fetch a paid API endpoint — OpacusPay handles the 402 automatically
const response = await OpacusAgent.fetch(
  'https://data-api.example.com/market-feed',
  { method: 'GET' },
  { chain: '0g', maxAmountUsdc: 0.10 }
);
const data = await response.json();
// If the server returned 402, OpacusPay settled it and retried — transparently.

The maxAmountUsdc guard prevents overpayment. If the server demands more than the cap, the request is cancelled and an error event is emitted.

4. Integrating OpacusPay into your app.0G.ai project

Apps generated by app.0G.ai are static HTML/JS apps. Adding OpacusPay takes three steps.

Step 1 — Add the widget script

Paste this before your closing </body> tag. Replace my-0g-app with your project slug.

<script src="https://opacus.xyz/agent-widget.js"
        data-opacus-app="my-0g-app"
        data-theme="dark"></script>

Step 2 — Gate features behind connection

OpacusAgent.on('connected', function(agent) {
  // show wallet balance, unlock premium features
  document.getElementById('balance').textContent = agent.balance + ' USDC';
  document.querySelectorAll('[data-requires-agent]').forEach(function(el) {
    el.removeAttribute('disabled');
  });
});

OpacusAgent.on('disconnected', function() {
  document.querySelectorAll('[data-requires-agent]').forEach(function(el) {
    el.setAttribute('disabled', 'disabled');
  });
});

Step 3 — Wire up payment actions

// Example: swap button
document.getElementById('swapBtn').addEventListener('click', async function() {
  try {
    const result = await OpacusAgent.execute('swap', {
      tokenIn: 'USDC', tokenOut: 'W0G', amountIn: 5,
      chain: '0g', execute: true
    });
    alert('Swap done: ' + result.transactionHash);
  } catch (err) {
    alert('Error: ' + err.message);
  }
});

// Example: pay for a service provided by another agent
document.getElementById('payBtn').addEventListener('click', async function() {
  await OpacusAgent.pay('agent_provider_id', 1.00, 'Premium report');
});

// Example: auto-pay a paid API with x402
async function fetchPremiumData(url) {
  const res = await OpacusAgent.fetch(url, {}, { chain: '0g', maxAmountUsdc: 0.05 });
  return res.json();
}

Agentboard visibility

Every payment, swap, bridge, and data purchase is logged in Agentboard under the connected agent's scope. Your users can review their full transaction history, balances, and Kinetic Score from a single dashboard — no extra work on your part.

5. Full API Reference

OpacusAgent.init(config)

Initialize the widget. Auto-called when data-opacus-app is set on the script tag.

OptionTypeDefaultDescription
appIdstringrequiredApp identifier — used for session scoping and audit logs
positionstringbottom-rightbottom-right | bottom-left | top-right | top-left
themestringdarkdark | light

OpacusAgent.connect()

Programmatically open the connect modal (e.g., from a custom "Connect" button).

document.getElementById('myConnectBtn').addEventListener('click', () => OpacusAgent.connect());

OpacusAgent.getAgent()

Returns connected agent info, or null if disconnected.

const agent = OpacusAgent.getAgent();
// { agentId, agentName, did, balance, kineticScore, scope }

OpacusAgent.execute(skill, params)

Run an on-chain skill. Throws if no agent is connected.

SkillParamsReturns
swaptokenIn, tokenOut, amountIn, chain, executetransactionHash, amountOut, opacusFee
bridgeamount, from, to, executetransactionHash, requestId, status

Set execute: false (default) to get a quote/plan without sending a transaction. Set execute: true to execute on-chain.

OpacusAgent.pay(toAgentId, amountUsdc, description)

Lock USDC into escrow on Base and transfer to toAgentId. Returns the escrow transaction hash.

const tx = await OpacusAgent.pay('agent_xyz', 1.50, 'Data access fee');
// tx.txHash, tx.escrowId

OpacusAgent.buyData(listingId)

Purchase a Data Market listing. Returns dataHash (0G DA root) and accessUrl.

const { dataHash, accessUrl } = await OpacusAgent.buyData('dm_abc123');

OpacusAgent.fetch(url, fetchOptions, payOptions)

Drop-in replacement for window.fetch with automatic x402 USDC payment handling.

payOptions fieldTypeDescription
chainstring'base' | '0g' — which chain to pay from
maxAmountUsdcnumberMaximum USDC to auto-pay (default: 0.10)
const res = await OpacusAgent.fetch(
  'https://api.example.com/feed',
  { method: 'GET', headers: { 'Accept': 'application/json' } },
  { chain: '0g', maxAmountUsdc: 0.05 }
);

OpacusAgent.on(event, callback) / .off(event, callback)

Subscribe to or unsubscribe from widget events.

EventPayloadDescription
connected{ agentId, agentName, did, balance, kineticScore, scope }Agent connected
disconnectednullAgent disconnected
executed{ skill, result }Swap or bridge completed
paid{ toAgentId, amountUsdc, txHash }Agent payment sent
errorErrorAny error in a payment operation

OpacusAgent.disconnect()

Clear the session and disconnect the agent.

6. x402 Auto-pay — How it works

The x402 protocol enables per-request micropayments over HTTP. When a server requires payment, it returns 402 Payment Required with a X-Payment-Details header describing the amount and recipient.

OpacusAgent.fetch() handles the full flow transparently:

  1. Makes the initial request.
  2. If 402 is received, reads the payment details from the response headers.
  3. Validates the requested amount against maxAmountUsdc.
  4. Calls POST /api/x402/settle to execute a real USDC ERC-20 transfer on-chain.
  5. Retries the original request with the X-Payment-Token header attached.
  6. Returns the final response to your code — as if it were a normal fetch() call.

Direct x402 settlement API

You can also settle x402 payments programmatically from your backend:

POST https://opacus.xyz/api/x402/settle
Content-Type: application/json
X-Opacus-User-Email: user@example.com

{
  "recipient": "0xRecipientAddress",
  "amountUsdc": 0.05,
  "chain": "0g",
  "idempotencyKey": "req_abc123"
}

// Response
{
  "ok": true,
  "transactionHash": "0x...",
  "chain": "0g",
  "amountUsdc": 0.05
}

GET /api/x402/payments returns a user's full x402 payment history.

7. Backend endpoint

The widget authenticates by calling POST /api/widget/connect. You can call this from your backend to verify a user's connected agent:

POST https://opacus.xyz/api/widget/connect
Content-Type: application/json
Authorization: Bearer <apiKey>

{}

// Response
{
  "ok": true,
  "agent": {
    "agentId": "agent_abc123",
    "agentName": "My Agent",
    "did": "did:opacus:...",
    "balance": 42.50,
    "kineticScore": 82,
    "scope": "user@example.com"
  }
}

8. Security

9. Customization

Override stable CSS IDs to match your brand:

/* Floating connect button */
#opacus-connect-btn { background: #your-color !important; }

/* Agent info popup */
#opacus-agent-popup { border-radius: 8px !important; }

/* Connect modal */
#opacus-connect-modal { /* backdrop overrides */ }