-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathuseSocketAssets.ts
93 lines (84 loc) · 2.94 KB
/
useSocketAssets.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { useState, useCallback, useEffect } from 'react';
import { AssetBalance, NATIVE_TOKEN_ADDRESS } from 'types/Bridge';
import { useWeb3 } from './useWeb3';
import { socketRequest } from 'utils/socket';
import usePrices from './usePrices';
import useBalance from './useBalance';
import { Hex } from 'viem';
import VELO_ from '@exactly/protocol/deployments/optimism/VELO.json' assert { type: 'json' };
import useVELO from './useVELO';
export const ETH = {
chainId: 10,
address: NATIVE_TOKEN_ADDRESS,
name: 'Ether',
symbol: 'ETH',
decimals: 18,
chainAgnosticId: null,
icon: '/img/assets/WETH.svg',
logoURI: '/img/assets/WETH.svg',
amount: 0,
usdAmount: 0,
} satisfies AssetBalance;
const VELO = {
chainId: 10,
address: VELO_.address as Hex,
name: 'Velodrome',
symbol: 'VELO',
decimals: 18,
chainAgnosticId: null,
icon: 'https://velodrome.finance/velodrome.svg',
logoURI: 'https://velodrome.finance/velodrome.svg',
amount: null,
usdAmount: null,
} satisfies Omit<AssetBalance, 'amount' | 'usdAmount'> & { amount: null; usdAmount: null };
export default (disableFetch?: boolean, chainId?: number) => {
const [assets, setAssets] = useState<AssetBalance[]>([ETH]);
const { walletAddress } = useWeb3();
const prices = usePrices();
const veloBalance = useBalance(VELO.symbol, VELO.address, true);
const { veloPrice } = useVELO();
const fetchAssets = useCallback(async () => {
if (!walletAddress || !process.env.NEXT_PUBLIC_SOCKET_API_KEY || disableFetch) return;
const result = await socketRequest<Omit<AssetBalance, 'usdAmount'>[]>('balances', { userAddress: walletAddress });
if (result.length === 0) {
return setAssets([ETH]);
}
setAssets(
[...result, VELO]
.filter((asset) => chainId === undefined || asset.chainId === chainId)
.map((asset) => {
const price = prices[asset.address.toLowerCase() as Hex];
const amount = asset.amount ?? Number(veloBalance);
return {
...asset,
amount,
usdAmount: price ? amount * (Number(price) / 1e18) : undefined,
...(asset.symbol === 'ETH'
? {
name: 'Ether',
icon: '/img/assets/WETH.svg',
logoURI: '/img/assets/WETH.svg',
}
: asset.symbol === 'VELO'
? {
usdAmount: veloPrice ? amount * veloPrice : undefined,
}
: {}),
};
})
.sort((a, b) =>
a.usdAmount === undefined && b.usdAmount === undefined
? a.symbol.localeCompare(b.symbol)
: a.usdAmount === undefined
? 1
: b.usdAmount === undefined
? -1
: b.usdAmount - a.usdAmount,
),
);
}, [chainId, disableFetch, prices, veloBalance, veloPrice, walletAddress]);
useEffect(() => {
fetchAssets();
}, [fetchAssets]);
return assets;
};