im working on a lending protocol and for tracking borrowers debt i want to use aave debtTokens pattern but i don't get how aave increases borrowers balances in real time since we cannot change blockchain state without sending a transaction . if anyone can explain the implementation it would be greate . PS : im only using variable borrow rate not stable rate PS1 : i know how to calculate variable borrow rate .
For debt tokens the balance is actually increased in real time (or as quickly as block times allows). If you are familiar with Olympus DAO or Wonderland their rebase tokens work in a very similar way, which is why you will see your MEMO balance increase without having to actually receive any incoming token transfers.
The key is to use an index. This index can be something as simple as the block height, but usually it represents something a little more informative. Often such index will for example start at 1 and then be multiplied by the interest rate at some given interval such that it always increases (assuming a positive interest rate). So after a year at 5% APY the index would for example have grown to 1.05.
Now this index is used to calculate each users balance. Such that when someone calls the balanceOf method what they get back is the principal amount multiplied by the index. This means that by only the index changing all balances will be updated according without having to actually change the state to update each user balance.
Of course this is a slightly simplified explanation, and there are other implementation details to consider. For example since not everyone has had the debt for the same amount of time it is also required that each opened position records at which index they entered, such that this can be considered to only increase the balance with the difference between the starting index and the current index.