-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathutils.ts
More file actions
274 lines (228 loc) · 7.54 KB
/
utils.ts
File metadata and controls
274 lines (228 loc) · 7.54 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import { CoinFeature, NetworkType, BaseCoin, EthereumNetwork } from '@bitgo/statics';
import EthereumCommon from '@ethereumjs/common';
import request from 'superagent';
import { InvalidTransactionError } from '@bitgo/sdk-core';
/**
* @param {NetworkType} network either mainnet or testnet
* @returns {EthereumCommon} Ethereum common configuration object
*/
export function getCommon(coin: Readonly<BaseCoin>): EthereumCommon {
if (!coin.features.includes(CoinFeature.SHARED_EVM_SDK)) {
throw new InvalidTransactionError(`Cannot use common sdk module for the coin ${coin.name}`);
}
return EthereumCommon.custom(
{
name: coin.network.name,
networkId: (coin.network as EthereumNetwork).chainId,
chainId: (coin.network as EthereumNetwork).chainId,
},
{
baseChain: coin.network.type === NetworkType.MAINNET ? 'mainnet' : 'sepolia',
hardfork: coin.features.includes(CoinFeature.EIP1559) ? 'london' : undefined,
eips: coin.features.includes(CoinFeature.EIP1559) ? [1559] : undefined,
}
);
}
function tinybarsToWei(tinybars: string): string {
// Convert from tinybars to wei (1 HBAR = 10^8 tinybars, 1 HBAR = 10^18 wei)
// So: wei = tinybars * 10^10
return (BigInt(tinybars) * BigInt('10000000000')).toString();
}
/**
*
* @param query - etherscan query parameters for the API call
* @param rpcUrl - RPC URL of the Hedera network
* @param explorerUrl - base URL of the Hedera Mirror Node API
* @param token - optional API key to use for the query
* @returns
*/
export async function recovery_HBAREVM_BlockchainExplorerQuery(
query: Record<string, string>,
rpcUrl: string,
explorerUrl: string,
token?: string
): Promise<Record<string, unknown>> {
// Hedera Mirror Node API does not use API keys, but we keep this for compatibility
if (token) {
query.apikey = token;
}
const { module, action } = query;
// Remove trailing slash from explorerUrl if present
const baseUrl = explorerUrl.replace(/\/$/, '');
switch (`${module}.${action}`) {
case 'account.balance':
return await queryAddressBalanceHedera(query, baseUrl);
case 'account.txlist':
return await getAddressNonceHedera(query, baseUrl);
case 'account.tokenbalance':
return await queryTokenBalanceHedera(query, baseUrl);
case 'proxy.eth_gasPrice':
return await getGasPriceFromRPC(query, rpcUrl);
case 'proxy.eth_estimateGas':
return await getGasLimitFromRPC(query, rpcUrl);
case 'proxy.eth_call':
return await querySequenceIdFromRPC(query, rpcUrl);
default:
throw new Error(`Unsupported API call: ${module}.${action}`);
}
}
/**
* 1. Gets address balance using Hedera Mirror Node API
*/
async function queryAddressBalanceHedera(
query: Record<string, string>,
baseUrl: string
): Promise<Record<string, unknown>> {
const address = query.address;
const url = `${baseUrl}/accounts/${address}?transactions=false`;
const response = await request.get(url).send();
if (!response.ok) {
throw new Error('could not reach explorer');
}
const balance = response.body.balance?.balance || '0';
const balanceInWei = tinybarsToWei(balance);
return { result: balanceInWei };
}
/**
* 2. Gets nonce using Hedera Mirror Node API
*/
async function getAddressNonceHedera(query: Record<string, string>, baseUrl: string): Promise<Record<string, unknown>> {
const address = query.address;
const accountUrl = `${baseUrl}/accounts/${address}?transactions=false`;
const response = await request.get(accountUrl).send();
if (!response.ok) {
throw new Error('could not reach explorer');
}
const nonce = response.body.ethereum_nonce || 0;
return { nonce: nonce };
}
/**
* 3. Gets token balance using Hedera Mirror Node API
*/
async function queryTokenBalanceHedera(
query: Record<string, string>,
baseUrl: string
): Promise<Record<string, unknown>> {
const contractAddress = query.contractaddress;
const address = query.address;
// Get token balances for the account
const url = `${baseUrl}/accounts/${address}/tokens`;
const response = await request.get(url).send();
if (!response.ok) {
throw new Error('could not reach explorer');
}
// Find the specific token balance
const tokens = response.body.tokens || [];
const tokenBalance = tokens.find(
(token: { token_id: string; contract_address: string; balance: number }) =>
token.token_id === contractAddress || token.contract_address === contractAddress
);
const balance = tokenBalance && tokenBalance.balance !== null ? tokenBalance.balance.toString() : '0';
const balanceInWei = tinybarsToWei(balance);
return { result: balanceInWei };
}
/**
* 4. Gets sequence ID using RPC call
*/
async function querySequenceIdFromRPC(query: Record<string, string>, rpcUrl: string): Promise<Record<string, unknown>> {
const { to, data } = query;
const requestBody = {
jsonrpc: '2.0',
method: 'eth_call',
params: [
{
to: to,
data: data,
},
],
id: 1,
};
const response = await request.post(rpcUrl).send(requestBody).set('Content-Type', 'application/json');
if (!response.ok) {
throw new Error('could not fetch sequence ID from RPC');
}
return response.body;
}
/**
* 5. getGasPriceFromRPC - Gets gas price using Hedera Mirror Node API
*/
async function getGasPriceFromRPC(query: Record<string, string>, rpcUrl: string): Promise<Record<string, unknown>> {
const requestBody = {
jsonrpc: '2.0',
method: 'eth_gasPrice',
params: [],
id: 1,
};
const response = await request.post(rpcUrl).send(requestBody).set('Content-Type', 'application/json');
if (!response.ok) {
throw new Error('could not fetch gas price from RPC');
}
return response.body;
}
/**
* 6. getGasLimitFromRPC - Gets gas limit estimate using RPC call.
*/
async function getGasLimitFromRPC(query: Record<string, string>, rpcUrl: string): Promise<Record<string, unknown>> {
const { from, to, data } = query;
const requestBody = {
jsonrpc: '2.0',
method: 'eth_estimateGas',
params: [
{
from,
to,
data,
},
],
id: 1,
};
const response = await request.post(rpcUrl).send(requestBody).set('Content-Type', 'application/json');
if (!response.ok) {
throw new Error('could not estimate gas limit from RPC');
}
return response.body;
}
export function validateHederaAccountId(address: string): { valid: boolean; error: string | null } {
const parts = address.split('.');
if (parts.length !== 3) {
return {
valid: false,
error: 'Invalid Hedera Account ID format. Use format: 0.0.12345',
};
}
const [shardStr, realmStr, accountStr] = parts;
if (!shardStr || !realmStr || !accountStr) {
return {
valid: false,
error: 'Invalid Hedera Account ID. All parts are required.',
};
}
const shard = Number(shardStr);
const realm = Number(realmStr);
const account = Number(accountStr);
// Validate all parts are valid non-negative integers within safe range
if (
!Number.isInteger(shard) ||
!Number.isInteger(realm) ||
!Number.isInteger(account) ||
shard < 0 ||
realm < 0 ||
account < 0
) {
return {
valid: false,
error: 'Invalid Hedera Account ID. All parts must be non-negative integers.',
};
}
// Check for JavaScript safe integer limits (prevents precision loss)
if (!Number.isSafeInteger(shard) || !Number.isSafeInteger(realm) || !Number.isSafeInteger(account)) {
return {
valid: false,
error: 'Invalid Hedera Account ID. Values are too large.',
};
}
return {
valid: true,
error: null,
};
}