Skip to content

Commit

Permalink
feat: add balance api endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
0xbulma committed Nov 28, 2023
1 parent bda7cea commit 10b61a6
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 15 deletions.
15 changes: 15 additions & 0 deletions front/src/app/api/balance/[address]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Hex, stringify } from "viem";

export async function GET(_req: Request, { params }: { params: { address: Hex } }) {
const { address } = params;
if (!address) {
return Response.json(JSON.parse(stringify({ error: "address is required" })));
}
const result = await fetch(
`https://api-sepolia.etherscan.io/api?module=account&action=balance&address=${address}&tag=latest&apikey=${process.env.ETHERSCAN_API_KEY}`,
);
const resultJSON = await result.json();
const balance = BigInt(resultJSON?.result || 0);

return Response.json(JSON.parse(stringify({ balance })));
}
13 changes: 12 additions & 1 deletion front/src/app/api/users/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ export async function GET(_req: Request, { params }: { params: { id: Hex } }) {
args: [BigInt(id)],
});

const balance = await PUBLIC_CLIENT.getBalance({ address: user.account });
//const balance = await PUBLIC_CLIENT.getBalance({ address: user.account });
let balance = BigInt(0);

// Using etherscan api instead of getBalance as Sepolia rcp node is not inconsistent
if (user?.account) {
const result = await fetch(
`https://api-sepolia.etherscan.io/api?module=account&action=balance&address=${user.account}&tag=latest&apikey=${process.env.ETHERSCAN_API_KEY}`,
);
const resultJSON = await result.json();
balance = BigInt(resultJSON?.result || 0);
}

return Response.json(JSON.parse(stringify({ ...user, id: toHex(user.id), balance })));
}
14 changes: 14 additions & 0 deletions front/src/libs/factory/getBalance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Address, Hex } from "viem";

export type User = { id: Hex; pubKey: { x: Hex; y: Hex }; account: Address; balance: bigint };

export async function getBalance(address: Hex): Promise<{ balance: bigint }> {
const response = await fetch(`/api/balance/${address}`, {
method: "GET",
});

const user = await response.json();
return {
balance: user.balance,
};
}
24 changes: 10 additions & 14 deletions front/src/providers/BalanceProvider/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"use client";

import { getUser } from "@/libs/factory/getUser";
import { getBalance } from "@/libs/factory/getBalance";
import { useMe } from "@/providers/MeProvider";
import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
import { Hex, formatEther, zeroAddress } from "viem";
import { Hex, formatEther } from "viem";

function useBalanceHook() {
// balance in usd
Expand All @@ -12,15 +12,11 @@ function useBalanceHook() {

const { me } = useMe();

const getBalance = useCallback(async (keyId: Hex) => {
const user = await getUser(keyId);
if (user?.account === zeroAddress || user?.account === undefined) {
setBalance("0.00");
return;
}
const getBalanceUSD = useCallback(async (address: Hex) => {
const res = await getBalance(address);
const priceData = await fetch("/api/price?ids=ethereum&currencies=usd");
const price: number = Math.trunc((await priceData.json()).ethereum.usd * 100);
const balance = formatEther((BigInt(user.balance) * BigInt(price)) / BigInt(100));
const balance = formatEther((BigInt(res.balance) * BigInt(price)) / BigInt(100));
setBalance(balance);
}, []);

Expand All @@ -31,17 +27,17 @@ function useBalanceHook() {
let interval = useRef<NodeJS.Timeout | null>(null);

useEffect(() => {
if (!me?.keyId) return;
getBalance(me?.keyId);
if (!me?.account) return;
getBalanceUSD(me?.account);
interval.current && clearInterval(interval.current);
interval.current = setInterval(() => {
getBalance(me?.keyId);
}, 3000);
getBalanceUSD(me?.account);
}, 5000);

return () => {
interval.current && clearInterval(interval.current);
};
}, [me, getBalance, increment]);
}, [me?.account, getBalanceUSD, increment]);

return {
balance,
Expand Down

0 comments on commit 10b61a6

Please sign in to comment.