-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathlib.rs
1278 lines (1062 loc) · 41.4 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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#[cfg(test)]
mod tests {
use std::{collections::HashSet, time::Duration};
use fuels::{
accounts::signers::{fake::FakeSigner, private_key::PrivateKeySigner},
core::codec::{ABIFormatter, DecoderConfig, EncoderConfig, encode_fn_selector},
prelude::{LoadConfiguration, NodeConfig, StorageConfiguration},
programs::debug::ScriptType,
test_helpers::{ChainConfig, StateConfig},
types::{
Bits256,
errors::{Result, transaction::Reason},
},
};
use rand::{Rng, thread_rng};
#[tokio::test]
async fn instantiate_client() -> Result<()> {
// ANCHOR: instantiate_client
use fuels::prelude::{FuelService, Provider};
// Run the fuel node.
let server = FuelService::start(
NodeConfig::default(),
ChainConfig::default(),
StateConfig::default(),
)
.await?;
// Create a client that will talk to the node created above.
let client = Provider::from(server.bound_address()).await?;
assert!(client.healthy().await?);
// ANCHOR_END: instantiate_client
Ok(())
}
#[tokio::test]
async fn deploy_contract() -> Result<()> {
use fuels::prelude::*;
// ANCHOR: deploy_contract
// This helper will launch a local node and provide a test wallet linked to it
let wallet = launch_provider_and_get_wallet().await?;
// This will load and deploy your contract binary to the chain so that its ID can
// be used to initialize the instance
let contract_id = Contract::load_from(
"../../e2e/sway/contracts/contract_test/out/release/contract_test.bin",
LoadConfiguration::default(),
)?
.deploy(&wallet, TxPolicies::default())
.await?
.contract_id;
println!("Contract deployed @ {contract_id}");
// ANCHOR_END: deploy_contract
Ok(())
}
#[tokio::test]
async fn setup_program_test_example() -> Result<()> {
use fuels::prelude::*;
// ANCHOR: deploy_contract_setup_macro_short
setup_program_test!(
Wallets("wallet"),
Abigen(Contract(
name = "TestContract",
project = "e2e/sway/contracts/contract_test"
)),
Deploy(
name = "contract_instance",
contract = "TestContract",
wallet = "wallet"
),
);
let response = contract_instance
.methods()
.initialize_counter(42)
.call()
.await?;
assert_eq!(42, response.value);
// ANCHOR_END: deploy_contract_setup_macro_short
Ok(())
}
#[tokio::test]
async fn contract_call_cost_estimation() -> Result<()> {
use fuels::prelude::*;
abigen!(Contract(
name = "MyContract",
abi = "e2e/sway/contracts/contract_test/out/release/contract_test-abi.json"
));
let wallet = launch_provider_and_get_wallet().await?;
let contract_id = Contract::load_from(
"../../e2e/sway/contracts/contract_test/out/release/contract_test.bin",
LoadConfiguration::default(),
)?
.deploy(&wallet, TxPolicies::default())
.await?
.contract_id;
// ANCHOR: contract_call_cost_estimation
let contract_instance = MyContract::new(contract_id, wallet);
let tolerance = Some(0.0);
let block_horizon = Some(1);
let transaction_cost = contract_instance
.methods()
.initialize_counter(42) // Build the ABI call
.estimate_transaction_cost(tolerance, block_horizon) // Get estimated transaction cost
.await?;
// ANCHOR_END: contract_call_cost_estimation
let expected_script_gas = 2615;
let expected_total_gas = 8867;
assert_eq!(transaction_cost.script_gas, expected_script_gas);
assert_eq!(transaction_cost.total_gas, expected_total_gas);
Ok(())
}
#[tokio::test]
async fn deploy_with_parameters() -> std::result::Result<(), Box<dyn std::error::Error>> {
use fuels::{prelude::*, tx::StorageSlot, types::Bytes32};
use rand::prelude::{Rng, SeedableRng, StdRng};
let wallet = launch_provider_and_get_wallet().await?;
let contract_id_1 = Contract::load_from(
"../../e2e/sway/contracts/contract_test/out/release/contract_test.bin",
LoadConfiguration::default(),
)?
.deploy(&wallet, TxPolicies::default())
.await?
.contract_id;
// ANCHOR: deploy_with_parameters
// Optional: Add `Salt`
let rng = &mut StdRng::seed_from_u64(2322u64);
let salt: [u8; 32] = rng.r#gen();
// Optional: Configure storage
let key = Bytes32::from([1u8; 32]);
let value = Bytes32::from([2u8; 32]);
let storage_slot = StorageSlot::new(key, value);
let storage_configuration =
StorageConfiguration::default().add_slot_overrides([storage_slot]);
let configuration = LoadConfiguration::default()
.with_storage_configuration(storage_configuration)
.with_salt(salt);
// Optional: Configure deployment parameters
let tx_policies = TxPolicies::default()
.with_tip(1)
.with_script_gas_limit(1_000_000)
.with_maturity(0)
.with_expiration(10_000);
let contract_id_2 = Contract::load_from(
"../../e2e/sway/contracts/contract_test/out/release/contract_test.bin",
configuration,
)?
.deploy(&wallet, tx_policies)
.await?
.contract_id;
println!("Contract deployed @ {contract_id_2}");
// ANCHOR_END: deploy_with_parameters
assert_ne!(contract_id_1, contract_id_2);
// ANCHOR: use_deployed_contract
// This will generate your contract's methods onto `MyContract`.
// This means an instance of `MyContract` will have access to all
// your contract's methods that are running on-chain!
// ANCHOR: abigen_example
abigen!(Contract(
name = "MyContract",
abi = "e2e/sway/contracts/contract_test/out/release/contract_test-abi.json"
));
// ANCHOR_END: abigen_example
// This is an instance of your contract which you can use to make calls to your functions
let contract_instance = MyContract::new(contract_id_2, wallet);
let response = contract_instance
.methods()
.initialize_counter(42) // Build the ABI call
.call() // Perform the network call
.await?;
assert_eq!(42, response.value);
let response = contract_instance
.methods()
.increment_counter(10)
.call()
.await?;
assert_eq!(52, response.value);
// ANCHOR_END: use_deployed_contract
// ANCHOR: submit_response_contract
let response = contract_instance
.methods()
.initialize_counter(42)
.submit()
.await?;
tokio::time::sleep(Duration::from_millis(500)).await;
let value = response.response().await?.value;
// ANCHOR_END: submit_response_contract
assert_eq!(42, value);
Ok(())
}
#[tokio::test]
async fn deploy_with_multiple_wallets() -> Result<()> {
use fuels::prelude::*;
abigen!(Contract(
name = "MyContract",
abi = "e2e/sway/contracts/contract_test/out/release/contract_test-abi.json"
));
let wallets =
launch_custom_provider_and_get_wallets(WalletsConfig::default(), None, None).await?;
let contract_id_1 = Contract::load_from(
"../../e2e/sway/contracts/contract_test/out/release/contract_test.bin",
LoadConfiguration::default(),
)?
.deploy(&wallets[0], TxPolicies::default())
.await?
.contract_id;
let contract_instance_1 = MyContract::new(contract_id_1, wallets[0].clone());
let response = contract_instance_1
.methods()
.initialize_counter(42)
.call()
.await?;
assert_eq!(42, response.value);
let contract_id_2 = Contract::load_from(
"../../e2e/sway/contracts/contract_test/out/release/contract_test.bin",
LoadConfiguration::default().with_salt([1; 32]),
)?
.deploy(&wallets[1], TxPolicies::default())
.await?
.contract_id;
let contract_instance_2 = MyContract::new(contract_id_2, wallets[1].clone());
let response = contract_instance_2
.methods()
.initialize_counter(42) // Build the ABI call
.call()
.await?;
assert_eq!(42, response.value);
Ok(())
}
#[tokio::test]
#[allow(unused_variables)]
async fn contract_tx_and_call_params() -> Result<()> {
use fuels::prelude::*;
abigen!(Contract(
name = "MyContract",
abi = "e2e/sway/contracts/contract_test/out/release/contract_test-abi.json"
));
let wallet = launch_provider_and_get_wallet().await?;
let contract_id = Contract::load_from(
"../../e2e/sway/contracts/contract_test/out/release/contract_test.bin",
LoadConfiguration::default(),
)?
.deploy(&wallet, TxPolicies::default())
.await?
.contract_id;
// ANCHOR: tx_policies
let contract_methods = MyContract::new(contract_id.clone(), wallet.clone()).methods();
let tx_policies = TxPolicies::default()
.with_tip(1)
.with_script_gas_limit(1_000_000)
.with_maturity(0)
.with_expiration(10_000);
let response = contract_methods
.initialize_counter(42) // Our contract method
.with_tx_policies(tx_policies) // Chain the tx policies
.call() // Perform the contract call
.await?; // This is an async call, `.await` it.
// ANCHOR_END: tx_policies
// ANCHOR: tx_policies_default
let response = contract_methods
.initialize_counter(42)
.with_tx_policies(TxPolicies::default())
.call()
.await?;
// ANCHOR_END: tx_policies_default
// ANCHOR: call_parameters
let contract_methods = MyContract::new(contract_id, wallet.clone()).methods();
let tx_policies = TxPolicies::default();
// Forward 1_000_000 coin amount of base asset_id
// this is a big number for checking that amount can be a u64
let call_params = CallParameters::default().with_amount(1_000_000);
let response = contract_methods
.get_msg_amount() // Our contract method.
.with_tx_policies(tx_policies) // Chain the tx policies.
.call_params(call_params)? // Chain the call parameters.
.call() // Perform the contract call.
.await?;
// ANCHOR_END: call_parameters
// ANCHOR: call_parameters_default
let response = contract_methods
.initialize_counter(42)
.call_params(CallParameters::default())?
.call()
.await?;
// ANCHOR_END: call_parameters_default
Ok(())
}
#[tokio::test]
#[allow(unused_variables)]
#[cfg(any(not(feature = "fuel-core-lib"), feature = "rocksdb"))]
async fn token_ops_tests() -> Result<()> {
use fuels::prelude::*;
abigen!(Contract(
name = "MyContract",
abi = "e2e/sway/contracts/token_ops/out/release/token_ops-abi.json"
));
let temp_dir = tempfile::tempdir().expect("failed to make tempdir");
let temp_dir_name = temp_dir
.path()
.file_name()
.expect("failed to get file name")
.to_string_lossy()
.to_string();
let temp_database_path = temp_dir.path().join("db");
let node_config = NodeConfig {
starting_gas_price: 1100,
database_type: DbType::RocksDb(Some(temp_database_path)),
historical_execution: true,
..NodeConfig::default()
};
let chain_config = ChainConfig {
chain_name: temp_dir_name,
..ChainConfig::default()
};
let wallets = launch_custom_provider_and_get_wallets(
WalletsConfig::default(),
Some(node_config),
Some(chain_config),
)
.await?;
let wallet = wallets.first().expect("is there");
let contract_id = Contract::load_from(
"../../e2e/sway/contracts/token_ops/out/release/token_ops.bin",
LoadConfiguration::default(),
)?
.deploy_if_not_exists(wallet, TxPolicies::default())
.await?
.contract_id;
let contract_methods = MyContract::new(contract_id.clone(), wallet.clone()).methods();
// ANCHOR: simulate
// you would mint 100 coins if the transaction wasn't simulated
let counter = contract_methods
.mint_coins(100)
.simulate(Execution::realistic())
.await?;
// ANCHOR_END: simulate
{
let contract_id = contract_id.clone();
// ANCHOR: simulate_read_state
// you don't need any funds to read state
let balance = contract_methods
.get_balance(contract_id, AssetId::zeroed())
.simulate(Execution::state_read_only())
.await?
.value;
// ANCHOR_END: simulate_read_state
}
{
let provider = wallet.provider();
provider.produce_blocks(2, None).await?;
let block_height = provider.latest_block_height().await?;
let contract_id = contract_id.clone();
// ANCHOR: simulate_read_state_at_height
let balance = contract_methods
.get_balance(contract_id, AssetId::zeroed())
.simulate(Execution::state_read_only().at_height(block_height))
.await?
.value;
// ANCHOR_END: simulate_read_state_at_height
}
let response = contract_methods.mint_coins(1_000_000).call().await?;
// ANCHOR: variable_outputs
let address = wallet.address();
let asset_id = contract_id.asset_id(&Bits256::zeroed());
// withdraw some tokens to wallet
let response = contract_methods
.transfer(1_000_000, asset_id, address.into())
.with_variable_output_policy(VariableOutputPolicy::Exactly(1))
.call()
.await?;
// ANCHOR_END: variable_outputs
Ok(())
}
#[tokio::test]
#[allow(unused_variables)]
async fn dependency_estimation() -> Result<()> {
use fuels::prelude::*;
abigen!(Contract(
name = "MyContract",
abi = "e2e/sway/contracts/lib_contract_caller/out/release/lib_contract_caller-abi.json"
));
let wallet = launch_provider_and_get_wallet().await?;
let called_contract_id: ContractId = Contract::load_from(
"../../e2e/sway/contracts/lib_contract/out/release/lib_contract.bin",
LoadConfiguration::default(),
)?
.deploy(&wallet, TxPolicies::default())
.await?
.contract_id
.into();
let bin_path =
"../../e2e/sway/contracts/lib_contract_caller/out/release/lib_contract_caller.bin";
let caller_contract_id = Contract::load_from(bin_path, LoadConfiguration::default())?
.deploy(&wallet, TxPolicies::default())
.await?
.contract_id;
let contract_methods =
MyContract::new(caller_contract_id.clone(), wallet.clone()).methods();
// ANCHOR: dependency_estimation_fail
let address = wallet.address();
let amount = 100;
let response = contract_methods
.mint_then_increment_from_contract(called_contract_id, amount, address.into())
.call()
.await;
assert!(matches!(
response,
Err(Error::Transaction(Reason::Failure { .. }))
));
// ANCHOR_END: dependency_estimation_fail
// ANCHOR: dependency_estimation_manual
let response = contract_methods
.mint_then_increment_from_contract(called_contract_id, amount, address.into())
.with_variable_output_policy(VariableOutputPolicy::Exactly(1))
.with_contract_ids(&[called_contract_id.into()])
.call()
.await?;
// ANCHOR_END: dependency_estimation_manual
let asset_id = caller_contract_id.asset_id(&Bits256::zeroed());
let balance = wallet.get_asset_balance(&asset_id).await?;
assert_eq!(balance, amount);
// ANCHOR: dependency_estimation
let response = contract_methods
.mint_then_increment_from_contract(called_contract_id, amount, address.into())
.with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
.determine_missing_contracts()
.await?
.call()
.await?;
// ANCHOR_END: dependency_estimation
let balance = wallet.get_asset_balance(&asset_id).await?;
assert_eq!(balance, 2 * amount);
Ok(())
}
#[tokio::test]
#[allow(unused_variables)]
async fn get_contract_outputs() -> Result<()> {
use fuels::prelude::*;
// ANCHOR: deployed_contracts
abigen!(Contract(
name = "MyContract",
// Replace with your contract ABI.json path
abi = "e2e/sway/contracts/contract_test/out/release/contract_test-abi.json"
));
let wallet_original = launch_provider_and_get_wallet().await?;
let wallet = wallet_original.clone();
// Your bech32m encoded contract ID.
let contract_id: Bech32ContractId =
"fuel1vkm285ypjesypw7vhdlhnty3kjxxx4efckdycqh3ttna4xvmxtfs6murwy".parse()?;
let connected_contract_instance = MyContract::new(contract_id, wallet);
// You can now use the `connected_contract_instance` just as you did above!
// ANCHOR_END: deployed_contracts
let wallet = wallet_original;
// ANCHOR: deployed_contracts_hex
let contract_id: ContractId =
"0x65b6a3d081966040bbccbb7f79ac91b48c635729c59a4c02f15ae7da999b32d3".parse()?;
let connected_contract_instance = MyContract::new(contract_id, wallet);
// ANCHOR_END: deployed_contracts_hex
Ok(())
}
#[tokio::test]
#[allow(unused_variables)]
async fn call_params_gas() -> Result<()> {
use fuels::prelude::*;
abigen!(Contract(
name = "MyContract",
abi = "e2e/sway/contracts/contract_test/out/release/contract_test-abi.json"
));
let wallet = launch_provider_and_get_wallet().await?;
let contract_id = Contract::load_from(
"../../e2e/sway/contracts/contract_test/out/release/contract_test.bin",
LoadConfiguration::default(),
)?
.deploy(&wallet, TxPolicies::default())
.await?
.contract_id;
let contract_methods = MyContract::new(contract_id, wallet.clone()).methods();
// ANCHOR: call_params_gas
// Set the transaction `gas_limit` to 1_000_000 and `gas_forwarded` to 4300 to specify that
// the contract call transaction may consume up to 1_000_000 gas, while the actual call may
// only use 4300 gas
let tx_policies = TxPolicies::default().with_script_gas_limit(1_000_000);
let call_params = CallParameters::default().with_gas_forwarded(4300);
let response = contract_methods
.get_msg_amount() // Our contract method.
.with_tx_policies(tx_policies) // Chain the tx policies.
.call_params(call_params)? // Chain the call parameters.
.call() // Perform the contract call.
.await?;
// ANCHOR_END: call_params_gas
Ok(())
}
#[tokio::test]
#[allow(unused_variables)]
async fn multi_call_example() -> Result<()> {
use fuels::prelude::*;
abigen!(Contract(
name = "MyContract",
abi = "e2e/sway/contracts/contract_test/out/release/contract_test-abi.json"
));
let wallet = launch_provider_and_get_wallet().await?;
let contract_id = Contract::load_from(
"../../e2e/sway/contracts/contract_test/out/release/contract_test.bin",
LoadConfiguration::default(),
)?
.deploy(&wallet, TxPolicies::default())
.await?
.contract_id;
// ANCHOR: multi_call_prepare
let contract_methods = MyContract::new(contract_id, wallet.clone()).methods();
let call_handler_1 = contract_methods.initialize_counter(42);
let call_handler_2 = contract_methods.get_array([42; 2]);
// ANCHOR_END: multi_call_prepare
// ANCHOR: multi_call_build
let multi_call_handler = CallHandler::new_multi_call(wallet.clone())
.add_call(call_handler_1)
.add_call(call_handler_2)
.with_tx_policies(TxPolicies::default());
// ANCHOR_END: multi_call_build
let multi_call_handler_tmp = multi_call_handler.clone();
// ANCHOR: multi_call_values
let (counter, array): (u64, [u64; 2]) = multi_call_handler.call().await?.value;
// ANCHOR_END: multi_call_values
let multi_call_handler = multi_call_handler_tmp.clone();
// ANCHOR: multi_contract_call_response
let response = multi_call_handler.call::<(u64, [u64; 2])>().await?;
// ANCHOR_END: multi_contract_call_response
assert_eq!(counter, 42);
assert_eq!(array, [42; 2]);
let multi_call_handler = multi_call_handler_tmp.clone();
// ANCHOR: submit_response_multicontract
let submitted_tx = multi_call_handler.submit().await?;
tokio::time::sleep(Duration::from_millis(500)).await;
let (counter, array): (u64, [u64; 2]) = submitted_tx.response().await?.value;
// ANCHOR_END: submit_response_multicontract
assert_eq!(counter, 42);
assert_eq!(array, [42; 2]);
Ok(())
}
#[tokio::test]
#[allow(unused_variables)]
async fn multi_call_cost_estimation() -> Result<()> {
use fuels::prelude::*;
abigen!(Contract(
name = "MyContract",
abi = "e2e/sway/contracts/contract_test/out/release/contract_test-abi.json"
));
let wallet = launch_provider_and_get_wallet().await?;
let contract_id = Contract::load_from(
"../../e2e/sway/contracts/contract_test/out/release/contract_test.bin",
LoadConfiguration::default(),
)?
.deploy(&wallet, TxPolicies::default())
.await?
.contract_id;
let contract_methods = MyContract::new(contract_id, wallet.clone()).methods();
// ANCHOR: multi_call_cost_estimation
let call_handler_1 = contract_methods.initialize_counter(42);
let call_handler_2 = contract_methods.get_array([42; 2]);
let multi_call_handler = CallHandler::new_multi_call(wallet.clone())
.add_call(call_handler_1)
.add_call(call_handler_2);
let tolerance = Some(0.0);
let block_horizon = Some(1);
let transaction_cost = multi_call_handler
.estimate_transaction_cost(tolerance, block_horizon) // Get estimated transaction cost
.await?;
// ANCHOR_END: multi_call_cost_estimation
let expected_script_gas = 4217;
let expected_total_gas = 11046;
assert_eq!(transaction_cost.script_gas, expected_script_gas);
assert_eq!(transaction_cost.total_gas, expected_total_gas);
Ok(())
}
#[tokio::test]
#[allow(unused_variables)]
async fn connect_wallet() -> Result<()> {
use fuels::prelude::*;
abigen!(Contract(
name = "MyContract",
abi = "e2e/sway/contracts/contract_test/out/release/contract_test-abi.json"
));
let config = WalletsConfig::new(Some(2), Some(1), Some(DEFAULT_COIN_AMOUNT));
let mut wallets = launch_custom_provider_and_get_wallets(config, None, None).await?;
let wallet_1 = wallets.pop().unwrap();
let wallet_2 = wallets.pop().unwrap();
let contract_id = Contract::load_from(
"../../e2e/sway/contracts/contract_test/out/release/contract_test.bin",
LoadConfiguration::default(),
)?
.deploy(&wallet_1, TxPolicies::default())
.await?
.contract_id;
// ANCHOR: connect_wallet
// Create contract instance with wallet_1
let contract_instance = MyContract::new(contract_id, wallet_1.clone());
// Perform contract call with wallet_2
let response = contract_instance
.with_account(wallet_2) // Connect wallet_2
.methods() // Get contract methods
.get_msg_amount() // Our contract method
.call() // Perform the contract call.
.await?; // This is an async call, `.await` for it.
// ANCHOR_END: connect_wallet
Ok(())
}
#[tokio::test]
async fn custom_assets_example() -> Result<()> {
use fuels::prelude::*;
setup_program_test!(
Wallets("wallet", "wallet_2"),
Abigen(Contract(
name = "MyContract",
project = "e2e/sway/contracts/contract_test"
)),
Deploy(
name = "contract_instance",
contract = "MyContract",
wallet = "wallet"
)
);
let some_addr: Bech32Address = thread_rng().r#gen();
// ANCHOR: add_custom_assets
let amount = 1000;
let _ = contract_instance
.methods()
.initialize_counter(42)
.add_custom_asset(AssetId::zeroed(), amount, Some(some_addr.clone()))
.call()
.await?;
// ANCHOR_END: add_custom_assets
let custom_inputs = vec![];
let custom_outputs = vec![];
// ANCHOR: add_custom_inputs_outputs
let _ = contract_instance
.methods()
.initialize_counter(42)
.with_inputs(custom_inputs)
.with_outputs(custom_outputs)
.add_signer(wallet_2.signer().clone())
.call()
.await?;
// ANCHOR_END: add_custom_inputs_outputs
Ok(())
}
#[tokio::test]
async fn low_level_call_example() -> Result<()> {
use fuels::{core::codec::calldata, prelude::*, types::SizedAsciiString};
setup_program_test!(
Wallets("wallet"),
Abigen(
Contract(
name = "MyCallerContract",
project = "e2e/sway/contracts/low_level_caller"
),
Contract(
name = "MyTargetContract",
project = "e2e/sway/contracts/contract_test"
),
),
Deploy(
name = "caller_contract_instance",
contract = "MyCallerContract",
wallet = "wallet"
),
Deploy(
name = "target_contract_instance",
contract = "MyTargetContract",
wallet = "wallet"
),
);
// ANCHOR: low_level_call
let function_selector = encode_fn_selector("set_value_multiple_complex");
let call_data = calldata!(
MyStruct {
a: true,
b: [1, 2, 3],
},
SizedAsciiString::<4>::try_from("fuel")?
)?;
caller_contract_instance
.methods()
.call_low_level_call(
target_contract_instance.id(),
Bytes(function_selector),
Bytes(call_data),
)
.determine_missing_contracts()
.await?
.call()
.await?;
// ANCHOR_END: low_level_call
let result_uint = target_contract_instance
.methods()
.read_counter()
.call()
.await
.unwrap()
.value;
let result_bool = target_contract_instance
.methods()
.get_bool_value()
.call()
.await
.unwrap()
.value;
let result_str = target_contract_instance
.methods()
.get_str_value()
.call()
.await
.unwrap()
.value;
assert_eq!(result_uint, 2);
assert!(result_bool);
assert_eq!(result_str, "fuel");
Ok(())
}
#[tokio::test]
async fn configure_the_return_value_decoder() -> Result<()> {
use fuels::prelude::*;
setup_program_test!(
Wallets("wallet"),
Abigen(Contract(
name = "MyContract",
project = "e2e/sway/contracts/contract_test"
)),
Deploy(
name = "contract_instance",
contract = "MyContract",
wallet = "wallet"
)
);
// ANCHOR: contract_decoder_config
let _ = contract_instance
.methods()
.initialize_counter(42)
.with_decoder_config(DecoderConfig {
max_depth: 10,
max_tokens: 2_000,
})
.call()
.await?;
// ANCHOR_END: contract_decoder_config
Ok(())
}
#[tokio::test]
async fn storage_slots_override() -> Result<()> {
{
// ANCHOR: storage_slots_override
use fuels::{programs::contract::Contract, tx::StorageSlot};
let slot_override = StorageSlot::new([1; 32].into(), [2; 32].into());
let storage_config =
StorageConfiguration::default().add_slot_overrides([slot_override]);
let load_config =
LoadConfiguration::default().with_storage_configuration(storage_config);
let _: Result<_> = Contract::load_from("...", load_config);
// ANCHOR_END: storage_slots_override
}
{
// ANCHOR: storage_slots_disable_autoload
use fuels::programs::contract::Contract;
let storage_config = StorageConfiguration::default().with_autoload(false);
let load_config =
LoadConfiguration::default().with_storage_configuration(storage_config);
let _: Result<_> = Contract::load_from("...", load_config);
// ANCHOR_END: storage_slots_disable_autoload
}
Ok(())
}
#[tokio::test]
async fn contract_custom_call() -> Result<()> {
use fuels::prelude::*;
setup_program_test!(
Wallets("wallet"),
Abigen(Contract(
name = "TestContract",
project = "e2e/sway/contracts/contract_test"
)),
Deploy(
name = "contract_instance",
contract = "TestContract",
wallet = "wallet"
),
);
let provider = wallet.provider();
let counter = 42;
// ANCHOR: contract_call_tb
let call_handler = contract_instance.methods().initialize_counter(counter);
let mut tb = call_handler.transaction_builder().await?;
// customize the builder...
wallet.adjust_for_fee(&mut tb, 0).await?;
wallet.add_witnesses(&mut tb)?;
let tx = tb.build(provider).await?;
let tx_id = provider.send_transaction(tx).await?;
tokio::time::sleep(Duration::from_millis(500)).await;
let tx_status = provider.tx_status(&tx_id).await?;
let response = call_handler.get_response(tx_status)?;
assert_eq!(counter, response.value);
// ANCHOR_END: contract_call_tb
Ok(())
}
#[tokio::test]
async fn configure_encoder_config() -> Result<()> {
use fuels::prelude::*;
setup_program_test!(
Wallets("wallet"),
Abigen(Contract(
name = "MyContract",
project = "e2e/sway/contracts/contract_test"
)),
Deploy(
name = "contract_instance",
contract = "MyContract",
wallet = "wallet"
)
);
// ANCHOR: contract_encoder_config
let _ = contract_instance
.with_encoder_config(EncoderConfig {
max_depth: 10,
max_tokens: 2_000,
})
.methods()
.initialize_counter(42)
.call()
.await?;
// ANCHOR_END: contract_encoder_config
Ok(())
}