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
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use Error;
use Address;
use Argument;
use Command;
use GasPayment;
use Identifier;
use Input;
use MakeMoveVector;
use MergeCoins;
use MoveCall;
use ObjectReference;
use Publish;
use SplitCoins;
use Transaction;
use TransactionExpiration;
use TransferObjects;
use TypeTag;
use Upgrade;
use Encoding;
use Serialize;
/// A builder for creating transactions. Use `resolve` to finalize the transaction data.
/// A transaction input that bypasses serialization. The input contents is already BCS serialized
/// and is put verbatim into the transaction.
;
/// A transaction input that will be serialized from BCS.
;
/// A separate type to support denoting a function by a more structured representation.
/// A transaction builder to build transactions.
/// Convert from an [`unresolved::Input`] to a [`unresolved::ObjectReference`]. This is used to
/// convert gas objects into unresolved object references.
/// Convert from an [`unresolved::ObjectReference`] to a [`ObjectReference`].
/// Convert from an [`unresolved::Input`] into an [`Input`] for resolving the
/// transaction.
// #[cfg(test)]
// mod tests {
// use std::str::FromStr;
// use anyhow::Context;
// use base64ct::Encoding;
// use serde::de;
// use serde::Deserialize;
// use serde::Deserializer;
// use sui_crypto::ed25519::Ed25519PrivateKey;
// use sui_crypto::SuiSigner;
// use sui_graphql_client::faucet::FaucetClient;
// use sui_graphql_client::Client;
// use sui_graphql_client::PaginationFilter;
// use sui_types::framework::Coin;
// use sui_types::Address;
// use sui_types::Digest;
// use sui_types::ExecutionStatus;
// use sui_types::IdOperation;
// use sui_types::ObjectType;
// use sui_types::TransactionEffects;
// use sui_types::TypeTag;
// use crate::unresolved::Input;
// use crate::Function;
// use crate::Serialized;
// use crate::TransactionBuilder;
// /// Type corresponding to the output of `sui move build --dump-bytecode-as-base64`
// #[derive(serde::Deserialize, Debug)]
// struct MovePackageData {
// #[serde(deserialize_with = "bcs_from_str")]
// modules: Vec<Vec<u8>>,
// #[serde(deserialize_with = "deps_from_str")]
// dependencies: Vec<Address>,
// digest: Vec<u8>,
// }
// fn bcs_from_str<'de, D>(deserializer: D) -> Result<Vec<Vec<u8>>, D::Error>
// where
// D: Deserializer<'de>,
// {
// let bcs = Vec::<String>::deserialize(deserializer)?;
// bcs.into_iter()
// .map(|s| base64ct::Base64::decode_vec(&s).map_err(de::Error::custom))
// .collect()
// }
// fn deps_from_str<'de, D>(deserializer: D) -> Result<Vec<Address>, D::Error>
// where
// D: Deserializer<'de>,
// {
// let deps = Vec::<String>::deserialize(deserializer)?;
// deps.into_iter()
// .map(|s| Address::from_str(&s).map_err(de::Error::custom))
// .collect()
// }
// /// This is used to read the json file that contains the modules/deps/digest generated with sui
// /// move build --dump-bytecode-as-base64 on the `test_example_v1 and test_example_v2` projects
// /// in the tests directory.
// /// The json files are generated automatically when running `make test-with-localnet` in the
// /// root of the sui-transaction-builder crate.
// fn move_package_data(file: &str) -> MovePackageData {
// let data = std::fs::read_to_string(file)
// .with_context(|| {
// format!(
// "Failed to read {file}. \
// Run `make test-with-localnet` from the root of the repository that will \
// generate the right json files with the package data and then run the tests."
// )
// })
// .unwrap();
// serde_json::from_str(&data).unwrap()
// }
// /// Generate a random private key and its corresponding address
// fn helper_address_pk() -> (Address, Ed25519PrivateKey) {
// let pk = Ed25519PrivateKey::generate(rand::thread_rng());
// let address = pk.public_key().derive_address();
// (address, pk)
// }
// /// Helper to:
// /// - generate a private key and its corresponding address
// /// - set the sender for the tx to this newly created address
// /// - set gas price
// /// - set gas budget
// /// - call faucet which returns 5 coin objects (by default)
// /// - set the gas object (last coin from the list of the 5 objects returned by faucet)
// /// - return the address, private key, and coins.
// async fn helper_setup(
// tx: &mut TransactionBuilder,
// client: &Client,
// ) -> (Address, Ed25519PrivateKey, Vec<Coin<'static>>) {
// let (address, pk) = helper_address_pk();
// let faucet = FaucetClient::local();
// let faucet_resp = faucet.request(address).await.unwrap();
// wait_for_tx(
// client,
// faucet_resp
// .coins_sent
// .unwrap()
// .first()
// .unwrap()
// .transfer_tx_digest,
// )
// .await;
// let coins = client
// .coins(address, None, PaginationFilter::default())
// .await
// .unwrap();
// let coins = coins.data();
// let gas = coins.last().unwrap().id();
// // TODO when we have tx resolution, we can just pass an ObjectId
// let gas_obj: Input = (&client.object(*gas, None).await.unwrap().unwrap()).into();
// tx.add_gas_objects(vec![gas_obj.with_owned_kind()]);
// tx.set_gas_budget(500000000);
// tx.set_gas_price(1000);
// tx.set_sender(address);
// (address, pk, coins.to_vec())
// }
// /// Wait for the transaction to be finalized and indexed. This queries the GraphQL server until
// /// it retrieves the requested transaction.
// async fn wait_for_tx(client: &Client, digest: Digest) {
// while client.transaction(digest).await.unwrap().is_none() {
// tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
// }
// }
// /// Wait for the transaction to be finalized and indexed, and check the effects' to ensure the
// /// transaction was successfully executed.
// async fn wait_for_tx_and_check_effects_status_success(
// client: &Client,
// digest: Digest,
// effects: Result<Option<TransactionEffects>, sui_graphql_client::error::Error>,
// ) {
// assert!(effects.is_ok(), "Execution failed. Effects: {effects:?}");
// // wait for the transaction to be finalized
// wait_for_tx(client, digest).await;
// // check that it succeeded
// let status = effects.unwrap();
// let expected_status = ExecutionStatus::Success;
// assert_eq!(&expected_status, status.as_ref().unwrap().status());
// }
// #[tokio::test]
// async fn test_finish() {
// let mut tx = TransactionBuilder::new();
// let coin_obj_id = "0x19406ea4d9609cd9422b85e6bf2486908f790b778c757aff805241f3f609f9b4";
// let coin_digest = "7opR9rFUYivSTqoJHvFb9p6p54THyHTatMG6id4JKZR9";
// let coin_version = 2;
// let coin = tx.input(Input::owned(
// coin_obj_id.parse().unwrap(),
// coin_version,
// coin_digest.parse().unwrap(),
// ));
// let addr = Address::generate(rand::thread_rng());
// let recipient = tx.input(Serialized(&addr));
// let result = tx.clone().finish();
// assert!(result.is_err());
// tx.transfer_objects(vec![coin], recipient);
// tx.set_gas_budget(500000000);
// tx.set_gas_price(1000);
// tx.add_gas_objects(vec![Input::immutable(
// "0xd8792bce2743e002673752902c0e7348dfffd78638cb5367b0b85857bceb9821"
// .parse()
// .unwrap(),
// 2,
// "2ZigdvsZn5BMeszscPQZq9z8ebnS2FpmAuRbAi9ednCk"
// .parse()
// .unwrap(),
// )]);
// tx.set_sender(
// "0xc574ea804d9c1a27c886312e96c0e2c9cfd71923ebaeb3000d04b5e65fca2793"
// .parse()
// .unwrap(),
// );
// let tx = tx.finish();
// assert!(tx.is_ok());
// }
// #[tokio::test]
// async fn test_transfer_obj_execution() {
// let mut tx = TransactionBuilder::new();
// let client = Client::new_localhost();
// let (_, pk, coins) = helper_setup(&mut tx, &client).await;
// // get the object information from the client
// let first = coins.first().unwrap().id();
// let coin: Input = (&client.object(*first, None).await.unwrap().unwrap()).into();
// let coin_input = tx.input(coin.with_owned_kind());
// let recipient = Address::generate(rand::thread_rng());
// let recipient_input = tx.input(Serialized(&recipient));
// tx.transfer_objects(vec![coin_input], recipient_input);
// let tx = tx.finish().unwrap();
// let sig = pk.sign_transaction(&tx).unwrap();
// let effects = client.execute_tx(vec![sig], &tx).await;
// wait_for_tx_and_check_effects_status_success(&client, tx.digest(), effects).await;
// // check that recipient has 1 coin
// let recipient_coins = client
// .coins(recipient, None, PaginationFilter::default())
// .await
// .unwrap();
// assert_eq!(recipient_coins.data().len(), 1);
// }
// #[tokio::test]
// async fn test_move_call() {
// // Check that `0x1::option::is_none` move call works when passing `1`
// let client = Client::new_localhost();
// let mut tx = TransactionBuilder::new();
// // set up the sender, gas object, gas budget, and gas price and return the pk to sign
// let (_, pk, _) = helper_setup(&mut tx, &client).await;
// let function = Function::new(
// "0x1".parse().unwrap(),
// "option".parse().unwrap(),
// "is_none".parse().unwrap(),
// vec![TypeTag::U64],
// );
// let input = tx.input(Serialized(&vec![1u64]));
// tx.move_call(function, vec![input]);
// let tx = tx.finish().unwrap();
// let sig = pk.sign_transaction(&tx).unwrap();
// let effects = client.execute_tx(vec![sig], &tx).await;
// wait_for_tx_and_check_effects_status_success(&client, tx.digest(), effects).await;
// }
// #[tokio::test]
// async fn test_split_transfer() {
// let client = Client::new_localhost();
// let mut tx = TransactionBuilder::new();
// let (_, pk, _) = helper_setup(&mut tx, &client).await;
// // transfer 1 SUI from Gas coin
// let amount = tx.input(Serialized(&1_000_000_000u64));
// let result = tx.split_coins(tx.gas(), vec![amount]);
// let recipient_address = Address::generate(rand::thread_rng());
// let recipient = tx.input(Serialized(&recipient_address));
// tx.transfer_objects(vec![result], recipient);
// let tx = tx.finish().unwrap();
// let sig = pk.sign_transaction(&tx).unwrap();
// let effects = client.execute_tx(vec![sig], &tx).await;
// wait_for_tx_and_check_effects_status_success(&client, tx.digest(), effects).await;
// // check that recipient has 1 coin
// let recipient_coins = client
// .coins(recipient_address, None, PaginationFilter::default())
// .await
// .unwrap();
// assert_eq!(recipient_coins.data().len(), 1);
// }
// #[tokio::test]
// async fn test_split_without_transfer_should_fail() {
// let client = Client::new_localhost();
// let mut tx = TransactionBuilder::new();
// let (_, pk, coins) = helper_setup(&mut tx, &client).await;
// let coin = coins.first().unwrap().id();
// let coin_obj: Input = (&client.object(*coin, None).await.unwrap().unwrap()).into();
// let coin_input = tx.input(coin_obj.with_owned_kind());
// // transfer 1 SUI
// let amount = tx.input(Serialized(&1_000_000_000u64));
// tx.split_coins(coin_input, vec![amount]);
// let tx = tx.finish().unwrap();
// let sig = pk.sign_transaction(&tx).unwrap();
// let effects = client.execute_tx(vec![sig], &tx).await;
// assert!(effects.is_ok());
// // wait for the transaction to be finalized
// loop {
// let tx_digest = client.transaction(tx.digest()).await.unwrap();
// if tx_digest.is_some() {
// break;
// }
// }
// assert!(effects.is_ok());
// let status = effects.unwrap();
// let expected_status = ExecutionStatus::Success;
// // The tx failed, so we expect Failure instead of Success
// assert_ne!(&expected_status, status.as_ref().unwrap().status());
// }
// #[tokio::test]
// async fn test_merge_coins() {
// let client = Client::new_localhost();
// let mut tx = TransactionBuilder::new();
// let (address, pk, coins) = helper_setup(&mut tx, &client).await;
// let coin1 = coins.first().unwrap().id();
// let coin1_obj: Input = (&client.object(*coin1, None).await.unwrap().unwrap()).into();
// let coin_to_merge = tx.input(coin1_obj.with_owned_kind());
// let mut coins_to_merge = vec![];
// // last coin is used for gas, first coin is the one we merge into
// for c in coins[1..&coins.len() - 1].iter() {
// let coin: Input = (&client.object(*c.id(), None).await.unwrap().unwrap()).into();
// coins_to_merge.push(tx.input(coin.with_owned_kind()));
// }
// tx.merge_coins(coin_to_merge, coins_to_merge);
// let tx = tx.finish().unwrap();
// let sig = pk.sign_transaction(&tx).unwrap();
// let effects = client.execute_tx(vec![sig], &tx).await;
// wait_for_tx_and_check_effects_status_success(&client, tx.digest(), effects).await;
// // check that there are two coins
// let coins_after = client
// .coins(address, None, PaginationFilter::default())
// .await
// .unwrap();
// assert_eq!(coins_after.data().len(), 2);
// }
// #[tokio::test]
// async fn test_make_move_vec() {
// let client = Client::new_localhost();
// let mut tx = TransactionBuilder::new();
// let (_, pk, _) = helper_setup(&mut tx, &client).await;
// let input = tx.input(Serialized(&1u64));
// tx.make_move_vec(Some(TypeTag::U64), vec![input]);
// let tx = tx.finish().unwrap();
// let sig = pk.sign_transaction(&tx).unwrap();
// let effects = client.execute_tx(vec![sig], &tx).await;
// wait_for_tx_and_check_effects_status_success(&client, tx.digest(), effects).await;
// }
// #[tokio::test]
// async fn test_publish() {
// let client = Client::new_localhost();
// let mut tx = TransactionBuilder::new();
// let (address, pk, _) = helper_setup(&mut tx, &client).await;
// let package = move_package_data("package_test_example_v1.json");
// let sender = tx.input(Serialized(&address));
// let upgrade_cap = tx.publish(package.modules, package.dependencies);
// tx.transfer_objects(vec![upgrade_cap], sender);
// let tx = tx.finish().unwrap();
// let sig = pk.sign_transaction(&tx).unwrap();
// let effects = client.execute_tx(vec![sig], &tx).await;
// wait_for_tx_and_check_effects_status_success(&client, tx.digest(), effects).await;
// }
// #[tokio::test]
// async fn test_upgrade() {
// let client = Client::new_localhost();
// let mut tx = TransactionBuilder::new();
// let (address, pk, coins) = helper_setup(&mut tx, &client).await;
// let package = move_package_data("package_test_example_v2.json");
// let sender = tx.input(Serialized(&address));
// let upgrade_cap = tx.publish(package.modules, package.dependencies);
// tx.transfer_objects(vec![upgrade_cap], sender);
// let tx = tx.finish().unwrap();
// let sig = pk.sign_transaction(&tx).unwrap();
// let effects = client.execute_tx(vec![sig], &tx).await;
// let mut package_id: Option<Address> = None;
// let mut created_objs = vec![];
// if let Ok(Some(ref effects)) = effects {
// match effects {
// TransactionEffects::V2(e) => {
// for obj in e.changed_objects.clone() {
// if obj.id_operation == IdOperation::Created {
// let change = obj.output_state;
// match change {
// sui_types::ObjectOut::PackageWrite { .. } => {
// package_id = Some(obj.object_id);
// }
// sui_types::ObjectOut::ObjectWrite { .. } => {
// created_objs.push(obj.object_id);
// }
// _ => {}
// }
// }
// }
// }
// _ => panic!("Expected V2 effects"),
// }
// }
// wait_for_tx_and_check_effects_status_success(&client, tx.digest(), effects).await;
// let mut tx = TransactionBuilder::new();
// let mut upgrade_cap = None;
// for o in created_objs {
// let obj = client.object(o, None).await.unwrap().unwrap();
// match obj.object_type() {
// ObjectType::Struct(x) if x.name.to_string() == "UpgradeCap" => {
// match obj.owner() {
// sui_types::Owner::Address(_) => {
// let obj: Input = (&obj).into();
// upgrade_cap = Some(tx.input(obj.with_owned_kind()))
// }
// sui_types::Owner::Shared(_) => {
// upgrade_cap = Some(tx.input(&obj))
// }
// // If the capability is owned by an object, then the module defining the owning
// // object gets to decide how the upgrade capability should be used.
// sui_types::Owner::Object(_) => {
// panic!("Upgrade capability controlled by object")
// }
// sui_types::Owner::Immutable => panic!("Upgrade capability is stored immutably and cannot be used for upgrades"),
// sui_types::Owner::ConsensusAddress { .. } => {
// upgrade_cap = Some(tx.input(&obj))
// }
// _ => panic!("unknwon owner"),
// };
// break;
// }
// _ => {}
// };
// }
// let upgrade_policy = tx.input(Serialized(&0u8));
// let updated_package = move_package_data("package_test_example_v2.json");
// let digest_arg = tx.input(Serialized(&updated_package.digest));
// // we need this ticket to authorize the upgrade
// let upgrade_ticket = tx.move_call(
// Function::new(
// "0x2".parse().unwrap(),
// "package".parse().unwrap(),
// "authorize_upgrade".parse().unwrap(),
// vec![],
// ),
// vec![upgrade_cap.unwrap(), upgrade_policy, digest_arg],
// );
// // now we can upgrade the package
// let upgrade_receipt = tx.upgrade(
// updated_package.modules,
// updated_package.dependencies,
// package_id.unwrap(),
// upgrade_ticket,
// );
// // commit the upgrade
// tx.move_call(
// Function::new(
// "0x2".parse().unwrap(),
// "package".parse().unwrap(),
// "commit_upgrade".parse().unwrap(),
// vec![],
// ),
// vec![upgrade_cap.unwrap(), upgrade_receipt],
// );
// let gas = coins.last().unwrap().id();
// let gas_obj: Input = (&client.object(*gas, None).await.unwrap().unwrap()).into();
// tx.add_gas_objects(vec![gas_obj.with_owned_kind()]);
// tx.set_gas_budget(500000000);
// tx.set_gas_price(1000);
// tx.set_sender(address);
// let tx = tx.finish().unwrap();
// let sig = pk.sign_transaction(&tx).unwrap();
// let effects = client.execute_tx(vec![sig], &tx).await;
// wait_for_tx_and_check_effects_status_success(&client, tx.digest(), effects).await;
// }
// }