Skip to content

Commit

Permalink
feat: add getBalance endpoint using etherscan api (#58)
Browse files Browse the repository at this point in the history
* feat: add balance api endpoint

* feat: etherscan api key
  • Loading branch information
0xbulma authored Nov 28, 2023
1 parent da4c984 commit ae978a7
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 16 deletions.
3 changes: 2 additions & 1 deletion front/.env.local.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
NEXT_PUBLIC_STACKUP_BUNDLER_API_KEY=""
NEXT_PUBLIC_RPC_ENDPOINT="https://eth-sepolia.g.alchemy.com/v2/N5ZVikrQ0kBZLVjyY8GwbpYSLPLRuINB"
NEXT_PUBLIC_RPC_ENDPOINT=""
ETHERSCAN_API_KEY=""
NEXT_PUBLIC_FACTORY_CONTRACT_ADDRESS="0xDD0f9cB4Cf53d28b976C13e7ee4a169F841924c0"
RELAYER_PRIVATE_KEY=""
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 ae978a7

Please sign in to comment.