Skip to main content
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 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 (eip155:42161 for Arbitrum One).
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)
  • An active wallet with collateral (USDC) and gas on the funding chain (see Create a wallet)
  • Yield.xyz integration enabled in your Portal Dashboard (see Yield.xyz Perps)
  • 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).
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.
Perps require a Portal client without account abstraction. 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:
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.
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.
YieldXyzPerpsGetMarketsParams takes: 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).
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 for the venue’s limits.
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.
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.

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.
YieldXyzPerpsCreateActionParams takes: 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.
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).

Closing a position and withdrawing

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

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.
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, 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, or CancellationError when the task is cancelled.
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). 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). 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 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). 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 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.
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.

Progress events

onProgress receives a YieldXyzPerpsExecutionProgress with the step, the actionId and the fields that apply to that step: 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). onProgress, like a custom signer, can be called off the main thread, so switch to the main actor before you update your UI.

Return value

Both methods return a YieldXyzPerpsExecutionResult:

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

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). 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:

What to do for each reason

What each reason means is listed in Handling errors.

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).
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 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). YieldXyzPerpsErrorId holds each id as a static constant: YieldXyzPerpsExecutionErrorReason values (the raw value is in parentheses); see What to do for each reason for how to recover: 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.
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 Strings 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): 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 as the reference for the order of calls:
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