> ## 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.

# Execution

> What an integrator sees when a rule fires, on chain and in the activity feed, and what to show the user for each status and reason.

After this page, you can follow a rule payment from the activity feed to the chain, explain each status and reason to the user, and check the payment on chain yourself. The engine decides when a rule fires. This page describes what you can observe, not how the engine decides.

## Sequence

```mermaid theme={null}
sequenceDiagram
    autonumber
    participant W as Owner wallet
    participant A as Your app (SDK)
    participant API as Anafi API
    participant E as Anafi engine (black box)
    participant C as Chain
    E->>E: A rule fires (time, price, or transfer)
    E->>E: Sign the payment: legs, gas terms, nonce, validUntil
    E->>API: Signed payment
    API->>C: adapter.redeemAsEngine(payload, gasTerms, nonce, validUntil, engineSignature)
    Note over C: Adapter checks, gas charge, legs, settlement
    C-->>C: Events: Transfer, EngineRedeemed or EngineRedeemFailed, GasCharged
    A->>API: GET /api/wallets/{account}/activity
    API-->>A: Rows: status, waitReason, failureReason, txHash, fee, gasCharge
    A->>C: Read the receipt of txHash
```

The owner signs nothing when a rule fires. Anafi submits the transaction and pays the chain gas. Anafi can delay a payment; it can never read, redirect or create one.

## The transaction on chain

Each payment is one call to `redeemAsEngine` on the adapter of the account: `AnafiDelegationAdapterSafe` or `AnafiDelegationAdapterERC20Allow`. See [Redeem](https://docs.ana.fi/contracts/redeem.md) for the payload, the digest, the gas terms and each check.

A redeem transaction has one of three outcomes. You see the outcome in the receipt:

| Outcome | What the receipt shows | Effect |
| - | - | - |
| Paid | Success. `EngineRedeemed(nonce, digest)`, then `GasCharged(nonce, digest, token, charge)`, and the `Transfer` events of the legs. | The legs ran. The nonce is spent. The gas charge is paid. |
| Legs failed | Success. `EngineRedeemFailed(nonce, digest)`, then `GasCharged(...)`. | The adapter undid the legs. The nonce is spent. The gas charge is paid. |
| Refused | Revert, with an adapter error such as `RedeemWindowExpired()`, `NonceAlreadyUsed()`, `OwnerBlocked(account)` or `GasChargeCollectionFailed()`. | Nothing changed. The nonce is not spent. |

When a payment to the receiver of the gas charge or a refund to the account fails, the adapter keeps the amount as a gas credit, which its payee can claim with `claimGasCredit(token, to)`. See [Redeem](https://docs.ana.fi/contracts/redeem.md) for each check and each error.

### Fee legs

When fees are on and the account has no sponsor, the legs of a payment include the Anafi fee: a transfer of the fee token to the fee treasury. `GET /api/fees` (`fetchFeeTerms`) names the treasury, the rate in basis points and the floor per token. The gas charge goes to the receiver that the gas terms name, the same `treasury`. On chain, you see these as `Transfer` events in the same transaction. In the activity row, `fee` lists the fee legs of a landed payment and `gasCharge` the gas charge. See [Fees](https://docs.ana.fi/concepts/fees.md).

### Nonce and deadline

Each payment carries a firing nonce and a deadline, `validUntil`. Read whether a nonce is spent with `usedNonces(nonce)` on the Safe adapter or `isNonceUsed(nonce)` on the ERC20Allow adapter. See [Redeem](https://docs.ana.fi/contracts/redeem.md#nonce-and-deadline) for the rules of the nonce and the deadline.

The deadline bounds the time at which a signed payment can land. It does not set the time at which a rule fires.

## The activity feed

`getActivity(account)` reads `GET /api/wallets/{account}/activity` and returns `ActivityItem[]`, newest first. The route needs no sign-in, so it shows only identity and status. The request times out after 10 seconds. Poll it, for example every few seconds while a payment is open. See [Activity and fees](https://docs.ana.fi/sdk/activity-and-fees.md) for each field.

| Field | Meaning |
| - | - |
| `kind` | `payment`, or `off_ramp_fee` for the fee of a bank payout. |
| `redemptionId` | A stable 32-byte id of the row. Use it as the key. |
| `status` | See the next table. |
| `txHash` | The hash of the redeem transaction, or `null` before the first send. |
| `createdAt` | Unix seconds when the engine created the payment. |
| `waitReason` | Why an open payment waits, or `null`. |
| `failureReason` | Why a `failed` payment failed, or `null`. |
| `fee` | The Anafi fee legs of a `landed` payment: `token`, `tokenAddress`, `amountRaw`. Empty when it paid none. `null` for other statuses. |
| `gasCharge` | The gas charge of the payment: `tokenAddress` (zero address for the native coin) and `amountRaw` as a `bigint`. The Anafi API leaves the field out when no charge is recorded, and the SDK then returns `null`. |

### Status

| `status` | Final | Meaning | What to show |
| - | - | - | - |
| `queued` | no | The engine signed the payment. It is not sent yet. | "Scheduled" |
| `in_progress` | no | Anafi sent an attempt, or holds the payment for a wait reason. | "In progress", and the wait reason |
| `delivered` | no | A successful receipt of the redeem is seen at the confirmation depth. This can still change. | "Sent, not final yet" |
| `landed` | yes | The chain holds `EngineRedeemed` for this payment. | "Paid", with the fee and the gas charge |
| `failed` | yes | The payment closed and did not land. See `failureReason`. | the failure text |
| `withdrawn` | yes | The engine closed the payment: a new document removed its rule, or the account was parked. | "Withdrawn" |

The SDK type `OutboxTaskStatus` also has `superseded`. The Anafi API never lists a row with this status, because a newer row carries the same payment. A value that is not in this table is unknown to your app. Show it as open, and do not treat it as final.

### Wait reasons

| `waitReason` | Meaning | What to show or do |
| - | - | - |
| `insufficient_funds` | The account holds less than the payment sends. | Ask the owner to add funds. The payment goes out after that. |
| `grant_inactive_pending` | The Safe module reads as disabled. | Ask the owner to enable the module again. |
| `adapter_delisted_pending` | The registry does not list the adapter now. | Nothing for the owner to do. |
| `simulation_reverted` | The payment cannot run at the current block. Anafi tries again. | Show "Waits". Check balances, caps and the block switch. |
| `swap_below_market` | The swap would pay too far below the market price now. | Show "Waits for a better price". |
| `guard_undecided` | The swap cannot be judged at the current block. | Show "Waits". |
| `fee_above_cap` | The network fee is too high to send the payment now. The payment waits for lower fees. | Show "Waits for lower network fees". |
| `in_flight` | Sent. The chain has not included it yet. | Show "sent". |
| `nonce_already_used` | Another copy of the same payment landed. The chain confirms it. | Show "Sent, not final yet". |
| `deadline_margin` | Too close to its deadline to send. It closes soon. | Show "Closes soon". |
| `account_blocked` | Anafi holds all payments of this account. | Show "paused by Anafi". Tell the owner to contact Anafi. |
| `account_redeem_in_flight` | Another payment of the account is in flight. | Show "Waits". |

### Failure reasons

| `failureReason` | Meaning | What to show or do |
| - | - | - |
| `insufficient_funds` | The account held less than the payment sends. | "Not enough funds. Nothing was paid." Add funds for the next run. |
| `grant_inactive` | The Safe module was disabled. | "The permission is off. Nothing was paid." |
| `adapter_delisted` | The registry no longer lists the adapter (`AdapterNotAllowed()`). | "Nothing was paid." |
| `window_expired` | The deadline passed before the payment landed. | "Nothing was paid." |
| `swap_below_market` | The swap would have paid far below the market price. | "Swap held back. Nothing was paid." |
| `reverted_on_chain` | The transaction reverted on chain. | "Nothing was paid." |
| `wrong_network` | The payment was signed for another network. | "Nothing was paid." |
| `other` | Any other failure. | "Nothing was paid." |
| `legs_failed_on_chain` | The transaction landed, and the legs failed (`EngineRedeemFailed`). | "The payment failed on chain." When `gasCharge.amountRaw` is above 0, add that the gas charge was paid. |

An unknown `failureReason` reads as `other`.

## Check a payment on chain

Do not trust the feed alone for money that matters. Read the receipt of `txHash` and look for:

* the `EngineRedeemed` event of the adapter of the account (the legs succeeded), or `EngineRedeemFailed`;
* the `GasCharged` event, with the token and the charge;
* the `Transfer` events of the payment and of the fee legs.

## Example

```ts theme={null}
import type { ActivityItem, AnafiClient, Hex } from "@anafi-cc/anafi-sdk";
import { decodeEventLog, parseAbi, type PublicClient } from "viem";

const ADAPTER_EVENTS = parseAbi([
  "event EngineRedeemed(uint256 indexed nonce, bytes32 indexed digest)",
  "event EngineRedeemFailed(uint256 indexed nonce, bytes32 indexed digest)",
  "event GasCharged(uint256 indexed nonce, bytes32 indexed digest, address token, uint256 charge)",
]);

const FINAL = new Set(["landed", "failed", "withdrawn"]);

export async function waitForFinal(anafi: AnafiClient, account: Hex, redemptionId: Hex): Promise<ActivityItem> {
  for (;;) {
    const row = (await anafi.getActivity(account)).find((item) => item.redemptionId === redemptionId);
    if (row && FINAL.has(row.status)) return row;
    console.log(row?.status, row?.waitReason ?? "");
    await new Promise((resolve) => setTimeout(resolve, 5_000));
  }
}

export async function checkOnChain(publicClient: PublicClient, adapter: Hex, txHash: Hex) {
  const receipt = await publicClient.getTransactionReceipt({ hash: txHash });
  for (const log of receipt.logs) {
    if (log.address.toLowerCase() !== adapter.toLowerCase()) continue;
    try {
      const event = decodeEventLog({ abi: ADAPTER_EVENTS, data: log.data, topics: log.topics });
      console.log(event.eventName, event.args);
    } catch {
      // another event of the adapter
    }
  }
}
```


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