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

# Payments and subscriptions

> Build a pay page that takes a one-time ERC-20 payment with proof, or a monthly payment on the ERC20Allow kind, with resume logic and a receipt email.

After this page, you can build a pay page: a page that a payee shares as a link, where a payer pays an amount of an ERC-20 token one time, or pays now and then each month. You know each prompt, how to prove the payment, how to resume after a reload, and how to send a receipt email.

## The pattern

A pay link carries the payee address, the token, the amount and the network. Your pay page reads the link, connects the wallet of the payer, and offers two modes:

| Mode | What happens | Anafi parts |
| - | - | - |
| Once | One `transfer` from the payer to the payee. | None on chain. Optional receipt email. |
| Monthly | The first payment now, then a committed rule document that pays the same amount each month through the ERC20Allow adapter. | Stage (Anafi API), ERC20Allow adapter, DSL registry. Optional receipt email. |

Where your code runs:

* A one-time payment is a plain transaction of the payer wallet. It does not use the Anafi API. It works in any browser page.
* The stage of the monthly rule goes through the Anafi API. Today, the Anafi API hosts answer CORS only for `https://app.ana.fi`, so stage the rule from your server or from your own same-origin proxy. The stage needs no wallet. The setup after the stage uses only the chain and the wallet, so it runs in the browser of the payer.
* `sendPayReceiptEmail` uses the Anafi API. Call it from your server or proxy.

## One-time payment

### Sequence

```mermaid theme={null}
sequenceDiagram
    autonumber
    participant W as Payer wallet
    participant A as Your app (SDK)
    participant API as Anafi API
    participant E as Anafi engine (black box)
    participant C as Chain
    A->>C: Block number (lowestPaymentBlock = tip + 1)
    A->>W: getChainId, getAddresses
    W->>C: Transaction: token.transfer(payee, amount)
    A->>C: Wait for the receipt (replacement detected)
    A->>A: Proof: Transfer(payer, payee, amount) in the receipt
    A->>API: POST /api/pay/receipt_email (optional)
```

### Steps

**1. Fix the lowest payment block**

Read the tip before the request and add 1: `const lowestPaymentBlock = (await anafi.resolveReadBlock(null)) + 1n`. A receipt below this block is an older transfer and proves nothing about this payment. Store this value with the request.

**2. Send the payment**

Call `sendErc20Payment({ payer, token, payee, amount, lowestPaymentBlock, signal?, onRequested?, onSubmitted? })`. `amount` is in base units of the token.

Before the prompt, the SDK checks that `signal` is not aborted, that the wallet is on the chain of the client, and that the connected account is `payer`. When a check fails, it returns `{ kind: "stopped_before_request", reason }` with `reason` `cancelled`, `wallet_on_other_chain` or `wallet_on_other_account`. The wallet client must have `getAddresses` and `getChainId`.

Then one transaction prompt: `token.transfer(payee, amount)`. `onSubmitted(txHash)` runs with the hash. Store the hash before you do anything else. The SDK waits for the receipt and follows a replacement that the wallet makes.

**3. Read the outcome**

| `kind` | Meaning | What to do |
| - | - | - |
| `paid` | The mined transaction succeeded, and its logs hold `Transfer(payer, payee, amount)` of the token, at or above `lowestPaymentBlock`. `txHash` is the mined transaction. | Show "paid". |
| `cancelled_in_wallet` | The wallet replaced the transfer with a cancel, and the receipt holds no such event. | Show "cancelled". |
| `reverted` | The mined transaction reverted. | Show "failed". |
| `mined_without_transfer` | The mined transaction succeeded with no such event. | Show "not paid". |
| `receipt_below_lowest_block` | The receipt is older than the request. It never means that the payment was not made. | Scan for the transfer. |
| `stopped_before_request` | The wallet was not asked. | Fix the wallet chain or account, and ask again. |

A rejection by the payer throws the wallet error. A receipt that does not arrive in time throws too. You then hold the hash from `onSubmitted`.

The proof of a payment is the `Transfer(payer, payee, amount)` event in a successful receipt. A successful receipt alone is not a proof: a wallet can replace a transfer with a cancel transaction that also succeeds. `logsHoldErc20Transfer(logs, transfer)` runs the same check on any logs.

### Resume after a reload

1. Read the stored hash with `readErc20PaymentTransactionState({ txHash, token, payer, payee, amount, lowestPaymentBlock })`. No prompt. It returns `paid`, `reverted`, `mined_without_transfer`, `receipt_below_lowest_block`, `pending` (the node knows the transaction, no receipt yet) or `not_found`.
2. On `not_found`, the wallet can have replaced the transaction under another hash. Call `scanErc20PaymentTransfers({ token, payer, payee, amount, fromBlock: lowestPaymentBlock })`. It reads at most 2000 blocks (`ERC20_PAYMENT_TRANSFER_SCAN_MAX_BLOCKS`) in one call and returns `{ transfers, toBlock, reachedTip }`. When `reachedTip` is `false`, scan again from `toBlock + 1n`.
3. Do not ask the payer to pay again before both reads say that no transfer exists.

## Monthly payment on the ERC20Allow kind

The payer account must be an ERC20Allow account: an address with no code, or with an EIP-7702 pointer. The rule pays from that address each month.

### Preconditions

| Condition | Check |
| - | - |
| The network has a live `erc20_allow` adapter | `classifyErc20AllowAccount(payer)` is not `leg_not_live` |
| The payer class is served | `no_code` or `eip7702_pointer` |
| The payer is not blocked | `readErc20AllowDelegation(...).blocked` is `false` |
| The payer has no committed document, or has the document of this plan | `readDslCommitment(payer)` |
| The token is an ERC-20 in your `erc20s` table and a fee token of the network | `fetchFeeTerms().feeTokens` |
| The payer holds the amount and the native coin for gas | balance reads |

> [!WARNING]
>
> Check the committed document of the payer first. A commit replaces the whole rule document of the account. A monthly setup over a document of another app removes the rules of that document.

### The rule and the cap

The rule pays `amount` of the token to the payee each month. The fee token is the same token, because the setup approves only one token. `buildStandingOrderDsl` builds the text:

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

const yaml = buildStandingOrderDsl(
  {
    ruleName: "monthly_payment",
    recipients: [{ destination: payee, amount: "10", amountUnit: "USDC" }],
    cadence: "monthly",
    startAt: firstMonthlyRunIso, // for example one month from now, on a day of month up to 28
    timezone: "UTC",
    expiresAt: "",
    notifyByEmail: false,
  },
  { type: "fixed_token", token: "USDC" },
);
```

The first payment is a separate transfer now, so `startAt` is the second payment.

The cap limits what the adapter can pull from the payer in each window. Each payment pulls the amount, the Anafi fee and the gas charge. Give the cap room for at least one full payment in each window, with `periodSeconds` of at least 3600. The fee terms give the numbers:

* Anafi fee: `max(ceil(amount × bps / 10000), floor of the token)`, from `fetchFeeTerms()`, when `feesOn` is `true`.
* Gas charge bound: `tokenAmountOfWei(transferCostBoundWei(gas, 2), rate.tokenUnitsPerNativeCoin)`, with `gas` from the fee terms and `rate` the row of the token in `gas.rates`. One payment has 2 transfer legs: the payment and the fee.

### Sequence of the step setup

```mermaid theme={null}
sequenceDiagram
    autonumber
    participant W as Payer wallet
    participant A as Your app (SDK)
    participant API as Anafi API
    participant E as Anafi engine (black box)
    participant C as Chain
    A->>API: POST /api/wallets/{payer}/dsl/commit/stage (from your server)
    API->>E: Relay
    E-->>A: StagedErc20AllowDsl
    loop Until each step holds on chain
        A->>C: Read allowance, capOf, isBlocked, commitments, account code (one block)
        A->>W: getChainId, getAddresses
        W->>C: Transaction for the next absent step
    end
    Note over C: transfer, approve(adapter, 0) when needed, approve(adapter, max), setCaps, commitDsl
```

### Steps

**1. Stage on your server**

```ts theme={null}
const staged = await anafi.stageErc20AllowDsl({
  account: payer,
  adapter,
  yaml,
  salt,
  parent: await anafi.readDslCommitment(payer),
  plannedCap: cap,
});
```

`plannedCap` makes the stage count the cap as it will be after the setup. Store `yaml` and `salt` with the pay request. The same text and the same salt give the same commitment again after a reload. Send `staged` to the browser. It is plain JSON data. The setup checks that its commitment and tokens match its own text.

**2. Build the plan**

```ts theme={null}
const plan: Erc20AllowSubscriptionPlan = {
  token,            // the ERC-20 address
  payee,
  amount,           // base units
  cap,              // Erc20AllowCapEntry on the same token
  staged,
  expectedCommitments: [], // commitments of earlier stages of this same plan
};
```

The setup refuses, before any read: an adapter that is not the `erc20_allow` row, a staged document of another account than the payer, a cap on another token, a cap window under 3600 seconds, and a staged document that pulls another token.

**3. Choose the transport**

`readWalletAtomicBatchSupport(payer)` returns `true` when the wallet reports the EIP-5792 `atomic` capability as `supported` or `ready` on this chain. Then you can send all steps in one prompt. Else use the step setup.

**4. Step setup: one transaction per step**

Call `setUpErc20AllowSubscription({ payer, plan, paymentConfirmed, lowestPaymentBlock, signal?, onRequested?, onSubmitted?, onStepConfirmed? })`.

Before each prompt, the SDK reads at one block the allowance and the cap of the token, the block switch, the committed document and the account class. It builds the list of absent steps with `buildErc20AllowSubscriptionCalls` and asks for the first one. A step that the chain already shows is skipped. The steps, in order:

| Step | Transaction | Present when |
| - | - | - |
| `payment` | `token.transfer(payee, amount)` | `paymentConfirmed` is `false` |
| `allowance_reset` | `token.approve(adapter, 0)` | the allowance is finite and not 0 |
| `approve` | `token.approve(adapter, 2^256 - 1)` | the allowance is not unlimited |
| `cap` | `adapter.setCaps([cap])` | the cap on chain has another window, or a lower limit |
| `commit` | `AnafiDslRegistry.commitDsl(...)` | the chain commitment is not `staged.commitment` or one of `expectedCommitments` |

The payment is complete when its receipt holds `Transfer(payer, payee, amount)` at or above `lowestPaymentBlock`. Each other step is complete when a later read shows its state. Before the `commit` request, the SDK counts the attestation as lapsed when 300 seconds or less remain (`ERC20_ALLOW_SUBSCRIPTION_ATTESTATION_MARGIN_SECONDS`).

`onRequested(step)` runs before each prompt and can return a promise; use it to store state first. `onSubmitted(step, txHash)` runs with each hash. `onStepConfirmed({ step, txHash, blockNumber })` runs when the chain shows a step.

**5. Batch setup: one prompt**

Call `setUpErc20AllowSubscriptionInBatch({ payer, plan, paymentConfirmed, lowestPaymentBlock, signal?, onRequested?, onSubmitted? })`.

The SDK reads the same facts, builds the same call list, and sends it in one `wallet_sendCalls` request (EIP-5792) with `forceAtomic: true` under a new random identifier. `onRequested(batchId)` runs before the request: store the identifier there. After the wallet accepts the batch, the SDK reads the calls status every 2 seconds for at most 180 seconds. It checks a payment that the status claims against the receipt that its own public client reads.

### Outcomes of the step setup

| `kind` | Meaning | What to do |
| - | - | - |
| `completed` | A read at `block` shows each step. | Show "subscribed". |
| `stopped_before_request` | The wallet was not asked for `step`. `reason` as for a payment. | Fix the wallet, run the setup again. |
| `payment_not_made` | The payment transaction `txHash` was mined with no transfer event. `reason`: `cancelled_in_wallet`, `reverted`, `mined_without_transfer`. | No later step was asked. |
| `payment_receipt_below_lowest_block` | The payment receipt is older than the request. | Scan for the transfer. It never means no payment. |
| `step_reverted` | The transaction of `step` reverted. | Run the setup again. |
| `step_without_effect` | The transaction of `step` succeeded, and a later read does not show its state. | Read the chain, then decide. The setup does not ask for that step again. |
| `attestation_lapsed` | The attestation lapsed before the commit request. | Stage again, run the setup with the new staged value. |
| `unexpected_commitment` | The chain holds another commitment than the plan expects. | Stop. Another document was committed. |

The steps that landed before the end stay on chain in each case.

### Outcomes of the batch setup

| `kind` | Meaning | What to do |
| - | - | - |
| `completed` | Each step holds at `block`. `payment` is the proven payment, or `null`. | Show "subscribed". |
| `steps_absent` | The payment is proven. `absentSteps` still lack. | Run the step setup with `paymentConfirmed: true`. |
| `setup_state_unread` | The payment is proven, and the read after it failed. | Read again later. |
| `pending` | The batch is not final, or the node has not seen the receipt. | Call `readErc20AllowSubscriptionBatchResult` later. |
| `nothing_landed` | The atomic batch failed completely, with no proof of the payment. | The chain is as before. Ask again. |
| `unknown` | No rule gives a definite result. It never means no payment. | Read the batch again, or scan for the transfer. |
| `unknown_to_wallet` | The wallet does not know the identifier (EIP-5792 code 5730). It never means no payment. | Scan for the transfer, then read the setup facts. |
| `unexpected_commitment` | Another document is on chain. | Stop. |
| `batch_refused` | The wallet refused the batch before acceptance, with `code` (EIP-1193, JSON-RPC or EIP-5792), or `null` when the wallet client has no batch methods. Nothing was sent. | Use the step setup. |
| `stopped_before_request` | The wallet was not asked. | Fix the wallet, run again. |
| `attestation_lapsed` | The attestation lapsed before a batch with the commit. | Stage again. |

A rejection by the payer throws the wallet error in both setups.

### Resume after a reload

Store, before each prompt: the pay request, `lowestPaymentBlock`, `yaml`, `salt`, the commitment of each stage, each transaction hash (`onSubmitted`) and the batch identifier (`onRequested`).

1. Batch: call `readErc20AllowSubscriptionBatchResult({ payer, plan, batchId, batchHoldsPayment, lowestPaymentBlock })`. It sends nothing, reads the status one time, and returns a batch result as above.
2. Payment: prove it with `readErc20PaymentTransactionState`, or `scanErc20PaymentTransfers` from `lowestPaymentBlock`. When it is proven, set `paymentConfirmed: true`.
3. Stage again when the attestation lapsed. Put the commitments of the earlier stages in `expectedCommitments`, so that a commit of an earlier stage that landed counts as this plan.
4. Run the step setup again. It skips each step that the chain already shows.

## Receipt email

`sendPayReceiptEmail({ email, txHash, payer, payee, token, amount, mode })` sends `POST /api/pay/receipt_email` with `{ email, txHash, payer, payee, token, amountRaw, mode }`. `mode` is `"once"` or `"monthly"`. No prompt. One request, no retry. `amount` must be above 0.

The Anafi API checks the payment on chain before it sends a mail. For `monthly`, it also checks the ERC20Allow facts of the payer for the token, a cap whose limit is at least the amount, and a committed document. It cannot check the schedule, because the document is confidential.

| `outcome.kind` | Meaning |
| - | - |
| `sent` | One receipt was sent. |
| `already_requested` | A receipt for this transaction hash was requested before. It does not say that a mail went out. |
| `invalid_email` | The address is not accepted. |
| `token_not_accepted` | The token is not a fee token of the network now. |
| `payment_not_found` | The transaction does not hold this payment. |
| `payment_too_old` | The block of the payment is more than 1 hour old. |
| `monthly_setup_not_found` | For `monthly`: the permission, the cap or the committed document is not on chain. |
| `retry_after` | Too many requests now. Wait `seconds`. |
| `mail_not_configured` | This deployment sends no mail. |
| `not_sent` | The mail server did not confirm the mail. Ask again. |

## Example

A browser page sends the one-time payment. The monthly setup takes a staged value from your server.

```ts theme={null}
import {
  type AnafiClient,
  type Erc20AllowCapEntry,
  type Erc20AllowSubscriptionPlan,
  type Hex,
  type StagedErc20AllowDsl,
} from "@anafi-cc/anafi-sdk";

export async function payOnce(anafi: AnafiClient, payer: Hex, token: Hex, payee: Hex, amount: bigint) {
  const lowestPaymentBlock = (await anafi.resolveReadBlock(null)) + 1n;
  const outcome = await anafi.sendErc20Payment({
    payer,
    token,
    payee,
    amount,
    lowestPaymentBlock,
    onSubmitted: (txHash) => localStorage.setItem("pay", JSON.stringify({ txHash, lowestPaymentBlock: `${lowestPaymentBlock}` })),
  });
  return outcome;
}

export async function payMonthly(
  anafi: AnafiClient,
  payer: Hex,
  token: Hex,
  payee: Hex,
  amount: bigint,
  cap: Erc20AllowCapEntry,
  staged: StagedErc20AllowDsl, // from your server
) {
  const plan: Erc20AllowSubscriptionPlan = { token, payee, amount, cap, staged, expectedCommitments: [] };
  const lowestPaymentBlock = (await anafi.resolveReadBlock(null)) + 1n;

  if (await anafi.readWalletAtomicBatchSupport(payer)) {
    const result = await anafi.setUpErc20AllowSubscriptionInBatch({
      payer,
      plan,
      paymentConfirmed: false,
      lowestPaymentBlock,
      onRequested: (batchId) => localStorage.setItem("batch", batchId),
    });
    if (result.kind !== "batch_refused") return result;
  }

  return anafi.setUpErc20AllowSubscription({
    payer,
    plan,
    paymentConfirmed: false,
    lowestPaymentBlock,
    onSubmitted: (step, txHash) => localStorage.setItem(`step:${step}`, txHash),
    onStepConfirmed: ({ step, blockNumber }) => console.log(step, "confirmed at", blockNumber),
  });
}
```


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