-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathtransaction-request.ts
556 lines (493 loc) · 15.8 KB
/
transaction-request.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
/* eslint-disable max-classes-per-file */
import type { BytesLike } from '@ethersproject/bytes';
import { arrayify, hexlify } from '@ethersproject/bytes';
import { addressify, Address } from '@fuel-ts/address';
import { NativeAssetId, ZeroBytes32 } from '@fuel-ts/constants';
import type {
AddressLike,
AbstractAddress,
ContractIdLike,
AbstractScript,
} from '@fuel-ts/interfaces';
import type { BigNumberish } from '@fuel-ts/math';
import { bn, toHex } from '@fuel-ts/math';
import type { Transaction } from '@fuel-ts/transactions';
import {
TransactionType,
TransactionCoder,
InputType,
OutputType,
GAS_PRICE_FACTOR,
} from '@fuel-ts/transactions';
import type { Coin } from '../coin';
import type { CoinQuantity, CoinQuantityLike } from '../coin-quantity';
import { coinQuantityfy } from '../coin-quantity';
import { calculatePriceWithFactor } from '../util';
import type {
CoinTransactionRequestOutput,
ContractCreatedTransactionRequestOutput,
ContractTransactionRequestOutput,
VariableTransactionRequestOutput,
} from '.';
import type {
TransactionRequestInput,
CoinTransactionRequestInput,
ContractTransactionRequestInput,
} from './input';
import { inputify } from './input';
import type { TransactionRequestOutput, ChangeTransactionRequestOutput } from './output';
import { outputify } from './output';
import type { TransactionRequestStorageSlot } from './storage-slot';
import { storageSlotify } from './storage-slot';
import type { TransactionRequestWitness } from './witness';
import { witnessify } from './witness';
export { TransactionType };
// We can't import this from `@fuel-ts/script` because it causes
// cyclic dependency errors so we duplicate it here.
export const returnZeroScript: AbstractScript<void> = {
/*
Opcode::RET(REG_ZERO)
Opcode::NOOP
*/
// TODO: Don't use hardcoded scripts: https://github.com/FuelLabs/fuels-ts/issues/281
bytes: arrayify('0x24000000'),
encodeScriptData: () => new Uint8Array(0),
};
interface BaseTransactionRequestLike {
/** Gas price for transaction */
gasPrice?: BigNumberish;
/** Gas limit for transaction */
gasLimit?: BigNumberish;
/** Price per transaction byte */
bytePrice?: BigNumberish;
/** Block until which tx cannot be included */
maturity?: BigNumberish;
/** List of inputs */
inputs?: TransactionRequestInput[];
/** List of outputs */
outputs?: TransactionRequestOutput[];
/** List of witnesses */
witnesses?: TransactionRequestWitness[];
}
export class ChangeOutputCollisionError extends Error {
name = 'ChangeOutputCollisionError';
message = 'A ChangeOutput with the same "assetId" already exists for a different "to" address';
}
export class NoWitnessAtIndexError extends Error {
name = 'NoWitnessAtIndexError';
constructor(public readonly index: number) {
super();
this.message = `Witness at index "${index}" was not found`;
}
}
export class NoWitnessByOwnerError extends Error {
name = 'NoWitnessByOwnerError';
constructor(public readonly owner: AbstractAddress) {
super();
this.message = `A witness for the given owner "${owner}" was not found`;
}
}
/**
* The provider required at least 1 native coin
* even if the gasPrice and bytePrice are 0
*/
export const MIN_TRANSACTION_AMOUNT = 1n;
abstract class BaseTransactionRequest implements BaseTransactionRequestLike {
/** Type of the transaction */
abstract type: TransactionType;
/** Gas price for transaction */
gasPrice: string;
/** Gas limit for transaction */
gasLimit: string;
/** Price per transaction byte */
bytePrice: string;
/** Block until which tx cannot be included */
maturity: string;
/** List of inputs */
inputs: TransactionRequestInput[] = [];
/** List of outputs */
outputs: TransactionRequestOutput[] = [];
/** List of witnesses */
witnesses: TransactionRequestWitness[] = [];
constructor({
gasPrice,
gasLimit,
bytePrice,
maturity,
inputs,
outputs,
witnesses,
}: BaseTransactionRequestLike = {}) {
this.gasPrice = toHex(gasPrice ?? 0);
this.gasLimit = toHex(gasLimit ?? 0);
this.bytePrice = toHex(bytePrice ?? 0);
this.maturity = toHex(maturity ?? 0);
this.inputs = [...(inputs ?? [])];
this.outputs = [...(outputs ?? [])];
this.witnesses = [...(witnesses ?? [])];
}
protected getBaseTransaction(): Pick<
Transaction,
keyof BaseTransactionRequestLike | 'inputsCount' | 'outputsCount' | 'witnessesCount'
> {
const inputs = this.inputs?.map(inputify) ?? [];
const outputs = this.outputs?.map(outputify) ?? [];
const witnesses = this.witnesses?.map(witnessify) ?? [];
return {
gasPrice: this.gasPrice,
gasLimit: this.gasLimit,
bytePrice: this.bytePrice,
maturity: this.maturity,
inputs,
outputs,
witnesses,
inputsCount: inputs.length,
outputsCount: outputs.length,
witnessesCount: witnesses.length,
};
}
abstract toTransaction(): Transaction;
toTransactionBytes(): Uint8Array {
return new TransactionCoder().encode(this.toTransaction());
}
/**
* Pushes an input to the list without any side effects and returns the index
*/
protected pushInput(input: TransactionRequestInput): number {
this.inputs.push(input);
return this.inputs.length - 1;
}
/**
* Pushes an output to the list without any side effects and returns the index
*/
protected pushOutput(output: TransactionRequestOutput): number {
this.outputs.push(output);
return this.outputs.length - 1;
}
/**
* Creates an empty witness without any side effects and returns the index
*/
protected createWitness() {
this.witnesses.push('0x');
return this.witnesses.length - 1;
}
/**
* Updates an existing witness without any side effects
*/
updateWitness(index: number, witness: TransactionRequestWitness) {
if (!this.witnesses[index]) {
throw new NoWitnessAtIndexError(index);
}
this.witnesses[index] = witness;
}
getCoinInputs(): CoinTransactionRequestInput[] {
return this.inputs.filter(
(input): input is CoinTransactionRequestInput => input.type === InputType.Coin
);
}
getCoinOutputs(): CoinTransactionRequestOutput[] {
return this.outputs.filter(
(output): output is CoinTransactionRequestOutput => output.type === OutputType.Coin
);
}
getChangeOutputs(): ChangeTransactionRequestOutput[] {
return this.outputs.filter(
(output): output is ChangeTransactionRequestOutput => output.type === OutputType.Change
);
}
/**
* Returns the witnessIndex of the found CoinInput
*/
getCoinInputWitnessIndexByOwner(owner: AddressLike): number | null {
const ownerAddress = addressify(owner);
return (
this.inputs.find(
(input): input is CoinTransactionRequestInput =>
input.type === InputType.Coin && input.owner === ownerAddress.toB256()
)?.witnessIndex ?? null
);
}
/**
* Updates the witness for the given CoinInput owner
*/
updateWitnessByCoinInputOwner(owner: AddressLike, witness: BytesLike) {
const witnessIndex = this.getCoinInputWitnessIndexByOwner(owner);
if (!witnessIndex) {
throw new NoWitnessByOwnerError(addressify(owner));
}
this.updateWitness(witnessIndex, witness);
}
/**
* Converts the given Coin to a CoinInput with the appropriate witnessIndex and pushes it
*/
addCoin(coin: Coin) {
let witnessIndex = this.getCoinInputWitnessIndexByOwner(Address.fromB256(coin.owner));
// Insert a dummy witness if no witness exists
if (typeof witnessIndex !== 'number') {
witnessIndex = this.createWitness();
}
// Insert the CoinInput
this.pushInput({
type: InputType.Coin,
...coin,
witnessIndex,
});
// Find the ChangeOutput for the AssetId of the Coin
const changeOutput = this.getChangeOutputs().find(
(output) => hexlify(output.assetId) === coin.assetId
);
// Throw if the existing ChangeOutput is not for the same owner
if (changeOutput && hexlify(changeOutput.to) !== coin.owner) {
throw new ChangeOutputCollisionError();
}
// Insert a ChangeOutput if it does not exist
if (!changeOutput) {
this.pushOutput({
type: OutputType.Change,
to: coin.owner,
assetId: coin.assetId,
});
}
}
addCoins(coins: ReadonlyArray<Coin>) {
coins.forEach((coin) => this.addCoin(coin));
}
addCoinOutput(
/** Address of the destination */
to: AddressLike,
/** Amount of coins */
amount: BigNumberish,
/** Asset ID of coins */
assetId: BytesLike = NativeAssetId
) {
this.pushOutput({
type: OutputType.Coin,
to: addressify(to).toB256(),
amount,
assetId,
});
}
addCoinOutputs(
/** Address of the destination */
to: AddressLike,
/** Quantities of coins */
quantities: CoinQuantityLike[]
) {
quantities.map(coinQuantityfy).forEach((quantity) => {
this.pushOutput({
type: OutputType.Coin,
to: addressify(to).toB256(),
amount: quantity.amount,
assetId: quantity.assetId,
});
});
}
byteSize() {
return this.toTransactionBytes().length;
}
chargeableByteSize() {
const witnessSize = this.witnesses.reduce((total, w) => total + arrayify(w).length, 0);
return toHex(this.toTransactionBytes().length - witnessSize);
}
/**
* Return the minimum amount in native coins required to create
* a transaction.
*
* Note: this is required even if the gasPrice and bytePrice
* are set to zero.
*/
calculateFee(): CoinQuantity {
const gasFee = bn(calculatePriceWithFactor(this.gasLimit, this.gasPrice, GAS_PRICE_FACTOR));
const byteFee = bn(
calculatePriceWithFactor(this.chargeableByteSize(), this.bytePrice, GAS_PRICE_FACTOR)
);
const totalFee = gasFee.add(byteFee.isZero() ? bn(1) : byteFee);
return {
assetId: NativeAssetId,
amount: toHex(totalFee),
};
}
}
export interface ScriptTransactionRequestLike extends BaseTransactionRequestLike {
/** Script to execute */
script?: BytesLike;
/** Script input data (parameters) */
scriptData?: BytesLike;
}
export class ScriptTransactionRequest extends BaseTransactionRequest {
static from(obj: ScriptTransactionRequestLike) {
if (obj instanceof this) {
return obj;
}
return new this(obj);
}
/** Type of the transaction */
type = TransactionType.Script as const;
/** Script to execute */
script: Uint8Array;
/** Script input data (parameters) */
scriptData: Uint8Array;
constructor({ script, scriptData, ...rest }: ScriptTransactionRequestLike = {}) {
super(rest);
this.script = arrayify(script ?? returnZeroScript.bytes);
this.scriptData = arrayify(scriptData ?? returnZeroScript.encodeScriptData());
}
toTransaction(): Transaction {
const script = arrayify(this.script ?? '0x');
const scriptData = arrayify(this.scriptData ?? '0x');
return {
type: TransactionType.Script,
...super.getBaseTransaction(),
scriptLength: script.length,
scriptDataLength: scriptData.length,
receiptsRoot: ZeroBytes32,
script: hexlify(script),
scriptData: hexlify(scriptData),
};
}
getContractInputs(): ContractTransactionRequestInput[] {
return this.inputs.filter(
(input): input is ContractTransactionRequestInput => input.type === InputType.Contract
);
}
getContractOutputs(): ContractTransactionRequestOutput[] {
return this.outputs.filter(
(output): output is ContractTransactionRequestOutput => output.type === OutputType.Contract
);
}
getVariableOutputs(): VariableTransactionRequestOutput[] {
return this.outputs.filter(
(output): output is VariableTransactionRequestOutput => output.type === OutputType.Variable
);
}
setScript<T>(script: AbstractScript<T>, data: T) {
this.script = script.bytes;
this.scriptData = script.encodeScriptData(data);
}
addVariableOutputs(numberOfVariables: number = 1) {
let outputsNumber = numberOfVariables;
while (outputsNumber) {
this.pushOutput({
type: OutputType.Variable,
});
outputsNumber -= 1;
}
return this.outputs.length - 1;
}
addContract(contract: ContractIdLike) {
const contractAddress = addressify(contract);
// Add only one input contract per contractId
if (this.getContractInputs().find((i) => i.contractId === contractAddress.toB256())) {
return;
}
const inputIndex = super.pushInput({
type: InputType.Contract,
contractId: contractAddress.toB256(),
});
this.pushOutput({
type: OutputType.Contract,
inputIndex,
});
}
}
export interface CreateTransactionRequestLike extends BaseTransactionRequestLike {
/** Witness index of contract bytecode to create */
bytecodeWitnessIndex?: number;
/** Salt */
salt?: BytesLike;
/** List of static contracts */
staticContracts?: BytesLike[];
/** List of storage slots to initialize */
storageSlots?: TransactionRequestStorageSlot[];
}
export class CreateTransactionRequest extends BaseTransactionRequest {
static from(obj: CreateTransactionRequestLike) {
if (obj instanceof this) {
return obj;
}
return new this(obj);
}
/** Type of the transaction */
type = TransactionType.Create as const;
/** Witness index of contract bytecode to create */
bytecodeWitnessIndex: number;
/** Salt */
salt: string;
/** List of static contracts */
staticContracts: string[];
/** List of storage slots to initialize */
storageSlots: TransactionRequestStorageSlot[];
constructor({
bytecodeWitnessIndex,
salt,
staticContracts,
storageSlots,
...rest
}: CreateTransactionRequestLike = {}) {
super(rest);
this.bytecodeWitnessIndex = bytecodeWitnessIndex ?? 0;
this.salt = hexlify(salt ?? ZeroBytes32);
this.staticContracts = [...(staticContracts?.map((value) => hexlify(value)) ?? [])];
this.storageSlots = [...(storageSlots ?? [])];
}
toTransaction(): Transaction {
const baseTransaction = this.getBaseTransaction();
const bytecodeWitnessIndex = this.bytecodeWitnessIndex;
const staticContracts = this.staticContracts ?? [];
const storageSlots = this.storageSlots?.map(storageSlotify) ?? [];
return {
type: TransactionType.Create,
...baseTransaction,
bytecodeLength: baseTransaction.witnesses[bytecodeWitnessIndex].dataLength / 4,
bytecodeWitnessIndex,
staticContractsCount: staticContracts.length,
storageSlotsCount: storageSlots.length,
salt: this.salt ? hexlify(this.salt) : ZeroBytes32,
staticContracts: staticContracts.map((id) => hexlify(id)),
storageSlots,
};
}
getContractCreatedOutputs(): ContractCreatedTransactionRequestOutput[] {
return this.outputs.filter(
(output): output is ContractCreatedTransactionRequestOutput =>
output.type === OutputType.ContractCreated
);
}
addContractCreatedOutput(
/** Contract ID */
contractId: BytesLike,
/** State Root */
stateRoot: BytesLike
) {
this.pushOutput({
type: OutputType.ContractCreated,
contractId,
stateRoot,
});
}
}
export type TransactionRequest = ScriptTransactionRequest | CreateTransactionRequest;
export type TransactionRequestLike =
| ({ type: TransactionType.Script } & ScriptTransactionRequestLike)
| ({ type: TransactionType.Create } & CreateTransactionRequestLike);
export const transactionRequestify = (obj: TransactionRequestLike): TransactionRequest => {
if (obj instanceof ScriptTransactionRequest || obj instanceof CreateTransactionRequest) {
return obj;
}
switch (obj.type) {
case TransactionType.Script: {
return ScriptTransactionRequest.from(obj);
}
case TransactionType.Create: {
return CreateTransactionRequest.from(obj);
}
default: {
throw new Error(
`Unknown transaction type: ${
// @ts-expect-error Unreachable code
obj.type
}`
);
}
}
};