Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add global apr matirity #639

Merged
merged 2 commits into from
May 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 27 additions & 6 deletions packages/core/src/services/protocol/index.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,43 @@
import { Contract } from 'ethers';
import { JsonRpcProvider } from '@ethersproject/providers';
import { queries } from '../../subgraph';
import { config } from '../../..';
import { ERC20ABI } from '../../contracts';
import BigNumber from 'bignumber.js';
import {
getMicroCreditStatsLastDays,
getGlobalData,
} from '../../subgraph/queries/microcredit';

export default class ProtocolService {
public getMicroCreditData = async (): Promise<any> => {
const subgraphData = await queries.microcredit.getGlobalData();
const subgraphData = await getGlobalData();
const todayDayId = Math.floor(Date.now() / 1000 / 86400);
const thirtyDaysData = await getMicroCreditStatsLastDays(
todayDayId - 30,
todayDayId
);
const ninetyDaysData = await getMicroCreditStatsLastDays(
todayDayId - 90,
todayDayId
);

// TODO: calculate applications { totalApplications, inReview }

const estimatedMaturity = 0; // (paid back in the past 3 months / 3 / current debt)
// paid back in the past 3 months / 3 / current debt
const estimatedMaturity =
ninetyDaysData.repaid / 3 / subgraphData.currentDebt;
const avgBorrowedAmount = Math.round(
subgraphData.totalBorrowed / subgraphData.activeBorrowers
);
const apr = 0; // (paid back past 7 months - borrowed past 7 months) / borrowed past 7 months / 7 * 12
// Interest paid in the past month / Debt paid in the past month * 12
const apr = (thirtyDaysData.interest / thirtyDaysData.repaid) * 12;

const provider = new JsonRpcProvider(config.jsonRpcUrl);
const cUSD = new Contract(config.cUSDContractAddress, ERC20ABI, provider);
const cUSD = new Contract(
config.cUSDContractAddress,
ERC20ABI,
provider
);
const balance = await cUSD.balanceOf(config.microcreditContractAddress);

return {
Expand All @@ -28,7 +47,9 @@ export default class ProtocolService {
avgBorrowedAmount,
apr,
...subgraphData,
liquidityAvailable: new BigNumber(balance.toString()).dividedBy(new BigNumber(10).pow(18)).toNumber(),
liquidityAvailable: new BigNumber(balance.toString())
.dividedBy(new BigNumber(10).pow(18))
.toNumber(),
};
};
}
124 changes: 121 additions & 3 deletions packages/core/src/subgraph/queries/microcredit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,117 @@ export const getGlobalData = async (): Promise<{
}
};

export const getMicroCreditStatsLastDays = async (
fromDayId: number,
toDayId: number
): Promise<{
borrowed: number;
debt: number;
repaid: number;
interest: number;
}> => {
try {
const graphqlQuery = {
operationName: 'microCredit',
query: `query microCredit {
microCredits(
where: {
id_gte: ${fromDayId}
id_lt: ${toDayId}
}
) {
borrowed {
asset
amount
}
debt {
asset
amount
}
repaid {
asset
amount
}
interest {
asset
amount
}
}
}`,
};

const cacheResults = await redisClient.get(graphqlQuery.query);

if (cacheResults) {
return JSON.parse(cacheResults);
}

const response = await axiosMicrocreditSubgraph.post<
any,
{
data: {
data: {
microCredits: {
borrowed: Asset[];
debt: Asset[];
repaid: Asset[];
interest: Asset[];
}[];
};
};
}
>('', graphqlQuery);

const microCredits = response.data?.data.microCredits;

const borrowed = microCredits.reduce((acc, curr) => {
if (curr.borrowed && curr.borrowed.length) {
return acc + parseFloat(curr.borrowed[0].amount);
}
return acc;
}, 0);

const debt = microCredits.reduce((acc, curr) => {
if (curr.debt && curr.debt.length) {
return acc + parseFloat(curr.debt[0].amount);
}
return acc;
}, 0);

const repaid = microCredits.reduce((acc, curr) => {
if (curr.repaid && curr.repaid.length) {
return acc + parseFloat(curr.repaid[0].amount);
}
return acc;
}, 0);

const interest = microCredits.reduce((acc, curr) => {
if (curr.interest && curr.interest.length) {
return acc + parseFloat(curr.interest[0].amount);
}
return acc;
}, 0);

const stats = {
borrowed,
debt,
repaid,
interest,
};

redisClient.set(
graphqlQuery.query,
JSON.stringify(stats),
'EX',
intervalsInSeconds.twoMins
);

return stats;
} catch (error) {
throw new Error(error);
}
};

export const getBorrowers = async (query: {
offset?: number;
limit?: number;
Expand Down Expand Up @@ -137,7 +248,11 @@ export const getBorrowers = async (query: {
}"
${query.claimed ? `claimed_not: null` : ''}
}
${query.claimed ? `orderBy: claimed orderDirection: desc` : ''}
${
query.claimed
? `orderBy: claimed orderDirection: desc`
: ''
}
) {
amount
period
Expand Down Expand Up @@ -195,7 +310,10 @@ export const getBorrowers = async (query: {
return borrowers;
};

export const getLoanRepayments = async (userAddress: string, loanId: number): Promise<number> => {
export const getLoanRepayments = async (
userAddress: string,
loanId: number
): Promise<number> => {
const graphqlQuery = {
operationName: 'loan',
query: `query loan {
Expand Down Expand Up @@ -234,4 +352,4 @@ export const getLoanRepayments = async (userAddress: string, loanId: number): Pr
);

return loanRepayments;
}
};