-
Notifications
You must be signed in to change notification settings - Fork 12
/
upgradable.rs
1125 lines (974 loc) · 38.5 KB
/
upgradable.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
// Using `pub` to avoid invalid `dead_code` warnings, see
// https://users.rust-lang.org/t/invalid-dead-code-warning-for-submodule-in-integration-test/80259
pub mod common;
use anyhow::Ok;
use common::access_controllable_contract::AccessControllableContract;
use common::upgradable_contract::UpgradableContract;
use common::utils::{
assert_failure_with, assert_insufficient_acl_permissions, assert_method_not_found_failure,
assert_success_with, assert_success_with_unit_return, fast_forward_beyond,
get_transaction_block, sdk_duration_from_secs,
};
use near_plugins::upgradable::FunctionCallArgs;
use near_sdk::serde_json::json;
use near_sdk::{CryptoHash, Duration, Gas, NearToken, Timestamp};
use near_workspaces::network::Sandbox;
use near_workspaces::result::ExecutionFinalResult;
use near_workspaces::{Account, AccountId, Contract, Worker};
use std::path::Path;
const PROJECT_PATH: &str = "./tests/contracts/upgradable";
const PROJECT_PATH_2: &str = "./tests/contracts/upgradable_2";
const PROJECT_PATH_STATE_MIGRATION: &str = "./tests/contracts/upgradable_state_migration";
const ERR_MSG_NO_STAGING_TS: &str = "Upgradable: staging timestamp isn't set";
const ERR_MSG_DEPLOY_CODE_TOO_EARLY: &str = "Upgradable: Deploy code too early: staging ends on";
const ERR_MSG_UPDATE_DURATION_TOO_EARLY: &str =
"Upgradable: Update duration too early: staging ends on";
/// Allows spinning up a setup for testing the contract in [`PROJECT_PATH`] and bundles related
/// resources.
struct Setup {
/// The worker interacting with the current sandbox.
worker: Worker<Sandbox>,
/// A deployed instance of the contract.
contract: Contract,
/// Wrapper around the deployed contract that facilitates interacting with methods provided by
/// the `Upgradable` plugin.
upgradable_contract: UpgradableContract,
/// Wrapper around the deployed contract that facilitates interacting with methods provided by
/// the `AccessControllable` plugin.
acl_contract: AccessControllableContract,
/// A newly created account without any `AccessControllable` permissions.
unauth_account: Account,
}
impl Setup {
/// Deploys and initializes the test contract in [`PROJECT_PATH`] and returns a new `Setup`.
///
/// The `dao` and `staging_duration` parameters are passed to the contract's constructor,
/// allowing to optionally grant the `DAO` role and initialize the staging duration.
///
/// Grantees of the `DAO` role are authorized to call all protected `Upgradable` methods of the
/// test contract, which facilitates testing.
async fn new(
worker: Worker<Sandbox>,
dao: Option<AccountId>,
staging_duration: Option<Duration>,
) -> anyhow::Result<Self> {
// Compile and deploy the contract.
let wasm = common::repo::compile_project(Path::new(PROJECT_PATH), "upgradable").await?;
let contract = worker.dev_deploy(&wasm).await?;
let upgradable_contract = UpgradableContract::new(contract.clone());
let acl_contract = AccessControllableContract::new(contract.clone());
// Call the contract's constructor.
contract
.call("new")
.args_json(json!({
"dao": dao,
"staging_duration": staging_duration,
}))
.max_gas()
.transact()
.await?
.into_result()?;
let unauth_account = worker.dev_create_account().await?;
Ok(Self {
worker,
contract,
upgradable_contract,
acl_contract,
unauth_account,
})
}
/// Computes the expected staging timestamp based on the result of a transaction that calls a
/// function which sets the timestamp. For example a transaction which calls
/// `Upgradable::up_stage_code`. The function call is expected to be the first action in the
/// transaction.
///
/// Panics if the block timestamp cannot be retrieved.
async fn expected_staging_timestamp(
&self,
result: ExecutionFinalResult,
delay: Duration,
) -> Timestamp {
// Grab the receipt corresponding to the function call.
let receipt = result
.receipt_outcomes()
.first()
.expect("There should be at least one receipt outcome");
let block_timestamp = get_transaction_block(&self.worker, receipt)
.await
.expect("Should retrieve the transaction's block")
.timestamp();
block_timestamp + delay
}
/// Asserts staged code equals `expected_code`.
async fn assert_staged_code(&self, expected_code: Option<&Vec<u8>>) {
let staged = self
.upgradable_contract
.up_staged_code(&self.unauth_account)
.await
.expect("Call to up_staged_code should succeed");
assert_eq!(staged.as_ref(), expected_code);
}
/// Asserts the staging duration of the `Upgradable` contract equals the `expected_duration`.
async fn assert_staging_duration(&self, expected_duration: Option<Duration>) {
let status = self
.upgradable_contract
.up_get_delay_status(&self.unauth_account)
.await
.expect("Call to up_get_delay_status should succeed");
assert_eq!(status.staging_duration, expected_duration);
}
/// Asserts the staging timestamp of the `Upgradable` contract equals the `expected_timestamp`.
async fn assert_staging_timestamp(&self, expected_timestamp: Option<Timestamp>) {
let status = self
.upgradable_contract
.up_get_delay_status(&self.unauth_account)
.await
.expect("Call to up_get_delay_status should succeed");
assert_eq!(status.staging_timestamp, expected_timestamp);
}
/// Asserts the staged new staging duration of the `Upgradable` contract equals the
/// `expected_duration`.
async fn assert_new_staging_duration(&self, expected_duration: Option<Duration>) {
let status = self
.upgradable_contract
.up_get_delay_status(&self.unauth_account)
.await
.expect("Call to up_get_delay_status should succeed");
assert_eq!(status.new_staging_duration, expected_duration);
}
/// Asserts the staging timestamp of the new duration of an `Upgradable` contract equals the
/// `expected_timestamp`.
async fn assert_new_duration_staging_timestamp(&self, expected_timestamp: Option<Timestamp>) {
let status = self
.upgradable_contract
.up_get_delay_status(&self.unauth_account)
.await
.expect("Call to up_get_delay_status should succeed");
assert_eq!(status.new_staging_duration_timestamp, expected_timestamp);
}
async fn call_is_upgraded(
&self,
caller: &Account,
) -> near_workspaces::Result<ExecutionFinalResult> {
// `is_upgraded` could be called via `view`, however here it is called via `transact` so we
// get an `ExecutionFinalResult` that can be passed to `assert_*` methods from
// `common::utils`. It is acceptable since all we care about is whether the method exists.
caller
.call(self.contract.id(), "is_upgraded")
.max_gas()
.transact()
.await
}
async fn call_is_migrated(
&self,
caller: &Account,
) -> near_workspaces::Result<ExecutionFinalResult> {
// `is_migrated` could be called via `view`, however here it is called via `transact` so we
// get an `ExecutionFinalResult` that can be passed to `assert_*` methods from
// `common::utils`. It is acceptable since all we care about is whether the method exists
// and can be called successfully.
caller
.call(self.contract.id(), "is_migrated")
.max_gas()
.transact()
.await
}
/// Calls the contract's `is_set_up` method and asserts it returns `true`. Panics on failure.
async fn assert_is_set_up(&self, caller: &Account) {
let res = caller
.call(self.contract.id(), "is_set_up")
.view()
.await
.expect("Function call should succeed");
let is_set_up = res
.json::<bool>()
.expect("Should be able to deserialize the result");
assert!(is_set_up);
}
}
/// Panics if the conversion fails.
fn convert_code_to_crypto_hash(code: &[u8]) -> CryptoHash {
near_sdk::env::sha256(code)
.try_into()
.expect("Code should be converted to CryptoHash")
}
/// Computes the hash `code` according the to requirements of the `hash` parameter of
/// `Upgradable::up_deploy_code`.
fn convert_code_to_deploy_hash(code: &[u8]) -> String {
use near_sdk::base64::Engine;
let hash = near_sdk::env::sha256(code);
near_sdk::base64::prelude::BASE64_STANDARD.encode(hash)
}
/// Smoke test of contract setup.
#[tokio::test]
async fn test_setup() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let setup = Setup::new(worker, None, None).await?;
setup.assert_is_set_up(&setup.unauth_account).await;
Ok(())
}
#[tokio::test]
async fn test_stage_code_permission_failure() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(
worker,
Some(dao.id().clone()),
Some(sdk_duration_from_secs(42)),
)
.await?;
// Only the roles passed as `code_stagers` to the `Upgradable` derive macro may successfully
// call this method.
let res = setup
.upgradable_contract
.up_stage_code(&setup.unauth_account, vec![])
.await?;
assert_insufficient_acl_permissions(
res,
"up_stage_code",
vec!["CodeStager".to_string(), "DAO".to_string()],
);
// Verify no code was staged.
setup.assert_staged_code(None).await;
Ok(())
}
#[tokio::test]
async fn test_stage_code_without_delay() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(worker, Some(dao.id().clone()), None).await?;
// Stage code.
let code = vec![1, 2, 3];
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res.clone());
// Verify code was staged.
let staged = setup
.upgradable_contract
.up_staged_code(&setup.unauth_account)
.await?
.expect("Code should be staged");
assert_eq!(staged, code);
// Verify staging timestamp. The staging duration defaults to zero if not set.
let staging_timestamp = setup.expected_staging_timestamp(res, 0).await;
setup
.assert_staging_timestamp(Some(staging_timestamp))
.await;
Ok(())
}
#[tokio::test]
async fn test_stage_code_with_delay() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let staging_duration = sdk_duration_from_secs(42);
let setup = Setup::new(worker, Some(dao.id().clone()), Some(staging_duration)).await?;
// Stage code.
let code = vec![1, 2, 3];
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res.clone());
// Verify code was staged.
let staged = setup
.upgradable_contract
.up_staged_code(&setup.unauth_account)
.await?
.expect("Code should be staged");
assert_eq!(staged, code);
// Verify staging timestamp.
let staging_timestamp = setup
.expected_staging_timestamp(res, staging_duration)
.await;
setup
.assert_staging_timestamp(Some(staging_timestamp))
.await;
Ok(())
}
#[tokio::test]
async fn test_staging_empty_code_clears_storage() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(
worker,
Some(dao.id().clone()),
Some(sdk_duration_from_secs(42)),
)
.await?;
// First stage some code.
let code = vec![1, 2, 3];
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res);
setup.assert_staged_code(Some(&code)).await;
// Verify staging empty code removes it.
let res = setup
.upgradable_contract
.up_stage_code(&dao, vec![])
.await?;
assert_success_with_unit_return(res);
setup.assert_staged_code(None).await;
// Verify the staging timestamp was removed along with the staged code.
setup.assert_staging_timestamp(None).await;
Ok(())
}
#[tokio::test]
async fn test_staged_code() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(
worker,
Some(dao.id().clone()),
Some(sdk_duration_from_secs(42)),
)
.await?;
// No code staged.
let staged = setup
.upgradable_contract
.up_staged_code(&setup.unauth_account)
.await?;
assert_eq!(staged, None);
// Stage code.
let code = vec![1, 2, 3];
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res);
// Some code is staged.
let staged = setup
.upgradable_contract
.up_staged_code(&setup.unauth_account)
.await?
.expect("Code should be staged");
assert_eq!(staged, code);
Ok(())
}
#[tokio::test]
async fn test_staged_code_hash() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(
worker,
Some(dao.id().clone()),
Some(sdk_duration_from_secs(42)),
)
.await?;
// No code staged.
let staged_hash = setup
.upgradable_contract
.up_staged_code_hash(&setup.unauth_account)
.await?;
assert_eq!(staged_hash, None);
// Stage code.
let code = vec![1, 2, 3];
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res);
// Some code is staged.
let staged_hash = setup
.upgradable_contract
.up_staged_code_hash(&setup.unauth_account)
.await?
.expect("Code should be staged");
let code_hash = convert_code_to_crypto_hash(code.as_slice());
assert_eq!(staged_hash, code_hash);
Ok(())
}
#[tokio::test]
async fn test_deploy_code_without_delay() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(worker.clone(), Some(dao.id().clone()), None).await?;
// Stage some code.
let code = vec![1, 2, 3];
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res);
setup.assert_staged_code(Some(&code)).await;
// Deploy staged code.
let res = setup
.upgradable_contract
.up_deploy_code(&dao, convert_code_to_deploy_hash(&code), None)
.await?;
assert_success_with_unit_return(res);
Ok(())
}
#[tokio::test]
async fn test_deploy_code_with_hash_success() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(worker.clone(), Some(dao.id().clone()), None).await?;
// Stage some code.
let code = vec![1, 2, 3];
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res);
setup.assert_staged_code(Some(&code)).await;
// Deploy staged code.
let hash = convert_code_to_deploy_hash(&code);
let res = setup
.upgradable_contract
.up_deploy_code(&dao, hash, None)
.await?;
assert_success_with_unit_return(res);
Ok(())
}
/// Verifies failure of `up_deploy_code(hash, ...)` when `hash` does not correspond to the
/// hash of staged code.
#[tokio::test]
async fn test_deploy_code_with_hash_invalid_hash() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(worker.clone(), Some(dao.id().clone()), None).await?;
// Stage some code.
let code = vec![1, 2, 3];
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res);
setup.assert_staged_code(Some(&code)).await;
// Deployment is aborted if an invalid hash is provided.
let res = setup
.upgradable_contract
.up_deploy_code(&dao, "invalid_hash".to_owned(), None)
.await?;
let actual_hash = convert_code_to_deploy_hash(&code);
let expected_err = format!(
"Upgradable: Cannot deploy due to wrong hash: expected hash: {}",
actual_hash
);
assert_failure_with(res, &expected_err);
Ok(())
}
/// Verifies the upgrade was successful by calling a method that's available only on the upgraded
/// contract. Ensures the new contract can be deployed and state remains valid without
/// explicit state migration.
#[tokio::test]
async fn test_deploy_code_and_call_method() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(worker.clone(), Some(dao.id().clone()), None).await?;
// Verify function `is_upgraded` is not defined in the initial contract.
let res = setup.call_is_upgraded(&setup.unauth_account).await?;
assert_method_not_found_failure(res);
// Compile the other version of the contract and stage its code.
let code = common::repo::compile_project(Path::new(PROJECT_PATH_2), "upgradable_2").await?;
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res);
setup.assert_staged_code(Some(&code)).await;
// Deploy staged code.
let res = setup
.upgradable_contract
.up_deploy_code(&dao, convert_code_to_deploy_hash(&code), None)
.await?;
assert_success_with_unit_return(res);
// The newly deployed contract defines the function `is_upgraded`. Calling it successfully
// verifies the staged contract is deployed and there are no issues with state migration.
let res = setup.call_is_upgraded(&setup.unauth_account).await?;
assert_success_with(res, true);
Ok(())
}
/// Deploys a new version of the contract that requires state migration and verifies the migration
/// succeeded.
#[tokio::test]
async fn test_deploy_code_with_migration() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(worker.clone(), Some(dao.id().clone()), None).await?;
// Verify function `is_migrated` is not defined in the initial contract.
let res = setup.call_is_migrated(&setup.unauth_account).await?;
assert_method_not_found_failure(res);
// Compile the other version of the contract and stage its code.
let code = common::repo::compile_project(
Path::new(PROJECT_PATH_STATE_MIGRATION),
"upgradable_state_migration",
)
.await?;
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res);
setup.assert_staged_code(Some(&code)).await;
// Deploy staged code and call the new contract's `migrate` method.
let function_call_args = FunctionCallArgs {
function_name: "migrate".to_string(),
arguments: Vec::new(),
amount: NearToken::from_yoctonear(0),
gas: Gas::from_tgas(3),
};
let res = setup
.upgradable_contract
.up_deploy_code(
&dao,
convert_code_to_deploy_hash(&code),
Some(function_call_args),
)
.await?;
assert_success_with_unit_return(res);
// The newly deployed contract defines the function `is_migrated`. Calling it successfully
// verifies the staged contract is deployed and state migration succeeded.
let res = setup.call_is_migrated(&setup.unauth_account).await?;
assert_success_with(res, true);
Ok(())
}
/// Deploys a new version of the contract and, batched with the `DeployContractAction`, calls a
/// migration method that fails. Verifies the failure rolls back the deployment, i.e. the initial
/// code remains active.
#[tokio::test]
async fn test_deploy_code_with_migration_failure_rollback() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(worker.clone(), Some(dao.id().clone()), None).await?;
// Compile the other version of the contract and stage its code.
let code = common::repo::compile_project(
Path::new(PROJECT_PATH_STATE_MIGRATION),
"upgradable_state_migration",
)
.await?;
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res);
setup.assert_staged_code(Some(&code)).await;
// Deploy staged code and call the new contract's `migrate_with_failure` method.
let function_call_args = FunctionCallArgs {
function_name: "migrate_with_failure".to_string(),
arguments: Vec::new(),
amount: NearToken::from_yoctonear(0),
gas: Gas::from_tgas(2),
};
let res = setup
.upgradable_contract
.up_deploy_code(
&dao,
convert_code_to_deploy_hash(&code),
Some(function_call_args),
)
.await?;
assert_failure_with(res, "Failing migration on purpose");
// Verify `code` wasn't deployed by calling a function that is defined only in the initial
// contract but not in the contract corresponding to the `code`.
setup.assert_is_set_up(&setup.unauth_account).await;
Ok(())
}
/// Deploys staged code in a batch transaction with two function call actions:
///
/// 1. `up_deploy_code` with a function call to a migration method that fails
/// 2. `up_stage_code` to remove staged code from storage
///
/// The pitfall is that a failure in the promise returned by 1 does _not_ make the transaction fail
/// and 2 executes anyway.
#[tokio::test]
async fn test_deploy_code_in_batch_transaction_pitfall() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(worker.clone(), Some(dao.id().clone()), None).await?;
// Compile the other version of the contract and stage its code.
let code = common::repo::compile_project(
Path::new(PROJECT_PATH_STATE_MIGRATION),
"upgradable_state_migration",
)
.await?;
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res);
setup.assert_staged_code(Some(&code)).await;
// Construct the function call actions to be executed in a batch transaction.
// Note that we are attaching a call to `migrate_with_failure`, which will fail.
let fn_call_deploy = near_workspaces::operations::Function::new("up_deploy_code")
.args_json(json!({
"hash": convert_code_to_deploy_hash(&code),
"function_call_args": FunctionCallArgs {
function_name: "migrate_with_failure".to_string(),
arguments: Vec::new(),
amount: NearToken::from_yoctonear(0),
gas: Gas::from_tgas(2),
} }))
.gas(Gas::from_tgas(220));
let fn_call_remove_code = near_workspaces::operations::Function::new("up_stage_code")
.args_borsh(Vec::<u8>::new())
.gas(Gas::from_tgas(80));
let res = dao
.batch(setup.contract.id())
.call(fn_call_deploy)
.call(fn_call_remove_code)
.transact()
.await?;
// Here is the pitfall: Despite the failure of `migrate_with_failure`, the transaction succeeds.
// This is due to `fn_call_deploy` _successfully_ returning a promise `p`. The promise `p`
// fails, however that does not affect the result of the transaction.
assert_success_with_unit_return(res.clone());
// Verify the promise resulting from `fn_call_deploy` failed. There seems to be no public API to
// get the status of an `ExecutionOutcome`, hence `is_failure` is used in combination with debug
// formatting. Since this is test code we can use debug formatting for this purpose.
let fn_call_deploy_receipt = res
.receipt_outcomes()
.get(1)
.expect("There should be at least two receipts");
assert!(fn_call_deploy_receipt.is_failure());
assert!(format!("{:?}", fn_call_deploy_receipt).contains("Failing migration on purpose"));
// Verify `code` wasn't deployed by calling a function that is defined only in the initial
// contract but not in the contract corresponding to `code`.
setup.assert_is_set_up(&setup.unauth_account).await;
// However the staged code was removed, i.e. `fn_call_remove_code` was executed anyway.
setup.assert_staged_code(None).await;
Ok(())
}
#[tokio::test]
async fn test_deploy_code_with_delay() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let staging_duration = sdk_duration_from_secs(3);
let setup = Setup::new(
worker.clone(),
Some(dao.id().clone()),
Some(staging_duration),
)
.await?;
// Stage some code.
let code = vec![1, 2, 3];
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res);
setup.assert_staged_code(Some(&code)).await;
// Let the staging duration pass.
fast_forward_beyond(&worker, staging_duration).await;
// Deploy staged code.
let res = setup
.upgradable_contract
.up_deploy_code(&dao, convert_code_to_deploy_hash(&code), None)
.await?;
assert_success_with_unit_return(res);
Ok(())
}
#[tokio::test]
async fn test_deploy_code_with_delay_failure_too_early() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(
worker.clone(),
Some(dao.id().clone()),
Some(sdk_duration_from_secs(1024)),
)
.await?;
// Stage some code.
let code = vec![1, 2, 3];
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res);
setup.assert_staged_code(Some(&code)).await;
// Let some time pass but not enough.
fast_forward_beyond(&worker, sdk_duration_from_secs(1)).await;
// Verify trying to deploy staged code fails.
let res = setup
.upgradable_contract
.up_deploy_code(&dao, convert_code_to_deploy_hash(&code), None)
.await?;
assert_failure_with(res, ERR_MSG_DEPLOY_CODE_TOO_EARLY);
// Verify `code` wasn't deployed by calling a function that is defined only in the initial
// contract but not in the contract contract corresponding to `code`.
setup.assert_is_set_up(&setup.unauth_account).await;
Ok(())
}
#[tokio::test]
async fn test_deploy_code_permission_failure() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(worker, Some(dao.id().clone()), None).await?;
// Stage some code.
let code = vec![1, 2, 3];
let res = setup
.upgradable_contract
.up_stage_code(&dao, code.clone())
.await?;
assert_success_with_unit_return(res);
setup.assert_staged_code(Some(&code)).await;
// Only the roles passed as `code_deployers` to the `Upgradable` derive macro may successfully
// call this method.
let res = setup
.upgradable_contract
.up_deploy_code(
&setup.unauth_account,
convert_code_to_deploy_hash(&code),
None,
)
.await?;
assert_insufficient_acl_permissions(
res,
"up_deploy_code",
vec!["CodeDeployer".to_string(), "DAO".to_string()],
);
// Verify `code` wasn't deployed by calling a function that is defined only in the initial
// contract but not in the contract contract corresponding to `code`.
setup.assert_is_set_up(&setup.unauth_account).await;
Ok(())
}
/// `up_deploy_code` fails if there's no code staged.
#[tokio::test]
async fn test_deploy_code_empty_failure() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(
worker,
Some(dao.id().clone()),
Some(sdk_duration_from_secs(42)),
)
.await?;
// Verify there is no code staged.
let staged_hash = setup
.upgradable_contract
.up_staged_code_hash(&setup.unauth_account)
.await?;
assert_eq!(staged_hash, None);
// Verify failure of `up_deploy_code`.
//
// The staging timestamp is set when staging code and removed when unstaging code. So when there
// is no code staged, there is no staging timestamp. Hence the error message regarding a missing
// staging timestamp is expected.
let res = setup
.upgradable_contract
.up_deploy_code(&dao, "".to_owned(), None)
.await?;
assert_failure_with(res, ERR_MSG_NO_STAGING_TS);
Ok(())
}
#[tokio::test]
async fn test_init_staging_duration_permission_failure() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(worker, Some(dao.id().clone()), None).await?;
// Only the roles passed as `duration_initializers` to the `Upgradable` derive macro may
// successfully call this method.
let res = setup
.upgradable_contract
.up_init_staging_duration(&setup.unauth_account, sdk_duration_from_secs(23))
.await?;
assert_insufficient_acl_permissions(
res,
"up_init_staging_duration",
vec!["DurationManager".to_string(), "DAO".to_string()],
);
setup.assert_staging_duration(None).await;
Ok(())
}
#[tokio::test]
async fn test_init_staging_duration() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let setup = Setup::new(worker, Some(dao.id().clone()), None).await?;
// Verify the contract was initialized without staging duration.
setup.assert_staging_duration(None).await;
// Initialize the staging duration.
let staging_duration = sdk_duration_from_secs(42);
let res = setup
.upgradable_contract
.up_init_staging_duration(&dao, staging_duration)
.await?;
assert_success_with_unit_return(res.clone());
// Verify the staging duration was set.
setup.assert_staging_duration(Some(staging_duration)).await;
Ok(())
}
#[tokio::test]
async fn test_stage_update_staging_duration_permission_failure() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let staging_duration = sdk_duration_from_secs(42);
let setup = Setup::new(worker, Some(dao.id().clone()), Some(staging_duration)).await?;
// Only the roles passed as `duration_update_stagers` to the `Upgradable` derive macro may
// successfully call this method.
let res = setup
.upgradable_contract
.up_stage_update_staging_duration(&setup.unauth_account, sdk_duration_from_secs(23))
.await?;
assert_insufficient_acl_permissions(
res,
"up_stage_update_staging_duration",
vec!["DurationManager".to_string(), "DAO".to_string()],
);
// Verify no duration was staged.
setup.assert_new_staging_duration(None).await;
Ok(())
}
#[tokio::test]
async fn test_stage_update_staging_duration() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let staging_duration = sdk_duration_from_secs(42);
let setup = Setup::new(worker, Some(dao.id().clone()), Some(staging_duration)).await?;
// Initially there's no new staging duration staged and no timestamp set.
setup.assert_new_staging_duration(None).await;
setup.assert_new_duration_staging_timestamp(None).await;
// Stage a new duration.
let new_staging_duration = sdk_duration_from_secs(23);
let res = setup
.upgradable_contract
.up_stage_update_staging_duration(&dao, new_staging_duration)
.await?;
assert_success_with_unit_return(res.clone());
// Verify the new duration was staged.
setup
.assert_new_staging_duration(Some(new_staging_duration))
.await;
// Verify timestamp for the staging duration update.
let expected_timestamp = setup
.expected_staging_timestamp(res, staging_duration)
.await;
setup
.assert_new_duration_staging_timestamp(Some(expected_timestamp))
.await;
Ok(())
}
#[tokio::test]
async fn test_apply_update_staging_duration_permission_failure() -> anyhow::Result<()> {
let worker = near_workspaces::sandbox().await?;
let dao = worker.dev_create_account().await?;
let staging_duration = sdk_duration_from_secs(21);
let setup = Setup::new(worker, Some(dao.id().clone()), Some(staging_duration)).await?;
// Verify the initial staging duration.
setup.assert_staging_duration(Some(staging_duration)).await;
// Stage a new duration.
let new_staging_duration = sdk_duration_from_secs(23);
let res = setup
.upgradable_contract
.up_stage_update_staging_duration(&dao, new_staging_duration)
.await?;
assert_success_with_unit_return(res.clone());
// Let the staging duration pass.
fast_forward_beyond(&setup.worker, staging_duration).await;
// Only the roles passed as `duration_update_appliers` to the `Upgradable` derive macro may
// successfully call this method.
let res = setup
.upgradable_contract
.up_apply_update_staging_duration(&setup.unauth_account)
.await?;
assert_insufficient_acl_permissions(
res,