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

# Lend and borrow with Yield.xyz

> Learn how to supply collateral, borrow, repay and withdraw on lending protocols with the iOS SDK and the Yield.xyz integration.

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](https://docs.portalhq.io/integrations/Yield/yield-xyz-borrow.md#how-lending-and-borrowing-works) 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](https://docs.portalhq.io/resources/chain-id-formatting.md) everywhere (`eip155:8453` for Base).

## Prerequisites

Before using lend and borrow 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 the required token(s) **and gas** on the target network (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 Borrow](https://docs.portalhq.io/integrations/Yield/yield-xyz-borrow.md))
* 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](https://docs.portalhq.io/sdks/ios/guide/getting-started.md#initializing-portal)).

> [!WARNING]
>
> 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:

```swift theme={null}
import PortalSwift

// Without withRpcConfig, Portal's default rpcConfig covers Base (eip155:8453).
let portal = try Portal("YOUR_CLIENT_API_KEY_OR_CLIENT_SESSION_TOKEN")

guard let address = await portal.getAddress("eip155:8453") else {
  throw MyAppError.noWallet // the wallet has no EVM address yet
}
```

For [account abstraction](https://docs.portalhq.io/resources/account-abstraction.md) 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`.

```swift theme={null}
let integrations = try await portal.borrow.yieldxyz.getIntegrations().data

for integration in integrations {
  print(
    integration.id, // e.g. aave-borrow
    integration.networks, // e.g. ["eip155:1", "eip155:8453", ...]
    integration.actions.map(\.id) // e.g. [supply, borrow, repay, withdraw, ...]
  )
}

let aave = try await portal.borrow.yieldxyz.getIntegration(integrationId: "aave-borrow").data
let supplyArgsSchema = aave.actions.first(where: { $0.id == .supply })?.schema
print(supplyArgsSchema ?? [:])
```

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.

```swift theme={null}
let page = try await portal.borrow.yieldxyz.getMarkets(params: YieldXyzBorrowGetMarketsParams(
  limit: 50,
  integrationId: "aave-borrow",
  network: "eip155:8453",
  scope: .all
)).data

for market in page.items {
  print(market.id, market.loanToken.symbol, market.borrowRate, market.availableLiquidity)
}

let market = try await portal.borrow.yieldxyz.getMarket(
  marketId: "aave-borrow-base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"
).data
for collateral in market.collateralTokens {
  print("\(collateral.token.symbol): max LTV \(collateral.maxLtv), liquidation threshold \(collateral.liquidationThreshold)")
}
```

`YieldXyzBorrowGetMarketsParams` takes:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `offset` | `Int?` | No | Pagination offset. |
| `limit` | `Int?` | No | Page size, at most `100`. |
| `integrationId` | `String?` | No | Only markets of this integration. |
| `network` | `String?` | No | CAIP-2 chain id, for example `eip155:8453`. |
| `scope` | `YieldXyzBorrowMarketScope?` | No | `.all` lists every market Yield.xyz supports; `.enabled` (what Yield.xyz applies when omitted) lists only the markets enabled for your project. |

`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](https://docs.portalhq.io/api-reference/yieldxyz-borrow/list-lending-markets.md) 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](#signing-and-execution)).

```swift theme={null}
let action = try await portal.borrow.yieldxyz.createAction(params: YieldXyzBorrowCreateActionParams(
  integrationId: "aave-borrow",
  action: .supply,
  address: address,
  args: YieldXyzBorrowActionArguments(
    marketId: "aave-borrow-base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
    amount: "5",
    tokenAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" // USDC on Base
  )
)).data

// Show the predicted impact before the user signs. A nil health factor means unknown, never safe.
print("Predicted health factor:", action.metadata?.predictedHealthFactor ?? "unknown")
print("Predicted LTV:", action.metadata?.predictedLtv ?? "unknown")
print(action.transactions.map(\.type)) // e.g. [APPROVAL, SUPPLY]

let result = try await portal.borrow.yieldxyz.signAndSubmitAction(action)
print(result.status, result.transactions.map(\.transactionHash))
```

`YieldXyzBorrowCreateActionParams` takes:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `integrationId` | `String` | Yes | Integration id from `getIntegrations()`. |
| `action` | `YieldXyzBorrowActionType` | Yes | `.supply`, `.borrow`, `.repay`, `.withdraw`, `.enableCollateral`, `.disableCollateral` or `.supplyAndBorrow`. |
| `address` | `String` | Yes | The wallet's EVM address (the smart contract address for account abstraction enabled clients). The SDK signs only actions built for the Portal wallet's address. |
| `args` | `YieldXyzBorrowActionArguments` | Yes | The action's arguments; always includes `marketId`. |

The most common `args`:

| Field | Description |
| - | - |
| `marketId` | Market id, exactly as `getMarkets` returned it. Always required. |
| `amount` | Human-readable amount, for example `"1.5"`. Provide either `amount` or `amountRaw`. |
| `amountRaw` | Amount in raw token units. |
| `repayAll` | `.repay` only: repay the whole debt. Omit `amount` and `amountRaw`. |
| `tokenAddress` | Required for `.supply` and `.withdraw` on pool-based protocols (Aave): the market's `loanToken.address`, or one of `collateralTokens[].token.address`. |
| `collateralTokenAddress`, `collateralAmount`, `collateralAmountRaw`, `borrowAmount`, `targetLtv` | Accepted only by some actions; check the action's schema in `getIntegration` before you pass them. |

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

> [!NOTE]
>
> 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.

```swift theme={null}
let marketId = "aave-borrow-base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"

let borrowAction = try await portal.borrow.yieldxyz.createAction(params: YieldXyzBorrowCreateActionParams(
  integrationId: "aave-borrow",
  action: .borrow,
  address: address,
  args: YieldXyzBorrowActionArguments(marketId: marketId, amount: "2")
)).data

print("Health factor after borrowing:", borrowAction.metadata?.predictedHealthFactor ?? "unknown")

_ = try await portal.borrow.yieldxyz.signAndSubmitAction(borrowAction)
```

> [!NOTE]
>
> 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.

```swift theme={null}
let position = try await portal.borrow.yieldxyz.getPositions(params: YieldXyzBorrowGetPositionsParams(
  integrationId: "aave-borrow",
  network: "eip155:8453",
  address: address
)).data

print("Health factor:", position.healthFactor ?? "unknown")
print("Supplied:", position.totalSuppliedUsd, "Borrowed:", position.totalBorrowedUsd)

for balance in position.debtBalances {
  print(balance.tokenSymbol, balance.balance, balance.pendingActions.map(\.type))
}
```

| Parameter | Type | Required | Description |
| - | - | - | - |
| `integrationId` | `String` | Yes | Integration id. |
| `network` | `String` | Yes | CAIP-2 chain id. |
| `address` | `String` | Yes | The wallet's EVM address. |

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

```swift theme={null}
if let repay = position.debtBalances.first?.pendingActions.first(where: { $0.type == .repay }) {
  let action = try await portal.borrow.yieldxyz.createAction(params: YieldXyzBorrowCreateActionParams(
    integrationId: position.integrationId,
    action: .repay,
    address: address,
    args: repay.args
  )).data
  _ = try await portal.borrow.yieldxyz.signAndSubmitAction(action)
}
```

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

```swift theme={null}
let marketId = "aave-borrow-base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"
let borrow = portal.borrow.yieldxyz

let repay = try await borrow.createAction(params: YieldXyzBorrowCreateActionParams(
  integrationId: "aave-borrow",
  action: .repay,
  address: address,
  args: YieldXyzBorrowActionArguments(marketId: marketId, repayAll: true)
)).data
_ = try await borrow.signAndSubmitAction(repay)

let withdraw = try await borrow.createAction(params: YieldXyzBorrowCreateActionParams(
  integrationId: "aave-borrow",
  action: .withdraw,
  address: address,
  args: YieldXyzBorrowActionArguments(
    marketId: marketId,
    amount: "5",
    tokenAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
  )
)).data
_ = try await borrow.signAndSubmitAction(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](#idempotency-keys), 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](#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`](#handling-errors), or `CancellationError` when the task is [cancelled](#cancelling-an-execution). 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](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`.

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](https://docs.portalhq.io/sdks/ios/guide/idempotency-keys.md) `yieldxyz-borrow-<transactionId>` (a transaction whose 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 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](#when-a-transaction-may-have-been-sent). 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](https://docs.portalhq.io/sdks/ios/guide/idempotency-keys.md#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](#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](#resuming-a-failed-execution)).

```swift theme={null}
let result = try await portal.borrow.yieldxyz.executeAction(
  params: YieldXyzBorrowCreateActionParams(
    integrationId: "aave-borrow",
    action: .borrow,
    address: address,
    args: YieldXyzBorrowActionArguments(
      marketId: "aave-borrow-base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
      amount: "2"
    )
  ),
  options: YieldXyzBorrowExecuteOptions(onProgress: { event in
    print(event.step, event.transactionId ?? "")
  })
)
print(result.status)
```

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.

| Name | Type | Default | Description |
| - | - | - | - |
| `onProgress` | `((YieldXyzBorrowExecutionProgress) -> Void)?` | `nil` | Called at each execution step. It can run after a transaction was broadcast, so it must not block. |
| `pollOptions` | `YieldXyzBorrowPollOptions` | `intervalSeconds: 2`, `timeoutSeconds: 600` | How the action, and the on-chain hash of a broadcast transaction, are 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: for a transaction to be signable, to be resolved on-chain, or to be confirmed by Yield.xyz, and for the step's outcome. |
| `useIdempotencyKeys` | `Bool` | `true` | Whether to send each transaction with its idempotency key. See [Idempotency keys](#idempotency-keys). |
| `signAndSendTransaction` | `YieldXyzBorrowSignAndSendTransaction?` | `nil` | Per-call signer used instead of the Portal wallet's. The SDK skips its own `rpcConfig` check for it, but a signer that signs through `portal.request`, like the one below, still needs the chain's `rpcConfig` entry. |
| `broadcastHashes` | `[String: String]` | `[:]` | Transactions an earlier attempt already broadcast, by transaction id. They are never signed again. See [Resuming a failed execution](#resuming-a-failed-execution). |

### Progress events

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

| `step` | Meaning | Fields |
| - | - | - |
| `.signing` | About to sign a transaction. | `transactionId`, `index` |
| `.confirming` | The transaction was broadcast; the SDK is resolving its on-chain hash (an account abstraction enabled client waits for inclusion). | `transactionId`, `index`, `broadcastHash` |
| `.submitted` | Yield.xyz accepted the on-chain transaction hash. | `transactionId`, `index`, `transactionHash`, `userOperationHash` |
| `.polling` | The action was read back. | `actionStatus` |
| `.confirmed` | Yield.xyz reports the transaction `CONFIRMED` or `SKIPPED`. | `transactionId`, `index`, `transactionHash`, `userOperationHash` |
| `.nextStep` | The next step's transactions were fetched. | `currentStep`, `totalSteps`, `actionStatus`, `action` |
| `.failed` | Execution stopped. | `error`, plus the transaction's id and hashes when known |

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

```swift theme={null}
func onProgress(_ event: YieldXyzBorrowExecutionProgress) {
  switch event.step {
  case .signing:
    print("Signing transaction \(event.transactionId ?? "")")
  case .confirming:
    print("Broadcast \(event.broadcastHash ?? "")")
  case .confirmed:
    print("Confirmed \(event.transactionHash ?? "")")
  case .nextStep:
    print("Step \(event.currentStep ?? 0) of \(event.totalSteps ?? 0)")
  case .failed:
    print("Stopped: \(event.error?.reason.rawValue ?? "")")
  case .submitted, .polling:
    break
  }
}

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

### Return value

Both methods return a `YieldXyzBorrowExecutionResult`:

| Field | Description |
| - | - |
| `actionId` | The action id. |
| `action` | The latest state of the action, with its transactions in signing order. |
| `status` | The action's final status (`SUCCESS`). |
| `transactions` | One `YieldXyzBorrowTransactionExecution` per transaction this call signed or submitted: `transactionId`, `type`, `transactionHash` (the on-chain hash reported to Yield.xyz), `userOperationHash` (account abstraction enabled clients only) and `submitResult` (`nil` when the submission's outcome was confirmed by reading the action back). |

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

```swift theme={null}
// `confirmWithUser` stands for your own confirmation UI: an async function that returns `true` to send.
let signAndSendTransaction: YieldXyzBorrowSignAndSendTransaction = { [weak portal] transaction, chainId, idempotencyKey in
  guard let portal, await confirmWithUser("Send this transaction to \(transaction.to) on \(chainId)?") else {
    return nil // stops the execution with signatureRejected
  }
  do {
    let response = try await portal.request(
      chainId: chainId,
      method: .eth_sendTransaction,
      params: [transaction],
      options: idempotencyKey.map { RequestOptions(idempotencyKey: $0) }
    )
    guard let hash = response.result as? String else {
      throw MyAppError.unexpectedSignerResult // stops the execution with signingFailed
    }
    return hash
  } catch ProviderSigningError.userDeclinedApproval {
    return nil // declined in your Events.PortalSigningRequested handler
  }
}

_ = try await portal.borrow.yieldxyz.signAndSubmitAction(
  action,
  options: YieldXyzBorrowExecuteOptions(signAndSendTransaction: signAndSendTransaction)
)
```

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

```swift theme={null}
var pending: YieldXyzBorrowAction = 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 -> YieldXyzBorrowExecutionResult {
  do {
    return try await portal.borrow.yieldxyz.signAndSubmitAction(
      pending,
      options: YieldXyzBorrowExecuteOptions(
        onProgress: { event in
          // Persist the hash as soon as the transaction is broadcast, and the new step's action:
          // iOS can suspend or end the app while the SDK waits.
          if event.step == .confirming, let transactionId = event.transactionId, let hash = event.broadcastHash {
            broadcastHashes[transactionId] = hash
          }
          if event.step == .nextStep, let action = event.action {
            pending = action
          }
        },
        broadcastHashes: broadcastHashes
      )
    )
  } catch let error as YieldXyzBorrowExecutionError {
    if let transactionId = error.transactionId {
      if error.reason == .userOperationFailed ||
        (error.reason == .invalidTransactionHash && error.broadcastHash != nil) {
        // Already processed, or a bad value you passed in broadcastHashes. An invalid value from your
        // signer has no broadcastHash: it may follow a broadcast, so check the chain (see the table below).
        broadcastHashes[transactionId] = nil
      } else if let hash = error.broadcastHash {
        broadcastHashes[transactionId] = hash
      }
    }
    pending = error.action ?? pending
    throw error
  }
}

do {
  _ = try await execute()
} catch let error as YieldXyzBorrowExecutionError {
  switch error.reason {
  case .transactionAlreadyBroadcast:
    // Resume with the hash from the confirming event, or find the transaction on-chain and add its hash.
    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 "When a transaction may have been sent").
    }
  case .userOperationFailed:
    // Already processed and not successful: build a new action, or resume with useIdempotencyKeys set to false.
    break
  case .signingFailed where error.transactionId != nil:
    // The transaction may have been sent without its hash coming back. With idempotency keys on, a resume
    // can't send it twice; with them off, check the chain first.
    break
  default:
    // Persist `pending` and `broadcastHashes`, and call execute() again when the user retries.
    // Check the reason in the table below before you offer a retry.
    break
  }
}
```

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](https://docs.portalhq.io/sdks/ios/guide/idempotency-keys.md#retry-sendasset)). 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`:

| Cause | What to do |
| - | - |
| `PortalIdempotencyErrorId.requestInProgress` | The earlier send is still being processed and may yet broadcast the transaction. 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 transaction was sent, resume with its hash in `broadcastHashes`. If it was not sent and nothing is pending, build a new action (its transactions get new keys), or resume this one with `useIdempotencyKeys` set to `false`. Prefer a new action, since `false` turns the keys off for every remaining transaction of that call, unless an earlier step of the action is already confirmed: a new action would repeat it. |

### 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](#when-a-transaction-may-have-been-sent) 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).

| Reason | What to do |
| - | - |
| `actionFailed` | The action ended as `FAILED`, `CANCELED` or `STALE`. It cannot be resumed. Transactions this call or an earlier one confirmed may already have taken effect, for example a supply or a borrow of a multi-step action. When `error.broadcastHash` is set, or your `broadcastHashes` hold a hash for this action, that transaction was broadcast and may still confirm: wait for its receipt first. Then check the position with `getPositions` before you create another action, or you may repeat them. |
| `actionInProgress` | Another call on this Portal instance is already executing the action. This call signed nothing: don't resume or build a new action; wait for the running call's result. |
| `signatureRejected` | Resume when the user is ready. A transaction rejected on a retry after `IDEMPOTENT_REQUEST_IN_PROGRESS` may still be broadcast by the earlier send: resume rather than build a new action. |
| `signingChainNotConfigured`, `dependencyUnavailable`, `missingWalletAddress` | Raised before the SDK signed the failing transaction, but earlier transactions of the action, in this step or an earlier one, may already have been submitted. The cause is on the device: fix it, then resume the same action, whose confirmed 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`, `unsupportedNetwork`, `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 `getPositions`) before you create another. |
| `signingFailed` | Signing or broadcasting failed. What to do depends on where it failed: see [After `signingFailed`](#after-signingfailed). |
| `transactionAlreadyBroadcast`, `broadcastOutcomeUnknown` | See [When a transaction may have been sent](#when-a-transaction-may-have-been-sent). |
| `invalidTransactionHash` | When `error.broadcastHash` is set, the bad value came from your `broadcastHashes`: nothing was sent, so drop or fix that entry. Otherwise it came from your signer, and the transaction may already have been sent. With keys on and a signer that passes the key to Portal, a resume can't send it twice; otherwise check the chain before you resume, since resuming signs it again. |
| `transactionFailed`, `submitFailed` | Yield.xyz reports the transaction as `FAILED`, so resuming fails the same way. It was broadcast and most likely reverted: check its receipt (`transactionHash` or `broadcastHash`) and the position with `getPositions`, then create a new action. |
| `userOperationFailed` | The user operation was included on-chain but did not succeed. Drop its `broadcastHashes` entry, and build a new action, or resume with `useIdempotencyKeys` set to `false`. When an earlier step of a multi-step action is already confirmed, a new action would repeat it: resume with keys off instead, or check `getPositions` and build an action for only what remains. |
| `submitOutcomeUnknown` | The submission failed ambiguously, or was cancelled. Check the action before retrying. With a `broadcastHash`, resume with it in `broadcastHashes`. |
| `submitRejected` | Submitting the on-chain hash was rejected, for example because the session expired. The transaction was already broadcast (`broadcastHash`): fix the cause and resume with the hash in `broadcastHashes`, never with a new action. |
| `pollingFailed`, `timeout` | Reading the action or a transaction back failed, or did not reach the awaited status in time. A rejected credential (`401`) fails polling at once: fix it first (with a session credential, sign in again and resume on a new `Portal` instance). With a `broadcastHash`, the transaction was broadcast: resume with it in `broadcastHashes`, not with a new action. The exception is a transaction that was dropped (or a user operation that was never included): when the chain doesn't know the hash and the wallet's nonce has moved past it (for a user operation, the smart contract wallet's EntryPoint nonce), every resume times out again, so check the position and create a new action, or, when an earlier step is confirmed, drop its `broadcastHashes` entry and resume with `useIdempotencyKeys` set to `false`. Without a `broadcastHash`, check the action with `getAction` and resume. |
| `nextStepFailed` | The next step could not be fetched or had nothing to sign. Yield.xyz may have moved to the next step anyway, so `error.action` can still be the previous step's; resuming from it signs the new step's transactions in the order `getAction` lists them, which may not be their signing order. If the new step has several transactions awaiting a signature, check their order before resuming: an approval must be signed before the transaction that spends it. If the order is wrong, resume with a `YieldXyzBorrowAction` whose `transactions` you put in signing order (a `WRAP` first, then the `APPROVAL`, then the transaction that spends it), or, after checking with `getPositions` what the confirmed steps already did, create a new action for only what remains. |

## 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](#cancelling-an-execution)).

```swift theme={null}
do {
  _ = try await portal.borrow.yieldxyz.signAndSubmitAction(action)
} catch {
  if let apiError = YieldXyzBorrowApiError.from(error) {
    if apiError.isSchemaDrift {
      print("Yield.xyz Borrow 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.details ?? [:])
  }

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

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](https://docs.portalhq.io/integrations/Yield/yield-xyz-borrow.md#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](#idempotency-keys)).

`YieldXyzBorrowExecutionErrorReason` 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 not `EVM_TRANSACTION`. |
| `unsupportedNetwork` (`UNSUPPORTED_NETWORK`) | The transaction's `network` is not an EIP-155 chain Portal supports. |
| `invalidSignablePayload` (`INVALID_SIGNABLE_PAYLOAD`) | The `signablePayload` is missing or is not a valid EVM transaction, or the transaction has no id to submit it under. |
| `missingWalletAddress` (`MISSING_WALLET_ADDRESS`) | No EVM wallet address is available to sign with. |
| `signerAddressMismatch` (`SIGNER_ADDRESS_MISMATCH`) | The action or the transaction was built for an address other than the Portal wallet's EVM address. |
| `signingChainNotConfigured` (`SIGNING_CHAIN_NOT_CONFIGURED`) | The transaction's chain has no `rpcConfig` entry. Add one. |
| `dependencyUnavailable` (`DEPENDENCY_UNAVAILABLE`) | A signer or transaction lookup needed to execute the action is not configured. |
| `signatureRejected` (`SIGNATURE_REJECTED`) | The signing request was rejected: no hash was returned. |
| `invalidTransactionHash` (`INVALID_TRANSACTION_HASH`) | The signer, or `broadcastHashes`, supplied a value that is not a 32-byte hex hash. |
| `signingFailed` (`SIGNING_FAILED`) | Signing or broadcasting failed; `underlyingError` holds the cause. Also used for unexpected errors. |
| `transactionAlreadyBroadcast` (`TRANSACTION_ALREADY_BROADCAST`) | Portal refused to broadcast the transaction again because its idempotency key shows it was already broadcast. |
| `broadcastOutcomeUnknown` (`BROADCAST_OUTCOME_UNKNOWN`) | Portal cannot say whether the transaction was broadcast; `underlyingError` holds Portal's idempotency error. |
| `userOperationFailed` (`USER_OPERATION_FAILED`) | The user operation was included on-chain but did not succeed. |
| `transactionFailed` (`TRANSACTION_FAILED`) | Yield.xyz reported the transaction as `FAILED`. |
| `submitRejected` (`SUBMIT_REJECTED`) | The Portal API rejected the submission; `underlyingError` holds the API error, or the SDK's error when the submission could not be sent. |
| `submitFailed` (`SUBMIT_FAILED`) | The submission was accepted, but Yield.xyz reported the transaction as `FAILED`. |
| `submitOutcomeUnknown` (`SUBMIT_OUTCOME_UNKNOWN`) | The submission failed ambiguously, or was cancelled, and its outcome could not be confirmed. |
| `nextStepFailed` (`NEXT_STEP_FAILED`) | The next step could not be fetched, or had nothing to sign. |
| `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, or a transaction's on-chain hash, could not be read back while tracking it; `underlyingError` holds the error, and `broadcastHash` is set when the transaction was already broadcast. |
| `timeout` (`TIMEOUT`) | A transaction or the action did not reach the awaited status before `pollOptions.timeoutSeconds`. |

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

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

let actions = try await borrow.getActions(params: YieldXyzBorrowGetActionsParams(
  limit: 20,
  address: address,
  integrationId: "aave-borrow",
  statuses: [.success, .failed]
)).data

for item in actions.items {
  print(item.id, item.action, item.status, item.createdAt)
}

// Read one action back by id, for example the one createAction returned
let current = try await borrow.getAction(actionId: action.id).data
print(current.status, current.currentStep, current.totalSteps)

let liquidations = try await borrow.getLiquidations(params: YieldXyzBorrowGetLiquidationsParams(
  integrationId: "morpho-blue-borrow",
  network: "eip155:1",
  address: address
)).data
print(liquidations.total)
```

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](#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](https://docs.portalhq.io/apis/enclave-mpc/guide/yield-xyz-borrow.md#transaction-processing) as the reference for the order of calls:

| Method | Description |
| - | - |
| `submitTransaction(transactionId:params:)` | Submits `transactionHash` for a transaction you broadcast, or `signedPayload` for Yield.xyz to broadcast. Returns `status`, `link`, `transactionHash`, `error` and `details` in `data`; a `status` of `FAILED` means the transaction failed even though the request succeeded. |
| `stepAction(actionId:)` | Fetches the next step's transactions. Call it only once every transaction of the current step is `CONFIRMED` or `SKIPPED` and the action has `hasNextStep: true`. |
| `getHealth()` | Returns the integration's health: `status` (`OK` or `FAIL`) and `timestamp`. |

```swift theme={null}
let borrow = portal.borrow.yieldxyz
guard let transactionId = action.transactions.first?.id else { return }

// Reports the hash to Yield.xyz; it does not wait for the transaction to confirm.
let submitted = try await borrow.submitTransaction(
  transactionId: transactionId,
  params: YieldXyzBorrowSubmitTransactionParams(transactionHash: "0x...")
).data
print(submitted.status, submitted.link)

// Advance only once the current step is confirmed and another step follows.
let current = try await borrow.getAction(actionId: action.id).data
let stepConfirmed = current.transactions.allSatisfy { $0.status == .confirmed || $0.status == .skipped }
if current.hasNextStep, stepConfirmed {
  let next = try await borrow.stepAction(actionId: action.id).data
  print(next.currentStep, next.transactions.count)
}
```

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

* Set up the integration: [Yield.xyz Borrow](https://docs.portalhq.io/integrations/Yield/yield-xyz-borrow.md)
* Use the [Enclave MPC API](https://docs.portalhq.io/apis/enclave-mpc/guide/yield-xyz-borrow.md) to lend and borrow from your backend
* Check out the [Yield.xyz Borrow API reference](https://docs.portalhq.io/api-reference/yieldxyz-borrow/get-positions.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.