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
12pub type OffchainPayloadType = (Vec<u8>, u32);
14pub type MessageIndex = u16;
16
17#[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 pub payload: BoundedVec<u8, MaxDataSize>,
27 pub provider_msa_id: MessageSourceId,
32 pub msa_id: Option<MessageSourceId>,
34}
35
36impl<MaxDataSize> Message<MaxDataSize>
37where
38 MaxDataSize: Get<u32> + Debug,
39{
40 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 }, _ => 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}