use dig_social_profile::{Profile as SchemaProfile, SlotId, Value, VerifiedBody};
use crate::mint::error::{MintError, MintResult};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProfileSeed(SchemaProfile);
impl ProfileSeed {
pub fn new() -> Self {
Self(SchemaProfile::with_schema_v2())
}
#[must_use]
pub fn with_display_name(self, name: impl Into<String>) -> Self {
self.with_utf8(dig_social_profile::slot::standard::DISPLAY_NAME, name)
}
#[must_use]
pub fn with_bio(self, bio: impl Into<String>) -> Self {
self.with_utf8(dig_social_profile::slot::standard::BIO, bio)
}
#[must_use]
pub fn with_xch_address(self, address: impl Into<String>) -> Self {
self.with_utf8(dig_social_profile::slot::standard::XCH_ADDRESS, address)
}
#[must_use]
pub fn with_utf8(mut self, slot: SlotId, text: impl Into<String>) -> Self {
self.0.set(slot, Value::Utf8(text.into()));
self
}
pub fn root(&self) -> MintResult<[u8; 32]> {
Ok(self.body()?.root())
}
pub fn body_bytes(&self) -> MintResult<Vec<u8>> {
Ok(self.body()?.as_bytes().to_vec())
}
fn body(&self) -> MintResult<VerifiedBody> {
VerifiedBody::from_profile(&self.0)
.map_err(|e| MintError::Build(format!("profile seed body: {e}")))
}
}
impl Default for ProfileSeed {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_root_is_determined_by_the_slots_not_their_order() {
let one = ProfileSeed::new()
.with_display_name("ada")
.with_bio("counts things");
let other = ProfileSeed::new()
.with_bio("counts things")
.with_display_name("ada");
assert_eq!(one.root().unwrap(), other.root().unwrap());
}
#[test]
fn different_content_commits_to_a_different_root() {
let ada = ProfileSeed::new().with_display_name("ada");
let grace = ProfileSeed::new().with_display_name("grace");
let empty = ProfileSeed::new();
assert_ne!(ada.root().unwrap(), grace.root().unwrap());
assert_ne!(ada.root().unwrap(), empty.root().unwrap());
}
#[test]
fn the_seed_body_is_the_preimage_of_the_root_the_mint_commits() {
let seed = ProfileSeed::new()
.with_display_name("ada")
.with_bio("counts things");
let bytes = seed.body_bytes().unwrap();
let reopened = dig_social_profile::VerifiedBody::open(
&bytes,
dig_social_profile::AnchoredRoot::from_chain_read(seed.root().unwrap()),
)
.expect("the seed's own bytes verify against the root the mint commits");
assert_eq!(reopened.root(), seed.root().unwrap());
assert_eq!(reopened.profile().display_name(), Some("ada"));
}
#[test]
fn an_equal_seed_rebuilds_byte_identical_bytes() {
let one = ProfileSeed::new().with_display_name("ada").with_bio("hi");
let rebuilt = ProfileSeed::new().with_bio("hi").with_display_name("ada");
assert_eq!(one.body_bytes().unwrap(), rebuilt.body_bytes().unwrap());
}
#[test]
fn the_default_seed_carries_the_v2_schema_stamp() {
assert_eq!(ProfileSeed::default(), ProfileSeed::new());
assert_eq!(
ProfileSeed::new().0.schema_version(),
Some(dig_social_profile::slot::standard::SCHEMA_VERSION_V2)
);
}
}