referrerpolicy=no-referrer-when-downgrade

pallet_revive_uapi/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! External C API to communicate with substrate contracts runtime module.
16//!
17//! Refer to substrate FRAME contract module for more documentation.
18
19#![no_std]
20#![cfg_attr(docsrs, feature(doc_cfg))]
21
22mod flags;
23pub use flags::*;
24mod host;
25mod macros;
26
27pub use host::{HostFn, HostFnImpl};
28
29/// Convert a u64 into a [u8; 32].
30pub const fn u256_bytes(value: u64) -> [u8; 32] {
31	let mut buffer = [0u8; 32];
32	let bytes = value.to_le_bytes();
33
34	buffer[0] = bytes[0];
35	buffer[1] = bytes[1];
36	buffer[2] = bytes[2];
37	buffer[3] = bytes[3];
38	buffer[4] = bytes[4];
39	buffer[5] = bytes[5];
40	buffer[6] = bytes[6];
41	buffer[7] = bytes[7];
42	buffer
43}
44
45macro_rules! define_error_codes {
46    (
47        $(
48            $( #[$attr:meta] )*
49            $name:ident = $discr:literal,
50        )*
51    ) => {
52        /// Every error that can be returned to a contract when it calls any of the host functions.
53        #[derive(Debug, PartialEq, Eq)]
54        #[repr(u32)]
55        pub enum ReturnErrorCode {
56            /// API call successful.
57            Success = 0,
58            $(
59                $( #[$attr] )*
60                $name = $discr,
61            )*
62            /// Returns if an unknown error was received from the host module.
63            Unknown,
64        }
65
66        impl From<ReturnCode> for Result {
67            fn from(return_code: ReturnCode) -> Self {
68                match return_code.0 {
69                    0 => Ok(()),
70                    $(
71                        $discr => Err(ReturnErrorCode::$name),
72                    )*
73                    _ => Err(ReturnErrorCode::Unknown),
74                }
75            }
76        }
77    };
78}
79
80impl From<ReturnErrorCode> for u32 {
81	fn from(code: ReturnErrorCode) -> u32 {
82		code as u32
83	}
84}
85
86impl From<ReturnErrorCode> for u64 {
87	fn from(error: ReturnErrorCode) -> Self {
88		u32::from(error).into()
89	}
90}
91
92define_error_codes! {
93	/// The called function trapped and has its state changes reverted.
94	/// In this case no output buffer is returned.
95	/// Can only be returned from `call` and `instantiate`.
96	CalleeTrapped = 1,
97	/// The called function ran to completion but decided to revert its state.
98	/// An output buffer is returned when one was supplied.
99	/// Can only be returned from `call` and `instantiate`.
100	CalleeReverted = 2,
101	/// The passed key does not exist in storage.
102	KeyNotFound = 3,
103	/// Transfer failed for other not further specified reason. Most probably
104	/// reserved or locked balance of the sender that was preventing the transfer.
105	TransferFailed = 4,
106	/// The subcall ran out of weight or storage deposit.
107	OutOfResources = 5,
108	/// ECDSA public key recovery failed. Most probably wrong recovery id or signature.
109	EcdsaRecoveryFailed = 7,
110	/// sr25519 signature verification failed.
111	Sr25519VerifyFailed = 8,
112	/// Contract instantiation failed because the address already exists.
113	/// Occurs when instantiating the same contract with the same salt more than once.
114	DuplicateContractAddress = 11,
115}
116
117/// The raw return code returned by the host side.
118#[repr(transparent)]
119pub struct ReturnCode(u32);
120
121/// Used as a sentinel value when reading and writing contract memory.
122///
123/// We use this value to signal `None` to a contract when only a primitive is
124/// allowed and we don't want to go through encoding a full Rust type.
125/// Using `u32::Max` is a safe sentinel because contracts are never
126/// allowed to use such a large amount of resources. So this value doesn't
127/// make sense for a memory location or length.
128const SENTINEL: u32 = u32::MAX;
129
130impl From<ReturnCode> for Option<u32> {
131	fn from(code: ReturnCode) -> Self {
132		(code.0 < SENTINEL).then_some(code.0)
133	}
134}
135
136impl ReturnCode {
137	/// Returns the raw underlying `u32` representation.
138	pub fn into_u32(self) -> u32 {
139		self.0
140	}
141	/// Returns the underlying `u32` converted into `bool`.
142	pub fn into_bool(self) -> bool {
143		self.0.ne(&0)
144	}
145}
146
147type Result = core::result::Result<(), ReturnErrorCode>;
148
149/// Helper to pack two `u32` values into a `u64` register.
150///
151/// Pointers to PVM memory are always 32 bit in size. Thus contracts can pack two
152/// pointers into a single register when calling a syscall API method.
153///
154/// This is done in syscall API methods where the number of arguments is exceeding
155/// the available registers.
156pub fn pack_hi_lo(hi: u32, lo: u32) -> u64 {
157	((hi as u64) << 32) | lo as u64
158}