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

# Bank payouts

> Pay a bank account in euros from a Safe with the off_ramp action, on Polygon Amoy with the Monerium sandbox.

After this page, you know what a Safe needs before a rule can pay a bank account, which steps are on chain, which go through the Anafi API, and how to follow the orders.

The `off_ramp` action redeems EURe for a SEPA transfer through Monerium: Monerium burns the EURe from the Safe and pays the same amount in euros to the bank account that the rule names.

> [!WARNING]
>
> Bank payouts work only on `polygon-amoy` today, with the Monerium sandbox. The engine refuses `off_ramp` on every other network, and for an account that is not a Safe. The `/api/monerium/*` routes are served only on `https://api.polygon-amoy.ana.fi`.

## Preconditions

| Condition | Why |
| - | - |
| A Safe account that runs Safe 1.5.0 | The off-ramp handler validates owner signatures with a function that only Safe 1.5.0 has. The Safe that the SDK provisions runs 1.5.0. |
| The Safe has no fallback handler, the off-ramp handler, or the standard Safe 1.5.0 `CompatibilityFallbackHandler` | A Safe has one fallback handler. The setup replaces the one that is there. Do not replace a custom handler. |
| EURe in the Safe | The order burns EURe. On `polygon-amoy`, EURe is `0xeD5D0B6C5BEFfDd607639094397C223536B0Bae7`. |
| The off-ramp handler address | `AnafiOffRampFallbackHandler` on `polygon-amoy`: `0x5F5dAF4084529D60a9144e002e67eC2DF4D35f7F`. See [Off-ramp handler](https://docs.ana.fi/contracts/off-ramp-handler.md). |

## Overview

```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
    W->>C: Safe transaction: setFallbackHandler(handler), then setOffRampPolicy(terms)
    W-->>A: EIP-712 SafeMessage signature over the link sentence hash
    A->>API: POST /api/monerium/connect (browser, with credentials)
    API->>C: Safe.isValidSignature (ERC-1271)
    API-->>A: authorizeUrl
    Note over A,API: The owner signs in at Monerium, Monerium returns to the Anafi API callback
    A->>API: GET /api/monerium/status/{safe}
    W->>C: Commit a document with an off_ramp action (stageDsl, commitStagedDsl)
    E->>E: The rule fires, the engine signs an order
    Note over C: Monerium burns EURe from the Safe. The handler checks the order against the policy.
    A->>API: GET /api/wallets/{safe}/off-ramp/orders
```

## Steps

**1. Install the handler and write the policy**

One Safe transaction with two calls to the Safe itself, in this order:

1. `Safe.setFallbackHandler(handler)`;
2. `Safe.setOffRampPolicy(terms)`. The Safe has no such function, so it forwards the call to its new fallback handler, which stores the policy for this Safe.

`terms` is `OffRampPolicyTerms`:

| Field | Type | Meaning |
| - | - | - |
| `authority` | `address` | The `AnafiRegistry` whose `engineSigKey()` may sign an order. The zero address clears the policy. |
| `perOrderCapMinor` | `uint256` | The largest order, in euro cents. |
| `expiry` | `uint64` | The Unix second from which the policy accepts nothing. `0` accepts nothing. |
| `ibanAllowlist` | `string[]` | The IBANs that an order may pay, at most 16. Empty accepts any IBAN. |

Send the batch with `executeSafeOwnerCalls({ safe, eoa, legs })`. Each leg is `{ target: safe, calldata }`. Anafi relays these two calls when it relays owner operations of the Safe; else the owner sends the transaction. See [Safe account](https://docs.ana.fi/flows/safe-account.md) for the prompts.

Read the policy with `offRampPolicyOf(safe)` on the handler. It returns the IBANs as `keccak256` hashes.

**2. Link the Safe to Monerium**

1. The owner signs the EIP-712 `SafeMessage` of the Safe (domain `{ chainId, verifyingContract: safe }`, message `hashMessage("I hereby declare that I am the address owner.")`). This is a typed-data prompt. Nothing goes on chain.
2. The browser sends `POST /api/monerium/connect` with `{ aaAddress, addressLinkSignature }` and credentials. The Anafi API asks the Safe, through ERC-1271, whether it accepts the signature. The answer is `{ authorizeUrl }`, and a cookie that binds the flow to this browser.
3. The browser opens `authorizeUrl`. Monerium returns the browser to the callback of the Anafi API, which redirects to a return address that the deployment sets, with `?monerium=connected` or `?monerium=error&reason=...`.

| `POST /api/monerium/connect` | Meaning |
| - | - |
| `400` | The signature is empty. |
| `403` | The Safe does not accept the signature: not signed by its owners, or its fallback handler is not the off-ramp handler. |
| `503` | The Anafi API could not ask the Safe. |

Today, the Anafi API hosts answer CORS only for `https://app.ana.fi`, and the flow is bound to the browser that started it. Do the link step in the Anafi dapp.

**3. Read the link status**

`GET /api/monerium/status/{safe}` needs no sign-in. It returns:

| Field | Meaning |
| - | - |
| `connected` | Whether a Monerium link exists for the Safe. |
| `addressLinkProofValid` | Whether the Safe accepts the stored link signature now. `null` with no link, or when the chain read failed. |
| `addressLinkState` | `unlinked`, `linked` or `pending_verification`, when present. |
| `maskedIban` | The IBAN that mints EURe to the Safe, masked, once issued. |
| `lastErrorReason` | `address_link_refused` or `token_refresh_refused`. Connect again. |
| `offRampHandler.state` | `installed`, `not_installed` (with `current`), `replaced` (the Safe has a policy, and another handler now, so no order validates), or `unread`. |
| `offRampPolicy.state` | `set` (with `authority`, `perOrderCapMinor`, `expiry`, `ibanAllowlistLen`), `none`, or `unread`. |

To read the full IBAN and BIC of the Safe, an owner signs (sign-in message prompt, `personal_sign`) the text `Anafi: show the bank account details of <Safe checksum address> on chain <chainId>.` and a second line `Valid until: <unix seconds>`, then you send `POST /api/monerium/bank-details` with `{ aaAddress, validUntil, signature }`. `validUntil` must lie in the next 10 minutes. Answers: `{ iban, bic }`, `400` (bad `validUntil` or signature), `403` (the signer is not an owner), `404` (no link), `503`.

**4. Commit a rule with an off\_ramp action**

```yaml theme={null}
global:
  fees_method: { type: fixed_token, token: USDC }
rules:
  rent_to_bank:
    trigger:
      type: calendar
      day_of_month: [1]
      time_of_day: "09:00"
      timezone: "Europe/Berlin"
    actions:
      - type: off_ramp
        provider: monerium
        value: "200 EURe"
        to:
          iban: "DE89370400440532013000"
          first_name: "Erika"
          last_name: "Mustermann"
          country: "DE"
        memo: "Rent"
```

`value` is an amount of EURe in whole cents, or a share of an EURe trigger value. `to` names a person (`first_name` and `last_name`) or a company (`company_name`). `memo` has 5 to 140 characters. `global.iban_allowlist` can bound the IBANs of the document. See [Actions](https://docs.ana.fi/rules/actions.md).

The SDK builders emit this action for a payee with a `bank` field (`buildRoutingDsl`, `buildStandingOrderDsl`). Stage and commit as for any Safe document.

## When the rule fires

The engine signs an order for the Safe. Monerium asks the Safe, through ERC-1271, whether it accepts the order. The off-ramp handler answers against the policy of the Safe. See [Off-ramp handler](https://docs.ana.fi/contracts/off-ramp-handler.md) for each check.

A Safe that installs another fallback handler stops each order until it installs the off-ramp handler again.

### Follow the orders

`GET /api/wallets/{safe}/off-ramp/orders` needs no sign-in. It returns the orders newest first. Each row has `seq`, `orderId`, `status`, `amount`, `currency`, `maskedIban`, `providerOrderId`, `providerState`, `lastError`, `firedAt`, `signedAt` and `updatedAt`.

| `status` | Meaning |
| - | - |
| `pending` | The order waits to go to Monerium. |
| `placing` | The order is on its way to Monerium. |
| `placed` | Monerium took the order. `providerOrderId` and `providerState` come from Monerium. |
| `failed` | The order did not go through. `lastError` says why. |
| `expired` | The order was not placed in time. |

The Anafi fee of a bank payout shows in the activity feed as a row with `kind: "off_ramp_fee"`. See [Execution](https://docs.ana.fi/flows/execution.md).

## Switch it off

| Way | Call |
| - | - |
| Clear the policy | `Safe.setOffRampPolicy` with `authority` set to the zero address |
| Remove the handler | `Safe.setFallbackHandler` with another handler or the zero address |
| Stop the rule | Commit a document without the `off_ramp` action |
| Remove the permission | `disableSafeModule`. See [Update, pause, revoke](https://docs.ana.fi/flows/update-pause-revoke.md). |

## Example

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

const SAFE_SETUP_ABI = parseAbi([
  "function setFallbackHandler(address handler)",
  "struct OffRampPolicyTerms { address authority; uint256 perOrderCapMinor; uint64 expiry; string[] ibanAllowlist; }",
  "function setOffRampPolicy(OffRampPolicyTerms terms)",
]);

export async function enableOffRamp(
  anafi: AnafiClient,
  safe: Hex,
  eoa: Hex,
  handler: Hex,
  anafiRegistry: Hex,
  ibans: string[],
) {
  const legs: SafeBatchLeg[] = [
    {
      target: safe,
      calldata: encodeFunctionData({ abi: SAFE_SETUP_ABI, functionName: "setFallbackHandler", args: [handler] }),
    },
    {
      target: safe,
      calldata: encodeFunctionData({
        abi: SAFE_SETUP_ABI,
        functionName: "setOffRampPolicy",
        args: [
          {
            authority: anafiRegistry,
            perOrderCapMinor: 50_000n, // 500.00 EUR
            expiry: BigInt(Math.floor(Date.now() / 1000) + 365 * 86_400),
            ibanAllowlist: ibans,
          },
        ],
      }),
    },
  ];
  const result = await anafi.executeSafeOwnerCalls({ safe, eoa, legs });
  if (!result.success) throw new Error(`the Safe refused ${result.txHash}`);
  return result;
}
```


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