Docs

Lend from a Morpho Blue position

Keep lend-offer assets supplied to Morpho Blue until a Midnight borrower takes them, then publish, cancel, and recover callback-backed offers.

Snippets use Morpho SDK 9.5.1 and reuse the client and midnight objects from its Setup section, with maker set to your wallet address.

How it works

The offer names a BlueBuyCallback contract instead of relying on your wallet balance. That contract belongs to you and holds a Morpho Blue supply position. When a borrower takes the offer, the callback withdraws exactly the amount taken from Morpho Blue and Midnight settles with it, in the borrower's transaction.

supplyBlueMakeLend does the setup in one MidnightBundlesV2 transaction:

  1. Creates your BlueBuyCallback through the BlueBuyCallbackFactory, if it doesn't exist yet.
  2. Pulls the loan tokens from your wallet and supplies them to the chosen Morpho Blue market on behalf of the callback.
  3. Activates the offer root on PriceRatifierV1 or RateRatifierV1 and publishes the offers.

Because the callback is created in the same transaction as the offers, it is registered before they are posted. The Morpho API and router only treat an offer as blue_buy when its callback was registered to the maker in the official factory at or before the offer was created.

The assets stay in the callback's Morpho Blue position until a take uses them or you withdraw them. Cancelling or letting the offer expire does not move them.

Choose the Morpho Blue market and the callback

Pick a Morpho Blue market whose loan token is the loan token of the Midnight market you lend on. The callback rejects a take when the two loan tokens differ, and the SDK rejects the offers before publishing.

MidnightBundlesV2 doesn't check the Morpho Blue supply share price, so pick a market that is protected against supply share price inflation. The SDK rejects a Morpho Blue market with no supply shares, and an amount that would mint zero shares.

The callback address depends on your address and a salt you choose. The same salt always gives the same callback, so the salt decides which offer groups share one callback and its assets. See Which callback an offer uses and How the Morpho app uses callbacks.

import { keccak256, toHex } from "viem";
import { base } from "viem/chains";
import {
  getMidnightBlueBuyCallbackAddress,
  getMidnightBlueBuyCallbackData,
} from "@morpho-org/morpho-sdk";
import { fetchBlueMarketParams } from "@morpho-org/morpho-sdk/fetch";
import type { BlueMarketId } from "@morpho-org/morpho-sdk/types";

// The Morpho Blue market that holds the assets while the offer waits.
const blueMarketId = "0xBlueMarketId..." as BlueMarketId;
const blueMarket = await fetchBlueMarketParams(blueMarketId, client);

// Any bytes32 value. Store it: you need it to find the callback again.
const callbackSalt = keccak256(toHex("my-lend-offer-1"));

// The callback address is computed locally. The contract may not exist yet.
const callback = getMidnightBlueBuyCallbackAddress({
  chainId: base.id,
  owner: maker,
  salt: callbackSalt,
});

// Tells the callback which Morpho Blue market to withdraw from.
const callbackData = getMidnightBlueBuyCallbackData(blueMarket);

Build the lend offers

For API-prepared publication, use the Morpho API tab in Publish the offers. It selects variable-rate funding and constructs the callback-backed offers for you. The manual SDK construction below remains useful when choosing your own callback salt.

Every offer must set callback to your callback address and callbackData to the encoded Morpho Blue market. Only lend offers (buy: true) can use this callback, and they can't be reduce-only.

import { parseUnits, zeroAddress } from "viem";
import { addresses } from "@morpho-org/morpho-sdk/addresses";
import { Offer } from "@morpho-org/morpho-sdk/midnight/entities";

const marketData = await midnight.getMarketData(marketId);

// Offer expiry: now + 7 days, capped at the market's maturity.
const offerExpiry = BigInt(
  Math.min(Number(marketData.params.maturity), Math.floor(Date.now() / 1000) + 604_800),
);

const lendOffer = Offer.create({
  market: marketData.params,
  maker,
  buy: true,
  tick: 5_000n,
  maxAssets: parseUnits("250000", 6),
  expiry: offerExpiry,
  ratifier: addresses[base.id].priceRatifierV1!,
  callback,
  callbackData,
});

How much a borrower can take is the smallest of three amounts: what is left of the offer group's size, the callback's Morpho Blue supply, and the liquidity that can be withdrawn from that Morpho Blue market. See How the router recognizes the liquidity.

The offer size is your choice. A fixed maxAssets, as above, caps fills at that amount. With maxAssets set to maxUint128, the offer size follows whatever the callback holds on Morpho Blue. See Sizing callback-backed offers for the trade-offs.

Use Publish Midnight lend offers with funding_source.type: "variable_rate_market" to prepare callback-backed publication without constructing offers by hand.

Set MIDNIGHT_MARKET_ID to a currently active Base market with USDC as its loan token. Replace the public test account with the connected wallet and keep $MORPHO_API_KEY on your backend. The shell computes fresh Unix timestamps in seconds. Shorten EXPIRES_AT if needed: it must be after STARTS_AT and no later than the market's maturity. Set BLUE_MARKET_ID to a Morpho Blue market on Base with the same USDC loan token. The 20-USDC amount is supplied from the wallet to the dedicated funding address's Morpho Blue position, not the account's own lending position.

STARTS_AT=$(date +%s)
EXPIRES_AT=$((STARTS_AT + 3600))

curl --silent --show-error --include \
  --request POST \
  "https://private.api.morpho.org/v0/actions/midnight/offers/lend" \
  --header "x-api-key: $MORPHO_API_KEY" \
  --header 'Content-Type: application/json' \
  --data-binary @- <<JSON
{
  "account": "0x4f620E5a62Eb51DA77502E8d3De7DB41f43e5695",
  "chain_id": 8453,
  "amount": {
    "unit": "assets",
    "value": "20000000"
  },
  "funding_source": {
    "type": "variable_rate_market",
    "market_id": "$BLUE_MARKET_ID"
  },
  "funding": {
    "type": "erc20"
  },
  "offers": {
    "type": "rate",
    "entries": [
      {
        "market_id": "$MIDNIGHT_MARKET_ID",
        "rate_wad": "1585489599",
        "starts_at": $STARTS_AT,
        "expires_at": $EXPIRES_AT
      }
    ]
  }
}
JSON

The rate parameter 1585489599 corresponds to 5% APR; it is a chosen offer rate, not a return forecast. Each entry carries the cap, but fills across the group share one total budget. Entries can target several Midnight markets on the same chain and loan token. The API controls the funding callback; it does not expose the SDK's custom callbackSalt or atomic replacement cancellations options.

Public offer admission can reject a preparation with ACTION_UNSUPPORTED and detail code min_offer_assets_usd. This is an admission rule, not a request field or a fixed minimum for every token and time. The examples use 20 USDC or its face-value units; check the current rule and resulting offer value. Offer publication does not support referral_fee.

Response fieldCheck before sending
data.status, data.actionRequire prepared and midnight.make_lend.
data.simulation.statusRequire success; a failed simulation has no executable calls.
data.callsInspect targets, calldata, values, and approvals; preserve order.
data.offer.groups, data.offer.entry_countCheck the intended group identifiers and entry count.
data.simulation.effects, data.simulation.wallet_changes, data.simulation.position_changesPublication is not a fill. Check the publication groups and count, and any funding movement.
data.funding_address, data.funding_marketRecord the dedicated funding address and Blue market for later asset recovery.

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 and verifying the signed proof, with user approval. Morpho does not submit transactions.

import { maxUint256, parseUnits } from "viem";

const supplyBlueMakeLend = await midnight.supplyBlueMakeLend({
  accountAddress: maker,
  offers: {
    type: "priceV1",
    entries: [{ offer: lendOffer, allowedTaker: zeroAddress }],
  },
  blueMarket,
  assetsToPark: parseUnits("250000", 6), // loan tokens supplied to Morpho Blue for the callback
  callbackSalt,
  deadline: maxUint256,
});

// A loan-token approval to MidnightBundlesV2 and the MidnightBundlesV2 authorization, when missing.
for (const requirement of await supplyBlueMakeLend.getRequirements()) {
  const hash = await client.sendTransaction(requirement);
  await client.waitForTransactionReceipt({ hash });
}
const publishHash = await client.sendTransaction(supplyBlueMakeLend.buildTx());
const publishReceipt = await client.waitForTransactionReceipt({ hash: publishHash });
if (publishReceipt.status !== "success") throw new Error("Publication failed");

To add assets or replace the offers later, call supplyBlueMakeLend again with the same callbackSalt. Pass the previous groups in cancellations to cancel them in the same transaction. The new amount is added to the same callback's Morpho Blue position.

See the supplyBlueMakeLend errors for the checks the SDK runs before building the transaction.

Back offers on several markets

One callback can back lend offers on several Midnight markets that share the same loan token. Put the offers in one group so they share one size budget: a fill on any market reduces what is left on all of them. See Multi-market offers.

All offers point to the same callback and the same Morpho Blue market, so every fill withdraws from the same Morpho Blue position.

import { Group } from "@morpho-org/morpho-sdk/midnight/entities";

const [marketA, marketB] = await Promise.all([
  midnight.getMarketData(marketIdA),
  midnight.getMarketData(marketIdB),
]);

// Every offer must expire at or before its own market's maturity, so cap at the earliest one.
const multiMarketExpiry = BigInt(
  Math.min(
    Number(marketA.params.maturity),
    Number(marketB.params.maturity),
    Math.floor(Date.now() / 1000) + 604_800,
  ),
);

// A separate salt gives this group its own callback and assets, apart from the first example.
const multiMarketSalt = keccak256(toHex("my-multi-market-offer-1"));
const multiMarketCallback = getMidnightBlueBuyCallbackAddress({
  chainId: base.id,
  owner: maker,
  salt: multiMarketSalt,
});

const commonOffer = {
  maker,
  buy: true,
  maxAssets: parseUnits("250000", 6), // one budget for both markets
  expiry: multiMarketExpiry,
  ratifier: addresses[base.id].priceRatifierV1!,
  callback: multiMarketCallback,
  callbackData,
} as const;

const group = Group.create([
  Offer.create({ ...commonOffer, market: marketA.params, tick: 5_000n }),
  Offer.create({ ...commonOffer, market: marketB.params, tick: 5_012n }),
]);

const multiMarket = await midnight.supplyBlueMakeLend({
  accountAddress: maker,
  offers: {
    type: "priceV1",
    entries: group.offers.map((offer) => ({ offer, allowedTaker: zeroAddress })),
  },
  blueMarket,
  assetsToPark: parseUnits("250000", 6),
  callbackSalt: multiMarketSalt,
  deadline: maxUint256,
});

Use Cancel Midnight offer groups for complete cancellation first. It does not withdraw the callback's supplied funding; use the funding withdrawal route below only after cancellation confirms.

Set MIDNIGHT_GROUP_ID to a group owned by the account, returned by the publication response's data.offer.groups or the user's offer-groups read endpoint. Use the group ID without a chain prefix. Replace the test account and keep $MORPHO_API_KEY on your backend.

curl --silent --show-error --include \
  --request POST \
  "https://private.api.morpho.org/v0/actions/midnight/offers/cancel" \
  --header "x-api-key: $MORPHO_API_KEY" \
  --header 'Content-Type: application/json' \
  --data-binary @- <<JSON
{
  "account": "0x4f620E5a62Eb51DA77502E8d3De7DB41f43e5695",
  "chain_id": 8453,
  "groups": [
    "$MIDNIGHT_GROUP_ID"
  ]
}
JSON
Response fieldCheck before sending
data.status, data.actionRequire prepared and midnight.cancel_offers.
data.simulation.statusRequire success; a failed simulation has no executable calls.
data.callsInspect targets, calldata, values, and approvals; preserve order.
data.groups, data.simulation.effectsCheck exactly the intended groups are cancelled.
data.simulation.wallet_changes, data.simulation.position_changesCancellation must not be mistaken for recovery of the callback's funding.

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 and verifying the signed proof, with user approval. Morpho does not submit transactions.

A newly published group may return ACTION_UNSUPPORTED until it is indexed; retry only after the group is returned by the read API. Cancellation leaves assets at funding_address in funding_market. It does not cancel other groups sharing the callback, and it does not recover assets from expired offers.

Withdraw the supplied funding

After cancellation is confirmed, use Withdraw a lend offer's supplied funding. Confirm cancellation or expiry for every offer backed by this funding address before requesting and sending the withdrawal. The route does not cancel offers or check cancellation or expiry itself.

Set FUNDING_ADDRESS to the publication response's data.funding_address and FUNDING_MARKET_ID to data.funding_market.id, without a chain prefix. The route withdraws the funding address's entire Morpho Blue supply position to account, not just the assets assigned to one offer group.

curl --silent --show-error --include \
  --request POST \
  "https://private.api.morpho.org/v0/actions/midnight/offers/funding/withdraw" \
  --header "x-api-key: $MORPHO_API_KEY" \
  --header 'Content-Type: application/json' \
  --data-binary @- <<JSON
{
  "account": "0x4f620E5a62Eb51DA77502E8d3De7DB41f43e5695",
  "chain_id": 8453,
  "funding_address": "$FUNDING_ADDRESS",
  "funding_market": "$FUNDING_MARKET_ID"
}
JSON
Response fieldCheck before sending
data.status, data.actionRequire prepared and midnight.withdraw_funding.
data.account, data.chain_id, data.funding_address, data.market.idMatch the intended wallet, chain, funding address, and Morpho Blue market.
data.simulation.statusRequire success; reverted or unverifiable simulations are rejected.
data.callsExpect exactly one call withdrawing all supply shares to the account; inspect target, calldata, and value.
data.simulation.effects, data.simulation.position_changes, data.simulation.wallet_changesCheck the burned shares, received assets, and loan-token receipt by the account.

The route accepts no amount or signature continuation. POSITION_EMPTY means there is nothing to withdraw; SHARED_LIQUIDITY_INSUFFICIENT means the market cannot cover the full position. Do not send calls after any error. expires_at is an offchain response-validity timestamp, not an onchain deadline.

The user's wallet sends the returned call only after checking the simulation and verifying the signed proof, with user approval. Morpho does not submit transactions.

Cancelling stops the offers but leaves the assets in the callback's Morpho Blue position. Withdraw them as a second step.

The callback authorizes you on Morpho Blue when it is created, so you can withdraw its position to your wallet with a regular Morpho Blue withdraw, passing the callback as onBehalf. Withdrawing alone doesn't cancel the offers: they stay published and can be filled again if assets are supplied to the callback again.

The Morpho app cancels first, then withdraws in a separate transaction, so a failed withdrawal can't undo the cancellation.

import { maxUint128, maxUint256 } from "viem";
import { blueAbi } from "@morpho-org/morpho-sdk/abis";
import { getChainAddress } from "@morpho-org/morpho-sdk/addresses";

// 1. Cancel the offer groups returned when they were published.
const cancelOffers = midnight.cancelOffers({
  accountAddress: maker,
  cancellations: supplyBlueMakeLend.groups.map((group) => ({ group, maxConsumed: maxUint128 })),
  deadline: maxUint256,
});
for (const requirement of await cancelOffers.getRequirements()) {
  const hash = await client.sendTransaction(requirement);
  await client.waitForTransactionReceipt({ hash });
}
const cancelHash = await client.sendTransaction(cancelOffers.buildTx());
const cancelReceipt = await client.waitForTransactionReceipt({ hash: cancelHash });
// Withdraw only once the cancellation has landed, so no take can use the assets in between.
if (cancelReceipt.status !== "success") throw new Error("Cancellation failed");

// 2. Withdraw all of the callback's supply shares to your wallet.
const blue = getChainAddress(base.id, "blue");
const [supplyShares] = await client.readContract({
  address: blue,
  abi: blueAbi,
  functionName: "position",
  args: [blueMarketId, callback],
});

// Morpho Blue reverts a withdrawal of zero shares, so skip an empty position.
if (supplyShares > 0n) {
  await client.writeContract({
    address: blue,
    abi: blueAbi,
    functionName: "withdraw",
    args: [blueMarket, 0n, supplyShares, callback, maker], // assets, shares, onBehalf, receiver
  });
}

The withdrawal reverts when the Morpho Blue market doesn't have enough liquidity for the full amount. Withdraw a smaller amount, or try again when liquidity comes back.

If several offer groups share the callback (same salt), withdrawing its position also removes the assets that back the groups that are still open.

Confirm the offers have expired first, including any other groups sharing their funding address. If an active or scheduled group still uses that address, confirm its cancellation before withdrawing. This route does not check offer status.

Use Withdraw a lend offer's supplied funding with FUNDING_ADDRESS and FUNDING_MARKET_ID retained from the publication response's data.funding_address and data.funding_market.id. It withdraws the funding address's entire Morpho Blue supply position to the account. Keep $MORPHO_API_KEY on your backend.

curl --silent --show-error --include \
  --request POST \
  "https://private.api.morpho.org/v0/actions/midnight/offers/funding/withdraw" \
  --header "x-api-key: $MORPHO_API_KEY" \
  --header 'Content-Type: application/json' \
  --data-binary @- <<JSON
{
  "account": "0x4f620E5a62Eb51DA77502E8d3De7DB41f43e5695",
  "chain_id": 8453,
  "funding_address": "$FUNDING_ADDRESS",
  "funding_market": "$FUNDING_MARKET_ID"
}
JSON
Response fieldCheck before sending
data.status, data.actionRequire prepared and midnight.withdraw_funding.
data.account, data.chain_id, data.funding_address, data.market.idMatch the intended wallet, chain, funding address, and Morpho Blue market.
data.simulation.statusRequire success; reverted or unverifiable simulations are rejected.
data.callsExpect exactly one call withdrawing all supply shares to the account; inspect target, calldata, and value.
data.simulation.effects, data.simulation.position_changes, data.simulation.wallet_changesCheck the burned shares, received assets, and loan-token receipt by the account.

The route accepts no amount or signature continuation. POSITION_EMPTY means there is nothing to withdraw; SHARED_LIQUIDITY_INSUFFICIENT means the market cannot cover the full position. Do not send calls after any error. expires_at is an offchain response-validity timestamp, not an onchain deadline.

The user's wallet sends the returned call only after checking the simulation and verifying the signed proof, with user approval. Morpho does not submit transactions.

To discover expired groups when you no longer have the publication response, use the read-API discovery in the Morpho SDK tab. Check all groups sharing a funding address before recovering its position.

An expired offer can't be taken, but its assets are still in the callback's Morpho Blue position. List your expired callback groups with the API, then withdraw each callback's position as above.

The endpoint returns at most 100 groups per page: keep the same filters and pass each returned cursor until it is null. Several groups can point to the same callback and Morpho Blue market, so withdraw each pair of callback_address and market_id once, and skip it when its supply shares are zero. Also skip a pair that still backs an active or scheduled group, such as replacement offers published with the same salt, or cancel those groups first: withdrawing would leave them published with no assets behind them.

GET https://api.morpho.org/v0/midnight/users/{maker}/offer-groups
  ?chain_ids=8453
  &statuses=expired
  &callback_type=blue_buy

Each returned group has a callback object with the callback address and the Morpho Blue market it holds assets in:

import type { Address } from "viem";

type BlueBuyCallbackInfo = {
  callback_address: string;
  market_id: string;
  market_params: {
    loan_token: string;
    collateral_token: string;
    oracle_address: string;
    irm_address: string;
    lltv_wad: string;
  };
};

const withdrawArgs = ({ callback_address, market_id, market_params }: BlueBuyCallbackInfo) => {
  return {
    callback: callback_address as Address,
    blueMarketId: market_id as BlueMarketId,
    blueMarket: {
      loanToken: market_params.loan_token as Address,
      collateralToken: market_params.collateral_token as Address,
      oracle: market_params.oracle_address as Address,
      irm: market_params.irm_address as Address,
      lltv: BigInt(market_params.lltv_wad),
    },
  };
};

The same applies to cancelled groups, and to filled groups whose callback still holds interest or leftover assets. The callback_type=blue_buy filter only returns verified callbacks. To find the others, see Find every callback that may still hold assets.

Tokens held by the callback contract itself, outside Morpho Blue, such as rewards earned by its Morpho Blue position, can be sent to you with the callback's skim(token) function. Anyone can call it, and it always pays the callback's owner.