Skip to main content
Portal’s iOS SDK lets your users lend and borrow on Aave V3, Morpho Blue, SparkLend and Lista through the portal.borrow.yieldxyz API. This guide covers discovering lending markets, building supply, borrow, repay and withdraw actions, and signing, submitting and tracking them with the Portal wallet. Borrow requires PortalSwift 8.2.0 or later.

Overview

With portal.borrow.yieldxyz you can:
  • Discover the lending integrations (protocols) and their markets, with live rates, LTVs, liquidation thresholds and liquidity
  • Supply collateral, borrow against it, repay debt and withdraw collateral
  • Execute an action in one call: the SDK signs each transaction with the Portal wallet, submits it to Yield.xyz, waits for Yield.xyz to confirm it and fetches the next step until the action succeeds
  • Track positions (supply and debt balances, health factor, LTV and available borrow), past actions and liquidations
The Yield.xyz Borrow integration page explains how lending and borrowing work: collateral, maxLtv, the health factor and liquidations. Every method except executeAction and signAndSubmitAction returns the Portal API response, a YieldXyzBorrowResponse whose data holds the result; those two return the execution result itself. Chain ids are CAIP-2 everywhere (eip155:8453 for Base).

Prerequisites

Before using lend and borrow operations, ensure you have:
  • A properly initialized Portal client (see Getting started)
  • An active wallet with the required token(s) and gas on the target network (see Create a wallet)
  • Yield.xyz integration enabled in your Portal Dashboard (see Yield.xyz Borrow)
  • An rpcConfig entry for every chain you sign on. When you don’t pass withRpcConfig, Portal’s default rpcConfig covers five mainnet EVM chains: Ethereum, Base, Arbitrum One, Polygon and Monad. Markets on other chains, such as Optimism, Avalanche or BNB Chain, need you to pass a withRpcConfig that includes them. A withRpcConfig you pass replaces the default entirely, so also list every default chain you still use (see Initializing Portal).
Lending integrations are live on mainnets only: there are no Sepolia, Base Sepolia or Amoy markets. Every signed action moves real funds, so test with small amounts on an inexpensive chain such as Base. The examples below use Aave V3 USDC on Base.
The examples in this guide use a portal instance and the wallet’s EVM address:
For account abstraction enabled clients, this is the smart contract address. Pass it as address in every Borrow call that takes one: Borrow does not default the address.

Discovering integrations

getIntegrations() lists the lending protocols, the networks each supports and the actions each exposes. getIntegration(integrationId:) returns one integration, including the JSON schema of every action’s args.
Integration ids look like aave-borrow, morpho-blue-borrow, sparklend-borrow and lista-borrow; use the ids getIntegrations() returns rather than a fixed list. networks holds CAIP-2 ids for the chains Portal supports and Yield.xyz network names for the others; only the CAIP-2 entries can be passed as network.

Discovering markets

getMarkets(params:) lists lending markets and getMarket(marketId:) returns one by id. Pass scope: .all: when scope is omitted, Yield.xyz lists only the markets enabled for your project, and the Yield.xyz dashboard does not yet support enabling lending markets, so that list is empty.
YieldXyzBorrowGetMarketsParams takes: getMarkets returns a page in data, with total, offset, limit and items. Each item is a YieldXyzBorrowMarket with loanToken, collateralTokens (maxLtv, liquidationThreshold, liquidationPenalty, supplyRate), borrowRate, availableLiquidity, utilizationRate, isBorrowEnabled, minLoan and the fee settings. Rates, amounts and ratios are decimal strings. See the API reference for every field. Treat market ids as opaque values returned by getMarkets: they embed the Yield.xyz network slug, not the CAIP-2 chain id, so do not build them yourself. Many markets hold little liquidity, so filter on availableLiquidity before showing a market to users.

Supplying collateral

Every lending action takes two calls:
  1. createAction(params:) builds the action and returns its unsigned transactions and the predicted impact on the position. Nothing is signed.
  2. signAndSubmitAction(_:) signs each transaction with the Portal wallet, submits it to Yield.xyz and tracks the action until it succeeds (see Signing and execution).
YieldXyzBorrowCreateActionParams takes: The most common args: Fields left nil are not sent. getIntegration(integrationId:) returns the exact schema of each action’s args for an integration. createAction returns the action in data. The action carries its id, its status, the transactions of the current step in signing order, hasNextStep, currentStep and totalSteps, and metadata with the predicted predictedHealthFactor, predictedLtv, predictedTotalSupplyUsd and predictedTotalDebtUsd.
Isolated-market protocols (Morpho Blue) infer the token from marketId, and on them supply only posts collateral: the loan token is borrowed or repaid, never supplied, so passing it as tokenAddress is rejected. When the collateral is a wrapped native token (for example WMON on Monad) and the wallet holds the native token instead, Yield.xyz adds a WRAP transaction before the approval; the SDK signs it like any other transaction. Yield.xyz builds the transactions even when the wallet does not hold the tokens yet: the balance check happens on-chain.

Borrowing

Borrowing uses the same flow with action: .borrow. Supplied assets on Aave are collateral by default, and on isolated-market protocols (Morpho Blue) a supply only posts collateral (see the note above). When a supply balance has isCollateral set to false, for example because you disabled it, run an .enableCollateral action first. Integrations that offer .supplyAndBorrow, which supplies collateral and borrows in one action, list it in getIntegration with the args it accepts.
Show metadata.predictedHealthFactor and metadata.predictedLtv to the user before they sign: a health factor at or below 1 means the position can be liquidated. predictedHealthFactor can be nil when Yield.xyz does not compute it for a market (Morpho Blue on Monad returns null even with open debt); treat nil as unknown, never as safe.

Checking positions

getPositions(params:) returns the wallet’s position on one integration and network.
The position holds the totals (totalSuppliedUsd, totalCollateralUsd, totalBorrowedUsd, netWorthUsd), healthFactor, currentLtv, availableToBorrowUsd, netApy, and the supplyBalances and debtBalances. For isolated-market protocols such as Morpho Blue, the account-level healthFactor and availableToBorrowUsd are always nil: read each supply balance’s positionState instead, which carries that market’s healthFactor, availableToBorrowUsd, currentLtv and liquidationThreshold. A healthFactor is also nil when there is no debt; treat any other nil as unknown. Each balance lists pendingActions, the actions available for it now, with pre-filled args you can pass to createAction:

Repaying and withdrawing

Repay debt with action: .repay (pass repayAll: true to clear the position, which avoids dust from accrued interest), then withdraw collateral with action: .withdraw.
Withdrawing a wrapped native collateral (for example WMON) returns the wrapped token. If your users expect the native token back, unwrap it after the withdraw confirms.

Signing and execution

How an action is executed

signAndSubmitAction(_:options:) executes an action step by step:
  1. It reads the action back from Yield.xyz. The action’s current state decides what still needs signing; the action you pass gives the signing order.
  2. For each transaction of the current step, in order, it signs and broadcasts the transactions awaiting a signature (CREATED or WAITING_FOR_SIGNATURE) with eth_sendTransaction on the transaction’s own chain, with an idempotency key, using the payload Yield.xyz lists at signing time. It submits the on-chain transaction hash to Yield.xyz, then polls until Yield.xyz reports the transaction CONFIRMED or SKIPPED before signing the next one. A transaction in any other status is waited on until it can be signed or is confirmed, so a transaction Yield.xyz has already recorded is never signed again. A transaction 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, while Portal remembers the key (at least 24 hours) and useIdempotencyKeys is on (see Resuming a failed execution).
  3. When the step is confirmed and hasNextStep is true, it fetches the next step with stepAction and repeats.
  4. It returns when the action reaches SUCCESS. Any failure throws a YieldXyzBorrowExecutionError, or CancellationError when the task is cancelled. An action with an empty id throws YieldXyzBorrowError.emptyIdentifier before anything is read or signed.
Pass an action whose transactions are in signing order: the one createAction returned, the action of the latest nextStep progress event, or the action of an execution result or a YieldXyzBorrowExecutionError. getAction may list transactions in a different order. Before signing a transaction, the SDK checks that its signingFormat is EVM_TRANSACTION (the only format Borrow signs), that its network is an EIP-155 chain with an rpcConfig entry, and that the action, the transaction and the payload’s from were all built for the Portal wallet’s EVM address. Only from, to, data and value are forwarded: the signer sets the nonce and fees, and estimates the gas limit when it sends. 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 transaction is signed. Each transaction 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. For account abstraction enabled clients, eth_sendTransaction returns a user operation hash. The SDK waits for the bundle transaction and submits its on-chain hash to Yield.xyz; progress events and results carry both hashes. A call made while another call on the same Portal instance is still executing the same action fails with actionInProgress and signs nothing.

Idempotency keys

Each transaction is sent with the idempotency key yieldxyz-borrow-<transactionId> (a transaction whose 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 transaction 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 after 2, 4 and 8 seconds. 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 transaction Portal already broadcast fails with transactionAlreadyBroadcast. Portal does not return that broadcast’s hash: resume with the broadcastHash the confirming progress event reported, or find the transaction on-chain. If it follows a userOperationFailed for the same transaction, that hash only reproduces the failure: build a new action or resume with useIdempotencyKeys set to false.
  • Any other refusal of the key fails with broadcastOutcomeUnknown.
With presignatures on, a failed presignature attempt falls back to a normal signature under the same key, so broadcastOutcomeUnknown can appear on a first attempt. See When a transaction 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 above when you want to show the predicted health factor before the user signs. Don’t retry a failed executeAction by calling it again: that builds a new action, and can repeat a supply or borrow that already executed. Resume with signAndSubmitAction and the error’s action instead (see Resuming a failed execution).
When createAction fails, executeAction throws its error as it is (or CancellationError when the task is cancelled): no action exists yet, so there is nothing to resume. That is a Portal API error, which you read with YieldXyzBorrowApiError.from(_:), or a transport or decoding error, or a PortalCredentialError raised before any request was sent, for which YieldXyzBorrowApiError.from(_:) returns nil (a 401 from the Portal API is an API error with status 401). No failed progress event is emitted.

Options

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

Progress events

onProgress receives a YieldXyzBorrowExecutionProgress with the step, the actionId and the fields that apply to that step: index counts the transactions this call signed or submitted before this one, across steps. A transaction resumed from broadcastHashes is not signed again, so it starts at confirming. Persist the broadcastHash of a confirming event as soon as it is reported: it is the hash to resume with, and iOS can suspend or end the app while the SDK waits for the transaction. Persist the action of a nextStep event too: resuming that step from it keeps the signing order, which getAction may not. 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 YieldXyzBorrowExecutionResult:

Cancelling an execution

Cancelling the task that runs signAndSubmitAction or executeAction stops the execution with CancellationError. The exception is while a broadcast transaction is being resolved and submitted: cancelling then fails with submitOutcomeUnknown, carrying that transaction’s broadcastHash. A cancellation that lands while the signer is still sending can lose the hash and stop with CancellationError although the transaction was broadcast. Resume with idempotency keys on, within Portal’s key window (at least 24 hours): Portal then broadcasts the transaction at most once, and the resume fails with transactionAlreadyBroadcast or broadcastOutcomeUnknown instead of sending it again, or sends it normally if Portal never received the first request. Don’t resume with useIdempotencyKeys: false without checking the chain first. If the cancelled call itself ran with useIdempotencyKeys: false, no key covers it: check the chain before resuming. Cancelling stops the SDK’s work, not what was already sent: a transaction already broadcast or submitted can still take effect. An approval your Events.PortalSigningRequested handler is showing is not dismissed: the call returns only after your handler answers, and approving it can still send the transaction. Reject any request your handler is still showing when you cancel. A CancellationError emits no failed progress event and carries no action id: with executeAction, keep the actionId every progress event carries, or use createAction and signAndSubmitAction so you hold the action. Before you offer a new action, read the action with getAction(actionId:) or resume it.

Using your own signer

Pass signAndSendTransaction to sign with your own logic, for example to add a confirmation step. It receives the ETHTransactionParam to send (from, to, data and value, with value as a hex quantity, and no gas), the CAIP-2 chain id and the transaction’s idempotency key, and returns the hash, or nil when the request is declined. Pass the key to eth_sendTransaction as RequestOptions(idempotencyKey:); it is nil when useIdempotencyKeys is false, or when the transaction id can’t form a valid key. Each retry of a send Portal reports as still in progress calls your signer again, so your confirmation step runs again too. A value that isn’t a hash should throw rather than return nil. Let a PortalMpcError from Portal propagate unchanged: the SDK reads its id to recognize an idempotency answer. The SDK still checks that every transaction was built for the Portal wallet’s EVM address. A signer that signs through portal.request, like this one, still needs an rpcConfig entry for the chain: without one, the request fails after the approval prompt (when autoApprove is off), the execution stops with signingFailed, and nothing was sent.
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.

Resuming a failed execution

A failed execution throws a YieldXyzBorrowExecutionError that carries the actionId, action (the latest known state of the action, with its transactions in signing order) and, when the failure concerns one transaction, its transactionId. Persist its action (which is Codable), transactionId and broadcastHash, and resume with signAndSubmitAction(error.action ?? pending), where pending is the latest action you persisted (the one createAction returned, or the latest nextStep event’s), passing your broadcastHashes. Prefer these over getAction, which may list the transactions in a different order. If the app was ended between a step being fetched and its nextStep event, the action you persisted is the previous step’s: before resuming, compare its currentStep with getAction(actionId:)’s, and if the action moved on, check the order as described for nextStepFailed. When the error carries a broadcastHash, that transaction was already broadcast and Yield.xyz may not have recorded it yet. Pass it in broadcastHashes, keyed by transaction id, so the SDK resolves and submits it instead of signing it again. The exception is userOperationFailed: that user operation was already processed and did not succeed, so passing its hash only reproduces the failure. Drop its entry, and sign the transaction again with a new action, or by resuming with useIdempotencyKeys set to false, since Portal refuses to send under the same key again. When an earlier step of the action is already confirmed, resume with keys off rather than build a new action, which would repeat it.
Once the action succeeds, drop its broadcastHashes entries.

When a transaction may have been sent

transactionAlreadyBroadcast means Portal already broadcast the transaction under its idempotency key: resume with the broadcastHash the confirming progress event reported, or find the transaction on-chain as described below and resume with its hash in broadcastHashes. To check the chain for a transaction, look it up in a block explorer or indexer that shows each transaction’s to and input data, and match the transaction’s to and data from its signablePayload, considering only transactions sent after the action’s createdAt, so an identical earlier approval doesn’t match. A send Portal is still processing can broadcast late, so wait a little before concluding it wasn’t sent. Conclude that it 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). Transactions run in order, so a later transaction is never sent before an earlier one is confirmed. For an account abstraction enabled client, the transaction runs as a call from the smart contract wallet inside a bundle transaction, so no top-level transaction from the wallet matches and the nonce rule doesn’t apply. Search the wallet’s internal transactions or user operations for a call with that to and data. Resume with the user operation hash (broadcastHash) in broadcastHashes. Use the hash of the bundle transaction you found only when you don’t have the user operation hash, and only after confirming the inner call succeeded: with a bundle hash the SDK can’t detect a failed user operation. If you can’t rule the send out, don’t build a new action or turn the keys off. What to do after broadcastOutcomeUnknown depends on its cause, the id of the PortalMpcError in underlyingError:

After signingFailed

Borrow reports every send failure that isn’t an idempotency answer as signingFailed, whether or not the transaction reached the chain:
  • The SDK raised it: underlyingError is a ProviderSigningError (for example no Events.PortalSigningRequested handler), a PortalCredentialError, a PortalIdempotencyError, or a provider error for a chain with no rpcConfig entry (from a custom signer). It never reached Portal. Resume once it is fixed.
  • Portal’s server refused the send before broadcasting it: a PortalMpcError whose id is MSG_BUILD_FAILED, TX_BUILD_FAILED, BAD_REQUEST, ADDRESS_BLOCKED, POLICY_AMOUNT_LIMIT_EXCEEDED or INSUFFICIENT_FUNDS. Nothing was sent, but with keys on Portal refuses that key afterwards: once the cause is fixed, build a new action, or resume with useIdempotencyKeys set to false. When an earlier step of the action is already confirmed, resume with keys off rather than build a new action, which would repeat it.
  • Anything else, such as RPC_OP_FAILED or a timeout, may come after the broadcast: the transaction may have been sent without its hash being returned. With keys on, a resume within 24 hours can’t send it twice: Portal answers with transactionAlreadyBroadcast or broadcastOutcomeUnknown, or sends it normally if it never received the first request. With useIdempotencyKeys set to false, or after that window, check the chain before retrying; if the transaction was sent, resume with its hash in broadcastHashes.
  • Without a transactionId, it is an unexpected error not tied to a specific transaction: check the action with getAction before retrying.
If you’re unsure which case applies and the failed call ran with idempotency keys on, within the last 24 hours, resume with keys on: it can’t send twice, and if Portal then answers requestPreviouslyFailed, follow broadcastOutcomeUnknown.

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:
  • YieldXyzBorrowError, thrown before any request is sent: submissionRequired when submitTransaction gets neither a hash nor a signed payload, and emptyIdentifier(name:) when an id sent in the request path (such as marketId or actionId) is empty.
  • Portal API errors, thrown as PortalRequestsError by the read methods, createAction, stepAction and submitTransaction, and carried as underlyingError by execution errors. YieldXyzBorrowApiError.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.
  • YieldXyzBorrowExecutionError, 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, unsupported chain id, a request Yield.xyz rejected, or a missing or rejected Yield.xyz API key), 404, 429, 503, or 500 with id: INTEGRATION_RESPONSE_SCHEMA_DRIFT when Yield.xyz changed a response shape. See Errors on the integration page. While executing, the SDK retries rate-limited (429) submissions and step requests and tolerates up to four consecutive transient failures while reading the action or a transaction back. After an ambiguous submission failure, it resubmits the transaction hash once, and only if the action shows Yield.xyz did not record it. A signature is never requested again, except that a send Portal reports as still in progress is sent again with the same idempotency key (see Idempotency keys). YieldXyzBorrowExecutionErrorReason 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 (the hash the signer returned, set when the SDK holds the hash of a transaction it knows was broadcast), transactionHash (the on-chain hash, once known), userOperationHash and underlyingError.

History and liquidations

getActions(params:) lists the wallet’s actions, filtered by integrationId, action, status or statuses, and getAction(actionId:) reads one action. getLiquidations(params:) returns a position’s liquidation history (Morpho Blue integrations only).
Both list methods take offset and limit (at most 100) and return a page in data, with total, offset, limit and items.

Values Yield.xyz may add

Statuses, action and transaction types, signing formats, market types and the other enumerations of Yield.xyz data are open values (YieldXyzOpenValue). The exceptions are the SDK’s own YieldXyzBorrowExecutionStep and YieldXyzBorrowExecutionErrorReason, and YieldXyzBorrowMarketScope, which 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 YieldXyzBorrowActionStatus.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.

Low-level APIs

signAndSubmitAction covers signing, submitting and stepping. To change only how a transaction is signed, prefer the per-call signAndSendTransaction option (see Using your own signer): it receives the transaction already prepared. If you drive the transactions yourself instead, prepare each one as the SDK does: 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-borrow-<transactionId>, the one signAndSubmitAction uses, so a later resume can’t broadcast the transaction twice while Portal remembers the key. Then use the low-level methods with the Enclave MPC API transaction flow as the reference for the order of calls:
Each transaction’s signablePayload is the unsigned transaction, JSON-encoded or as an object. For account abstraction enabled clients, submit the on-chain transaction hash, never the user operation hash: read it from eth_getUserOperationReceipt (result.receipt.transactionHash) or with portal.getTransactionDetails(chain:signature:).

Testing

portal.borrow is a Borrow, and PortalProtocol exposes it. To use your own implementation in a PortalProtocol test double, build the namespace around a YieldXyzBorrowProtocol conformance with Borrow(yieldxyz:).

Best practices

  1. Show the predicted health factor and LTV from metadata before the user signs a borrow or withdraw: build with createAction, then execute with signAndSubmitAction
  2. Persist error.action and broadcastHashes so a failed execution can be resumed without signing a transaction twice
  3. Use repayAll when closing a position so accrued interest does not leave dust
  4. Pass scope: .all and filter markets to the ones your UI offers, for example by availableLiquidity
  5. Handle INTEGRATION_RESPONSE_SCHEMA_DRIFT as a feature outage rather than a user error
  6. Keep gas on the wallet: every transaction is on-chain

Supported networks

Lending integrations run on mainnets only; the exact list per protocol is returned by getIntegrations() (networks; CAIP-2 for the chains Portal supports). Aave V3 covers the major EVM chains (Ethereum eip155:1, Base eip155:8453, Arbitrum eip155:42161, Optimism eip155:10, Polygon eip155:137, Avalanche eip155:43114, and more); Morpho Blue covers Ethereum, Base, Monad (eip155:143) and other EVM chains; SparkLend is Ethereum-only; Lista runs on BNB Chain (eip155:56) and Ethereum. Signing needs an rpcConfig entry for the transaction’s chain. The default rpcConfig covers five mainnet EVM chains, Ethereum, Base, Arbitrum One, Polygon and Monad; add any other chain, such as Optimism, Avalanche or BNB Chain, yourself.

Next Steps