-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathsdkClient.ts
421 lines (367 loc) · 17.2 KB
/
sdkClient.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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/*-
*
* Hedera JSON RPC Relay
*
* Copyright (C) 2022 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import {
AccountBalance,
AccountBalanceQuery,
AccountId, AccountInfoQuery,
Client,
ContractByteCodeQuery,
ContractCallQuery,
ExchangeRates,
FeeSchedules,
FileContentsQuery,
ContractId,
ContractFunctionResult,
TransactionResponse,
AccountInfo,
HbarUnit,
TransactionId,
FeeComponents,
Query,
Transaction,
TransactionRecord,
Status,
FileCreateTransaction,
FileAppendTransaction,
FileInfoQuery,
EthereumTransaction,
EthereumTransactionData,
} from '@hashgraph/sdk';
import { BigNumber } from '@hashgraph/sdk/lib/Transfer';
import { Logger } from "pino";
import { Gauge, Histogram, Registry } from 'prom-client';
import { formatRequestIdMessage } from '../../formatters';
import constants from './../constants';
import { SDKClientError } from './../errors/SDKClientError';
const _ = require('lodash');
export class SDKClient {
static transactionMode = 'TRANSACTION';
static queryMode = 'QUERY';
/**
* The client to use for connecting to the main consensus network. The account
* associated with this client will pay for all operations on the main network.
*
* @private
*/
private readonly clientMain: Client;
/**
* The logger used for logging all output from this class.
* @private
*/
private readonly logger: Logger;
/**
* The metrics register used for metrics tracking.
* @private
*/
private readonly register: Registry;
private consensusNodeClientHistorgram;
private operatorAccountGauge;
private operatorAccountId;
// populate with consensusnode requests via SDK
constructor(clientMain: Client, logger: Logger, register: Registry) {
this.clientMain = clientMain;
this.logger = logger;
this.register = register;
this.operatorAccountId = clientMain.operatorAccountId ? clientMain.operatorAccountId.toString() : 'UNKNOWN';
// clear and create metrics in registry
const metricHistogramName = 'rpc_relay_consensusnode_response';
register.removeSingleMetric(metricHistogramName);
this.consensusNodeClientHistorgram = new Histogram({
name: metricHistogramName,
help: 'Relay consensusnode mode type status cost histogram',
labelNames: ['mode', 'type', 'status', 'caller'],
registers: [register]
});
const metricGaugeName = 'rpc_relay_operator_balance';
register.removeSingleMetric(metricGaugeName);
this.operatorAccountGauge = new Gauge({
name: metricGaugeName,
help: 'Relay operator balance gauge',
labelNames: ['mode', 'type', 'accountId'],
registers: [register],
async collect() {
// Invoked when the registry collects its metrics' values.
// Allows for updated account balance tracking
try {
const accountBalance = await (new AccountBalanceQuery()
.setAccountId(clientMain.operatorAccountId!))
.execute(clientMain);
this.labels({ 'accountId': clientMain.operatorAccountId!.toString() })
.set(accountBalance.hbars.toTinybars().toNumber());
} catch (e: any) {
logger.error(e, `Error collecting operator balance. Skipping balance set`);
}
},
});
}
async getAccountBalance(account: string, callerName: string, requestId?: string): Promise<AccountBalance> {
return this.executeQuery(new AccountBalanceQuery()
.setAccountId(AccountId.fromString(account)), this.clientMain, callerName, requestId);
}
async getAccountBalanceInTinyBar(account: string, callerName: string, requestId?: string): Promise<BigNumber> {
const balance = await this.getAccountBalance(account, callerName, requestId);
return balance.hbars.to(HbarUnit.Tinybar);
}
async getAccountBalanceInWeiBar(account: string, callerName: string, requestId?: string): Promise<BigNumber> {
const balance = await this.getAccountBalance(account, callerName, requestId);
return SDKClient.HbarToWeiBar(balance);
}
async getAccountInfo(address: string, callerName: string, requestId?: string): Promise<AccountInfo> {
return this.executeQuery(new AccountInfoQuery()
.setAccountId(AccountId.fromString(address)), this.clientMain, callerName, requestId);
}
async getContractByteCode(shard: number | Long, realm: number | Long, address: string, callerName: string, requestId?: string): Promise<Uint8Array> {
return this.executeQuery(new ContractByteCodeQuery()
.setContractId(ContractId.fromEvmAddress(shard, realm, address)), this.clientMain, callerName, requestId);
}
async getContractBalance(contract: string, callerName: string, requestId?: string): Promise<AccountBalance> {
return this.executeQuery(new AccountBalanceQuery()
.setContractId(ContractId.fromString(contract)), this.clientMain, callerName, requestId);
}
async getContractBalanceInWeiBar(account: string, callerName: string, requestId?: string): Promise<BigNumber> {
const balance = await this.getContractBalance(account, callerName, requestId);
return SDKClient.HbarToWeiBar(balance);
}
async getExchangeRate(callerName: string, requestId?: string): Promise<ExchangeRates> {
const exchangeFileBytes = await this.getFileIdBytes(constants.EXCHANGE_RATE_FILE_ID, callerName, requestId);
return ExchangeRates.fromBytes(exchangeFileBytes);
}
async getFeeSchedule(callerName: string, requestId?: string): Promise<FeeSchedules> {
const feeSchedulesFileBytes = await this.getFileIdBytes(constants.FEE_SCHEDULE_FILE_ID, callerName, requestId);
return FeeSchedules.fromBytes(feeSchedulesFileBytes);
}
async getTinyBarGasFee(callerName: string, requestId?: string): Promise<number> {
const feeSchedules = await this.getFeeSchedule(callerName, requestId);
if (_.isNil(feeSchedules.current) || feeSchedules.current?.transactionFeeSchedule === undefined) {
throw new SDKClientError({}, 'Invalid FeeSchedules proto format');
}
for (const schedule of feeSchedules.current?.transactionFeeSchedule) {
if (schedule.hederaFunctionality?._code === constants.ETH_FUNCTIONALITY_CODE && schedule.fees !== undefined) {
// get exchange rate & convert to tiny bar
const exchangeRates = await this.getExchangeRate(callerName, requestId);
return this.convertGasPriceToTinyBars(schedule.fees[0].servicedata, exchangeRates);
}
}
throw new SDKClientError({}, `${constants.ETH_FUNCTIONALITY_CODE} code not found in feeSchedule`);
}
async getFileIdBytes(address: string, callerName: string, requestId?: string): Promise<Uint8Array> {
return this.executeQuery(new FileContentsQuery()
.setFileId(address), this.clientMain, callerName, requestId);
}
async getRecord(transactionResponse: TransactionResponse) {
return transactionResponse.getRecord(this.clientMain);
}
async submitEthereumTransaction(transactionBuffer: Uint8Array, callerName: string, requestId?: string): Promise<TransactionResponse> {
const ethereumTransactionData: EthereumTransactionData = EthereumTransactionData.fromBytes(transactionBuffer);
const ethereumTransaction = new EthereumTransaction();
if (ethereumTransactionData.toBytes().length <= 5120) {
ethereumTransaction.setEthereumData(ethereumTransactionData.toBytes());
} else {
const fileId = await this.createFile(ethereumTransactionData.callData, this.clientMain, requestId);
if(!fileId) {
const requestIdPrefix = formatRequestIdMessage(requestId);
throw new SDKClientError({}, `${requestIdPrefix} No fileId created for transaction. `);
}
ethereumTransactionData.callData = new Uint8Array();
ethereumTransaction.setEthereumData(ethereumTransactionData.toBytes()).setCallDataFileId(fileId)
}
return this.executeTransaction(ethereumTransaction, callerName, requestId);
}
async submitContractCallQuery(to: string, data: string, gas: number, from: string, callerName: string, requestId?: string): Promise<ContractFunctionResult> {
const contract = SDKClient.prune0x(to);
const contractId = contract.startsWith("00000000000")
? ContractId.fromSolidityAddress(contract)
: ContractId.fromEvmAddress(0, 0, contract);
const contractCallQuery = new ContractCallQuery()
.setContractId(contractId)
.setGas(gas);
// data is optional and can be omitted in which case fallback function will be employed
if (data) {
contractCallQuery.setFunctionParameters(Buffer.from(SDKClient.prune0x(data), 'hex'));
}
if (from) {
contractCallQuery.setSenderAccountId(AccountId.fromEvmAddress(0,0, from))
}
if (this.clientMain.operatorAccountId !== null) {
contractCallQuery
.setPaymentTransactionId(TransactionId.generate(this.clientMain.operatorAccountId));
}
const cost = await contractCallQuery
.getCost(this.clientMain);
return this.executeQuery(contractCallQuery
.setQueryPayment(cost), this.clientMain, callerName, requestId);
}
private convertGasPriceToTinyBars = (feeComponents: FeeComponents | undefined, exchangeRates: ExchangeRates) => {
// gas -> tinCents: gas / 1000
// tinCents -> tinyBars: tinCents * exchangeRate (hbarEquiv/ centsEquiv)
if (feeComponents === undefined || feeComponents.contractTransactionGas === undefined) {
return constants.DEFAULT_TINY_BAR_GAS;
}
return Math.ceil(
(feeComponents.contractTransactionGas.toNumber() / 1_000) * (exchangeRates.currentRate.hbars / exchangeRates.currentRate.cents)
);
};
private executeQuery = async (query: Query<any>, client: Client, callerName: string, requestId?: string) => {
const requestIdPrefix = formatRequestIdMessage(requestId);
try {
const resp = await query.execute(client);
this.logger.info(`${requestIdPrefix} Consensus Node query response: ${query.constructor.name} ${Status.Success._code}`);
// local free queries will have a '0.0.0' accountId on transactionId
this.logger.trace(`${requestIdPrefix} ${query.paymentTransactionId} ${callerName} query cost: ${query._queryPayment}`);
this.captureMetrics(
SDKClient.queryMode,
query.constructor.name,
Status.Success,
query._queryPayment?.toTinybars().toNumber(),
callerName);
return resp;
}
catch (e: any) {
const sdkClientError = new SDKClientError(e);
this.logger.debug(`${requestIdPrefix} Consensus Node query response: ${query.constructor.name} ${sdkClientError.status}`);
this.captureMetrics(
SDKClient.queryMode,
query.constructor.name,
sdkClientError.status,
query._queryPayment?.toTinybars().toNumber(),
callerName);
this.logger.trace(`${requestIdPrefix} ${query.paymentTransactionId} ${callerName} query cost: ${query._queryPayment}`);
throw sdkClientError;
}
};
private executeTransaction = async (transaction: Transaction, callerName: string, requestId?: string): Promise<TransactionResponse> => {
const transactionType = transaction.constructor.name;
const requestIdPrefix = formatRequestIdMessage(requestId);
try {
this.logger.info(`${requestIdPrefix} Execute ${transactionType} transaction`);
const resp = await transaction.execute(this.clientMain);
this.logger.info(`${requestIdPrefix} Consensus Node ${transactionType} transaction response: ${resp.transactionId.toString()} ${Status.Success._code}`);
return resp;
}
catch (e: any) {
const sdkClientError = new SDKClientError(e);
this.logger.info(`${requestIdPrefix} Consensus Node ${transactionType} transaction response: ${sdkClientError.status}`);
this.captureMetrics(
SDKClient.transactionMode,
transactionType,
sdkClientError.status,
0,
callerName);
throw sdkClientError;
}
};
executeGetTransactionRecord = async (resp: TransactionResponse, transactionName: string, callerName: string, requestId?: string): Promise<TransactionRecord> => {
const requestIdPrefix = formatRequestIdMessage(requestId);
try {
if (!resp.getRecord) {
throw new SDKClientError({}, `${requestIdPrefix} Invalid response format, expected record availability: ${JSON.stringify(resp)}`);
}
const transactionRecord: TransactionRecord = await resp.getRecord(this.clientMain);
this.logger.trace(`${requestIdPrefix} ${resp.transactionId.toString()} ${callerName} transaction cost: ${transactionRecord.transactionFee}`);
this.captureMetrics(
SDKClient.transactionMode,
transactionName,
transactionRecord.receipt.status,
transactionRecord.transactionFee.toTinybars().toNumber(),
callerName);
return transactionRecord;
}
catch (e: any) {
// capture sdk record retrieval errors and shorten familiar stack trace
const sdkClientError = new SDKClientError(e);
if(sdkClientError.isValidNetworkError()) {
this.captureMetrics(
SDKClient.transactionMode,
transactionName,
sdkClientError.status,
0,
callerName);
}
throw sdkClientError;
}
};
private captureMetrics = (mode, type, status, cost, caller) => {
const resolvedCost = cost ? cost : 0;
this.consensusNodeClientHistorgram.labels(
mode,
type,
status,
caller)
.observe(resolvedCost);
this.operatorAccountGauge.labels(mode, type, this.operatorAccountId).dec(resolvedCost);
};
/**
* Internal helper method that removes the leading 0x if there is one.
* @param input
* @private
*/
private static prune0x(input: string): string {
return input.startsWith('0x')
? input.substring(2)
: input;
}
private static HbarToWeiBar(balance: AccountBalance): BigNumber {
return balance.hbars
.to(HbarUnit.Tinybar)
.multipliedBy(constants.TINYBAR_TO_WEIBAR_COEF);
}
private createFile = async (callData: Uint8Array, client: Client, requestId?: string) => {
const requestIdPrefix = formatRequestIdMessage(requestId);
const hexedCallData = Buffer.from(callData).toString("hex");
const fileId = (
(
await (
await new FileCreateTransaction()
.setContents(hexedCallData.substring(0, 4096))
.setKeys(
client.operatorPublicKey
? [client.operatorPublicKey]
: []
)
.execute(client)
).getReceipt(client)
).fileId
);
if (fileId && callData.length > 4096) {
await (
await new FileAppendTransaction()
.setFileId(fileId)
.setContents(
hexedCallData.substring(4096, hexedCallData.length)
)
.setChunkSize(4096)
.execute(client)
).getReceipt(client);
}
// Ensure that the calldata file is not empty
if(fileId) {
const fileSize = await (
await new FileInfoQuery()
.setFileId(fileId)
.execute(client)
).size;
if(callData.length > 0 && fileSize.isZero()) {
throw new SDKClientError({}, `${requestIdPrefix} Created file is empty. `);
}
this.logger.trace(`${requestIdPrefix} Created file with fileId: ${fileId} and file size ${fileSize}`);
}
return fileId;
}
}