Docs

Fetch Rewards Data

Fetch vault and market reward APRs, combine them with native APY, and query claimable rewards from Merkl.

Fetch vault and market reward APRs, combine them with native APY, or query a user's claimable rewards through the Merkl API.

What You'll Learn

  • How to fetch reward APRs and combine them with native APY
  • How to query user-specific rewards from Merkl API
  • Handle caching and errors for user-specific reward data

Prerequisites

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

  • Basic understanding of Reward Programs
  • Familiarity with REST APIs
  • A tool for making API requests (curl, fetch, or axios)

Use the Morpho Read API for native APY and Merkl for reward APR. Claimable balances are separate from APR.

Follow the native APY plus reward APR recipe below. Add rewards for supply and vaults; subtract them for borrow:

netVaultApyApproximation = nativeVaultApy + directVaultRewardApr + forwardedRewardApr
netSupplyApyApproximation = nativeSupplyApy + supplyRewardApr
netBorrowApyApproximation = nativeBorrowApy - borrowRewardApr

For user-specific claimable balances, use the Merkl user rewards endpoint:

APIUse CaseRewards TypeData Provided
Morpho Read APIKnown token metadataToken dataFor a known token, use GET /v0/tokens/{token-selector}
Merkl APIUser claimable rewardsMerkl onlyUser balances, claim data, real-time rewards
Legacy RewardsUser claimable rewardsURD onlyDeprecated. Use rewards-legacy.morpho.org

Recommended Strategy:

  1. Use Merkl API for user-specific claimable rewards.
  2. For legacy URD rewards, direct users to rewards-legacy.morpho.org

Fetch the reward APR of a vault or market

Fetch Merkl rewards

Reward campaigns are served by Merkl's opportunities endpoint at https://api.merkl.xyz. Get an API key from Merkl and send it as the X-API-Key header.

Filter the endpoint by chainId and campaigns=true, plus:

  • For a vault: the vault address as explorerAddress. Do not add mainProtocolId=morpho: some Morpho vault opportunities do not match that filter and append a campaign type to identifier.
  • For supply rewards on a Morpho Blue market: mainProtocolId=morpho, type=MORPHOSUPPLY and the first 20 bytes of the market ID as identifier (its first 42 characters, including 0x).
  • For borrow rewards on a Morpho Blue market: mainProtocolId=morpho, type=MORPHOBORROW and the same truncated market ID as identifier.

For borrow rewards, verify the returned campaign's params.market against the full market ID, ignoring case. The live Merkl response identifies these opportunities with action=BORROW.

Cross-market loan-token campaigns such as MORPHOBORROW_SINGLETOKEN are outside this recipe.

The market recipe covers direct MORPHOSUPPLY and MORPHOBORROW campaigns. The vault recipe below adds allocation-weighted market supply rewards and one nested vault level. Other campaign types and deeper nesting remain outside its scope.

Combine with native APY

For market native APY, select a window from data.supply_apy_averages or data.borrow_apy_averages in Get market APY averages. For example, use ["6h"] for six hours. Match the reward window to it. A null native APY makes the combined result unknown.

Choose the reward metric:

  • Reward APR per token: keep the campaigns where startTimestamp ≤ now < endTimestamp and apr > 0, group them by reward token, and sum their apr. Merkl's apr is a percentage, so divide by 100 to get a fractional reward APR.
  • APY including rewards: add the average reward APR over the same window, from Merkl's APR records, to the Read API apy (for a Vault V2, data.apy from Get Vault V2 realized average APY).

Drop records where hasUntrustedContribution=true. Sum the retained avg percentages, then divide by the number of buckets expected in the window. This makes missing or untrusted buckets contribute zero. Do not weight records by samples.

Merkl percentages become fractions after division by 100. Morpho apy is already a fraction:

historicalRewardApr = sum(retained avg) / expectedBuckets / 100
netApyApproximation = nativeApy + sum(historicalRewardApr across opportunity IDs)

For borrow rewards, subtract the reward APR instead:

netBorrowApyApproximation = nativeBorrowApy - sum(historicalBorrowRewardApr across opportunity IDs)

Use only borrow opportunities in this sum. Net borrow APY is the native borrow APY minus the sum of borrow reward APRs, because rewards lower the cost of borrowing.

Example: Vault V2 net APY

Run the three steps in order in the same directory. Each language is a complete alternative. Step 1 saves native.json; step 2 saves rewards.json; step 3 reads both files. Use Bash with cURL and jq, Bun for TypeScript, Python with requests, or Go. Save each snippet separately, then run it before moving to the next step. Set MERKL_API_KEY before step 2. The examples read MORPHO_API_KEY from the environment when supplied.

Fetch native APY from the Read API

Read data.apy from Get Vault V2 realized average APY with lookback=six_hours. This example uses the Steakhouse USDG Vault V2 on Robinhood Chain.

set -euo pipefail
checked_curl() {
  local response status
  response=$(curl --fail-with-body --silent --show-error --write-out '\n%{http_code}' "$@") || return
  status=${response##*$'\n'}
  case "$status" in
    2??) printf '%s\n' "${response%$'\n'*}" ;;
    *) printf 'HTTP %s\n' "$status" >&2; return 1 ;;
  esac
}
checked_curl \
  -H "X-API-Key: ${MORPHO_API_KEY:-}" \
  "https://api.morpho.org/v1/vaults-v2/4663:0xBeEff033F34C046626B8D0A041844C5d1A5409dd/apy-averages?lookback=six_hours" > native.json

Fetch reward APR from the Merkl API

Fetch direct vault campaigns by chainId and explorerAddress. Do not require mainProtocolId=morpho: some vault opportunities do not match it. Fetch market supply campaigns with chainId, mainProtocolId=morpho, type=MORPHOSUPPLY and the first 42 characters of the market ID as identifier.

Use these public Read API fields to weight the market reward APRs:

VaultAllocationsDenominator
V1/v0/vaults-v1/{selector}/allocations: data.allocations[].market_id and supply_assets/v0/vaults-v1/{selector}/state: data.total_assets
V2/v0/vaults-v2/{selector}/allocations: data.allocations[].target and caps[]/v1/vaults-v2/{selector}/state: data.idle_assets plus stored adapter allocations

For V1, add marketRewardApr × supply_assets / total_assets for each active market allocation. Market reward APR already measures return per supplied capital. Do not multiply by the vault's share of the market's total supply again.

For V2, use stored allocated_assets, as the app's reward composer does, rather than accrued real_assets or expected_supply_assets. For a blue_market adapter, sum only market_v1 caps. For a vault adapter, use only its adapter cap. Never use absolute_cap or relative_cap_wad, which are limits, or count adapter-wide and market allocations twice.

V1 forwardedRewardApr = Σmarket (supply_assets / total_assets) × marketRewardApr
V2 D = idle_assets + Σadapter storedAdapterAssets
V2 forwardedRewardApr = Σmarket (market allocated_assets / D) × marketRewardApr
                     + ΣvaultAdapter (adapter allocated_assets / D) × nestedVaultRewardApr
vaultRewardApr = directRewardApr + forwardedRewardApr

The scripts support one nested vault level, including a Vault V1 adapter's direct and market rewards. A nested V2 uses the same rules. Deeper or unknown vault targets contribute no reward APR, but their stored allocations remain in the denominator. Zero-asset positions are skipped. A zero denominator gives zero forwarded APR.

Use the same vault selector in steps 1 and 2. The final vault-reward call's version argument selects V2 (2 here) or V1 (1).

For Vault V1, step 1 uses Get V1 vault realized average APY at /v0/vaults-v1/{selector}/apy-averages?lookback=six_hours, which also returns data.apy.

Page through every opportunity and APR record. Deduplicate opportunity IDs within each lookup. Average six complete hourly buckets per opportunity, including ended campaigns for history. Drop untrusted records.

Missing or untrusted buckets contribute zero through the six-bucket denominator. Divide Merkl percentages by 100 to obtain decimal rates. A complete lookup with no opportunities gives zero reward APR. Failed requests and selector mismatches stop the calculation.

This uses current allocations with each market's averaged APR. Averaging allocation-weighted APR over time would be more accurate. Market campaign types beyond MORPHOSUPPLY, such as single-token and multi lend/borrow campaigns, and nesting deeper than one level are omitted. The result can remain below the app. Check campaign forwarding eligibility too: these examples do not reproduce campaign-specific hooks or address exclusions.

set -euo pipefail
checked_curl() {
  local response status
  response=$(curl --fail-with-body --silent --show-error --write-out '\n%{http_code}' "$@") || return
  status=${response##*$'\n'}
  case "$status" in
    2??) printf '%s\n' "${response%$'\n'*}" ;;
    *) printf 'HTTP %s\n' "$status" >&2; return 1 ;;
  esac
}
: "${MERKL_API_KEY:?Set MERKL_API_KEY}"
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
to=$(( $(date +%s) / 3600 * 3600 - 3600 ))
from=$((to - 5 * 3600))
chain=4663
read_api() {
  checked_curl -H "X-API-Key: ${MORPHO_API_KEY:-}" "https://api.morpho.org$1"
}
merkl() {
  checked_curl -H "X-API-Key: $MERKL_API_KEY" "https://api.merkl.xyz/v4/$1"
}
reward_apr() {
  local address=$1 kind=$2 folder filters field expected page id
  folder=$(mktemp -d "$work/rate.XXXXXX") || return
  filters="chainId=$chain&explorerAddress=$address"
  field=explorerAddress; expected=$address
  if [ "$kind" = market ]; then
    expected=${address:0:42}; field=identifier
    filters="chainId=$chain&mainProtocolId=morpho&identifier=$expected&type=MORPHOSUPPLY"
  fi
  : > "$folder/ids"; page=0
  while :; do
    merkl "opportunities?$filters&campaigns=true&items=100&page=$page" > "$folder/page" || return
    jq -e --argjson chain "$chain" --arg field "$field" --arg expected "$expected" --arg kind "$kind" '
      all(.[]; .chainId == $chain and
        ((.[$field] // "" | ascii_downcase) == ($expected | ascii_downcase)) and
        ($kind != "market" or .type == "MORPHOSUPPLY"))
    ' "$folder/page" > /dev/null || return
    jq -r '.[].id' "$folder/page" >> "$folder/ids" || return
    [ "$(jq length "$folder/page")" -eq 100 ] || break
    page=$((page + 1))
  done
  sort -u "$folder/ids" > "$folder/unique"
  : > "$folder/sums"
  while IFS= read -r id; do
    id=$(printf '%s' "$id" | jq -sRr @uri) || return
    page=0
    while :; do
      merkl "opportunities/$id/apr-records?from=$from&to=$to&grain=HOUR&items=200&page=$page" > "$folder/page" || return
      jq '[.[] | select(.hasUntrustedContribution != true) | .avg] | add // 0' "$folder/page" >> "$folder/sums" || return
      [ "$(jq length "$folder/page")" -eq 200 ] || break
      page=$((page + 1))
    done
  done < "$folder/unique"
  jq -s '(add // 0) / 6 / 100' "$folder/sums"
}
vault_rewards() {
  local version=$1 address=$2 depth=$3 folder state_version denominator direct row assets kind destination rate nested
  folder=$(mktemp -d "$work/vault.XXXXXX") || return
  read_api "/v0/vaults-v$version/$chain:$address/allocations" > "$folder/allocations" || return
  state_version=v0; [ "$version" = 1 ] || state_version=v1
  read_api "/$state_version/vaults-v$version/$chain:$address/state" > "$folder/state" || return
  jq -c --argjson version "$version" '
    .data.allocations[] |
    if $version == 1 then {assets: (.supply_assets|tonumber), kind: "market", target: .market_id}
    elif .target.type == "blue_market" then
      .caps[] | select(.cap_type == "market_v1") | {assets: (.allocated_assets|tonumber), kind: "market", target: .market_id}
    else {assets: ([.caps[] | select(.cap_type == "adapter") | .allocated_assets|tonumber] | add // 0),
          kind: .target.type, target: .target.vault_address} end
  ' "$folder/allocations" > "$folder/positions" || return
  if [ "$version" = 1 ]; then
    denominator=$(jq '.data.total_assets|tonumber' "$folder/state") || return
  else
    denominator=$(jq -s --slurpfile state "$folder/state" '([.[].assets] | add // 0) + ($state[0].data.idle_assets|tonumber)' "$folder/positions") || return
  fi
  direct=$(reward_apr "$address" vault) || return
  : > "$folder/terms"
  while IFS= read -r row; do
    assets=$(jq -r .assets <<< "$row") || return
    if [ "$denominator" = 0 ] || ! jq -en --argjson a "$assets" '$a > 0' > /dev/null; then continue; fi
    kind=$(jq -r .kind <<< "$row"); destination=$(jq -r .target <<< "$row")
    rate=0
    if [ "$kind" = market ]; then rate=$(reward_apr "$destination" market) || return
    elif [ "$depth" -lt 1 ] && { [ "$kind" = vault_v1 ] || [ "$kind" = vault_v2 ]; }; then
      nested=$(vault_rewards "${kind#vault_v}" "$destination" "$((depth + 1))") || return
      rate=$(jq '.direct + .forwarded' <<< "$nested") || return
    fi
    jq -n --argjson a "$assets" --argjson d "$denominator" --argjson r "$rate" '$a / $d * $r' >> "$folder/terms" || return
  done < "$folder/positions"
  jq -s --argjson direct "$direct" '{direct: $direct, forwarded: (add // 0)}' "$folder/terms"
}
vault_rewards 2 "0xBeEff033F34C046626B8D0A041844C5d1A5409dd" 0 > "$work/rewards.json"
mv "$work/rewards.json" rewards.json

Combine into Net APY

Add direct and forwarded reward APR to native vault APY. Do not deduct vault fees again from this Read API APY. A null native APY keeps the combined result unknown. Rates are decimals: 0.05 means 5%. This historical approximation is not a projection. The two APIs do not provide an atomic snapshot, so align their windows as closely as available timestamps permit.

set -euo pipefail
jq --slurpfile rewards rewards.json '
(($rewards[0].direct | numbers) // error("missing direct rewards")) as $direct |
(($rewards[0].forwarded | numbers) // error("missing forwarded rewards")) as $forwarded |
{
  netApyApproximation: (if .data.apy == null then null else .data.apy + $direct + $forwarded end)
}' native.json

This calculation includes direct vault campaigns and allocation-weighted market supply rewards, subject to the campaign and nesting limits above.

For lookback=one_day, use 24 expected hourly buckets. For lookback=seven_days, use 168. Change the start time and denominator together. The pagination loops also cover windows longer than 200 buckets.

Things to check

Within a complete successful lookup, missing or untrusted buckets contribute zero through the expected-bucket denominator. No retained records means a zero contribution. No matching opportunities means zero historical rewards, but failed requests, missing pages or selector mismatches make the result unknown. For current per-token rewards only, no live campaigns after a complete lookup means zero.

For history charts, repeat the calculation over each point's trailing averaging window, not the full chart range, and do not average Morpho's APY points again. Adding reward APR to native APY remains an approximation with narrower campaign coverage, not exact GraphQL parity or a promise of returns.

Don't use the opportunity's totalApr or nativeApr: they include Merkl's own estimate of the base yield.

Merkl returns APRs, not APYs, except for campaigns that use the UNCLAIMED_DISTRIBUTOR processor, whose apr already counts unclaimed rewards. For a user's claimable rewards, see Fetching user-specific rewards. For interface examples, see Integrate Rewards Display.

Fetching User-Specific Rewards

Merkl API (Current Programs)

To get a user's claimable Merkl rewards:

Endpoint:

GET https://api.merkl.xyz/v4/users/{address}/rewards?chainId={chainId}

Example: Replace the public test account with the connected wallet.

curl --silent --show-error --include "https://api.merkl.xyz/v4/users/0x4f620E5a62Eb51DA77502E8d3De7DB41f43e5695/rewards?chainId=1"

Response Structure:

[
  {
    "chain": { "id": 1, "name": "Ethereum" },
    "rewards": [
      {
        "token": { "address": "0xREWARD_TOKEN", "symbol": "MORPHO", "decimals": 18 },
        "amount": "2000000000000000000",
        "claimed": "1000000000000000000",
        "pending": "0",
        "proofs": ["0xproof1", "0xproof2"]
      }
    ]
  }
]

The response is an array of per-chain objects, each with a rewards array. A token's currently-claimable balance is amount - claimed (both are cumulative). pending is reward not yet in a live merkle root.

TypeScript Example:

async function fetchMerklRewards(userAddress: string, chainId: number) {
  const response = await fetch(
    `https://api.merkl.xyz/v4/users/${userAddress.toLowerCase()}/rewards?chainId=${chainId}`
  );
  const data = await response.json();

  // The endpoint returns an array of per-chain objects; flatten to a list of rewards.
  const rewards = data.flatMap((entry) => entry.rewards);

  // Aggregate the unclaimed balance per token (amount - claimed)
  const claimableByToken: Record<string, bigint> = {};

  for (const reward of rewards) {
    const unclaimed = BigInt(reward.amount) - BigInt(reward.claimed);
    claimableByToken[reward.token.address] =
      (claimableByToken[reward.token.address] || 0n) + unclaimed;
  }

  return claimableByToken;
}

Legacy Rewards (Pre-Merkl)

Performance Considerations

Caching

User Merkl Rewards:

  • Cache for 5-10 minutes
  • Updates every 8 hours, but users expect fresh data

Parallel Fetching

When fetching rewards for multiple users, independent Merkl requests can run in parallel.

Error Handling

async function fetchRewardsSafely(userAddress: string) {
  try {
    const merkl = await fetchMerklRewards(userAddress);
    return merkl;
  } catch (error) {
    console.error("Merkl API error:", error);
    return {}; // Fallback to empty
  }
}

API Rate Limits

Be mindful of rate limits:

APIRate LimitNotes
Read API5k / 5 minUse responsibly
Merkl API10 request / secondCache responses

Best Practice: Cache aggressively and fetch only when needed.

Next Steps

Resources