# Multi-Agent Payments

When an orchestrating agent delegates work to sub-agents, those sub-agents incur their own payment costs. RailProtocol tracks the full payment chain on-chain: every sub-agent payment is linked to the parent transaction, and the entire cost tree is auditable from a single root transaction hash.

***

## How it works

Each agent has its own wallet and its own spend policies. When Agent A invokes Agent B and Agent B makes payments:

1. Agent B's payments are settled on-chain from Agent B's wallet
2. Each of Agent B's transactions includes a `parentTxHash` field linking it to the invocation from Agent A
3. The dashboard and CLI can resolve the full transaction tree from any node

This means you can trace the total cost of any task, across any number of agent hops, from a single root transaction hash.

***

## Invoking a sub-agent with a budget cap

```typescript
import { RailProtocol } from "@railprotocol/sdk";

const rail = new RailProtocol({
  agentId: "orchestrator-agent",
  apiKey: process.env.RAIL_API_KEY,
});

const result = await rail.agents.invoke({
  agentEndpoint: "https://research-agent.yourplatform.com/run",
  task: {
    query: "Summarize Solana TVL trends for Q1 2026",
    outputFormat: "markdown",
  },
  budget: { usdc: 2.00 },  // max spend authorized for this sub-agent run
});

console.log(result.output);           // the sub-agent's response
console.log(result.totalCost);        // { usdc: 0.84 }
console.log(result.paymentChain);     // array of on-chain tx hashes
```

The `budget` field enforces a hard cap on the sub-agent's spend for this invocation. If the sub-agent's payments would exceed the budget, further payment calls are rejected and the sub-agent receives a `BudgetExceededError`.

***

## On-chain transaction chain

Every transaction in a multi-agent chain is linked on-chain via the `parentTxHash` field stored in the RailProtocol program's ledger account. The chain is queryable from either end.

```typescript
// Get all transactions in a chain, starting from the root
const chain = await rail.transactions.getChain(rootTxHash);

for (const tx of chain) {
  console.log(`${tx.agentId}: ${tx.amountPaid.usdc} USDC via ${tx.protocol}`);
  console.log(`  Endpoint: ${tx.endpoint}`);
  console.log(`  Depth: ${tx.depth}`);
}
```

Example output:

```
orchestrator-agent: 0.00 USDC (invocation root)
  Depth: 0
research-agent: 0.002 USDC via x402
  Endpoint: api.dune.com/v1/query/1234/results
  Depth: 1
research-agent: 0.012 USDC via mpp
  Endpoint: api.browserbase.com/v1/sessions
  Depth: 1
research-agent: 0.004 USDC via x402
  Endpoint: api.coingecko.com/v3/coins/solana
  Depth: 1
```

***

## Sequential pipeline

Chain agents where each step uses the output of the previous one:

```typescript
// Step 1: fetch raw data
const fetchResult = await rail.agents.invoke({
  agentEndpoint: "https://data-agent.yourplatform.com/run",
  task: { source: "dune", queryId: "1234" },
  budget: { usdc: 0.50 },
});

// Step 2: analyze
const analysisResult = await rail.agents.invoke({
  agentEndpoint: "https://analyst-agent.yourplatform.com/run",
  task: { data: fetchResult.output },
  budget: { usdc: 1.00 },
});

// Step 3: write report
const reportResult = await rail.agents.invoke({
  agentEndpoint: "https://writer-agent.yourplatform.com/run",
  task: { analysis: analysisResult.output, format: "markdown" },
  budget: { usdc: 0.50 },
});
```

The total cost across the three steps is visible in the dashboard, aggregated under the orchestrator's run ID.

***

## Concurrent fan-out

Run multiple sub-agents in parallel and merge results:

```typescript
const [solanaReport, ethereumReport, bitcoinReport] = await Promise.all([
  rail.agents.invoke({
    agentEndpoint: "https://research-agent.yourplatform.com/run",
    task: { topic: "Solana ecosystem Q1 2026" },
    budget: { usdc: 1.00 },
  }),
  rail.agents.invoke({
    agentEndpoint: "https://research-agent.yourplatform.com/run",
    task: { topic: "Ethereum ecosystem Q1 2026" },
    budget: { usdc: 1.00 },
  }),
  rail.agents.invoke({
    agentEndpoint: "https://research-agent.yourplatform.com/run",
    task: { topic: "Bitcoin ecosystem Q1 2026" },
    budget: { usdc: 1.00 },
  }),
]);

// Total budget exposure: 3.00 USDC
// Actual cost visible on-chain per sub-agent
```

***

## Agent-to-agent invoicing

For marketplace scenarios where one agent charges another for its services, RailProtocol supports direct agent-to-agent payment using x402 or MPP. The payee agent exposes an HTTP endpoint that returns a 402 response. The paying agent calls `rail.pay()` against that endpoint.

```typescript
// Paying agent
const result = await rail.pay({
  endpoint: "https://specialist-agent.marketplace.com/run",
  method: "POST",
  body: { task: "classify this document" },
});

// Specialist agent's endpoint returns 402 with x402 requirements
// RailProtocol handles the payment and returns the classification result
```

The specialist agent's endpoint can be protected using the RailProtocol server-side middleware. See [x402: accepting payments](/protocols/x402.md) for the server-side setup.

***

## Viewing payment trees in the dashboard

The dashboard at [app.railprotocol.org](https://app.railprotocol.org) shows multi-agent payment chains in a tree view. Select any transaction to expand its children and see the full cost breakdown at each level.

Via CLI:

```bash
rail transactions tree <root-tx-hash>
```

```
root: orchestrator-agent (invocation)
  research-agent
    0.002 USDC  x402  api.dune.com/...
    0.012 USDC  mpp   api.browserbase.com/...
    0.004 USDC  x402  api.coingecko.com/...
  writer-agent
    0.001 USDC  x402  api.anthropic.com/...

Total: 0.019 USDC across 4 transactions, 2 agents
```

***

## Further reading

* [Agent wallets](/features/agent-wallets.md)
* [Spend policies](/features/spend-policies.md)
* [Observability](/features/observability.md)
* [TypeScript SDK reference](/sdk/typescript.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.railprotocol.org/features/multi-agent-payments.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
