> ## 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 `8.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 | Where to pass the key | Supported on |
| - | - | - |
| `portal.request(chainId:method:params:options:)` | `RequestOptions(idempotencyKey:)` | `eth_sendTransaction`, `sol_signAndSendTransaction`, `sol_signAndConfirmTransaction` |
| `portal.sendAsset(chainId:params:)` | `SendAssetParams(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

```swift theme={null}
public func generateIdempotencyKey() -> String
```

`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 `PortalIdempotencyError.invalidKey` before the user is asked to approve the request, so nothing is signed or sent.

## Send a transaction with a key

Build the transaction once, then send it with the key:

```swift theme={null}
import PortalSwift

let chainId = "eip155:11155111" // Ethereum Sepolia

// Build the transaction once. A retry sends this same transaction.
let txDetails = try await portal.buildEip155Transaction(
  chainId: chainId,
  params: BuildTransactionParam(
    to: "0xDestinationAddress",
    token: "USDC",
    amount: "1"
  )
)

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

let response = try await portal.request(
  chainId: chainId,
  method: .eth_sendTransaction,
  params: [txDetails.transaction],
  options: RequestOptions(
    signatureApprovalMemo: "Send USDC",
    idempotencyKey: idempotencyKey
  )
)

if let txHash = response.result as? String {
  print("✅ Transaction hash: \(txHash)")
}
```

On Solana, build the transaction with `portal.buildSolanaTransaction(chainId:params:)` and send it with `.sol_signAndSendTransaction` or `.sol_signAndConfirmTransaction` the same way.

## Retry with the same key

If a send fails and you don't know whether the transaction went out, for example after a timeout, call `portal.request(...)` 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 `PortalMpcError` 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

`PortalMpcError` has two helpers for idempotency rejections:

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

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

| Error ID | `PortalIdempotencyErrorId` | 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. |

```swift theme={null}
import PortalSwift

do {
  let response = try await portal.request(
    chainId: chainId,
    method: .eth_sendTransaction,
    params: [txDetails.transaction],
    options: RequestOptions(idempotencyKey: idempotencyKey) // The key stored with this transfer
  )

  if let txHash = response.result as? String {
    print("✅ Transaction hash: \(txHash)")
  }
} catch let error as PortalMpcError where error.isIdempotencyRejection {
  switch error.id {
  case PortalIdempotencyErrorId.requestInProgress:
    print("⏳ Still processing. Retry later with the same key.")
  case PortalIdempotencyErrorId.requestAlreadyCompleted:
    print("✅ Already broadcast. Look the transaction up instead of sending it again.")
  default:
    print("⚠️ Outcome unconfirmed (\(error.id ?? "unknown")). Check the chain before sending again with a new key.")
  }
} catch {
  // No answer about the broadcast, for example a timeout. Retrying with the same key is safe.
  print("❌ Send failed: \(error)")
}
```

<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.
</Warning>

<Note>
  Match rejections on `id`, not on the error message or code.
</Note>

## Retry `sendAsset`

Pass the key in `SendAssetParams`:

```swift theme={null}
import PortalSwift

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

let params = SendAssetParams(
  to: "0xDestinationAddress",
  amount: "0.0001",
  token: "NATIVE",
  signatureApprovalMemo: "Send ETH",
  idempotencyKey: idempotencyKey
)

let response = try await portal.sendAsset(chainId: "eip155:11155111", params: params)

print("✅ Transaction hash: \(response.txHash)")
```

`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 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`.
</Tip>

## Requests that don't take a key

| Request | With a key |
| - | - |
| `eth_sendRawTransaction`, `sol_sendTransaction` | Throws `PortalIdempotencyError.unsupportedTarget` 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 `PortalIdempotencyError.unsupportedTarget` before the transaction is built. |
| Any other method, such as `eth_signTransaction` or `personal_sign` | The SDK ignores the key and logs a warning. |

## 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 `FeatureFlags`) 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).

## Custom signers

If you pass your own `PortalSignerProtocol` signer to `PortalProvider`, implement the overload that takes the key so your requests are protected:

```swift theme={null}
func sign(
  _ chainId: String,
  withPayload: PortalSignRequest,
  andRpcUrl: String,
  usingBlockchain: PortalBlockchain,
  signatureApprovalMemo: String?,
  sponsorGas: Bool?,
  reqId: String?,
  idempotencyKey: String?,
  token: String
) async throws -> String
```

`idempotencyKey` arrives trimmed and validated, and is non-`nil` only for `eth_sendTransaction`, `sol_signAndSendTransaction` and `sol_signAndConfirmTransaction`. Existing signers keep compiling without this overload, but the SDK drops the key for them and logs a warning.

## Next Steps

* Review the [generateIdempotencyKey reference](../reference/generateidempotencykey)
* Learn about [signing transactions](./sign-a-transaction)
* Read [Send tokens](./send-tokens) for the full `sendAsset` flow
* See [Idempotency keys](/resources/idempotency-keys) for the Enclave MPC API


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