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 /// The call dispatched by `call_runtime` was executed but returned an error.
109 CallRuntimeFailed = 6,
110 /// ECDSA public key recovery failed. Most probably wrong recovery id or signature.
111 EcdsaRecoveryFailed = 7,
112 /// sr25519 signature verification failed.
113 Sr25519VerifyFailed = 8,
114 /// The `xcm_execute` call failed.
115 XcmExecutionFailed = 9,
116 /// The `xcm_send` call failed.
117 XcmSendFailed = 10,
118 /// Contract instantiation failed because the address already exists.
119 /// Occurs when instantiating the same contract with the same salt more than once.
120 DuplicateContractAddress = 11,
121}
122
123/// The raw return code returned by the host side.
124#[repr(transparent)]
125pub struct ReturnCode(u32);
126
127/// Used as a sentinel value when reading and writing contract memory.
128///
129/// We use this value to signal `None` to a contract when only a primitive is
130/// allowed and we don't want to go through encoding a full Rust type.
131/// Using `u32::Max` is a safe sentinel because contracts are never
132/// allowed to use such a large amount of resources. So this value doesn't
133/// make sense for a memory location or length.
134const SENTINEL: u32 = u32::MAX;
135
136impl From<ReturnCode> for Option<u32> {
137 fn from(code: ReturnCode) -> Self {
138 (code.0 < SENTINEL).then_some(code.0)
139 }
140}
141
142impl ReturnCode {
143 /// Returns the raw underlying `u32` representation.
144 pub fn into_u32(self) -> u32 {
145 self.0
146 }
147 /// Returns the underlying `u32` converted into `bool`.
148 pub fn into_bool(self) -> bool {
149 self.0.ne(&0)
150 }
151}
152
153type Result = core::result::Result<(), ReturnErrorCode>;
154
155/// Helper to pack two `u32` values into a `u64` register.
156///
157/// Pointers to PVM memory are always 32 bit in size. Thus contracts can pack two
158/// pointers into a single register when calling a syscall API method.
159///
160/// This is done in syscall API methods where the number of arguments is exceeding
161/// the available registers.
162pub fn pack_hi_lo(hi: u32, lo: u32) -> u64 {
163 ((hi as u64) << 32) | lo as u64
164}