diff --git a/sway-lib-std/src/identity.sw b/sway-lib-std/src/identity.sw index 65f54ffb6a5..38daebbd56c 100644 --- a/sway-lib-std/src/identity.sw +++ b/sway-lib-std/src/identity.sw @@ -2,8 +2,11 @@ //! 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 @@ -21,3 +24,53 @@ impl core::ops::Eq for Identity { } } } + +impl Identity { + pub fn as_address(self) -> Option
{ + match self { + Identity::Address(address) => Option::Some(address), + Identity::ContractId(_) => Option::None, + } + } + + pub fn as_contract_id(self) -> Option { + 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()); +}