forked from FuelLabs/sway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
identity.sw
76 lines (68 loc) · 2.19 KB
/
identity.sw
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
//! A wrapper type with two variants, `Address` and `ContractId`.
//! The use of this type allows for handling interactions with contracts and addresses in a unified manner.
library;
use ::assert::assert;
use ::address::Address;
use ::constants::{ZERO_B256, BASE_ASSET_ID};
use ::contract_id::ContractId;
use ::option::Option;
/// The `Identity` type: either an `Address` or a `ContractId`.
// ANCHOR: docs_identity
pub enum Identity {
Address: Address,
ContractId: ContractId,
}
// ANCHOR_END: docs_identity
impl core::ops::Eq for Identity {
fn eq(self, other: Self) -> bool {
match (self, other) {
(Identity::Address(address1), Identity::Address(address2)) => address1 == address2,
(Identity::ContractId(asset1), Identity::ContractId(asset2)) => asset1 == asset2,
_ => false,
}
}
}
impl Identity {
pub fn as_address(self) -> Option<Address> {
match self {
Identity::Address(address) => Option::Some(address),
Identity::ContractId(_) => Option::None,
}
}
pub fn as_contract_id(self) -> Option<ContractId> {
match self {
Identity::Address(_) => Option::None,
Identity::ContractId(contract_id) => Option::Some(contract_id),
}
}
pub fn is_address(self) -> bool {
match self {
Identity::Address(_) => true,
Identity::ContractId(_) => false,
}
}
pub fn is_contract_id(self) -> bool {
match self {
Identity::Address(_) => false,
Identity::ContractId(_) => true,
}
}
}
#[test]
fn test_address() {
let address = Address::from(ZERO_B256);
let identity = Identity::Address(address);
assert(identity.is_address());
assert(!identity.is_contract_id());
assert(identity.as_address().unwrap() == address);
assert(identity.as_contract_id().is_none());
}
#[test]
fn test_contract_id() {
let contract_id = BASE_ASSET_ID;
let identity = Identity::ContractId(contract_id);
assert(!identity.is_address());
assert(identity.is_contract_id());
assert(identity.as_contract_id().unwrap() == contract_id);
assert(identity.as_address().is_none());
}