-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathblockchainMetadataClient.ts
More file actions
171 lines (146 loc) · 4.86 KB
/
Copy pathblockchainMetadataClient.ts
File metadata and controls
171 lines (146 loc) · 4.86 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import { logger } from '@metamask/7715-permissions-shared/utils';
import { decodeSingle } from '@metamask/abi-utils';
import type { Hex } from '@metamask/delegation-core';
import type { SnapsEthereumProvider } from '@metamask/snaps-sdk';
import { ZERO_ADDRESS } from '../constants';
import type { TokenBalanceAndMetadata, TokenMetadataClient } from './types';
/**
* Client that fetches token metadata directly from the blockchain using the ethereum provider
*/
export class BlockchainTokenMetadataClient implements TokenMetadataClient {
readonly #ethereumProvider: SnapsEthereumProvider;
static readonly #nativeTokenAddress = ZERO_ADDRESS;
static readonly #nativeTokenDecimals = 18;
static readonly #nativeTokenSymbol = 'ETH';
// keccak256('balanceOf(address)')
static readonly #balanceOfCalldata = '0x70a08231';
// keccak256('decimals()')
static readonly #decimalsCalldata = '0x313ce567';
// keccak256('symbol()')
static readonly #symbolCalldata = '0x95d89b41';
constructor({
ethereumProvider,
}: {
ethereumProvider: SnapsEthereumProvider;
}) {
this.#ethereumProvider = ethereumProvider;
}
/**
* Fetch the token balance and metadata for a given account and token.
* @param args - The parameters for fetching the token balance.
* @param args.chainId - The chain ID to fetch the balance from.
* @param args.assetAddress - The token address to fetch the balance for. If not provided, fetches native token balance.
* @param args.account - The account address to fetch the balance for.
* @returns The token balance and metadata.
*/
public async getTokenBalanceAndMetadata({
chainId,
assetAddress,
account,
}: {
chainId: number;
account: Hex;
assetAddress?: Hex | undefined;
}): Promise<TokenBalanceAndMetadata> {
logger.debug('BlockchainTokenMetadataClient:getTokenBalanceAndMetadata()');
if (!chainId) {
const message = 'No chainId provided to fetch token balance';
logger.error(message);
throw new Error(message);
}
if (!account) {
const message = 'No account address provided to fetch token balance';
logger.error(message);
throw new Error(message);
}
// Check if we're on the correct chain
const selectedChain = await this.#ethereumProvider.request({
method: 'eth_chainId',
params: [],
});
if (Number(selectedChain) !== chainId) {
throw new Error('Selected chain does not match the requested chain');
}
// If no asset address is provided, fetch native token balance
if (
!assetAddress ||
assetAddress === BlockchainTokenMetadataClient.#nativeTokenAddress
) {
const balance = await this.#ethereumProvider.request<Hex>({
method: 'eth_getBalance',
params: [account, 'latest'],
});
if (balance === undefined || balance === null) {
throw new Error('Failed to fetch native token balance');
}
const { symbol, decimals } = {
symbol: BlockchainTokenMetadataClient.#nativeTokenSymbol,
decimals: BlockchainTokenMetadataClient.#nativeTokenDecimals,
};
return {
balance: BigInt(balance),
decimals,
symbol,
};
}
const [balanceEncoded, decimalsEncoded, symbolEncoded] = await Promise.all([
this.#ethereumProvider.request<Hex>({
method: 'eth_call',
params: [
{
to: assetAddress,
data: BlockchainTokenMetadataClient.#balanceOfCalldata,
},
'latest',
],
}),
this.#ethereumProvider.request<Hex>({
method: 'eth_call',
params: [
{
to: assetAddress,
data: BlockchainTokenMetadataClient.#decimalsCalldata,
},
'latest',
],
}),
this.#ethereumProvider.request<Hex>({
method: 'eth_call',
params: [
{
to: assetAddress,
data: BlockchainTokenMetadataClient.#symbolCalldata,
},
'latest',
],
}),
]);
if (!symbolEncoded) {
logger.error('Failed to fetch token symbol');
throw new Error('Failed to fetch token symbol');
}
if (!decimalsEncoded) {
logger.error('Failed to fetch token decimals');
throw new Error('Failed to fetch token decimals');
}
if (!balanceEncoded) {
logger.error('Failed to fetch token balance');
throw new Error('Failed to fetch token balance');
}
try {
const symbol = decodeSingle('string', symbolEncoded);
const decimals = decodeSingle('uint8', decimalsEncoded);
const balance = decodeSingle('uint256', balanceEncoded);
return {
balance,
decimals: Number(decimals),
symbol,
};
} catch (error) {
logger.error(
`Failed to fetch token balance and metadata: ${(error as Error).message}.`,
);
throw error;
}
}
}