Supply Collateral, Borrow, Repay & Withdraw Collateral
Prepare Morpho Blue supply, borrowing, repayment, and withdrawal actions with the Actions API or SDK.
This tutorial provides a comprehensive guide for developers on how to integrate the core functionalities of Morpho Markets: supplying collateral, borrowing, repaying debt, and withdrawing collateral.
Unlike ERC4626 vaults, Morpho Markets have a unique interface defined by the core Morpho contract. Understanding these functions is essential for building any application with borrowing capabilities.
Choose API preparation or SDK construction below. The API returns calls for the user's wallet to authorize and send; the Morpho SDK builds transactions locally.
Key Concepts: Assets vs. Shares
The core accounting system in Morpho Markets revolves around the concepts of assets and shares. This applies to the borrow positions (the loanable asset), but not to the collateral.
| Concept | Functions Affected | Description |
|---|---|---|
| Assets | borrow, repay | The actual underlying token (e.g., USDC, WETH) that a user wants to lend or borrow. |
| Shares | borrow, repay | Internal accounting units representing a proportional claim on the market's total supply or debt. |
Best Practice:
- For
borrow, specifying an exact asset amount is the most common and intuitive approach for users. - For full repayments, choose the full-debt mode shown in the API or SDK tab to avoid leaving a small debt balance.
- Collateral (
supplyCollateralandwithdrawCollateral) is always handled inassets.
Prerequisites
For the Python examples, install Requests with pip install requests.
Before you begin, you will need:
- The
MarketParamsfor the market you want to interact with. You can find active markets using the Read API. - An account with a balance of the collateral asset (e.g., wstETH) and the loan asset (e.g., WETH for repayments).
For an end-to-end walkthrough of every market action this SDK exposes (supply collateral, borrow, atomic supply+borrow, repay by assets vs shares, withdraw collateral, atomic repay+withdraw, shared-liquidity reallocations) see the Blue subpage; the Morpho SDK page covers the getRequirements flow, the builder = signer invariant, and error classes. For shared-liquidity implementation, use the Vault V2 Public Allocator guide.
Supply collateral and borrow
Private APIUse Blue Borrow with collateral_amount to supply collateral and borrow atomically. These API examples use Base and the listed WETH/USDC market below. Replace the public test account with the connected wallet and keep $MORPHO_API_KEY in your backend environment. Amounts are integer strings in token base units: this request supplies 0.001 WETH and borrows 1 USDC. signature_mode: "none" requests authorization calls instead of typed-data signatures.
curl --silent --show-error --include \
--request POST \
'https://private.api.morpho.org/v0/actions/blue/markets/8453:0x8793cf302b8ffd655ab97bd1c695dbd967807e8367a65cb2f4edaf1380ba1bda/borrow' \
--header "x-api-key: $MORPHO_API_KEY" \
--header 'Content-Type: application/json' \
--data-raw '{
"account": "0x4f620E5a62Eb51DA77502E8d3De7DB41f43e5695",
"amount": {
"unit": "assets",
"value": "1000000"
},
"collateral_amount": {
"unit": "assets",
"value": "1000000000000000"
},
"funding": {
"type": "erc20"
},
"signature_mode": "none"
}'| Response field | Check before sending |
|---|---|
data.status, data.action | Require prepared and blue.borrow. |
data.simulation.status | Require success. A failed simulation has no executable calls. |
data.calls | Inspect targets, calldata, values, and approvals; preserve order. |
data.simulation.effects | Compare supplied_collateral_assets, gross_assets, referral_fee_assets, net_assets, ltv_bps, and max_ltv_bps with the user's intent. Inspect data.simulation.position_changes.collateral_assets and borrow_shares. |
If status is signature_required, complete the signature and continuation flow before expecting calls. Do not send an error response or a simulation_failed result.
The user's wallet sends the returned calls, in order, only after checking the simulation, verifying the signed proof, and matching the calldata to your request, with user approval. Morpho does not submit transactions.
For collateral-only supply, use Supply collateral (only). For borrow only, omit both collateral_amount and funding. Do not concatenate independently prepared call lists and assume atomicity.
Optional borrow referral fee
The borrow route accepts an optional referral_fee object:
{
"bps": 25,
"recipient": "0x1111111111111111111111111111111111111111"
}The integrator chooses the nonzero recipient; replace the placeholder address above. There is no default recipient. bps is an integer from 1 to 200. Omit the entire object for no fee rather than sending zero. The recipient receives loan tokens deducted from the gross borrowed amount: debt is unchanged while the wallet receives less. Compare gross_assets, referral_fee_assets, and net_assets in the simulation. The standalone collateral-supply route does not support this fee.
Complete the Morpho SDK setup before using this SDK example.
import { parseUnits } from "viem";
import { MarketParams } from "@morpho-org/morpho-sdk/entities";
const market = client.morpho.blue(
new MarketParams({
loanToken: "0xLoanToken...",
collateralToken: "0xCollateralToken...",
oracle: "0xOracle...",
irm: "0xIrm...",
lltv: 860000000000000000n, // 86%
}),
mainnet.id,
);The SDK builds an atomic BlueBundlesV1 call that supplies collateral, then borrows, with an LLTV buffer that prevents the new position from being instantly liquidatable. getRequirements() returns the ERC-20 approval (or ERC-2612 permit signature) for the collateral token, plus the one-time morpho.setAuthorization(blueBundlesV1, true) if it has not been done yet.
const positionData = await market.getPositionData(account.address);
const supplyCollateralBorrow = market.supplyCollateralBorrow({
collateralAssets: parseUnits("1.0", 18), // 1 wstETH
borrowAssets: parseUnits("2000", 18), // 2000 WETH
userAddress: account.address,
positionData,
deadline: BigInt(Math.floor(Date.now() / 1000) + 3_600), // Unix seconds, now + 1 hour
});
const signatures = [];
for (const req of await supplyCollateralBorrow.getRequirements()) {
if ("sign" in req) {
signatures.push(await req.sign(client, account.address));
} else {
await client.sendTransaction(req); // approval / setAuthorization
}
}
const txHash = await client.sendTransaction(supplyCollateralBorrow.buildTx(signatures));
console.log("Supply + borrow:", txHash);Supply collateral (only)
Private APIFor collateral only, use Blue Supply Collateral Asset. This example supplies 0.001 WETH on Base. Replace the public test account with the connected wallet and keep $MORPHO_API_KEY in your backend environment.
curl --silent --show-error --include \
--request POST \
'https://private.api.morpho.org/v0/actions/blue/markets/8453:0x8793cf302b8ffd655ab97bd1c695dbd967807e8367a65cb2f4edaf1380ba1bda/supply-collateral' \
--header "x-api-key: $MORPHO_API_KEY" \
--header 'Content-Type: application/json' \
--data-raw '{
"account": "0x4f620E5a62Eb51DA77502E8d3De7DB41f43e5695",
"amount": {
"unit": "assets",
"value": "1000000000000000"
},
"funding": {
"type": "erc20"
},
"signature_mode": "none"
}'| Response field | Check before sending |
|---|---|
data.status, data.action | Require prepared and blue.supply_collateral. |
data.simulation.status | Require success. A failed simulation has no executable calls. |
data.calls | Inspect targets, calldata, values, and approvals; preserve order. |
data.simulation.effects.supplied_collateral_assets | Compare the supplied collateral amount with the user's intent. |
Apply the same simulation, signed-proof, and calldata checks before wallet submission. This is an alternative to supplying collateral in the combined borrow request, not an additional step. Do not concatenate independently prepared call lists and assume atomicity.
Complete the Morpho SDK setup before using this SDK example.
To construct the action locally, follow the SDK collateral-supply example and its authorization flow.
Repay and withdraw collateral
Private APIUse Blue Repay with collateral_amount to repay and withdraw collateral atomically. This Base WETH/USDC example uses amount.unit: "all" for the full debt, then withdraws 0.001 WETH. It assumes a borrower position already exists and enough USDC is available for the actual debt and any fee. Replace the test account and keep the API key on your backend.
curl --silent --show-error --include \
--request POST \
'https://private.api.morpho.org/v0/actions/blue/markets/8453:0x8793cf302b8ffd655ab97bd1c695dbd967807e8367a65cb2f4edaf1380ba1bda/repay' \
--header "x-api-key: $MORPHO_API_KEY" \
--header 'Content-Type: application/json' \
--data-raw '{
"account": "0x4f620E5a62Eb51DA77502E8d3De7DB41f43e5695",
"amount": {
"unit": "all"
},
"collateral_amount": {
"unit": "assets",
"value": "1000000000000000"
},
"funding": {
"type": "erc20"
},
"signature_mode": "none"
}'| Repayment mode | amount |
|---|---|
| Exact loan assets | { "unit": "assets", "value": "1000000" } |
| Exact borrow shares | { "unit": "shares", "value": "1000000" } in borrow-share units, not token units. |
| Full debt | { "unit": "all" }, without value. Do not send the SDK's maxUint256 sentinel as an API share amount. |
| Response field | Check before sending |
|---|---|
data.status, data.action | Require prepared and blue.repay. |
data.max_repay_assets | Check the maximum loan-token spend, including the fee and share-mode interest accrual. |
data.simulation.status | Require success. A failed simulation has no executable calls. |
data.calls | Inspect targets, calldata, values, and approvals; preserve order. |
data.simulation.effects | Check repaid_assets, repaid_shares, referral_fee_assets, and withdrawn_collateral_assets. Inspect data.simulation.position_changes.borrow_shares and collateral_assets for the expected decreases. |
If status is signature_required, complete the signature and continuation flow before expecting calls. Do not send an error response or a simulation_failed result.
The user's wallet sends the returned calls, in order, only after checking the simulation, verifying the signed proof, and matching the calldata to your request, with user approval. Morpho does not submit transactions.
Repayment requires an existing debt position; otherwise the API returns 422 POSITION_EMPTY.
Optional repayment referral fee
The repayment route supports the same optional referral_fee object shown in the borrow tab: integer bps from 1 to 200 and a nonzero recipient chosen by the integrator. Omit it for no fee. The fee is added on top of loan assets actually repaid, not deducted from the debt repayment. Compare repaid_assets plus referral_fee_assets with the wallet's total loan-token spend. The standalone collateral-withdrawal route does not support this fee.
Complete the Morpho SDK setup before using this SDK example.
For full repayments, pass maxUint256 as the shares-mode repay input (repayShares): the contract replaces it with the position's live borrow shares, so the full debt is cleared regardless of interest accrued between quote and inclusion (no dust). Passing the position's freshly fetched borrowShares also works when the data is fresh. The operation order is encoded for you: repay first, then withdraw.
import { maxUint256, parseUnits } from "viem";
import { MarketParams } from "@morpho-org/morpho-sdk/entities";
const market = client.morpho.blue(
new MarketParams({
loanToken: "0xLoanToken...",
collateralToken: "0xCollateralToken...",
oracle: "0xOracle...",
irm: "0xIrm...",
lltv: 860000000000000000n, // 86%
}),
mainnet.id,
);
const fresh = await market.getPositionData(account.address);
const repayWithdrawCollateral = market.repayWithdrawCollateral({
repayShares: maxUint256, // full repay (saturated close; use { repayAssets } for partial)
collateralAssets: parseUnits("1.0", 18), // 1 wstETH
userAddress: account.address,
positionData: fresh,
deadline: BigInt(Math.floor(Date.now() / 1000) + 3_600),
});
const signatures = [];
for (const req of await repayWithdrawCollateral.getRequirements()) {
if ("sign" in req) {
signatures.push(await req.sign(client, account.address));
} else {
await client.sendTransaction(req); // loan-token approval / setAuthorization
}
}
const txHash = await client.sendTransaction(repayWithdrawCollateral.buildTx(signatures));
console.log("Repay + withdraw:", txHash);Need to move an existing borrower from one Morpho Blue market to another with the same loan and collateral tokens? Use refinance() to migrate the full collateral and debt atomically, with optional shared liquidity from the Vault V2 Public Allocator on the target market.
For separate, non-atomic flows (e.g. supplyCollateral only, borrow only, repay only, withdrawCollateral only), see the equivalent action documented on the Morpho SDK's Blue subpage.
Withdraw collateral (only)
Private APIFor collateral only, use Blue Withdraw Collateral Asset:
curl --silent --show-error --include \
--request POST \
'https://private.api.morpho.org/v0/actions/blue/markets/8453:0x8793cf302b8ffd655ab97bd1c695dbd967807e8367a65cb2f4edaf1380ba1bda/withdraw-collateral' \
--header "x-api-key: $MORPHO_API_KEY" \
--header 'Content-Type: application/json' \
--data-raw '{
"account": "0x4f620E5a62Eb51DA77502E8d3De7DB41f43e5695",
"amount": {
"unit": "assets",
"value": "1000000000000000"
},
"signature_mode": "none"
}'Require data.status: "prepared", data.action: "blue.withdraw_collateral", and data.simulation.status: "success". Inspect data.calls and the withdrawn_collateral_assets, ltv_bps, and max_ltv_bps simulation effects. Apply the same proof, simulation, and calldata checks before wallet submission; remaining collateral must keep the debt healthy. Do not send this separately if the combined repayment already withdraws the intended collateral. For repay only, omit collateral_amount.
Complete the Morpho SDK setup before using this SDK example.
To construct the action locally, follow the SDK collateral-withdrawal example and its authorization flow.
Supply loan asset
Private APILoan-asset supply creates a lending position. It does not supply collateral for borrowing.
Use Blue Supply Loan Asset to supply the loan asset, not collateral. This Base WETH/USDC example supplies 1 USDC from the account's ERC-20 balance. Replace the account and keep $MORPHO_API_KEY on your backend.
curl --silent --show-error --include \
--request POST \
'https://private.api.morpho.org/v0/actions/blue/markets/8453:0x8793cf302b8ffd655ab97bd1c695dbd967807e8367a65cb2f4edaf1380ba1bda/supply' \
--header "x-api-key: $MORPHO_API_KEY" \
--header 'Content-Type: application/json' \
--data-raw '{
"account": "0x4f620E5a62Eb51DA77502E8d3De7DB41f43e5695",
"amount": {
"unit": "assets",
"value": "1000000"
},
"funding": {
"type": "erc20"
},
"signature_mode": "none"
}'| Response field | Check before sending |
|---|---|
data.status, data.action | Require prepared and blue.supply. |
data.simulation.status | Require success. A failed simulation has no executable calls. |
data.calls | Inspect targets, calldata, values, and approvals; preserve order. |
data.simulation.effects | Check gross_assets, referral_fee_assets, and net_assets. Inspect data.simulation.position_changes.supply_shares for the expected increase. |
If status is signature_required, complete the signature and continuation flow before expecting calls. Do not send an error response or a simulation_failed result.
The user's wallet sends the returned calls, in order, only after checking the simulation, verifying the signed proof, and matching the calldata to your request, with user approval. Morpho does not submit transactions.
Complete the Morpho SDK setup before using this SDK example.
To construct the action locally, follow the SDK loan-asset supply example and its authorization flow.
Withdraw loan asset
Private APIUse Blue Withdraw Loan Asset to withdraw supplied loan assets, not collateral. This example requests 1 USDC from the same Base market. Replace the account and keep the API key on your backend. The account must have an existing supply position.
curl --silent --show-error --include \
--request POST \
'https://private.api.morpho.org/v0/actions/blue/markets/8453:0x8793cf302b8ffd655ab97bd1c695dbd967807e8367a65cb2f4edaf1380ba1bda/withdraw' \
--header "x-api-key: $MORPHO_API_KEY" \
--header 'Content-Type: application/json' \
--data-raw '{
"account": "0x4f620E5a62Eb51DA77502E8d3De7DB41f43e5695",
"amount": {
"unit": "assets",
"value": "1000000"
},
"signature_mode": "none"
}'| Withdrawal mode | amount |
|---|---|
| Exact loan assets | { "unit": "assets", "value": "1000000" } |
| Exact supply shares | { "unit": "shares", "value": "1000000" } in supply-share units. |
| Maximum available | { "unit": "all" }, without value. This can leave supplied assets or residual shares when liquidity is insufficient. |
| Response field | Check before sending |
|---|---|
data.status, data.action | Require prepared and blue.withdraw. |
data.simulation.status | Require success. A failed simulation has no executable calls. |
data.calls | Inspect targets, calldata, values, and approvals; preserve order. |
data.simulation.effects | Check gross_assets, referral_fee_assets, and net_assets. Inspect data.simulation.position_changes.supply_shares for the expected decrease. |
If status is signature_required, complete the signature and continuation flow before expecting calls. Do not send an error response or a simulation_failed result.
The user's wallet sends the returned calls, in order, only after checking the simulation, verifying the signed proof, and matching the calldata to your request, with user approval. Morpho does not submit transactions.
A preparation error or failed simulation is not a withdrawal. The API may use shared liquidity automatically. For custom SDK planning, review the Public Allocator guide; do not append a separately prepared plan to signed API calls. Check the simulated position change rather than assuming that all clears the balance.
Complete the Morpho SDK setup before using this SDK example.
To construct the action locally, follow the SDK loan-asset withdrawal example. For shared liquidity, use the Public Allocator planning guide.