encode.rs (1967B)
1 #[cfg(not(feature = "std"))] 2 use alloc::vec; 3 #[cfg(not(feature = "std"))] 4 use alloc::{ 5 string::{String, ToString}, 6 vec::Vec, 7 }; 8 9 use radroots_event::envelope::kind::KIND_GIFT_WRAP; 10 use radroots_event::social::gift_wrap::{GiftWrap, GiftWrapRecipient}; 11 12 use crate::error::EventEncodeError; 13 use radroots_event::wire::Nip01EventWireParts; 14 15 const DEFAULT_KIND: u32 = KIND_GIFT_WRAP; 16 17 fn validate_recipient(recipient: &GiftWrapRecipient) -> Result<Vec<String>, EventEncodeError> { 18 if recipient.public_key.trim().is_empty() { 19 return Err(EventEncodeError::EmptyRequiredField("recipient.public_key")); 20 } 21 let mut tag = Vec::with_capacity(3); 22 tag.push("p".to_string()); 23 tag.push(recipient.public_key.clone()); 24 if let Some(relay_url) = &recipient.relay_url { 25 if relay_url.trim().is_empty() { 26 return Err(EventEncodeError::EmptyRequiredField("recipient.relay_url")); 27 } 28 tag.push(relay_url.clone()); 29 } 30 Ok(tag) 31 } 32 33 pub fn gift_wrap_build_tags(gift_wrap: &GiftWrap) -> Result<Vec<Vec<String>>, EventEncodeError> { 34 let mut tags = Vec::with_capacity(2); 35 tags.push(validate_recipient(&gift_wrap.recipient)?); 36 if let Some(expiration) = gift_wrap.expiration { 37 tags.push(vec!["expiration".to_string(), expiration.to_string()]); 38 } 39 Ok(tags) 40 } 41 42 pub fn to_wire_parts(gift_wrap: &GiftWrap) -> Result<Nip01EventWireParts, EventEncodeError> { 43 if gift_wrap.content.trim().is_empty() { 44 return Err(EventEncodeError::EmptyRequiredField("content")); 45 } 46 let tags = gift_wrap_build_tags(gift_wrap)?; 47 Ok(Nip01EventWireParts { 48 kind: DEFAULT_KIND, 49 content: gift_wrap.content.clone(), 50 tags, 51 }) 52 } 53 54 pub fn to_wire_parts_with_kind( 55 gift_wrap: &GiftWrap, 56 kind: u32, 57 ) -> Result<Nip01EventWireParts, EventEncodeError> { 58 if kind != DEFAULT_KIND { 59 return Err(EventEncodeError::InvalidKind(kind)); 60 } 61 to_wire_parts(gift_wrap) 62 }