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

# Trade perps with Yield.xyz

> Learn how to fund a trading account, open and manage leveraged perpetual-futures positions, and sign and submit the resulting actions with the Android SDK and the Yield.xyz integration.

Portal's Android SDK lets your users trade perpetual futures on venues such as Hyperliquid through the `portal.perps.yieldxyz` API. This guide covers discovering venues and markets, funding a trading account, opening and managing leveraged positions, and signing, submitting and tracking each action with the Portal wallet.

Perps requires Portal Android SDK `11.0.0` or later.

## Overview

With `portal.perps.yieldxyz` you can:

* **Discover** the trading venues (providers) and their markets, with mark and oracle prices, funding rates, leverage ranges, fees and price candles
* **Fund** a trading account and complete any one-time venue approvals
* **Open**, **manage** and **close** leveraged long or short positions, and **withdraw** collateral
* **Execute** an action in one call: the SDK signs each transaction with the Portal wallet in the format it requires (EIP-712 typed data or an on-chain transaction), submits it to Yield.xyz and tracks the action to a final status
* **Track** positions, orders, account balances, past actions and venue events

The [Yield.xyz Perps integration page](https://docs.portalhq.io/integrations/Yield/yield-xyz-perps.md#how-perpetual-futures-trading-works) explains how perpetual-futures trading works. Venues are identified by an opaque `providerId` (for example `hyperliquid`); real chains, where they appear, use [CAIP-2](https://docs.portalhq.io/resources/chain-id-formatting.md) (`eip155:42161` for Arbitrum One).

Every method is a `suspend` function that returns a `Result`. Except for `executeAction` and `signAndSubmitAction`, the value is the Portal API response, such as `YieldXyzPerpsGetProvidersResponse`, whose `data` holds the result; those two return a `YieldXyzPerpsExecutionResult`. A failure of the other methods carries the error unchanged; the two execution methods fail mostly with `YieldXyzPerpsExecutionException` (see [Handling errors](#handling-errors) for the other failures). Cancelling the calling coroutine is not returned as a failure: the method throws `CancellationException`. The examples unwrap each `Result` with `getOrThrow()` for brevity; in your app, handle the failure with `onFailure` or `fold`:

```kotlin theme={null}
portal.perps.yieldxyz.getProviders().fold(
    onSuccess = { response -> println(response.data.map { it.id }) },
    onFailure = { error -> println("getProviders failed: ${YieldXyzPerpsApiError.from(error)?.id ?: error.message}") },
)
```

> [!NOTE]
>
> This guide uses **Hyperliquid**, the launch venue, as the example. A venue's supported actions and the `args` each action takes come from `getProviders()` (`supportedActions` and `argumentSchemas`), and how each transaction is signed follows the `signingFormat` Yield.xyz returns on it, not the venue.

## Prerequisites

Before using perps operations, ensure you have:

* A properly initialized Portal client (see [Getting started](https://docs.portalhq.io/sdks/android/guide/getting-started.md))
* An active wallet with collateral (USDC) and **gas** on the funding chain (see [Create a wallet](https://docs.portalhq.io/sdks/android/guide/create-a-wallet.md))
* Yield.xyz integration enabled in your Portal Dashboard (see [Yield.xyz Perps](https://docs.portalhq.io/integrations/Yield/yield-xyz-perps.md))
* An `rpcConfig` entry for Arbitrum One (`eip155:42161`), the default `signingChainId` that EIP-712 signing requests are routed through, and for every chain an on-chain leg runs on. When you don't pass `rpcConfig`, Portal's default `rpcConfig` covers 11 chains, Arbitrum One included. An `rpcConfig` you pass replaces the default entirely, so add `eip155:42161` to it (see [Initializing Portal](https://docs.portalhq.io/sdks/android/guide/getting-started.md#initializing-portal)).

> [!WARNING]
>
> **There is no testnet for perps.** The Yield.xyz Perps API is production-only: every action is real money on mainnet. Perpetual futures are high-risk: leverage amplifies losses, and a position can be liquidated, losing its entire margin, within minutes.

> [!WARNING]
>
> **Perps require a Portal client *without* [account abstraction](https://docs.portalhq.io/resources/account-abstraction.md).** Hyperliquid verifies every action by recovering the signer from an EIP-712 signature, so funds deposited from a smart-contract wallet can be neither traded nor withdrawn. The Portal API rejects `createAction` and `submitTransaction` from an account abstraction enabled client with `INTEGRATION_REQUIRES_EOA_CLIENT`.

The examples in this guide use a `portal` instance. The request and response types are in `io.portalhq.android.api.data.yieldxyzperps`; the execution options, progress events, results and errors are in `io.portalhq.android.perps`.

```kotlin theme={null}
import io.portalhq.android.Portal
import io.portalhq.android.api.data.yieldxyzperps.*
import io.portalhq.android.perps.*

// Without rpcConfig, Portal's default rpcConfig covers Arbitrum One (eip155:42161).
val portal = Portal(apiKey = "YOUR_CLIENT_API_KEY_OR_CLIENT_SESSION_TOKEN")
```

Every account request (`createAction`, `getPositions`, `getOrders`, `getBalances`, `getActions`, `getActivity`, `getEvents`) takes an optional `address` in its parameters that defaults to the Portal wallet's EVM address; when there is no wallet address to default to, the request fails with `YieldXyzPerpsException.NoAddress` before it is sent. A custom `address` is for the read methods: `signAndSubmitAction` signs only transactions built for the Portal wallet's address, so an action created for another address fails with `SIGNER_ADDRESS_MISMATCH`.

## Discovering venues

`getProviders()` lists the trading venues, the actions each supports and the JSON schema of each action's `args`. `getProvider(providerId)` returns one venue.

```kotlin theme={null}
val providers = portal.perps.yieldxyz.getProviders().getOrThrow().data

for (provider in providers) {
    println("${provider.id} ${provider.name} ${provider.supportedActions}") // e.g. hyperliquid Hyperliquid [open, close, ...]
}

val hyperliquid = portal.perps.yieldxyz.getProvider("hyperliquid").getOrThrow().data
println(hyperliquid.argumentSchemas["open"] ?: "none") // the arguments `open` accepts on this venue
```

Use the `providerId` values `getProviders()` returns rather than a fixed list, and treat `argumentSchemas` (a Gson `JsonObject`, keyed by action type) as the source of truth for the `args` each action needs on a venue.

## Discovering markets

`getMarkets(params)` lists the tradable markets, `getMarket(marketId)` returns one by id, and `getMarketCandles(marketId, params)` returns price candles for a chart.

```kotlin theme={null}
val page = portal.perps.yieldxyz.getMarkets(
    YieldXyzPerpsGetMarketsParams(
        limit = 10,
        providerId = "hyperliquid",
        sortBy = YieldXyzPerpsMarketSortKey.VOLUME_24H,
        order = YieldXyzPerpsSortOrder.DESC,
    ),
).getOrThrow().data

for (market in page.items) {
    println("${market.id} ${market.markPrice} ${market.leverageRange} ${market.supportedMarginModes}")
}

val market = portal.perps.yieldxyz.getMarket("hyperliquid-eth-usdc").getOrThrow().data

val now = System.currentTimeMillis() // unix milliseconds
val candles = portal.perps.yieldxyz.getMarketCandles(
    marketId = market.id,
    params = YieldXyzPerpsGetMarketCandlesParams(
        interval = YieldXyzPerpsCandleInterval.ONE_HOUR,
        from = now - 24 * 60 * 60 * 1000L,
    ),
).getOrThrow().data
println(candles.candles.size)
```

`YieldXyzPerpsGetMarketsParams` takes:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `offset` | `Int?` | No | Pagination offset. |
| `limit` | `Int?` | No | Page size, from `1` to `100`. |
| `providerId` | `String?` | No | Only markets of this venue. |
| `sortBy` | `String?` | No | Sort key. Known values are in `YieldXyzPerpsMarketSortKey`: `VOLUME_24H`, `MARK_PRICE` and `PRICE_CHANGE_PERCENT_24H`. |
| `order` | `YieldXyzPerpsSortOrder?` | No | `ASC` or `DESC`. |

`getMarkets()` without arguments returns the first page of markets across all venues; page through the rest with `offset` and `limit`, and read `total`. Each market carries `baseAsset` and `quoteAsset`, `leverageRange` (`[min, max]`), `supportedMarginModes`, `markPrice`, `oraclePrice`, `fundingRate` with `fundingRateIntervalHours`, `makerFee` and `takerFee`, `openInterest` and `minSize`. Treat market ids as opaque values returned by `getMarkets`; do not build them yourself. The examples use `hyperliquid-eth-usdc` for illustration; use an `id` that `getMarkets` returned. `YieldXyzPerpsGetMarketCandlesParams` requires an `interval` (known values in `YieldXyzPerpsCandleInterval`: `ONE_MINUTE`, `FIVE_MINUTES`, `FIFTEEN_MINUTES`, `ONE_HOUR`, `FOUR_HOURS` and `ONE_DAY`) and a `from` timestamp in unix milliseconds, with an optional `to`.

## Funding a trading account and approving the venue

A perps venue holds collateral in a **trading account**, separate from the wallet's on-chain balance. Before a user can open a position, fund that account and complete any one-time approvals the venue requires.

Like every perps action, funding takes two calls: `createAction(params)` builds the action with its unsigned transactions, and `signAndSubmitAction(action)` signs, submits and tracks it (see [Signing and execution](#signing-and-execution)).

```kotlin theme={null}
val fund = portal.perps.yieldxyz.createAction(
    YieldXyzPerpsCreateActionParams(
        providerId = "hyperliquid",
        action = YieldXyzPerpsActionType.FUND,
        args = YieldXyzPerpsActionArgs(
            amount = "10", // in source-token units: 10 USDC
            fromToken = YieldXyzPerpsTokenIdentifier(
                network = "eip155:42161",
                address = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", // USDC on Arbitrum One
            ),
            fundingMethod = YieldXyzPerpsFundingMethod.BRIDGE2,
        ),
    ),
).getOrThrow().data

portal.perps.yieldxyz.signAndSubmitAction(fund).getOrThrow()
```

> [!WARNING]
>
> `bridge2` deposits below 5 USDC are not credited, and the funds are lost. USDC on Arbitrum One funds through `bridge2`, so check the amount before you build any `fund` action from it, whether you set `fundingMethod = YieldXyzPerpsFundingMethod.BRIDGE2` or leave `fundingMethod` out. The SDK does not check the amount.

`fund` returns on-chain `EVM_TRANSACTION` legs on the source chain (for example a USDC approval and the transfer), so the wallet needs gas there. `args.amount` is in units of the source token, not USD: from native ETH (`fromToken` without `address`) the same `"10"` means 10 ETH. `fundingMethod` selects the route: `BRIDGE2` (`bridge2`) bridges USDC from Arbitrum One, and `LIFI` (`lifi`) routes from other EVM chains and tokens. See [Funding sources and limits](https://docs.portalhq.io/integrations/Yield/yield-xyz-perps.md#funding-sources-and-limits) for the venue's limits.

> [!NOTE]
>
> A `fund` action reaches `SUCCESS` when the source-chain transaction confirms, **not** when the collateral lands on the venue. Poll `getBalances(params)` until `availableBalance` reflects the deposit before you show a funded state.

```kotlin theme={null}
val balance = portal.perps.yieldxyz.getBalances(
    YieldXyzPerpsBalancesParams(providerId = "hyperliquid"),
).getOrThrow().data
println("${balance.accountValue} ${balance.availableBalance}")
```

Build approvals the same way. `supportedActions` lists every action a venue supports, not only the approvals it requires, so check the venue's requirements before you add an approval step. Hyperliquid, for example, may require `approveBuilderFee`, and can place orders through an **agent wallet** the user authorizes once with `approveAgent`, which takes the agent's `agentAddress` and an `agentName`. An approved agent can trade the account: approve only an address whose key your app generated and holds.

```kotlin theme={null}
val approval = portal.perps.yieldxyz.createAction(
    YieldXyzPerpsCreateActionParams(
        providerId = "hyperliquid",
        action = YieldXyzPerpsActionType.APPROVE_AGENT,
        args = YieldXyzPerpsActionArgs(
            agentAddress = agentAddress, // the address of the agent key your app holds
            agentName = "my-app",
        ),
    ),
).getOrThrow().data

portal.perps.yieldxyz.signAndSubmitAction(approval).getOrThrow()
```

## Opening a position

Open a position with `action = YieldXyzPerpsActionType.OPEN`. The fields that size the order, and their units, are defined by the venue's `argumentSchemas["open"]`, so read that schema before you build the arguments. The Portal API requires `marketId`, `side` and `leverage`, plus exactly one of `amount` or `size`: sending both is rejected with a `400`.

```kotlin theme={null}
val open = portal.perps.yieldxyz.createAction(
    YieldXyzPerpsCreateActionParams(
        providerId = "hyperliquid",
        action = YieldXyzPerpsActionType.OPEN,
        args = YieldXyzPerpsActionArgs(
            marketId = "hyperliquid-eth-usdc",
            side = YieldXyzPerpsSide.LONG,
            amount = "10", // the size field and its units come from argumentSchemas["open"]
            leverage = 5.0,
            marginMode = YieldXyzPerpsMarginMode.ISOLATED,
        ),
    ),
).getOrThrow().data

// Show the summary before the user signs: Portal adds no trading guardrails.
open.summary?.let { summary ->
    println("Direction: ${summary.direction ?: "-"}, size: ${summary.size ?: "-"}, leverage: ${summary.leverage?.let { "${it.toBigDecimal().stripTrailingZeros().toPlainString()}x" } ?: "-"}")
    println("Collateral: ${summary.collateral ?: "-"}, estimated liquidation price: ${summary.estimatedLiquidationPrice ?: "-"}")
}

val result = portal.perps.yieldxyz.signAndSubmitAction(open).getOrThrow()
println(result.status) // SUCCESS
```

`YieldXyzPerpsCreateActionParams` takes:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `providerId` | `String` | Yes | Venue id from `getProviders()`. |
| `action` | `String` | Yes | The action type. The values the Portal API accepts are the constants of `YieldXyzPerpsActionType`: `OPEN`, `CLOSE`, `UPDATE_LEVERAGE`, `STOP_LOSS`, `TAKE_PROFIT`, `SET_TP_AND_SL`, `CANCEL_ORDER`, `EDIT_ORDER`, `UPDATE_MARGIN`, `FUND`, `WITHDRAW`, `APPROVE_AGENT`, `APPROVE_BUILDER_FEE` and `SET_UNIFIED_ACCOUNT`. |
| `args` | `YieldXyzPerpsActionArgs` | Yes | The action's arguments. The venue's `argumentSchemas` describes them. |
| `address` | `String?` | No | Defaults to the Portal wallet's EVM address. |

`YieldXyzPerpsActionArgs` types the documented fields (`marketId`, `side`, `amount`, `size`, `leverage`, `marginMode`, `limitPrice`, `stopLossPrice`, `takeProfitPrice`, `orderId`, `orderIds`, `fromToken`, `agentAddress`, `agentName`, `fundingMethod`, `enabled` and others). `leverage` and the prices are `Double`s: a whole number is sent without a fraction (`5`, not `5.0`), and a value that isn't finite fails the request with `IllegalArgumentException`. Put any other key a venue's schema asks for in `additionalFields`, a `Map<String, JsonElement>`; it is sent as it is. A key in `additionalFields` named like a typed field is ignored: set the typed field instead (the exceptions are the undocumented `fund` keys `spenderAddress`, `tokenAddress` and `expectedSpenderAddress`, which are sent from `additionalFields` when the typed field is `null`).

`createAction` returns the action in `data`. The action carries its `id`, its `status`, a `summary` of the trade (`direction`, `size`, `leverage`, `collateral`, `fee`, `estimatedLiquidationPrice` and similar; simpler or `null` for non-trade actions such as `fund`) and its `transactions`, each with a `signingFormat` and `signablePayload`. Nothing is signed yet.

## Managing a position

Every management action follows the same `createAction` and `signAndSubmitAction` flow; only `action` and `args` differ. Each venue's `argumentSchemas` describes the exact `args`.

| Action | What it does | Key `args` |
| - | - | - |
| `UPDATE_LEVERAGE` | Change a market's leverage | `marketId`, `leverage`, `marginMode` |
| `SET_TP_AND_SL` | Set or update stop-loss and take-profit together | `marketId`, `stopLossPrice`, `takeProfitPrice` |
| `STOP_LOSS` | Set or update a stop-loss | `marketId`, `stopLossPrice` |
| `TAKE_PROFIT` | Set or update a take-profit | `marketId`, `takeProfitPrice` |
| `UPDATE_MARGIN` | Add or remove margin on an isolated position | `marketId`, `amount` |
| `EDIT_ORDER` | Adjust a resting order's price or size | `marketId`, `orderId`, and `limitPrice` or `size` |
| `CANCEL_ORDER` | Cancel one or more resting orders | `marketId`, and `orderId` or `orderIds` |
| `SET_UNIFIED_ACCOUNT` | Enable or disable unified-account mode where supported | `enabled` |

```kotlin theme={null}
val perps = portal.perps.yieldxyz

val leverage = perps.createAction(
    YieldXyzPerpsCreateActionParams(
        providerId = "hyperliquid",
        action = YieldXyzPerpsActionType.UPDATE_LEVERAGE,
        args = YieldXyzPerpsActionArgs(
            marketId = "hyperliquid-eth-usdc",
            leverage = 2.0,
            marginMode = YieldXyzPerpsMarginMode.ISOLATED,
        ),
    ),
).getOrThrow().data
perps.signAndSubmitAction(leverage).getOrThrow()

val protection = perps.createAction(
    YieldXyzPerpsCreateActionParams(
        providerId = "hyperliquid",
        action = YieldXyzPerpsActionType.SET_TP_AND_SL,
        args = YieldXyzPerpsActionArgs(
            marketId = "hyperliquid-eth-usdc",
            stopLossPrice = 3600.0,
            takeProfitPrice = 4400.0,
        ),
    ),
).getOrThrow().data
perps.signAndSubmitAction(protection).getOrThrow()
```

Each position and order also lists `pendingActions`, the actions available for it now, with pre-filled `args` you can pass to `createAction` unchanged (see [Positions, orders and balances](#positions-orders-and-balances)).

## Closing a position and withdrawing

Close a position with `action = YieldXyzPerpsActionType.CLOSE`, then withdraw collateral from the trading account with `action = YieldXyzPerpsActionType.WITHDRAW`.

```kotlin theme={null}
val perps = portal.perps.yieldxyz

val close = perps.createAction(
    YieldXyzPerpsCreateActionParams(
        providerId = "hyperliquid",
        action = YieldXyzPerpsActionType.CLOSE,
        args = YieldXyzPerpsActionArgs(marketId = "hyperliquid-eth-usdc"),
    ),
).getOrThrow().data
perps.signAndSubmitAction(close).getOrThrow()

val withdraw = perps.createAction(
    YieldXyzPerpsCreateActionParams(
        providerId = "hyperliquid",
        action = YieldXyzPerpsActionType.WITHDRAW,
        args = YieldXyzPerpsActionArgs(amount = "100"),
    ),
).getOrThrow().data
perps.signAndSubmitAction(withdraw).getOrThrow()
```

On Hyperliquid, withdrawals return USDC on Arbitrum One to the signing address, with a flat fee and a minimum; see [Funding sources and limits](https://docs.portalhq.io/integrations/Yield/yield-xyz-perps.md#funding-sources-and-limits).

## Positions, orders and balances

`getPositions(params)` and `getOrders(params)` take at least one venue (`providerId` or `providerIds`). `getBalances(params)` takes exactly one venue and returns a single balance.

```kotlin theme={null}
val perps = portal.perps.yieldxyz

val positions = perps.getPositions(YieldXyzPerpsPortfolioParams(providerId = "hyperliquid")).getOrThrow().data
for (position in positions) {
    println("${position.marketId} ${position.side} ${position.size} ${position.unrealizedPnl} ${position.liquidationPrice}")
}

val orders = perps.getOrders(YieldXyzPerpsPortfolioParams(providerId = "hyperliquid")).getOrThrow().data
val balance = perps.getBalances(YieldXyzPerpsBalancesParams(providerId = "hyperliquid")).getOrThrow().data
println("${orders.size} ${balance.availableBalance}")

val pending = positions.firstOrNull()?.pendingActions?.firstOrNull { it.type == YieldXyzPerpsActionType.CLOSE }
if (pending != null) {
    val action = perps.createAction(
        YieldXyzPerpsCreateActionParams(providerId = "hyperliquid", action = pending.type, args = pending.args),
    ).getOrThrow().data
    perps.signAndSubmitAction(action).getOrThrow()
}
```

A position carries `marketId`, `side`, `size`, `entryPrice`, `markPrice`, `leverage`, `marginMode`, `margin`, `unrealizedPnl`, `funding`, `liquidationPrice` and `pendingActions`. A balance carries `accountValue`, `usedMargin`, `availableBalance` and `unrealizedPnl`. Calling `getPositions` or `getOrders` without a venue, or `getBalances` with an empty `providerId`, fails with `YieldXyzPerpsException.ProviderRequired` before any request is sent.

## Signing and execution

### How an action is executed

`signAndSubmitAction(action, options)` signs and submits an action's transactions, then tracks it:

1. It goes through the action's transactions in order. A transaction awaits a signature only while it is `CREATED`. Before signing one, the SDK reads the action back: a transaction Yield.xyz no longer lists as `CREATED` is skipped, and the payload signed is the one Yield.xyz lists now.
2. It signs each transaction according to its `signingFormat`:
   * **`EIP712_TYPED_DATA`** (Hyperliquid orders and account changes such as `updateLeverage`): signed off-chain with `eth_signTypedData_v4`, routed through `signingChainId` (Arbitrum One by default), and submitted as `signedPayload` with the action id. The typed data is signed as Yield.xyz returns it: its domain `chainId` (`1337` on Hyperliquid) is not rewritten and is never used for routing. The SDK only adds `types.EIP712Domain` when it is missing.
   * **`EVM_TRANSACTION`** (on-chain legs such as the `fund` approval and transfer): sent with `eth_sendTransaction` on the transaction's own chain with an [idempotency key](#idempotency-keys-on-on-chain-legs), confirmed on-chain (the default waiter checks the receipt every 2 seconds, up to 450 times: about 15 minutes), then submitted as `transactionHash`.
3. It polls the action until it reaches a final status (`SUCCESS`, `FAILED`, `CANCELED` or `STALE`), signing any transaction Yield.xyz adds meanwhile, for example while the action is `WAITING_FOR_NEXT`.
4. It returns a successful `Result` when the action reaches `SUCCESS`. An action that ends `FAILED`, `CANCELED` or `STALE` fails with a [`YieldXyzPerpsExecutionException`](#handling-errors) whose `reason` is `ACTION_FAILED`, and other failures carry another reason, except that an action missing its `id`, `status` or `transactions` fails with `JsonParseException` before anything is signed. When the coroutine is [cancelled](#cancelling-an-execution), it throws `CancellationException` instead.

Yield.xyz reports a submitted transaction as `QUEUED`. Only `CREATED` transactions are signed, so running `signAndSubmitAction` again on the same action never re-signs a transaction Yield.xyz has already recorded. An on-chain leg broadcast without its hash reaching Yield.xyz is not recorded yet and stays `CREATED`, so a re-run tries to send it again unless you pass its hash in `broadcastHashes`. Only its idempotency key then stops a second broadcast, and only while Portal remembers the key (at least 24 hours) and `useIdempotencyKeys` is on (see [Resuming a failed execution](#resuming-a-failed-execution)). Calling it while another call on the same Portal instance is still executing that action fails with `ACTION_IN_PROGRESS` and signs nothing.

Before signing, the SDK checks that the `signingFormat` is `EIP712_TYPED_DATA` or `EVM_TRANSACTION` (other formats, including Solana and Cosmos, are not supported yet), that the transaction and an on-chain payload's `from` were built for the Portal wallet's EVM address, and that the chain the request is routed through is an EIP-155 chain with an `rpcConfig` entry. That chain check applies to per-call signers too. For on-chain legs, only `from`, `to`, `data` and `value` are forwarded: the signer sets the nonce, fees and gas limit. The `gasLimit` Yield.xyz returns is not sent as `gas`, because it is estimated when the action is built and can fall short by the time the leg is signed. Portal's signer estimates gas when the transaction is sent.

Each signature goes through Portal's signing flow. Unless the `Portal` instance was created with `autoApprove = true`, approve each request in a `portal_signingRequested` handler: register it with `portal.on(PortalEvents.PortalSigningRequested)`, and answer with `portal.emit(PortalEvents.PortalSigningApproved, request)` or `portal.emit(PortalEvents.PortalSigningRejected, request)`, passing the `PortalProviderRequestWithId` the handler received (see also [Add custom signature hooks](https://docs.portalhq.io/sdks/android/guide/add-custom-signature-hooks.md)). A rejected request stops the execution with `SIGNATURE_REJECTED`, except for a retried on-chain send (see [Idempotency keys on on-chain legs](#idempotency-keys-on-on-chain-legs)). Without a handler, the request throws `PortalException.Provider.NoBindingForSigningApprovalFound` before anything is signed, so the execution stops with `SIGNING_FAILED`.

```kotlin theme={null}
import android.os.Handler
import android.os.Looper
import io.portalhq.android.provider.data.PortalProviderRequestWithId
import io.portalhq.android.utils.events.PortalEvents

// Register once, where you create the Portal. The handler runs on a background thread.
val mainThread = Handler(Looper.getMainLooper())
portal.on(PortalEvents.PortalSigningRequested) { data ->
    val request = data as PortalProviderRequestWithId
    mainThread.post {
        showApproval( // your confirmation UI
            request,
            onApprove = { portal.emit(PortalEvents.PortalSigningApproved, request) },
            onReject = { portal.emit(PortalEvents.PortalSigningRejected, request) },
        )
    }
}
```

Show your UI from the main thread, as above, and don't let the handler throw. An exception it throws fails the execution: with `SIGNING_FAILED` for a typed-data transaction, and with `BROADCAST_OUTCOME_UNKNOWN` for an on-chain leg, although nothing was sent.

### Idempotency keys on on-chain legs

Each `EVM_TRANSACTION` leg is sent with the [idempotency key](https://docs.portalhq.io/sdks/android/guide/idempotency-keys.md) `yieldxyz-perps-<transactionId>` (a leg whose transaction id can't form a valid key is sent without one, with a warning in the SDK log when the [log level](https://docs.portalhq.io/sdks/android/guide/configure-log-level.md) is `WARN` or more verbose). While Portal remembers the key (at least 24 hours), it broadcasts the leg at most once, for example when an execution is resumed after the app was killed before the hash reached Yield.xyz.

* A send Portal reports as still in progress (`IDEMPOTENT_REQUEST_IN_PROGRESS`) is sent again with the same key, waiting 2, 4, then 8 seconds before each retry. Each retry is a new signing request, so it asks for approval again unless `autoApprove` is on. If Portal still reports it in progress after that, the execution fails with `BROADCAST_OUTCOME_UNKNOWN`. A retry that is rejected in your handler, or that fails with an error other than an idempotency answer, also fails with `BROADCAST_OUTCOME_UNKNOWN`, not `SIGNATURE_REJECTED` or `SIGNING_FAILED`: the earlier send may still broadcast the leg.
* A leg Portal already broadcast fails with `TRANSACTION_ALREADY_BROADCAST`. Portal does not return that broadcast's hash.
* Any other refusal of the key, and a send that failed in a way that doesn't prove it never reached the chain, fail with `BROADCAST_OUTCOME_UNKNOWN`.

See [When an on-chain leg may have been sent](#when-an-on-chain-leg-may-have-been-sent) for what to do after each.

### Executing in one call

`executeAction(params, options)` calls `createAction` and then `signAndSubmitAction`. Use the two-call flow when you want to show the `summary` before the user signs. When `executeAction` fails with a `YieldXyzPerpsExecutionException`, don't call it again: that builds a new action, and can repeat legs that already executed. Resume with `signAndSubmitAction(error.action)` instead, or with the action from `getAction(error.actionId)` when `action` is `null`. A failure before the action exists is described below the example.

```kotlin theme={null}
val result = portal.perps.yieldxyz.executeAction(
    params = YieldXyzPerpsCreateActionParams(
        providerId = "hyperliquid",
        action = YieldXyzPerpsActionType.UPDATE_LEVERAGE,
        args = YieldXyzPerpsActionArgs(
            marketId = "hyperliquid-eth-usdc",
            leverage = 1.0,
            marginMode = YieldXyzPerpsMarginMode.ISOLATED,
        ),
    ),
    options = YieldXyzPerpsExecuteOptions(onProgress = { event ->
        println("${event.step} ${event.signingFormat ?: ""}")
    }),
).getOrThrow()
println(result.status)
```

When `createAction` fails, `executeAction` returns its failure as it is, with no `FAILED` progress event: no action exists yet, so there is nothing to resume. That is a Portal API error, which you read with `YieldXyzPerpsApiError.from(error)`, a `YieldXyzPerpsException` such as `ProviderRequired` or `NoAddress`, a transport `IOException`, a `JsonParseException` (also when the response carries no action), a `PortalException.Credentials` raised before any request was sent, or an `IllegalArgumentException` for an argument that can't be sent. `YieldXyzPerpsApiError.from(error)` returns `null` for all but the first; a `401` from the Portal API is an API error with `status` 401. A cancelled coroutine throws `CancellationException`.

### Options

Both methods take a `YieldXyzPerpsExecuteOptions`; leave out `options` to use the defaults.

| Name | Type | Default | Description |
| - | - | - | - |
| `onProgress` | `((YieldXyzPerpsExecutionProgress) -> Unit)?` | `null` | Called at each execution step. It can run after a transaction was broadcast, so it must return quickly. An exception it throws is logged and does not affect the execution. |
| `signingChainId` | `String` | `"eip155:42161"` (`YieldXyzPerps.DEFAULT_SIGNING_CHAIN_ID`) | CAIP-2 chain that EIP-712 signing requests are routed through. Must have an `rpcConfig` entry. |
| `pollAction` | `Boolean` | `true` | Whether to poll the action to a final status after its transactions are submitted. With `false`, the method returns once the transactions listed as `CREATED` are submitted, and `status` is the action's current status. |
| `pollOptions` | `YieldXyzPerpsPollOptions` | `intervalMs = 2_000`, `timeoutMs = 600_000` | How the action is read back, in **milliseconds**. The interval (at least 250 ms) grows by 1.5× after each read, up to 10 seconds. The timeout applies to each wait separately, including the read before each signature, which happens even with `pollAction = false`, so `TIMEOUT` can still occur. Each wait reads the action at least once, even with a timeout of `0`. |
| `useIdempotencyKeys` | `Boolean` | `true` | Whether to send each on-chain leg with its idempotency key. See [Idempotency keys on on-chain legs](#idempotency-keys-on-on-chain-legs). |
| `signTypedData` | `YieldXyzPerpsSignTypedData?` | `null` | Per-call typed-data signer. |
| `signAndSendTransaction` | `YieldXyzPerpsSignAndSendTransaction?` | `null` | Per-call on-chain transaction signer. |
| `waitForConfirmation` | `YieldXyzPerpsWaitForConfirmation?` | `null` | Per-call confirmation waiter for on-chain legs. Return `true` only when the leg confirmed successfully. |
| `broadcastHashes` | `Map<String, String>` | `emptyMap()` | On-chain legs an earlier attempt already broadcast, by transaction id. See [Resuming a failed execution](#resuming-a-failed-execution). |

### Progress events

`onProgress` receives a `YieldXyzPerpsExecutionProgress` with the `step`, the `actionId` and the fields that apply to that step:

| `step` | Meaning | Fields |
| - | - | - |
| `SIGNING` | About to sign a transaction. | `transactionId`, `index`, `signingFormat` |
| `CONFIRMING` | An on-chain leg was broadcast; waiting for its receipt. | `transactionId`, `index`, `signingFormat`, `transactionHash` |
| `CONFIRMED` | The on-chain leg confirmed. | `transactionId`, `index`, `signingFormat`, `transactionHash` |
| `SUBMITTED` | Yield.xyz accepted the signature or the transaction hash. | `transactionId`, `index`, `signingFormat`, plus `transactionHash` for on-chain legs |
| `POLLING` | The action was read back. | `actionStatus` |
| `FAILED` | Execution stopped. | `error`, plus `transactionId` and `transactionHash` when known |

An EIP-712 transaction goes `SIGNING` → `SUBMITTED`; an on-chain leg goes `SIGNING` → `CONFIRMING` → `CONFIRMED` → `SUBMITTED`. A leg resumed from `broadcastHashes` is not signed again, so it starts at `CONFIRMING`. `index` counts the transactions this call signed or submitted before this one.

The `CONFIRMING` event reports the hash as soon as the leg is broadcast. Persist it then: the wait for the confirmation can last about 15 minutes, and Android can stop the app's process in the meantime (see [Resuming a failed execution](#resuming-a-failed-execution)). `onProgress` is not a `suspend` function, and it runs in the coroutine that called the method (the SDK moves only its own network and signing work to `Dispatchers.IO`), so don't block in it: under `viewModelScope` it runs on the main thread. To persist the hash, start the write on `Dispatchers.IO` in an application-wide scope (for example to Room or DataStore), so it completes even if the screen closes.

```kotlin theme={null}
fun onProgress(event: YieldXyzPerpsExecutionProgress) {
    when (event.step) {
        YieldXyzPerpsExecutionStep.SIGNING ->
            println("Signing ${event.signingFormat} transaction ${event.transactionId}")
        YieldXyzPerpsExecutionStep.CONFIRMING ->
            println("Waiting for ${event.transactionHash} to confirm")
        YieldXyzPerpsExecutionStep.CONFIRMED ->
            println("Confirmed ${event.transactionHash}")
        YieldXyzPerpsExecutionStep.SUBMITTED ->
            println("Submitted transaction ${event.transactionId}")
        YieldXyzPerpsExecutionStep.POLLING ->
            println("Action status: ${event.actionStatus}")
        YieldXyzPerpsExecutionStep.FAILED ->
            println("Stopped: ${event.error?.reason}")
    }
}

portal.perps.yieldxyz.signAndSubmitAction(action, YieldXyzPerpsExecuteOptions(onProgress = ::onProgress)).getOrThrow()
```

### Return value

Both methods return a `YieldXyzPerpsExecutionResult`:

| Field | Description |
| - | - |
| `actionId` | The action id. |
| `action` | The latest state of the action. |
| `status` | The action's final status (`SUCCESS`), or its current status with `pollAction = false`. |
| `transactions` | One `YieldXyzPerpsTransactionExecution` per transaction this call signed or submitted: `transactionId`, `type`, `signingFormat`, `signedPayload` (EIP-712 transactions), `transactionHash` (on-chain legs) and `submitResult` (`null` when the outcome was confirmed by reading the action back). |

### Cancelling an execution

Cancelling the coroutine that runs `signAndSubmitAction` or `executeAction`, for example by cancelling its scope, stops the SDK's work, not the trade. The method throws `CancellationException` instead of returning a `Result`, with no `FAILED` progress event, also when an on-chain leg was already broadcast.

Cancelling does not undo what was already sent:

* A transaction reported `SUBMITTED`, or one whose submission was in flight, can still execute: the order is with the venue and can fill.
* An on-chain leg's hash is reported in the `CONFIRMING` event once the signer returns it. A cancellation that lands while the signer is still sending can lose that hash although the leg is broadcast. With idempotency keys on, resuming then fails with `TRANSACTION_ALREADY_BROADCAST` or `BROADCAST_OUTCOME_UNKNOWN` instead of sending the leg again, and you find the hash on-chain; with `useIdempotencyKeys = false`, a resume would broadcast it a second time.
* An approval your `portal_signingRequested` handler is showing is not dismissed. Portal's approval wait doesn't observe cancellation and has no timeout, so the cancelled call ends only once the request is approved or rejected; it then throws `CancellationException` without signing. Until that call ends, resuming the action on the same `Portal` fails with `ACTION_IN_PROGRESS`. Reject any request your handler is still showing when you cancel (`portal.emit(PortalEvents.PortalSigningRejected, request)`), so the call can end.

So don't treat `CancellationException` as "nothing happened". Before you offer a new action, read the action with `getAction(actionId)`, or resume it. `CancellationException` carries no action id: with `executeAction`, keep the `actionId` every progress event carries, or use `createAction` and `signAndSubmitAction` so you hold the action. Resuming skips the transactions Yield.xyz recorded. For an on-chain send that may be in flight, resume with idempotency keys on and within Portal's key window (at least 24 hours), so Portal broadcasts the leg at most once. If the cancelled call ran with `useIdempotencyKeys = false`, or the leg was sent without a key, no key covers it: check the chain before resuming.

Choose the coroutine scope with this in mind. Don't run an execution in an `Activity`'s or `Fragment`'s `lifecycleScope`, which a configuration change such as a rotation cancels. Use a `ViewModel`'s `viewModelScope`, which survives a configuration change, or an application-wide scope, which also survives the screen closing. And don't wrap the call in `runCatching`, or a `catch` of `Exception` or `Throwable`, that reports a `CancellationException` as an ordinary failure. Create the `Portal` and register its `portal_signingRequested` handler outside the `Activity` too, for example in your `Application` or alongside the `ViewModel`: otherwise the destroyed screen's handler keeps receiving requests after a configuration change, because `portal.on` doesn't remove earlier handlers (to remove one, keep a reference to it and call `portal.provider.removeEventListener("portal_signingRequested", handler)`). Handlers run in the order they were added: if the old one throws, the execution fails and the handlers after it don't run; if it answers nothing, the call waits until another handler answers.

```kotlin theme={null}
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

class TradeViewModel(private val portal: Portal) : ViewModel() {
    fun execute(action: YieldXyzPerpsAction) {
        // viewModelScope survives a rotation; an Activity's lifecycleScope would cancel the execution.
        viewModelScope.launch {
            portal.perps.yieldxyz.signAndSubmitAction(action)
                .onSuccess { result -> println("Action ${result.actionId} ended ${result.status}") }
                .onFailure { error -> println("Execution failed: ${error.message}") }
        }
    }
}
```

### Using your own signers

Pass `signTypedData`, `signAndSendTransaction` or `waitForConfirmation` to replace one part of the signing, for example to add a confirmation step. The signing chain must still have an `rpcConfig` entry, and every transaction must have been built for the Portal wallet's EVM address.

```kotlin theme={null}
import io.portalhq.android.exceptions.PortalException
import io.portalhq.android.provider.data.PortalRequestMethod

// `confirmWithUser` stands for your own confirmation UI: a suspend function that returns `true` to sign.
val signTypedData: YieldXyzPerpsSignTypedData = { request ->
    if (!confirmWithUser("Sign this Hyperliquid action?")) {
        null // stops the execution with SIGNATURE_REJECTED
    } else {
        try {
            val response = portal.request(
                chainId = request.chainId,
                method = PortalRequestMethod.eth_signTypedData_v4,
                params = listOf(request.address, request.typedData),
            )
            response.result as? String
                ?: throw IllegalStateException("eth_signTypedData_v4 returned no signature") // stops the execution with SIGNING_FAILED
        } catch (e: PortalException.Provider.UserDeclinedApproval) {
            null // declined in your portal_signingRequested handler
        }
    }
}

portal.perps.yieldxyz.signAndSubmitAction(
    action,
    YieldXyzPerpsExecuteOptions(signTypedData = signTypedData),
).getOrThrow()
```

`portal.request` still goes through Portal's approval flow, so with `autoApprove` off the user approves twice: once in your UI and once in your `portal_signingRequested` handler. This pattern suits a `Portal` created with `autoApprove = true`. A request declined in the handler throws `PortalException.Provider.UserDeclinedApproval`; return `null` for it, as above, so the execution stops with `SIGNATURE_REJECTED` rather than `SIGNING_FAILED`.

What each signer receives and returns:

* `signTypedData` receives a `YieldXyzPerpsSignTypedDataRequest` with the wallet `address`, the JSON-encoded typed data and the CAIP-2 `chainId` to route through, and returns the 65-byte hex signature.
* `signAndSendTransaction` receives the `EthTransactionParam` to send (without `gas`), the CAIP-2 chain id and the leg's idempotency key, and returns the transaction hash. Pass the key to `eth_sendTransaction` as `RequestOptions(idempotencyKey = ...)` (`io.portalhq.android.provider.data.RequestOptions`). The key is a `String?`: `null` when `useIdempotencyKeys` is `false`, or when the transaction id can't form a valid key.
* Both return `null` when the request is declined. A value that isn't a signature or hash should throw rather than return `null`.

Let errors from Portal propagate unchanged, because the SDK reads them:

* A failure before the broadcast becomes `SIGNING_FAILED`: `PortalException.Provider.UserDeclinedApproval`, `NoBindingForSigningApprovalFound`, `InvalidIdempotencyKey` and `IdempotencyKeyUnsupported`, `PortalException.Credentials`, and a `PortalException.Mpc.MpcResultError` for an auth failure, or a refused build, malformed request, blocked address, policy limit or insufficient balance.
* An idempotency answer is handled as described in [Idempotency keys on on-chain legs](#idempotency-keys-on-on-chain-legs).
* Any other error from an on-chain send becomes `BROADCAST_OUTCOME_UNKNOWN`.
* A `CancellationException` your signer throws while the calling coroutine is still active, for example from its own `withTimeout`, is handled like any other error.

## Resuming a failed execution

A failed execution returns a `YieldXyzPerpsExecutionException` that carries the `actionId`, `action` (the latest known state of the action) and, when the failure concerns one transaction, its `transactionId`. Resume with `signAndSubmitAction(error.action)`, or, when `action` is `null` (as for an unexpected `SIGNING_FAILED` without a `transactionId`), with the action read back with `getAction(actionId)`: transactions Yield.xyz already recorded are never signed again.

When the error carries a `broadcastHash`, that on-chain leg was already broadcast and Yield.xyz may not have recorded it yet. Pass it in `broadcastHashes`, keyed by transaction id, so the SDK confirms and submits that hash instead of signing and broadcasting the leg again. Record the hash from the `CONFIRMING` progress event too, so it survives the app's process being stopped before the error arrives. Once the action succeeds, drop its entries.

```kotlin theme={null}
import io.portalhq.android.exceptions.PortalException
import io.portalhq.android.utils.PortalIdempotencyErrorId

class PerpsExecution(private val portal: Portal, action: YieldXyzPerpsAction) {
    // Persist both in your app's storage: pending.id (read the action back with getAction) and broadcastHashes.
    var pending: YieldXyzPerpsAction = action
        private set
    val broadcastHashes = mutableMapOf<String, String>()

    // Call once to execute, and again only when the user chooses to retry.
    suspend fun execute(): Result<YieldXyzPerpsExecutionResult> =
        portal.perps.yieldxyz.signAndSubmitAction(
            pending,
            YieldXyzPerpsExecuteOptions(
                onProgress = { event ->
                    // Record the hash as soon as the on-chain leg is broadcast, and persist it now, without blocking
                    // (start the write on Dispatchers.IO): Android can stop the app's process during the confirmation wait.
                    val transactionId = event.transactionId
                    val hash = event.transactionHash
                    if (event.step == YieldXyzPerpsExecutionStep.CONFIRMING && transactionId != null && hash != null) {
                        broadcastHashes[transactionId] = hash
                    }
                },
                broadcastHashes = broadcastHashes.toMap(),
            ),
        ).onSuccess { result ->
            result.action.transactions.forEach { broadcastHashes.remove(it.id) }
        }.onFailure { error ->
            if (error is YieldXyzPerpsExecutionException) {
                val transactionId = error.transactionId
                val hash = error.broadcastHash
                if (transactionId != null && hash != null) {
                    broadcastHashes[transactionId] = hash
                }
                pending = error.action ?: pending
            }
        }
}

// From a coroutine in your ViewModel's viewModelScope:
val execution = PerpsExecution(portal, action) // keep it in your ViewModel
execution.execute().onFailure { error ->
    if (error !is YieldXyzPerpsExecutionException) return@onFailure // see "Handling errors"
    when (error.reason) {
        YieldXyzPerpsExecutionErrorReason.TRANSACTION_ALREADY_BROADCAST -> {
            // Find the leg on-chain and add its hash to broadcastHashes: see "When an on-chain leg may have been sent".
        }
        YieldXyzPerpsExecutionErrorReason.BROADCAST_OUTCOME_UNKNOWN -> {
            // What to do depends on Portal's idempotency answer behind the error.
            when ((error.cause as? PortalException.Mpc.MpcResultError)?.id) {
                PortalIdempotencyErrorId.IDEMPOTENT_REQUEST_IN_PROGRESS -> {
                    // Still in progress: wait, then call execute() again with keys on.
                }
                PortalIdempotencyErrorId.IDEMPOTENT_REQUEST_PREVIOUSLY_FAILED,
                PortalIdempotencyErrorId.IDEMPOTENT_REQUEST_UNEXPECTED_STATE,
                PortalIdempotencyErrorId.IDEMPOTENT_TX_MISSING,
                PortalIdempotencyErrorId.IDEMPOTENCY_KEY_REUSED -> {
                    // Portal refuses the key: check the chain before you offer a retry (see the table below).
                }
                else -> {
                    // The send may have reached the chain: call execute() again with keys on, within 24 hours of the
                    // failed send. After that, or when the leg was sent without a key, check the chain first.
                }
            }
        }
        else -> {
            // Persist pending and broadcastHashes, and call execute() again when the user retries.
            // Check the reason in "What to do for each reason" before you offer a retry.
        }
    }
}
```

### When an on-chain leg may have been sent

To check the chain for a leg, look it up in a block explorer or indexer that shows each transaction's `to` and input data, for example the wallet's transaction list on Arbiscan, and match the leg's `to` and `data` from its `signablePayload`. Conclude that the leg was not sent only when no matching transaction is mined and none is pending: the wallet's pending nonce (`eth_getTransactionCount` with `pending`) equals its latest nonce (see also the [EVM rule of the idempotency guide](https://docs.portalhq.io/sdks/android/guide/idempotency-keys.md#retry-sendasset)). Legs run in order, so a later leg is never sent before an earlier one is submitted.

`TRANSACTION_ALREADY_BROADCAST` means Portal already broadcast the leg under its idempotency key: find the transaction on-chain and resume with its hash in `broadcastHashes`. For `BROADCAST_OUTCOME_UNKNOWN`, what to do depends on the cause, the `id` of the `PortalException.Mpc.MpcResultError` in `cause`, compared with the constants of `PortalIdempotencyErrorId`:

| Cause | What to do |
| - | - |
| `IDEMPOTENT_REQUEST_IN_PROGRESS` | The earlier send is still being processed and may yet broadcast the leg. This is also the cause when a retry of that send was rejected in your handler. Wait, then resume with idempotency keys on, within 24 hours of the failed send (Portal remembers a key at least that long); after that, check the chain first. |
| `IDEMPOTENT_REQUEST_PREVIOUSLY_FAILED`, `IDEMPOTENT_REQUEST_UNEXPECTED_STATE`, `IDEMPOTENT_TX_MISSING` or `IDEMPOTENCY_KEY_REUSED` | Portal can't say whether the earlier send went out, and refuses the key for at least 24 hours, even once a cause such as missing gas is fixed. Check the chain as described above. If the leg was sent, resume with its hash in `broadcastHashes`. If it was not sent and nothing is pending, build a new action (its legs get new keys), or resume this one with `useIdempotencyKeys = false`. Prefer a new action: `false` turns the keys off for every remaining leg of that call. |
| Anything else, for example an RPC timeout or a failed retry of a send still in progress | The send may have reached the chain. Resume with idempotency keys on first, within 24 hours of the failed send (Portal remembers a key at least that long): Portal then sends the leg at most once, and reports what happened to the earlier send. After that window, check the chain first. If the failed call ran with `useIdempotencyKeys = false`, or the leg was sent without a key, no key covers it: check the chain before resuming. |

### What to do for each reason

What each reason means is listed in [Handling errors](#handling-errors).

| Reason | What to do |
| - | - |
| `ACTION_FAILED` | The action ended as `FAILED`, `CANCELED` or `STALE` and cannot be resumed. A leg may still have executed on-chain: when `error.broadcastHash` is set, when your persisted `broadcastHashes` hold a hash for one of its legs (a leg stays `CREATED` when the action ended before its hash was submitted), or when `error.action` lists an `EVM_TRANSACTION` leg as `QUEUED`, `BROADCASTED` or `CONFIRMED`. Check its effect first (for a `fund`, the trading account with `getBalances`) before you create another action, or you may repeat it. |
| `ACTION_IN_PROGRESS` | Another call on this Portal instance is already executing the action. This call signed nothing. |
| `SIGNATURE_REJECTED`, `POLLING_FAILED`, `TIMEOUT` | Resume as is when the user is ready, after fixing a rejected credential (`401`) for `POLLING_FAILED` (with a Client Auth session, sign in again and resume on the new `Portal` instance). For `POLLING_FAILED` with another `4xx` (other than `429`), resuming fails the same way: read the cause with `YieldXyzPerpsApiError.from(error)` and fix it first. |
| `SIGNING_FAILED` | Signing failed, or an on-chain leg failed before it was broadcast. Check the action before retrying; without a `transactionId`, it is an unexpected error not tied to one transaction, so read the action with `getAction` first. For an on-chain leg, when Portal's server returned the failure (a `PortalException.Mpc.MpcResultError` such as `INSUFFICIENT_FUNDS`) and keys are on, Portal refuses that key afterwards: once the cause is fixed, build a new action, or resume with `useIdempotencyKeys = false` (which turns the keys off for every remaining leg of that call, so prefer a new action). A failure the SDK raised itself, such as a missing `portal_signingRequested` handler, never reached Portal: resume once it is fixed. |
| `TRANSACTION_ALREADY_BROADCAST`, `BROADCAST_OUTCOME_UNKNOWN` | See [When an on-chain leg may have been sent](#when-an-on-chain-leg-may-have-been-sent). |
| `SUBMIT_OUTCOME_UNKNOWN` | The submission failed ambiguously and its outcome could not be confirmed. Check the action before retrying; a signature is never resubmitted automatically. With a `broadcastHash`, resume with it in `broadcastHashes`. If a typed-data transaction is still `CREATED`, the lost submission may still have reached the venue: look for the order with `getOrders`, `getPositions` or `getEvents` before you build a new action. Resuming doesn't build a new action: it reads the action again, then signs and submits the payload Yield.xyz lists for that transaction. |
| `SUBMIT_REJECTED` | With a `PERPS_SIGNATURE_*` API error, the Portal API could not verify the signature; resuming signs the same payload and fails the same way, so check a custom `signTypedData` or `signingChainId` instead. With a `broadcastHash`, the leg already executed but its hash was rejected, for example because the session expired: fix the cause and resume with the hash in `broadcastHashes`, never with a new action. Otherwise (for example a `401`, or the SDK refused to send it), fix the cause and resume: the transaction is still `CREATED`, so it is signed again. |
| `SUBMIT_FAILED` | Yield.xyz reported the transaction as `FAILED` after accepting it. For a typed-data transaction, the venue rejected the signed request: create a new action. An on-chain leg is submitted only after it confirmed, so it may already have taken effect: check its effect (for example with `getBalances`) before you create another action. |
| `TRANSACTION_NOT_CONFIRMED` | The leg was broadcast but was not seen to confirm: it was still pending when the wait ended, it reverted, or the wait itself failed (for example an expired session or a persistent RPC error). Check its receipt (`error.broadcastHash`). If it confirmed or is still pending, resume with the hash in `broadcastHashes`; never create a new action. If it reverted, or the chain doesn't know the hash and the wallet's nonce has moved past it (the transaction was dropped), create a new action. |
| `INVALID_SIGNATURE` | The signer returned something other than a 65-byte signature or a transaction hash, or `broadcastHashes` held an invalid hash; a retry with the same input fails the same way. For an on-chain leg the signer may already have broadcast it: [check the chain](#when-an-on-chain-leg-may-have-been-sent) first. |
| `SIGNING_CHAIN_NOT_CONFIGURED`, `DEPENDENCY_UNAVAILABLE`, `MISSING_WALLET_ADDRESS` | Raised before the SDK signed the failing transaction. `MISSING_WALLET_ADDRESS` is raised before anything is signed; with the other two, earlier transactions of the action may already have been submitted in this call. The cause is on the device: fix it, then resume the same action, whose recorded transactions are skipped. A `Portal` keeps the `rpcConfig` it was created with, so for a missing chain, create a `Portal` whose `rpcConfig` includes it and resume on that instance. |
| `UNSUPPORTED_SIGNING_FORMAT`, `INVALID_SIGNABLE_PAYLOAD`, `SIGNER_ADDRESS_MISMATCH` | The cause is in the action itself, so it fails the same way every time. If none of its transactions were submitted, create a new action. Otherwise check the effect of the submitted ones (for example with `getBalances`) before you create another. |

## Handling errors

Every method returns its failure in the `Result`, as one of these:

* **`YieldXyzPerpsException`**, a request the SDK refused before sending it because the parameters are incomplete: `NoAddress`, `ProviderRequired` (with the `method`), `SubmissionRequired`, `ActionIdRequired` or `EmptyIdentifier` (with the `name` of an empty path id such as `marketId`).
* **Portal API errors**, the transport's exceptions unchanged: `PortalException.Api.HttpBadRequest` (400), `HttpUnauthorized` (401) and `HttpRequestFailed` (any other status), returned by the read methods, `createAction` and `submitTransaction`, and carried as `cause` by execution errors. `YieldXyzPerpsApiError.from(error)` returns the API error, with the HTTP `status`, the stable error `id`, the `message` and `details`, whether it is the failure itself or the cause of a `YieldXyzPerpsExecutionException`. A `401` carries only its `status`. It returns `null` for any other error.
* **`YieldXyzPerpsExecutionException`**, returned by `signAndSubmitAction` and `executeAction`. Branch on its `reason`.
* **Other errors**: a transport `IOException`, a `JsonParseException` for a response that doesn't decode (including the malformed-action cases above), a `PortalException.Credentials` when the credential can't be resolved before a request is sent, and an `IllegalArgumentException` for an argument that can't be sent, such as a `leverage` that isn't finite.

A cancelled coroutine is not among them: the method throws `CancellationException` (see [Cancelling an execution](#cancelling-an-execution)).

```kotlin theme={null}
portal.perps.yieldxyz.signAndSubmitAction(action).onFailure { error ->
    YieldXyzPerpsApiError.from(error)?.let { apiError ->
        when {
            apiError.isEoaRequired -> println("Perps needs a Portal client without account abstraction.")
            apiError.isSignatureError -> println("The signature could not be verified; do not retry as is.")
            apiError.isSchemaDrift -> println("Yield.xyz Perps is temporarily unavailable.")
            apiError.isRateLimit -> println("Rate limited by Yield.xyz; try again shortly.")
        }
        println("${apiError.status} ${apiError.id} ${apiError.message} ${apiError.code} ${apiError.reason}")
    }

    when (error) {
        is YieldXyzPerpsExecutionException ->
            println("${error.reason} ${error.actionId} ${error.transactionId} ${error.broadcastHash}")
        is YieldXyzPerpsException ->
            println("Refused before sending: ${error.message}")
        else ->
            println("Failed: $error") // a transport, decoding or credential error
    }
}
```

The Portal API answers with `401` when the credential is rejected, `400` (invalid request, a precondition the venue rejected such as insufficient margin, a missing or rejected Yield.xyz API key, a venue disabled for your Yield.xyz project, or one of the ids below), `404`, `429`, `503`, or `500` with `id: INTEGRATION_RESPONSE_SCHEMA_DRIFT`. When the venue returns a machine-readable code, `apiError.code` reads it from `details.code`, and `apiError.reason` reads a Yield.xyz sub-code such as `NO_ROUTE_AVAILABLE` from `details.reason`. `status` is `null` when the request got no HTTP status to report. See [Errors](https://docs.portalhq.io/integrations/Yield/yield-xyz-perps.md#errors) on the integration page. While executing, the SDK retries rate-limited (`429`) submissions up to three times, and tolerates up to four consecutive transient failures (a `429`, a 5xx, a transport failure or an undecodable response) while reading the action back. After an ambiguous submission failure (a 5xx or no HTTP status), it resubmits a transaction hash once, and only if the action shows Yield.xyz did not record it; it never resubmits a signature. A signature is never requested again, except that an on-chain send Portal reports as still in progress is sent again with the same idempotency key (see [Idempotency keys on on-chain legs](#idempotency-keys-on-on-chain-legs)).

`YieldXyzPerpsErrorId` holds each id as a constant of the same name:

| Id | Property | Meaning |
| - | - | - |
| `INTEGRATION_REQUIRES_EOA_CLIENT` | `isEoaRequired` | The client is account abstraction enabled; perps actions require an EOA client. |
| `PERPS_SIGNATURE_UNVERIFIABLE` | `isSignatureError` | The EIP-712 payload could not be hashed, so the signer could not be verified. |
| `PERPS_SIGNATURE_INVALID` | `isSignatureError` | No signer could be recovered from the signature. |
| `PERPS_SIGNATURE_ADDRESS_MISMATCH` | `isSignatureError` | The signature recovered to a different account than the action was built for. |
| `INTEGRATION_RESPONSE_SCHEMA_DRIFT` | `isSchemaDrift` | Yield.xyz changed a response shape; treat it as a temporary outage of the feature. |

`YieldXyzPerpsExecutionErrorReason` values (each one's `value` is the same string); see [What to do for each reason](#what-to-do-for-each-reason) for how to recover:

| Reason | Meaning |
| - | - |
| `UNSUPPORTED_SIGNING_FORMAT` | The transaction's `signingFormat` is missing or is not `EIP712_TYPED_DATA` or `EVM_TRANSACTION`. |
| `INVALID_SIGNABLE_PAYLOAD` | The `signablePayload` is missing or malformed, or neither the transaction's `network` nor its `chainId` identifies an EVM chain. |
| `MISSING_WALLET_ADDRESS` | No EVM wallet address is available to sign with. |
| `SIGNER_ADDRESS_MISMATCH` | The transaction was built for an address other than the Portal wallet's EVM address. |
| `SIGNING_CHAIN_NOT_CONFIGURED` | The chain the signing request is routed through is not an EIP-155 chain with an `rpcConfig` entry. |
| `DEPENDENCY_UNAVAILABLE` | A signer or confirmation waiter needed for the transaction is not configured. |
| `SIGNATURE_REJECTED` | The signing request was rejected: no signature or hash was returned. |
| `INVALID_SIGNATURE` | The signer, or `broadcastHashes`, supplied a value that is not a 65-byte hex signature or a 32-byte transaction hash. |
| `SIGNING_FAILED` | Signing failed, or an on-chain leg failed before it was broadcast; `cause` holds the underlying error. Also used for unexpected errors. |
| `TRANSACTION_ALREADY_BROADCAST` | Portal refused to broadcast an on-chain leg again because its idempotency key shows it was already broadcast. |
| `BROADCAST_OUTCOME_UNKNOWN` | An on-chain leg may have been broadcast; `cause` holds the underlying error. |
| `TRANSACTION_NOT_CONFIRMED` | An on-chain leg was broadcast but did not confirm successfully. |
| `SUBMIT_REJECTED` | The Portal API rejected the submission, or the SDK refused to send it; `cause` holds the error. |
| `SUBMIT_FAILED` | The submission was accepted, but Yield.xyz reported the transaction as `FAILED`. |
| `SUBMIT_OUTCOME_UNKNOWN` | The outcome of a transaction could not be confirmed. |
| `ACTION_FAILED` | The action ended as `FAILED`, `CANCELED` or `STALE`. |
| `ACTION_IN_PROGRESS` | Another call on this Portal instance is already executing the action. |
| `POLLING_FAILED` | The action could not be read back while tracking it; `cause` holds the error. |
| `TIMEOUT` | The action did not reach the awaited status before `pollOptions.timeoutMs`. |

The exception also carries a `detail` (its `message` is `detail` with a `[YieldXyzPerps]` prefix), `broadcastHash` (set when the SDK holds the hash of a leg it knows was broadcast), `transactionHash` (the same hash) and `cause`.

## Activity and events

`getActions(params)` lists the wallet's actions (filter by `marketId`, `type`, `status` or `statuses`) and `getAction(actionId)` reads one. `getEvents(params)` lists venue-side outcomes the user did not initiate, such as order fills, liquidations and stop-loss or take-profit triggers, and `getEvent(eventId)` reads one. `getActivity(params)` interleaves actions and events in a single feed, newest first. Each list method needs a venue (`providerId` or `providerIds`), or it fails with `YieldXyzPerpsException.ProviderRequired` before any request is sent.

```kotlin theme={null}
val perps = portal.perps.yieldxyz

val actions = perps.getActions(YieldXyzPerpsGetActionsParams(limit = 20, providerId = "hyperliquid")).getOrThrow().data
for (item in actions.items) {
    println("${item.id} ${item.action} ${item.status} ${item.completedAt ?: ""}")
}

// Read one action back by id, for example the one createAction returned
val current = perps.getAction(action.id).getOrThrow().data
println("${current.status} ${current.completedAt ?: ""}")

val events = perps.getEvents(
    YieldXyzPerpsGetEventsParams(
        providerId = "hyperliquid",
        eventTypes = listOf(YieldXyzPerpsEventType.ORDER_FILLED, YieldXyzPerpsEventType.LIQUIDATION),
    ),
).getOrThrow().data
events.items.firstOrNull()?.let { first ->
    val event = perps.getEvent(first.id).getOrThrow().data
    println("${event.eventType} ${event.occurredAt} ${event.order.marketId}")
}

val activity = perps.getActivity(YieldXyzPerpsGetActivityParams(limit = 20, providerId = "hyperliquid")).getOrThrow().data
for (item in activity.items) {
    when (item) {
        is YieldXyzPerpsActivityItem.Event -> println("event ${item.event.eventType}")
        is YieldXyzPerpsActivityItem.Action -> println("action ${item.action.action} ${item.action.status}")
        is YieldXyzPerpsActivityItem.Unknown -> println("unknown activity type ${item.type}")
    }
}
```

The list methods take `offset` and `limit` (from `1` to `100`) and return a page in `data`, with `total`, `offset`, `limit` and `items`. `getEvents` also filters by `eventType` or `eventTypes`, `marketId`, `perpActionId`, `providerOrderId` and `fromDate` / `toDate` (ISO-8601). `getActivity` also takes `actionStatus` or `actionStatuses`, which narrow only the action items of the feed.

## Values Yield.xyz may add

Enumerations of Yield.xyz data, such as statuses, action and transaction types, signing formats, event types, sides, margin modes and order types, are plain `String` fields. The known values are constants in objects named after them, such as `YieldXyzPerpsActionStatus.SUCCESS`, `YieldXyzPerpsTransactionStatus`, `YieldXyzPerpsActionType`, `YieldXyzPerpsSigningFormat`, `YieldXyzPerpsEventType`, `YieldXyzPerpsSide`, `YieldXyzPerpsMarginMode` and `YieldXyzPerpsOrderType`. A value Yield.xyz adds later reaches you unchanged instead of failing the response, so compare against the constants in a `when` with an `else` branch. A few fields have no constants object: an event order's `side` (`buy` or `sell`) and `timeInForce`, and a summary's `type`, `method` and `cancelledOrderTypes`. The SDK's own `YieldXyzPerpsExecutionStep` and `YieldXyzPerpsExecutionErrorReason`, and the `YieldXyzPerpsSortOrder` request parameter, are enums you can match exhaustively. An activity item of an unknown `type` decodes as `YieldXyzPerpsActivityItem.Unknown`, with its `type` and the item as a `JsonObject` in `raw`.

On requests, the Portal API accepts only the known values for `createAction`'s `action` and for the `type`, `status`, `statuses`, `eventType`, `eventTypes`, `actionStatus` and `actionStatuses` filters, and rejects any other value with a `400`.

## Low-level APIs

`signAndSubmitAction` covers signing, submitting and tracking. To change only how a transaction is signed, prefer the per-call `signTypedData` and `signAndSendTransaction` options (see [Using your own signers](#using-your-own-signers)): they receive the payload already prepared. If you sign the transactions yourself instead, prepare them as the SDK does before you sign:

* For `EIP712_TYPED_DATA`, add `types.EIP712Domain` when it is missing, derived from the `domain` fields that are present. Portal's signer needs it, and the Portal API verifies the signature against the same hash.
* For `EVM_TRANSACTION`, send only `from`, `to`, `data` and `value`, with `value` as a canonical hex quantity (`0x0`, not a decimal or `0x00`). Leave out `gas`, so the signer estimates it when it sends, and pass the idempotency key `yieldxyz-perps-<transactionId>`, the one `signAndSubmitAction` uses, so a later resume with it can't broadcast the leg twice while Portal remembers the key.

Then use the low-level methods with the [Enclave MPC API signing flow](https://docs.portalhq.io/apis/enclave-mpc/guide/yield-xyz-perps.md#transaction-processing) as the reference for the order of calls:

| Method | Description |
| - | - |
| `submitTransaction(params)` | Submits a signature (`transactionId`, `actionId` and `signedPayload`; the Portal API needs `actionId` to verify the signer), or the hash of an on-chain leg you broadcast (`transactionId` and `transactionHash`). Returns `status`, `link`, `transactionHash`, `error` and `details` in `data`; a `status` of `FAILED` means the venue rejected the transaction even though the request succeeded. |
| `getHealth()` | Returns the integration's health: `status` (`OK` or `FAIL`) and `timestamp`. |
| `getProvidersHealth()` | Returns each venue's state: `generatedAt` and `providers`, each with `providerId`, `state` (`healthy`, `degraded` or `down`), `message` and `setAt`. |

```kotlin theme={null}
val transaction = action.transactions.firstOrNull() ?: return

val submitted = portal.perps.yieldxyz.submitTransaction(
    YieldXyzPerpsSubmitTransactionParams(
        transactionId = transaction.id,
        actionId = action.id,
        signedPayload = "0x...", // the EIP-712 signature
    ),
).getOrThrow().data
println("${submitted.status} ${submitted.link}")
```

`submitTransaction` fails with `YieldXyzPerpsException.SubmissionRequired` before any request is sent when neither `signedPayload` nor `transactionHash` is given, and with `ActionIdRequired` when `signedPayload` comes without `actionId`. There is no step method in Perps: poll `getAction(actionId)` until the action reaches a final status, and sign the transactions Yield.xyz adds while it is `WAITING_FOR_NEXT`.

## Testing

`portal.perps.yieldxyz` is a `YieldXyzPerps`, an `open` class whose methods are all `open`. To test code that trades perps without reaching the Portal API, have it take a `YieldXyzPerps` and pass a subclass that overrides the methods it calls. The class's public constructor takes a `YieldXyzPerpsApi`, so a test subclass can be built around one created with test credentials; its overridden methods never call it.

## Best practices

1. **Show the `summary`** (`direction`, `size`, `leverage`, `collateral`, `estimatedLiquidationPrice`) before the user signs: Portal adds no trading guardrails
2. **Fund and approve first**: a position cannot open until the trading account has collateral and the approvals the venue requires are complete
3. **Respect the venue's limits** before building an action, for example Hyperliquid's 5 USDC `bridge2` minimum and its minimum order notional
4. **Run executions in `viewModelScope` or an application-wide scope**, not in an `Activity`'s `lifecycleScope`, which a rotation cancels, and keep the `Portal` and its approval handler outside the `Activity`
5. **Persist `error.action` and `broadcastHashes`** so a failed execution can be resumed without broadcasting an on-chain leg twice
6. **Handle `INTEGRATION_RESPONSE_SCHEMA_DRIFT`** as a feature outage rather than a user error
7. **Keep gas on the wallet** for the on-chain funding legs

## Supported venues

Perps launches on Hyperliquid; the exact list of live venues is returned by `getProviders()`. On-chain funding legs settle on real chains (for example Arbitrum One, `eip155:42161`), and each needs an `rpcConfig` entry to be signed.

## Next Steps

* Set up the integration: [Yield.xyz Perps](https://docs.portalhq.io/integrations/Yield/yield-xyz-perps.md)
* Use the [Enclave MPC API](https://docs.portalhq.io/apis/enclave-mpc/guide/yield-xyz-perps.md) to trade perps from your backend
* Check out the [Yield.xyz Perps API reference](https://docs.portalhq.io/api-reference/yieldxyz-perps/list-trading-venues.md)
* Approve signing requests with [custom signature hooks](https://docs.portalhq.io/sdks/android/guide/add-custom-signature-hooks.md)
* Learn how Portal uses [idempotency keys](https://docs.portalhq.io/sdks/android/guide/idempotency-keys.md)
* Review [Error handling](https://docs.portalhq.io/sdks/android/guide/error-handling.md) for the `PortalException` hierarchy


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