pallet_messages/
types.rs

1use common_primitives::{
2	messages::MessageResponse, msa::MessageSourceId, node::BlockNumber, schema::PayloadLocation,
3};
4use core::fmt::Debug;
5use frame_support::{traits::Get, BoundedVec};
6use multibase::Base;
7use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
8use scale_info::TypeInfo;
9extern crate alloc;
10use alloc::vec::Vec;
11
12/// Payloads stored offchain contain a tuple of (bytes(the payload reference), payload length).
13pub type OffchainPayloadType = (Vec<u8>, u32);
14/// Index of message in the block
15pub type MessageIndex = u16;
16
17/// A single message type definition.
18#[derive(Default, Encode, Decode, PartialEq, Debug, TypeInfo, Eq, MaxEncodedLen)]
19#[scale_info(skip_type_params(MaxDataSize))]
20#[codec(mel_bound(MaxDataSize: MaxEncodedLen))]
21pub struct Message<MaxDataSize>
22where
23	MaxDataSize: Get<u32> + Debug,
24{
25	///  Data structured by the associated schema's model.
26	pub payload: BoundedVec<u8, MaxDataSize>,
27	/// Message source account id of the Provider. This may be the same id as contained in `msa_id`,
28	/// indicating that the original source MSA is acting as its own provider. An id differing from that
29	/// of `msa_id` indicates that `provider_msa_id` was delegated by `msa_id` to send this message on
30	/// its behalf.
31	pub provider_msa_id: MessageSourceId,
32	///  Message source account id (the original source).
33	pub msa_id: Option<MessageSourceId>,
34}
35
36impl<MaxDataSize> Message<MaxDataSize>
37where
38	MaxDataSize: Get<u32> + Debug,
39{
40	/// Helper function to handle response type [`MessageResponse`] depending on the Payload Location (on chain or IPFS)
41	pub fn map_to_response(
42		&self,
43		block_number: BlockNumber,
44		payload_location: PayloadLocation,
45		index: u16,
46	) -> MessageResponse {
47		match payload_location {
48			PayloadLocation::OnChain => MessageResponse {
49				provider_msa_id: self.provider_msa_id,
50				index,
51				block_number,
52				msa_id: self.msa_id,
53				payload: Some(self.payload.to_vec()),
54				cid: None,
55				payload_length: None,
56			},
57			PayloadLocation::IPFS => {
58				let (binary_cid, payload_length) =
59					OffchainPayloadType::decode(&mut &self.payload[..]).unwrap_or_default();
60				MessageResponse {
61					provider_msa_id: self.provider_msa_id,
62					index,
63					block_number,
64					cid: Some(multibase::encode(Base::Base32Lower, binary_cid).as_bytes().to_vec()),
65					payload_length: Some(payload_length),
66					msa_id: None,
67					payload: None,
68				}
69			}, // Message types of Itemized and Paginated are retrieved differently
70			_ => MessageResponse {
71				provider_msa_id: self.provider_msa_id,
72				index,
73				block_number,
74				msa_id: None,
75				payload: None,
76				cid: None,
77				payload_length: None,
78			},
79		}
80	}
81}