> ## Documentation Index
> Fetch the complete documentation index at: https://docs.trustware.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Build Earn with the headless core

> Find yield vaults, deposit into one from any supported asset, and show and withdraw vault positions in your own UI with the Trustware headless core.

Earn lets a user deposit into a yield vault from any supported asset, then withdraw later. The swap widget ships Earn as a prebuilt screen, covered in [offer vault deposits](https://docs.trustware.io/guides/swap-mode.md#offer-vault-deposits). This page covers the same capability through the [headless core](https://docs.trustware.io/integration/headless-core.md), for when you build the UI yourself.

Use Earn for vaults supported by its integration. Find vaults with `searchVaults` or `getVaultDetails`; a returned vault does not guarantee that a deposit can be built. Pass `vault: { vaultId, network }` on `buildRoute`, and Trustware builds the deposit call. For a custom destination contract, or a deposit call you encode yourself, use a [destination posthook](https://docs.trustware.io/guides/vault-destinations.md) instead. Who owns the vault doesn't decide which one you use.

> [!NOTE]
>
> Requires `@trustware/sdk` 1.1.17 or later. Vaults and the positions they
> credit are on EVM chains, and withdrawing needs an EVM wallet.

## Choose an integration

| You want to | Use | Who builds the destination call |
| - | - | - |
| Send tokens to an address | A normal route, with the recipient from [route configuration](https://docs.trustware.io/configuration/routes.md) or [`setDestinationAddress()`](https://docs.trustware.io/guides/runtime-destination) | No additional destination contract call is requested |
| Run a contract call you encode, such as a deposit into a custom contract | `hooks.postHook`, as in [vault destinations](https://docs.trustware.io/guides/vault-destinations.md) | You encode `target` and `callData`, and you handle positions and withdrawals for that contract |
| Deposit into a vault Earn supports | `vault`, on this page | Trustware. Earn's search, details, positions, and withdrawal methods cover the vault |

Earn isn't separate settlement infrastructure. Trustware turns `vault` into a destination call, so an Earn deposit runs on providers that support destination calls and shares their constraints.

Picking vaults in advance, as a preset or a fixed list in your UI, is a selection choice, not a separate API. A supported vault still uses `vault`, and a call you encode still uses `hooks.postHook`. Using `hooks.postHook` doesn't add a contract to Earn, so Earn's positions and withdrawals only cover vaults Earn supports.

## Methods

| Method | Returns | Purpose |
| - | - | - |
| `Trustware.searchVaults(params?)` | `Promise<VaultSearchResult>` | Find vaults, filtered and paged. |
| `Trustware.getVaultDetails(network, vaultId)` | `Promise<VaultSummary>` | Fetch one vault, such as an entry in your own list. |
| `Trustware.buildRoute({ ...route, vault })` | `Promise<BuildRouteResult>` | Build a deposit into a vault. |
| `Trustware.getVaultPositions(address)` | `Promise<Position[]>` | List every vault position a wallet holds. |
| `Trustware.getVaultRedeemActions(params)` | `Promise<VaultRedeemAction[]>` | Get the unsigned withdrawal transactions for a position. |
| `Trustware.sendVaultRedeemTx(action)` | `Promise<string>` | Sign and send one withdrawal transaction, returning its hash. |

Without the SDK, the same flow runs on the [Earn vault endpoints](https://docs.trustware.io/api-reference/vaults.md) and [`POST /route`](https://docs.trustware.io/api-reference/route#vault-deposits).

`VaultDepositRequest` is exported from the package root. The other vault types are exported from `@trustware/sdk/core`, not the package root. See [Earn types](https://docs.trustware.io/api-reference/types.md#earn).

The read methods throw on a failed request, including a `503` when vault data is temporarily unavailable. The error is an `Error` whose `name` is `"HttpError"`, with a numeric `status`.

## Find a vault

`searchVaults` returns one page of vaults that match your filters.

```ts theme={null}
import { Trustware } from "@trustware/sdk";

const { vaults, nextPage } = await Trustware.searchVaults({
  allowedNetworks: ["base"],
  minTvl: 1_000_000, // USD
  minApy: 0.03, // 3%, as a decimal fraction
  perPage: 10,
});
```

* `perPage` takes 1 to 10 and defaults to 10. A larger value fails with `400`.
* To fetch the next page, pass `nextPage` as `page`. `nextPage` is absent on the last page.
* Show each vault's `flags` and `warnings` with it.

If you offer a fixed list of vaults, skip search and fetch each one with `getVaultDetails`. It takes the vault's network name first, then its `vaultId`, which is the vault's contract address.

```ts theme={null}
const vault = await Trustware.getVaultDetails("base", "0xVaultAddress...");
```

See [`VaultSearchParams`](https://docs.trustware.io/api-reference/types#vaultsearchparams) for every filter.

## Deposit into a vault

Pass the vault as `vault` on `buildRoute`. Set the destination to the vault's chain and asset, and set `toAddress` to the wallet that should hold the position.

```ts theme={null}
import { Trustware } from "@trustware/sdk";
import type { VaultSummary } from "@trustware/sdk/core";

export async function buildVaultDeposit(vault: VaultSummary, fromAmount: string) {
  const user = await Trustware.getAddress();

  return Trustware.buildRoute({
    fromChain: "42161",
    fromToken: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", // USDC on Arbitrum
    fromAmount, // in the source token's smallest unit
    fromAddress: user,
    toChain: String(vault.network.chainId),
    toToken: vault.asset.address,
    toAddress: user,
    slippage: 1,
    vault: { vaultId: vault.vaultId, network: vault.network.name },
  });
}
```

| Field | Value |
| - | - |
| `toChain` | The vault's chain ID, from `vault.network.chainId`. |
| `toToken` | The vault's asset, from `vault.asset.address`. Trustware deposits this token. |
| `toAddress` | The EVM address that receives the vault position. |
| `vault.vaultId` | The vault's `vaultId`, its contract address. |
| `vault.network` | The vault's network name, from `vault.network.name`. Don't pass a chain ID: the network name can differ from the chain identifiers used elsewhere. |

Trustware turns the vault into a destination call that deposits the whole amount the route delivers. That uses [amount patching](https://docs.trustware.io/guides/destination-call-options.md#dynamic-landed-balance-mode), and how the amount is patched is provider dependent. If the deposit call fails, the delivered tokens go to `toAddress` when the resolving provider implements a fallback. Not every provider does, so this is not a guarantee.

Not every vault can be deposited into through a route. When Trustware can't build the deposit for a vault, `buildRoute` throws a [`RouteError`](https://docs.trustware.io/events-errors/error-handling#the-routeerror-class) with the reason. Treat it like any other failed build.

`vault` and `hooks` are mutually exclusive, because Trustware builds the destination call itself. `buildRoute` throws before sending when both `vault` and `hooks.postHook` are set, and when `vault.vaultId` or `vault.network` is empty. To run the same checks in your own form validation, call `assertValidVaultRequest` from `@trustware/sdk/core`.

From here, the deposit is an ordinary route. Show the estimate, then send it, submit the receipt, and poll status as in [sign and send a route](https://docs.trustware.io/integration/headless-core.md#3-sign-and-send-a-route). For a Solana source, use [review, then send](https://docs.trustware.io/integration/headless-core.md#solana-routes-review-then-send).

## Show positions

`getVaultPositions` lists every vault position a wallet holds, including vaults you don't offer. Filter the result if you only show your own vaults.

```ts theme={null}
import { formatUnits } from "viem";
import { Trustware } from "@trustware/sdk";

const positions = await Trustware.getVaultPositions(address);

const rows = positions.map((position) => ({
  vault: position.name,
  valueUsd: Number(position.lpToken.balanceUsd),
  inAsset: formatUnits(
    BigInt(position.asset.positionValueInAsset),
    position.asset.decimals,
  ),
}));
```

> [!WARNING]
>
> Use `lpToken.balanceUsd` for a position's USD value. `asset.balanceUsd` is
> the wallet's total balance of the asset token, repeated on every position
> row. It is not the value of the position, and summing it across positions
> overcounts.

`asset.positionValueInAsset` is the position's value in the asset's base units, scaled by `asset.decimals`. A position's `apy` is a single `{ base, reward, total }` window. For the full vault, including every APY window, call `getVaultDetails(position.network.name, position.vaultId)`.

Positions are cached for up to a minute, so a new deposit can take a short time to appear.

## Withdraw from a position

A withdrawal is not a route. It runs on the vault's own chain, and the vault's asset returns to the wallet that holds the position. There is no `intentId`, so don't call `submitReceipt` or `pollStatus`.

```ts theme={null}
import { Trustware } from "@trustware/sdk";
import type { Position } from "@trustware/sdk/core";

// Resolves once the transaction is mined, with whether it succeeded. For
// example, wrap viem's waitForTransactionReceipt on a client for chainId.
type ConfirmTx = (hash: string, chainId: number) => Promise<boolean>;

export async function withdrawPosition(
  position: Position,
  confirmTx: ConfirmTx,
): Promise<string[]> {
  const address = await Trustware.getAddress();

  const actions = await Trustware.getVaultRedeemActions({
    address,
    network: position.network.name,
    vaultId: position.vaultId,
    assetAddress: position.asset.address,
    all: true,
  });

  const hashes: string[] = [];
  for (const action of actions) {
    const hash = await Trustware.sendVaultRedeemTx(action);
    hashes.push(hash);
    // The SDK doesn't wait for confirmation. Wait before the next action,
    // and stop if this one failed.
    if (!(await confirmTx(hash, Number(action.tx.chainId)))) {
      throw new Error(`Withdrawal step "${action.name}" failed: ${hash}`);
    }
  }
  return hashes;
}
```

* `all: true` withdraws the whole position. To withdraw part of it, pass `amount` instead: the number of vault shares in base units, scaled by `lpToken.decimals`. Don't scale it by `asset.decimals`, because a share isn't always worth one unit of the asset. You can't pass both.
* `assetAddress` is required, even with `all: true`. Use `position.asset.address`.
* `address` owns the shares and receives the asset. Pass the connected wallet's address, because `sendVaultRedeemTx` signs with the connected wallet.
* Send the returned actions in order. `sendVaultRedeemTx` switches the wallet to the action's chain if needed, then sends the transaction. It resolves with the hash once the wallet submits, not when the transaction confirms.
* The SDK doesn't wait between actions. Wait for each transaction to confirm before you send the next, and stop if one fails.

The prebuilt widget only offers full withdrawals. That limit belongs to the widget, not to `getVaultRedeemActions`.

To move the withdrawn asset to another token, chain, or vault, build a new route with it as the source once the withdrawal confirms. The user signs that route as a separate transaction.

## Related reference

> [card] [Swap mode](https://docs.trustware.io/guides/swap-mode.md#offer-vault-deposits)
>
> The prebuilt **Earn** screen, configured with `features.vaultDeposits`.

> [card] [Deposit into vault destinations](https://docs.trustware.io/guides/vault-destinations.md)
>
> Encode your own destination call with `hooks.postHook`.

> [card] [Earn types](https://docs.trustware.io/api-reference/types.md#earn)
>
> `VaultSummary`, `Position`, `VaultRedeemParams`, and the other vault types.

> [card] [Earn vault endpoints](https://docs.trustware.io/api-reference/vaults.md)
>
> Vault search, details, positions, and withdrawals over REST, plus the `vault` field on `POST /route`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.