# API Reference

`Divigent` is the main SDK facade. It owns the viem public/wallet clients and exposes:

* read functions for protocol and wallet state;
* write functions for deposit, withdrawal, and authorization;
* planning helpers that build viem transaction requests without broadcasting;
* signing helpers for permits and initialization;
* x402 buyer and seller attach helpers;
* protocol and admin functions.

For installation and a first deposit/withdraw, see the [SDK Quickstart.](/divigent-docs/quick-start/sdk.md)

## Import

```ts
import {
  Divigent,
  evmAddress,
  formatUsdc,
  parseUsdc,
} from '@divigent/sdk';
```

## `Divigent.create`

Creates the main SDK facade.

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

| Field          | Type                       | Description                                            |
| -------------- | -------------------------- | ------------------------------------------------------ |
| `publicClient` | `PublicClient`             | viem public client                                     |
| `walletClient` | `WalletClient`             | viem wallet client for writes and signing              |
| `chain`        | `'base' \| 'base-sepolia'` | Divigent chain id                                      |
| `addresses`    | `ContractAddresses`        | Optional full address set for private/test deployments |

If `chain` is omitted, the SDK tries to infer it from the bound viem clients and then falls back to `base-sepolia` for backwards compatibility. Production code should set the chain explicitly.

## Chain Helpers

| Function                        | Description                                                       |
| ------------------------------- | ----------------------------------------------------------------- |
| `getAddresses(chain)`           | Return the built-in address registry for `base` or `base-sepolia` |
| `getChainConfig(chain)`         | Return chain metadata and addresses                               |
| `chainFromId(chainId)`          | Resolve `8453` or `84532` to a Divigent chain id                  |
| `assertProtocolDeployed(chain)` | Throw if required protocol addresses are missing                  |
| `isZeroAddress(address)`        | Check the canonical zero address                                  |

## Read Functions

Read functions never broadcast transactions.

### Wallet and Position Reads

| Function                       | Use                                                            |
| ------------------------------ | -------------------------------------------------------------- |
| `getPosition(wallet)`          | Read deposited principal, current value, and accrued yield     |
| `costBasis(wallet)`            | Read the wallet's USDC cost basis                              |
| `dvUsdcBalance(wallet)`        | Read wallet dvUSDC share balance                               |
| `dvUsdcTotalSupply()`          | Read total dvUSDC supply                                       |
| `usdcBalance(account)`         | Read wallet USDC balance                                       |
| `usdcAllowance(owner)`         | Read USDC allowance from owner to the Divigent router          |
| `isAuthorized(wallet)`         | Check whether a wallet is initialized/authorized               |
| `isOperator(wallet, operator)` | Check whether an operator can withdraw for a wallet            |
| `nonce(wallet)`                | Read the router nonce used for wallet authorization signatures |

### Deposit and Withdrawal Previews

| Function                                  | Use                                                       |
| ----------------------------------------- | --------------------------------------------------------- |
| `previewDeposit(amount)`                  | Preview dvUSDC shares minted for a USDC deposit           |
| `previewRedeem(shares, wallet)`           | Preview gross USDC returned for burning shares            |
| `previewWithdrawNet(desiredUsdc, wallet)` | Preview shares needed to receive a target net USDC amount |
| `convertToShares(assets)`                 | Convert USDC assets to dvUSDC shares using router math    |
| `convertToAssets(shares)`                 | Convert dvUSDC shares to USDC assets using router math    |

### Protocol State Reads

| Function                      | Use                                                     |
| ----------------------------- | ------------------------------------------------------- |
| `withdrawCapacity()`          | Read available withdrawal liquidity across venues       |
| `getCurrentAllocation()`      | Read current Aave/Morpho allocation                     |
| `getRecommendedRoute(amount)` | Read the recommended deposit route for an amount        |
| `pricePerShare()`             | Read current dvUSDC price per share                     |
| `totalVaultAssets()`          | Read total USDC-equivalent assets managed by the router |
| `currentTVLCap()`             | Read the active protocol TVL cap                        |
| `minDeposit()`                | Read the router's minimum accepted deposit              |
| `depositsPaused()`            | Check whether deposits are paused                       |

### Oracle and Fee Reads

| Function                    | Use                                                  |
| --------------------------- | ---------------------------------------------------- |
| `getOptimalVault()`         | Read the oracle's preferred deposit venue            |
| `getAllRates()`             | Read all venue rates and safety flags                |
| `isVaultSafe(vaultType)`    | Check whether a venue is currently safe              |
| `isFresh()`                 | Check whether oracle observations are fresh          |
| `lastGoodObservationAge()`  | Read age of the last good oracle observation         |
| `oracleStatus()`            | Read oracle freshness and last observation timestamp |
| `treasuryStatus()`          | Read fee-collector treasury rotation state           |
| `calculateFee(yieldEarned)` | Preview protocol fee on a yield amount               |

## Write Functions

Write functions broadcast transactions from the configured wallet client.

| Function                            | Use                                                                                  |
| ----------------------------------- | ------------------------------------------------------------------------------------ |
| `approveUsdc(amount, fees?)`        | Approve the Divigent router to spend USDC                                            |
| `deposit(params)`                   | Deposit USDC after allowance is already available                                    |
| `depositAndWait(params)`            | Deposit and wait for the receipt, returning parsed minted shares                     |
| `depositWithPermit(params)`         | Sign USDC permit and deposit in one router transaction when supported                |
| `depositWithPermitAndWait(params)`  | Permit-deposit, wait for receipt, and return parsed minted shares                    |
| `withdraw(params)`                  | Burn dvUSDC shares and withdraw USDC                                                 |
| `withdrawAndWait(params)`           | Withdraw, wait for receipt, and return parsed USDC received                          |
| `initialize()`                      | Initialize/authorize the connected wallet with the router                            |
| `ensureInitializedAndWait(params?)` | Initialize the connected wallet if needed; return `undefined` if already initialized |
| `initializeFor(params)`             | Initialize another wallet with an off-chain signature                                |
| `setOperator(params)`               | Grant or revoke operator withdrawal authority                                        |
| `depositIdle(options?)`             | Deposit wallet USDC above a reserve floor into Divigent                              |

The common user-facing path:

```ts
await divigent.ensureInitializedAndWait({ wallet });
await divigent.depositWithPermitAndWait({
  amount,
  wallet,
  fallbackOnPermitUnsupported: true,
});

const shares = await divigent.previewWithdrawNet(desiredUsdc, wallet);
await divigent.withdrawAndWait({ shares, wallet, slippageBps: 50 });
```

### Deposit Params

```ts
type DepositParams = {
  amount: bigint;
  wallet?: EvmAddress;
  minSharesOut?: bigint;
  slippageBps?: number;
  fees?: FeeOverrides;
};
```

### Deposit With Permit Params

```ts
type DepositWithPermitParams = DepositParams & {
  deadline?: bigint;
  fallbackOnPermitUnsupported?: boolean;
  fallbackOn7702?: boolean; // deprecated
};
```

### Withdraw Params

```ts
type WithdrawParams = {
  shares: bigint;
  wallet?: EvmAddress;
  minUsdcOut?: bigint;
  slippageBps?: number;
  fees?: FeeOverrides;
};
```

### Ensure Initialized Params

```ts
type EnsureInitializedParams = {
  wallet?: EvmAddress;
  confirmations?: number;
  pollingInterval?: number;
  timeout?: number;
};
```

## Planning Functions

Planning helpers simulate and build viem-ready transactions without broadcasting. Use these when your app wants to show a confirmation screen or route the final write through another transaction sender.

| Function                         | Use                                                                   |
| -------------------------------- | --------------------------------------------------------------------- |
| `planApproveUsdc(amount, fees?)` | Build an approval transaction request                                 |
| `planDeposit(params)`            | Build a deposit transaction request and report allowance requirements |
| `planWithdraw(params)`           | Build a withdrawal transaction request                                |
| `sendPlan(plan)`                 | Broadcast a plan returned by the planning helpers                     |

## Signing Helpers

| Function                    | Use                                           |
| --------------------------- | --------------------------------------------- |
| `signPermit(params)`        | Create a USDC permit signature                |
| `signInitializeFor(params)` | Sign router initialization for another wallet |

## x402 Buyer APIs

`divigent.attachTo(x402Client, config)` attaches Divigent liquidity hooks to an existing x402 client and returns a handle.

```ts
const handle = divigent.attachTo(client, config);
```

### Buyer Handle Functions

| Function                                               | Use                                                         |
| ------------------------------------------------------ | ----------------------------------------------------------- |
| `detach()`                                             | Remove Divigent hooks from the x402 client                  |
| `wrapFetchWithYield(fetchWithPayment, http, options?)` | Redeposit idle wallet USDC after successful x402 settlement |
| `depositIdle(options?)`                                | Manually sweep wallet USDC above the configured reserve     |

### `X402WrapConfig`

| Setting                      | Use                                                         |
| ---------------------------- | ----------------------------------------------------------- |
| `minIdleThreshold`           | Minimum wallet USDC to keep liquid                          |
| `reserveRatio`               | Share of recent payment EMA used for adaptive reserves      |
| `reserveMultiplier`          | Multiplier applied to the EMA reserve                       |
| `slippageBps`                | Withdrawal slippage guard for x402 recalls                  |
| `maxPaymentAmount`           | Hard cap on each payment the SDK will act on                |
| `maxSessionPaymentAmount`    | Cumulative cap for the attached client session              |
| `requireAllowedPayTo`        | Require `allowedPayTo` before handling payments             |
| `allowedPayTo`               | Payee allowlist for x402 requests                           |
| `allowedOrigins`             | Origin allowlist for x402 requests                          |
| `allowedOrigin`              | Deprecated; use `allowedOrigins`                            |
| `allowedResources`           | Resource allowlist for x402 requests                        |
| `allowedResource`            | Deprecated; use `allowedResources`                          |
| `maxPaymentAmountByResource` | Per-resource payment caps                                   |
| `shouldHandlePayment`        | Last-mile policy predicate                                  |
| `redact`                     | Redact wallet addresses and tx hashes in observer callbacks |
| `onNonFatalError`            | Receives non-fatal integration errors                       |
| `onBeforePayment`            | Fires after the pre-payment recall hook finishes            |
| `onAfterPaymentCreation`     | Fires after x402 signs the payment payload                  |
| `onPaymentFailure`           | Fires when x402 payment-payload creation fails              |

```ts
type X402WrapConfig = {
  minIdleThreshold?: bigint;
  reserveRatio?: number;
  reserveMultiplier?: number;
  slippageBps?: number;
  maxPaymentAmount?: bigint;
  maxSessionPaymentAmount?: bigint;
  requireAllowedPayTo?: boolean;
  allowedPayTo?: readonly string[];
  allowedOrigins?: readonly string[];
  allowedOrigin?: readonly string[] | string;
  allowedResources?: readonly X402ResourcePattern[];
  allowedResource?: readonly X402ResourcePattern[] | X402ResourcePattern;
  maxPaymentAmountByResource?: Record<string, bigint> | readonly X402ResourceCap[];
  shouldHandlePayment?: (ctx: X402PolicyContext) => boolean | Promise<boolean>;
  redact?: boolean;
  onNonFatalError?: (ctx: IntegrationErrorContext) => void | Promise<void>;
  onBeforePayment?: (ctx: PaymentContext) => void | Promise<void>;
  onAfterPaymentCreation?: (ctx: PaymentCreatedContext) => void | Promise<void>;
  onPaymentFailure?: (ctx: FailureContext) => void | Promise<void>;
};
```

### `X402AutoDepositOptions`

```ts
type X402AutoDepositOptions = {
  dedupeCapacity?: number;
  seenTxHashes?: Set<string>;
  minDeposit?: bigint | (() => bigint | Promise<bigint>);
  waitForIdleDeposit?: boolean;
  onIdleDeposit?: (ctx: IdleDepositContext) => void | Promise<void>;
  onNonFatalError?: (ctx: IntegrationErrorContext) => void | Promise<void>;
};
```

## x402 Seller APIs

`divigent.attachToResourceServer(resourceServer, config)` attaches seller-side income deposit hooks to an existing x402 resource server.

```ts
const incomeHandle = divigent.attachToResourceServer(resourceServer, {
  minIdleThreshold: parseUsdc('1'),
});
```

### Seller Handle Functions

| Function                | Use                                                                   |
| ----------------------- | --------------------------------------------------------------------- |
| `detach()`              | Disable future seller-side income deposit hooks                       |
| `depositIdle(options?)` | Deposit current seller wallet USDC above the configured reserve floor |

### `X402IncomeConfig`

```ts
type X402IncomeConfig = {
  wallet?: EvmAddress;
  minIdleThreshold?: bigint;
  reserveRatio?: number;
  reserveMultiplier?: number;
  dedupeCapacity?: number;
  minDeposit?: bigint | (() => bigint | Promise<bigint>);
  onIdleDeposit?: (ctx: IdleDepositContext) => void | Promise<void>;
  onNonFatalError?: (ctx: IntegrationErrorContext) => void | Promise<void>;
};
```

### `X402IdleDepositOptions`

```ts
type X402IdleDepositOptions = {
  wallet?: EvmAddress;
  minIdleThreshold?: bigint;
  reserveRatio?: number;
  reserveMultiplier?: number;
  dedupeKey?: string;
  seenTxHashes?: Set<string>;
  minDeposit?: bigint | (() => bigint | Promise<bigint>);
  onIdleDeposit?: (ctx: IdleDepositContext) => void | Promise<void>;
  onNonFatalError?: (ctx: IntegrationErrorContext) => void | Promise<void>;
};
```

## x402 USDC Helpers

Use these helpers to build seller payment requirements for Divigent-supported USDC assets.

| Export                     | Use                                                              |
| -------------------------- | ---------------------------------------------------------------- |
| `x402UsdcPrice(params)`    | Build `{ amount, asset, extra }` for x402 seller `accepts.price` |
| `x402UsdcExtra(chain)`     | Return x402 token metadata for a supported chain                 |
| `X402_USDC_EXTRA_BY_CHAIN` | Metadata registry for `base` and `base-sepolia`                  |

```ts
const price = x402UsdcPrice({
  chain: 'base',
  amount: parseUsdc('0.001'),
  asset: divigent.addresses.usdc,
});
```

Base mainnet uses Circle USDC EIP-3009 metadata:

```ts
{
  name: 'USD Coin',
  version: '2',
  assetTransferMethod: 'eip3009',
}
```

Base Sepolia uses Divigent's configured test USDC metadata with Permit2.

## Protocol and Admin Functions

These are exposed because the SDK can operate the full protocol surface, but normal user wallets cannot call them unless they hold protocol roles.

| Function                               | Use                                 |
| -------------------------------------- | ----------------------------------- |
| `recordObservation()`                  | Record a yield oracle observation   |
| `proposeTreasuryRotation(newTreasury)` | Propose a new fee treasury          |
| `executeTreasuryRotation()`            | Execute a pending treasury rotation |
| `cancelTreasuryRotation()`             | Cancel a pending treasury rotation  |
| `pauseDeposits()`                      | Pause deposits                      |
| `unpauseDeposits()`                    | Unpause deposits                    |

## Permit Behavior

`depositWithPermit` uses USDC permit when available. If permit is unsupported, the SDK can fall back to `approveUsdc + deposit` for the signer wallet when `fallbackOnPermitUnsupported: true` is set. The fallback will not approve signer funds while crediting a different wallet.

Base mainnet Circle USDC supports the permit fields used by the SDK. Base Sepolia behavior depends on Divigent's configured test USDC.

## Utilities

| Function                        | Description                           |
| ------------------------------- | ------------------------------------- |
| `parseUsdc(value)`              | Parse display USDC into atomic units  |
| `formatUsdc(value)`             | Format atomic USDC into display units |
| `evmAddress(value)`             | Validate and checksum an EVM address  |
| `txHash(value)`                 | Validate a transaction hash           |
| `applySlippageDown(value, bps)` | Apply slippage tolerance              |
| `convertToShares(assets)`       | Pure share conversion helper          |
| `convertToAssets(shares)`       | Pure asset conversion helper          |

## Exported Result Types

Common public types:

* `DepositResult`
* `WithdrawResult`
* `Position`
* `VaultAllocation`
* `VaultCapacity`
* `VaultRate`
* `OptimalVault`
* `OracleStatus`
* `TreasuryStatus`
* `PermitSig`
* `TxHash`
* `EvmAddress`
* `FeeOverrides`
* `WaitOptions`
* `X402AttachHandle`
* `X402AutoDepositOptions`
* `X402IdleDepositOptions`
* `X402IncomeAttachHandle`
* `X402IncomeConfig`
* `X402WrapConfig`
* `IdleDepositContext`
* `PaymentContext`
* `PaymentCreatedContext`
* `FailureContext`

`PaymentContext` includes `recallError` when a pre-payment recall did not fully satisfy the reserve policy.

## Exported Errors

Common exported errors:

* `DivigentError`
* `ChainMismatchError`
* `AddressMismatchError`
* `AlreadyAttachedError`
* `PaymentCapExceededError`
* `PermitUnsupportedFor7702AccountError`
* `PermitUnsupportedForTokenError`
* `OperatorAckRequiredError`
* `ReceiptParseError`
* `ContractRevertError`
* `UserRejectedError`
* `ZeroAddressError`

`DivigentError` code `DIVIGENT_X402_RECALL_INSUFFICIENT_LIQUIDITY` means x402 recall could not make enough USDC liquid before signing the payment.

## Raw ABIs

Advanced viem users can import the raw ABIs:

```ts
import {
  routerAbi,
  oracleAbi,
  feeCollectorAbi,
  dvUsdcAbi,
  usdcAbi,
} from '@divigent/sdk';
```

## Development Commands

```bash
# Type check
npm run typecheck

# Unit tests
npm test

# Build package
npm run build

# Base fork tests
npm run test:fork:base

# Base integration tests
npm run test:integration:base

# x402 local integration tests
npm run test:x402:local

# Package preview
npm pack --dry-run --json
```


---

# 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://divigent.gitbook.io/divigent-docs/sdk/api-reference.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.
