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

```kotlin theme={null}
// io.portalhq.android.utils
fun 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 `PortalException.Provider.InvalidIdempotencyKey` 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:

```kotlin theme={null}
import io.portalhq.android.api.data.buildtransaction.BuildTransactionParam
import io.portalhq.android.provider.data.PortalRequestMethod
import io.portalhq.android.provider.data.RequestOptions
import io.portalhq.android.utils.generateIdempotencyKey

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

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

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

val result = portal.request(
    chainId = chainId,
    method = PortalRequestMethod.eth_sendTransaction,
    params = listOf(txDetails.transaction),
    options = RequestOptions(
        signatureApprovalMemo = "Send USDC",
        idempotencyKey = idempotencyKey,
    ),
)

println("✅ Transaction hash: ${result.result}")
```

On Solana, build the transaction with `portal.api.buildSolanaTransaction(chainId, params)` and send it with `PortalRequestMethod.sol_signAndSendTransaction` or `PortalRequestMethod.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 `PortalException.Mpc.MpcResultError` 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

Two extension functions on `PortalError` (in `io.portalhq.android.utils.errors`) identify an idempotency rejection. Call them on the exception's `error`:

| Function | `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` (in `io.portalhq.android.utils`):

| Error ID | What it means | What to do |
| - | - | - |
| `IDEMPOTENT_REQUEST_IN_PROGRESS` | A request with this key is still being processed. | Wait, then retry with the same key. |
| `IDEMPOTENT_REQUEST_ALREADY_COMPLETED` | The transaction was broadcast. | Don't send it again. Look the transaction up on-chain. |
| `IDEMPOTENT_REQUEST_PREVIOUSLY_FAILED` | 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` | Portal can't confirm the outcome of the earlier request. | Check the chain before sending again with a new key. |
| `IDEMPOTENT_TX_MISSING` | Portal can't find the request recorded for this key. | Check the chain before sending again with a new key. |
| `IDEMPOTENCY_KEY_REUSED` | 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. |

```kotlin theme={null}
import io.portalhq.android.exceptions.PortalException
import io.portalhq.android.provider.data.PortalRequestMethod
import io.portalhq.android.provider.data.RequestOptions
import io.portalhq.android.utils.PortalIdempotencyErrorId
import io.portalhq.android.utils.errors.isIdempotencyRejection
import java.io.IOException

try {
    val result = portal.request(
        chainId = chainId,
        method = PortalRequestMethod.eth_sendTransaction,
        params = listOf(txDetails.transaction),
        options = RequestOptions(idempotencyKey = idempotencyKey), // The key stored with this transfer
    )

    println("✅ Transaction hash: ${result.result}")
} catch (e: PortalException.Mpc.MpcResultError) {
    when {
        !e.error.isIdempotencyRejection() ->
            println("❌ Signing failed: ${e.message}")
        e.id == PortalIdempotencyErrorId.IDEMPOTENT_REQUEST_IN_PROGRESS ->
            println("⏳ Still processing. Retry later with the same key.")
        e.id == PortalIdempotencyErrorId.IDEMPOTENT_REQUEST_ALREADY_COMPLETED ->
            println("✅ Already broadcast. Look the transaction up instead of sending it again.")
        else ->
            println("⚠️ Outcome unconfirmed (${e.id}). Check the chain before sending again with a new key.")
    }
} catch (e: IOException) {
    // No answer about the broadcast, for example a timeout. Retrying with the same key is safe.
    println("❌ Send failed: ${e.message}")
}
```

<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`. `sendAsset` returns a `Result`, so a rejection arrives as its failure:

```kotlin theme={null}
import io.portalhq.android.data.SendAssetParams
import io.portalhq.android.exceptions.PortalException
import io.portalhq.android.utils.errors.isIdempotencyRejection
import io.portalhq.android.utils.generateIdempotencyKey

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

portal.sendAsset(
    chainId = "eip155:11155111",
    params = SendAssetParams(
        to = "0xDestinationAddress",
        amount = "0.0001",
        token = "NATIVE",
        signatureApprovalMemo = "Send ETH",
        idempotencyKey = idempotencyKey,
    ),
).onSuccess { response ->
    println("✅ Transaction hash: ${response.data?.txHash}")
}.onFailure { e ->
    if (e is PortalException.Mpc.MpcResultError && e.error.isIdempotencyRejection()) {
        println("Portal already handled this key: ${e.id}")
    } else {
        println("❌ Send failed: ${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 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 `PortalException.Provider.IdempotencyKeyUnsupported` 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 | Fails with `PortalException.Provider.IdempotencyKeyUnsupported` before the transaction is built. |
| Any other method, such as `eth_signTransaction` or `personal_sign` | The SDK ignores the key and logs a warning when the [log level](./configure-log-level) 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 `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).

## Next Steps

* Learn about [signing transactions](./sign-a-transaction)
* Read [Send tokens](./send-tokens) for the full `sendAsset` flow
* Review [Error handling](./error-handling) for the `PortalException` hierarchy
* 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.