Docs

Borrow at a fixed rate

Build a Midnight borrower flow that finds markets, quotes an offer, authorizes the transaction, and borrows at a fixed rate.

For the Python examples, install Requests with pip install requests.

To keep the loan open past maturity, the position can move to a variable rate Morpho Blue market through fallback rolling instead of staying on Midnight.

Browse markets

Public API

Fetch the list of books filtered by chain and loan token. Each book represents one market with its top ask/bid price levels:

GET https://api.morpho.org/v0/midnight/books
  ?chain_ids=8453                                                // Base
  &loan_tokens=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913        // USDC on Base
  &sort=maturity

// Response (each book is one market with its top ask/bid levels)
{
  "cursor": "eyJzb3J0Ijpb...",                                  // null when there is no next page
  "data": [
    {
      "market_id": "0xd92de5e7fbb...7614",                       // use this ID in the next step
      "chain_id": 8453,
      "midnight": "0xAdedD8ab6dE832766Fedf0FaC4992E5C4D3EA18A",
      "loan_token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "collaterals": [
        {
          "token": "0x4200000000000000000000000000000000000006", // WETH on Base
          "lltv": "770000000000000000",                          // 77% LTV
          "liquidation_cursor": "250000000000000000",
          "oracle": "0xD09048c8B568Dbf5f189302beA26c9edABFC4858"
        }
      ],
      "maturity": 1798761600,                                    // January 1, 2027
      "rcf_threshold": "0",
      "enter_gate": "0x0000000000000000000000000000000000000000",
      "liquidator_gate": "0x0000000000000000000000000000000000000000",

      "asks": [
        { "tick": 4990, "price": "957900000000000000", "units": "5000000000", "assets": "4789500000", "count": 1 }
      ], // lending side; ignore for borrowing

      // ┌──────────────────────────────────────────────────────────────┐
      // │  FOR BORROWING → read the BIDS                               │
      // │  Bids = lenders buying units = offering to lend you money    │
      // │  You (the borrower) take these bids = sell your units        │
      // │  The bid price is what you receive per unit → your cost      │
      // └──────────────────────────────────────────────────────────────┘
      "bids": [
        {
          "tick": 4988,
          "price": "956937000000000000",                         // ≈ 0.9569 per unit
          "units": "8000000000",
          "assets": "7655497000",                               // ≈ 7,655 USDC on the bid
          "count": 2
        },
        {
          "tick": 4976,
          "price": "951000000000000000",                         // ≈ 0.9510 (worse for borrower)
          "units": "12000000000",
          "assets": "11412000000",
          "count": 4
        }
      ]
    }
  ]
}

Select market & estimate borrow rate

The best bid is the highest price. Higher means you receive more per unit sold, so lower borrowing cost.

// Select book data
const book = response.data[0];

// Obtain best bid price (highest = cheapest to borrow)
const bestBidPrice = Number(book.bids[0].price) / 1e18;          // ≈ 0.9569

// Calculate time to maturity (ttm) in seconds
const ttm = book.maturity - Date.now() / 1000;

// Calculate fixed borrow APR
const borrowAPR = (1 / bestBidPrice - 1) * (365 * 86400) / ttm;
console.log(`Borrow APR: ${(borrowAPR * 100).toFixed(2)}%`);

// If the rate looks good, save the market ID for the next step
const marketId = book.market_id;                                 // "0xd92de5e7fbb...7614"

Step 1: Get a quote

Specify the amount of USDC you want to borrow from a market with slippage. Morpho's router returns executable takeable offers (quotes against the bids) with fallback liquidity. The total may exceed your target so the Bundles call can skip stale offers and still take offers.

Set the server-side environment variable MIDNIGHT_MARKET_ID to the marketId selected in the previous step.

The quote's assets value must equal loanAssets, the amount later passed to the contract call.

const loanAssets = 10_000_000_000n; // 10,000 USDC (6 decimals)
curl --silent --show-error --include \
  --request GET \
  "https://api.morpho.org/v0/midnight/books/$MIDNIGHT_MARKET_ID/bids/quote?assets=10000000000&slippage=0.5&limit=10000"
// Response - the Router's execution plan:
{
  "data": {
    "average_best_price": "956937000000000000", // realized target fill using onchain per-offer rounding, rounded against the taker
    "average_worst_price": "952200000000000000", // conservative adverse-placement bound across returned caps; not the slippage-derived guard
    "available_assets": "14000000000", // max assets in this returned limit window
    "available_units": "14630000000", // max units in this returned limit window
    "takeable_offers": [
      {
        "market_id": "0xd92de5e7fbb...7614",
        "units": "8000000000", // maximum this offer may contribute, not an exact allocation
        "offer": {
          "market": {
            "chain_id": 8453,
            "midnight": "0xAdedD8ab6dE832766Fedf0FaC4992E5C4D3EA18A",
            "loan_token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
            "collaterals": [
              {
                "token": "0x4200000000000000000000000000000000000006",
                "lltv": "770000000000000000",
                "liquidation_cursor": "250000000000000000",
                "oracle": "0xD09048c8B568Dbf5f189302beA26c9edABFC4858"
              }
            ],
            "maturity": 1798761600,
            "rcf_threshold": "0",
            "enter_gate": "0x0000000000000000000000000000000000000000",
            "liquidator_gate": "0x0000000000000000000000000000000000000000"
          },
          "buy": true, // buy offer (bid): the maker is lending
          "maker": "0x7b093658BE7f90B63D7c359e8f408e503c2D9401",
          "max_units": "8000000000",
          "start": 1761922790,
          "expiry": 1786147200,
          "tick": 4988,
          "group": "0x000000000000000000000000000000000000000000000000000000000008b8f4",
          "callback": "0x0000000000000000000000000000000000000000",
          "callback_data": "0x",
          "receiver_if_maker_is_seller": "0x7b093658BE7f90B63D7c359e8f408e503c2D9401",
          "ratifier": "0x0000000000000000000000000000000000000002",
          "reduce_only": false,
          "max_assets": "0",
          "continuous_fee_cap": "115792089237316195423570985008687907853269984665640564039457584007913129639935"
        },
        "ratifier_data": "0x7c1e...d402",
        "valid_until": 1786147200,
        "warning": null
      }
      // Additional complete offers follow in best-price order as fallback excess.
    ]
  }
}

// Interpreting the quote
const quote = response.data;
const avgPrice = Number(quote.average_best_price) / 1e18; // 0.9569
const borrowAPR = (1 / avgPrice - 1) * (365 * 86400) / ttm;

// To borrow 10,000 USDC at price ≈ 0.9569 you sell ≈ 10,450 units
// At maturity you repay 10,450 USDC → net cost ≈ 450 USDC
const unitsToSell = Math.ceil(10000e6 / avgPrice);

Step 2: Convert takeable offers to ABI-encoded data

The quote API returns snake_case JSON, whereas the onchain ABI expects camelCase tuples. The apiOfferToAbi helper converts the API offer to an ABI struct.

const apiOfferToAbi = ({ offer, ratifier_data, units }) => ({
  offer: {
    market: {
      chainId: BigInt(offer.market.chain_id),
      midnight: offer.market.midnight,
      loanToken: offer.market.loan_token,
      collateralParams: offer.market.collaterals.map(({ token, lltv, liquidation_cursor, oracle }) => ({
        token,
        lltv: BigInt(lltv),
        liquidationCursor: BigInt(liquidation_cursor),
        oracle,
      })),
      maturity: BigInt(offer.market.maturity),
      rcfThreshold: BigInt(offer.market.rcf_threshold),
      enterGate: offer.market.enter_gate,
      liquidatorGate: offer.market.liquidator_gate,
    },
    buy: offer.buy,
    maker: offer.maker,
    start: BigInt(offer.start),
    expiry: BigInt(offer.expiry),
    tick: BigInt(offer.tick),
    group: offer.group,
    callback: offer.callback,
    callbackData: offer.callback_data,
    receiverIfMakerIsSeller: offer.receiver_if_maker_is_seller,
    ratifier: offer.ratifier,
    reduceOnly: offer.reduce_only,
    maxUnits: BigInt(offer.max_units),
    maxAssets: BigInt(offer.max_assets),
    continuousFeeCap: BigInt(offer.continuous_fee_cap),
  },
  ratifierData: ratifier_data,
  units: BigInt(units),
});

const takes = quote.takeable_offers.map(apiOfferToAbi);

Endpoint references: Get quote

MidnightApi.fetchBookQuote wraps the quote endpoint as part of the Morpho SDK's Midnight API helpers and returns ABI-ready take objects

Step 1: Install dependencies

npm install @morpho-org/morpho-sdk viem

Step 2: Get ABI-ready takeable offers

import { MidnightApi } from "@morpho-org/morpho-sdk/midnight-api";

const loanAssets = 10_000_000_000n; // 10,000 USDC (6 decimals)
const quote = await MidnightApi.fetchBookQuote({
  marketId,
  side: "bids",
  assets: loanAssets,
  slippage: "0.5",
});
const takes = quote.data.takeableOffers;
const borrowAPR =
  (1 / (Number(quote.data.averageBestPrice) / 1e18) - 1) * (365 * 86400) / ttm;

The SDK wraps the quote endpoint and uses Morpho's router by default with no config.

The Morpho SDK path derives the collateral (WETH) approval and any required MidnightBundlesV2 authorization, applies your rate guard, and builds an atomic supply-and-borrow transaction. The Contract call tab shows the manual equivalent. Hold sufficient collateral for the debt units owed at maturity (maxUnits plus any existing debt), sized at the market's LLTV.

Use Midnight Borrow to take existing lend offers across the selected market, with collateral supplied atomically. The API prepares its own quote and authorization calls; do not append the SDK or Contract tab's separately built calls.

If the API is unavailable or rejects the request, use the Morpho SDK tab with your own RPC, or the Contract call tab below to build the transaction directly. See the Midnight SDK page; do not send calls from a rejected API response.

Use a Base market whose loan token is USDC. Set MIDNIGHT_MARKET_SELECTOR to 8453:MARKET_ID from the read step and replace the public test account below with the connected wallet. Amounts are integer strings in token base units. Keep $MORPHO_API_KEY on your backend. This collateral example requires a market configured with WETH. It supplies 0.005 WETH and requests 1 USDC; choose collateral sufficient for all debt at the market's LLTV.

curl --silent --show-error --include \
  --request POST \
  "https://private.api.morpho.org/v0/actions/midnight/markets/$MIDNIGHT_MARKET_SELECTOR/borrow" \
  --header "x-api-key: $MORPHO_API_KEY" \
  --header 'Content-Type: application/json' \
--data-raw '{
  "account": "0x4f620E5a62Eb51DA77502E8d3De7DB41f43e5695",
  "amount": {
    "unit": "assets",
    "value": "1000000"
  },
  "collateral_supplies": [
    {
      "collateral": {
        "address": "0x4200000000000000000000000000000000000006"
      },
      "amount": {
        "unit": "assets",
        "value": "5000000000000000"
      }
    }
  ],
  "funding": {
    "type": "erc20"
  },
  "referral_fee": {
    "bps": 10,
    "recipient": "0x1111111111111111111111111111111111111111"
  },
  "guard": {
    "type": "slippage",
    "bps": 50
  }
}'
Response fieldCheck before sending
data.status, data.actionRequire prepared and midnight.borrow.
data.simulation.statusRequire success; a failed simulation has no executable calls.
data.callsInspect targets, calldata, values, and approvals; preserve order.
data.market, data.quote, data.max_borrow_unitsConfirm market, available quote, prices, and the maximum debt owed at maturity.
data.simulation.effects, data.simulation.position_changesCheck borrowed assets and units, supplied collateral, and the debt/collateral changes.
data.referral_fee, data.simulation.effects.referral_fee_assetsMatch the optional fee configuration and inspect the loan-token fee in base units, alongside wallet changes and the maximum debt.

Optional referral fee

The market borrow route accepts optional referral_fee: integer bps from 1 to 200 and a checksummed, nonzero recipient chosen by the integrator. The recipient must differ from the borrowing account. Omit the object for no fee; do not send bps: 0. The 10-bps recipient above is an example, not a required destination.

For market borrow, an assets target is the exact amount received by the account after the fee. The action obtains the additional loan assets needed for the fee and transfers them to the recipient; inspect the quote, fee, and resulting debt rather than assuming the debt equals the amount received.

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.

Take one selected offer group instead

Midnight Take Offer is an alternative to the market-wide request, not another call list to concatenate. Set MIDNIGHT_GROUP_SELECTOR to 8453:GROUP_ID for a currently active lend-offer group (buy: true) and MIDNIGHT_MARKET_ID to its selected market. The position must already have sufficient collateral. guard.bps: 50 is a 50-basis-point slippage guard, not slippage_bps.

curl --silent --show-error --include \
  --request POST \
  "https://private.api.morpho.org/v0/actions/midnight/offer-groups/$MIDNIGHT_GROUP_SELECTOR/take" \
  --header "x-api-key: $MORPHO_API_KEY" \
  --header 'Content-Type: application/json' \
  --data-binary @- <<JSON
{
  "account": "0x4f620E5a62Eb51DA77502E8d3De7DB41f43e5695",
  "market_id": "$MIDNIGHT_MARKET_ID",
  "amount": {
    "unit": "assets",
    "value": "1000000"
  },
  "referral_fee": {
    "bps": 10,
    "recipient": "0x1111111111111111111111111111111111111111"
  },
  "guard": {
    "type": "slippage",
    "bps": 50
  }
}
JSON

For this alternative require midnight.take_borrow, inspect data.group, data.market, data.quote, data.max_borrow_units, effects, and position changes, then apply the same simulation, call, and proof checks above. Check current collateral and offers before taking; an unhealthy position returns 422 POSITION_UNHEALTHY without executable calls.

On the borrow side, selected-group take accepts the same optional referral_fee bounds and recipient restrictions. Its assets target is described by the take schema as the loan assets taken before the optional fee. Inspect the returned fee, data.simulation.effects.referral_fee_assets, wallet changes, and resulting debt before sending; do not assume market-borrow and take amount targets are interchangeable. Offer publication does not accept this option.

For a collateral-only top-up, use Midnight Supply Collateral. It takes one configured ERC-20 collateral and an assets amount, without native funding or a signature continuation. Expect midnight.supply_collateral, inspect max_collateral_approval_assets, supplied collateral effects, and the resulting position, and apply the same checks before sending.

Extend walletClient and hand the flow the quote from the Morpho SDK tab in “Get a quote for your offer”:

import { parseUnits, publicActions } from "viem";
import { Time } from "@morpho-org/morpho-ts";
import { morphoViemExtension } from "@morpho-org/morpho-sdk";
import { blueOracleAbi } from "@morpho-org/morpho-sdk/abis";

const client = walletClient.extend(morphoViemExtension()).extend(publicActions);
const midnight = client.morpho.midnight(8453);
const block = await client.getBlock();
const marketData = await midnight.getMarketData(marketId, {
  blockNumber: block.number,
});
const positionData = (
  await midnight.getPositionData({
    marketId,
    accountAddress: taker,
    parameters: { blockNumber: block.number },
  })
).accrueInterest(block.timestamp);
const collateralPrices = await Promise.all(
  marketData.params.collateralParams.map(({ oracle }) =>
    client.readContract({
      address: oracle,
      abi: blueOracleAbi,
      functionName: "price",
      blockNumber: block.number,
    }),
  ),
);
const targetAssets = loanAssets;
const minimumPrice = BigInt(quote.data.averageWorstPrice);
const maxUnits = (targetAssets * 10n ** 18n + minimumPrice - 1n) / minimumPrice;
// Minimum WETH = (maxUnits + existing debt units) × loan-token price / (WETH price × LLTV); add a safety buffer (5 WETH in this example).
const collateralAssets = parseUnits("5", 18);

const action = midnight.supplyCollateralTakeBorrow({
  accountAddress: taker,
  marketData,
  positionData,
  collateralPrices,
  collateralSupplies: [{ collateralIndex: 0n, assets: collateralAssets }],
  target: { type: "assets", assets: targetAssets, maxUnits },
  takeableOffers: quote.data.takeableOffers,
  deadline: Time.timestamp() + 600n,
});

const requirements = await action.getRequirements();
// Fulfill the WETH approval and MidnightBundlesV2 authorization separately.
for (const requirement of requirements) {
  const requirementHash = await client.sendTransaction({ ...requirement, account: taker });
  await client.waitForTransactionReceipt({ hash: requirementHash });
}
const hash = await client.sendTransaction({ ...action.buildTx(), account: taker });
await client.waitForTransactionReceipt({ hash });

See Taker flows for the full surface, including the borrow-only takeBorrow.

For a direct integration, call MidnightBundlesV2. It takes offers toward your target in one transaction and skips stale offers; handle the token approval and Midnight authorization separately.

Authorizations & Approvals Submit the collateral-token ERC-20 approval to MidnightBundlesV2 separately, then authorize it on the Midnight contract.

import { erc20Abi, maxUint256, zeroAddress } from "viem";
import { midnightAbi } from "@morpho-org/morpho-sdk/abis";

const MIDNIGHT_BUNDLES_V2 = "0x0bF30B530f816a619C3F28a3b9f44C441122555D"; // MidnightBundlesV2 on Base (from the @morpho-org/morpho-ts address registry)
const MIDNIGHT = "0xAdedD8ab6dE832766Fedf0FaC4992E5C4D3EA18A";
const WETH = "0x4200000000000000000000000000000000000006";

await walletClient.writeContract({
  account: taker,
  address: WETH,
  abi: erc20Abi,
  functionName: "approve",
  args: [MIDNIGHT_BUNDLES_V2, maxUint256],
});

await walletClient.writeContract({
  account: taker,
  address: MIDNIGHT,
  abi: midnightAbi,
  functionName: "setIsAuthorized",
  args: [MIDNIGHT_BUNDLES_V2, true, taker],
});

Execute onchain Specify the target amount of assets you want to sell (i.e. borrow), a price guard, the collateral you want to post, and the call's arguments.

import { parseUnits, zeroAddress } from "viem";
import { midnightBundlesV2Abi } from "@morpho-org/morpho-sdk/abis";

const collateralSupplies = [{ collateralIndex: 0n, assets: parseUnits("5", 18) }];
const targetSellerAssets = loanAssets;
const minimumPrice = BigInt(quote.average_worst_price);
const maxUnits = (targetSellerAssets * 10n ** 18n + minimumPrice - 1n) / minimumPrice;
// Minimum WETH = (maxUnits + existing debt units) × loan-token price / (WETH price × LLTV); add a safety buffer (5 WETH in this example).
const offerFills = quote.takeable_offers.map(apiOfferToAbi);
const market = offerFills[0].offer.market;

await walletClient.writeContract({
  account: taker,
  address: MIDNIGHT_BUNDLES_V2,
  abi: midnightBundlesV2Abi,
  functionName: "midnightBundlesV2SupplyCollateralAndSellWithAssetsTarget",
  args: [
    market, // market
    targetSellerAssets, // targetSellerAssets
    maxUnits, // maxUnits
    false, // reduceOnly
    taker, // receiver
    collateralSupplies, // collateralSupplies
    offerFills, // offerFills
    0n, // referralFeePct
    zeroAddress, // referralFeeRecipient
    BigInt(Math.floor(Date.now() / 1000) + 600), // deadline
    zeroAddress, // wrappedNative, unused when msg.value is 0
  ],
});

The rate guard derives minimumPrice from quote.average_worst_price and uses it to calculate maxUnits. Collateral sizing uses the debt units owed at maturity (maxUnits plus any existing debt) at the market's LLTV to find the minimum, then adds a safety buffer; this example supplies 5 WETH. collateralIndex refers to the collateral's position in the market's collateralParams.

Use Midnight Make Borrow Offer to publish an unfunded borrow offer, rather than take an existing lend offer. Omit collateral_supplies and funding: publication does not transfer loan assets or open debt. Collateral must be sufficient when an offer is later taken.

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. The shared cap is 20 USDC. The rate parameter 1585489599 is a WAD-scaled per-second simple rate corresponding to 5% APR, not a return forecast.

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/borrow" \
  --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"
  },
  "offers": {
    "type": "rate",
    "entries": [
      {
        "market_id": "$MIDNIGHT_MARKET_ID",
        "rate_wad": "1585489599",
        "starts_at": $STARTS_AT,
        "expires_at": $EXPIRES_AT
      }
    ]
  }
}
JSON

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

Before signing the returned calls, verify the signed proof and check that the simulation succeeded and its results match what the user expects. These checks do not tell you whether the calldata matches your request.

The TypeScript and Go calldata verifiers do not support this make-offer action. CalldataUnsupportedError means the check did not pass. Decode the calldata independently and check that the full list of calls matches your original request. If you cannot verify the calls, do not sign or send them. With user approval, the user's wallet sends verified calls in the returned order. Morpho does not submit transactions.

To construct publication locally, follow Maker flows. Publication and taking an existing offer are different operations.