-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
util.ts
95 lines (83 loc) · 2.45 KB
/
util.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
import { sha256 } from '@ethersproject/sha2';
import { ZeroBytes32 } from '@fuel-ts/constants';
import type { Transaction } from '@fuel-ts/transactions';
import {
ReceiptType,
InputType,
OutputType,
TransactionType,
TransactionCoder,
} from '@fuel-ts/transactions';
import type { TransactionResultReceipt } from './transaction-response';
export const getSignableTransaction = (transaction: Transaction): Transaction => {
const signableTransaction = { ...transaction } as Transaction;
switch (signableTransaction.type) {
case TransactionType.Script: {
signableTransaction.receiptsRoot = ZeroBytes32;
break;
}
case TransactionType.Create: {
break;
}
default: {
throw new Error('Not implemented');
}
}
signableTransaction.inputs = signableTransaction.inputs.map((input) => {
if (input.type === InputType.Contract) {
return {
...input,
utxoID: {
transactionId: ZeroBytes32,
outputIndex: 0,
},
balanceRoot: ZeroBytes32,
stateRoot: ZeroBytes32,
};
}
return input;
});
signableTransaction.outputs = signableTransaction.outputs.map((output) => {
switch (output.type) {
case OutputType.Contract: {
return {
...output,
balanceRoot: ZeroBytes32,
stateRoot: ZeroBytes32,
};
}
case OutputType.Change: {
return {
...output,
amount: 0n,
};
}
case OutputType.Variable: {
return {
...output,
to: ZeroBytes32,
amount: 0n,
assetId: ZeroBytes32,
};
}
default: {
return output;
}
}
});
return signableTransaction;
};
export const getTransactionId = (transaction: Transaction): string => {
const signableTransaction = getSignableTransaction(transaction);
const encodedTransaction = new TransactionCoder().encode(signableTransaction);
return sha256(encodedTransaction);
};
export const calculatePriceWithFactor = (gasUsed: bigint, gasPrice: bigint, priceFactor: bigint) =>
BigInt(Math.ceil(Number(gasUsed) / Number(priceFactor))) * gasPrice;
export const getGasUsedFromReceipts = (receipts: Array<TransactionResultReceipt>): bigint => {
const scriptResult = receipts.find((receipt) => receipt.type === ReceiptType.ScriptResult);
if (scriptResult && scriptResult.type === ReceiptType.ScriptResult) {
return scriptResult.gasUsed;
}
return 0n;
};