Skip to main content
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 explains how perpetual-futures trading works. Venues are identified by an opaque providerId (for example hyperliquid); real chains, where they appear, use CAIP-2 (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 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:
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 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).
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. 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.
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.
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.
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 (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).
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 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 = 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.
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). leverage and the prices are Doubles: 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.
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 = YieldXyzPerpsActionType.CLOSE, then withdraw collateral from the trading account with action = YieldXyzPerpsActionType.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, 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, 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 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, 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). 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). A rejected request stops the execution with SIGNATURE_REJECTED, except for a retried on-chain send (see 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.
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 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 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 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.
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.

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 about 15 minutes, and Android can stop the app’s process in the meantime (see 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.

Return value

Both methods return a YieldXyzPerpsExecutionResult:

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.

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

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

What to do for each reason

What each reason means is listed in Handling errors.

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).
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 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). YieldXyzPerpsErrorId holds each id as a constant of the same name: YieldXyzPerpsExecutionErrorReason values (each one’s value is the same string); see What to do for each reason for how to recover: 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.
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): 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 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