> ## 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 iOS SDK and the Yield.xyz integration.

Portal's iOS 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 PortalSwift `8.2.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. Every method except `executeAction` and `signAndSubmitAction` returns the Portal API response, a `YieldXyzPerpsResponse` whose `data` holds the result; those two return the execution result itself. 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).

> [!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/ios/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/ios/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 `withRpcConfig`, Portal's default `rpcConfig` covers 11 chains, Arbitrum One included. A `withRpcConfig` you pass replaces the default entirely, so add `eip155:42161` to it (see [Initializing Portal](https://docs.portalhq.io/sdks/ios/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:

```swift theme={null}
import PortalSwift

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

Every account method (`createAction`, `getPositions`, `getOrders`, `getBalances`, `getActions`, `getActivity`, `getEvents`) takes an optional `address` that defaults to the Portal wallet's EVM address. 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 `.signerAddressMismatch` (`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.

```swift theme={null}
let providers = try await portal.perps.yieldxyz.getProviders().data

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

let hyperliquid = try await portal.perps.yieldxyz.getProvider(providerId: "hyperliquid").data
print(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` 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.

```swift theme={null}
let page = try await portal.perps.yieldxyz.getMarkets(params: YieldXyzPerpsGetMarketsParams(
  limit: 10,
  providerId: "hyperliquid",
  sortBy: .volume24h,
  order: .desc
)).data

for market in page.items {
  print(market.id, market.markPrice, market.leverageRange, market.supportedMarginModes)
}

let market = try await portal.perps.yieldxyz.getMarket(marketId: "hyperliquid-eth-usdc").data

let now = Int64(Date().timeIntervalSince1970 * 1000) // unix milliseconds
let candles = try await portal.perps.yieldxyz.getMarketCandles(
  marketId: market.id,
  params: YieldXyzPerpsGetMarketCandlesParams(interval: .oneHour, from: now - 24 * 60 * 60 * 1000)
).data
print(candles.candles.count)
```

`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` | `YieldXyzPerpsMarketSortKey?` | No | `.volume24h`, `.markPrice` or `.priceChangePercent24h`. |
| `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` (`.oneMinute`, `.fiveMinutes`, `.fifteenMinutes`, `.oneHour`, `.fourHours` or `.oneDay`) 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(_:)` signs, submits and tracks it (see [Signing and execution](#signing-and-execution)).

```swift theme={null}
let fund = try await portal.perps.yieldxyz.createAction(params: YieldXyzPerpsCreateActionParams(
  providerId: "hyperliquid",
  action: .fund,
  args: YieldXyzPerpsActionArgs(
    amount: "10", // in source-token units: 10 USDC
    fromToken: YieldXyzPerpsTokenIdentifier(
      network: "eip155:42161",
      address: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831" // USDC on Arbitrum One
    ),
    fundingMethod: .bridge2
  )
)).data

_ = try await portal.perps.yieldxyz.signAndSubmitAction(fund)
```

> [!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: .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` bridges USDC from Arbitrum One, and `.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.

```swift theme={null}
let balance = try await portal.perps.yieldxyz.getBalances(
  params: YieldXyzPerpsBalancesParams(providerId: "hyperliquid")
).data
print(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.

```swift theme={null}
let approval = try await portal.perps.yieldxyz.createAction(params: YieldXyzPerpsCreateActionParams(
  providerId: "hyperliquid",
  action: .approveAgent,
  args: YieldXyzPerpsActionArgs(
    agentAddress: agentAddress, // the address of the agent key your app holds
    agentName: "my-app"
  )
)).data

_ = try await portal.perps.yieldxyz.signAndSubmitAction(approval)
```

## Opening a position

Open a position with `action: .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`.

```swift theme={null}
let open = try await portal.perps.yieldxyz.createAction(params: YieldXyzPerpsCreateActionParams(
  providerId: "hyperliquid",
  action: .open,
  args: YieldXyzPerpsActionArgs(
    marketId: "hyperliquid-eth-usdc",
    side: .long,
    amount: "10", // the size field and its units come from argumentSchemas["open"]
    leverage: 5,
    marginMode: .isolated
  )
)).data

// Show the summary before the user signs: Portal adds no trading guardrails.
if let summary = open.summary {
  print("Direction:", summary.direction?.rawValue ?? "-", "size:", summary.size ?? "-", "leverage:", summary.leverage.map { "\($0)x" } ?? "-")
  print("Collateral:", summary.collateral ?? "-", "estimated liquidation price:", summary.estimatedLiquidationPrice.map { "\($0)" } ?? "-")
}

let result = try await portal.perps.yieldxyz.signAndSubmitAction(open)
print(result.status) // SUCCESS
```

`YieldXyzPerpsCreateActionParams` takes:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `providerId` | `String` | Yes | Venue id from `getProviders()`. |
| `action` | `YieldXyzPerpsActionType` | Yes | `.open`, `.close`, `.updateLeverage`, `.stopLoss`, `.takeProfit`, `.setTpAndSl`, `.cancelOrder`, `.editOrder`, `.updateMargin`, `.fund`, `.withdraw`, `.approveAgent`, `.approveBuilderFee` or `.setUnifiedAccount`. |
| `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). Put any other key a venue's schema asks for in `additionalFields`; 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 `nil`).

`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 `nil` 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` |
| - | - | - |
| `.updateLeverage` | Change a market's leverage | `marketId`, `leverage`, `marginMode` |
| `.setTpAndSl` | Set or update stop-loss and take-profit together | `marketId`, `stopLossPrice`, `takeProfitPrice` |
| `.stopLoss` | Set or update a stop-loss | `marketId`, `stopLossPrice` |
| `.takeProfit` | Set or update a take-profit | `marketId`, `takeProfitPrice` |
| `.updateMargin` | Add or remove margin on an isolated position | `marketId`, `amount` |
| `.editOrder` | Adjust a resting order's price or size | `marketId`, `orderId`, and `limitPrice` or `size` |
| `.cancelOrder` | Cancel one or more resting orders | `marketId`, and `orderId` or `orderIds` |
| `.setUnifiedAccount` | Enable or disable unified-account mode where supported | `enabled` |

```swift theme={null}
let perps = portal.perps.yieldxyz

let leverage = try await perps.createAction(params: YieldXyzPerpsCreateActionParams(
  providerId: "hyperliquid",
  action: .updateLeverage,
  args: YieldXyzPerpsActionArgs(marketId: "hyperliquid-eth-usdc", leverage: 2, marginMode: .isolated)
)).data
_ = try await perps.signAndSubmitAction(leverage)

let protection = try await perps.createAction(params: YieldXyzPerpsCreateActionParams(
  providerId: "hyperliquid",
  action: .setTpAndSl,
  args: YieldXyzPerpsActionArgs(marketId: "hyperliquid-eth-usdc", stopLossPrice: 3600, takeProfitPrice: 4400)
)).data
_ = try await perps.signAndSubmitAction(protection)
```

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: .close`, then withdraw collateral from the trading account with `action: .withdraw`.

```swift theme={null}
let perps = portal.perps.yieldxyz

let close = try await perps.createAction(params: YieldXyzPerpsCreateActionParams(
  providerId: "hyperliquid",
  action: .close,
  args: YieldXyzPerpsActionArgs(marketId: "hyperliquid-eth-usdc")
)).data
_ = try await perps.signAndSubmitAction(close)

let withdraw = try await perps.createAction(params: YieldXyzPerpsCreateActionParams(
  providerId: "hyperliquid",
  action: .withdraw,
  args: YieldXyzPerpsActionArgs(amount: "100")
)).data
_ = try await perps.signAndSubmitAction(withdraw)
```

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.

```swift theme={null}
let perps = portal.perps.yieldxyz

let positions = try await perps.getPositions(params: YieldXyzPerpsPortfolioParams(providerId: "hyperliquid")).data
for position in positions {
  print(position.marketId, position.side, position.size, position.unrealizedPnl, position.liquidationPrice)
}

let orders = try await perps.getOrders(params: YieldXyzPerpsPortfolioParams(providerId: "hyperliquid")).data
let balance = try await perps.getBalances(params: YieldXyzPerpsBalancesParams(providerId: "hyperliquid")).data
print(orders.count, balance.availableBalance)

if let pending = positions.first?.pendingActions.first(where: { $0.type == .close }) {
  let action = try await perps.createAction(params: YieldXyzPerpsCreateActionParams(
    providerId: "hyperliquid",
    action: pending.type,
    args: pending.args
  )).data
  _ = try await perps.signAndSubmitAction(action)
}
```

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`, throws `YieldXyzPerpsError.providerRequired` before any request is sent.

## Signing and execution

### How an action is executed

`signAndSubmitAction(_: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 wait is up to 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 when the action reaches `SUCCESS`. An action that ends `FAILED`, `CANCELED` or `STALE` throws `actionFailed`, and any other failure throws a [`YieldXyzPerpsExecutionError`](#handling-errors), or `CancellationError` when the task is [cancelled](#cancelling-an-execution).

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 `actionInProgress` and signs nothing.

Before signing, the SDK checks that the `signingFormat` is `EIP712_TYPED_DATA` or `EVM_TRANSACTION` (other formats, including Solana, 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 has 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 your `Events.PortalSigningRequested` handler (see [Add custom signature hooks](https://docs.portalhq.io/sdks/ios/guide/add-custom-signature-hooks.md)). A rejected request stops the execution with `signatureRejected`. Without a handler, the request throws before anything is signed, so the execution stops with `signingFailed`.

### Idempotency keys on on-chain legs

Each `EVM_TRANSACTION` leg is sent with the [idempotency key](https://docs.portalhq.io/sdks/ios/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](https://docs.portalhq.io/sdks/ios/guide/configure-log-level.md)). 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 `broadcastOutcomeUnknown`.
* A leg Portal already broadcast fails with `transactionAlreadyBroadcast`. 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 `broadcastOutcomeUnknown`.

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. Don't retry a failed `executeAction` by calling it again: that builds a new action, and can repeat legs that already executed. Resume with `signAndSubmitAction(error.action)` instead.

```swift theme={null}
let result = try await portal.perps.yieldxyz.executeAction(
  params: YieldXyzPerpsCreateActionParams(
    providerId: "hyperliquid",
    action: .updateLeverage,
    args: YieldXyzPerpsActionArgs(marketId: "hyperliquid-eth-usdc", leverage: 1, marginMode: .isolated)
  ),
  options: YieldXyzPerpsExecuteOptions(onProgress: { event in
    print(event.step, event.signingFormat?.rawValue ?? "")
  })
)
print(result.status)
```

When `createAction` fails, `executeAction` throws its error as it is (or `CancellationError` when the task is cancelled), 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(_:)`, a `YieldXyzPerpsError` such as `providerRequired` or `noAddress`, or a transport or decoding error, or a `PortalCredentialError` raised before any request was sent, for which `YieldXyzPerpsApiError.from(_:)` returns `nil` (a `401` from the Portal API is an API error with `status` 401).

### Options

Both methods take a `YieldXyzPerpsExecuteOptions`; the overloads without `options` use the defaults.

| Name | Type | Default | Description |
| - | - | - | - |
| `onProgress` | `((YieldXyzPerpsExecutionProgress) -> Void)?` | `nil` | Called at each execution step. It can run after a transaction was broadcast, so it must not block. |
| `signingChainId` | `String` | `"eip155:42161"` | CAIP-2 chain that EIP-712 signing requests are routed through. Must have an `rpcConfig` entry. |
| `pollAction` | `Bool` | `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` | `intervalSeconds: 2`, `timeoutSeconds: 600` | How the action is read back. The interval (at least 0.25 seconds) 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. |
| `useIdempotencyKeys` | `Bool` | `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?` | `nil` | Per-call typed-data signer. |
| `signAndSendTransaction` | `YieldXyzPerpsSignAndSendTransaction?` | `nil` | Per-call on-chain transaction signer. |
| `waitForConfirmation` | `YieldXyzPerpsWaitForConfirmation?` | `nil` | Per-call confirmation waiter for on-chain legs. Return `true` only when the leg confirmed successfully. |
| `broadcastHashes` | `[String: String]` | `[:]` | 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 up to 15 minutes, and iOS can suspend or end the app in the meantime (see [Resuming a failed execution](#resuming-a-failed-execution)). `onProgress`, like a custom signer, can be called off the main thread, so switch to the main actor before you update your UI.

```swift theme={null}
func onProgress(_ event: YieldXyzPerpsExecutionProgress) {
  switch event.step {
  case .signing:
    print("Signing \(event.signingFormat?.rawValue ?? "") transaction \(event.transactionId ?? "")")
  case .confirming:
    print("Waiting for \(event.transactionHash ?? "") to confirm")
  case .confirmed:
    print("Confirmed \(event.transactionHash ?? "")")
  case .submitted:
    print("Submitted transaction \(event.transactionId ?? "")")
  case .polling:
    print("Action status: \(event.actionStatus?.rawValue ?? "")")
  case .failed:
    print("Stopped: \(event.error?.reason.rawValue ?? "")")
  }
}

_ = try await portal.perps.yieldxyz.signAndSubmitAction(action, options: YieldXyzPerpsExecuteOptions(onProgress: onProgress))
```

### 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` (`nil` when the outcome was confirmed by reading the action back). |

### Cancelling an execution

Cancelling the task that runs `signAndSubmitAction` or `executeAction` stops the SDK's work, not the trade. It throws `CancellationError`, with no `failed` progress event, except in the window between an on-chain leg's broadcast and the submission of its hash: cancelling then fails with `submitOutcomeUnknown`, carrying that leg's `broadcastHash`.

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 send still in flight can still be broadcast, and the SDK has no hash to report.
* An approval your `Events.PortalSigningRequested` handler is showing is not dismissed, and approving it can still sign and send the transaction. Reject any request your handler is still showing when you cancel.

So don't treat `CancellationError` as "nothing happened". Before you offer a new action, read the action with `getAction(actionId:)`, or resume it. `CancellationError` 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`, the key doesn't cover it: check the chain before resuming.

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

```swift theme={null}
// `confirmWithUser` stands for your own confirmation UI: an async function that returns `true` to sign.
let signTypedData: YieldXyzPerpsSignTypedData = { [weak portal] request in
  guard let portal, await confirmWithUser("Sign this Hyperliquid action?") else {
    return nil // stops the execution with signatureRejected
  }
  do {
    let response = try await portal.request(
      chainId: request.chainId,
      method: .eth_signTypedData_v4,
      params: [request.address, request.typedData]
    )
    guard let signature = response.result as? String else {
      throw MyAppError.unexpectedSignerResult // stops the execution with signingFailed
    }
    return signature
  } catch ProviderSigningError.userDeclinedApproval {
    return nil // declined in your Events.PortalSigningRequested handler
  }
}

_ = try await portal.perps.yieldxyz.signAndSubmitAction(
  action,
  options: YieldXyzPerpsExecuteOptions(signTypedData: signTypedData)
)
```

`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 `Events.PortalSigningRequested` handler. This pattern suits a `Portal` created with `autoApprove: true`. A request declined in the handler throws `ProviderSigningError.userDeclinedApproval`; return `nil` for it, as above, so the execution stops with `signatureRejected` rather than `signingFailed`.

`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 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:)`. The key is a `String?`: `nil` when `useIdempotencyKeys` is `false`, or when the transaction id can't form a valid key. Both return `nil` when the request is declined, and a value that isn't a signature or hash should throw rather than return `nil`. Let errors from Portal propagate unchanged. The SDK reads them to tell a failure before the broadcast (`ProviderSigningError`, `PortalCredentialError`, `PortalIdempotencyError`, and a `PortalMpcError` for an auth failure or a refused build, policy or balance), which becomes `signingFailed`, and an idempotency answer, handled as described in [Idempotency keys on on-chain legs](#idempotency-keys-on-on-chain-legs). Any other error from an on-chain send is treated as `broadcastOutcomeUnknown`.

## Resuming a failed execution

A failed execution throws a `YieldXyzPerpsExecutionError` 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 `nil` (as for an unexpected `signingFailed`), 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 being suspended or ended before the error arrives. Once the action succeeds, drop its entries.

```swift theme={null}
var pending: YieldXyzPerpsAction = action
var broadcastHashes: [String: String] = [:] // persist this, and `pending` (Codable), in your app's storage

// Call once to execute, and again only when the user chooses to retry.
func execute() async throws -> YieldXyzPerpsExecutionResult {
  do {
    return try await portal.perps.yieldxyz.signAndSubmitAction(
      pending,
      options: YieldXyzPerpsExecuteOptions(
        onProgress: { event in
          // Record the hash as soon as the on-chain leg is broadcast, and persist it now:
          // iOS can suspend or end the app during the confirmation wait.
          if event.step == .confirming, let transactionId = event.transactionId, let hash = event.transactionHash {
            broadcastHashes[transactionId] = hash
          }
        },
        broadcastHashes: broadcastHashes
      )
    )
  } catch let error as YieldXyzPerpsExecutionError {
    if let transactionId = error.transactionId, let hash = error.broadcastHash {
      broadcastHashes[transactionId] = hash
    }
    pending = error.action ?? pending
    throw error
  }
}

do {
  _ = try await execute()
} catch let error as YieldXyzPerpsExecutionError {
  switch error.reason {
  case .transactionAlreadyBroadcast:
    // Find the leg on-chain and add its hash to broadcastHashes: see "When an on-chain leg may have been sent".
    break
  case .broadcastOutcomeUnknown:
    // What to do depends on Portal's idempotency answer behind the error.
    let causeId = (error.underlyingError as? PortalMpcError)?.id
    if causeId == PortalIdempotencyErrorId.requestInProgress {
      // Still in progress: wait, then call execute() again with keys on.
    } else {
      // Check the chain before you offer a retry (see the table below).
    }
  default:
    // 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.
    break
  }
}
```

### 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/ios/guide/idempotency-keys.md#retry-sendasset)). Legs run in order, so a later leg is never sent before an earlier one is submitted.

`transactionAlreadyBroadcast` means Portal already broadcast the leg under its idempotency key: find the transaction on-chain and resume with its hash in `broadcastHashes`. For `broadcastOutcomeUnknown`, what to do depends on the cause, the `id` of the `PortalMpcError` in `underlyingError`:

| Cause | What to do |
| - | - |
| `PortalIdempotencyErrorId.requestInProgress` | The earlier send is still being processed and may yet broadcast the leg. 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. |
| `.requestPreviouslyFailed`, `.requestUnexpectedState`, `.txMissing` or `.keyReused` | 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` set to `false`. Prefer a new action: `false` turns the keys off for every remaining leg of that call. |
| Anything else, for example an RPC timeout | 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`, the key doesn't cover 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 |
| - | - |
| `actionFailed` | 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. |
| `actionInProgress` | Another call on this Portal instance is already executing the action. This call signed nothing. |
| `signatureRejected`, `pollingFailed`, `timeout` | Resume as is when the user is ready, after fixing a rejected credential (`401`) for `pollingFailed` (with a session credential, sign in again and resume on a new `Portal` instance). An on-chain leg rejected on a retry after `IDEMPOTENT_REQUEST_IN_PROGRESS` may still be broadcast by the earlier send: resume rather than build a new action. |
| `signingFailed` | Signing failed, or an on-chain leg failed before it was broadcast. Check the action before retrying. For an on-chain leg, when Portal's server returned the failure (a `PortalMpcError` 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` set to `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 `Events.PortalSigningRequested` handler, never reached Portal: resume once it is fixed. |
| `transactionAlreadyBroadcast`, `broadcastOutcomeUnknown` | See [When an on-chain leg may have been sent](#when-an-on-chain-leg-may-have-been-sent). |
| `submitOutcomeUnknown` | The submission failed ambiguously, or the task was cancelled after an on-chain leg was broadcast. Check the action before retrying; a signature is never resubmitted automatically. With a `broadcastHash`, resume with it in `broadcastHashes`. |
| `submitRejected` | 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. |
| `submitFailed` | 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. |
| `transactionNotConfirmed` | 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). 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. |
| `invalidSignature` | 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. |
| `signingChainNotConfigured`, `dependencyUnavailable`, `missingWalletAddress` | Raised before the SDK signed the failing transaction, but 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 `withRpcConfig` includes it and resume on that instance. |
| `unsupportedSigningFormat`, `invalidSignablePayload`, `signerAddressMismatch` | 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

Besides transport, decoding and credential errors, four kinds of error reach your app:

* **`YieldXyzPerpsError`**, thrown before any request is sent when the parameters are incomplete: `noAddress`, `providerRequired(method:)`, `submissionRequired`, `actionIdRequired` or `emptyIdentifier(name:)`.
* **Portal API errors**, thrown as `PortalRequestsError` by the read methods, `createAction` and `submitTransaction`, and carried as `underlyingError` by execution errors. `YieldXyzPerpsApiError.from(_:)` returns the API error, with the HTTP `status`, the stable error `id`, the `message` and `details`, whether it was thrown directly or wrapped. It returns `nil` for a transport or decoding error.
* **`YieldXyzPerpsExecutionError`**, thrown by `signAndSubmitAction` and `executeAction`. Branch on its `reason`.
* **`CancellationError`**, when the surrounding task is cancelled (see [Cancelling an execution](#cancelling-an-execution)).

```swift theme={null}
do {
  _ = try await portal.perps.yieldxyz.signAndSubmitAction(action)
} catch {
  if let apiError = YieldXyzPerpsApiError.from(error) {
    if apiError.isEoaRequired {
      print("Perps needs a Portal client without account abstraction.")
    } else if apiError.isSignatureError {
      print("The signature could not be verified; do not retry as is.")
    } else if apiError.isSchemaDrift {
      print("Yield.xyz Perps is temporarily unavailable.")
    } else if apiError.isRateLimit {
      print("Rate limited by Yield.xyz; try again shortly.")
    }
    print(apiError.status ?? 0, apiError.id ?? "", apiError.message ?? "", apiError.code ?? "", apiError.reason ?? "")
  }

  if let executionError = error as? YieldXyzPerpsExecutionError {
    print(executionError.reason, executionError.actionId ?? "", executionError.transactionId ?? "", executionError.broadcastHash ?? "")
  }
}
```

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`. 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 and tolerates up to four consecutive transient failures while reading the action back. After an ambiguous submission failure, 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 static constant:

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

`YieldXyzPerpsExecutionErrorReason` values (the raw value is in parentheses); see [What to do for each reason](#what-to-do-for-each-reason) for how to recover:

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

The error also carries a `message`, `broadcastHash` (set when the SDK holds the hash of a leg it knows was broadcast), `transactionHash` and `underlyingError`.

## 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 throws `YieldXyzPerpsError.providerRequired` before any request is sent.

```swift theme={null}
let perps = portal.perps.yieldxyz

let actions = try await perps.getActions(params: YieldXyzPerpsGetActionsParams(limit: 20, providerId: "hyperliquid")).data
for item in actions.items {
  print(item.id, item.action, item.status, item.completedAt ?? "")
}

// Read one action back by id, for example the one createAction returned
let current = try await perps.getAction(actionId: action.id).data
print(current.status, current.completedAt ?? "")

let events = try await perps.getEvents(params: YieldXyzPerpsGetEventsParams(
  providerId: "hyperliquid",
  eventTypes: [.orderFilled, .liquidation]
)).data
if let first = events.items.first {
  let event = try await perps.getEvent(eventId: first.id).data
  print(event.eventType, event.occurredAt, event.order.marketId)
}

let activity = try await perps.getActivity(params: YieldXyzPerpsGetActivityParams(limit: 20, providerId: "hyperliquid")).data
for item in activity.items {
  switch item {
  case let .event(event):
    print("event", event.eventType)
  case let .action(action):
    print("action", action.action, action.status)
  case let .unknown(type):
    print("unknown activity type", 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

Most enumerations of Yield.xyz data, such as statuses, action and transaction types, signing formats, event types, sides and margin modes, are open values (`YieldXyzOpenValue`). A few fields are plain `String`s instead: an event order's `side` and `timeInForce`, and a summary's `type`, `method` and `cancelledOrderTypes`. The SDK's own `YieldXyzPerpsExecutionStep` and `YieldXyzPerpsExecutionErrorReason`, and the `YieldXyzPerpsSortOrder` request parameter, are closed Swift enums you can switch over exhaustively. An open value is a struct with a `rawValue` and a static constant for each known value, such as `YieldXyzPerpsActionStatus.success`. A value Yield.xyz adds later still decodes, with its `rawValue`, instead of failing the response. Compare against the known constants, and add a fallback for the rest. An activity item of an unknown `type` decodes as `.unknown(type:)`.

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

```swift theme={null}
guard let transaction = action.transactions.first else { return }

let submitted = try await portal.perps.yieldxyz.submitTransaction(params: YieldXyzPerpsSubmitTransactionParams(
  transactionId: transaction.id,
  actionId: action.id,
  signedPayload: "0x..." // the EIP-712 signature
)).data
print(submitted.status, submitted.link)
```

`submitTransaction` throws `YieldXyzPerpsError.submissionRequired` before any request is sent when neither `signedPayload` nor `transactionHash` is given, and `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` is a `Perps`, and `PortalProtocol` exposes it. To use your own implementation in a `PortalProtocol` test double, build the namespace around a `YieldXyzPerpsProtocol` conformance with `Perps(yieldxyz:)`.

## 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. **Persist `error.action` and `broadcastHashes`** so a failed execution can be resumed without broadcasting an on-chain leg twice
5. **Handle `INTEGRATION_RESPONSE_SCHEMA_DRIFT`** as a feature outage rather than a user error
6. **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/ios/guide/add-custom-signature-hooks.md)
* Learn how Portal uses [idempotency keys](https://docs.portalhq.io/sdks/ios/guide/idempotency-keys.md)


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