-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
provider.ts
616 lines (557 loc) · 17.2 KB
/
provider.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import type { BytesLike } from '@ethersproject/bytes';
import { arrayify, hexlify } from '@ethersproject/bytes';
import type { Network } from '@ethersproject/networks';
import type { InputValue } from '@fuel-ts/abi-coder';
import { AbiCoder } from '@fuel-ts/abi-coder';
import { NativeAssetId } from '@fuel-ts/constants';
import type { AbstractAddress, AbstractPredicate } from '@fuel-ts/interfaces';
import type { BigNumberish } from '@fuel-ts/math';
import { max, multiply } from '@fuel-ts/math';
import type { Transaction } from '@fuel-ts/transactions';
import {
GAS_PRICE_FACTOR,
MAX_GAS_PER_TX,
ReceiptType,
ReceiptCoder,
TransactionCoder,
} from '@fuel-ts/transactions';
import { GraphQLClient } from 'graphql-request';
import cloneDeep from 'lodash.clonedeep';
import type {
GqlChainInfoFragmentFragment,
GqlGetInfoQuery,
GqlReceiptFragmentFragment,
} from './__generated__/operations';
import { getSdk as getOperationsSdk } from './__generated__/operations';
import type { Coin } from './coin';
import type { CoinQuantity, CoinQuantityLike } from './coin-quantity';
import { coinQuantityfy } from './coin-quantity';
import { ScriptTransactionRequest, transactionRequestify } from './transaction-request';
import type { TransactionRequestLike } from './transaction-request';
import type {
TransactionResult,
TransactionResultReceipt,
} from './transaction-response/transaction-response';
import { TransactionResponse } from './transaction-response/transaction-response';
import { calculatePriceWithFactor, getGasUsedFromReceipts } from './util';
export type CallResult = {
receipts: TransactionResultReceipt[];
};
/**
* A Fuel block
*/
export type Block = {
id: string;
height: bigint;
time: string;
producer: string;
transactionIds: string[];
};
/**
* Deployed Contract bytecode and contract id
*/
export type ContractResult = {
id: string;
bytecode: string;
};
/**
* Chain information
*/
export type ChainInfo = {
name: string;
baseChainHeight: bigint;
peerCount: number;
consensusParameters: {
gasPriceFactor: bigint;
maxGasPerTx: bigint;
maxScriptLength: bigint;
};
latestBlock: {
id: string;
height: bigint;
producer: string;
time: string;
transactions: Array<{ id: string }>;
};
};
/**
* Node information
*/
export type NodeInfo = {
minBytePrice: bigint;
minGasPrice: bigint;
nodeVersion: string;
};
export type TransactionCost = {
minGasPrice: bigint;
minBytePrice: bigint;
gasPrice: bigint;
bytePrice: bigint;
byteSize: bigint;
gasUsed: bigint;
fee: bigint;
};
const processGqlReceipt = (gqlReceipt: GqlReceiptFragmentFragment): TransactionResultReceipt => {
const receipt = new ReceiptCoder().decode(arrayify(gqlReceipt.rawPayload), 0)[0];
switch (receipt.type) {
case ReceiptType.ReturnData: {
return {
...receipt,
data: gqlReceipt.data!,
};
}
case ReceiptType.LogData: {
return {
...receipt,
data: gqlReceipt.data!,
};
}
default:
return receipt;
}
};
const processGqlChain = (chain: GqlChainInfoFragmentFragment): ChainInfo => ({
name: chain.name,
baseChainHeight: BigInt(chain.baseChainHeight),
peerCount: chain.peerCount,
consensusParameters: {
gasPriceFactor: BigInt(chain.consensusParameters.gasPriceFactor),
maxGasPerTx: BigInt(chain.consensusParameters.maxGasPerTx),
maxScriptLength: BigInt(chain.consensusParameters.maxScriptLength),
},
latestBlock: {
id: chain.latestBlock.id,
height: BigInt(chain.latestBlock.height),
producer: chain.latestBlock.producer,
time: chain.latestBlock.time,
transactions: chain.latestBlock.transactions.map((i) => ({
id: i.id,
})),
},
});
const processNodeInfo = (nodeInfo: GqlGetInfoQuery['nodeInfo']) => ({
minBytePrice: BigInt(nodeInfo.minBytePrice),
minGasPrice: BigInt(nodeInfo.minGasPrice),
nodeVersion: nodeInfo.nodeVersion,
});
/**
* Cursor pagination arguments
*
* https://relay.dev/graphql/connections.htm#sec-Arguments
*/
export type CursorPaginationArgs = {
/** Forward pagination limit */
first?: number | null;
/** Forward pagination cursor */
after?: string | null;
/** Backward pagination limit */
last?: number | null;
/** Backward pagination cursor */
before?: string | null;
};
export type BuildPredicateOptions = {
fundTransaction?: boolean;
} & Pick<TransactionRequestLike, 'gasLimit' | 'gasPrice' | 'bytePrice' | 'maturity'>;
/**
* Provider Call transaction params
*/
export type ProviderCallParams = {
utxoValidation?: boolean;
};
/**
* A provider for connecting to a Fuel node
*/
export default class Provider {
operations: ReturnType<typeof getOperationsSdk>;
constructor(
/** GraphQL endpoint of the Fuel node */
public url: string
) {
const gqlClient = new GraphQLClient(url);
this.operations = getOperationsSdk(gqlClient);
}
/**
* Returns the version of the connected Fuel node
*/
async getVersion(): Promise<string> {
const {
nodeInfo: { nodeVersion },
} = await this.operations.getVersion();
return nodeVersion;
}
/**
* Returns the network configuration of the connected Fuel node
*/
async getNetwork(): Promise<Network> {
return {
name: 'fuelv2',
chainId: 0xdeadbeef,
};
}
/**
* Returns the current block number
*/
async getBlockNumber(): Promise<bigint> {
const { chain } = await this.operations.getChain();
return BigInt(chain.latestBlock.height);
}
/**
* Returns node information
*/
async getNodeInfo(): Promise<NodeInfo> {
const { nodeInfo } = await this.operations.getInfo();
return processNodeInfo(nodeInfo);
}
/**
* Returns chain information
*/
async getChain(): Promise<ChainInfo> {
const { chain } = await this.operations.getChain();
return processGqlChain(chain);
}
/**
* Submits a transaction to the chain to be executed
*/
async sendTransaction(
transactionRequestLike: TransactionRequestLike
): Promise<TransactionResponse> {
const transactionRequest = transactionRequestify(transactionRequestLike);
const encodedTransaction = hexlify(transactionRequest.toTransactionBytes());
const { gasUsed, minGasPrice, minBytePrice } = await this.getTransactionCost(
transactionRequest,
0
);
// Fail transaction before submit to avoid submit failure
// Resulting in lost of funds on a OutOfGas situation.
if (gasUsed > transactionRequest.gasLimit) {
throw new Error(
`gasLimit(${transactionRequest.gasLimit}) is lower than the required (${gasUsed})`
);
} else if (minGasPrice > transactionRequest.gasPrice) {
throw new Error(
`gasPrice(${transactionRequest.gasPrice}) is lower than the required ${minGasPrice}`
);
} else if (minBytePrice > transactionRequest.bytePrice) {
throw new Error(
`bytePrice(${transactionRequest.bytePrice}) is lower than the required ${minBytePrice}`
);
}
const {
submit: { id: transactionId },
} = await this.operations.submit({ encodedTransaction });
const response = new TransactionResponse(transactionId, transactionRequest, this);
return response;
}
/**
* Executes a transaction without actually submitting it to the chain
*/
async call(
transactionRequestLike: TransactionRequestLike,
{ utxoValidation }: ProviderCallParams = {}
): Promise<CallResult> {
const transactionRequest = transactionRequestify(transactionRequestLike);
const encodedTransaction = hexlify(transactionRequest.toTransactionBytes());
const { dryRun: gqlReceipts } = await this.operations.dryRun({
encodedTransaction,
utxoValidation: utxoValidation || false,
});
const receipts = gqlReceipts.map(processGqlReceipt);
return {
receipts,
};
}
/**
* Returns a transaction cost to enable user
* to set gasLimit and also reserve balance amounts
* on the the transaction.
*
* The tolerance is add on top of the gasUsed calculated
* from the node, this create a safe margin costs like
* change states on transfer that don't occur on the dryRun
* transaction. The default value is 0.2 or 20%
*/
async getTransactionCost(
transactionRequestLike: TransactionRequestLike,
tolerance: number = 0.2
): Promise<TransactionCost> {
const transactionRequest = transactionRequestify(cloneDeep(transactionRequestLike));
const { minBytePrice, minGasPrice } = await this.getNodeInfo();
const gasPrice = max(transactionRequest.gasPrice, minGasPrice);
const bytePrice = max(transactionRequest.bytePrice, minBytePrice);
const margin = 1 + tolerance;
// Set gasLimit to the maximum of the chain
// and bytePrice and gasPrice to 0 for measure
// Transaction without arrive to OutOfGas
transactionRequest.gasLimit = MAX_GAS_PER_TX;
transactionRequest.bytePrice = 0n;
transactionRequest.gasPrice = 0n;
// Execute dryRun not validated transaction to query gasUsed
const { receipts } = await this.call(transactionRequest);
const gasUsed = multiply(getGasUsedFromReceipts(receipts), margin);
const byteSize = transactionRequest.chargeableByteSize();
const gasFee = calculatePriceWithFactor(gasUsed, gasPrice, GAS_PRICE_FACTOR);
const byteFee = calculatePriceWithFactor(byteSize, bytePrice, GAS_PRICE_FACTOR);
return {
minGasPrice,
minBytePrice,
bytePrice,
gasPrice,
gasUsed,
byteSize,
fee: byteFee + gasFee,
};
}
/**
* Returns coins for the given owner
*/
async getCoins(
/** The address to get coins for */
owner: AbstractAddress,
/** The asset ID of coins to get */
assetId?: BytesLike,
/** Pagination arguments */
paginationArgs?: CursorPaginationArgs
): Promise<Coin[]> {
const result = await this.operations.getCoins({
first: 10,
...paginationArgs,
filter: { owner: owner.toB256(), assetId: assetId && hexlify(assetId) },
});
const coins = result.coins.edges!.map((edge) => edge!.node!);
return coins.map((coin) => ({
id: coin.utxoId,
assetId: coin.assetId,
amount: BigInt(coin.amount),
owner: coin.owner,
status: coin.status,
maturity: BigInt(coin.maturity),
blockCreated: BigInt(coin.blockCreated),
}));
}
/**
* Returns coins for the given owner satisfying the spend query
*/
async getCoinsToSpend(
/** The address to get coins for */
owner: AbstractAddress,
/** The quantitites to get */
quantities: CoinQuantityLike[],
/** Maximum number of coins to return */
maxInputs?: number
): Promise<Coin[]> {
const result = await this.operations.getCoinsToSpend({
owner: owner.toB256(),
spendQuery: quantities.map(coinQuantityfy).map((quantity) => ({
assetId: hexlify(quantity.assetId),
amount: quantity.amount.toString(),
})),
maxInputs,
});
const coins = result.coinsToSpend;
return coins.map((coin) => ({
id: coin.utxoId,
status: coin.status,
assetId: coin.assetId,
amount: BigInt(coin.amount),
owner: coin.owner,
maturity: BigInt(coin.maturity),
blockCreated: BigInt(coin.blockCreated),
}));
}
/**
* Returns block matching the given ID or type
*/
async getBlock(
/** ID or height of the block */
idOrHeight: string | number | 'latest'
): Promise<Block | null> {
let variables;
if (typeof idOrHeight === 'number') {
variables = { blockHeight: BigInt(idOrHeight).toString() };
} else if (idOrHeight === 'latest') {
variables = { blockHeight: (await this.getBlockNumber()).toString() };
} else {
variables = { blockId: idOrHeight };
}
const { block } = await this.operations.getBlock(variables);
if (!block) {
return null;
}
return {
id: block.id,
height: BigInt(block.height),
time: block.time,
producer: block.producer,
transactionIds: block.transactions.map((tx) => tx.id),
};
}
/**
* Returns block matching the given ID or type, including transaction data
*/
async getBlockWithTransactions(
/** ID or height of the block */
idOrHeight: string | number | 'latest'
): Promise<(Block & { transactions: Transaction[] }) | null> {
let variables;
if (typeof idOrHeight === 'number') {
variables = { blockHeight: BigInt(idOrHeight).toString() };
} else if (idOrHeight === 'latest') {
variables = { blockHeight: (await this.getBlockNumber()).toString() };
} else {
variables = { blockId: idOrHeight };
}
const { block } = await this.operations.getBlockWithTransactions(variables);
if (!block) {
return null;
}
return {
id: block.id,
height: BigInt(block.height),
time: block.time,
producer: block.producer,
transactionIds: block.transactions.map((tx) => tx.id),
transactions: block.transactions.map(
(tx) => new TransactionCoder().decode(arrayify(tx.rawPayload), 0)?.[0]
),
};
}
/**
* Get transaction with the given ID
*/
async getTransaction(transactionId: string): Promise<Transaction | null> {
const { transaction } = await this.operations.getTransaction({ transactionId });
if (!transaction) {
return null;
}
return new TransactionCoder().decode(arrayify(transaction.rawPayload), 0)?.[0];
}
/**
* Get deployed contract with the given ID
*
* @returns contract bytecode and contract id
*/
async getContract(contractId: string): Promise<ContractResult | null> {
const { contract } = await this.operations.getContract({ contractId });
if (!contract) {
return null;
}
return contract;
}
/**
* Returns the balance for the given owner for the given asset ID
*/
async getBalance(
/** The address to get coins for */
owner: AbstractAddress,
/** The asset ID of coins to get */
assetId: BytesLike
): Promise<bigint> {
const { balance } = await this.operations.getBalance({
owner: owner.toB256(),
assetId: hexlify(assetId),
});
return BigInt(balance.amount);
}
/**
* Returns balances for the given owner
*/
async getBalances(
/** The address to get coins for */
owner: AbstractAddress,
/** Pagination arguments */
paginationArgs?: CursorPaginationArgs
): Promise<CoinQuantity[]> {
const result = await this.operations.getBalances({
first: 10,
...paginationArgs,
filter: { owner: owner.toB256() },
});
const balances = result.balances.edges!.map((edge) => edge!.node!);
return balances.map((balance) => ({
assetId: balance.assetId,
amount: BigInt(balance.amount),
}));
}
async buildSpendPredicate(
predicate: AbstractPredicate,
amountToSpend: BigNumberish,
receiverAddress: AbstractAddress,
predicateData?: InputValue[],
assetId: BytesLike = NativeAssetId,
predicateOptions?: BuildPredicateOptions,
walletAddress?: AbstractAddress
): Promise<ScriptTransactionRequest> {
const predicateCoins: Coin[] = await this.getCoinsToSpend(predicate.address, [
[amountToSpend, assetId],
]);
const options = {
fundTransaction: true,
...predicateOptions,
};
const request = new ScriptTransactionRequest({
gasLimit: MAX_GAS_PER_TX,
...options,
});
let encoded: undefined | Uint8Array;
if (predicateData && predicate.types) {
const abiCoder = new AbiCoder();
encoded = abiCoder.encode(predicate.types, predicateData);
}
let totalInPredicate = 0n;
predicateCoins.forEach((coin: Coin) => {
totalInPredicate += coin.amount;
request.addCoin({
...coin,
predicate: predicate.bytes,
predicateData: encoded,
} as Coin);
request.outputs = [];
});
// output sent to receiver
request.addCoinOutput(receiverAddress, totalInPredicate, assetId);
const requiredCoinQuantities: CoinQuantityLike[] = [];
if (options.fundTransaction) {
requiredCoinQuantities.push(request.calculateFee());
}
if (requiredCoinQuantities.length && walletAddress) {
const coins = await this.getCoinsToSpend(walletAddress, requiredCoinQuantities);
request.addCoins(coins);
}
return request;
}
async submitSpendPredicate(
predicate: AbstractPredicate,
amountToSpend: BigNumberish,
receiverAddress: AbstractAddress,
predicateData?: InputValue[],
assetId: BytesLike = NativeAssetId,
options?: BuildPredicateOptions,
walletAddress?: AbstractAddress
): Promise<TransactionResult<'success'>> {
const request = await this.buildSpendPredicate(
predicate,
amountToSpend,
receiverAddress,
predicateData,
assetId,
options,
walletAddress
);
try {
const response = await this.sendTransaction(request);
return await response.waitForResult();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
const errors: { message: string }[] = error?.response?.errors || [];
if (
errors.some(({ message }) =>
message.includes('unexpected block execution error TransactionValidity(InvalidPredicate')
)
) {
throw new Error('Invalid Predicate');
}
throw error;
}
}
}