-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonboard_asset.rs
More file actions
1689 lines (1632 loc) · 69.8 KB
/
onboard_asset.rs
File metadata and controls
1689 lines (1632 loc) · 69.8 KB
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
use crate::core::error::ContractError;
use crate::core::msg::ExecuteMsg;
use crate::core::state::{load_asset_definition_by_type_v3, STATE_V2};
use crate::core::types::access_route::AccessRoute;
use crate::core::types::asset_identifier::AssetIdentifier;
use crate::core::types::asset_onboarding_status::AssetOnboardingStatus;
use crate::core::types::asset_scope_attribute::AssetScopeAttribute;
use crate::service::asset_meta_repository::AssetMetaRepository;
use crate::service::deps_manager::DepsManager;
use crate::service::message_gathering_service::MessageGatheringService;
use crate::util::aliases::{AssetResult, EntryPointResponse};
use crate::util::contract_helpers::check_funds_are_empty;
use crate::util::event_attributes::{EventAttributes, EventType};
use crate::util::functions::generate_os_gateway_grant_id;
use crate::util::traits::OptionExtensions;
use cosmwasm_std::{Env, MessageInfo, Response};
use os_gateway_contract_attributes::OsGatewayAttributeGenerator;
use provwasm_std::types::provenance::metadata::v1::MetadataQuerier;
use result_extensions::ResultExtensions;
/// A transformation of [ExecuteMsg::OnboardAsset](crate::core::msg::ExecuteMsg::OnboardAsset)
/// for ease of use in the underlying [onboard_asset](self::onboard_asset) function.
///
/// # Parameters
///
/// * `identifier` An instance of the asset identifier enum that helps the contract identify which
/// scope that the requestor is referring to in the request.
/// * `asset_type` [AssetDefinitionV3's](crate::core::types::asset_definition::AssetDefinitionV3) unique
/// [asset_type](crate::core::types::asset_definition::AssetDefinitionV3::asset_type) value. This
/// value must correspond to an existing type in the contract's internal storage, or the request
/// for onboarding will be rejected.
/// * `verifier_address` The bech32 Provenance Blockchain [address](crate::core::types::verifier_detail::VerifierDetailV2::address)
/// of a [VerifierDetailV2](crate::core::types::verifier_detail::VerifierDetailV2) on the [AssetDefinitionV3](crate::core::types::asset_definition::AssetDefinitionV3)
/// referred to by the [asset_type](self::OnboardAssetV1::asset_type) property. If the address does
/// not refer to any existing verifier detail, the request will be rejected.
/// * `access_routes` A vector of access routes to be added to the generated [AssetScopeAttribute's](crate::core::types::asset_scope_attribute::AssetScopeAttribute)
/// [AccessDefinition](crate::core::types::access_definition::AccessDefinition) for the [Requestor](crate::core::types::access_definition::AccessDefinitionType::Requestor)
/// entry.
/// * `add_os_gateway_permission` An optional parameter that will cause the emitted events to
/// include values that signal to any [Object Store Gateway](https://github.com/FigureTechnologies/object-store-gateway)
/// watching the events that the selected verifier has permission to inspect the identified scope's
/// records via fetch routes. This behavior defaults to TRUE.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OnboardAssetV1 {
pub identifier: AssetIdentifier,
pub asset_type: String,
pub verifier_address: String,
pub access_routes: Vec<AccessRoute>,
pub add_os_gateway_permission: bool,
}
impl OnboardAssetV1 {
/// Attempts to create an instance of this struct from a provided execute msg. If the provided
/// value is not of the [OnboardAsset](crate::core::msg::ExecuteMsg::OnboardAsset)
/// variant, then an [InvalidMessageType](crate::core::error::ContractError::InvalidMessageType)
/// error will be returned.
///
/// # Parameters
///
/// * `msg` An execute msg provided by the contract's [execute](crate::contract::execute) function.
pub fn from_execute_msg(msg: ExecuteMsg) -> AssetResult<OnboardAssetV1> {
match msg {
ExecuteMsg::OnboardAsset {
identifier,
asset_type,
verifier_address,
access_routes,
add_os_gateway_permission,
} => OnboardAssetV1 {
identifier: identifier.to_asset_identifier()?,
asset_type,
verifier_address,
access_routes: access_routes.unwrap_or_default(),
add_os_gateway_permission: add_os_gateway_permission.unwrap_or(true),
}
.to_ok(),
_ => ContractError::InvalidMessageType {
expected_message_type: "ExecuteMsg::OnboardAsset".to_string(),
}
.to_err(),
}
}
}
/// The function used by [execute](crate::contract::execute) when an [ExecuteMsg::OnboardAsset](crate::core::msg::ExecuteMsg::OnboardAsset)
/// message is provided. Attempts to verify that a provided Provenance Blockchain Metadata Scope is
/// properly formed on a basic level, and then adds an [AssetScopeAttribute](crate::core::types::asset_scope_attribute::AssetScopeAttribute)
/// to it as a Provenance Blockchain Attribute.
///
/// # Parameters
///
/// * `repository` A helper collection of traits that allows complex lookups of scope values and
/// emits messages to construct the process of onboarding as a collection of messages to produce
/// in the function's result.
/// * `info` A message information object provided by the cosmwasm framework. Describes the sender
/// of the instantiation message, as well as the funds provided as an amount during the transaction.
/// * `msg` An instance of the onboard asset v1 struct, provided by conversion from an
/// [ExecuteMsg](crate::core::msg::ExecuteMsg).
pub fn onboard_asset<'a, T>(
repository: T,
env: Env,
info: MessageInfo,
msg: OnboardAssetV1,
) -> EntryPointResponse
where
T: AssetMetaRepository + MessageGatheringService + DepsManager<'a>,
{
let asset_identifiers = msg.identifier.to_identifiers()?;
// get asset definition config for type, or error if not present
let asset_definition = match repository
.use_deps(|d| load_asset_definition_by_type_v3(d.storage, &msg.asset_type))
{
Ok(state) => {
if !state.enabled {
return ContractError::AssetTypeDisabled {
asset_type: msg.asset_type,
}
.to_err();
}
state
}
Err(_) => {
return ContractError::UnsupportedAssetType {
asset_type: msg.asset_type,
}
.to_err()
}
};
// verify prescribed verifier is present as a verifier in asset definition
let verifier_config = asset_definition.get_verifier_detail(&msg.verifier_address)?;
// verify no funds are sent, as msg fee handles fees
check_funds_are_empty(&info)?;
// verify asset (scope) exists
let error_response = ContractError::AssetNotFound {
scope_address: asset_identifiers.scope_address.to_owned(),
}
.to_err();
let scope = match repository.use_deps(|d| {
MetadataQuerier::new(&d.querier).scope(
asset_identifiers.scope_address.to_owned(),
String::from(""),
String::from(""),
false,
false,
false,
false,
)
}) {
Err(..) => return error_response,
Ok(scope_response) => match scope_response.scope {
Some(scope_wrapper) => match scope_wrapper.scope {
Some(scope) => scope,
None => return error_response,
},
None => return error_response,
},
};
let state = repository.use_deps(|deps| STATE_V2.load(deps.storage))?;
// verify that the sender of this message is a scope owner
if !scope
.owners
.iter()
.any(|owner| owner.address == info.sender.as_str())
{
return ContractError::Unauthorized {
explanation: "sender address does not own the scope".to_string(),
}
.to_err();
}
// no need to verify records during a test run - this check makes testing the contract a pretty lengthy process
if !state.is_test {
// pull scope records for validation - if no records exist on the scope, the querier will produce an error here
let records = repository
.use_deps(|d| {
MetadataQuerier::new(&d.querier).records(
String::from(""),
asset_identifiers.scope_address.to_owned(),
String::from(""),
String::from(""),
false,
false,
false,
false,
)
})?
.records;
// verify scope has at least one record that is not empty
if !records
.into_iter()
.any(|record_wrapper| match record_wrapper.record {
Some(record) => !record.outputs.is_empty(),
None => false,
})
{
return ContractError::InvalidScope {
explanation: format!(
"cannot onboard scope [{}]. scope must have at least one non-empty record",
asset_identifiers.scope_address.to_owned(),
),
}
.to_err();
}
}
let new_asset_attribute = AssetScopeAttribute::new(
&msg.identifier,
&msg.asset_type,
&info.sender,
&msg.verifier_address,
AssetOnboardingStatus::Pending.to_some(),
msg.access_routes,
)?;
// check to see if the attribute already exists, and determine if this is a fresh onboard or a subsequent one
let is_retry = if let Some(existing_attribute) =
repository.try_get_asset_by_asset_type(&asset_identifiers.scope_address, &msg.asset_type)?
{
match existing_attribute.onboarding_status {
// If the attribute indicates that the asset is approved, then it's already fully onboarded and verified
AssetOnboardingStatus::Approved => {
return ContractError::AssetAlreadyOnboarded {
scope_address: asset_identifiers.scope_address,
asset_type: msg.asset_type,
}
.to_err();
}
// If the attribute indicates that the asset is pending, then it's currently waiting for verification
AssetOnboardingStatus::Pending => {
return ContractError::AssetPendingVerification {
scope_address: existing_attribute.scope_address,
asset_type: msg.asset_type,
verifier_address: existing_attribute.verifier_address.to_string(),
}
.to_err()
}
// If the attribute indicates that the asset is pending, then it's been denied by a verifier, and this is a secondary
// attempt to onboard the asset
AssetOnboardingStatus::Denied => true,
}
} else {
// If no scope attribute exists, it's safe to simply add the attribute to the scope
false
};
// store asset metadata in contract storage, with assigned verifier and provided fee (in case fee changes between onboarding and verification)
repository.onboard_asset(&env, &new_asset_attribute, &verifier_config, is_retry)?;
let response = Response::new()
.add_attributes(
EventAttributes::for_asset_event(
EventType::OnboardAsset,
&msg.asset_type,
&asset_identifiers.scope_address,
)
.set_verifier(&msg.verifier_address)
.set_scope_owner(info.sender)
.set_new_asset_onboarding_status(&new_asset_attribute.onboarding_status),
)
.add_messages(repository.get_messages());
let response = if msg.add_os_gateway_permission {
response.add_attributes(
OsGatewayAttributeGenerator::access_grant(
&asset_identifiers.scope_address,
msg.verifier_address,
)
.with_access_grant_id(generate_os_gateway_grant_id(
msg.asset_type,
asset_identifiers.scope_address,
)),
)
} else {
response
};
response.to_ok()
}
#[cfg(test)]
mod tests {
use cosmwasm_std::testing::{mock_env, MOCK_CONTRACT_ADDR};
use cosmwasm_std::{coins, from_json, Response, Uint128};
use os_gateway_contract_attributes::{OS_GATEWAY_EVENT_TYPES, OS_GATEWAY_KEYS};
use provwasm_mocks::mock_provenance_dependencies;
use provwasm_std::types::provenance::attribute::v1::{
AttributeType, MsgAddAttributeRequest, MsgUpdateAttributeRequest, QueryAttributeRequest,
QueryAttributeResponse, QueryAttributesRequest, QueryAttributesResponse,
};
use provwasm_std::types::provenance::metadata::v1::process::ProcessId;
use provwasm_std::types::provenance::metadata::v1::{
Process, Record, RecordWrapper, RecordsRequest, RecordsResponse, ScopeRequest,
ScopeResponse, ScopeWrapper,
};
use provwasm_std::types::provenance::msgfees::v1::MsgAssessCustomMsgFeeRequest;
use crate::contract::execute;
use crate::core::msg::ExecuteMsg::OnboardAsset;
use crate::core::state::{load_asset_definition_by_type_v3, load_fee_payment_detail};
use crate::core::types::asset_definition::{AssetDefinitionInputV3, AssetDefinitionV3};
use crate::core::types::fee_destination::FeeDestinationV2;
use crate::core::types::fee_payment_detail::FeePaymentDetail;
use crate::core::types::onboarding_cost::OnboardingCost;
use crate::core::types::subsequent_classification_detail::SubsequentClassificationDetail;
use crate::core::types::verifier_detail::VerifierDetailV2;
use crate::execute::add_asset_definition::{add_asset_definition, AddAssetDefinitionV1};
use crate::execute::add_asset_verifier::{add_asset_verifier, AddAssetVerifierV1};
use crate::testutil::msg_utilities::{
test_aggregate_msg_fees_are_charged, test_no_money_moved_in_response,
};
use crate::testutil::test_constants::{
DEFAULT_ONBOARDING_COST, DEFAULT_RETRY_COST, DEFAULT_SECONDARY_ASSET_TYPE,
};
use crate::testutil::test_utilities::{
assert_single_item, build_attribute, get_default_asset_definition_input,
get_default_verifier_detail, mock_single_scope_attribute, setup_no_attribute_response,
single_attribute_for_key,
};
use crate::util::constants::{NEW_ASSET_ONBOARDING_STATUS_KEY, NHASH};
use crate::util::functions::{
generate_os_gateway_grant_id, try_into_add_attribute_request, try_into_custom_fee_request,
try_into_update_attribute_request,
};
use crate::util::traits::OptionExtensions;
use crate::{
core::{
error::ContractError,
types::{
access_definition::{AccessDefinition, AccessDefinitionType},
asset_identifier::AssetIdentifier,
asset_onboarding_status::AssetOnboardingStatus,
asset_scope_attribute::AssetScopeAttribute,
},
},
execute::toggle_asset_definition::{toggle_asset_definition, ToggleAssetDefinitionV1},
service::{
asset_meta_repository::AssetMetaRepository, asset_meta_service::AssetMetaService,
message_gathering_service::MessageGatheringService,
},
testutil::{
onboard_asset_helpers::{test_onboard_asset, TestOnboardAsset},
test_constants::{
DEFAULT_ADMIN_ADDRESS, DEFAULT_ASSET_TYPE, DEFAULT_CONTRACT_BASE_NAME,
DEFAULT_RECORD_SPEC_ADDRESS, DEFAULT_SCOPE_ADDRESS, DEFAULT_SENDER_ADDRESS,
DEFAULT_SESSION_ADDRESS, DEFAULT_VERIFIER_ADDRESS,
},
test_utilities::{
empty_mock_info, get_default_access_routes, get_default_scope,
mock_info_with_funds, mock_info_with_nhash, setup_test_suite,
test_instantiate_success, InstArgs,
},
verify_asset_helpers::{test_verify_asset, TestVerifyAsset},
},
util::{
constants::{
ASSET_EVENT_TYPE_KEY, ASSET_SCOPE_ADDRESS_KEY, ASSET_TYPE_KEY, SCOPE_OWNER_KEY,
VERIFIER_ADDRESS_KEY,
},
functions::generate_asset_attribute_name,
},
};
use super::{onboard_asset, OnboardAssetV1};
#[test]
fn test_onboard_asset_errors_on_unsupported_asset_type() {
let mut deps = mock_provenance_dependencies();
setup_test_suite(&mut deps, &InstArgs::default());
let err = onboard_asset(
AssetMetaService::new(deps.as_mut()),
mock_env(),
mock_info_with_nhash(DEFAULT_SENDER_ADDRESS, 1000),
OnboardAssetV1 {
identifier: AssetIdentifier::scope_address(DEFAULT_SCOPE_ADDRESS),
asset_type: "bogus".into(),
verifier_address: DEFAULT_VERIFIER_ADDRESS.into(),
access_routes: vec![],
add_os_gateway_permission: false,
},
)
.unwrap_err();
match err {
ContractError::UnsupportedAssetType { asset_type } => {
assert_eq!(
"bogus", asset_type,
"the unsupported asset type message should reflect the type provided"
)
}
_ => panic!(
"unexpected error when unsupported asset type provided: {:?}",
err
),
}
}
#[test]
fn test_onboard_asset_errors_on_disabled_asset_type() {
let mut deps = mock_provenance_dependencies();
setup_test_suite(&mut deps, &InstArgs::default());
toggle_asset_definition(
deps.as_mut(),
empty_mock_info(DEFAULT_ADMIN_ADDRESS),
ToggleAssetDefinitionV1::new(DEFAULT_ASSET_TYPE, false),
)
.expect("toggling the asset definition to be disabled should succeed");
let err = onboard_asset(
AssetMetaService::new(deps.as_mut()),
mock_env(),
mock_info_with_nhash(DEFAULT_SENDER_ADDRESS, 1000),
OnboardAssetV1 {
identifier: AssetIdentifier::scope_address(DEFAULT_SCOPE_ADDRESS),
asset_type: DEFAULT_ASSET_TYPE.into(),
verifier_address: DEFAULT_VERIFIER_ADDRESS.into(),
access_routes: vec![],
add_os_gateway_permission: false,
},
)
.unwrap_err();
assert!(
matches!(err, ContractError::AssetTypeDisabled { .. }),
"the request should be rejected for a disabled asset type, but got: {:?}",
err,
);
}
#[test]
fn test_onboard_asset_errors_on_unsupported_verifier() {
let mut deps = mock_provenance_dependencies();
setup_test_suite(&mut deps, &InstArgs::default());
let err = onboard_asset(
AssetMetaService::new(deps.as_mut()),
mock_env(),
empty_mock_info(DEFAULT_SENDER_ADDRESS),
OnboardAssetV1 {
identifier: AssetIdentifier::scope_address(DEFAULT_SCOPE_ADDRESS),
asset_type: DEFAULT_ASSET_TYPE.into(),
verifier_address: DEFAULT_VERIFIER_ADDRESS.to_string() + "bogus".into(),
access_routes: vec![],
add_os_gateway_permission: false,
},
)
.unwrap_err();
match err {
ContractError::UnsupportedVerifier {
asset_type,
verifier_address,
} => {
assert_eq!(
DEFAULT_ASSET_TYPE, asset_type,
"the unsupported verifier message should reflect the asset type provided"
);
assert_eq!(
DEFAULT_VERIFIER_ADDRESS.to_string() + "bogus".into(),
verifier_address,
"the unsupported verifier message should reflect the verifier address provided"
);
}
_ => panic!(
"unexpected error when unsupported verifier provided: {:?}",
err
),
}
}
#[test]
fn test_onboard_asset_errors_on_funds_provided() {
let mut deps = mock_provenance_dependencies();
setup_test_suite(&mut deps, &InstArgs::default());
let err = onboard_asset(
AssetMetaService::new(deps.as_mut()),
mock_env(),
mock_info_with_funds(DEFAULT_SENDER_ADDRESS, &coins(100, NHASH)),
OnboardAssetV1 {
identifier: AssetIdentifier::scope_address(DEFAULT_SCOPE_ADDRESS),
asset_type: DEFAULT_ASSET_TYPE.into(),
verifier_address: DEFAULT_VERIFIER_ADDRESS.to_string(),
access_routes: vec![],
add_os_gateway_permission: false,
},
)
.unwrap_err();
match err {
ContractError::InvalidFunds(message) => {
assert_eq!(
"route requires no funds be present", message,
"the error should indicate that no funds should be sent when onboarding an asset",
);
}
_ => panic!(
"unexpected error when unsupported asset type provided: {:?}",
err
),
}
}
#[test]
fn test_onboard_asset_errors_on_asset_not_found() {
let mut deps = mock_provenance_dependencies();
setup_test_suite(&mut deps, &InstArgs::default());
setup_no_attribute_response(&mut deps, None);
// Some random scope address unrelated to the default scope address, which is mocked during setup_test_suite
let bogus_scope_address = "scope1qp9szrgvvpy5ph5fmxrzs2euyltssfc3lu";
ScopeRequest::mock_response(
&mut deps.querier,
ScopeResponse {
scope: None,
sessions: vec![],
records: vec![],
request: None,
},
);
let err = onboard_asset(
AssetMetaService::new(deps.as_mut()),
mock_env(),
empty_mock_info(DEFAULT_SENDER_ADDRESS),
OnboardAssetV1 {
identifier: AssetIdentifier::scope_address(bogus_scope_address),
asset_type: DEFAULT_ASSET_TYPE.into(),
verifier_address: DEFAULT_VERIFIER_ADDRESS.to_string(),
access_routes: vec![],
add_os_gateway_permission: false,
},
)
.unwrap_err();
match err {
ContractError::AssetNotFound { scope_address } => {
assert_eq!(
bogus_scope_address,
scope_address.as_str(),
"the asset not found message should reflect that the asset uuid was not found"
);
}
_ => panic!(
"unexpected error when unsupported asset type provided: {:?}",
err
),
}
}
#[test]
fn test_onboard_asset_errors_on_asset_pending_status() {
let mut deps = mock_provenance_dependencies();
setup_test_suite(&mut deps, &InstArgs::default());
setup_no_attribute_response(&mut deps, None);
test_onboard_asset(&mut deps, TestOnboardAsset::default()).unwrap();
let err = onboard_asset(
AssetMetaService::new(deps.as_mut()),
mock_env(),
empty_mock_info(DEFAULT_SENDER_ADDRESS),
OnboardAssetV1 {
identifier: AssetIdentifier::scope_address(DEFAULT_SCOPE_ADDRESS),
asset_type: DEFAULT_ASSET_TYPE.into(),
verifier_address: DEFAULT_VERIFIER_ADDRESS.to_string(),
access_routes: vec![],
add_os_gateway_permission: false,
},
)
.unwrap_err();
match err {
ContractError::AssetPendingVerification {
scope_address,
asset_type,
verifier_address,
} => {
assert_eq!(
DEFAULT_SCOPE_ADDRESS,
scope_address,
"the asset pending verification message should reflect that the asset address is awaiting verification"
);
assert_eq!(
DEFAULT_ASSET_TYPE,
asset_type,
"the asset pending verification message should reflect the asset type for which the asset address is awaiting verification"
);
assert_eq!(
DEFAULT_VERIFIER_ADDRESS,
verifier_address,
"the asset pending verification message should reflect that the asset is waiting to be verified by the default verifier",
);
}
_ => panic!(
"unexpected error when unsupported asset type provided: {:?}",
err
),
}
}
#[test]
fn test_onboard_asset_errors_on_asset_approved_status() {
let mut deps = mock_provenance_dependencies();
let instantiate_args = InstArgs::default();
setup_test_suite(&mut deps, &instantiate_args);
setup_no_attribute_response(&mut deps, None);
test_onboard_asset(&mut deps, TestOnboardAsset::default()).unwrap();
test_verify_asset(&mut deps, &instantiate_args.env, TestVerifyAsset::default()).unwrap();
let err = onboard_asset(
AssetMetaService::new(deps.as_mut()),
mock_env(),
empty_mock_info(DEFAULT_SENDER_ADDRESS),
TestOnboardAsset::default_onboard_asset(),
)
.unwrap_err();
match err {
ContractError::AssetAlreadyOnboarded {
scope_address,
asset_type,
} => {
assert_eq!(
DEFAULT_SCOPE_ADDRESS,
scope_address,
"the asset already onboarded message should reflect that the asset address was already onboarded",
);
assert_eq!(
DEFAULT_ASSET_TYPE,
asset_type,
"the asset already onboarded message should reflect the asswet type for which the asset address was already onboarded",
);
}
_ => panic!(
"unexpected error encountered when trying to board a verified asset: {:?}",
err
),
};
}
#[test]
fn test_onboard_asset_errors_on_no_records() {
let mut deps = mock_provenance_dependencies();
test_instantiate_success(deps.as_mut(), &InstArgs::default());
// Setup the default scope as the result value of a scope query, but don't establish any records
ScopeRequest::mock_response(
&mut deps.querier,
ScopeResponse {
scope: Some(ScopeWrapper {
scope: Some(get_default_scope()),
scope_id_info: None,
scope_spec_id_info: None,
}),
sessions: vec![],
records: vec![],
request: None,
},
);
RecordsRequest::mock_response(
&mut deps.querier,
RecordsResponse {
scope: None,
sessions: vec![],
records: vec![],
request: None,
},
);
let err = onboard_asset(
AssetMetaService::new(deps.as_mut()),
mock_env(),
empty_mock_info(DEFAULT_SENDER_ADDRESS),
OnboardAssetV1 {
identifier: AssetIdentifier::scope_address(DEFAULT_SCOPE_ADDRESS),
asset_type: DEFAULT_ASSET_TYPE.into(),
verifier_address: DEFAULT_VERIFIER_ADDRESS.to_string(),
access_routes: vec![],
add_os_gateway_permission: false,
},
)
.unwrap_err();
match err {
ContractError::InvalidScope { explanation } => {
assert!(
explanation.contains("scope must have at least one non-empty record"),
"the message should denote that the issue was related to the scope not having any records",
);
},
_ => panic!("unexpected ContractError encountered when onboarding a scope with no records: {:?}", err),
};
}
#[test]
fn test_onboard_asset_succeeds_on_no_records_in_test_mode() {
let mut deps = mock_provenance_dependencies();
test_instantiate_success(
deps.as_mut(),
&InstArgs {
is_test: true,
..Default::default()
},
);
// Setup the default scope as the result value of a scope query, but don't establish any records
ScopeRequest::mock_response(
&mut deps.querier,
ScopeResponse {
scope: Some(ScopeWrapper {
scope: Some(get_default_scope()),
scope_id_info: None,
scope_spec_id_info: None,
}),
sessions: vec![],
records: vec![],
request: None,
},
);
setup_no_attribute_response(&mut deps, None);
onboard_asset(
AssetMetaService::new(deps.as_mut()),
mock_env(),
empty_mock_info(DEFAULT_SENDER_ADDRESS),
OnboardAssetV1 {
identifier: AssetIdentifier::scope_address(DEFAULT_SCOPE_ADDRESS),
asset_type: DEFAULT_ASSET_TYPE.into(),
verifier_address: DEFAULT_VERIFIER_ADDRESS.to_string(),
access_routes: vec![],
add_os_gateway_permission: false,
},
)
.expect("onboarding should succeed due to test mode being enabled");
}
#[test]
fn test_onboard_asset_errors_on_empty_records() {
let mut deps = mock_provenance_dependencies();
test_instantiate_success(deps.as_mut(), &InstArgs::default());
// Setup the default scope and add a record, but make sure the record is not formed properly
let scope = get_default_scope();
let malformed_record = vec![RecordWrapper {
record: Some(Record {
name: "record-name".to_string(),
session_id: DEFAULT_SESSION_ADDRESS.to_string().into(),
specification_id: DEFAULT_RECORD_SPEC_ADDRESS.to_string().into(),
process: Some(Process {
process_id: Some(ProcessId::Address(String::new())),
method: String::new(),
name: String::new(),
}),
inputs: vec![],
outputs: vec![],
}),
record_id_info: None,
record_spec_id_info: None,
}];
ScopeRequest::mock_response(
&mut deps.querier,
ScopeResponse {
scope: Some(ScopeWrapper {
scope: Some(scope.clone()),
scope_id_info: None,
scope_spec_id_info: None,
}),
sessions: vec![],
records: malformed_record.to_owned(),
request: None,
},
);
RecordsRequest::mock_response(
&mut deps.querier,
RecordsResponse {
scope: None,
sessions: vec![],
records: malformed_record,
request: None,
},
);
let err = onboard_asset(
AssetMetaService::new(deps.as_mut()),
mock_env(),
empty_mock_info(DEFAULT_SENDER_ADDRESS),
OnboardAssetV1 {
identifier: AssetIdentifier::scope_address(DEFAULT_SCOPE_ADDRESS),
asset_type: DEFAULT_ASSET_TYPE.into(),
verifier_address: DEFAULT_VERIFIER_ADDRESS.to_string(),
access_routes: vec![],
add_os_gateway_permission: false,
},
)
.unwrap_err();
assert!(
matches!(err, ContractError::InvalidScope { .. }),
"expected the error to indicate that the scope was invalid for records, but got: {:?}",
err,
);
}
#[test]
fn test_onboard_asset_succeeds_for_empty_records_in_test_mode() {
let mut deps = mock_provenance_dependencies();
test_instantiate_success(
deps.as_mut(),
&InstArgs {
is_test: true,
..Default::default()
},
);
// Setup the default scope and add a record, but make sure the record is not formed properly
let scope = get_default_scope();
ScopeRequest::mock_response(
&mut deps.querier,
ScopeResponse {
scope: Some(ScopeWrapper {
scope: Some(scope.clone()),
scope_id_info: None,
scope_spec_id_info: None,
}),
sessions: vec![],
records: vec![RecordWrapper {
record: Some(Record {
name: "record-name".to_string(),
session_id: DEFAULT_SESSION_ADDRESS.to_string().into(),
specification_id: DEFAULT_RECORD_SPEC_ADDRESS.to_string().into(),
process: Some(Process {
process_id: Some(ProcessId::Address(String::new())),
method: String::new(),
name: String::new(),
}),
inputs: vec![],
outputs: vec![],
}),
record_id_info: None,
record_spec_id_info: None,
}],
request: None,
},
);
setup_no_attribute_response(&mut deps, None);
onboard_asset(
AssetMetaService::new(deps.as_mut()),
mock_env(),
empty_mock_info(DEFAULT_SENDER_ADDRESS),
OnboardAssetV1 {
identifier: AssetIdentifier::scope_address(DEFAULT_SCOPE_ADDRESS),
asset_type: DEFAULT_ASSET_TYPE.into(),
verifier_address: DEFAULT_VERIFIER_ADDRESS.to_string(),
access_routes: vec![],
add_os_gateway_permission: false,
},
)
.expect("onboarding should succeed due to test mode being enabled");
}
#[test]
fn test_onboard_asset_success() {
let mut deps = mock_provenance_dependencies();
setup_test_suite(&mut deps, &InstArgs::default());
setup_no_attribute_response(&mut deps, None);
let result = onboard_asset(
AssetMetaService::new(deps.as_mut()),
mock_env(),
empty_mock_info(DEFAULT_SENDER_ADDRESS),
OnboardAssetV1 {
identifier: AssetIdentifier::scope_address(DEFAULT_SCOPE_ADDRESS),
asset_type: DEFAULT_ASSET_TYPE.into(),
verifier_address: DEFAULT_VERIFIER_ADDRESS.to_string(),
access_routes: get_default_access_routes(),
add_os_gateway_permission: false,
},
)
.unwrap();
let fee_payment_result = load_fee_payment_detail(
deps.as_ref().storage,
DEFAULT_SCOPE_ADDRESS,
DEFAULT_ASSET_TYPE,
);
if let Err(_) = fee_payment_result {
panic!("fee payment detail should be stored for onboarded asset")
}
assert_eq!(
2,
result.messages.len(),
"Onboarding should produce the correct number of messages"
);
result.messages.iter().for_each(|msg| {
if let Some(add_attribute_request) = try_into_add_attribute_request(&msg.msg) {
let MsgAddAttributeRequest {
name,
value,
..
} = add_attribute_request;
assert_eq!(
generate_asset_attribute_name(DEFAULT_ASSET_TYPE, DEFAULT_CONTRACT_BASE_NAME),
name,
"bound asset name should match what is expected for the asset_type"
);
let deserialized: AssetScopeAttribute = from_json(value).unwrap();
assert_eq!(
DEFAULT_ASSET_TYPE.to_string(),
deserialized.asset_type,
"Asset type in attribute should match what was provided at onboarding"
);
assert_eq!(
AssetOnboardingStatus::Pending,
deserialized.onboarding_status,
"Onboarding status should initially be Pending"
);
assert_eq!(
1,
deserialized.access_definitions.len(),
"Provided access route should be set upon onboarding"
);
assert_eq!(
&AccessDefinition {
owner_address: DEFAULT_SENDER_ADDRESS.to_string(),
access_routes: get_default_access_routes(),
definition_type: AccessDefinitionType::Requestor,
},
deserialized.access_definitions.first().unwrap(),
"Proper access route should be set upon onboarding"
);
} else if let Some(custom_fee_request) = try_into_custom_fee_request(&msg.msg) {
let MsgAssessCustomMsgFeeRequest {
name,
amount,
recipient,
from,
..
} = custom_fee_request;
assert_eq!(
DEFAULT_ONBOARDING_COST,
amount.expect("fee should have amount defined").amount.parse().expect("amount should be parseable"),
"double the default verifier cost should be included in the fee msg to account for the provenance cut",
);
assert_ne!(
name,
String::from(""),
"the fee message should include a fee name",
);
assert_eq!(
MOCK_CONTRACT_ADDR,
from.as_str(),
"the fee message should always be sent from the contract's address",
);
assert_eq!(
MOCK_CONTRACT_ADDR,
recipient.to_owned().as_str(),
"the contract's address should be the recipient of the fee",
);
} else {
panic!("Unexpected message from onboard_asset: {:?}", msg)
}
});
assert_onboard_response_attributes_are_correct(&result, false);
}
#[test]
fn test_onboarding_asset_with_free_onboarding_cost() {
let mut deps = mock_provenance_dependencies();
// Set up the contract as normal, but make onboarding free
setup_test_suite(
&mut deps,
&InstArgs {
asset_definitions: vec![AssetDefinitionInputV3 {
verifiers: vec![VerifierDetailV2 {
onboarding_cost: Uint128::zero(),
..get_default_verifier_detail()
}],
..get_default_asset_definition_input()
}],
..InstArgs::default()
},
);
setup_no_attribute_response(&mut deps, None);
let response = test_onboard_asset(&mut deps, TestOnboardAsset::default()).unwrap();
test_no_money_moved_in_response(
&response,
"no funds should be sent when onboarding with a free onboarding cost",
);
}
#[test]
fn test_onboard_asset_retry_success() {
let mut deps = mock_provenance_dependencies();
let instantiate_args = InstArgs::default();
setup_test_suite(&mut deps, &instantiate_args);
setup_no_attribute_response(&mut deps, None);
test_onboard_asset(&mut deps, TestOnboardAsset::default()).unwrap();
let payment_detail_before_retry = load_fee_payment_detail(
deps.as_ref().storage,
DEFAULT_SCOPE_ADDRESS,
DEFAULT_ASSET_TYPE,
)
.expect("a fee payment detail should be stored for the asset after onboarding");
test_verify_asset(
&mut deps,
&instantiate_args.env,
TestVerifyAsset::default_with_success(false),
)