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

Portal's Android 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 Portal Android SDK `11.0.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. Chain ids are [CAIP-2](https://docs.portalhq.io/resources/chain-id-formatting.md) everywhere (`eip155:8453` for Base).

Every method is a `suspend` function that returns a Kotlin `Result`. Every method except `executeAction` and `signAndSubmitAction` succeeds with the Portal API response, such as a `YieldXyzBorrowActionResponse`, whose `data` holds the result; those two succeed with the execution result itself. A failure is returned in the `Result`, not thrown. The exception is cancellation: cancelling the calling coroutine throws its `CancellationException` (see [Cancelling an execution](#cancelling-an-execution)). The examples call `getOrThrow()` for brevity; in your app, handle the failure with `onFailure` or `fold`.

## Prerequisites

Before using lend and borrow operations, ensure you have:

* A properly initialized Portal client (see [Getting started](https://docs.portalhq.io/sdks/android/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/android/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 `rpcConfig`, 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 an `rpcConfig` that includes them. An `rpcConfig` you pass replaces the default entirely, so build it on `Portal.buildDefaultRpcConfig` to keep the default chains (see [below](#adding-a-chain)).

> [!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 these imports, a `portal` instance and the wallet's EVM address:

```kotlin theme={null}
import io.portalhq.android.Portal
import io.portalhq.android.api.data.yieldxyzborrow.*
import io.portalhq.android.borrow.*
import io.portalhq.android.storage.mobile.PortalNamespace

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

val address = portal.getAddress(PortalNamespace.EIP155)
    ?: throw IllegalStateException("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.

### Adding a chain

To sign on a chain outside the default `rpcConfig`, pass an `rpcConfig` built on the default, so Base, Ethereum and the other default chains keep working:

```kotlin theme={null}
val portal = Portal(
    apiKey = "YOUR_CLIENT_API_KEY_OR_CLIENT_SESSION_TOKEN",
    rpcConfig = Portal.buildDefaultRpcConfig("api.portalhq.io") + mapOf(
        "eip155:56" to "YOUR_BNB_CHAIN_RPC_URL",
    ),
)
```

Pass `buildDefaultRpcConfig` the same `apiHost` you give `Portal` (`api.portalhq.io` unless you override it).

## 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` (a Gson `JsonObject`).

```kotlin theme={null}
val integrations = portal.borrow.yieldxyz.getIntegrations().getOrThrow().data

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

val aave = portal.borrow.yieldxyz.getIntegration("aave-borrow").getOrThrow().data
val supplyArgsSchema = aave.actions.firstOrNull { it.id == YieldXyzBorrowActionType.SUPPLY }?.schema
println(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 = YieldXyzBorrowMarketScope.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.

```kotlin theme={null}
val page = portal.borrow.yieldxyz.getMarkets(
    YieldXyzBorrowGetMarketsParams(
        limit = 50,
        integrationId = "aave-borrow",
        network = "eip155:8453",
        scope = YieldXyzBorrowMarketScope.ALL,
    ),
).getOrThrow().data

for (market in page.items) {
    println("${market.id} ${market.loanToken.symbol} ${market.borrowRate} ${market.availableLiquidity}")
}

val market = portal.borrow.yieldxyz.getMarket(
    "aave-borrow-base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
).getOrThrow().data
for (collateral in market.collateralTokens) {
    println("${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 `YieldXyzBorrowPage` 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(action)` 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)).

```kotlin theme={null}
val action = portal.borrow.yieldxyz.createAction(
    YieldXyzBorrowCreateActionParams(
        integrationId = "aave-borrow",
        action = YieldXyzBorrowActionType.SUPPLY,
        address = address,
        args = YieldXyzBorrowActionArguments(
            marketId = "aave-borrow-base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
            amount = "5",
            tokenAddress = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base
        ),
    ),
).getOrThrow().data

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

val result = portal.borrow.yieldxyz.signAndSubmitAction(action).getOrThrow()
println("${result.status} ${result.transactions.map { it.transactionHash }}")
```

> [!NOTE]
>
> Run `signAndSubmitAction` and `executeAction` in a `ViewModel`'s `viewModelScope` or an application-wide scope, not in an Activity's `lifecycleScope`: a rotation cancels `lifecycleScope`, and a cancelled execution can lose the hash of a transaction it just broadcast (see [Cancelling an execution](#cancelling-an-execution)).

`YieldXyzBorrowCreateActionParams` takes:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `integrationId` | `String` | Yes | Integration id from `getIntegrations()`. |
| `action` | `String` | Yes | One of the `YieldXyzBorrowActionType` constants: `SUPPLY`, `BORROW`, `REPAY`, `WITHDRAW`, `ENABLE_COLLATERAL`, `DISABLE_COLLATERAL` or `SUPPLY_AND_BORROW` (`"supply"`, `"borrow"` and so on). |
| `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 `null` are not sent. `getIntegration(integrationId)` returns the exact schema of each action's `args` for an integration.

`createAction` returns the action, a `YieldXyzBorrowAction`, 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 = YieldXyzBorrowActionType.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 `ENABLE_COLLATERAL` action first. Integrations that offer `SUPPLY_AND_BORROW`, which supplies collateral and borrows in one action, list it in `getIntegration` with the `args` it accepts.

```kotlin theme={null}
val marketId = "aave-borrow-base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"

val borrowAction = portal.borrow.yieldxyz.createAction(
    YieldXyzBorrowCreateActionParams(
        integrationId = "aave-borrow",
        action = YieldXyzBorrowActionType.BORROW,
        address = address,
        args = YieldXyzBorrowActionArguments(marketId = marketId, amount = "2"),
    ),
).getOrThrow().data

println("Health factor after borrowing: ${borrowAction.metadata?.predictedHealthFactor ?: "unknown"}")

portal.borrow.yieldxyz.signAndSubmitAction(borrowAction).getOrThrow()
```

> [!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 `null` when Yield.xyz does not compute it for a market (Morpho Blue on Monad returns `null` even with open debt); treat `null` as unknown, never as safe.

## Checking positions

`getPositions(params)` returns the wallet's position on one integration and network.

```kotlin theme={null}
val position = portal.borrow.yieldxyz.getPositions(
    YieldXyzBorrowGetPositionsParams(
        integrationId = "aave-borrow",
        network = "eip155:8453",
        address = address,
    ),
).getOrThrow().data

println("Health factor: ${position.healthFactor ?: "unknown"}")
println("Supplied: ${position.totalSuppliedUsd} Borrowed: ${position.totalBorrowedUsd}")

for (balance in position.debtBalances) {
    println("${balance.tokenSymbol} ${balance.balance} ${balance.pendingActions.map { it.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 `null`: read each supply balance's `positionState` instead, which carries that market's `healthFactor`, `availableToBorrowUsd`, `currentLtv` and `liquidationThreshold`. A `healthFactor` is also `null` when there is no debt; treat any other `null` as unknown.

Each balance lists `pendingActions`, the actions available for it now, with pre-filled `args` you can pass to `createAction`:

```kotlin theme={null}
val repay = position.debtBalances.firstOrNull()
    ?.pendingActions
    ?.firstOrNull { it.type == YieldXyzBorrowActionType.REPAY }

if (repay != null) {
    val action = portal.borrow.yieldxyz.createAction(
        YieldXyzBorrowCreateActionParams(
            integrationId = position.integrationId,
            action = YieldXyzBorrowActionType.REPAY,
            address = address,
            args = repay.args,
        ),
    ).getOrThrow().data
    portal.borrow.yieldxyz.signAndSubmitAction(action).getOrThrow()
}
```

## Repaying and withdrawing

Repay debt with `YieldXyzBorrowActionType.REPAY` (pass `repayAll = true` to clear the position, which avoids dust from accrued interest), then withdraw collateral with `YieldXyzBorrowActionType.WITHDRAW`.

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

val repay = borrow.createAction(
    YieldXyzBorrowCreateActionParams(
        integrationId = "aave-borrow",
        action = YieldXyzBorrowActionType.REPAY,
        address = address,
        args = YieldXyzBorrowActionArguments(marketId = marketId, repayAll = true),
    ),
).getOrThrow().data
borrow.signAndSubmitAction(repay).getOrThrow()

val withdraw = borrow.createAction(
    YieldXyzBorrowCreateActionParams(
        integrationId = "aave-borrow",
        action = YieldXyzBorrowActionType.WITHDRAW,
        address = address,
        args = YieldXyzBorrowActionArguments(
            marketId = marketId,
            amount = "5",
            tokenAddress = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
        ),
    ),
).getOrThrow().data
borrow.signAndSubmitAction(withdraw).getOrThrow()
```

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(action, 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 still awaits a signature, 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 a successful `Result` when the action reaches `SUCCESS`. Any failure is returned as a [`YieldXyzBorrowExecutionException`](#handling-errors), and cancelling the calling coroutine throws its `CancellationException` (see [Cancelling an execution](#cancelling-an-execution)). An action with an empty `id` fails with `YieldXyzBorrowException.EmptyIdentifier` before anything is read or signed. An action without an `id`, or with a transaction without one (for example restored from storage without them), fails with Gson's `JsonParseException` and signs nothing.

Pass an action whose transactions are in signing order: the one `createAction` returned, the `action` of the latest `NEXT_STEP` progress event, or the `action` of an execution result or a `YieldXyzBorrowExecutionException`. `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 `portal_signingRequested` handler (see [Add custom signature hooks](https://docs.portalhq.io/sdks/android/guide/add-custom-signature-hooks.md)): 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. A rejected request stops the execution with `SIGNATURE_REJECTED`. Without a handler, the request fails with `PortalException.Provider.NoBindingForSigningApprovalFound` before anything is signed, so the execution stops with `SIGNING_FAILED`.

```kotlin theme={null}
import io.portalhq.android.provider.data.PortalProviderRequestWithId
import io.portalhq.android.utils.events.PortalEvents

portal.on(PortalEvents.PortalSigningRequested) { data ->
    val request = data as PortalProviderRequestWithId
    // Runs on a background thread: switch to the main thread before you show a confirmation.
    val approved = true // your decision, for example from a confirmation dialog
    if (approved) {
        portal.emit(PortalEvents.PortalSigningApproved, request)
    } else {
        portal.emit(PortalEvents.PortalSigningRejected, request)
    }
}
```

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

### Idempotency keys

Each transaction is sent with the [idempotency key](https://docs.portalhq.io/sdks/android/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/android/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 `BROADCAST_OUTCOME_UNKNOWN`. A retry that is declined, or that fails with an error other than an idempotency answer, also fails with `BROADCAST_OUTCOME_UNKNOWN`, not `SIGNATURE_REJECTED` or `SIGNING_FAILED`, because the earlier send may still broadcast the transaction.
* A transaction Portal already broadcast fails with `TRANSACTION_ALREADY_BROADCAST`. 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 `USER_OPERATION_FAILED` 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 `BROADCAST_OUTCOME_UNKNOWN`.

With [presignatures](https://docs.portalhq.io/sdks/android/guide/idempotency-keys.md#presignatures) on, a failed presignature attempt falls back to a normal signature under the same key, so `BROADCAST_OUTCOME_UNKNOWN` 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)).

```kotlin theme={null}
val result = portal.borrow.yieldxyz.executeAction(
    YieldXyzBorrowCreateActionParams(
        integrationId = "aave-borrow",
        action = YieldXyzBorrowActionType.BORROW,
        address = address,
        args = YieldXyzBorrowActionArguments(
            marketId = "aave-borrow-base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
            amount = "2",
        ),
    ),
    YieldXyzBorrowExecuteOptions(onProgress = { event ->
        println("${event.step} ${event.transactionId ?: ""}")
    }),
).getOrThrow()
println(result.status)
```

When `createAction` fails, `executeAction` returns its failure as it is: no action exists yet, so there is nothing to resume. That is a Portal API error, which you read with `YieldXyzBorrowApiError.from(error)`, or a transport error (`IOException`), a decoding error (Gson's `JsonParseException`), or a `PortalException.Credentials` raised before any request was sent, for which `YieldXyzBorrowApiError.from(error)` returns `null` (a `401` from the Portal API is an API error with `status` 401). No `FAILED` progress event is emitted. When `createAction` succeeds but its response holds no readable action, `executeAction` fails with `JsonParseException` and signs nothing, although Yield.xyz created the action: find it with `getActions` before you create another.

### Options

Both methods take a `YieldXyzBorrowExecuteOptions`; leave it out to use the defaults.

| Name | Type | Default | Description |
| - | - | - | - |
| `onProgress` | `((YieldXyzBorrowExecutionProgress) -> Unit)?` | `null` | Called at each execution step. It can run after a transaction was broadcast, so it must return quickly. An exception it throws is logged and does not affect the execution. |
| `pollOptions` | `YieldXyzBorrowPollOptions` | `intervalMs = 2_000`, `timeoutMs = 600_000` | How the action, and the on-chain hash of a broadcast transaction, are read back, in milliseconds. The interval (at least 250 ms) 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. A zero timeout fails with `TIMEOUT` before the action is read, so nothing is signed. |
| `useIdempotencyKeys` | `Boolean` | `true` | Whether to send each transaction with its idempotency key. See [Idempotency keys](#idempotency-keys). |
| `signAndSendTransaction` | `YieldXyzBorrowSignAndSendTransaction?` | `null` | 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` | `Map<String, String>` | `emptyMap()` | 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` (a `YieldXyzBorrowExecutionStep`), 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` |
| `NEXT_STEP` | 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 Android can kill your app's process while the SDK waits for the transaction. Persist the `action` of a `NEXT_STEP` event too: resuming that step from it keeps the signing order, which `getAction` may not. `onProgress`, like a custom signer, runs in the coroutine that called `signAndSubmitAction`, on its dispatcher: from `viewModelScope`, that is the main thread.

```kotlin theme={null}
val onProgress: (YieldXyzBorrowExecutionProgress) -> Unit = { event ->
    when (event.step) {
        YieldXyzBorrowExecutionStep.SIGNING -> println("Signing transaction ${event.transactionId}")
        YieldXyzBorrowExecutionStep.CONFIRMING -> println("Broadcast ${event.broadcastHash}")
        YieldXyzBorrowExecutionStep.CONFIRMED -> println("Confirmed ${event.transactionHash}")
        YieldXyzBorrowExecutionStep.NEXT_STEP -> println("Step ${event.currentStep} of ${event.totalSteps}")
        YieldXyzBorrowExecutionStep.FAILED -> println("Stopped: ${event.error?.reason?.value}")
        YieldXyzBorrowExecutionStep.SUBMITTED, YieldXyzBorrowExecutionStep.POLLING -> Unit
    }
}

portal.borrow.yieldxyz.signAndSubmitAction(action, YieldXyzBorrowExecuteOptions(onProgress = onProgress))
```

### Return value

Both methods succeed with 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` (`null` when the submission's outcome was confirmed by reading the action back). |

### Cancelling an execution

Cancelling the coroutine that runs `signAndSubmitAction` or `executeAction` stops the execution: the call throws the coroutine's `CancellationException` instead of returning a `Result`, wherever the execution is, including while a broadcast transaction is being resolved and submitted. A `withTimeout` around the call cancels it the same way. The `broadcastHash` of the last `CONFIRMING` progress event is then the hash to resume with. A cancellation that lands while the signer is still sending can lose the hash 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 `TRANSACTION_ALREADY_BROADCAST` or `BROADCAST_OUTCOME_UNKNOWN` 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.

So don't run an execution in an Activity's `lifecycleScope`, which a configuration change such as a rotation cancels. Use a `ViewModel`'s `viewModelScope`, which survives one, or an application-wide scope, which also survives the screen closing:

```kotlin theme={null}
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

class BorrowViewModel(private val portal: Portal) : ViewModel() {
    fun signAndSubmit(action: YieldXyzBorrowAction) {
        viewModelScope.launch {
            portal.borrow.yieldxyz.signAndSubmitAction(action)
                .onSuccess { result -> println("Action ${result.actionId} ended ${result.status}") }
                .onFailure { error -> println("Execution stopped: ${error.message}") }
        }
    }
}
```

Cancelling stops the SDK's work, not what was already sent: a transaction already broadcast or submitted can still take effect. 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. A cancellation 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, `data` as `0x` when the transaction has none, and no `gas`), the CAIP-2 chain id and the transaction's idempotency key, and returns the hash, or `null` when the request is declined. Pass the key to `eth_sendTransaction` as `RequestOptions(idempotencyKey = ...)`; it is `null` 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 `null`. Let a `PortalException.Mpc.MpcResultError` 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 with `PortalException.Provider.NoRpcUrlFoundForChainId` after the approval prompt (when `autoApprove` is off), the execution stops with `SIGNING_FAILED`, and nothing was sent.

```kotlin theme={null}
import io.portalhq.android.exceptions.PortalException
import io.portalhq.android.provider.data.PortalRequestMethod
import io.portalhq.android.provider.data.RequestOptions

// `confirmWithUser` stands for your own confirmation UI: a suspend function that returns `true` to send.
val signAndSendTransaction: YieldXyzBorrowSignAndSendTransaction = { transaction, chainId, idempotencyKey ->
    if (!confirmWithUser("Send this transaction to ${transaction.to} on $chainId?")) {
        null // stops the execution with SIGNATURE_REJECTED (BROADCAST_OUTCOME_UNKNOWN when it declines a retry)
    } else {
        try {
            val response = portal.request(
                chainId = chainId,
                method = PortalRequestMethod.eth_sendTransaction,
                params = listOf(transaction),
                options = idempotencyKey?.let { RequestOptions(idempotencyKey = it) },
            )
            response.result as? String
                ?: throw IllegalStateException("eth_sendTransaction returned no hash") // stops the execution with SIGNING_FAILED
        } catch (e: PortalException.Provider.UserDeclinedApproval) {
            null // declined in your portal_signingRequested handler
        }
    }
}

portal.borrow.yieldxyz.signAndSubmitAction(
    action,
    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 `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`.

## Resuming a failed execution

A failed execution returns a `YieldXyzBorrowExecutionException` 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`, `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 `NEXT_STEP` event's), passing your `broadcastHashes`. `YieldXyzBorrowAction` is a plain data class: store it as JSON, for example with Gson (`Gson().toJson(action)`, and `Gson().fromJson(json, YieldXyzBorrowAction::class.java)` to read it back). Prefer these over `getAction`, which may list the transactions in a different order. If the app was killed between a step being fetched and its `NEXT_STEP` 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 `NEXT_STEP_FAILED`.

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

```kotlin theme={null}
// Persist `pending` and `broadcastHashes` in your app's storage, so a retry survives the process being killed.
class BorrowExecution(private val portal: Portal, action: YieldXyzBorrowAction) {
    var pending: YieldXyzBorrowAction = action
        private set
    val broadcastHashes = mutableMapOf<String, String>()

    // Call once to execute, and again only when the user chooses to retry.
    suspend fun execute(): Result<YieldXyzBorrowExecutionResult> =
        portal.borrow.yieldxyz.signAndSubmitAction(
            pending,
            YieldXyzBorrowExecuteOptions(
                onProgress = { event ->
                    // Persist the hash as soon as the transaction is broadcast, and the new step's action:
                    // Android can kill the process while the SDK waits.
                    val transactionId = event.transactionId
                    val hash = event.broadcastHash
                    if (event.step == YieldXyzBorrowExecutionStep.CONFIRMING && transactionId != null && hash != null) {
                        broadcastHashes[transactionId] = hash
                    }
                    if (event.step == YieldXyzBorrowExecutionStep.NEXT_STEP) {
                        event.action?.let { pending = it }
                    }
                },
                broadcastHashes = broadcastHashes.toMap(),
            ),
        ).onFailure { error ->
            if (error !is YieldXyzBorrowExecutionException) return@onFailure
            val transactionId = error.transactionId
            if (transactionId != null) {
                if (error.reason == YieldXyzBorrowExecutionErrorReason.USER_OPERATION_FAILED ||
                    (error.reason == YieldXyzBorrowExecutionErrorReason.INVALID_TRANSACTION_HASH && error.broadcastHash != null)
                ) {
                    // 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.remove(transactionId)
                } else {
                    error.broadcastHash?.let { broadcastHashes[transactionId] = it }
                }
            }
            pending = error.action ?: pending
        }
}
```

```kotlin theme={null}
import io.portalhq.android.exceptions.PortalException
import io.portalhq.android.utils.PortalIdempotencyErrorId
import io.portalhq.android.utils.errors.isIdempotencyRejection

execution.execute().onFailure { error ->
    if (error !is YieldXyzBorrowExecutionException) return@onFailure
    when (error.reason) {
        YieldXyzBorrowExecutionErrorReason.TRANSACTION_ALREADY_BROADCAST -> {
            // Resume with the hash from the CONFIRMING event, or find the transaction on-chain and add its hash.
        }
        YieldXyzBorrowExecutionErrorReason.BROADCAST_OUTCOME_UNKNOWN -> {
            // What to do depends on the cause behind the error.
            val cause = error.cause
            val keyRefused = cause is PortalException.Mpc.MpcResultError &&
                cause.error.isIdempotencyRejection() &&
                cause.id != PortalIdempotencyErrorId.IDEMPOTENT_REQUEST_IN_PROGRESS
            if (keyRefused) {
                // Check the chain before you offer a retry (see "When a transaction may have been sent").
            } else {
                // Still in progress, or a retry failed while it was: wait, then call execute() again with keys on.
            }
        }
        YieldXyzBorrowExecutionErrorReason.USER_OPERATION_FAILED -> {
            // Already processed and not successful: build a new action, or resume with useIdempotencyKeys = false.
        }
        YieldXyzBorrowExecutionErrorReason.SIGNING_FAILED -> if (error.transactionId != null) {
            // 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.
        }
        else -> {
            // Persist `pending` and `broadcastHashes`, and call execute() again when the user retries.
            // Check the reason in the table below before you offer a retry.
        }
    }
}
```

Once the action succeeds, drop its `broadcastHashes` entries.

### When a transaction may have been sent

`TRANSACTION_ALREADY_BROADCAST` 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/android/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 `BROADCAST_OUTCOME_UNKNOWN` depends on its `cause`. The idempotency error ids are constants of `PortalIdempotencyErrorId`:

| Cause | What to do |
| - | - |
| A `PortalException.Mpc.MpcResultError` with `id` `IDEMPOTENT_REQUEST_IN_PROGRESS`, or another error from a retry sent while Portal reported the earlier send in progress | 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. |
| A `PortalException.Mpc.MpcResultError` with `id` `IDEMPOTENT_REQUEST_PREVIOUSLY_FAILED`, `IDEMPOTENT_REQUEST_UNEXPECTED_STATE`, `IDEMPOTENT_TX_MISSING` or `IDEMPOTENCY_KEY_REUSED` | 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 a signing failure

Borrow reports every send failure that isn't an idempotency answer as `SIGNING_FAILED`, whether or not the transaction reached the chain. The exception is a retry after `IDEMPOTENT_REQUEST_IN_PROGRESS`, which fails with `BROADCAST_OUTCOME_UNKNOWN` (see [Idempotency keys](#idempotency-keys)).

* **The SDK raised it**: `cause` is a `PortalException.Provider.NoBindingForSigningApprovalFound` (no `portal_signingRequested` handler), a `PortalException.Credentials`, a `PortalException.Provider.InvalidIdempotencyKey`, or a `PortalException.Provider.NoRpcUrlFoundForChainId` 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 `PortalException.Mpc.MpcResultError` 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 `TRANSACTION_ALREADY_BROADCAST` or `BROADCAST_OUTCOME_UNKNOWN`, 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 `IDEMPOTENT_REQUEST_PREVIOUSLY_FAILED`, follow `BROADCAST_OUTCOME_UNKNOWN`.

### What to do for each reason

What each reason means is listed in [Handling errors](#handling-errors).

| Reason | What to do |
| - | - |
| `ACTION_FAILED` | 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. |
| `ACTION_IN_PROGRESS` | 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. |
| `SIGNATURE_REJECTED` | Resume when the user is ready. |
| `SIGNING_CHAIN_NOT_CONFIGURED`, `DEPENDENCY_UNAVAILABLE`, `MISSING_WALLET_ADDRESS` | 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 `rpcConfig` includes it and resume on that instance. |
| `UNSUPPORTED_SIGNING_FORMAT`, `UNSUPPORTED_NETWORK`, `INVALID_SIGNABLE_PAYLOAD`, `SIGNER_ADDRESS_MISMATCH` | 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. |
| `SIGNING_FAILED` | Signing or broadcasting failed. What to do depends on where it failed: see [After a signing failure](#after-a-signing-failure). |
| `TRANSACTION_ALREADY_BROADCAST`, `BROADCAST_OUTCOME_UNKNOWN` | See [When a transaction may have been sent](#when-a-transaction-may-have-been-sent). |
| `INVALID_TRANSACTION_HASH` | 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. |
| `TRANSACTION_FAILED`, `SUBMIT_FAILED` | 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. |
| `USER_OPERATION_FAILED` | 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. |
| `SUBMIT_OUTCOME_UNKNOWN` | The submission failed ambiguously. Check the action before retrying. With a `broadcastHash`, resume with it in `broadcastHashes`. |
| `SUBMIT_REJECTED` | 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. |
| `POLLING_FAILED`, `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. |
| `NEXT_STEP_FAILED` | 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 copy of the action `getAction(actionId)` returns, with its `transactions` put in signing order (`action.copy(transactions = ...)`: 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 errors (`IOException`, such as a `SocketTimeoutException`), decoding errors (Gson's `JsonParseException`) and credential errors (`PortalException.Credentials`), these errors reach your app as the failure of the returned `Result`:

* **`YieldXyzBorrowException`**, before any request is sent: `SubmissionRequired` when `submitTransaction` gets neither a hash nor a signed payload, and `EmptyIdentifier` (its `name` says which) when an id sent in the request path (such as `marketId` or `actionId`) is empty.
* **Portal API errors**: the transport's `PortalException.Api.HttpBadRequest` (`400`), `HttpUnauthorized` (`401`) or `HttpRequestFailed` (other statuses), returned by the read methods, `createAction`, `stepAction` and `submitTransaction`, and carried as `cause` by execution errors. `YieldXyzBorrowApiError.from(error)` returns the API error, with the HTTP `status`, the stable error `id`, the `message` and `details` (a Gson `JsonObject`), whether it was returned directly or wrapped in an execution error. It returns `null` for a transport, decoding or credential error. For a `401`, only `status` is set.
* **`YieldXyzBorrowExecutionException`**, returned by `signAndSubmitAction` and `executeAction`. Branch on its `reason`.
* **`JsonParseException`**, returned by `signAndSubmitAction` for an action without its ids, and by `executeAction` when the action `createAction` returned can't be read.

Cancelling the calling coroutine throws its `CancellationException` instead (see [Cancelling an execution](#cancelling-an-execution)).

```kotlin theme={null}
portal.borrow.yieldxyz.signAndSubmitAction(action).onFailure { error ->
    YieldXyzBorrowApiError.from(error)?.let { apiError ->
        when {
            apiError.isSchemaDrift -> println("Yield.xyz Borrow is temporarily unavailable.")
            apiError.isRateLimit -> println("Rate limited by Yield.xyz; try again shortly.")
        }
        println("${apiError.status} ${apiError.id} ${apiError.message} ${apiError.details}")
    }

    if (error is YieldXyzBorrowExecutionException) {
        println("${error.reason} ${error.actionId} ${error.transactionId} ${error.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` (`YieldXyzBorrowErrorId.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 up to three times, and tolerates up to four consecutive transient failures (`429`, `5xx`, transport or decoding errors) while reading the action or a transaction back. A step request that fails with a `5xx` is not retried: it fails with `NEXT_STEP_FAILED`. 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` is an enum; each entry's `value` is the same string. See [What to do for each reason](#what-to-do-for-each-reason) for how to recover:

| Reason | Meaning |
| - | - |
| `UNSUPPORTED_SIGNING_FORMAT` | The transaction's `signingFormat` is not `EVM_TRANSACTION`. |
| `UNSUPPORTED_NETWORK` | The transaction's `network` is not an EIP-155 chain Portal supports. |
| `INVALID_SIGNABLE_PAYLOAD` | The `signablePayload` is missing or is not a valid EVM transaction, or the transaction has no id to submit it under. |
| `MISSING_WALLET_ADDRESS` | No EVM wallet address is available to sign with. |
| `SIGNER_ADDRESS_MISMATCH` | The action or the transaction was built for an address other than the Portal wallet's EVM address. |
| `SIGNING_CHAIN_NOT_CONFIGURED` | The transaction's chain has no `rpcConfig` entry, or checking for one failed (`cause` holds that error). Add one. |
| `DEPENDENCY_UNAVAILABLE` | A signer or transaction lookup needed to execute the action is not configured. |
| `SIGNATURE_REJECTED` | The signing request was rejected: no hash was returned. |
| `INVALID_TRANSACTION_HASH` | The signer, or `broadcastHashes`, supplied a value that is not a 32-byte hex hash. |
| `SIGNING_FAILED` | Signing or broadcasting failed; `cause` holds the underlying error. Also used for unexpected errors. |
| `TRANSACTION_ALREADY_BROADCAST` | Portal refused to broadcast the transaction again because its idempotency key shows it was already broadcast. |
| `BROADCAST_OUTCOME_UNKNOWN` | Portal cannot say whether the transaction was broadcast; `cause` holds Portal's idempotency error, or the error of a retry that failed while Portal was still processing the earlier send. |
| `USER_OPERATION_FAILED` | The user operation was included on-chain but did not succeed. |
| `TRANSACTION_FAILED` | Yield.xyz reported the transaction as `FAILED`. |
| `SUBMIT_REJECTED` | The Portal API rejected the submission; `cause` holds the API error, or the SDK's error when the submission could not be sent. |
| `SUBMIT_FAILED` | The submission was accepted, but Yield.xyz reported the transaction as `FAILED`. |
| `SUBMIT_OUTCOME_UNKNOWN` | The submission failed ambiguously, and its outcome could not be confirmed. |
| `NEXT_STEP_FAILED` | The next step could not be fetched, or had nothing to sign. |
| `ACTION_FAILED` | The action ended as `FAILED`, `CANCELED` or `STALE`. |
| `ACTION_IN_PROGRESS` | Another call on this `Portal` instance is already executing the action. |
| `POLLING_FAILED` | The action, or a transaction's on-chain hash, could not be read back while tracking it; `cause` holds the error, and `broadcastHash` is set when the transaction was already broadcast. |
| `TIMEOUT` | A transaction or the action did not reach the awaited status before `pollOptions.timeoutMs`. |

The error also carries a `detail` (its `message`, without the `[YieldXyzBorrow]` prefix), `broadcastHash` (the hash the signer returned, or the one you passed in `broadcastHashes`), `transactionHash` (the on-chain hash, once known), `userOperationHash` and `cause`.

## 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), optionally for one `marketId`.

```kotlin theme={null}
val borrow = portal.borrow.yieldxyz

val actions = borrow.getActions(
    YieldXyzBorrowGetActionsParams(
        address = address,
        limit = 20,
        integrationId = "aave-borrow",
        statuses = listOf(YieldXyzBorrowActionStatus.SUCCESS, YieldXyzBorrowActionStatus.FAILED),
    ),
).getOrThrow().data

for (item in actions.items) {
    println("${item.id} ${item.action} ${item.status} ${item.createdAt}")
}

// Read one action back by id, for example the one createAction returned
val current = borrow.getAction(action.id).getOrThrow().data
println("${current.status} ${current.currentStep} ${current.totalSteps}")

val liquidations = borrow.getLiquidations(
    YieldXyzBorrowGetLiquidationsParams(
        integrationId = "morpho-blue-borrow",
        network = "eip155:1",
        address = address,
    ),
).getOrThrow().data
println(liquidations.total)
```

Both list methods take `offset` and `limit` (at most `100`) and return a `YieldXyzBorrowPage` in `data`, with `total`, `offset`, `limit` and `items`.

## Values Yield.xyz may add

Statuses, action and transaction types, signing formats, market and liquidation types and the health status are plain `String`s, with the known values as constants in `YieldXyzBorrowActionStatus`, `YieldXyzBorrowActionType`, `YieldXyzBorrowTransactionStatus`, `YieldXyzBorrowTransactionType`, `YieldXyzBorrowSigningFormat`, `YieldXyzBorrowMarketType`, `YieldXyzBorrowLiquidationType` and `YieldXyzBorrowHealthStatusValue`. A value Yield.xyz adds later reaches your app as it is, instead of failing the response. Compare against the constants, and give a `when` over one of these strings an `else` branch. The SDK's own `YieldXyzBorrowExecutionStep` and `YieldXyzBorrowExecutionErrorReason`, and `YieldXyzBorrowMarketScope`, are Kotlin enums you can match exhaustively.

## 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` set to `true`. |
| `getHealth()` | Returns the integration's health: `status` (`OK` or `FAIL`) and `timestamp`. |

```kotlin theme={null}
val borrow = portal.borrow.yieldxyz
val transactionId = action.transactions.firstOrNull()?.id ?: error("The action has no transactions")

// Reports the hash to Yield.xyz; it does not wait for the transaction to confirm.
val submitted = borrow.submitTransaction(
    transactionId = transactionId,
    params = YieldXyzBorrowSubmitTransactionParams(transactionHash = "0x..."),
).getOrThrow().data
println("${submitted.status} ${submitted.link}")

// Advance only once the current step is confirmed and another step follows.
val current = borrow.getAction(action.id).getOrThrow().data
val stepConfirmed = current.transactions.all {
    it.status == YieldXyzBorrowTransactionStatus.CONFIRMED || it.status == YieldXyzBorrowTransactionStatus.SKIPPED
}
if (current.hasNextStep && stepConfirmed) {
    val next = borrow.stepAction(action.id).getOrThrow().data
    println("${next.currentStep} ${next.transactions.size}")
}
```

Each transaction's `signablePayload` (a Gson `JsonElement`) is the unsigned transaction, JSON-encoded as a string 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)` (`data.evmUserOperation?.receipt?.hash`).

## Testing

`YieldXyzBorrow`, the type of `portal.borrow.yieldxyz`, is an `open` class whose methods are all `open`, so a test can replace it with a mock (for example with MockK) or a subclass. `portal.borrow` itself can't be overridden: have your own classes take the `YieldXyzBorrow` rather than the `Portal`, and pass them the test double in tests.

## 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. **Run executions in `viewModelScope` or an application scope**, never in an Activity's `lifecycleScope`, which a rotation cancels
4. **Use `repayAll`** when closing a position so accrued interest does not leave dust
5. **Pass `scope = YieldXyzBorrowMarketScope.ALL` and filter** markets to the ones your UI offers, for example by `availableLiquidity`
6. **Handle `INTEGRATION_RESPONSE_SCHEMA_DRIFT`** as a feature outage rather than a user error
7. **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 (see [Adding a chain](#adding-a-chain)).

## 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/android/guide/add-custom-signature-hooks.md)
* Learn how Portal uses [idempotency keys](https://docs.portalhq.io/sdks/android/guide/idempotency-keys.md)
* Review [Error handling](https://docs.portalhq.io/sdks/android/guide/error-handling.md) for the `PortalException` hierarchy


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