encode.rs (1985B)
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_events::gift_wrap::{RadrootsGiftWrap, RadrootsGiftWrapRecipient}; 10 use radroots_events::kinds::KIND_GIFT_WRAP; 11 12 use crate::error::EventEncodeError; 13 use crate::wire::WireEventParts; 14 15 const DEFAULT_KIND: u32 = KIND_GIFT_WRAP; 16 17 fn validate_recipient( 18 recipient: &RadrootsGiftWrapRecipient, 19 ) -> Result<Vec<String>, EventEncodeError> { 20 if recipient.public_key.trim().is_empty() { 21 return Err(EventEncodeError::EmptyRequiredField("recipient.public_key")); 22 } 23 let mut tag = Vec::with_capacity(3); 24 tag.push("p".to_string()); 25 tag.push(recipient.public_key.clone()); 26 if let Some(relay_url) = &recipient.relay_url { 27 if relay_url.trim().is_empty() { 28 return Err(EventEncodeError::EmptyRequiredField("recipient.relay_url")); 29 } 30 tag.push(relay_url.clone()); 31 } 32 Ok(tag) 33 } 34 35 pub fn gift_wrap_build_tags( 36 gift_wrap: &RadrootsGiftWrap, 37 ) -> Result<Vec<Vec<String>>, EventEncodeError> { 38 let mut tags = Vec::with_capacity(2); 39 tags.push(validate_recipient(&gift_wrap.recipient)?); 40 if let Some(expiration) = gift_wrap.expiration { 41 tags.push(vec!["expiration".to_string(), expiration.to_string()]); 42 } 43 Ok(tags) 44 } 45 46 pub fn to_wire_parts(gift_wrap: &RadrootsGiftWrap) -> Result<WireEventParts, EventEncodeError> { 47 if gift_wrap.content.trim().is_empty() { 48 return Err(EventEncodeError::EmptyRequiredField("content")); 49 } 50 let tags = gift_wrap_build_tags(gift_wrap)?; 51 Ok(WireEventParts { 52 kind: DEFAULT_KIND, 53 content: gift_wrap.content.clone(), 54 tags, 55 }) 56 } 57 58 pub fn to_wire_parts_with_kind( 59 gift_wrap: &RadrootsGiftWrap, 60 kind: u32, 61 ) -> Result<WireEventParts, EventEncodeError> { 62 if kind != DEFAULT_KIND { 63 return Err(EventEncodeError::InvalidKind(kind)); 64 } 65 to_wire_parts(gift_wrap) 66 }