> For the complete documentation index, see [llms.txt](https://divigent.gitbook.io/divigent-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://divigent.gitbook.io/divigent-docs/integration/agent-wallet-integration.md).

# Agent Wallet Integration

Divigent is the treasury layer for x402 agent wallets. It lets an agent keep enough USDC liquid for payments while deploying idle USDC into Divigent until that liquidity is needed again.

This guide explains the integration pattern used in the Franklin + Divigent demo and how the same pattern applies to any agent wallet or x402 payment flow.

## What Divigent Adds

Divigent does not replace your agent wallet, your x402 client, or your payment policy.

It adds a liquidity layer around the payment lifecycle:

```
agent wallet has USDC
-> idle USDC is deposited into Divigent
-> agent receives an x402 payment requirement
-> Divigent checks payment + idle buffer
-> if wallet USDC is short, Divigent recalls just enough USDC
-> agent signs and settles the payment normally
-> optional idle sweep moves excess USDC back into Divigent
```

The agent still decides what to buy. The wallet still signs. Divigent only answers:

```
How much USDC should stay liquid, and how much can remain productive?
```

## Integration Points

{% tabs %}
{% tab title="Standard x402 Client" %}
If your application uses a standard `@x402/core` client, use Divigent's x402 hooks:

```ts
const handle = divigent.attachTo(x402Client, {
  minIdleThreshold: parseUsdc('0.25'),
  maxPaymentAmount: parseUsdc('5'),
  allowedOrigins: ['https://api.example.com'],
});
```

This lets Divigent run before x402 signing and after successful settlement.
{% endtab %}

{% tab title="Manual x402 Flow" %}
Some agent frameworks handle x402 manually. Franklin currently follows this shape:

```
request paid resource
-> receive 402
-> parse payment requirement
-> extract amount, network, recipient
-> sign payment payload
-> retry with payment header
```

For this shape, integrate Divigent immediately after payment details are extracted and before the agent signs the payment.

```
after extractPaymentDetails(...)
before createPaymentPayload(...)
```

That is the hook used in the Franklin + Divigent demo.
{% endtab %}
{% endtabs %}

## Prerequisites

Install the SDK and wallet dependencies used by your agent:

```bash
npm install @divigent/sdk viem
```

For the Franklin-style demo, the wallet and payment helpers come from BlockRun:

```bash
npm install @blockrun/franklin @blockrun/llm
```

The wallet needs:

* Base ETH for gas.
* Base USDC for payments and Divigent deposits.
* A configured Base RPC URL.

## 1. Create The Divigent Client

Use the same account that owns the agent wallet.

```ts
import { Divigent, evmAddress, parseUsdc } from '@divigent/sdk';
import { createPublicClient, createWalletClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { base } from 'viem/chains';

const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const wallet = evmAddress(account.address);

const publicClient = createPublicClient({
  chain: base,
  transport: http(process.env.BASE_RPC_URL),
});

const walletClient = createWalletClient({
  account,
  chain: base,
  transport: http(process.env.BASE_RPC_URL),
});

const divigent = Divigent.create({
  publicClient,
  walletClient,
  chain: 'base',
});
```

Divigent never needs a separate custody key. It uses the agent wallet's own signer for deposits and withdrawals.

## 2. Initialize The Wallet

Initialize once before the wallet uses Divigent.

```ts
const initTx = await divigent.ensureInitializedAndWait({ wallet });

if (initTx) {
  console.log(`Divigent initialized: ${initTx}`);
}
```

Re-running this check is safe. If the wallet is already initialized, no transaction is sent.

## 3. Deposit Idle USDC

Before the agent starts paying for resources, deposit the portion of USDC that does not need to remain liquid.

```ts
const idleBuffer = parseUsdc('0.25');
const walletUsdc = await divigent.usdcBalance(wallet);
const minimumDeposit = await divigent.minDeposit();

const depositAmount = walletUsdc > idleBuffer
  ? walletUsdc - idleBuffer
  : 0n;

if (depositAmount >= minimumDeposit) {
  const result = await divigent.depositWithApprovalAndWait({
    amount: depositAmount,
    wallet,
  });

  console.log(`Divigent deposit tx: ${result.txHash}`);
}
```

This leaves `idleBuffer` in the wallet and moves the rest into Divigent.

{% hint style="info" %}
Divigent enforces the router's minimum deposit. The Franklin demo reads `divigent.minDeposit()` before the seed deposit and fails loudly if a configured seed amount is below that minimum. Production integrations can instead skip seed deposits below the minimum and keep that USDC liquid.
{% endhint %}

## 4. Check Liquidity Before Signing

When the agent receives a `402 Payment Required`, parse the payment requirement first. Then call `ensurePaymentReady` before signing.

```ts
const paymentAmount = BigInt(details.amount);

const readiness = await divigent.ensurePaymentReady({
  wallet,
  pendingPaymentAmount: paymentAmount,
  minOperatingBalance: parseUsdc('0.25'),
  reserveTopUp: 'opportunistic',
  slippageBps: 50,
});

if (readiness.recallTxHash) {
  console.log(`Divigent recall tx: ${readiness.recallTxHash}`);
}
```

`ensurePaymentReady` checks:

* current wallet USDC;
* pending payment amount;
* required idle buffer;
* current Divigent position value;
* recall capacity and slippage guard.

If wallet USDC is below `pending payment + idle buffer`, Divigent withdraws only the missing amount before the agent signs.

## 5. Sign And Pay Normally

After `ensurePaymentReady` returns, continue with your existing x402 payment path.

In the Franklin-style flow:

```ts
const payload = await createPaymentPayload(
  privateKey,
  wallet,
  details.recipient,
  details.amount,
  details.network || 'eip155:8453',
  {
    resourceUrl: details.resource?.url,
    resourceDescription: details.resource?.description,
    maxTimeoutSeconds: details.maxTimeoutSeconds || 300,
    extra: details.extra,
  },
);

const paid = await fetch(resourceUrl, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'PAYMENT-SIGNATURE': payload,
  },
  body: JSON.stringify(requestBody),
});
```

Divigent does not approve or deny the payment. Your agent's own budget, recipient, resource, and policy checks should still run.

## 6. Sweep Idle USDC After Settlement

After a successful paid response, optionally sweep wallet USDC above the buffer back into Divigent.

```ts
if (paid.ok) {
  const sweepTx = await divigent.depositIdle({
    wallet,
    minIdleThreshold: parseUsdc('0.25'),
  });

  if (sweepTx) {
    console.log(`Divigent idle sweep tx: ${sweepTx}`);
  }
}
```

For latency-sensitive agents, the sweep can run after the response has already been returned to the user or agent runtime.

## Franklin Example Flow

The Franklin + Divigent demo uses this exact integration point:

```
Franklin wallet is loaded
-> Divigent initializes the same wallet
-> idle USDC is deposited into Divigent
-> Franklin calls a live BlockRun x402 endpoint
-> BlockRun returns 402 payment details
-> Divigent checks payment readiness
-> Divigent recalls USDC if wallet liquidity is below payment + idle buffer
-> Franklin signs createPaymentPayload(...)
-> Franklin retries with PAYMENT-SIGNATURE
-> BlockRun settles the payment on Base
```

In product terms:

```
Franklin decides what to buy.
Franklin signs the x402 payment.
Divigent keeps the Franklin wallet liquid enough to pay without leaving all USDC idle.
```

## What To Log Or Display

For demos and production dashboards, show:

* wallet address;
* wallet USDC before payment;
* Divigent position value;
* required idle buffer;
* pending x402 amount;
* recall tx hash, if any;
* payment settlement tx hash;
* final wallet USDC and Divigent position value.

BaseScan links are useful because they make the lifecycle easy to verify:

```
Divigent deposit tx
Divigent recall tx
x402 settlement tx
Divigent idle sweep tx
```

## Safety Boundaries

Keep these responsibilities separate:

| Layer               | Responsibility                                                   |
| ------------------- | ---------------------------------------------------------------- |
| Agent app           | decides what resource to request                                 |
| Payment policy      | decides whether the payment is allowed                           |
| x402 client/helpers | parse payment details, sign, and retry                           |
| Divigent SDK        | deposit idle USDC, recall before payment, sweep after settlement |
| Wallet signer       | signs all onchain actions                                        |

Divigent should not bypass your agent's payment policy. It should only make sure approved payments can be funded while idle USDC remains productive.

## Recommended Defaults

For a simple buyer-side agent wallet:

```ts
const divigentConfig = {
  minIdleThreshold: parseUsdc('0.25'),
  reserveTopUp: 'opportunistic' as const,
  slippageBps: 50,
};
```

Use a higher idle buffer for agents with larger payment sizes, stricter latency needs, or non-x402 operating expenses.

## Integration Checklist

1. Create the Divigent client with the agent wallet's public and wallet clients.
2. Initialize the wallet once with `ensureInitializedAndWait`.
3. Deposit idle USDC above the desired buffer.
4. Before signing an x402 payment, call `ensurePaymentReady`.
5. Sign and settle the x402 payment through the existing agent flow.
6. Optionally call `depositIdle` after settlement.
7. Log deposit, recall, settlement, and sweep transaction hashes.

The result is an agent wallet that can keep operating liquidity available while routing idle float through Divigent.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://divigent.gitbook.io/divigent-docs/integration/agent-wallet-integration.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.
