Get User Earnings

Tracking earnings on Idle is easy, you just need the avg buy price of the IdleTokens, the amount of IdleTokens held by a user and the current price.

IdleToken contract saves and updates the userAvgPrices mapping which contains the avg price paid for each IdleToken of a user, so to calculate earnings (in underlying) one can do the following:

address user = <address_of_user>;
IIdleToken idleDAI = IIdleToken(<address_idle_token>);
‚Äč
uint256 userBalance = idleDAI.balanceOf(user);
uint256 avgCost = userBalance.times(idleDAI.userAvgPrices(user)).div(10**18);
uint256 currentValue = userBalance.times(idleDAI.tokenPrice()).div(10**18);
uint256 earnings = currentValue.minus(avgCost);