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

> Send a plain ERC-20 payment, prove it on chain, and set up a monthly subscription from an ERC20Allow account step by step or in one EIP-5792 batch.

After you read this page, you can take a one-time payment, check it on chain, and set up a monthly payment that Anafi runs from the payer's own address.

These methods power a pay page: a payer pays once, or pays now and every month after. The first payment is a plain ERC-20 `transfer` from the payer's wallet. The monthly payment is a rule document of an [ERC20Allow account](https://docs.ana.fi/sdk/erc20-allow.md). See [payments and subscriptions](https://docs.ana.fi/flows/payments-and-subscriptions.md).

## Common rules

* **The proof of a payment is the `Transfer` event.** A successful receipt is not proof. A wallet can replace a transfer by a cancel with the same nonce, and that transaction also succeeds. The SDK counts a payment as made only when a successful receipt holds `Transfer(payer, payee, amount)` of the token, with the exact amount (`logsHoldErc20Transfer`).
* **`lowestPaymentBlock` guards against old receipts.** Read the tip before the request, and pass the tip plus 1. A receipt in a lower block belongs to an older transaction, and the SDK never counts it as this payment.
* **The wallet must be on the right chain and account.** Before each wallet request, the payment methods check that `signal` is not aborted, that `walletClient.getChainId()` is `chainId`, and that `walletClient.getAddresses()[0]` is the payer. A failed check answers `stopped_before_request` with a reason. A wallet client without `getAddresses` or `getChainId` makes the method throw.
* **A wallet rejection rejects.** When the payer rejects the request, the method rejects with the error of the wallet.

### `OwnerRequestStopReason`

```ts theme={null}
type OwnerRequestStopReason = "cancelled" | "wallet_on_other_chain" | "wallet_on_other_account";
```

| Value | Meaning | What to do |
| - | - | - |
| `cancelled` | Your `signal` aborted, or the wallet client threw `OwnerRequestCancelledError`. | Nothing was sent. |
| `wallet_on_other_chain` | The wallet is on another chain. | Ask the payer to switch the chain, then start again. |
| `wallet_on_other_account` | The first address of the wallet is not the payer. | Ask the payer to select the payer account. |

## `sendErc20Payment`

```ts theme={null}
sendErc20Payment(params: SendErc20PaymentParams): Promise<Erc20PaymentOutcome>;

interface SendErc20PaymentParams {
  payer: Hex;
  token: Hex;
  payee: Hex;
  amount: bigint;              // base units of the token
  lowestPaymentBlock: bigint;
  signal?: AbortSignal;
  onRequested?: () => void;
  onSubmitted?: (txHash: Hex) => void;
}
```

Sends one ERC-20 `transfer(payee, amount)` from `payer` to the token, and answers what became of it. No adapter, no registry and no Anafi API is in it. Prompts: 1 transaction.

| Parameter | Meaning |
| - | - |
| `lowestPaymentBlock` | The tip that you read before the request, plus 1. |
| `signal` | Stops the method before the wallet request. It does not stop a sent transaction. |
| `onRequested` | Runs just before the wallet request. An abort of `signal` inside it still stops the request. |
| `onSubmitted` | Runs with the hash that the wallet returned, before the receipt wait. Store the hash here, so you can check the payment later with `readErc20PaymentTransactionState`. |

### `Erc20PaymentOutcome`

```ts theme={null}
type Erc20PaymentOutcome =
  | { kind: "paid"; txHash: Hex; blockNumber: bigint }
  | { kind: "cancelled_in_wallet"; txHash: Hex }
  | { kind: "reverted"; txHash: Hex }
  | { kind: "mined_without_transfer"; txHash: Hex }
  | { kind: "receipt_below_lowest_block"; txHash: Hex; blockNumber: bigint }
  | { kind: "stopped_before_request"; reason: OwnerRequestStopReason };
```

`txHash` is the hash of the mined transaction. It differs from the submitted hash when the wallet replaced the transaction.

| `kind` | Meaning | What to show |
| - | - | - |
| `paid` | The mined transaction holds the `Transfer` event. This holds also after a cancel that the wallet reported. | Paid. |
| `cancelled_in_wallet` | The wallet replaced the transfer by a cancel with no such event. | Not paid. Offer a retry. |
| `reverted` | The mined transaction reverted. | Not paid. |
| `mined_without_transfer` | The mined transaction succeeded with no such event. | Not paid. |
| `receipt_below_lowest_block` | The receipt is below `lowestPaymentBlock`. It proves nothing about this request. | Unknown. This never means "not paid". Check again with `scanErc20PaymentTransfers`. |
| `stopped_before_request` | The wallet was not asked. | See the reason. |

Throws: a wallet answer that is not a 32-byte hex hash rejects before `onSubmitted`; the transfer can still have been sent. A receipt that does not arrive in 180 seconds rejects; you then hold the hash from `onSubmitted`. A receipt that names no mined transaction rejects.

```ts theme={null}
const tip = await publicClient.getBlockNumber({ cacheTime: 0 });
const outcome = await anafi.sendErc20Payment({
  payer,
  token: "0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582", // USDC on polygon-amoy
  payee,
  amount: 25_000_000n, // 25 USDC
  lowestPaymentBlock: tip + 1n,
  onSubmitted: (txHash) => localStorage.setItem("payment", txHash),
});
if (outcome.kind === "paid") showReceipt(outcome.txHash);
```

## `readErc20PaymentTransactionState`

```ts theme={null}
readErc20PaymentTransactionState(params: ReadErc20PaymentTransactionStateParams): Promise<Erc20PaymentTransactionState>;

interface ReadErc20PaymentTransactionStateParams {
  txHash: Hex;
  token: Hex;
  payer: Hex;
  payee: Hex;
  amount: bigint;
  lowestPaymentBlock: bigint;
}

type Erc20PaymentTransactionState =
  | { kind: "paid"; txHash: Hex; blockNumber: bigint }
  | { kind: "reverted"; txHash: Hex }
  | { kind: "mined_without_transfer"; txHash: Hex }
  | { kind: "receipt_below_lowest_block"; txHash: Hex; blockNumber: bigint }
  | { kind: "pending" }
  | { kind: "not_found" };
```

Reads what the chain shows now of a stored payment transaction, with no wallet request. It reads the receipt. With no receipt, it asks the node for the transaction.

| `kind` | Meaning |
| - | - |
| `paid`, `reverted`, `mined_without_transfer`, `receipt_below_lowest_block` | As for `sendErc20Payment`. |
| `pending` | The node knows the transaction and has no receipt yet. |
| `not_found` | The node knows neither. A transaction that the wallet replaced never gets a receipt under its own hash. Scan for the transfer with `scanErc20PaymentTransfers`. |

Throws: a failed read, a receipt that names no mined transaction, and a public client with no `getTransactionReceipt` or no `getTransaction`.

## `scanErc20PaymentTransfers`

```ts theme={null}
scanErc20PaymentTransfers(params: ScanErc20PaymentTransfersParams): Promise<Erc20PaymentTransferScan>;

interface ScanErc20PaymentTransfersParams {
  token: Hex;
  payer: Hex;
  payee: Hex;
  amount: bigint;
  fromBlock: bigint;
}

interface Erc20PaymentTransferScan {
  transfers: Erc20PaymentTransferLocation[]; // oldest first
  toBlock: bigint;                           // the last block read
  reachedTip: boolean;
}

interface Erc20PaymentTransferLocation {
  txHash: Hex;
  blockNumber: bigint;
  logIndex: number;
}

const ERC20_PAYMENT_TRANSFER_SCAN_MAX_BLOCKS = 2_000n;
```

Scans the `Transfer(payer, payee, value)` events of the token from `fromBlock` to the uncached tip, with one `getLogs` call of at most `ERC20_PAYMENT_TRANSFER_SCAN_MAX_BLOCKS` blocks. Only an exact `amount` counts. A removed log does not count. When `reachedTip` is `false`, call again from `toBlock + 1n`. A `fromBlock` above the tip reads nothing and answers `reachedTip: true`.

Throws: a log with a malformed field, a failed read, and a public client with no `getLogs`.

```ts theme={null}
let from = lowestPaymentBlock;
for (;;) {
  const scan = await anafi.scanErc20PaymentTransfers({ token, payer, payee, amount, fromBlock: from });
  if (scan.transfers.length > 0) return scan.transfers[0];
  if (scan.reachedTip) return null;
  from = scan.toBlock + 1n;
}
```

## Monthly subscription

A monthly subscription has five steps. The payer sends each one from the payer address.

| Step | Transaction | Skipped when |
| - | - | - |
| `payment` | `token.transfer(payee, amount)`: the first payment | `paymentConfirmed` is `true` |
| `allowance_reset` | `token.approve(adapter, 0)` | the allowance is 0 or unlimited |
| `approve` | `token.approve(adapter, 2^256 - 1)` | the allowance is unlimited |
| `cap` | `adapter.setCaps([plan.cap])` | the cap on chain has the same window and a limit at least as high (`isErc20AllowCapAtLeast`) |
| `commit` | `AnafiDslRegistry.commitDsl(...)` of `plan.staged` | the committed document is one that the plan expects |

`buildErc20AllowSubscriptionCalls` builds this list from the chain facts. A step that the chain already shows is never asked for.

### The plan

```ts theme={null}
interface Erc20AllowSubscriptionPlan {
  token: Hex;
  payee: Hex;
  amount: bigint;
  cap: Erc20AllowCapEntry;
  staged: StagedErc20AllowDsl;
  expectedCommitments: readonly Hex[];
}
```

| Field | Meaning |
| - | - |
| `token` | The ERC-20 of the payment. |
| `payee` | The receiver. |
| `amount` | The first payment, in base units. |
| `cap` | The cap that the setup sets. `cap.token` must be `token`. The window must be 3600 seconds or more. |
| `staged` | The staged monthly document of the payer, from `stageErc20AllowDsl`. `staged.account` must be the payer. Every token of `staged.tokens` must be `token`, so the fee token of the document must also be `token`. |
| `expectedCommitments` | Other commitments that you staged for this same subscription, for example an earlier stage of a retry. A chain commitment equal to one of them, or to `staged.commitment`, counts as done. |

### Prepare a plan

```ts theme={null}
import {
  buildStandingOrderDsl,
  type Erc20AllowSubscriptionPlan,
  type Hex,
} from "@anafi-cc/anafi-sdk";
import { toHex } from "viem";

const usdc: Hex = "0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582";
const yaml = buildStandingOrderDsl(
  {
    ruleName: "monthly_plan",
    recipients: [{ destination: payee, amount: "25", amountUnit: "USDC" }],
    cadence: "monthly",
    startAt: "2027-02-01T09:00:00Z",
    timezone: "Europe/Berlin",
    expiresAt: "",
    notifyByEmail: false,
  },
  { type: "fixed_token", token: "USDC" },
);
const cap = { token: usdc, limit: 30_000_000n, periodSeconds: 31 * 24 * 3600 };
const staged = await anafi.stageErc20AllowDsl({
  account: payer,
  adapter: config.delegationAdapters.erc20_allow!,
  yaml,
  salt: toHex(crypto.getRandomValues(new Uint8Array(32))),
  parent: await anafi.readDslCommitment(payer),
  plannedCap: cap,
});
const plan: Erc20AllowSubscriptionPlan = {
  token: usdc,
  payee,
  amount: 25_000_000n,
  cap,
  staged,
  expectedCommitments: [],
};
```

### Plan checks

Before any read, both setup methods refuse with an `Error`:

* a `staged.adapter` that is not the configured `erc20_allow` row;
* a `staged.account` that is not the payer;
* a `cap.token` that is not `token`;
* a cap window under 3600 seconds;
* a staged document that pulls another token than `token`.

Then they check the staged value as `commitStagedErc20AllowDsl` does (`Erc20AllowStagedDocumentMismatchError`, the token checks, and a new swap support read for a document with a swap). They refuse a wallet client without `getAddresses` or `getChainId`. At each chain read, they refuse an adapter that the registry does not list, an account that the leg does not serve, and a blocked account (`Erc20AllowNotLiveError`).

## `setUpErc20AllowSubscription`

```ts theme={null}
setUpErc20AllowSubscription(params: SetUpErc20AllowSubscriptionParams): Promise<Erc20AllowSubscriptionOutcome>;

interface SetUpErc20AllowSubscriptionParams {
  payer: Hex;
  plan: Erc20AllowSubscriptionPlan;
  paymentConfirmed: boolean;
  lowestPaymentBlock: bigint;
  signal?: AbortSignal;
  onRequested?: (step: Erc20AllowSubscriptionStep) => void | Promise<void>;
  onSubmitted?: (step: Erc20AllowSubscriptionStep, txHash: Hex) => void;
  onStepConfirmed?: (confirmed: Erc20AllowSubscriptionConfirmedStep) => void;
}

type Erc20AllowSubscriptionStep = "payment" | "allowance_reset" | "approve" | "cap" | "commit";

interface Erc20AllowSubscriptionConfirmedStep {
  step: Erc20AllowSubscriptionStep;
  txHash: Hex;        // for the payment, the mined transaction with the Transfer event
  blockNumber: bigint;
}
```

Sets up the subscription one plain transaction at a time. Prompts: 1 per step that the chain does not show, at most 5.

The loop:

1. Read the facts of the payer at one block: the allowance and the cap of `token`, the block switch, the committed document, and the account class. The block is the tip, or the block of the last receipt when the tip is below it.
2. If the chain holds a commitment that the plan does not expect, end with `unexpected_commitment`.
3. Build the list of the steps that are still absent.
4. If a step that this setup sent and confirmed is still in the list, end with `step_without_effect`. The setup never asks for a step twice.
5. Report the step that the read now shows with `onStepConfirmed`.
6. If the list is empty, end with `completed`.
7. Run the stop checks. For the `commit` step, end with `attestation_lapsed` when 300 seconds or less remain to the attestation deadline (`ERC20_ALLOW_SUBSCRIPTION_ATTESTATION_MARGIN_SECONDS`).
8. Call `onRequested(step)` and wait for its promise. Ask the wallet for the first step. Call `onSubmitted(step, hash)`. Wait for the receipt.
9. For `payment`: a receipt with the `Transfer` event confirms it (`onStepConfirmed`). Any other verdict ends the setup. For another step: a reverted receipt ends with `step_reverted`.
10. Go to step 1.

| Parameter | Meaning |
| - | - |
| `paymentConfirmed` | `true` when the first payment is already confirmed. The setup then sends no payment. |
| `lowestPaymentBlock` | The tip that you read before the first request, plus 1. |
| `signal` | Stops the setup before its next wallet request. |
| `onRequested` | Runs before each wallet request. The request waits for its promise. Store your progress here. |

### `Erc20AllowSubscriptionOutcome`

```ts theme={null}
type Erc20AllowSubscriptionOutcome =
  | { kind: "completed"; block: bigint }
  | { kind: "stopped_before_request"; step: Erc20AllowSubscriptionStep; reason: OwnerRequestStopReason }
  | { kind: "payment_not_made"; reason: "cancelled_in_wallet" | "reverted" | "mined_without_transfer"; txHash: Hex }
  | { kind: "payment_receipt_below_lowest_block"; txHash: Hex }
  | { kind: "step_reverted"; step: Exclude<Erc20AllowSubscriptionStep, "payment">; txHash: Hex }
  | { kind: "step_without_effect"; step: Exclude<Erc20AllowSubscriptionStep, "payment">; txHash: Hex }
  | { kind: "attestation_lapsed" }
  | { kind: "unexpected_commitment"; commitment: OnChainDsl };
```

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

| `kind` | Meaning | What to do |
| - | - | - |
| `completed` | A read at `block` shows every step. | Done. |
| `stopped_before_request` | The wallet was not asked for `step`. | Fix the reason, and run the setup again. |
| `payment_not_made` | The payment transaction holds no `Transfer` event. No later step was asked. | Ask the payer to pay again. |
| `payment_receipt_below_lowest_block` | The payment receipt is below `lowestPaymentBlock`. No later step was asked. This never means "not paid". | Scan for the transfer before you ask again. |
| `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. | Show an error. Do not loop. |
| `attestation_lapsed` | The attestation of the staged document lapsed before the commit request. | Stage the document again, and run the setup with the new staged document. Set `paymentConfirmed: true` when the payment step was confirmed. |
| `unexpected_commitment` | The chain holds `commitment`, which the plan does not expect. | Another document of the payer is live. Ask the payer what to do. |

```ts theme={null}
const tip = await publicClient.getBlockNumber({ cacheTime: 0 });
const outcome = await anafi.setUpErc20AllowSubscription({
  payer,
  plan,
  paymentConfirmed: false,
  lowestPaymentBlock: tip + 1n,
  onRequested: (step) => showStatus(`Confirm the ${step} step in your wallet`),
  onStepConfirmed: ({ step }) => markDone(step),
});
```

## `setUpErc20AllowSubscriptionInBatch`

```ts theme={null}
setUpErc20AllowSubscriptionInBatch(params: SetUpErc20AllowSubscriptionInBatchParams): Promise<Erc20AllowSubscriptionBatchOutcome>;

interface SetUpErc20AllowSubscriptionInBatchParams {
  payer: Hex;
  plan: Erc20AllowSubscriptionPlan;
  paymentConfirmed: boolean;
  lowestPaymentBlock: bigint;
  signal?: AbortSignal;
  onRequested?: (batchId: string) => void | Promise<void>;
  onSubmitted?: (batchId: string) => void;
}
```

Sets up the subscription with one atomic EIP-5792 batch. Prompts: 1 batch.

1. Runs the plan checks. A wallet client with no `sendCalls` or no `getCallsStatus` answers `{ kind: "batch_refused", code: null }`.
2. Reads the facts once and builds the same call list. An unexpected commitment answers `unexpected_commitment` with `payment: null`. An empty list answers `completed` with `payment: null`.
3. Makes a new random 32-byte batch id. Runs the stop checks, and for a batch with the commit, the 300-second attestation margin.
4. Calls `onRequested(batchId)` and waits for its promise. Store the id here.
5. Calls `sendCalls({ account: payer, calls, id: batchId, forceAtomic: true })`.
6. A wallet error with one of the codes 4100, 4200, -32601, -32602, 5700, 5710, 5740, 5750, 5760 proves a refusal before acceptance: `batch_refused` with that `code`. A user rejection (4001) rejects. Any other error can hide an accepted batch, so the setup reads the status of its id.
7. Calls `onSubmitted(id)` when the wallet accepted the batch.
8. Reads `getCallsStatus` every 2 seconds while the batch is not final, for up to 180 seconds.
9. Classifies the status. A payment that the wallet claims counts only when the receipt from your public client proves it, at or above `lowestPaymentBlock`.
10. After the proof, or after a final batch with no payment, reads the facts again and lists the steps that are still absent.

After the request, a failed node read never rejects. It answers `setup_state_unread` after the proof of the payment, and `unknown` in other cases.

### `Erc20AllowSubscriptionBatchOutcome` and `Erc20AllowSubscriptionBatchResult`

```ts theme={null}
type Erc20AllowSubscriptionBatchResult =
  | { kind: "completed"; block: bigint; payment: Erc20AllowSubscriptionConfirmedStep | null }
  | { kind: "steps_absent"; block: bigint; payment: Erc20AllowSubscriptionConfirmedStep | null;
      absentSteps: Exclude<Erc20AllowSubscriptionStep, "payment">[] }
  | { kind: "setup_state_unread"; payment: Erc20AllowSubscriptionConfirmedStep }
  | { kind: "pending"; batchId: string }
  | { kind: "nothing_landed"; batchId: string }
  | { kind: "unknown"; batchId: string }
  | { kind: "unknown_to_wallet"; batchId: string }
  | { kind: "unexpected_commitment"; commitment: OnChainDsl; payment: Erc20AllowSubscriptionConfirmedStep | null };

type Erc20AllowSubscriptionBatchOutcome =
  | Erc20AllowSubscriptionBatchResult
  | { kind: "batch_refused"; code: number | null }
  | { kind: "stopped_before_request"; reason: OwnerRequestStopReason }
  | { kind: "attestation_lapsed" };
```

`payment` is the payment that your node proves, or `null` when the batch held no payment.

| `kind` | Meaning | What to do |
| - | - | - |
| `completed` | A read at `block` shows every step. | Done. |
| `steps_absent` | The payment is confirmed, and `absentSteps` are still absent. | Run `setUpErc20AllowSubscription` with `paymentConfirmed: true`. |
| `setup_state_unread` | Your node proves `payment`, and the read of the other steps failed. | Read again later with `readErc20AllowSubscriptionBatchResult`. |
| `pending` | The batch is not final, or your node has no receipt yet for the claimed payment. | Read again later. |
| `nothing_landed` | The atomic batch failed completely (status 400 or 500). The chain is as before. | Offer a retry. |
| `unknown` | No rule gives a definite result. This never means "not paid". | Read again later, or scan for the transfer. |
| `unknown_to_wallet` | The wallet does not know the id (EIP-5792 code 5730). A wallet can lose a batch that it accepted. This never means "not paid". | Scan for the transfer. |
| `unexpected_commitment` | The chain holds a commitment that the plan does not expect. | Ask the payer. |
| `batch_refused` | The wallet refused the batch before it accepted it. Nothing was sent. `code` is the wallet error code, or `null` when the wallet client has no batch methods. | Use `setUpErc20AllowSubscription`. |
| `stopped_before_request` | The wallet was not asked. | See the reason. |
| `attestation_lapsed` | The attestation lapsed before the request. | Stage again. |

## `readErc20AllowSubscriptionBatchResult`

```ts theme={null}
readErc20AllowSubscriptionBatchResult(params: ReadErc20AllowSubscriptionBatchResultParams): Promise<Erc20AllowSubscriptionBatchResult>;

interface ReadErc20AllowSubscriptionBatchResultParams {
  payer: Hex;
  plan: Erc20AllowSubscriptionPlan;
  batchId: string;
  batchHoldsPayment: boolean;   // false when the payment was confirmed before the batch
  lowestPaymentBlock: bigint;
}
```

Reads the status of an earlier batch one time, with no prompt, and classifies it as `setUpErc20AllowSubscriptionInBatch` does. Use it after a page reload, with the id that you stored in `onRequested`. A read that takes more than 20 seconds, a failed read, and a wallet client with no `getCallsStatus` answer `unknown`. It applies the plan checks, and not the check of the staged text, because it sends nothing.

## `readWalletAtomicBatchSupport`

```ts theme={null}
readWalletAtomicBatchSupport(account: Hex): Promise<boolean>;
```

Answers `true` when `getCapabilities({ account, chainId })` reports an `atomic` capability with status `supported` or `ready`. A wallet client with no `getCapabilities`, a failed read, and any other answer give `false`. It never rejects. Use it to choose between the batch setup and the step setup.

```ts theme={null}
const outcome = (await anafi.readWalletAtomicBatchSupport(payer))
  ? await anafi.setUpErc20AllowSubscriptionInBatch({ payer, plan, paymentConfirmed: false, lowestPaymentBlock })
  : await anafi.setUpErc20AllowSubscription({ payer, plan, paymentConfirmed: false, lowestPaymentBlock });
```

## Subscription helpers

```ts theme={null}
interface Erc20AllowSubscriptionCall {
  step: Erc20AllowSubscriptionStep;
  to: Hex;
  data: Hex;
}

interface Erc20AllowSubscriptionChainFacts {
  allowance: bigint;
  cap: Erc20AllowCap | null;
  commitment: OnChainDsl | null;
}

function buildErc20AllowSubscriptionCalls(params: {
  plan: Erc20AllowSubscriptionPlan;
  dslRegistry: Hex;
  paymentConfirmed: boolean;
  chain: Erc20AllowSubscriptionChainFacts;
}): Erc20AllowSubscriptionCall[];

function isExpectedErc20AllowSubscriptionCommitment(plan: Erc20AllowSubscriptionPlan, commitment: Hex): boolean;

type Erc20AllowSubscriptionBatchStatusClass =
  | { kind: "pending" }
  | { kind: "payment_proven"; txHash: Hex; blockNumber: bigint; lastReceiptBlock: bigint }
  | { kind: "final_without_payment"; lastReceiptBlock: bigint | null }
  | { kind: "nothing_landed" }
  | { kind: "unknown" }
  | { kind: "unknown_to_wallet" };

function classifyErc20AllowSubscriptionBatchStatus(
  callsStatus: unknown,
  transfer: Erc20PaymentTransfer | null,
): Erc20AllowSubscriptionBatchStatusClass;

const ERC20_ALLOW_SUBSCRIPTION_ATTESTATION_MARGIN_SECONDS = 300;
```

`classifyErc20AllowSubscriptionBatchStatus` reads a status in the form of viem `getCallsStatus`. The first rule that fits decides:

1. A status code from 100 to 199 is `pending`.
2. A successful receipt that holds the `Transfer` event of `transfer` is `payment_proven`. This is the word of the wallet, not a proof.
3. Status 400 or 500 of an atomic batch is `nothing_landed`.
4. Any other status is `unknown`.

For a batch with no payment (`transfer` is `null`), a final code (200 to 299, or 400 to 699) is `final_without_payment`. A status with a malformed field is `unknown`. Only a status read gives `unknown_to_wallet`.

## Transfer helpers

```ts theme={null}
interface Erc20PaymentTransfer {
  token: Hex;
  from: Hex;
  to: Hex;
  amount: bigint;
}

interface TransactionLog {
  address: Hex;
  topics: readonly Hex[];
  data: Hex;
}

function logsHoldErc20Transfer(logs: readonly TransactionLog[], transfer: Erc20PaymentTransfer): boolean;
```

`logsHoldErc20Transfer` answers `true` when a log of `transfer.token` is `Transfer(from, to, value)` with 3 topics, the same sender and receiver, and a one-word `data` equal to `amount`. Addresses compare without regard to case.

## `sendPayReceiptEmail`

```ts theme={null}
sendPayReceiptEmail(params: PayReceiptEmailParams): Promise<PayReceiptEmailOutcome>;

type PayMode = "once" | "monthly";

interface PayReceiptEmailParams {
  email: string;   // sent as given
  txHash: Hex;     // the payment transaction
  payer: Hex;
  payee: Hex;
  token: Hex;
  amount: bigint;  // base units, above 0
  mode: PayMode;
}
```

Asks the Anafi API to check one payment on chain and mail one receipt for it. No prompt. It sends one request and does not retry. Route: `POST /api/pay/receipt_email`.

The request body is `payReceiptEmailRequestBody(params)`:

```json theme={null}
{
  "email": "ada@example.com",
  "txHash": "0x…",
  "payer": "0x…",
  "payee": "0x…",
  "token": "0x…",
  "amountRaw": "25000000",
  "mode": "once"
}
```

`payReceiptEmailRequestBody` throws `Error("pay receipt amount must be above 0")` for an amount of 0 or less, and an `Error` for an unknown `mode`.

### `PayReceiptEmailOutcome`

| `kind` | Meaning | What to do |
| - | - | - |
| `sent` | The mail server accepted the receipt. | Show "sent". |
| `already_requested` | A receipt for this transaction was sent, or a send runs now. No mail was sent for this request. | Show "already sent". |
| `invalid_email` | The address has no canonical form, or is not a bare mail address. | Ask for another address. |
| `token_not_accepted` | The token is not a fee token of this network, or it is the native coin. | No receipt is possible. |
| `payment_not_found` | The node knows no mined, successful transaction with this hash that holds `Transfer(payer, payee, amount)` of the token. | Wait, then ask again. |
| `payment_too_old` | The block of the payment is more than 1 hour old. | No receipt is possible. |
| `monthly_setup_not_found` | The mode is `monthly`, and the chain does not show the monthly setup of the payer: an ERC20Allow permission for the token with no block, a cap at or above the amount, and a committed document. | Finish the setup, then ask again. |
| `retry_after` | The receipt budget is full now. `seconds` is the wait. | Ask again after `seconds`. |
| `mail_not_configured` | This network sends no mail. | No receipt is possible. |
| `not_sent` | The mail server did not accept the receipt. | Ask again. |

`readPayReceiptEmailReply(value)` reads the reply `{ outcome }` and throws on any other shape or an unknown `kind`. A failed request throws `BackendRequestError`.

```ts theme={null}
const result = await anafi.sendPayReceiptEmail({
  email: "ada@example.com",
  txHash: outcome.txHash,
  payer,
  payee,
  token: usdc,
  amount: 25_000_000n,
  mode: "once",
});
if (result.kind === "retry_after") setTimeout(retry, result.seconds * 1000);
```


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