Skip to main content

Monitor Aave V4 Position Health with Quicknode

Updated on
Nov 20, 2026

24 min read

Overview​

If you run a service that watches many Aave V4 positions, such as an alert bot, a risk dashboard, or a liquidation tool, you want to know when a position gets risky before a liquidation does the telling. Three things make that harder than it was on Aave V3. Health is tracked per Spoke, so one wallet can have several health factors and no single number. Health also moves without any action from the user: oracle prices change, and interest accrues every block without emitting an event. On top of that, the risk premium is easy to misread, because the premium a position pays today can differ from the premium it would pay after a refresh, and only some Spokes use a premium at all.

The fix is to let events tell you when to look, and let the chain tell you what you see. Quicknode Webhooks report two kinds of events: a wallet acting on a Spoke, and a price feed posting a new price. Each delivery triggers a batched getUserAccountData read over Quicknode RPC, and a slow timer covers interest, which has no event. A second plain eth_call shows the latest risk premium next to the applied one.

When it runs, the monitor prints one line per position with debt, and flags the ones under your threshold:

Monitor output
ethereum 0x94e7A5dCbE816e498b89aB752661904E2F56c485 0xYourAddress health 1.4338 at block 26446954
ALERT ethereum 0x94e7A5dCbE816e498b89aB752661904E2F56c485 0xWatchedAddress health 1.1446 at block 26446954
avalanche 0x435272CefF93a1E657E8ABfdf0A13e95900A3a56 0xWatchedAddress health 2.4966 at block 100736447

This guide builds that monitor as a handful of TypeScript snippets with viem. Each snippet does one job, so you can drop it into your own service. It follows the same idea as the Aave V3 borrower health guide, adapted to the V4 Hub and Spoke design.

Aave SDK or This Monitor?

The Aave SDK and API return positions, health, and premiums for the addresses you ask about. They are the simpler choice for a UI or a few known wallets. This monitor fits a backend that watches many positions: webhooks tell it when to read, Spoke events surface wallets you did not know about, and getUserAccountData returns the value the contract itself uses, at a block you choose. The two also combine well: keep the webhooks as triggers and swap the read for the SDK.

TLDR
  • Aave V4 health is per Spoke. A wallet needs one getUserAccountData read for each Spoke it uses
  • Health moves on position actions, price updates, and interest. Only the first two emit events
  • A Quicknode Webhooks Contract Events template watches Spoke events and Chainlink AnswerUpdated events, and a slow timer covers interest
  • The applied premium comes from getUserLastRiskPremium. The latest premium is the first value of getUserAccountData
  • This guide builds a small viem monitor for Ethereum, Base, and Avalanche

What You Will Need​

  • A Quicknode account with RPC endpoints for Ethereum, Base, and Avalanche, and access to Webhooks
  • Node.js (latest LTS)
  • A tunnel tool such as cloudflared or ngrok, so Webhooks can reach your receiver during development
  • A wallet address with an Aave V4 position, or one you want to watch. The examples use the placeholder 0xYourAddress
  • Basic knowledge of Aave V4 positions and TypeScript

Create a project folder for the snippets and install the packages. Every .ts file in this guide goes in this folder:

Terminal
mkdir aave-v4-monitor && cd aave-v4-monitor
npm init -y
npm pkg set type=module
npm install viem
npm install -D tsx typescript @types/node

The type=module setting lets the scripts use top-level await. Run any file with npx tsx <file>.ts.

Keep each RPC URL in an environment variable. The snippets read ETHEREUM_RPC, BASE_RPC, and AVALANCHE_RPC, and never contain an endpoint URL.

Why Is Aave V4 Health Per Spoke?​

In Aave V4, Hubs hold liquidity and Spokes hold user positions. A position belongs to one user inside one Spoke on one chain, and its health factor covers only that position. No chain-wide or cross-Spoke health factor exists, so a monitor must read each Spoke separately.

Hubs share liquidity across Spokes, but each Spoke keeps its own position and health factor for a user, so no health factor crosses the Spoke boundary.Hubs share liquidity across Spokes, but each Spoke keeps its own position and health factor for a user, so no health factor crosses the Spoke boundary.

Each Spoke is its own lending market. It decides which assets you can supply and borrow, how much each collateral counts toward your borrowing power, and which price oracle it reads. The Hubs behind it only provide the liquidity. Spoke names describe the market: a Main Spoke is a general-purpose market with a broad asset list, while a themed Spoke such as Coinbase Stocks or Ethena Ecosystem accepts a narrow set of collateral and lends stablecoins against it. Because the rules differ, the same wallet can be safe in one Spoke and close to liquidation in another.

A position is identified by three values: the chain ID, the Spoke address, and the user address. Your watchlist should use that same key. If one wallet borrows in two Spokes, you track two positions and expect two health factors that move independently. Aave describes this in its docs on fetching positions and position conditions.

You can list the Spokes of a chain with the public Aave API. Read the list from the API, because the table of deployed Spokes in the docs can lag behind it.

Terminal
curl https://api.v4.aave.com/graphql \
-H 'content-type: application/json' \
-d '{"query":"{ spokes(request:{query:{chainIds:[1]}}) { name address } }"}'

Change chainIds to 8453 for Base or 43114 for Avalanche. The rest of this guide uses these public Spokes:

ChainSpokeMarketAddress
EthereumMainGeneral-purpose, widest asset list0x94e7A5dCbE816e498b89aB752661904E2F56c485
BaseCoinbase StocksTokenized stocks as collateral, USDC to borrow0x17905Db0e4A3514467539956c084180616AE7B8D
AvalancheMainGeneral-purpose0x435272CefF93a1E657E8ABfdf0A13e95900A3a56
AvalancheEthena EcosystemUSDe as collateral, stablecoins to borrow0xaf22446124e566e54845f65b722E4dCbf12b650A

Find Spoke Activity with Quicknode Webhooks​

Every action on a Spoke emits an event that names the position owner. A Quicknode Webhooks Contract Events template (evm-contract-events) watches a list of contracts and event hashes and posts every match to your URL. Point it at your Spokes, and each delivery tells you which wallets just acted.

Most Spoke events share one shape. Their indexed topics hold the reserve ID (which asset), the caller (the account that sent the transaction), and the user (the position owner), and the data field holds the share and token amounts. The caller and the user differ when someone acts on a user's behalf, so always key your watchlist on the user. Eight events cover the actions that can change a position's health or premium:

EventEmitted whenUser is inTopic 0 hash
SupplyA user adds an asset to a reservetopic 30xd986db228cb1fe8392c5f45ff5f2c639b7db6cbd9ca7d1fe70b2de90c2c8c961
WithdrawA user takes supplied assets outtopic 30xfe7813e2866053d5c3938554e517b554fce6666a6561bed9eaa7419b29fa9b68
BorrowA user draws debt from a reservetopic 30xef18174796a5d2f91d51dc5e907a4d7867bbd6e800f6225168e0453d581d0dcd
RepayA user pays back debt to a reservetopic 30xd765a0263e8a360da8dd4fdb8c0dc5553adec12a96f29a462cdb45e5bea407dd
SetUsingAsCollateralA user turns a supplied asset on or off as collateraltopic 30x4763df430bc5274807f8ab4ce0734e7898513638418d6eec0c5285ef85f7f51f
LiquidationCallA liquidator repays debt and takes collateraltopic 30x2a1f12d996f530f89d8038aa293f9fde81cac44b6dfd6225e3358d09b78a4a37
UpdateUserRiskPremiumThe Spoke stores a new applied premium, in BPS in the data fieldtopic 10x9a9082fd74a00ac52b567642a2d8fd3383cb2bd8690f6b2a3b7b37aaf489dac1
RefreshAllUserDynamicConfigThe user's collateral settings move to the latest reserve configtopic 10x837314749a8459031ad895d39a13552d1627fddc93d64b404bab0ae5f0798da7

LiquidationCall indexes the collateral reserve and the debt reserve in place of a caller. The two premium events index only the user. The full event definitions are in the Aave V4 ISpoke.sol interface.

For Ethereum Main, the Contract Events webhook takes the Spoke address as its contract list and the eight hashes above as its event hash list. You create it near the end of the guide, once the receiver is ready to take deliveries.

The Parsed Contract Events template (evm-abi in the CLI) is an alternative that decodes logs with an ABI you provide. This guide uses Contract Events because it needs only the event hashes, and viem decodes each log in a few lines.

Each delivery has a matchingReceipts array. A receipt holds every log of the transaction, not only the Spoke logs, so the receiver must filter by log.address before it trusts a log. It then decodes the log with the event ABI and reads the user from the decoded arguments, so you never read topics by hand.

spoke-events.ts
import { decodeEventLog, parseAbi, type Address, type Hex } from "viem";

const spokeEventsAbi = parseAbi([
"event Supply(uint256 indexed reserveId, address indexed caller, address indexed user, uint256 suppliedShares, uint256 suppliedAmount)",
"event Withdraw(uint256 indexed reserveId, address indexed caller, address indexed user, uint256 withdrawnShares, uint256 withdrawnAmount)",
"event Borrow(uint256 indexed reserveId, address indexed caller, address indexed user, uint256 drawnShares, uint256 drawnAmount)",
"event Repay(uint256 indexed reserveId, address indexed caller, address indexed user, uint256 drawnShares, uint256 totalAmountRepaid, (int256 sharesDelta, int256 offsetRayDelta, uint256 restoredPremiumRay) premiumDelta)",
"event SetUsingAsCollateral(uint256 indexed reserveId, address indexed caller, address indexed user, bool usingAsCollateral)",
"event LiquidationCall(uint256 indexed collateralReserveId, uint256 indexed debtReserveId, address indexed user, address liquidator, bool receiveShares, uint256 debtAmountRestored, uint256 drawnSharesLiquidated, (int256 sharesDelta, int256 offsetRayDelta, uint256 restoredPremiumRay) premiumDelta, uint256 collateralAmountRemoved, uint256 collateralSharesLiquidated, uint256 collateralSharesToLiquidator)",
"event UpdateUserRiskPremium(address indexed user, uint256 riskPremium)",
"event RefreshAllUserDynamicConfig(address indexed user)",
]);

type WebhookLog = { address: Address; topics: Hex[]; data: Hex };
type WebhookPayload = { matchingReceipts: { logs: WebhookLog[] }[] };

// Returns every user that a Spoke event in this payload touched.
export function usersFromPayload(payload: WebhookPayload, spokes: Address[]): Address[] {
const watched = new Set(spokes.map((spoke) => spoke.toLowerCase()));
const users = new Set<Address>();

for (const receipt of payload.matchingReceipts) {
for (const log of receipt.logs) {
if (!watched.has(log.address.toLowerCase())) continue;
try {
const event = decodeEventLog({
abi: spokeEventsAbi,
topics: log.topics as [Hex, ...Hex[]],
data: log.data,
});
users.add(event.args.user);
} catch {
// A Spoke event outside the list above, such as SetUserPositionManager.
}
}
}
return [...users];
}

The receiver later in this guide feeds this function. An event only tells you that a position changed. It does not tell you how healthy the position is, so the next section reads that from the chain.

Read a Position's Health Factor with getUserAccountData​

getUserAccountData(user) on a Spoke returns the position's health factor on-chain, in a single eth_call. The health factor is a WAD value, so 1e18 means a health of 1.0, and a position becomes liquidatable when it falls below that.

The call returns seven values: riskPremium in basis points (BPS), avgCollateralFactor, healthFactor, totalCollateralValue, totalDebtValueRay, activeCollateralCount, and borrowCount. The layout is the same on Ethereum, Base, and Avalanche. Start with the ABI and a client map, which keeps each RPC URL in an environment variable:

spoke-abi.ts
import { parseAbi } from "viem";

export const spokeAbi = parseAbi([
"function getUserAccountData(address user) view returns ((uint256 riskPremium, uint256 avgCollateralFactor, uint256 healthFactor, uint256 totalCollateralValue, uint256 totalDebtValueRay, uint256 activeCollateralCount, uint256 borrowCount))",
"function getUserLastRiskPremium(address user) view returns (uint256)",
"function getReserveCount() view returns (uint256)",
"function getReserveConfig(uint256 reserveId) view returns ((uint24 collateralRisk, bool paused, bool frozen, bool borrowable, bool receiveSharesEnabled))",
]);
clients.ts
import { createPublicClient, http, type Address, type Chain } from "viem";
import { mainnet } from "viem/chains";

type ChainConfig = { chain: Chain; rpcEnv: string; spokes: Address[] };

export const chains = {
ethereum: {
chain: mainnet,
rpcEnv: "ETHEREUM_RPC",
spokes: ["0x94e7A5dCbE816e498b89aB752661904E2F56c485"], // Main
},
} satisfies Record<string, ChainConfig>;

export type ChainName = keyof typeof chains;

export function getClient(name: ChainName) {
const { chain, rpcEnv }: ChainConfig = chains[name];
const url = process.env[rpcEnv];
if (!url) throw new Error(`${rpcEnv} is not set`);
return createPublicClient({ chain, transport: http(url) });
}

Now write the health read. It pins the read to one block, so every result has a known source, and it checks borrowCount first. A position with no debt returns the maximum uint256 as its health factor, and an address that never used the Spoke returns the same value without a revert. Without that check, your monitor would treat empty positions as the healthiest ones.

health.ts
import { formatUnits, type Address, type PublicClient } from "viem";
import { spokeAbi } from "./spoke-abi.js";

export async function readHealth(client: PublicClient, spoke: Address, user: Address) {
// Pin the read to one block so the result has a known source.
const blockNumber = await client.getBlockNumber();
const account = await client.readContract({
address: spoke,
abi: spokeAbi,
functionName: "getUserAccountData",
args: [user],
blockNumber,
});

// No debt returns the maximum uint256 as health factor, so check borrowCount first.
if (account.borrowCount === 0n) return { blockNumber, hasDebt: false as const };

return {
blockNumber,
hasDebt: true as const,
healthFactor: Number(formatUnits(account.healthFactor, 18)),
};
}

Sweep Positions with Batched Reads​

A Spoke event tells you that a wallet acted, but a position can get riskier while its owner does nothing. Three things move a health factor, and only two of them emit an event:

  • Position actions, such as a borrow or a withdrawal, emit Spoke events. The Spoke webhook from the previous section catches them.
  • Price updates come from the Spoke's oracle. The Chainlink aggregators behind it emit an AnswerUpdated event for each new price, and a second webhook can watch them.
  • Interest accrues every block and emits nothing. Only a read on a timer catches it.
Three causes move a health factor. Position actions and oracle price updates emit events, so a webhook triggers a read. Interest emits no event, so a timer sweep covers it. All three triggers lead to one batched getUserAccountData read.Three causes move a health factor. Position actions and oracle price updates emit events, so a webhook triggers a read. Interest emits no event, so a timer sweep covers it. All three triggers lead to one batched getUserAccountData read.

All three triggers end in the same read, so make that read cheap. The sweep below keeps a watchlist keyed by chain, Spoke, and user, which matches the position identity from the first section. It reads every watched position on a chain with viem's multicall, which packs the reads into as few eth_call requests as it can. viem splits a large batch into chunks, so many positions can take more than one request, but every request reads the same block. The sweep applies the same borrowCount rule as readHealth.

Because the webhooks handle actions and prices, the timer only has to catch interest, which moves slowly. The ten-minute interval and the 1.2 alert threshold are teaching values. Choose them from your own risk appetite and your endpoint's rate limits.

sweep.ts
import { formatUnits, type Address } from "viem";
import { chains, getClient, type ChainName } from "./clients.js";
import { spokeAbi } from "./spoke-abi.js";

type Position = { chain: ChainName; spoke: Address; user: Address };

const ALERT_BELOW = 1.2;
const SWEEP_INTERVAL_MS = 10 * 60_000;

const watchlist = new Map<string, Position>();

export function watch(position: Position) {
watchlist.set(`${position.chain}:${position.spoke}:${position.user}`, position);
}

// Reads every watched position on one chain in batched calls, pinned to one block.
export async function sweepChain(chain: ChainName) {
const positions = [...watchlist.values()].filter((position) => position.chain === chain);
if (positions.length === 0) return;

const client = getClient(chain);
const blockNumber = await client.getBlockNumber();
const results = await client.multicall({
contracts: positions.map(({ spoke, user }) => ({
address: spoke,
abi: spokeAbi,
functionName: "getUserAccountData",
args: [user],
}) as const),
blockNumber,
});

results.forEach((result, i) => {
const { spoke, user } = positions[i];
if (result.status === "failure") return console.error(`Read failed for ${user} on ${chain}`);
// Same rule as readHealth: no debt means no health factor to watch.
if (result.result.borrowCount === 0n) return;
const health = Number(formatUnits(result.result.healthFactor, 18));
const line = `${chain} ${spoke} ${user} health ${health.toFixed(4)} at block ${blockNumber}`;
console.log(health < ALERT_BELOW ? `ALERT ${line}` : line);
});
}

// Sweeps every chain now, then on a timer, the safety net for interest.
export function startSweep() {
const sweepAll = () => {
for (const chain of Object.keys(chains) as ChainName[]) {
sweepChain(chain).catch((error) => console.error(`Sweep failed on ${chain}:`, error));
}
};
sweepAll();
setInterval(sweepAll, SWEEP_INTERVAL_MS);
}

Re-Read When a Price Feed Updates​

Each Spoke reads prices through its own oracle, and most price sources are Chainlink feeds. The contract that emits AnswerUpdated is the aggregator behind each feed, so those aggregators are what the price webhook watches. A small helper, priceFeeds(client, spoke), finds them for a Spoke.

feeds.ts: find the Chainlink aggregators behind a Spoke

The helper reads the oracle from ORACLE() and the source of each reserve from getReserveSource. A plain source is a Chainlink proxy. Many sources are adapters that combine two proxies, such as an asset-to-USD and a base-to-USD feed for a capped stablecoin, or an asset-to-peg and a peg-to-base feed for WBTC. The helper reads every adapter getter it knows and asks each proxy for its aggregator(). If a Spoke adds an adapter with other getters, add them to the list.

Some price inputs have no aggregator, so the timer sweep covers them. Examples are fixed prices and exchange rates read from a token contract, such as the stETH rate behind the wstETH adapter's RATIO_PROVIDER().

feeds.ts
import { parseAbi, type Address, type PublicClient } from "viem";

const feedAbi = parseAbi([
"function ORACLE() view returns (address)",
"function getReserveCount() view returns (uint256)",
"function getReserveSource(uint256 reserveId) view returns (address)",
"function aggregator() view returns (address)",
"function ASSET_TO_USD_AGGREGATOR() view returns (address)",
"function BASE_TO_USD_AGGREGATOR() view returns (address)",
"function ASSET_TO_PEG() view returns (address)",
"function PEG_TO_BASE() view returns (address)",
]);

// Getters that adapters use to expose the Chainlink proxies they combine.
const adapterGetters = ["ASSET_TO_USD_AGGREGATOR", "BASE_TO_USD_AGGREGATOR", "ASSET_TO_PEG", "PEG_TO_BASE"] as const;
type AddressGetter = "aggregator" | (typeof adapterGetters)[number];

// Returns undefined when the contract does not have the function.
function tryRead(client: PublicClient, address: Address, functionName: AddressGetter) {
return client.readContract({ address, abi: feedAbi, functionName }).catch(() => undefined);
}

// Returns the Chainlink aggregators that emit price updates for a Spoke's reserves.
export async function priceFeeds(client: PublicClient, spoke: Address) {
const oracle = await client.readContract({ address: spoke, abi: feedAbi, functionName: "ORACLE" });
const count = await client.readContract({ address: spoke, abi: feedAbi, functionName: "getReserveCount" });
const feeds = new Set<Address>();

for (let reserveId = 0n; reserveId < count; reserveId++) {
const source = await client.readContract({ address: oracle, abi: feedAbi, functionName: "getReserveSource", args: [reserveId] });
// An adapter can combine two proxies. A plain source is the proxy itself.
const wrapped = await Promise.all(adapterGetters.map((getter) => tryRead(client, source, getter)));
const proxies = wrapped.filter((proxy): proxy is Address => proxy !== undefined);
for (const proxy of proxies.length > 0 ? proxies : [source]) {
const aggregator = await tryRead(client, proxy, "aggregator");
// Sources without an aggregator, such as fixed prices, rely on the sweep.
if (aggregator) feeds.add(aggregator);
}
}
return [...feeds];
}

Print the list for a chain with a short script:

list-feeds.ts
import { chains, getClient, type ChainName } from "./clients.js";
import { priceFeeds } from "./feeds.js";

const chain = (process.argv[2] ?? "ethereum") as ChainName;
const client = getClient(chain);
const feeds = new Set<string>();
for (const spoke of chains[chain].spokes) {
for (const feed of await priceFeeds(client, spoke)) feeds.add(feed);
}
for (const feed of feeds) console.log(feed);
Terminal
ETHEREUM_RPC="<your-ethereum-endpoint-url>" npx tsx list-feeds.ts ethereum

These aggregators become the contract list of a second Contract Events webhook, with the AnswerUpdated hash as its only event. You create it next to the Spoke webhook.

Chainlink can move a feed to a new aggregator, so re-run list-feeds.ts from time to time and update the webhook with qn webhook update-template.

Connect Webhooks to the Sweep​

The receiver ties both webhooks to the sweep. It first checks that the request comes from Quicknode. Each delivery carries a nonce, a timestamp, and a signature in its headers, and the signature is an HMAC-SHA256 of the nonce, the timestamp, and the raw body, keyed with the webhook's security token. Every webhook has its own token unless you set the same one with the CLI, so the receiver accepts a comma-separated list.

At startup, it watches the wallets in WATCH_USERS on every Spoke and runs a first sweep, so an existing position shows up at once. It then routes each request by path. A Spoke delivery on /ethereum adds every user it finds to the watchlist, once for each Spoke on that chain, because health is per Spoke. A price delivery on /prices/ethereum does not need its body. Any price change can move any position on that chain, so it sweeps them all.

receiver.ts
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer, type IncomingHttpHeaders } from "node:http";
import { getAddress } from "viem";
import { chains, type ChainName } from "./clients.js";
import { usersFromPayload } from "./spoke-events.js";
import { startSweep, sweepChain, watch } from "./sweep.js";

// One security token per webhook, separated by commas.
const secrets = (process.env.WEBHOOK_SECRETS ?? "").split(",").filter(Boolean);
if (secrets.length === 0) throw new Error("WEBHOOK_SECRETS is not set");

// Optional wallets to watch from the start, separated by commas.
const seedUsers = (process.env.WATCH_USERS ?? "").split(",").filter(Boolean).map((user) => getAddress(user.trim()));
for (const chain of Object.keys(chains) as ChainName[]) {
for (const spoke of chains[chain].spokes) {
for (const user of seedUsers) watch({ chain, spoke, user });
}
}

// The signature is an HMAC-SHA256 of nonce + timestamp + body, keyed with the security token.
function isFromQuicknode(headers: IncomingHttpHeaders, body: string, key: string) {
const nonce = headers["x-qn-nonce"];
const timestamp = headers["x-qn-timestamp"];
const signature = headers["x-qn-signature"];
if (typeof nonce !== "string" || typeof timestamp !== "string" || typeof signature !== "string") return false;
const expected = createHmac("sha256", key).update(nonce + timestamp + body).digest("hex");
return expected.length === signature.length && timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
}

const sweep = (chain: ChainName) =>
sweepChain(chain).catch((error) => console.error(`Sweep failed on ${chain}:`, error));

const server = createServer((req, res) => {
// POST /ethereum for Spoke events, POST /prices/ethereum for price updates.
const [kind, name] = req.url?.startsWith("/prices/") ? ["prices", req.url.slice(8)] : ["spokes", req.url?.slice(1)];
const chain = name as ChainName;
if (req.method !== "POST" || !(chain in chains)) {
res.writeHead(404).end();
return;
}

let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
if (!secrets.some((key) => isFromQuicknode(req.headers, body, key))) {
console.error(`Rejected a ${kind} request with a bad signature`);
res.writeHead(401).end();
return;
}
res.writeHead(200).end();
console.log(`${kind} delivery on ${chain}`);

// A price update can move every position on the chain, so sweep them all.
if (kind === "prices") return void sweep(chain);

const { spokes } = chains[chain];
for (const user of usersFromPayload(JSON.parse(body), spokes)) {
for (const spoke of spokes) watch({ chain, spoke, user });
}
void sweep(chain);
});
});

startSweep();
server.listen(3000, () => console.log("Listening on http://localhost:3000"));

Create the Webhooks and Run the Monitor​

The monitor has all its parts. To run it, give Webhooks a public URL, start the receiver, and create the Spoke and price webhooks.

Expose the Receiver with a Tunnel​

Webhooks deliver to a public HTTPS URL, and the receiver listens on localhost:3000. During development, a tunnel connects the two. With cloudflared, one command starts a quick tunnel and prints a random HTTPS URL:

Terminal
cloudflared tunnel --url http://localhost:3000

Keep that terminal open, and save the printed URL as PUBLIC_URL. Other tunnel tools, such as ngrok, work the same way. In production, use your server's own URL.

Start the Receiver​

Start the receiver before a webhook goes live. Otherwise, the first deliveries reach a closed port, and the tunnel answers with an error. Webhooks retry failed deliveries, but the errors make a first run hard to read.

The receiver needs the security token of each webhook, and you get each token before its webhook exists. With the CLI, you generate the tokens yourself. In the dashboard, the create form shows the token before you click Create. The next section shows both paths. Run the receiver in a second terminal:

Terminal
ETHEREUM_RPC="<your-ethereum-endpoint-url>" \
WEBHOOK_SECRETS="<spoke-webhook-token>,<price-webhook-token>" \
WATCH_USERS="0xYourAddress" \
npx tsx receiver.ts

WATCH_USERS is optional. It holds the wallets you want to watch from the start, separated by commas. The receiver sweeps them at startup, so an existing position prints a line at once. Replace 0xYourAddress with a real address, or leave the variable out. After that, each Spoke delivery adds wallets to the watchlist, and each price delivery sweeps them. The output matches the sample at the top of this guide, with an ALERT prefix on any position under your threshold.

Create the Spoke and Price Webhooks​

Create two webhooks on Ethereum Mainnet. Both use the Contract Events template:

  • Spoke webhook: the Spoke address, the eight event hashes, and $PUBLIC_URL/ethereum
  • Price webhook: the aggregators from list-feeds.ts, the AnswerUpdated hash 0x0559884fd3a460db3073b7fc896cc77986f16e378210ded43186175bf646fc5f, and $PUBLIC_URL/prices/ethereum
  1. Open the Webhooks page in your Quicknode dashboard and click Create Webhook.
  2. Choose Ethereum Mainnet as the network.
  3. Select the Contract Events template.
  4. Under Contracts, open Manual Input and add the Spoke address. You can also Import a list from a file, or pick one from Saved Lists.
  5. Under Event Hashes, add the eight hashes from the event table the same way.
  6. Optional: under Test your filter, enter a recent block and click Run to see an example payload.
  7. Enter your tunnel URL followed by /ethereum as the Webhook URL.
  8. Copy the Security Token, because the receiver uses it to check each request. Leave Enable Compression off.
  9. Start the receiver with this token in WEBHOOK_SECRETS. Then name the webhook and click Create.

Repeat the steps for the price webhook. Add the aggregators as a new contract list, add only the AnswerUpdated hash, and use /prices/ethereum as the path. Before you click Create, restart the receiver with both tokens in WEBHOOK_SECRETS.

The dashboard saves each list in your Key-Value Store, so you can pick it from Saved Lists later. The event hash list works on every chain, so the Avalanche Spoke webhook can reuse it as is.

Script This with the Quicknode CLI

The CLI suits scripts and AI agents, because every step is a command with flags. See the Quicknode CLI guide and the CLI docs to get started.

When a delivery arrives, the receiver logs its kind and chain, such as prices delivery on ethereum, and the sweep prints a line for each watched position with debt. A Rejected line means the signature did not match, so check the tokens in WEBHOOK_SECRETS.

Both webhooks have compression off, so the body arrives as plain JSON and the signature check runs on it directly. If you turn on gzip, decompress the body before you check the signature. Webhooks sign requests the same way as Streams, so the guide to validating incoming Streams webhook messages covers the same check in more languages.

Keep the Receiver Short on Purpose

This receiver skips retries, reorg handling, and replay protection to stay readable. Add them before you rely on it in production.

Read the Applied and Latest Risk Premium​

A Spoke stores two risk premiums for each position. The applied premium is what the position pays right now, and the latest premium is what the position would pay after a refresh. Both are plain eth_call reads, and both are in BPS, so 1000 means 10%.

The two values come from different places on the same Spoke:

PremiumWhere to read itAave API field
AppliedgetUserLastRiskPremium(user)riskPremium.current
LatestFirst value of getUserAccountData(user)riskPremium.latest

The applied premium can lag the latest one until the position is refreshed by a user action, so the gap is normal. The premium is a multiplier on top of each reserve's base borrow rate. It does not add percentage points to the APY. A premium change also does not move the health factor at that moment. It sets the rate on future premium debt.

Only some Spokes use a premium. A Spoke can emit premium updates only when at least one of its reserves has a collateralRisk above 0. The first value of getReserveConfig holds it. Base Coinbase Stocks is an example of a Spoke that uses one, and Ethereum Main is an example of a Spoke that does not. Read the config instead of relying on that list, because Spoke configuration can change.

The snippet reads both premiums at the same block, so the comparison is fair. It also includes a check that tells you whether a Spoke uses a premium:

premium.ts
import type { Address, PublicClient } from "viem";
import { spokeAbi } from "./spoke-abi.js";

export async function readPremium(client: PublicClient, spoke: Address, user: Address) {
const blockNumber = await client.getBlockNumber();
const [applied, account] = await Promise.all([
client.readContract({ address: spoke, abi: spokeAbi, functionName: "getUserLastRiskPremium", args: [user], blockNumber }),
client.readContract({ address: spoke, abi: spokeAbi, functionName: "getUserAccountData", args: [user], blockNumber }),
]);

return {
blockNumber,
appliedBps: Number(applied),
latestBps: Number(account.riskPremium),
borrowCount: Number(account.borrowCount),
};
}

// True when at least one reserve carries collateral risk, so the Spoke can use a premium.
export async function spokeUsesPremium(client: PublicClient, spoke: Address) {
const count = await client.readContract({ address: spoke, abi: spokeAbi, functionName: "getReserveCount" });
const configs = await Promise.all(
Array.from({ length: Number(count) }, (_, reserveId) =>
client.readContract({ address: spoke, abi: spokeAbi, functionName: "getReserveConfig", args: [BigInt(reserveId)] }),
),
);
return configs.some((config) => config.collateralRisk > 0);
}

To try it on Base, add a base entry to the chains object in clients.ts, then run the check and the read:

clients.ts
import { base, mainnet } from "viem/chains";

// Add inside the chains object.
base: {
chain: base,
rpcEnv: "BASE_RPC",
spokes: ["0x17905Db0e4A3514467539956c084180616AE7B8D"], // Coinbase Stocks
},
check-premium.ts
import { getAddress } from "viem";
import { getClient, chains } from "./clients.js";
import { readPremium, spokeUsesPremium } from "./premium.js";

const client = getClient("base");
const [spoke] = chains.base.spokes;
const user = getAddress(process.argv[2] ?? "");

console.log("Uses a premium:", await spokeUsesPremium(client, spoke));
console.log(await readPremium(client, spoke, user));

Pass the wallet address as the first argument. Replace 0xYourAddress with a real address, because viem rejects anything that is not a valid address:

Terminal
BASE_RPC="<your-base-endpoint-url>" npx tsx check-premium.ts 0xYourAddress

If appliedBps and latestBps differ, the position will pay the latest premium after its next refresh. If latestBps is 0 and borrowCount is 0, the address has no debt on that Spoke.

Extend the Monitor to Avalanche​

The same reads work on Avalanche, because getUserAccountData has the same seven-value layout there. Add an avalanche entry to clients.ts with the Spokes you want to watch. Then create two more webhooks on the Avalanche network: one for the Spoke addresses at /avalanche, and one for the aggregators from npx tsx list-feeds.ts avalanche at /prices/avalanche. Add both security tokens to WEBHOOK_SECRETS.

clients.ts
import { avalanche, base, mainnet } from "viem/chains";

// Add inside the chains object.
avalanche: {
chain: avalanche,
rpcEnv: "AVALANCHE_RPC",
spokes: [
"0x435272CefF93a1E657E8ABfdf0A13e95900A3a56", // Main
"0xaf22446124e566e54845f65b722E4dCbf12b650A", // Ethena Ecosystem
],
},

Three details differ from Ethereum:

  • Spoke list: Pull the Avalanche Spokes from the Aave API with chainIds:[43114], then add the ones you care about.
  • Timestamps: Avalanche webhook logs have no blockTimestamp. Read the time from the block with client.getBlock({ blockNumber }) when you need it.
  • Premium: A Spoke uses a premium only when a reserve has collateralRisk above 0. Of the two Avalanche Spokes above, Ethena Ecosystem qualifies and Main does not. Run spokeUsesPremium on each Spoke to confirm.

For history, query logs with eth_getLogs in windows of 10,000 blocks. Quicknode SQL Explorer does not cover Avalanche.

Next Steps​

You now have the three parts of a position monitor: discovery, health, and premium. A few directions to take it further:

  • Store the watchlist in a database, so a restart does not lose the wallets your webhooks already found.
  • Replace console.log with a Slack, email, or pager alert, and add a cooldown so one risky position does not alert on every read.
  • Map each aggregator to the Spokes that use it, so a price update re-reads only the positions it can move.
  • Add the retry, reorg, and replay handling that the short receiver skips.
  • Use Quicknode Streams when you need to filter and shape the data before it reaches your receiver.

Wrapping Up​

You built a monitor that finds Aave V4 wallets with Quicknode Webhooks, re-reads their health per Spoke when a price feed updates, and sweeps on a slow timer for interest. It also shows the applied premium next to the latest one. You also saw why each part exists: no event covers interest, and a premium only matters on Spokes that use one. Add your own alert channel and thresholds, and the same pattern covers every Spoke you hold or watch.

Resources​

Frequently Asked Questions​

Should I use the Aave SDK or RPC reads to monitor Aave V4 health?

Use the Aave SDK or API for a UI or a few known wallets. Use webhooks and `getUserAccountData` reads for a backend that watches many positions and needs to know when to read. You can also combine them: keep the webhooks as triggers and read health with the SDK.

How do I get an Aave V4 health factor with viem?

Call `getUserAccountData(user)` on the Spoke with `readContract`. The third returned value is the health factor in WAD, so divide by 1e18. Check `borrowCount` first, because a position with no debt returns the maximum uint256.

Does Aave V4 have one health factor for my whole wallet?

No. Health is per position, and a position is one user in one Spoke on one chain. A wallet that uses two Spokes has two health factors, so read each Spoke separately.

Why does my Aave V4 health factor change when no event fires?

Oracle prices move and interest accrues without any action from the user. Price changes emit an `AnswerUpdated` event on the Chainlink aggregator behind the Spoke's oracle, so a webhook on those aggregators can trigger a read. Interest emits no event, so keep a slow periodic `getUserAccountData` read as well.

What is the difference between the applied and latest risk premium?

The applied premium comes from `getUserLastRiskPremium` and is what the position pays now. The latest premium is the first value of `getUserAccountData`. Both are in BPS, and the applied one can lag the latest until the position is refreshed.

Does every Aave V4 Spoke use a risk premium?

No. A Spoke can emit premium updates only when one of its reserves has a `collateralRisk` above 0. Call `getReserveConfig` for each reserve to check, instead of relying on a fixed list.

Which Quicknode Webhooks template finds Aave V4 activity?

Use the Contract Events template (`evm-contract-events`) with your Spoke addresses and the event hashes for the actions you care about, such as Supply, Borrow, Repay, Withdraw, LiquidationCall, and UpdateUserRiskPremium. Filter each receipt by `log.address`, because a receipt holds every log of the transaction.