use common_primitives::{
messages::MessageResponse, msa::MessageSourceId, node::BlockNumber, schema::PayloadLocation,
};
use frame_support::{traits::Get, BoundedVec};
use multibase::Base;
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use sp_std::{fmt::Debug, prelude::*};
pub type OffchainPayloadType = (Vec<u8>, u32);
pub type MessageIndex = u16;
#[derive(Default, Encode, Decode, PartialEq, Debug, TypeInfo, Eq, MaxEncodedLen)]
#[scale_info(skip_type_params(MaxDataSize))]
#[codec(mel_bound(MaxDataSize: MaxEncodedLen))]
pub struct Message<MaxDataSize>
where
MaxDataSize: Get<u32> + Debug,
{
pub payload: BoundedVec<u8, MaxDataSize>,
pub provider_msa_id: MessageSourceId,
pub msa_id: Option<MessageSourceId>,
}
impl<MaxDataSize> Message<MaxDataSize>
where
MaxDataSize: Get<u32> + Debug,
{
pub fn map_to_response(
&self,
block_number: BlockNumber,
payload_location: PayloadLocation,
index: u16,
) -> MessageResponse {
match payload_location {
PayloadLocation::OnChain => MessageResponse {
provider_msa_id: self.provider_msa_id,
index,
block_number,
msa_id: self.msa_id,
payload: Some(self.payload.to_vec()),
cid: None,
payload_length: None,
},
PayloadLocation::IPFS => {
let (binary_cid, payload_length) =
OffchainPayloadType::decode(&mut &self.payload[..]).unwrap_or_default();
MessageResponse {
provider_msa_id: self.provider_msa_id,
index,
block_number,
cid: Some(multibase::encode(Base::Base32Lower, binary_cid).as_bytes().to_vec()),
payload_length: Some(payload_length),
msa_id: None,
payload: None,
}
}, _ => MessageResponse {
provider_msa_id: self.provider_msa_id,
index,
block_number,
msa_id: None,
payload: None,
cid: None,
payload_length: None,
},
}
}
}