0

I am trying to build a Python script to retrieve different AAVE rates programmatically (borrow, lending, and rewards), on the Polygon blockchain (will be very similar for Ethereum). I am using Python.

So far I managed to retrieve the borrow and lending rates for the available currencies on AAVE (DAI, USDC, MATIC, WETH, WBTC, USDT). See the code to do that below. I would like also to retrieve the WMATIC APR Rewards rates automatically. I did not find a way to do that yet. Does someone know how to do it ?

To be clear I mean to retrieve the numbers highlighted here:

enter image description here

In the following link https://docs.aave.com/developers/guides/apy-and-apr they give a way to calculate a "percentDepositAPR" and "percentBorrowAPR", but it gives obviously wrong values when I implement it, and so I assume this concerns something else and not the MATIC token rewards distribution.

Also interesting information here:

Polygon is giving out MATIC rewards in two phases: 0.5% of the total supply from today until June 14th, and another 0.5% between June 14th and April 13th, 2022.

But that is not enough information to calculate the reward rates.

Thanks in advance.

import json
import requests
import urllib3
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport

token_ticker = 'USDC'
reward_token_ticker = 'WMATIC'

URL_API = 'https://api.thegraph.com/subgraphs/name/aave/aave-v2-matic'
query = gql('''
query {
  reserves (where: {
    usageAsCollateralEnabled: true
  }) {
    id
    name
    price {
      id
      priceInEth
    }
    liquidityRate
    variableBorrowRate
    stableBorrowRate
    aEmissionPerSecond
    vEmissionPerSecond
    decimals
    totalATokenSupply
    totalCurrentVariableDebt
    symbol
  }
}
''')
sample_transport=RequestsHTTPTransport(
    url=URL_API,
    verify=True,
    retries=3,
)
client = Client(
    transport=sample_transport
)

response = client.execute(query)

for token in response['reserves']:
    if token_ticker in token['symbol']:
        variableBorrowRate = float(token['variableBorrowRate'])
        liquidityRate = float(token['liquidityRate'])
        TOKEN_DECIMALS = float(token['decimals'])
        TOKEN_PRICE_ETH = float(token['price']['priceInEth'])/10.0**18
        aEmissionPerSecond = float(token['aEmissionPerSecond'])
        vEmissionPerSecond = float(token['vEmissionPerSecond'])
        totalCurrentVariableDebt = float(token['totalCurrentVariableDebt'])
        totalATokenSupply  = float(token['totalATokenSupply'])
    if reward_token_ticker in token['symbol']:
        REWARD_PRICE_ETH = float(token['price']['priceInEth'])/10.0**18
        REWARD_DECIMALS = float(token['decimals'])
        

RAY = 10.0**27
WAD = 10.0**18
SECONDS_PER_YEAR = 31556926.0

# deposit and borrow calculation

percentDepositAPY = 100.0 * liquidityRate/RAY
percentVariableBorrowAPY = 100.0 * variableBorrowRate/RAY
percentStableBorrowAPY = 100.0 * variableBorrowRate/RAY

print(f"{token_ticker} deposit APY: {percentDepositAPY:.2f}%")
print(f"{token_ticker} borrow APY: {percentVariableBorrowAPY:.2f}%")

EDIT: Below is attempt to calculate the WMATIC rewards APR. But resulting values are not consistent with the AAVE website, except for WMATIC as token_ticker. When I set WMATIC both as main token and reward, I get the values I need. But I still can't get it for the rest: USDC, DAI, etc...

percentDepositAPR = 100 * (aEmissionPerSecond*SECONDS_PER_YEAR * REWARD_PRICE_ETH * TOKEN_DECIMALS) / (totalATokenSupply * TOKEN_PRICE_ETH * REWARD_DECIMALS)
print(f"{percentDepositAPR:.2f}")

percentBorrowAPR = 100 * (vEmissionPerSecond*SECONDS_PER_YEAR * REWARD_PRICE_ETH * TOKEN_DECIMALS) / (totalCurrentVariableDebt * TOKEN_PRICE_ETH * REWARD_DECIMALS)
print(f"{percentBorrowAPR:.2f}")
0

So I solved the problem. There were two mistakes:

  1. For the "REWARD_DECIMAL" and the "TOKEN_DECIMAL" I should use 10 to the power of the number, and not the numbers themselves.
  2. Prices in ETH retrieved from the call to the API api.thegraph.com are wrong for some reason. So I replaced by calls to Binance API to get the prices in ETH.

Bellow is the Python code giving the correct results:

import json
import requests
import urllib3
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport

token_ticker = 'USDC'
reward_token_ticker = 'WMATIC'

RAY = 10.0**27
WAD = 10.0**18
SECONDS_PER_YEAR = 31556926.0

#################################################
def get_token_price_in_eth(token_ticker):

    if token_ticker!='USDT':
      while True:
        r = requests.get(
          f'https://api.binance.com/api/v3/ticker/price?symbol={token_ticker}USDT')
        if r.status_code == 200:
          break
      data = r.json()
      token_in_usdt=  float(data['price'])
    else:
      token_in_usdt = 1.0

    while True:
      r = requests.get(
        'https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT')
      if r.status_code == 200:
        break
    data = r.json()
    eth_in_usdt=  float(data['price'])

    return token_in_usdt/eth_in_usdt

#################################################

URL_API = 'https://api.thegraph.com/subgraphs/name/aave/aave-v2-matic'
query = gql('''
query {
  reserves (where: {
    usageAsCollateralEnabled: true
  }) {
    id
    name
    price {
      id
      priceInEth
    }
    liquidityRate
    variableBorrowRate
    stableBorrowRate
    aEmissionPerSecond
    vEmissionPerSecond
    decimals
    totalATokenSupply
    totalCurrentVariableDebt
    symbol
  }
}
''')

sample_transport=RequestsHTTPTransport(
    url=URL_API,
    verify=True,
    retries=3,
)
client = Client(
    transport=sample_transport
)

response = client.execute(query)

for token in response['reserves']:
    if token_ticker in token['symbol']:
        variableBorrowRate = float(token['variableBorrowRate'])
        liquidityRate = float(token['liquidityRate'])
        TOKEN_DECIMALS = 10**float(token['decimals'])
        aEmissionPerSecond = float(token['aEmissionPerSecond'])
        vEmissionPerSecond = float(token['vEmissionPerSecond'])
        totalCurrentVariableDebt = float(token['totalCurrentVariableDebt'])
        totalATokenSupply  = float(token['totalATokenSupply'])
    if reward_token_ticker in token['symbol']:
        REWARD_DECIMALS = 10**float(token['decimals'])


REWARD_PRICE_ETH = get_token_price_in_eth('MATIC') 
TOKEN_PRICE_ETH = get_token_price_in_eth(token_ticker.replace('W', '')) 

# deposit and borrow calculation

percentDepositAPY = 100.0 * liquidityRate/RAY
percentVariableBorrowAPY = 100.0 * variableBorrowRate/RAY
percentStableBorrowAPY = 100.0 * variableBorrowRate/RAY

print(f"{token_ticker} deposit APY: {percentDepositAPY:.2f}%")
print(f"{token_ticker} borrow APY: {percentVariableBorrowAPY:.2f}%")

percentDepositAPR = 100 * (aEmissionPerSecond*SECONDS_PER_YEAR * REWARD_PRICE_ETH * TOKEN_DECIMALS) / (totalATokenSupply * TOKEN_PRICE_ETH * REWARD_DECIMALS)
percentBorrowAPR = 100 * (vEmissionPerSecond*SECONDS_PER_YEAR * REWARD_PRICE_ETH * TOKEN_DECIMALS) / (totalCurrentVariableDebt * TOKEN_PRICE_ETH * REWARD_DECIMALS)

print(f"{token_ticker} WMATIC reward deposit APR: {percentDepositAPR:.2f}%")
print(f"{token_ticker} WMATIC reward borrow APR: {percentBorrowAPR:.2f}%")

It gives the following result (on 12 Sept. 2021 @ 21:05 UTC):

USDC deposit APY: 3.18%
USDC borrow APY: 3.96%
USDC WMATIC reward deposit APR: 1.60%
USDC WMATIC reward borrow APR: 2.71%

Which is close enough to what is given on the AAVE app website :

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.