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

# Managed Balance Refills

> Keep a user's managed USDC balance above a target-chain minimum after trading

<Info>
  Balance refill endpoints require a signed-in user session. Start with
  [Authentication](/recipes/authentication) and [Funding & Withdrawals](/recipes/deposits).
</Info>

Managed balance refills let a user keep a USDC buffer on a selected chain. The user chooses a
minimum balance and a refill amount, and AGG can move USDC from another one of the user's managed
chains after trading lowers the target-chain balance.

For example, a user can set a `$100` minimum and a `$50` refill amount on Polygon. After a completed
trade:

| Observed Polygon balance | Result                                                             |
| ------------------------ | ------------------------------------------------------------------ |
| `$120`                   | No refill is needed.                                               |
| `$80`                    | AGG requests at least `$50`, bringing the balance to about `$130`. |
| `$20`                    | AGG requests at least `$80`, enough to restore the `$100` minimum. |

The requested delivery is the larger of the configured refill amount or the amount needed to
restore the minimum. Network and bridge fees are paid from the source balance and must stay within
the user's configured maximum fee.

## When a refill runs

A refill is considered only after a trade has finished and all orders linked to that trade are in a
terminal state, such as filled, canceled, expired, or failed. AGG refreshes the balance after the
trade before comparing it with the policy minimum.

<Note>
  Creating a policy or making a withdrawal does not immediately trigger a refill. An open resting
  limit order does not trigger one either.
</Note>

Trading always takes priority:

* If another trade is active or queued, AGG waits until queued trading is finished before
  considering the refill.
* Once a refill has started, a newly submitted trade waits for the refill to finish.
* AGG runs at most one balance-moving operation for a user at a time.

## Create a policy

Amounts use six-decimal USDC integer strings. For example, `"100000000"` is `$100` and
`"50000000"` is `$50`.

```ts theme={null}
import { createAggClient } from "@agg-build/sdk";

const client = createAggClient({
  baseUrl: "https://api.agg.market",
  appId: "your-app-id",
});

// Call after the user authenticates.
const policy = await client.createBalanceRefillPolicy({
  targetChainId: 137,
  minimumRaw: "100000000",     // $100 minimum
  refillAmountRaw: "50000000", // refill by at least $50
});
```

The target chain must support managed USDC. A user can have one policy per target chain and can
create policies for more than one chain.

By default, refills are limited to `$250` per UTC day and `$2` in fees per refill. Pass
`dailyCapRaw` or `maxFeeRaw` when the user wants different limits. The daily cap is applied
conservatively to each requested delivery plus its maximum allowed fee and must be large enough to
cover the configured amounts and fee limit. See the
[Create balance refill policy API](/api-reference/execution/create-a-managed-balance-refill-policy)
for field constraints and the complete request and response schemas.

## Read, update, or pause a policy

Use the SDK methods to build the policy controls in your app:

```ts theme={null}
const policies = await client.getBalanceRefillPolicies();

await client.updateBalanceRefillPolicy(policy.id, {
  minimumRaw: "150000000",
  refillAmountRaw: "75000000",
});

await client.updateBalanceRefillPolicy(policy.id, { status: "paused" });
await client.updateBalanceRefillPolicy(policy.id, { status: "enabled" });
```

After a transfer completes or fails, AGG applies the policy's five-minute cooldown before another
attempt can start. The policy response includes `lastObservedRaw`, `lastEvaluatedAt`,
`nextEligibleAt`, and `latestAttempt` so your app can show its current state without reproducing the
refill logic.

<CardGroup cols={2}>
  <Card title="List policies" icon="list" href="/api-reference/execution/list-managed-balance-refill-policies">
    Read the user's configured policies and latest attempt.
  </Card>

  <Card title="Update or pause a policy" icon="sliders" href="/api-reference/execution/update-or-pause-a-managed-balance-refill-policy">
    Change limits or switch a policy between enabled and paused.
  </Card>
</CardGroup>

## Monitor refill attempts

Fetch the most recent attempts when you need a detailed activity view:

```ts theme={null}
const attempts = await client.getBalanceRefillAttempts(policy.id);
```

An attempt moves through `reserved` and `executing`, then ends as `completed` or `failed`. Use
`completedAmountRaw`, `feeRaw`, and `errorMessage` to present the final outcome. The endpoint returns
the 25 most recent attempts for the policy.

<Card title="List refill attempts" icon="clock-rotate-left" href="/api-reference/execution/list-recent-managed-balance-refill-attempts">
  View the complete attempt response schema and status fields.
</Card>

## Source balances and fees

AGG selects an available managed USDC balance on a different supported chain. The source must have
enough spendable USDC for the requested delivery and the maximum fee; funds already reserved for
orders or other operations are not available to a refill.

Managed balance refills do not pull money from a bank account, card, or external wallet. If no
eligible managed source balance is available, or if the fee or daily cap would be exceeded, no
transfer starts. The policy remains enabled and can be considered again after a later completed
trade.

## Withdrawals

Withdrawals and balance refills are serialized so they cannot spend the same managed balance:

* If a withdrawal is already in progress, AGG does not start a refill.
* If a refill is already in progress, a withdrawal request returns `409`. Retry it shortly.
* A withdrawal can take the target balance below its minimum, but the withdrawal itself does not
  trigger a refill. The next eligible completed trade can trigger a new evaluation.

See [Funding & Withdrawals](/recipes/deposits) for the withdrawal flow and the
[Withdrawal API](/api-reference/execution/withdraw-funds) for its complete contract.

## API reference

<CardGroup cols={2}>
  <Card title="Create a policy" icon="circle-plus" href="/api-reference/execution/create-a-managed-balance-refill-policy">
    Configure a target chain, balance minimum, and refill amount, with optional custom safety limits.
  </Card>

  <Card title="List policies" icon="list" href="/api-reference/execution/list-managed-balance-refill-policies">
    Load all policies owned by the authenticated user.
  </Card>

  <Card title="Update a policy" icon="sliders" href="/api-reference/execution/update-or-pause-a-managed-balance-refill-policy">
    Change thresholds or pause and resume automatic refills.
  </Card>

  <Card title="List attempts" icon="clock-rotate-left" href="/api-reference/execution/list-recent-managed-balance-refill-attempts">
    Review recent refill activity and outcomes.
  </Card>
</CardGroup>
