Skip to content
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
86 changes: 86 additions & 0 deletions apps/indexer/src/app/routes/_chain/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ import { TTokenSelected, tTokensSelectors } from '../../../database/selectors';
import {
fetchPoolList,
fetchPoolReserves,
fetchUserReserves,
selectPoolById,
} from '../../../libs/loaders/money-market';
import { paginationResponse, paginationSchema } from '../../../libs/pagination';
import { transformUserReservesData } from '../../../libs/utils/user-reserves';

interface ReserveDataHumanized {
originalId: number;
Expand Down Expand Up @@ -262,4 +264,88 @@ export default async function (fastify: FastifyInstance) {
// };
},
);

fastify.withTypeProvider<ZodTypeProvider>().get(
'/money-market/:pool/user/:address/lendings',
{
schema: {
querystring: paginationSchema,
params: z.object({
pool: z.string(),
address: z.string(),
}),
},
config: {
cache: true,
},
},
async (
req: FastifyRequest<{ Params: { pool: string; address: string } }>,
reply,
) => {
const pools = await fetchPoolList(req.chain.chainId);
const pool = selectPoolById(req.params.pool, pools);

if (!pool) return reply.notFound('Pool not found');

const userReservesRaw = await fetchUserReserves(
req.chain.chainId,
pool,
req.params.address,
);

const activePositions = userReservesRaw.filter(
(r) => r.scaledATokenBalance > 0n,
);

return transformUserReservesData({
chainId: req.chain.chainId,
userAddress: req.params.address,
pool,
reserves: activePositions,
});
},
);

fastify.withTypeProvider<ZodTypeProvider>().get(
'/money-market/:pool/user/:address/borrowings',
{
schema: {
querystring: paginationSchema,
params: z.object({
pool: z.string(),
address: z.string(),
}),
},
config: {
cache: true,
},
},
async (
req: FastifyRequest<{ Params: { pool: string; address: string } }>,
reply,
) => {
const pools = await fetchPoolList(req.chain.chainId);
const pool = selectPoolById(req.params.pool, pools);

if (!pool) return reply.notFound('Pool not found');

const userReservesRaw = await fetchUserReserves(
req.chain.chainId,
pool,
req.params.address,
);

const activeBorrows = userReservesRaw.filter(
(r) => r.scaledVariableDebt > 0n || r.principalStableDebt > 0n,
);

return transformUserReservesData({
chainId: req.chain.chainId,
userAddress: req.params.address,
pool,
reserves: activeBorrows,
});
},
);
}
20 changes: 19 additions & 1 deletion apps/indexer/src/libs/loaders/money-market.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ const uiPoolDataProviderAbi = [
},
] as const;

type PoolDefinition = {
export type PoolDefinition = {
id: string | 'default';
name: string;
logoURI: string;
Expand Down Expand Up @@ -407,3 +407,21 @@ export async function fetchPoolReserves(
args: [pool.poolAddressesProvider],
});
}

export async function fetchUserReserves(
chainId: ChainSelector,
pool: PoolDefinition,
user: string,
) {
const chain = chains.get(chainId);
if (!chain) {
throw new Error(`Unsupported chain: ${chainId}`);
}

return chain.rpc.readContract({
address: pool.uiPoolDataProvider,
abi: uiPoolDataProviderAbi,
functionName: 'getUserReservesData',
args: [pool.poolAddressesProvider, user as Address],
});
}
57 changes: 57 additions & 0 deletions apps/indexer/src/libs/utils/user-reserves.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { areAddressesEqual } from '@sovryn/slayer-shared';
import { and, eq, inArray } from 'drizzle-orm';
import { client } from '../../database/client';
import { tTokens } from '../../database/schema';
import { tTokensSelectors } from '../../database/selectors';
import { PoolDefinition } from '../loaders/money-market';

export async function transformUserReservesData({
chainId,
userAddress,
pool,
reserves,
}: {
chainId: number;
userAddress: string;
pool: PoolDefinition;
reserves: Array<{
underlyingAsset: string;
scaledATokenBalance: bigint;
usageAsCollateralEnabledOnUser: boolean;
stableBorrowRate: bigint;
scaledVariableDebt: bigint;
principalStableDebt: bigint;
stableBorrowLastUpdateTimestamp: bigint;
}>;
}) {
if (!reserves.length) {
return { data: [], count: 0 };
}

const tokens = await client.query.tTokens.findMany({
columns: tTokensSelectors.columns,
where: and(
eq(tTokens.chainId, chainId),
inArray(
tTokens.address,
reserves.map((i) => i.underlyingAsset.toLowerCase()),
),
),
});

const data = reserves.map((pos) => ({
id: `${chainId}-${pos.underlyingAsset}-${pool.address}-${userAddress}`.toLowerCase(),
user: userAddress,
pool,
token: tokens.find((t) =>
areAddressesEqual(t.address, pos.underlyingAsset),
),
scaledVariableDebt: pos?.scaledVariableDebt.toString(),
principalStableDebt: pos?.principalStableDebt.toString(),
stableBorrowRate: pos?.stableBorrowRate.toString(),
stableBorrowLastUpdateTimestamp: pos.stableBorrowLastUpdateTimestamp,
usageAsCollateralEnabledOnUser: pos.usageAsCollateralEnabledOnUser,
}));

return { data, count: data.length };
}