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

# Example: Treasury Portfolio

Enable automatic rebalancing when Ground should keep funds near percentage
targets. Ground deploys deposits and rebalances the wallet as balances change.

```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
sequenceDiagram
    participant Treasury
    participant App as "Your application"
    participant Ground

    App->>Ground: Create wallet with auto-rebalance
    Ground-->>App: Wallet and deposit addresses
    Treasury->>Ground: Send stablecoin
    Ground-->>App: Deposit completed
    Ground->>Ground: Deploy toward percentage targets
    Ground-->>App: Rebalance completed
    App->>Ground: Read balances, positions, and yield
    App->>Ground: Create withdrawal
    Ground-->>Treasury: Stablecoin payout
```

Store your API key in `GROUND_API_KEY`. The examples below use the sandbox API:

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
const baseUrl = "https://sandbox.groundtech.co";
const apiToken = process.env.GROUND_API_KEY!;
```

## 1. Fetch yield sources

Fetch the available yield sources before creating the wallet. Use the returned
`id` and `depositToken` values when building the strategy.

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
type YieldSource = {
  id: string;
  name: string;
  depositToken: "usdc" | "usdt" | "ousd";
  apyPct: number | null;
};

const catalogResponse = await fetch(`${baseUrl}/v3/assets`, {
  headers: { Authorization: `Bearer ${apiToken}` },
});

if (!catalogResponse.ok) throw new Error(await catalogResponse.text());
const catalog = (await catalogResponse.json()) as { data: YieldSource[] };
```

## 2. Create the wallet

Allocations for each allocation group must total 100%. Persist the request ID and payload before submitting; reuse them unchanged after an uncertain response.

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
type Wallet = {
  id: string;
  autoRebalance: boolean;
  status: string;
  depositAddresses: Record<string, string>;
  positions: Array<{
    assetId: string;
    kind: string;
    label: string;
    valueUsd: string;
  }>;
};

const requestId = crypto.randomUUID();
await saveGroundRequestId("treasury", "wallet_creation", requestId);

const response = await fetch(`${baseUrl}/v3/wallets`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiToken}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    requestId,
    label: "Corporate Treasury",
    autoRebalance: true,
    strategy: {
      allocations: {
        "usdc:crosschain": [
          { assetId: "528c2a8c-e961-4cb6-8a6b-966e05475496", targetWeightPct: 60 },
          { assetId: "03389041-80ad-4dcf-8fe2-3536bcfe92db", targetWeightPct: 40 },
        ],
      },
    },
  }),
});

if (!response.ok) throw new Error(await response.text());
const treasuryWallet = (await response.json()) as Wallet;
```

The response can start with `status: "creating"` or return a prepared wallet. Subscribe to
`portfolio_wallet.status_changed` before creating the wallet. When the matching
`walletId` reaches `idle`, read `GET /v3/wallets/{id}` to get its deposit
addresses. Fund only after the intended network’s address appears; `idle` does not imply all networks are ready. Handle `failed` as a provisioning failure, and use the wallet read
to reconcile a delayed or missed webhook.

## 3. Deposit funds

Send a supported stablecoin to the matching deposit address. Ground credits the
deposit and deploys the funds toward the target percentages.

Subscribe to these events or poll the related resources:

| Event | Meaning |
| - | - |
| `portfolio_wallet.deposit.status_changed` | The deposit status changed |
| `portfolio_wallet.rebalance.status_changed` | Deployment or rebalancing progressed |

Wait for the deposit to become `completed` before using it in your application.
See [Deposits](https://docs.groundtech.co/v3/docs/portfolio-wallets/deposits.md).

## 4. Read or update the portfolio

Read the wallet to get its current cash, investments, and balances:

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
const response = await fetch(
  `${baseUrl}/v3/wallets/${treasuryWallet.id}`,
  { headers: { Authorization: `Bearer ${apiToken}` } },
);

if (!response.ok) throw new Error(await response.text());
const currentTreasury = (await response.json()) as Wallet;

console.log(currentTreasury.positions);
```

Ground continues to maintain the target percentages. To change them, call
`PATCH /v3/wallets/{id}/strategy`.

## 5. Monitor earnings and withdrawals

Use [Balances and Yield](https://docs.groundtech.co/v3/docs/portfolio-wallets/balances-and-yield.md) to interpret holdings and earnings. To pay treasury funds out, follow [Withdraw Funds](https://docs.groundtech.co/v3/docs/portfolio-wallets/withdraw-funds.md): preview first, persist the withdrawal request, handle any customer approval, and track receiver delivery. Automatic wallets let Ground choose funding positions; omit explicit `sources`.

## Test the integration

In sandbox:

1. Create a wallet with automatic rebalancing and wait for the intended deposit address.
2. Deposit test USDC to `depositAddresses.ethereum_sepolia`.
3. Confirm the deposit completes and a rebalance deploys the funds.
4. Confirm `GET /v3/wallets/{id}` returns the new positions.
5. Confirm `GET /v3/wallets/{id}/yield` returns the yield summary.
6. Preview and complete a small withdrawal.

Switch the base URL and API key before using production chain names and
addresses.


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