Skip to content

Commit

Permalink
Additional identity methods (FuelLabs#4683)
Browse files Browse the repository at this point in the history
## Description
Added some utility methods to the Identity struct

## Checklist

- [] I have linked to any relevant issues.
- [ ] I have commented my code, particularly in hard-to-understand
areas.
- [ ] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [ ] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
  • Loading branch information
SwayStar123 authored Jun 20, 2023
1 parent 96c6103 commit c149252
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions sway-lib-std/src/identity.sw
Original file line number Diff line number Diff line change
@@ -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<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());
}

0 comments on commit c149252

Please sign in to comment.