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

# Idempotency keys

> Retry a transaction send safely: while Portal remembers an idempotency key, it broadcasts that key at most once.

When a send times out or the connection drops, you can't tell whether the transaction reached the chain. Retrying might send it twice, and not retrying might lose it. Starting in `portal_flutter` `2.1.0`, you can attach an **idempotency key** to a send. Portal broadcasts a key at most once while it [remembers the key](#how-long-portal-remembers-a-key) (at least 24 hours), so a retry with the same key within that time cannot send the same transaction twice.

Idempotency keys are optional. Requests without one behave exactly as before.

## Supported requests

| Entry point | Supported on |
| - | - |
| `portal.sendTransaction(..., idempotencyKey: ...)` | EVM (`eip155`) chains |
| `portal.request(..., idempotencyKey: ...)` | `eth_sendTransaction`, `sol_signAndSendTransaction`, `sol_signAndConfirmTransaction` |
| `portal.sendAsset(..., idempotencyKey: ...)` | EVM (`eip155`) and Solana chains |

Portal enforces the key whether the transaction is signed on the device or through the Enclave MPC API ([`useEnclaveMpcApi`](./feature-flags)).

## Generate a key

```dart theme={null}
String generateIdempotencyKey()
```

`generateIdempotencyKey()` returns a lowercase UUID v4. Generate one key per operation, such as one transfer or one payment, and store it with the pending operation before you send. A retry, even one after the app restarts, can then reuse it.

You can also use your own key, for example an ID from your backend. The SDK trims surrounding whitespace, and the key must then follow these rules:

| Rule | Detail |
| - | - |
| Length | 1–255 characters |
| Allowed characters | `A-Z`, `a-z`, `0-9`, `-`, `.`, `_`, `~` |

A key that breaks these rules throws a `PortalException` with code `INVALID_IDEMPOTENCY_KEY` before the user is asked to approve the request, so nothing is signed or sent.

## Send a transaction with a key

Pass the key to `sendTransaction`:

```dart theme={null}
import 'package:portal_flutter/portal_flutter.dart';

final portal = Portal();

// One key per transfer. Store it with the pending transfer.
final idempotencyKey = generateIdempotencyKey();

final txHash = await portal.sendTransaction(
  chainId: 'eip155:11155111', // Ethereum Sepolia
  to: '0xDestinationAddress',
  value: '0x2386F26FC10000', // 0.01 ETH in wei (hex)
  idempotencyKey: idempotencyKey,
);

print('Transaction hash: $txHash');
```

Or pass it to `request` for `eth_sendTransaction`, `sol_signAndSendTransaction` or `sol_signAndConfirmTransaction`:

```dart theme={null}
final response = await portal.request(
  chainId: 'eip155:11155111',
  method: 'eth_sendTransaction',
  params: [
    {
      'from': '0xYourAddress',
      'to': '0xDestinationAddress',
      'value': '0x2386F26FC10000',
    },
  ],
  signatureApprovalMemo: 'Send ETH',
  idempotencyKey: idempotencyKey,
);

if (response.error != null) {
  // Not an idempotency rejection, so it's safe to retry with the same key
  print('Request failed: ${response.error}');
} else {
  print('Transaction hash: ${response.result}');
}
```

> [!NOTE]
>
> `request` returns most failures in `PortalProviderResponse.error`, but it **throws** a `PortalException` for the idempotency error codes on this page. Handle them the same way for `request`, `sendTransaction` and `sendAsset`.

## Retry with the same key

If a send fails and you don't know whether the transaction went out, for example after a timeout, send it again with the **same transaction and the same key**. One of two things happens:

* The first attempt never reached Portal, so Portal has no record of the key, and the retry sends the transaction.
* Portal already recorded the key, whether that attempt is still in progress, was broadcast or failed, and it rejects the retry with a `PortalException` instead of broadcasting again.

Reuse a key only for the identical request. If anything changes, such as the amount, the recipient, the chain or the method, generate a new key.

### Handle a rejection

When Portal rejects a request because of its key, the exception's `code` is one of the error IDs below. Two getters on `PortalException` identify a rejection:

| Getter | `true` when |
| - | - |
| `isIdempotencyRejection` | `code` is any of the idempotency error IDs below. |
| `isIdempotencyKeyReused` | `code` is `IDEMPOTENCY_KEY_REUSED`. |

Branch on `code` to decide what to do next. Each ID is also available as a constant on `PortalIdempotencyErrorId`:

| Error ID | Constant | What it means | What to do |
| - | - | - | - |
| `IDEMPOTENT_REQUEST_IN_PROGRESS` | `requestInProgress` | A request with this key is still being processed. | Wait, then retry with the same key. |
| `IDEMPOTENT_REQUEST_ALREADY_COMPLETED` | `requestAlreadyCompleted` | The transaction was broadcast. | Don't send it again. Look the transaction up on-chain. |
| `IDEMPOTENT_REQUEST_PREVIOUSLY_FAILED` | `requestPreviouslyFailed` | The earlier request failed, or its outcome is unknown. Portal returns this ID in both cases, so it doesn't confirm that the transaction was not broadcast. | Check the chain before sending again with a new key. |
| `IDEMPOTENT_REQUEST_UNEXPECTED_STATE` | `requestUnexpectedState` | Portal can't confirm the outcome of the earlier request. | Check the chain before sending again with a new key. |
| `IDEMPOTENT_TX_MISSING` | `txMissing` | Portal can't find the request recorded for this key. | Check the chain before sending again with a new key. |
| `IDEMPOTENCY_KEY_REUSED` | `keyReused` | The key was already used for a request with a different payload. This doesn't tell you the state of that earlier request. | Check the chain before sending again with a new key. |

```dart theme={null}
import 'package:portal_flutter/portal_flutter.dart';

try {
  final txHash = await portal.sendTransaction(
    chainId: 'eip155:11155111',
    to: '0xDestinationAddress',
    value: '0x2386F26FC10000',
    idempotencyKey: idempotencyKey, // The key stored with this transfer
  );

  print('✅ Transaction hash: $txHash');
} on PortalException catch (e) {
  if (!e.isIdempotencyRejection) {
    print('❌ Send failed: [${e.code}] ${e.message}');
  } else if (e.code == PortalIdempotencyErrorId.requestInProgress) {
    print('⏳ Still processing. Retry later with the same key.');
  } else if (e.code == PortalIdempotencyErrorId.requestAlreadyCompleted) {
    print('✅ Already broadcast. Look the transaction up instead of sending it again.');
  } else {
    print('⚠️ Outcome unconfirmed (${e.code}). Check the chain before sending again with a new key.');
  }
}
```

> [!WARNING]
>
> No rejection returns the original transaction hash. Before you send an operation again under a **new** key, check the chain or your transaction history to confirm the first attempt didn't land. Portal treats a new key as a new transaction.

> [!NOTE]
>
> Match rejections on `code`, not on the error message. The operation's own code, such as `SEND_TRANSACTION_ERROR`, is at the start of `details`.

## Retry `sendAsset`

Pass the key to `sendAsset`:

```dart theme={null}
import 'package:portal_flutter/portal_flutter.dart';

// One key per transfer. Store it with the pending transfer.
final idempotencyKey = generateIdempotencyKey();

try {
  final txHash = await portal.sendAsset(
    chainId: 'eip155:11155111',
    to: '0xDestinationAddress',
    amount: '0.0001',
    token: 'NATIVE',
    signatureApprovalMemo: 'Send ETH',
    idempotencyKey: idempotencyKey,
  );

  print('✅ Transaction hash: $txHash');
} on PortalException catch (e) {
  if (e.isIdempotencyRejection) {
    print('Portal already handled this key: ${e.code}');
  } else {
    print('❌ Send failed: [${e.code}] ${e.message}');
  }
}
```

`sendAsset` builds the transaction again on every call, and Portal compares a retry with the request it first received under the key before it checks that request's status:

* **EVM:** the rebuilt transaction normally matches the first one, because Portal fills in the nonce and gas when it signs. A retry gets the status of the first request, as described in [Handle a rejection](#handle-a-rejection).
* **Solana:** each build carries a new recent blockhash, so a retry with the same key is normally rejected with `IDEMPOTENCY_KEY_REUSED`, whatever happened to the first attempt.

Either way, while Portal remembers the key, the transfer is never broadcast twice under it. Before you retry with a new key, wait until the first transfer can no longer land, then check the chain:

* **Solana:** wait until the first transfer is confirmed or its recent blockhash has expired, about 60–90 seconds after the transaction was built.
* **EVM:** wait until the first transfer is confirmed or the account nonce has moved past it.

> [!TIP]
>
> For the most predictable retries, especially on Solana, build the transaction once with [`buildSolanaTransaction`](../reference/buildsolanatransaction) or [`buildEip155Transaction`](../reference/buildeip155transaction) and send it with `portal.request(...)` as shown in [Send a transaction with a key](#send-a-transaction-with-a-key). Every retry then gets the status of the first request, including `IDEMPOTENT_REQUEST_IN_PROGRESS`.

## Requests that don't take a key

| Request | With a key |
| - | - |
| `eth_sendRawTransaction`, `sol_sendTransaction` | Throws a `PortalException` with code `IDEMPOTENCY_KEY_UNSUPPORTED` before anything is sent. These methods broadcast a transaction that is already signed through a plain RPC call, which Portal can't deduplicate. |
| `sendAsset` on a Bitcoin chain | Throws a `PortalException` with code `IDEMPOTENCY_KEY_UNSUPPORTED` before the transaction is built. |
| Any other method, such as `eth_signTransaction` or `personal_sign` | The SDK checks the key, then ignores it and logs a warning when the [log level](https://docs.portalhq.io/sdks/flutter/guide/configure-log-level.md) is `PortalLogLevel.warn` or more verbose. |

## How long Portal remembers a key

Portal remembers a key for at least 24 hours after the request was last updated, then removes it. Once the key is removed, the same key is treated as a new request. Because the exact removal time isn't fixed, check the chain before you retry an operation that is older than 24 hours, whatever key you use.

## Presignatures

If you enable presignatures (`usePresignatures` in `PortalFeatureFlags`) and a presignature attempt fails after reaching Portal, the SDK's fallback sign reuses the key. Portal can reject it, for example with `IDEMPOTENT_REQUEST_IN_PROGRESS` or `IDEMPOTENT_REQUEST_PREVIOUSLY_FAILED`, where a request without a key would have been signed. Handle it like any other [rejection](#handle-a-rejection).

## Next Steps

* Learn about [signing transactions](https://docs.portalhq.io/sdks/flutter/guide/sign-a-transaction.md)
* Read [Send tokens](https://docs.portalhq.io/sdks/flutter/guide/send-tokens.md) for the full `sendAsset` flow
* See the [`generateIdempotencyKey` reference](../reference/generateidempotencykey)
* See [Idempotency keys](https://docs.portalhq.io/resources/idempotency-keys.md) for the Enclave MPC API


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