ChainScore Labs
LABS
Guides

Setting Up Automated Alerts for Your Borrowing Positions

A technical guide to implementing automated monitoring systems for DeFi lending positions using Chainscore's data infrastructure.
Chainscore © 2025
core-concepts

Core Monitoring Concepts

Learn the essential principles for setting up automated alerts to protect your borrowing positions and manage risk proactively.

01

Liquidation Threshold Alert

Liquidation Threshold is the collateral value level at which your position becomes eligible for automatic closure to repay the loan. This alert is your primary defense against forced liquidation.

  • Monitors your Loan-to-Value (LTV) ratio in real-time against the protocol's set threshold.
  • Example: Receive a push notification when your ETH collateral drops, pushing your LTV to 85% on a platform with a 90% liquidation threshold.
  • This matters as it gives you critical time to add collateral or repay debt, avoiding the penalties and fees of a forced liquidation event.
02

Health Factor Monitoring

Health Factor is a dynamic numerical score representing the safety of your borrowed position; a lower number indicates higher risk. Automated tracking of this metric is crucial for ongoing position management.

  • Continuously calculates based on collateral value, borrowed amount, and asset volatility.
  • Use case: Set an alert to trigger when your health factor falls below 1.5, signaling you are approaching the dangerous zone near 1.0 (liquidation).
  • This proactive monitoring allows you to take corrective action before your position's health deteriorates irreversibly, safeguarding your assets.
03

Collateral Value Swing Alert

Collateral Value Swings refer to significant percentage changes in the market value of your deposited assets, which directly impact your borrowing power and liquidation risk.

  • Tracks daily or hourly price movements of your collateral portfolio against a defined percentage change (e.g., +/-10%).
  • Real example: Get an email if your staked SOL collateral surges 15%, potentially allowing you to borrow more, or crashes 12%, increasing your risk.
  • This matters because volatile markets can rapidly alter your position's safety, and timely alerts enable strategic adjustments to leverage or risk exposure.
04

Debt Ceiling Notification

Debt Ceiling is the maximum amount you can borrow against a specific collateral type, as defined by the lending protocol's risk parameters. Hitting this limit blocks further borrowing.

  • Alerts you when your borrowed amount for an asset (e.g., USDC) approaches 80-90% of its allocated ceiling.
  • Use case: Be notified before reaching the cap on your DAI borrowing, allowing you to either adjust your collateral mix or seek alternative liquidity sources.
  • This is vital for maintaining financial flexibility and ensuring your strategic borrowing plans are not unexpectedly halted by protocol constraints.
05

Interest Rate Change Alert

Variable Interest Rates on borrowed funds can fluctuate based on pool utilization and market conditions, directly affecting your cost of capital. Monitoring these changes is key to cost management.

  • Tracks the annual percentage rate (APR) for your specific borrowed assets and notifies you of significant increases.
  • Example: Receive a dashboard alert when the borrowing APR for WBTC jumps from 5% to 8%, significantly raising your repayment obligations.
  • This matters because rising rates can erode profitability or increase financial strain, prompting you to consider repaying, refinancing, or reallocating funds.

Implementation Methodology

A structured process for setting up automated monitoring and alerting for DeFi borrowing positions to manage risk and avoid liquidation.

1

Define Risk Parameters and Connect to Data Sources

Establish your alert thresholds and connect to the necessary blockchain data.

Detailed Instructions

First, you must define your liquidation risk thresholds and identify the data sources for your positions. The key metric is the Health Factor (HF), a numerical representation of your loan's safety. A health factor below 1.0 means your position is eligible for liquidation.

  • Sub-step 1: Determine Alert Levels: Set multiple Health Factor thresholds. For example, set a Warning Alert at HF < 1.5 and a Critical Alert at HF < 1.2. This gives you time to act before liquidation.
  • Sub-step 2: Identify Your Protocol and Wallet: Note the DeFi protocol (e.g., Aave V3 on Ethereum Mainnet) and your public wallet address (e.g., 0x742d35Cc6634C0532925a3b844Bc9e0a3d3c1e1f).
  • Sub-step 3: Select Data Provider: Choose an API to fetch real-time data. Use a service like The Graph for historical queries or a node provider like Alchemy/Infura for live RPC calls.

Tip: Consider also monitoring the Loan-to-Value (LTV) ratio and the price volatility of your collateral assets for a more comprehensive view.

2

Build the Health Factor Query Script

Create a script to programmatically fetch and calculate your position's health metrics.

Detailed Instructions

Develop a script that queries on-chain data to calculate your current Health Factor. This involves calling the protocol's smart contract functions. Use the Aave V3 protocol as a common example.

  • Sub-step 1: Set Up Environment: Initialize a Node.js/ Python project and install necessary libraries like web3.js or ethers.js and the Aave SDK.
  • Sub-step 2: Query User Account Data: Call the getUserAccountData function on the Aave Pool contract. This returns key values including healthFactor.
  • Sub-step 3: Execute the Query: Here is a simplified JavaScript example using ethers:
javascript
const { ethers } = require('ethers'); const provider = new ethers.providers.JsonRpcProvider('YOUR_RPC_URL'); const aavePoolAddress = '0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2'; // Aave V3 Pool const aavePoolABI = ["function getUserAccountData(address user) view returns (uint256, uint256, uint256, uint256, uint256, uint256)"]; const poolContract = new ethers.Contract(aavePoolAddress, aavePoolABI, provider); async function getHealthFactor(userAddress) { const data = await poolContract.getUserAccountData(userAddress); // healthFactor is returned as a uint256, divide by 1e18 for readable value const healthFactor = Number(data[5]) / 1e18; console.log(`Current Health Factor: ${healthFactor}`); return healthFactor; }

Tip: Run this script locally first to verify it returns correct data for your address before automating it.

3

Automate Script Execution and Integrate Alerting

Schedule the monitoring script and connect it to notification channels.

Detailed Instructions

Automate the execution of your query script and integrate it with an alerting service. Cron jobs are ideal for scheduling, and services like Twilio (SMS), Discord Webhooks, or Telegram Bots are perfect for notifications.

  • Sub-step 1: Schedule the Script: Use a cron job on a server or a serverless function (AWS Lambda, Google Cloud Functions) to run your script every 5-10 minutes. A cron expression for every 5 minutes is */5 * * * *.
  • Sub-step 2: Add Alert Logic: In your script, add conditional statements that trigger alerts. For example: if (healthFactor < 1.2) { sendCriticalAlert(); }.
  • Sub-step 3: Configure Notification Channel: Set up the alert sender. For a Discord webhook, you would HTTP POST a JSON payload to your unique webhook URL.
javascript
// Example snippet for Discord alert const fetch = require('node-fetch'); async function sendDiscordAlert(hfValue) { const webhookURL = 'https://discord.com/api/webhooks/YOUR_WEBHOOK_ID/YOUR_TOKEN'; const message = { content: `🚨 CRITICAL ALERT! Health Factor is ${hfValue.toFixed(2)}!` }; await fetch(webhookURL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(message) }); }

Tip: Include relevant details in the alert: HF value, collateral assets, and a link to the protocol's UI for quick action.

4

Test, Deploy, and Establish a Response Protocol

Validate the entire system and create a plan for when alerts fire.

Detailed Instructions

Thoroughly test the system in a controlled environment and deploy it. Most importantly, establish a clear response protocol so you know exactly what to do when an alert is received.

  • Sub-step 1: Conduct End-to-End Testing: Simulate a dropping Health Factor by using a testnet (e.g., Sepolia) or mocking API responses. Verify that alerts fire correctly at your set thresholds and are delivered to all configured channels (Email, SMS, Discord).
  • Sub-step 2: Deploy Monitoring Service: Move your script and scheduler to a reliable, always-on environment. Using a cloud VM with PM2 or a managed serverless function is recommended for uptime.
  • Sub-step 3: Document the Response Protocol: Create a clear action plan. This should include:
    • Immediate Action: If HF < Critical Threshold, prepare to add collateral or repay debt immediately.
    • Tool Preparation: Have a pre-approved transaction ready in your wallet (e.g., on Aave's UI) with the correct amount of stablecoins or collateral.
    • Fallback Alert: Designate a secondary person to receive alerts in case you are unavailable.

Tip: Regularly review and adjust your thresholds based on market volatility and update your script if the protocol's contract addresses or ABIs change.

Alert Type Comparison

Comparison of alert methods for monitoring borrowing positions and liquidation risk.

FeatureEmail AlertSMS AlertPlatform Notification

Delivery Speed

1-5 minutes

10-30 seconds

Instant (<5 seconds)

Cost

Free

$0.01 per alert

Free

Character Limit

Unlimited

160 characters

500 characters

Requires App Open

No

No

Yes

Supports Price Thresholds

Yes

Yes

Yes

Supports Health Factor %

Yes

No

Yes

Multi-Wallet Support

Up to 5 wallets

Up to 3 wallets

Unlimited

Historical Log

30 days

7 days

90 days

Protocol-Specific Considerations

Understanding Protocol Differences

Automated alerts for borrowing positions are not one-size-fits-all. Each lending protocol has unique mechanics that affect your risk and the alerts you need. The core concept is that while all protocols allow you to borrow assets by providing collateral, their specific rules for liquidation thresholds, health factors, and oracle price feeds vary significantly. Ignoring these differences can lead to unexpected liquidations even with alerts set.

Key Points to Know

  • Liquidation Engine: Protocols like Aave use a Health Factor (HF) that must stay above 1.0 to avoid liquidation, while Compound uses a Collateral Factor. Your alert must track the correct metric.
  • Price Oracle Reliance: Protocols use different oracles. An alert based on a CoinGecko price might not match the Chainlink oracle used by MakerDAO's Vaults, causing a timing gap.
  • Multi-Asset Complexity: On Compound, you can borrow multiple assets against your collateral. An alert should monitor the weighted average health of your entire position, not just a single borrowed token.

Practical Example

When using Aave V3 on Ethereum, you would set an alert for when your Health Factor drops below 1.5 (a safe buffer, not just 1.0). If your collateral is ETH and you borrow USDC, the alert must calculate based on Aave's specific liquidation threshold for ETH (e.g., 80%) and the real-time prices from its designated oracles.

Technical Implementation FAQ

The core setup requires a data ingestion pipeline, a logic engine, and a notification dispatcher. The pipeline fetches real-time on-chain data like collateral ratios and liquidation prices from sources like The Graph or direct RPC calls. The logic engine, often a serverless function or dedicated microservice, applies your custom rules, such as checking if a position's health factor drops below 1.5. The dispatcher then sends alerts via your chosen channel, like email, SMS, or a webhook to platforms like Discord or Slack. For example, a Node.js script using Ethers.js can poll data every minute and trigger an AWS Lambda function to send an alert.

Advanced Configuration & Optimization

Process for setting up automated, intelligent alerts to monitor and manage your DeFi borrowing positions, preventing liquidation and optimizing costs.

1

Define Your Alert Logic & Parameters

Establish the core conditions that will trigger alerts based on your risk tolerance and strategy.

Detailed Instructions

First, you must define the precise Health Factor thresholds and cost metrics that matter to your strategy. The Health Factor is the most critical risk indicator; a value below 1.0 means your position can be liquidated.

  • Sub-step 1: Set Primary Liquidation Alerts: Determine your warning thresholds. For example, set a Critical Alert for a Health Factor below 1.2 and a Warning Alert for below 1.5.
  • Sub-step 2: Configure Cost & Efficiency Alerts: Monitor borrowing costs. Set alerts for when the variable borrow APR on your asset (e.g., USDC) exceeds a specific value like 8% or when a better lending rate becomes available on another platform.
  • Sub-step 3: Define Position-Specific Rules: If you have multiple positions, create rules for each. For a WBTC collateralized loan, you might want a tighter threshold due to volatility compared to a stablecoin-collateralized loan.

Tip: Use a staging environment or testnet to simulate market movements and verify your alert logic triggers correctly before deploying with real funds.

2

Integrate with On-Chain Data Oracles & APIs

Connect your alert system to reliable real-time data sources for prices, rates, and protocol states.

Detailed Instructions

Your alerts are only as good as their data. You must integrate with oracle services like Chainlink and protocol-specific subgraphs or APIs to fetch live market information.

  • Sub-step 1: Fetch Asset Prices: Use a Chainlink price feed to get the real-time price of your collateral (e.g., ETH) and borrowed asset. For mainnet, the ETH/USD feed address is 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419.
  • Sub-step 2: Query Protocol State: Use Aave's subgraph or direct contract calls to fetch your position's dynamic data. A GraphQL query to get a user's health factor might look like:
graphql
query { user(id: "0xYourAddress") { healthFactor } }
  • Sub-step 3: Pull Interest Rate Data: Call the getReserveData function on the Aave LendingPool contract (0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9) for the reserve asset to get current variable and stable borrow rates.

Tip: Implement data aggregation and sanity checks to defend against oracle manipulation or API failures, ensuring your alerts are based on consensus values.

3

Automate with Smart Contracts or Bots

Deploy the automated logic that will monitor conditions and execute alert actions.

Detailed Instructions

This step involves coding the monitoring bot or keeper network script that will evaluate your rules and trigger actions. You can use OpenZeppelin Defender for a managed service or build a custom keeper.

  • Sub-step 1: Choose an Automation Framework: For a custom solution, use a script with ethers.js that runs on a cron job. For a decentralized approach, use Chainlink Keepers by registering an Upkeep contract.
  • Sub-step 2: Implement the Check-Upkeep Logic: Write the function that performs the check. For a Chainlink Keeper, it would look like:
solidity
function checkUpkeep(bytes calldata) external view override returns (bool upkeepNeeded, bytes memory) { uint256 healthFactor = getUserHealthFactor(msg.sender); upkeepNeeded = healthFactor < 1.2 ether; // 1.2 in 18 decimals return (upkeepNeeded, ""); }
  • Sub-step 3: Define the Perform-Upkeep Action: This function executes when a threshold is breached. The action could be calling a notification API, automatically depositing more collateral, or even initiating a safe repayment.

Tip: Always include a circuit breaker or pause function in your automation contracts to manually intervene if the logic behaves unexpectedly during extreme market events.

4

Configure Multi-Channel Notification System

Set up reliable and immediate alert delivery across multiple platforms to ensure you never miss a critical update.

Detailed Instructions

An unseen alert is useless. Configure a robust system that pushes notifications through several channels based on severity.

  • Sub-step 1: Set Up Priority Tiers: Route alerts by urgency. Critical alerts (Health Factor < 1.2) should trigger SMS (via Twilio) and phone calls. Warning alerts (Health Factor < 1.5) can go to Telegram or Discord webhooks.
  • Sub-step 2: Implement Webhook Endpoints: Create secure endpoints to receive alerts from your bot. A Discord webhook URL looks like https://discord.com/api/webhooks/123456/abc123. Your bot would send a POST request with a JSON payload containing the alert details.
  • Sub-step 3: Add On-Chain & Dashboard Visibility: For transparency, emit an event from your alert contract and log the alert. Also, integrate with a dashboard like DeBank or Zapper to visualize your position health alongside the alerts.

Tip: Regularly test your notification channels with non-critical alerts (e.g., weekly test pings) to ensure the entire pipeline—from on-chain event to your phone—is operational and reliable.