forked from FuelLabs/sway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
977 lines (925 loc) · 32.9 KB
/
lib.rs
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
//! A simple tool for constructing transactions from the command line.
use clap::{Args, Parser};
use devault::Devault;
use forc_util::tx_utils::Salt;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use thiserror::Error;
/// The top-level `forc tx` command.
#[derive(Debug, Parser, Deserialize, Serialize)]
#[clap(about, version, after_help = EXAMPLES)]
pub struct Command {
#[clap(long, short = 'o')]
pub output_path: Option<PathBuf>,
#[clap(subcommand)]
pub tx: Transaction,
}
/// Construct a transaction.
#[derive(Debug, Parser, Deserialize, Serialize)]
#[clap(name = "transaction")]
pub enum Transaction {
Create(Create),
Script(Script),
Mint(Mint),
}
/// Construct a `Create` transaction for deploying a contract.
#[derive(Debug, Parser, Deserialize, Serialize)]
pub struct Create {
#[clap(flatten)]
pub gas: Gas,
#[clap(flatten)]
pub maturity: Maturity,
#[clap(flatten)]
pub salt: Salt,
/// Path to the contract bytecode.
#[clap(long)]
pub bytecode: PathBuf,
/// Witness index of contract bytecode to create.
#[clap(long, default_value_t = 0)]
pub bytecode_witness_index: u8,
/// Path to a JSON file with a list of storage slots to initialize (key, value).
#[clap(long)]
pub storage_slots: PathBuf,
/// An arbitrary length string of hex-encoded bytes (e.g. "1F2E3D4C5B6A")
///
/// Can be specified multiple times.
#[clap(long = "witness", multiple = true, max_values = 255)]
pub witnesses: Vec<String>,
// Inputs and outputs must follow all other arguments and are parsed separately.
#[clap(skip)]
pub inputs: Vec<Input>,
// Inputs and outputs must follow all other arguments and are parsed separately.
#[clap(skip)]
pub outputs: Vec<Output>,
}
/// Construct a `Mint` transaction for emulating a block producer.
#[derive(Debug, Parser, Deserialize, Serialize)]
pub struct Mint {
/// The location of the `Mint` transaction in the block.
#[clap(long)]
pub tx_ptr: fuel_tx::TxPointer,
// Outputs must follow all other arguments and are parsed separately.
#[clap(skip)]
pub outputs: Vec<Output>,
}
/// Construct a `Script` transaction for running a script.
#[derive(Debug, Parser, Deserialize, Serialize)]
pub struct Script {
#[clap(flatten)]
pub gas: Gas,
#[clap(flatten)]
pub maturity: Maturity,
/// Script to execute.
#[clap(long)]
pub bytecode: PathBuf,
/// Script input data (parameters). Specified file is loaded as raw bytes.
#[clap(long)]
pub data: PathBuf,
/// Merkle root of receipts.
#[clap(long)]
pub receipts_root: fuel_tx::Bytes32,
/// An arbitrary length string of hex-encoded bytes (e.g. "1F2E3D4C5B6A")
///
/// Can be specified multiple times.
#[clap(long = "witness", multiple = true, max_values = 255)]
pub witnesses: Vec<String>,
// Inputs and outputs must follow all other arguments and are parsed separately.
#[clap(skip)]
pub inputs: Vec<Input>,
// Inputs and outputs must follow all other arguments and are parsed separately.
#[clap(skip)]
pub outputs: Vec<Output>,
}
/// Flag set for specifying gas price and limit.
#[derive(Debug, Devault, Parser, Deserialize, Serialize)]
pub struct Gas {
/// Gas price for the transaction.
#[clap(long = "gas-price", default_value_t = 0)]
#[devault("0")]
pub price: u64,
/// Gas limit for the transaction.
#[clap(long = "gas-limit", default_value_t = fuel_tx::ConsensusParameters::DEFAULT.max_gas_per_tx)]
#[devault("fuel_tx::ConsensusParameters::DEFAULT.max_gas_per_tx")]
pub limit: u64,
}
/// Block until which tx cannot be included.
#[derive(Debug, Args, Default, Deserialize, Serialize)]
pub struct Maturity {
/// Block height until which tx cannot be included.
#[clap(long = "maturity", default_value_t = 0)]
pub maturity: u32,
}
/// Transaction input.
#[derive(Debug, Parser, Deserialize, Serialize)]
#[clap(name = "input")]
pub enum Input {
Coin(InputCoin),
Contract(InputContract),
Message(InputMessage),
}
#[derive(Debug, Parser, Deserialize, Serialize)]
pub struct InputCoin {
/// Hash of the unspent transaction.
#[clap(long)]
pub utxo_id: fuel_tx::UtxoId,
/// Index of transaction output.
#[clap(long)]
pub output_ix: u8,
/// Owning address or predicate root.
#[clap(long)]
pub owner: fuel_tx::Address,
/// Amount of coins.
#[clap(long)]
pub amount: u64,
/// Asset ID of the coins.
#[clap(long)]
pub asset_id: fuel_tx::AssetId,
/// Points to the TX whose output is being spent. Includes block height, tx index.
#[clap(long)]
pub tx_ptr: fuel_tx::TxPointer,
/// Index of witness that authorizes spending the coin.
#[clap(long)]
pub witness_ix: Option<u8>,
/// UTXO being spent must have been created at least this many blocks ago.
#[clap(long)]
pub maturity: u32,
#[clap(flatten)]
pub predicate: Predicate,
}
#[derive(Debug, Parser, Deserialize, Serialize)]
pub struct InputContract {
/// Hash of the unspent transaction.
#[clap(long)]
pub utxo_id: fuel_tx::UtxoId,
/// Index of transaction output.
#[clap(long)]
pub output_ix: u8,
/// Root of the amount of coins owned by the contract before transaction execution.
#[clap(long)]
pub balance_root: fuel_tx::Bytes32,
/// State root of contract before transaction execution.
#[clap(long)]
pub state_root: fuel_tx::Bytes32,
/// Points to the TX whose output is being spent. Includes block height, tx index.
#[clap(long)]
pub tx_ptr: fuel_tx::TxPointer,
/// The ID of the contract.
#[clap(long)]
pub contract_id: fuel_tx::ContractId,
}
#[derive(Debug, Parser, Deserialize, Serialize)]
pub struct InputMessage {
/// The address of the message sender.
#[clap(long)]
pub sender: fuel_tx::Address,
/// The address or predicate root of the message recipient.
#[clap(long)]
pub recipient: fuel_tx::Address,
/// Amount of base asset coins sent with message.
#[clap(long)]
pub amount: u64,
/// The message nonce.
#[clap(long)]
pub nonce: fuel_types::Nonce,
/// The message data.
#[clap(long)]
pub msg_data: PathBuf,
/// Index of witness that authorizes the message.
#[clap(long)]
pub witness_ix: Option<u8>,
#[clap(flatten)]
pub predicate: Predicate,
}
/// Grouped arguments related to an input's predicate.
#[derive(Debug, Parser, Deserialize, Serialize)]
pub struct Predicate {
/// The predicate bytecode.
#[clap(long = "predicate")]
pub bytecode: Option<PathBuf>,
/// The predicate's input data (parameters). Specified file is loaded as raw bytes.
#[clap(long = "predicate-data")]
pub data: Option<PathBuf>,
}
/// The location of the transaction in the block.
#[derive(Debug, Parser, Deserialize, Serialize)]
pub struct TxPointer {
/// The transaction block height.
#[clap(long = "tx-ptr-block-height")]
pub block_height: u32,
/// Transaction index.
#[clap(long = "tx-ptr-ix")]
pub tx_ix: u16,
}
/// Transaction output.
#[derive(Debug, Parser, Deserialize, Serialize)]
#[clap(name = "output")]
pub enum Output {
Coin(OutputCoin),
Contract(OutputContract),
Change(OutputChange),
Variable(OutputVariable),
ContractCreated(OutputContractCreated),
}
#[derive(Debug, Parser, Deserialize, Serialize)]
pub struct OutputCoin {
/// Hash of the unspent transaction.
#[clap(long)]
pub to: fuel_tx::Address,
/// Amount of coins.
#[clap(long)]
pub amount: fuel_tx::Word,
/// Asset ID of the coins.
#[clap(long)]
pub asset_id: fuel_tx::AssetId,
}
#[derive(Debug, Parser, Deserialize, Serialize)]
pub struct OutputContract {
/// Index of input contract.
#[clap(long)]
pub input_ix: u8,
/// Root of amount of coins owned by contract after transaction execution.
#[clap(long)]
pub balance_root: fuel_tx::Bytes32,
/// State root of contract after transaction execution.
#[clap(long)]
pub state_root: fuel_tx::Bytes32,
}
#[derive(Debug, Parser, Deserialize, Serialize)]
pub struct OutputChange {
/// Receiving address or predicate root.
#[clap(long)]
pub to: fuel_tx::Address,
/// Amount of coins to send.
#[clap(long)]
pub amount: fuel_tx::Word,
/// Asset ID of coins.
#[clap(long)]
pub asset_id: fuel_tx::AssetId,
}
#[derive(Debug, Parser, Deserialize, Serialize)]
pub struct OutputVariable {
/// Receiving address or predicate root.
#[clap(long)]
pub to: fuel_tx::Address,
/// Amount of coins to send.
#[clap(long)]
pub amount: fuel_tx::Word,
/// Asset ID of coins.
#[clap(long)]
pub asset_id: fuel_tx::AssetId,
}
#[derive(Debug, Parser, Deserialize, Serialize)]
pub struct OutputContractCreated {
/// Contract ID
#[clap(long)]
pub contract_id: fuel_tx::ContractId,
/// Initial state root of contract.
#[clap(long)]
pub state_root: fuel_tx::Bytes32,
}
/// Errors that can occur while parsing the `Command`.
#[derive(Debug, Error)]
pub enum ParseError {
#[error("Failed to parse the command")]
Command {
#[source]
err: clap::Error,
},
#[error("Failed to parse transaction `input`")]
Input {
#[source]
err: clap::Error,
},
#[error("Failed to parse transaction `output`")]
Output {
#[source]
err: clap::Error,
},
#[error("Unrecognized argument {arg:?}, expected `input` or `output`")]
UnrecognizedArgumentExpectedInputOutput { arg: String, remaining: Vec<String> },
#[error("Found argument `input` which isn't valid for a mint transaction")]
MintTxHasInput,
}
/// Errors that can occur during conversion from the CLI transaction
/// representation to the `fuel-tx` representation.
#[derive(Debug, Error)]
pub enum ConvertTxError {
#[error("failed to convert create transaction")]
Create(#[from] ConvertCreateTxError),
#[error("failed to convert script transaction")]
Script(#[from] ConvertScriptTxError),
}
/// Errors that can occur during "create" transaction conversion.
#[derive(Debug, Error)]
pub enum ConvertCreateTxError {
#[error("failed to open `--storage-slots` from {path:?}")]
StorageSlotsOpen {
path: PathBuf,
#[source]
err: std::io::Error,
},
#[error("failed to deserialize storage slots file")]
StorageSlotsDeserialize(#[source] serde_json::Error),
#[error("failed to convert an input")]
Input(#[from] ConvertInputError),
}
/// Errors that can occur during "script" transaction conversion.
#[derive(Debug, Error)]
pub enum ConvertScriptTxError {
#[error("failed to read `--bytecode` from {path:?}")]
BytecodeRead {
path: PathBuf,
#[source]
err: std::io::Error,
},
#[error("failed to read `--data` from {path:?}")]
DataRead {
path: PathBuf,
#[source]
err: std::io::Error,
},
#[error("failed to convert an input")]
Input(#[from] ConvertInputError),
}
/// Errors that can occur during transaction input conversion.
#[derive(Debug, Error)]
pub enum ConvertInputError {
#[error("failed to read `--msg-data` from {path:?}")]
MessageDataRead {
path: PathBuf,
#[source]
err: std::io::Error,
},
#[error("failed to read `--predicate` from {path:?}")]
PredicateRead {
path: PathBuf,
#[source]
err: std::io::Error,
},
#[error("failed to read `--predicate-data` from {path:?}")]
PredicateDataRead {
path: PathBuf,
#[source]
err: std::io::Error,
},
#[error("input accepts either witness index or predicate, not both")]
WitnessPredicateMismatch,
}
const EXAMPLES: &str = r#"EXAMPLES:
# An example constructing a `create` transaction.
forc tx create \
--bytecode ./my-contract/out/debug/my-contract.bin \
--storage-slots ./my-contract/out/debug/my-contract-storage_slots.json \
--gas-limit 100 \
--gas-price 0 \
--maturity 0 \
--witness ADFD \
--witness DFDA \
input coin \
--utxo-id 0 \
--output-ix 0 \
--owner 0x0000000000000000000000000000000000000000000000000000000000000000 \
--amount 100 \
--asset-id 0x0000000000000000000000000000000000000000000000000000000000000000 \
--tx-ptr 89ACBDEFBDEF \
--witness-ix 0 \
--maturity 0 \
--predicate ./my-predicate/out/debug/my-predicate.bin \
--predicate-data ./my-predicate.dat \
input contract \
--utxo-id 1 \
--output-ix 1 \
--balance-root 0x0000000000000000000000000000000000000000000000000000000000000000 \
--state-root 0x0000000000000000000000000000000000000000000000000000000000000000 \
--tx-ptr 89ACBDEFBDEF \
--contract-id 0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC \
input message \
--sender 0x1111111111111111111111111111111111111111111111111111111111111111 \
--recipient 0x2222222222222222222222222222222222222222222222222222222222222222 \
--amount 1 \
--nonce 0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB \
--witness-ix 1 \
--msg-data ./message.dat \
--predicate ./my-predicate2/out/debug/my-predicate2.bin \
--predicate-data ./my-predicate2.dat \
output coin \
--to 0x2222222222222222222222222222222222222222222222222222222222222222 \
--amount 100 \
--asset-id 0x0000000000000000000000000000000000000000000000000000000000000000 \
output contract \
--input-ix 1 \
--balance-root 0x0000000000000000000000000000000000000000000000000000000000000000 \
--state-root 0x0000000000000000000000000000000000000000000000000000000000000000 \
output change \
--to 0x2222222222222222222222222222222222222222222222222222222222222222 \
--amount 100 \
--asset-id 0x0000000000000000000000000000000000000000000000000000000000000000 \
output variable \
--to 0x2222222222222222222222222222222222222222222222222222222222222222 \
--amount 100 \
--asset-id 0x0000000000000000000000000000000000000000000000000000000000000000 \
output contract-created \
--contract-id 0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC \
--state-root 0x0000000000000000000000000000000000000000000000000000000000000000
"#;
impl ParseError {
/// Print the error with clap's fancy formatting.
pub fn print(&self) -> Result<(), clap::Error> {
match self {
ParseError::Command { err } => {
err.print()?;
}
ParseError::Input { err } => {
err.print()?;
}
ParseError::Output { err } => {
err.print()?;
}
ParseError::UnrecognizedArgumentExpectedInputOutput { .. } => {
use clap::CommandFactory;
// Create a type as a hack to produce consistent-looking clap help output.
#[derive(Parser)]
enum ForcTxIo {
#[clap(subcommand)]
Input(Input),
#[clap(subcommand)]
Output(Output),
}
println!("{self}\n");
ForcTxIo::command().print_long_help()?;
}
ParseError::MintTxHasInput => {
println!("{self}");
}
}
Ok(())
}
}
impl Command {
/// Emulates `clap::Parser::parse` behaviour, but returns the parsed inputs and outputs.
///
/// If parsing fails, prints the error along with the help output and exits with an error code.
///
/// We provide this custom `parse` function solely due to clap's limitations around parsing
/// trailing subcommands.
pub fn parse() -> Self {
let err = match Self::try_parse() {
Err(err) => err,
Ok(cmd) => return cmd,
};
let _ = err.print();
std::process::exit(1);
}
/// Parse a full `Transaction` including trailing inputs and outputs.
pub fn try_parse() -> Result<Self, ParseError> {
Self::try_parse_from_args(std::env::args())
}
/// Parse a full `Transaction` including trailing inputs and outputs from an iterator yielding
/// whitespace-separate string arguments.
pub fn try_parse_from_args(args: impl IntoIterator<Item = String>) -> Result<Self, ParseError> {
const INPUT: &str = "input";
const OUTPUT: &str = "output";
fn is_input_or_output(s: &str) -> bool {
s == INPUT || s == OUTPUT
}
fn push_input(cmd: &mut Transaction, input: Input) -> Result<(), ParseError> {
match cmd {
Transaction::Create(ref mut create) => create.inputs.push(input),
Transaction::Script(ref mut script) => script.inputs.push(input),
Transaction::Mint(_) => return Err(ParseError::MintTxHasInput),
}
Ok(())
}
fn push_output(cmd: &mut Transaction, output: Output) {
match cmd {
Transaction::Create(ref mut create) => create.outputs.push(output),
Transaction::Script(ref mut script) => script.outputs.push(output),
Transaction::Mint(ref mut mint) => mint.outputs.push(output),
}
}
let mut args = args.into_iter().peekable();
// Collect args until the first `input` or `output` is reached.
let mut cmd = {
let cmd_args = std::iter::from_fn(|| args.next_if(|s| !is_input_or_output(s)));
Command::try_parse_from(cmd_args).map_err(|err| ParseError::Command { err })?
};
// The remaining args (if any) are the inputs and outputs.
while let Some(arg) = args.next() {
let args_til_next = std::iter::once(arg.clone()).chain(std::iter::from_fn(|| {
args.next_if(|s| !is_input_or_output(s))
}));
match &arg[..] {
INPUT => {
let input = Input::try_parse_from(args_til_next)
.map_err(|err| ParseError::Input { err })?;
push_input(&mut cmd.tx, input)?
}
OUTPUT => {
let output = Output::try_parse_from(args_til_next)
.map_err(|err| ParseError::Output { err })?;
push_output(&mut cmd.tx, output)
}
arg => {
return Err(ParseError::UnrecognizedArgumentExpectedInputOutput {
arg: arg.to_string(),
remaining: args.collect(),
})
}
}
}
// If there are args remaining, report them.
if args.peek().is_some() {
return Err(ParseError::UnrecognizedArgumentExpectedInputOutput {
arg: args.peek().unwrap().to_string(),
remaining: args.collect(),
});
}
Ok(cmd)
}
}
impl TryFrom<Transaction> for fuel_tx::Transaction {
type Error = ConvertTxError;
fn try_from(tx: Transaction) -> Result<Self, Self::Error> {
let tx = match tx {
Transaction::Create(create) => Self::Create(<_>::try_from(create)?),
Transaction::Script(script) => Self::Script(<_>::try_from(script)?),
Transaction::Mint(mint) => Self::Mint(mint.into()),
};
Ok(tx)
}
}
impl TryFrom<Create> for fuel_tx::Create {
type Error = ConvertCreateTxError;
fn try_from(create: Create) -> Result<Self, Self::Error> {
let storage_slots = {
let file = std::fs::File::open(&create.storage_slots).map_err(|err| {
ConvertCreateTxError::StorageSlotsOpen {
path: create.storage_slots,
err,
}
})?;
let reader = std::io::BufReader::new(file);
serde_json::from_reader(reader)
.map_err(ConvertCreateTxError::StorageSlotsDeserialize)?
};
let inputs = create
.inputs
.into_iter()
.map(fuel_tx::Input::try_from)
.collect::<Result<Vec<_>, _>>()?;
let outputs = create
.outputs
.into_iter()
.map(fuel_tx::Output::from)
.collect();
let witnesses = create
.witnesses
.into_iter()
.map(|s| fuel_tx::Witness::from(s.as_bytes()))
.collect();
let create = fuel_tx::Transaction::create(
create.gas.price,
create.gas.limit,
create.maturity.maturity.into(),
create.bytecode_witness_index,
create.salt.salt.unwrap_or_default(),
storage_slots,
inputs,
outputs,
witnesses,
);
Ok(create)
}
}
impl TryFrom<Script> for fuel_tx::Script {
type Error = ConvertScriptTxError;
fn try_from(script: Script) -> Result<Self, Self::Error> {
let script_bytecode =
std::fs::read(&script.bytecode).map_err(|err| ConvertScriptTxError::BytecodeRead {
path: script.bytecode,
err,
})?;
let script_data =
std::fs::read(&script.data).map_err(|err| ConvertScriptTxError::DataRead {
path: script.data,
err,
})?;
let inputs = script
.inputs
.into_iter()
.map(fuel_tx::Input::try_from)
.collect::<Result<Vec<_>, _>>()?;
let outputs = script
.outputs
.into_iter()
.map(fuel_tx::Output::from)
.collect();
let witnesses = script
.witnesses
.into_iter()
.map(|s| fuel_tx::Witness::from(s.as_bytes()))
.collect();
let script = fuel_tx::Transaction::script(
script.gas.price,
script.gas.limit,
script.maturity.maturity.into(),
script_bytecode,
script_data,
inputs,
outputs,
witnesses,
);
Ok(script)
}
}
impl From<Mint> for fuel_tx::Mint {
fn from(mint: Mint) -> Self {
let outputs = mint
.outputs
.into_iter()
.map(fuel_tx::Output::from)
.collect();
fuel_tx::Transaction::mint(mint.tx_ptr, outputs)
}
}
impl TryFrom<Input> for fuel_tx::Input {
type Error = ConvertInputError;
fn try_from(input: Input) -> Result<Self, Self::Error> {
let input = match input {
Input::Coin(coin) => {
let InputCoin {
utxo_id,
// TODO: Should this be verified / checked in some way?
output_ix: _,
owner,
amount,
asset_id,
tx_ptr: tx_pointer,
maturity,
predicate,
witness_ix,
} = coin;
match (witness_ix, predicate.bytecode, predicate.data) {
(Some(witness_index), None, None) => fuel_tx::Input::coin_signed(
utxo_id,
owner,
amount,
asset_id,
tx_pointer,
witness_index,
maturity.into(),
),
(None, Some(predicate), Some(predicate_data)) => {
fuel_tx::Input::coin_predicate(
utxo_id,
owner,
amount,
asset_id,
tx_pointer,
maturity.into(),
std::fs::read(&predicate).map_err(|err| {
ConvertInputError::PredicateRead {
path: predicate,
err,
}
})?,
std::fs::read(&predicate_data).map_err(|err| {
ConvertInputError::PredicateDataRead {
path: predicate_data,
err,
}
})?,
)
}
_ => return Err(ConvertInputError::WitnessPredicateMismatch),
}
}
Input::Contract(contract) => fuel_tx::Input::contract(
contract.utxo_id,
contract.balance_root,
contract.state_root,
contract.tx_ptr,
contract.contract_id,
),
Input::Message(msg) => {
let InputMessage {
sender,
recipient,
amount,
nonce,
msg_data,
witness_ix,
predicate,
} = msg;
let data =
std::fs::read(&msg_data).map_err(|err| ConvertInputError::MessageDataRead {
path: msg_data,
err,
})?;
match (witness_ix, predicate.bytecode, predicate.data) {
(Some(witness_index), None, None) => {
if data.is_empty() {
fuel_tx::Input::message_coin_signed(
sender,
recipient,
amount,
nonce,
witness_index,
)
} else {
fuel_tx::Input::message_data_signed(
sender,
recipient,
amount,
nonce,
witness_index,
data,
)
}
}
(None, Some(predicate), Some(predicate_data)) => {
let predicate = std::fs::read(&predicate).map_err(|err| {
ConvertInputError::PredicateRead {
path: predicate,
err,
}
})?;
let predicate_data = std::fs::read(&predicate_data).map_err(|err| {
ConvertInputError::PredicateDataRead {
path: predicate_data,
err,
}
})?;
if data.is_empty() {
fuel_tx::Input::message_coin_predicate(
sender,
recipient,
amount,
nonce,
predicate,
predicate_data,
)
} else {
fuel_tx::Input::message_data_predicate(
sender,
recipient,
amount,
nonce,
data,
predicate,
predicate_data,
)
}
}
_ => return Err(ConvertInputError::WitnessPredicateMismatch),
}
}
};
Ok(input)
}
}
impl From<Output> for fuel_tx::Output {
fn from(output: Output) -> Self {
match output {
Output::Coin(coin) => fuel_tx::Output::Coin {
to: coin.to,
amount: coin.amount,
asset_id: coin.asset_id,
},
Output::Contract(contract) => fuel_tx::Output::Contract {
input_index: contract.input_ix,
balance_root: contract.balance_root,
state_root: contract.state_root,
},
Output::Change(change) => fuel_tx::Output::Change {
to: change.to,
amount: change.amount,
asset_id: change.asset_id,
},
Output::Variable(variable) => fuel_tx::Output::Variable {
to: variable.to,
amount: variable.amount,
asset_id: variable.asset_id,
},
Output::ContractCreated(contract_created) => fuel_tx::Output::ContractCreated {
contract_id: contract_created.contract_id,
state_root: contract_created.state_root,
},
}
}
}
#[test]
fn test_parse_create() {
let cmd = r#"
forc-tx create
--bytecode ./my-contract/out/debug/my-contract.bin
--storage-slots ./my-contract/out/debug/my-contract-storage_slots.json
--gas-limit 100
--gas-price 0
--maturity 0
--witness ADFD
--witness DFDA
"#;
dbg!(Command::try_parse_from_args(cmd.split_whitespace().map(|s| s.to_string())).unwrap());
}
#[test]
fn test_parse_script() {
let receipts_root = fuel_tx::Bytes32::default();
let cmd = format!(
r#"
forc-tx script
--bytecode ./my-script/out/debug/my-script.bin
--data ./my-script.dat
--gas-limit 100
--gas-price 0
--maturity 0
--receipts-root {receipts_root}
--witness ADFD
--witness DFDA
"#
);
dbg!(Command::try_parse_from_args(cmd.split_whitespace().map(|s| s.to_string())).unwrap());
}
#[test]
fn test_parse_mint_coin() {
let tx_ptr = fuel_tx::TxPointer::default();
let address = fuel_tx::Address::default();
let asset_id = fuel_tx::AssetId::default();
let cmd = format!(
r#"
forc-tx mint --tx-ptr {tx_ptr:X} output coin --to {address} --amount 100 --asset-id {asset_id}
"#
);
dbg!(Command::try_parse_from_args(cmd.split_whitespace().map(|s| s.to_string())).unwrap());
}
#[test]
fn test_parse_create_inputs_outputs() {
let address = fuel_tx::Address::default();
let asset_id = fuel_tx::AssetId::default();
let tx_ptr = fuel_tx::TxPointer::default();
let balance_root = fuel_tx::Bytes32::default();
let state_root = fuel_tx::Bytes32::default();
let contract_id = fuel_tx::ContractId::default();
let nonce = fuel_types::Nonce::default();
let sender = fuel_tx::Address::default();
let recipient = fuel_tx::Address::default();
let args = format!(
r#"
forc-tx create
--bytecode ./my-contract/out/debug/my-contract.bin
--storage-slots ./my-contract/out/debug/my-contract-storage_slots.json
--gas-limit 100
--gas-price 0
--maturity 0
--witness ADFD
--witness DFDA
input coin
--utxo-id 0
--output-ix 0
--owner {address}
--amount 100
--asset-id {asset_id}
--tx-ptr {tx_ptr:X}
--witness-ix 0
--maturity 0
--predicate ./my-predicate/out/debug/my-predicate.bin
--predicate-data ./my-predicate.dat
input contract
--utxo-id 1
--output-ix 1
--balance-root {balance_root}
--state-root {state_root}
--tx-ptr {tx_ptr:X}
--contract-id {contract_id}
input message
--sender {sender}
--recipient {recipient}
--amount 1
--nonce {nonce}
--witness-ix 1
--msg-data ./message.dat
--predicate ./my-predicate2/out/debug/my-predicate2.bin
--predicate-data ./my-predicate2.dat
output coin
--to {address}
--amount 100
--asset-id {asset_id}
output contract
--input-ix 1
--balance-root {balance_root}
--state-root {state_root}
output change
--to {address}
--amount 100
--asset-id {asset_id}
output variable
--to {address}
--amount 100
--asset-id {asset_id}
output contract-created
--contract-id {contract_id}
--state-root {state_root}
"#
);
dbg!(Command::try_parse_from_args(args.split_whitespace().map(|s| s.to_string())).unwrap());
}