polymesh_extension/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2
3extern crate alloc;
4
5use ink_env::Environment;
6use ink_lang as ink;
7
8use scale::{Encode, Output};
9
10#[cfg(feature = "std")]
11use scale_info::TypeInfo;
12
13use alloc::vec::Vec;
14
15/// `Encoded` is used to avoid encoding an extra length that isn't needed.
16pub struct Encoded(pub Vec<u8>);
17
18impl From<Vec<u8>> for Encoded {
19    fn from(data: Vec<u8>) -> Self {
20        Self(data)
21    }
22}
23
24impl<T: Encode> From<&T> for Encoded {
25    fn from(v: &T) -> Self {
26        Self(v.encode())
27    }
28}
29
30impl Encode for Encoded {
31    fn size_hint(&self) -> usize {
32        self.0.len()
33    }
34
35    fn encode_to<O: Output + ?Sized>(&self, out: &mut O) {
36        out.write(&self.0)
37    }
38}
39
40#[ink::chain_extension]
41#[derive(Clone, Copy)]
42pub trait PolymeshRuntime {
43    type ErrorCode = PolymeshRuntimeErr;
44
45    #[ink(extension = 0x00_00_00_01, returns_result = false)]
46    fn call_runtime(call: Encoded);
47
48    #[ink(extension = 0x00_00_00_02, returns_result = false)]
49    fn read_storage(key: Encoded) -> Option<Vec<u8>>;
50
51    #[ink(extension = 0x00_00_00_03, returns_result = false)]
52    fn get_spec_version() -> u32;
53
54    #[ink(extension = 0x00_00_00_04, returns_result = false)]
55    fn get_transaction_version() -> u32;
56}
57
58pub type PolymeshRuntimeInstance = <PolymeshRuntime as ink::ChainExtensionInstance>::Instance;
59
60pub fn new_instance() -> PolymeshRuntimeInstance {
61    <PolymeshRuntime as ink::ChainExtensionInstance>::instantiate()
62}
63
64#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)]
65#[cfg_attr(feature = "std", derive(TypeInfo))]
66pub enum PolymeshRuntimeErr {
67    Unknown,
68}
69
70impl ink_env::chain_extension::FromStatusCode for PolymeshRuntimeErr {
71    fn from_status_code(status_code: u32) -> Result<(), Self> {
72        match status_code {
73            0 => Ok(()),
74            1 => Err(Self::Unknown),
75            _ => panic!("encountered unknown status code"),
76        }
77    }
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum PolymeshEnvironment {}
82
83impl Environment for PolymeshEnvironment {
84    const MAX_EVENT_TOPICS: usize = <ink_env::DefaultEnvironment as Environment>::MAX_EVENT_TOPICS;
85
86    type AccountId = <ink_env::DefaultEnvironment as Environment>::AccountId;
87    type Balance = <ink_env::DefaultEnvironment as Environment>::Balance;
88    type Hash = <ink_env::DefaultEnvironment as Environment>::Hash;
89    type BlockNumber = <ink_env::DefaultEnvironment as Environment>::BlockNumber;
90    type Timestamp = <ink_env::DefaultEnvironment as Environment>::Timestamp;
91
92    type ChainExtension = PolymeshRuntime;
93}