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

# Activity and fees

> Read the payments that the rules of an account made, the live fee terms of a network, the sponsorship of an account, and the gas credit of a payee.

After you read this page, you can show the payment history of an account with the right status for each row, show the fees before the owner commits, and know who pays the gas.

## `getActivity`

```ts theme={null}
// client method
getActivity(aa: Hex): Promise<ActivityItem[]>;

// function
function getActivity(backendUrl: string, aa: Hex, fetchImpl: typeof fetch): Promise<ActivityItem[]>;

const ACTIVITY_REQUEST_TIMEOUT_MS = 10_000;
```

Calls `GET /api/wallets/:aa/activity` and returns the payment rows of the account, newest first. The route needs no sign-in, so anyone who names the address can read the rows. A row carries no amount, no recipient and no rule text.

| Item | Value |
| - | - |
| Prompts | none |
| Timeout | `ACTIVITY_REQUEST_TIMEOUT_MS`, 10 seconds. Poll no faster than that. |
| Throws | `Error("getActivity(<aa>) failed: <status> <body>")` on a status that is not 2xx. `Error` for a row with an unknown `kind`. A timeout rejects with the `fetch` error. |

The reader keeps a row with a bad `fee` list and sets `fee` to `null`. It sets an absent or bad `gasCharge` to `null`.

### `ActivityItem`

```ts theme={null}
interface ActivityItem {
  kind: "payment" | "off_ramp_fee";
  redemptionId: Hex;
  status: OutboxTaskStatus;
  txHash?: Hex | null;
  createdAt: number;
  failureReason?: RedemptionFailureReason | null;
  waitReason?: OutboxTaskWaitReason | null;
  fee?: ActivityFeeLeg[] | null;
  gasCharge: ActivityGasCharge | null;
}

interface ActivityFeeLeg {
  token: RoutingToken | null; // null for a contract that the token table does not name
  tokenAddress: Hex;          // the zero address for the native coin
  amountRaw: string;          // a decimal integer string
}

interface ActivityGasCharge {
  tokenAddress: Hex;  // the zero address for the native coin
  amountRaw: bigint;  // base units
}
```

| Field | Meaning |
| - | - |
| `kind` | `payment`: a payment that a rule made. `off_ramp_fee`: the fee part of a bank payout. |
| `redemptionId` | An opaque 32-byte id of the row, as lowercase hex. It is unique within the account and stays the same for the life of the row. Use it as the key of the row. |
| `status` | The state of the payment. See below. |
| `txHash` | The transaction of the payment: the mined one, or the newest sent one for an open row. `null` before any send. |
| `createdAt` | Unix seconds when the engine made the payment. |
| `failureReason` | Why the payment failed. `null` unless `status` is `failed`. |
| `waitReason` | Why an open payment waits. `null` when there is no reported reason. |
| `fee` | The Anafi fee legs of a `landed` payment, empty when it paid no fee. `null` for every other status, and absent from an older Anafi API. |
| `gasCharge` | The network fee that the adapter charged for this payment, or `null` when there was no charge. |

A `waitReason` or a `failureReason` outside the lists below is a value that your SDK version does not know. Show it as "unknown".

### `OutboxTaskStatus`

| Value | Final | Meaning | What to show |
| - | - | - | - |
| `queued` | no | The engine made the payment. Anafi has not sent it yet. | Not started. |
| `in_progress` | no | Anafi sent a transaction, or holds the payment for a `waitReason`. | In progress, and the wait reason. |
| `delivered` | no | A transaction of the payment succeeded on chain. The row becomes `landed` later. | Not final yet. |
| `landed` | yes | The payment landed. | Done, with `txHash` and `fee`. |
| `failed` | yes | The payment closed without a landing. See `failureReason`. | Failed, and the reason. |
| `withdrawn` | yes | The engine withdrew the payment: the account stopped (see `tenant` in [`recover`](https://docs.ana.fi/sdk/confidential-channel#recover)), or a new document removed the rule. | Canceled. |
| `superseded` | yes | The engine replaced the payment with a new one, for example a swap that expired before it landed. The Anafi API does not list a row with this status. The row of the new payment carries the payment. | Nothing. |

### `OutboxTaskWaitReason`

| Value | Meaning | What the owner can do |
| - | - | - |
| `insufficient_funds` | The account holds less than the payment pays out. | Add funds. |
| `grant_inactive_pending` | The Safe does not have the adapter enabled as a module. | Enable the adapter, or revoke the rule. |
| `adapter_delisted_pending` | The registry no longer lists the adapter. | Nothing. |
| `simulation_reverted` | The payment would revert now, for a cause that a later block can change. | Check the balances and permissions. |
| `swap_below_market` | The swap would return too little compared with the market price now. | Wait. |
| `guard_undecided` | Anafi cannot check the swap price now. | Wait. |
| `fee_above_cap` | The network gas price is too high now. | Wait. |
| `in_flight` | A transaction of the payment waits for inclusion. | Wait. |
| `nonce_already_used` | Another copy of the payment landed. The row closes soon. | Wait. |
| `deadline_margin` | The payment is too close to its expiry to send. It closes soon. | Wait. |
| `account_blocked` | Anafi holds the payments of this account. | Contact Anafi. |
| `account_redeem_in_flight` | Another payment of this account waits for its first receipt. | Wait. |

### `RedemptionFailureReason`

| Value | Meaning |
| - | - |
| `insufficient_funds` | The account held less than the payment pays out. |
| `grant_inactive` | The Safe did not have the adapter enabled as a module. |
| `adapter_delisted` | The registry no longer listed the adapter. |
| `window_expired` | The expiry of the payment passed before it landed. |
| `swap_below_market` | The swap would have returned too little compared with the market price. |
| `reverted_on_chain` | The transaction was mined and reverted. |
| `wrong_network` | The payment was made for another network. |
| `legs_failed_on_chain` | The transaction landed, but one or more parts of the payment failed. |
| `other` | Any other failure. |

```ts theme={null}
const rows = await anafi.getActivity(account);
for (const row of rows) {
  const why = row.status === "failed" ? row.failureReason : row.waitReason;
  console.log(row.redemptionId, row.status, why ?? "", row.txHash ?? "");
}
```

See [activity](https://docs.ana.fi/concepts/activity.md).

## `fetchFeeTerms`

```ts theme={null}
// client method
fetchFeeTerms(): Promise<FeeTerms>;

// function
function fetchFeeTerms(backendUrl: string, fetchImpl: typeof fetch): Promise<FeeTerms>;
```

Calls `GET /api/fees` and reads the live fee terms of the network field by field. An absent or bad field throws an `Error`. A failed request throws `BackendRequestError`. The timeout is 10 seconds.

```ts theme={null}
interface FeeTerms {
  feesOn: boolean;
  treasury: Hex | null;
  bps: number | null;
  floorUsdCents: number | null;
  floors: TokenFeeFloor[];
  feeTokens: RoutingToken[];
  observedAt: number | null;
  gas: FeeGasTerms | null;
}

interface TokenFeeFloor {
  token: RoutingToken;
  tokenAddress: Hex;  // the zero address for the native coin
  amountRaw: string;  // a decimal integer string
}

interface FeeGasTerms {
  transferCostBoundBaseWei: bigint;
  transferCostBoundPerLegWei: bigint;
  swapCostBoundWei: bigint;
  maxSendBatchRecipients: number;
  rates: TokenGasRate[];
}

interface TokenGasRate {
  token: RoutingToken;
  tokenAddress: Hex;
  tokenUnitsPerNativeCoin: bigint; // base units of the token that 1 native coin (10^18 wei) costs, rounded up
}
```

| Field | Meaning |
| - | - |
| `feesOn` | Whether the engine adds Anafi fee legs to the payments of accounts that have no sponsor. When `false`, `treasury`, `bps`, `floorUsdCents` and `observedAt` are `null`, and `floors` is empty. |
| `treasury` | The address that the fee legs pay. Checksummed. |
| `bps` | The fee of one leg, in basis points of its gross amount, before the floor. From 0 to 10000. |
| `floorUsdCents` | The smallest fee of one leg, in US cents. |
| `floors` | The floor in each token, in raw units. No fee leg is smaller. A transfer at or below the floor is refused. The reader drops a row in a token that the SDK does not know. |
| `feeTokens` | The tokens that a document can choose in `global.fees_method`, in the order of the API. |
| `observedAt` | Unix seconds of the price read behind `floors`, or `null`. |
| `gas` | The gas cost bounds, or `null` when the answer has no `gas` field. |
| `gas.transferCostBoundBaseWei` | The cost bound of a transfer with no leg, in wei. |
| `gas.transferCostBoundPerLegWei` | What each leg adds to the bound, in wei. |
| `gas.swapCostBoundWei` | The cost bound of a swap, in wei. |
| `gas.maxSendBatchRecipients` | The largest recipient count of one `send_batch`. |
| `gas.rates` | The price of 1 native coin in each fee token. |

```ts theme={null}
function transferCostBoundWei(gas: FeeGasTerms, legs: number): bigint;     // base + per-leg × legs
function tokenAmountOfWei(costWei: bigint, tokenUnitsPerNativeCoin: bigint): bigint; // rounded up
```

`transferCostBoundWei` throws `RangeError` for a `legs` value that is not a whole number of 0 or more.

Show the most gas that a rule can cost in its fee token:

```ts theme={null}
const terms = await anafi.fetchFeeTerms();
if (terms.gas) {
  const rate = terms.gas.rates.find((r) => r.token === "USDC");
  const boundWei = transferCostBoundWei(terms.gas, 2); // a send_batch with 2 recipients
  if (rate) console.log("at most", tokenAmountOfWei(boundWei, rate.tokenUnitsPerNativeCoin), "USDC base units of gas");
}
```

See [fees](https://docs.ana.fi/concepts/fees.md).

## `fetchWalletSponsorship`

```ts theme={null}
// client method
fetchWalletSponsorship(aa: Hex): Promise<WalletSponsorship>;

// function
function fetchWalletSponsorship(backendUrl: string, aa: Hex, fetchImpl: typeof fetch): Promise<WalletSponsorship>;

interface WalletSponsorship {
  feesOn: boolean;
  sponsored: boolean;
}
```

Calls `GET /api/wallets/:aa/sponsorship`. A failed request throws `BackendRequestError`. A bad body throws an `Error`. The timeout is 10 seconds.

| `feesOn` | `sponsored` | Who pays the gas of a Safe owner operation |
| - | - | - |
| `false` | any | Anafi (relayed) |
| `true` | `true` | Anafi (relayed) |
| `true` | `false` | The owner (owner-sent) |

The client reads this before each Safe owner operation. See [Safe account](https://docs.ana.fi/sdk/safe.md#relayed-and-owner-sent-execution). The ERC20Allow leg does not read it.

## Gas credit

```ts theme={null}
function readGasCredit(params: {
  publicClient: PublicClient; // viem
  adapter: Hex;
  payee: Hex;
  token: Hex;                 // the zero address for the native coin
}): Promise<bigint>;

function buildClaimGasCreditCalldata(token: Hex, to: Hex): Hex;
```

Both adapters keep an amount for a payee when a gas charge or a gas refund to that payee fails to pay out: the gas credit. For an account, the credit is a gas refund that the adapter could not pay. `readGasCredit` reads `adapter.gasCredit(payee, token)`. `buildClaimGasCreditCalldata(token, to)` encodes `claimGasCredit(token, to)`, which pays the whole credit of the caller in `token` to `to`. The payee sends this call itself. For the rules of the claim, see [the Safe adapter](https://docs.ana.fi/contracts/safe-adapter.md) and [the ERC20Allow adapter](https://docs.ana.fi/contracts/erc20-allow-adapter.md).

> [!NOTE]
>
> `readGasCredit` takes `publicClient` as the viem `PublicClient` type of the viem version that the SDK pins (`2.55.10`). With another viem version in your project, TypeScript can refuse your client. Install `viem@2.55.10` in your project, or cast the client to the parameter type.

```ts theme={null}
import { buildClaimGasCreditCalldata, readGasCredit } from "@anafi-cc/anafi-sdk";

const credit = await readGasCredit({ publicClient, adapter, payee: account, token: usdc });
if (credit > 0n) {
  const data = buildClaimGasCreditCalldata(usdc, account);
  // For a Safe: executeSafeOwnerCalls({ safe, eoa, legs: [{ target: adapter, calldata: data }], ownerSent: true })
  // For an ERC20Allow account: send { to: adapter, data } from the account.
}
```


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