-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
executable file
·2113 lines (1752 loc) · 71.7 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_attr(not(feature = "std"), no_std)]
#[ink::contract]
mod asset_co2_emissions {
use ink::prelude::collections::{BTreeMap, BTreeSet};
use ink::prelude::vec::Vec;
use ink::storage::Mapping;
// Max size of the Metadata vector.
pub const MAX_METADATA_LENGTH: u16 = 1024; // 1KB
// Max CO2 Emissions per Asset.
pub const MAX_EMISSIONS_PER_ASSET: u8 = 100;
// Max size of DataSource for CO2 Emission record.
pub const MAX_DATA_SOURCE_LENGTH: u8 = 128;
/// Asset ID type.
pub type AssetId = u128;
// Metadata represented by a vector of bytes/characters.
pub type Metadata = Vec<u8>;
// CO2 Emissions Data Source represented by vector of bytes/characters.
pub type DataSource = Vec<u8>;
// Optional argument for referencing a parent asset that is split into child assets.
pub type ParentDetails = Option<AssetId>;
// The type returned when querying for an Asset.
#[derive(Debug, PartialEq, Clone, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct AssetDetails {
asset_id: AssetId,
metadata: Metadata,
emissions: Vec<CO2Emissions>,
parent: ParentDetails,
}
#[derive(Copy, Clone, Debug, PartialEq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
enum EmissionsCategory {
Process,
Transport,
Upstream,
}
#[derive(Clone, Debug, PartialEq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct CO2Emissions {
// Type of CO2 Emissions (bucket).
category: EmissionsCategory,
// Emissions source of data.
data_source: DataSource,
// If CO2 Emissions item is balanced (per record).
balanced: bool,
// CO2 Emissions in kg CO2 (to avoid fractions).
value: u128,
// Real CO2 Emissions date as UNIX timestamp, not block creation time.
date: u64,
}
/// The AssetCO2Emissions Error types.
#[derive(Debug, PartialEq, Eq, Copy, Clone, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum AssetCO2EmissionsError {
// Overflow with AssetId.
AssetIdOverflow,
// When an Asset does not exist.
AssetNotFound,
// When an Asset has been already `Paused`.
AlreadyPaused,
// When not an Asset's Owner wants to take any action over the Asset.
NotOwner,
// When the calling account is not the owner of the contract.
NotContractOwner,
// When an Asset is not in a `Paused` state.
NotPaused,
// When an Asset's parent is not found.
ParentNotFound,
// When an Asset's parent is not in `Paused` state.
ParentNotPaused,
// When CO2 Emissions vector is empty.
EmissionsEmpty,
// Too many CO2 Emissions in vector.
EmissionsOverflow,
// When CO2 Emissions item contains 0 emissions value.
ZeroEmissionsItem,
// When the Metadata vector contains too many characters.
MetadataOverflow,
// When the data source vector contains too many characters.
DataSourceOverflow,
// When an Asset with ID already exists.
AssetAlreadyExists,
}
/// This emits when an Asset gets created.
#[ink(event)]
pub struct Blasted {
#[ink(topic)]
id: AssetId,
metadata: Metadata,
owner: AccountId,
parent: ParentDetails,
}
/// This emits when ownership of any Asset changes.
#[ink(event)]
pub struct Transfer {
from: AccountId,
to: AccountId,
#[ink(topic)]
id: AssetId,
}
/// This emits when an Asset gets paused.
#[ink(event)]
pub struct Paused {
#[ink(topic)]
id: AssetId,
}
/// This emits when CO2 Emission is added.
#[ink(event)]
pub struct Emission {
#[ink(topic)]
id: AssetId,
category: EmissionsCategory,
data_source: DataSource,
balanced: bool,
date: u64,
value: u128,
}
#[ink::trait_definition]
pub trait AssetCO2Emissions {
/// List all Assets assigned to an owner.
///
/// Returns empty vector if an account does not own any Assets.
///
/// # Arguments
///
/// * `owner` - An account for whom to query assets.
///
#[ink(message)]
fn list_assets(&self, owner: AccountId) -> Vec<AssetId>;
/// Find the owner of an Asset.
///
/// Returns None if Asset does not exist.
///
/// # Arguments
///
/// * `id` - The identifier for an Asset.
///
#[ink(message)]
fn owner_of(&self, id: AssetId) -> Option<AccountId>;
/// Blast an Asset.
///
/// # Arguments
///
/// * `to` - The account that will own the Asset.
/// * `metadata` - Immutable Asset's metadata (physical details of steel); Can be a string, a JSON string or a link to IPFS.
/// * `emissions` - CO2 Emissions during asset creation (like blasting or splitting).
/// * `parent` - Information about asset creation from the existing Asset (in the case of e.g. splitting) - identifier of the Asset's parent
///
/// # Errors
///
/// * `AssetAlreadyExists` - When Asset already exists.
/// * `AssetNotFound` - When the Asset's parent does not exist.
/// * `DataSourceOverflow` - When Data Source for any of CO2 Emission items exceeds maximum length.
/// * `EmissionsEmpty` - When list of CO2 Emissions is empty.
/// * `EmissionsOverflow` - When list of CO2 Emissions exceeds maximum length.
/// * `MetadataOverflow` - When Metadata exceeds maximum length.
/// * `NotPaused`- When Asset's parent is not paused.
/// * `NotOwner` - When action executor is not a parent Asset owner.
/// * `ZeroEmissionsItem` When emission value for any of CO2 Emission items is equal to Zero.
///
/// # Events
///
/// * `Blasted` - When an Asset gets blasted.
/// * `Emissions` - When CO2 Emissions are added. Emitted per each CO2 Emission item.
///
#[ink(message)]
fn blast(
&mut self,
to: AccountId,
metadata: Metadata,
emissions: Vec<CO2Emissions>,
parent: ParentDetails,
) -> Result<(), AssetCO2EmissionsError>;
/// Transfers the ownership of an Asset to another account
///
/// # Arguments
///
/// * `to` - The new owner
/// * `id` - The Asset to be transferred
/// * `emissions` - CO2 Emissions caused by the Asset transfer
///
/// # Errors
///
/// * `AlreadyPaused` - When the Asset is paused.
/// * `AssetNotFound` - When the Asset does not exist.
/// * `DataSourceOverflow` - When Data Source for any of CO2 Emission items exceeds maximum length.
/// * `EmissionsEmpty` - When list of CO2 Emissions is empty.
/// * `EmissionsOverflow` - When list of CO2 Emissions exceeds maximum length.
/// * `NotOwner` - When transaction sender is not an owner.
/// * `ZeroEmissionsItem` When emission value for any of CO2 Emission items is equal to Zero.
///
/// # Events
///
/// * `Transfer` - When Asset gets transferred.
/// * `Emissions` - When CO2 Emissions are added. Emitted per each CO2 Emission item.
///
#[ink(message)]
fn transfer(
&mut self,
to: AccountId,
id: AssetId,
emissions: Vec<CO2Emissions>,
) -> Result<(), AssetCO2EmissionsError>;
/// Set stopped state for an Asset.
/// In this state no one is able to transfer/add emissions to the Asset.
/// Should be used before splitting into smaller parts.
///
/// # Arguments
///
/// * `id` - The Asset to lock.
///
/// # Errors
///
/// * `AlreadyPaused` - When the Asset is already paused.
/// * `AssetNotFound` - When the Asset does not exist.
/// * `NotOwner` - When transaction sender is not an owner.
///
/// # Events
///
/// * `Paused` - When asset gets paused.
#[ink(message)]
fn pause(&mut self, id: AssetId) -> Result<(), AssetCO2EmissionsError>;
/// Query if an Asset is paused.
///
/// Returns None if Asset does not exist.
///
/// # Arguments
///
/// * `id` - The Asset id.
///
#[ink(message)]
fn has_paused(&self, id: AssetId) -> Option<bool>;
/// Add CO2 emissions to an Asset.
///
///
/// # Arguments
///
/// * `id` - The Asset id.
/// * `emissions` - CO2 emissions caused by any real world action.
///
/// # Errors
///
/// * `AlreadyPaused` - When asset is paused.
/// * `AssetNotFound` - When the Asset does not exist.
/// * `EmissionsOverflow` - When list of CO2 Emissions exceeds maximum length.
/// * `NotOwner` - When transaction sender is not an owner.
/// * `ZeroEmissionsItem` When emission value for any of CO2 Emission items is equal to Zero.
///
/// # Events
///
/// * `Emissions` - When CO2 Emissions are added.
///
#[ink(message)]
fn add_emissions(
&mut self,
id: AssetId,
emissions: CO2Emissions,
) -> Result<(), AssetCO2EmissionsError>;
/// Get specified Asset's CO2 Emissions.
///
/// Returns None is Asset does not exist.
///
/// # Arguments
///
/// * `id` - The Asset id.
///
#[ink(message)]
fn get_asset_emissions(&self, id: AssetId) -> Option<Vec<CO2Emissions>>;
/// Get specified Asset's metadata.
///
/// Returns None is Asset does not exist.
///
/// # Arguments
///
/// * `id` - The Asset id.
///
#[ink(message)]
fn get_metadata(&self, id: AssetId) -> Option<Metadata>;
/// Get Asset's parent.
///
/// Returns None is Asset does not exist.
///
/// # Arguments
///
/// * `id` - The Asset id.
///
#[ink(message)]
fn get_parent_details(&self, id: AssetId) -> Option<ParentDetails>;
/// Get Asset details.
///
/// Returns None is Asset does not exist.
///
/// # Arguments
///
/// * `id` - The Asset id.
///
#[ink(message)]
fn get_asset(&self, id: AssetId) -> Option<AssetDetails>;
/// Query Asset's emissions.
/// This function returns CO2 Emissions not only from specified Asset but also its parents.
/// It returns full Asset's history from the Asset's tree.
///
/// Returns None is Asset does not exist.
///
/// # Arguments
///
/// * `id` - The Asset id.
///
#[ink(message)]
fn query_emissions(&self, id: AssetId) -> Option<Vec<AssetDetails>>;
}
#[ink(storage)]
pub struct InfinityAsset {
// Privileged contract owner.
contract_owner: AccountId,
// The next Asset id to assign.
next_id: AssetId,
// Mapping Asset id to its owner.
asset_owner: Mapping<AssetId, AccountId>,
// Mapping to find what Assets an account has.
owned_assets: BTreeMap<AccountId, BTreeSet<AssetId>>,
// CO2 Emissions of an Asset.
co2_emissions: Mapping<AssetId, Vec<CO2Emissions>>,
// Metadata of an Asset.
metadata: Mapping<AssetId, Metadata>,
// What Assets are paused.
paused: Mapping<AssetId, bool>,
// Child Asset's parent.
parent: Mapping<AssetId, ParentDetails>,
}
impl Default for InfinityAsset {
fn default() -> Self {
Self::new()
}
}
impl InfinityAsset {
/// Default constructor for the Smart Contract instance.
#[ink(constructor)]
pub fn new() -> Self {
Self {
contract_owner: Self::env().caller(),
next_id: 1,
asset_owner: Mapping::new(),
owned_assets: BTreeMap::new(),
co2_emissions: Mapping::new(),
metadata: Mapping::new(),
paused: Mapping::new(),
parent: Mapping::new(),
}
}
/// Sets the new smart contract owner.
/// Must be called by current contract owner.
///
/// # Arguments
///
/// * `new_owner` - The new owner of the smart contract.
///
/// # Errors
///
/// * `NotContractOwner` - When action triggered by not the current owner.
///
#[ink(message)]
pub fn set_contract_owner(
&mut self,
new_owner: AccountId,
) -> Result<(), AssetCO2EmissionsError> {
// Only the owner of the contract may set the new owner.
self.ensure_contract_owner(self.env().caller())?;
self.contract_owner = new_owner;
Ok(())
}
/// Modifies the code which is used to execute calls to this contract address (`AccountId`).
/// Must be called by current contract owner.
///
/// # Arguments
///
/// * `code_hash` - Hash of the new smart contract's code.
///
#[ink(message)]
pub fn set_code(&mut self, code_hash: [u8; 32]) {
self.ensure_contract_owner(self.env().caller())
.expect("Only contract owner can set code hash");
ink::env::set_code_hash(&code_hash).unwrap_or_else(|err| {
panic!("Failed to `set_code_hash` to {code_hash:?} due to {err:?}")
});
ink::env::debug_println!("Switched code hash to {:?}.", code_hash);
}
/// Insert new Asset in the Assets of `owner`.
fn insert_owned_asset(
&mut self,
owner: &AccountId,
asset_id: &AssetId,
) -> Result<(), AssetCO2EmissionsError> {
match self.owned_assets.get_mut(owner) {
None => {
let mut new_owned_assets = BTreeSet::new();
new_owned_assets.insert(*asset_id);
self.owned_assets.insert(*owner, new_owned_assets);
}
Some(owned_assets) => {
owned_assets.insert(*asset_id);
}
}
Ok(())
}
/// Remove Asset from the Assets of `owner`.
fn remove_owned_asset(
&mut self,
owner: &AccountId,
asset_id: &AssetId,
) -> Result<(), AssetCO2EmissionsError> {
self.owned_assets
.get_mut(owner)
.expect("Owned assets must exist when removing during Asset transfer")
.remove(asset_id);
Ok(())
}
/// Ensure that Asset does not exist.
fn ensure_not_exist(&self, id: &AssetId) -> Result<(), AssetCO2EmissionsError> {
match self.asset_owner.contains(id) {
false => Ok(()),
true => Err(AssetCO2EmissionsError::AssetAlreadyExists),
}
}
/// Ensure that Asset does exist.
fn ensure_exists(&self, id: &AssetId) -> Result<(), AssetCO2EmissionsError> {
match self.asset_owner.contains(id) {
true => Ok(()),
false => Err(AssetCO2EmissionsError::AssetNotFound),
}
}
/// Ensure the calling origin is the contract owner.
fn ensure_contract_owner(&self, caller: AccountId) -> Result<(), AssetCO2EmissionsError> {
match caller.eq(&self.contract_owner) {
true => Ok(()),
false => Err(AssetCO2EmissionsError::NotContractOwner),
}
}
/// Ensure the calling origin is the Asset owner.
fn ensure_owner(
&self,
id: &AssetId,
account: &AccountId,
) -> Result<(), AssetCO2EmissionsError> {
match self.asset_owner.get(id) {
None => Err(AssetCO2EmissionsError::AssetNotFound),
Some(owner) => {
if owner.eq(account) {
Ok(())
} else {
Err(AssetCO2EmissionsError::NotOwner)
}
}
}
}
/// Ensure the Asset is `Paused`.
fn ensure_paused(&self, id: &AssetId) -> Result<(), AssetCO2EmissionsError> {
match self.has_paused(*id) {
None => Err(AssetCO2EmissionsError::AssetNotFound),
Some(false) => Err(AssetCO2EmissionsError::NotPaused),
Some(true) => Ok(()),
}
}
/// Ensure the Asset is not `Paused`.
fn ensure_not_paused(&self, id: &AssetId) -> Result<(), AssetCO2EmissionsError> {
match self.has_paused(*id) {
None => Err(AssetCO2EmissionsError::AssetNotFound),
Some(true) => Err(AssetCO2EmissionsError::AlreadyPaused),
Some(false) => Ok(()),
}
}
/// Ensure the parent details of child Asset are correct.
fn ensure_proper_parent(
&self,
parent: &ParentDetails,
caller: &AccountId,
) -> Result<(), AssetCO2EmissionsError> {
match parent {
None => Ok(()),
Some(parent_id) => {
self.ensure_owner(parent_id, caller)?;
self.ensure_paused(parent_id)
}
}
}
/// Ensure that CO2 Emissions are correct: not empty, not unbounded, and all items are correct.
fn ensure_emissions_correct(
&self,
asset: Option<AssetId>,
emissions: &Vec<CO2Emissions>,
) -> Result<(), AssetCO2EmissionsError> {
self.ensure_emissions_not_empty(emissions)?;
self.ensure_emissions_not_unbounded(emissions)?;
match asset {
None => (),
Some(asset_id) => {
let mut updated_emissions =
self.co2_emissions.get(asset_id).unwrap_or(Vec::new());
updated_emissions.extend_from_slice(emissions);
self.ensure_emissions_not_unbounded(&updated_emissions)?;
}
}
// Ensure all CO2 Emissions items are correct.
emissions.iter().try_for_each(|item| {
self.ensure_emissions_item_correct(item)?;
Ok(())
})
}
/// Ensure CO2 Emissions vec is not empty.
fn ensure_emissions_not_empty(
&self,
emissions: &Vec<CO2Emissions>,
) -> Result<(), AssetCO2EmissionsError> {
match emissions.len() {
0 => Err(AssetCO2EmissionsError::EmissionsEmpty),
_ => Ok(()),
}
}
/// Ensure length of CO2 Emissions vec is not greater than `MAX_EMISSIONS_PER_ASSET`.
fn ensure_emissions_not_unbounded(
&self,
emissions: &Vec<CO2Emissions>,
) -> Result<(), AssetCO2EmissionsError> {
if emissions.len() > MAX_EMISSIONS_PER_ASSET as usize {
return Err(AssetCO2EmissionsError::EmissionsOverflow);
}
Ok(())
}
/// Ensure length of Data Source for CO2 Emission item is not greater than `MAX_DATA_SOURCE_LENGTH`.
fn ensure_emissions_data_src_not_unbounded(
&self,
data_source: &DataSource,
) -> Result<(), AssetCO2EmissionsError> {
if data_source.len() > MAX_DATA_SOURCE_LENGTH as usize {
return Err(AssetCO2EmissionsError::DataSourceOverflow);
}
Ok(())
}
/// Ensure CO2 Emissions item is correct.
fn ensure_emissions_item_correct(
&self,
item: &CO2Emissions,
) -> Result<(), AssetCO2EmissionsError> {
self.ensure_emissions_data_src_not_unbounded(&item.data_source)?;
self.ensure_emissions_item_not_zero(item)?;
Ok(())
}
/// Ensure CO2 Emissions item value is non-zero.
fn ensure_emissions_item_not_zero(
&self,
emissions: &CO2Emissions,
) -> Result<(), AssetCO2EmissionsError> {
match emissions.value {
0 => Err(AssetCO2EmissionsError::ZeroEmissionsItem),
_ => Ok(()),
}
}
/// Ensure metadata does not exceed `MAX_METADATA_LENGTH`.
fn ensure_proper_metadata(
&self,
metadata: &Metadata,
) -> Result<(), AssetCO2EmissionsError> {
if metadata.len() > MAX_METADATA_LENGTH as usize {
return Err(AssetCO2EmissionsError::MetadataOverflow);
}
Ok(())
}
/// Save new CO2 Emissions for Asset and emit an event for each emission item.
fn save_new_co2_emissions(&mut self, id: &AssetId, emissions: &[CO2Emissions]) {
let mut updated_emissions = self.co2_emissions.get(id).unwrap_or(Vec::new());
updated_emissions.extend_from_slice(emissions);
self.co2_emissions.insert(id, &updated_emissions);
// emit an event for each emission item.
emissions.iter().for_each(|emission| {
self.env().emit_event(Emission {
id: *id,
category: emission.category,
data_source: emission.data_source.clone(),
balanced: emission.balanced,
date: emission.date,
value: emission.value,
})
});
}
/// Return the next id and increase by 1.
fn next_id(&mut self) -> Result<AssetId, AssetCO2EmissionsError> {
let asset_id = self.next_id;
self.next_id = self
.next_id
.checked_add(1)
.ok_or(AssetCO2EmissionsError::AssetIdOverflow)?;
Ok(asset_id)
}
/// Build Asset tree from child to parent.
fn build_asset_tree(&self, id: AssetId) -> Vec<AssetDetails> {
let mut asset_id = id;
let mut tree_path: Vec<AssetDetails> = Vec::new();
loop {
// This function is called after initial check if asset exists
// So it must contain asset and its children -- unwrap must be safe
// It has been confirmed in previous test cases
// If not, we need to capture that sth is wrong with the smart contract
let asset: AssetDetails = self
.get_asset(asset_id)
.expect("Asset existence already checked");
let parent_details = asset.parent;
tree_path.push(asset);
match parent_details {
None => break,
Some(parent_id) => asset_id = parent_id,
}
}
tree_path
}
}
impl AssetCO2Emissions for InfinityAsset {
#[ink(message)]
fn list_assets(&self, owner: AccountId) -> Vec<AssetId> {
match self.owned_assets.get(&owner) {
None => Vec::new(),
Some(owned_assets) => owned_assets.iter().copied().collect::<Vec<AssetId>>(),
}
}
#[ink(message)]
fn owner_of(&self, id: AssetId) -> Option<AccountId> {
self.asset_owner.get(id)
}
#[ink(message)]
fn blast(
&mut self,
to: AccountId,
metadata: Metadata,
emissions: Vec<CO2Emissions>,
parent: ParentDetails,
) -> Result<(), AssetCO2EmissionsError> {
let caller = self.env().caller();
self.ensure_proper_metadata(&metadata)?;
self.ensure_emissions_correct(None, &emissions)?;
self.ensure_proper_parent(&parent, &caller)?;
let asset_id: u128 = self.next_id()?;
self.ensure_not_exist(&asset_id)?;
self.insert_owned_asset(&to, &asset_id)?;
self.asset_owner.insert(asset_id, &to);
self.metadata.insert(asset_id, &metadata);
self.paused.insert(asset_id, &false);
self.parent.insert(asset_id, &parent);
self.env().emit_event(Blasted {
id: asset_id,
metadata,
owner: to,
parent,
});
// Save CO2 Emissions & emit corresponding events.
self.save_new_co2_emissions(&asset_id, &emissions);
Ok(())
}
#[ink(message)]
fn transfer(
&mut self,
to: AccountId,
id: AssetId,
emissions: Vec<CO2Emissions>,
) -> Result<(), AssetCO2EmissionsError> {
let from = self.env().caller();
self.ensure_exists(&id)?;
self.ensure_owner(&id, &from)?;
self.ensure_not_paused(&id)?;
self.ensure_emissions_correct(Some(id), &emissions)?;
self.remove_owned_asset(&from, &id)?;
self.insert_owned_asset(&to, &id)?;
self.asset_owner.insert(id, &to);
self.env().emit_event(Transfer { from, to, id });
// Save CO2 Emissions & emit corresponding events.
self.save_new_co2_emissions(&id, &emissions);
Ok(())
}
#[ink(message)]
fn pause(&mut self, id: AssetId) -> Result<(), AssetCO2EmissionsError> {
self.ensure_owner(&id, &self.env().caller())?;
self.ensure_not_paused(&id)?;
self.paused.insert(id, &true);
self.env().emit_event(Paused { id });
Ok(())
}
#[ink(message)]
fn has_paused(&self, id: AssetId) -> Option<bool> {
self.paused.get(id)
}
#[ink(message)]
fn add_emissions(
&mut self,
id: AssetId,
emissions: CO2Emissions,
) -> Result<(), AssetCO2EmissionsError> {
self.ensure_exists(&id)?;
self.ensure_owner(&id, &self.env().caller())?;
self.ensure_not_paused(&id)?;
let emissions: Vec<CO2Emissions> = Vec::from([emissions]);
self.ensure_emissions_correct(Some(id), &emissions)?;
// Save CO2 Emissions & emit corresponding events.
self.save_new_co2_emissions(&id, &emissions);
Ok(())
}
#[ink(message)]
fn get_asset_emissions(&self, id: AssetId) -> Option<Vec<CO2Emissions>> {
self.co2_emissions.get(id)
}
#[ink(message)]
fn get_metadata(&self, id: AssetId) -> Option<Metadata> {
self.metadata.get(id)
}
#[ink(message)]
fn get_parent_details(&self, id: AssetId) -> Option<ParentDetails> {
self.parent.get(id)
}
#[ink(message)]
fn get_asset(&self, id: AssetId) -> Option<AssetDetails> {
match self.get_metadata(id) {
// Asset does not exist, return None.
None => None,
// Asset must exist, fetch and unpack attributes.
Some(metadata) => {
let emissions = self.get_asset_emissions(id).expect("Emissions must exist");
let parent = self
.get_parent_details(id)
.expect("Parent Details must exist");
Some(AssetDetails {
asset_id: id,
metadata,
emissions,
parent,
})
}
}
}
#[ink(message)]
fn query_emissions(&self, id: AssetId) -> Option<Vec<AssetDetails>> {
match self.ensure_exists(&id) {
Err(_) => None,
Ok(_) => Some(self.build_asset_tree(id)),
}
}
}
/// Unit tests
#[cfg(test)]
mod tests {
use ink::env::test;
use ink::env::test::DefaultAccounts;
use ink::env::DefaultEnvironment;
use super::*;
use ink::primitives::{Clear, Hash};
type Event = <InfinityAsset as ::ink::reflect::ContractEventBase>::Type;
fn get_accounts() -> DefaultAccounts<DefaultEnvironment> {
test::default_accounts::<DefaultEnvironment>()
}
fn prepare_env() -> (DefaultAccounts<DefaultEnvironment>, InfinityAsset) {
(get_accounts(), InfinityAsset::new())
}
fn env_with_default_asset() -> (
(DefaultAccounts<DefaultEnvironment>, InfinityAsset),
(AssetId, AccountId),
) {
let (accounts, mut contract) = prepare_env();
let asset_owner = accounts.django;
let asset_id = blast_default_asset(&mut contract, &asset_owner);
((accounts, contract), (asset_id, asset_owner))
}
fn set_caller(sender: AccountId) {
test::set_caller::<DefaultEnvironment>(sender);
}
fn new_emission(
category: EmissionsCategory,
data_source: DataSource,
balanced: bool,
value: u128,
date: u64,
) -> CO2Emissions {
CO2Emissions {
category,
data_source,
balanced,
value,
date,
}
}
fn default_data_source() -> Vec<u8> {
Vec::from([0u8, 1u8, 2u8, 3u8])
}
fn new_emissions(items: u8) -> Vec<CO2Emissions> {
let mut emissions = Vec::new();
for i in 0..items {
emissions.push(new_emission(
EmissionsCategory::Upstream,
default_data_source(),
true,
i as u128 + 1, // avoid Zero Emissions Item
default_timestamp(),
));
}
emissions
}
fn default_metadata() -> Vec<u8> {
Vec::from([0u8, 1u8, 2u8, 3u8])
}
fn default_timestamp() -> u64 {
// 28.04.2023 00:00:00
1682632800
}
fn default_emission_item() -> CO2Emissions {
let emissions_category = EmissionsCategory::Upstream;
let emissions_data_source = default_data_source();
let emissions_balanced = true;
let emissions_value = 1;
let timestamp: u64 = default_timestamp();
new_emission(
emissions_category,
emissions_data_source,
emissions_balanced,
emissions_value,
timestamp,
)
}
fn blast_default_asset(contract: &mut InfinityAsset, owner: &AccountId) -> AssetId {
let metadata = default_metadata();
let parent = None;
let emissions: Vec<CO2Emissions> = new_emissions(1);
assert!(contract.blast(*owner, metadata, emissions, parent).is_ok());
contract.next_id - 1
}
/// For calculating the event topic hash.
struct PrefixedValue<'a, 'b, T> {
pub prefix: &'a [u8],
pub value: &'b T,
}
impl<X> scale::Encode for PrefixedValue<'_, '_, X>
where
X: scale::Encode,
{
#[inline]
fn size_hint(&self) -> usize {
self.prefix.size_hint() + self.value.size_hint()
}
#[inline]
fn encode_to<T: scale::Output + ?Sized>(&self, dest: &mut T) {
self.prefix.encode_to(dest);
self.value.encode_to(dest);
}
}
fn encoded_into_hash<T>(entity: &T) -> Hash
where
T: scale::Encode,
{
use ink::{
env::hash::{Blake2x256, CryptoHash, HashOutput},
primitives::Clear,
};
let mut result = Hash::CLEAR_HASH;
let len_result = result.as_ref().len();
let encoded = entity.encode();
let len_encoded = encoded.len();
if len_encoded <= len_result {
result.as_mut()[..len_encoded].copy_from_slice(&encoded);
return result;
}
let mut hash_output = <<Blake2x256 as HashOutput>::Type as Default>::default();
<Blake2x256 as CryptoHash>::hash(&encoded, &mut hash_output);
let copy_len = core::cmp::min(hash_output.len(), len_result);
result.as_mut()[0..copy_len].copy_from_slice(&hash_output[0..copy_len]);
result
}
fn assert_blasted_event(
event: &test::EmittedEvent,
expected_id: AssetId,
expected_metadata: Metadata,
expected_owner: AccountId,
expected_parent: ParentDetails,
) {
let decoded_event = <Event as scale::Decode>::decode(&mut &event.data[..])
.expect("Encountered invalid contract event data buffer");
if let Event::Blasted(Blasted {
id,
metadata,
owner,
parent,
}) = decoded_event
{