ab_contracts_common/lib.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
#![feature(non_null_from_ref)]
#![no_std]
pub mod env;
pub mod metadata;
pub mod method;
use crate::method::MethodFingerprint;
use ab_contracts_io_type::IoType;
use ab_contracts_io_type::trivial_type::TrivialType;
use core::ffi::c_void;
use core::fmt;
use core::ptr::NonNull;
use derive_more::{
Add, AddAssign, Display, Div, DivAssign, From, Into, Mul, MulAssign, Sub, SubAssign,
};
/// Pointers to methods of all contracts.
///
/// `fn_pointer`'s argument is actually `NonNull<InternalArgs>` of corresponding method and must
/// have corresponding ABI.
///
/// NOTE: It is unlikely to be necessary to interact with this directly.
#[derive(Debug, Copy, Clone)]
#[cfg(any(unix, windows))]
pub struct ContractsMethodsFnPointer {
pub crate_name: &'static str,
pub main_contract_metadata: &'static [u8],
pub method_fingerprint: &'static MethodFingerprint,
pub method_metadata: &'static [u8],
pub ffi_fn: unsafe extern "C" fn(NonNull<NonNull<c_void>>) -> ExitCode,
}
#[cfg(any(unix, windows))]
inventory::collect!(ContractsMethodsFnPointer);
/// A trait that indicates the struct is a contact.
///
/// **Do not implement this trait explicitly!** Implementation is automatically generated by the
/// macro which generates smart contract implementation. This trait is required, but not sufficient
/// for proper contract implementation, use `#[contract]` attribute macro instead.
pub trait Contract: IoType {
/// Main contract metadata, see [`ContractMetadataKind`] for encoding details.
///
/// More metadata can be contributed by trait implementations.
///
/// [`ContractMetadataKind`]: crate::metadata::ContractMetadataKind
const MAIN_CONTRACT_METADATA: &[u8];
/// Name of the crate where contact is located.
///
/// NOTE: It is unlikely to be necessary to interact with this directly.
#[cfg(any(unix, windows))]
const CRATE_NAME: &str;
// Default value is provided to only fail to compile when contract that uses
// `ab-contracts-common` has feature specified, but `ab-contracts-common` does not, but not the
// other way around (as will be the case with dependencies where `guest` feature must not be
// enabled)
#[cfg(feature = "guest")]
#[doc(hidden)]
const GUEST_FEATURE_ENABLED: () = ();
/// Slot type used by this contract
type Slot: IoType;
/// Tmp type used by this contract
type Tmp: IoType;
}
#[derive(Debug, Display, Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
#[repr(u8)]
pub enum ContractError {
NotFound = 1,
InvalidState,
InvalidInput,
InvalidOutput,
AccessDenied,
}
impl ContractError {
/// Convert contact error into contract exit code.
///
/// Mosty useful for low-level code.
#[inline]
pub const fn exit_code(self) -> ExitCode {
match self {
Self::NotFound => ExitCode::NotFound,
Self::InvalidState => ExitCode::InvalidState,
Self::InvalidInput => ExitCode::InvalidInput,
Self::InvalidOutput => ExitCode::InvalidOutput,
Self::AccessDenied => ExitCode::AccessDenied,
}
}
}
#[derive(Debug, Display, Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
#[repr(u8)]
#[must_use = "Code can be Ok or one of the errors, consider converting to Result<(), ContractCode>"]
pub enum ExitCode {
Ok = 0,
NotFound = 1,
InvalidState,
InvalidInput,
InvalidOutput,
AccessDenied,
}
impl From<ContractError> for ExitCode {
#[inline]
fn from(error: ContractError) -> Self {
error.exit_code()
}
}
impl From<Result<(), ContractError>> for ExitCode {
#[inline]
fn from(error: Result<(), ContractError>) -> Self {
match error {
Ok(()) => Self::Ok,
Err(error) => error.exit_code(),
}
}
}
impl From<ExitCode> for Result<(), ContractError> {
#[inline]
fn from(value: ExitCode) -> Self {
match value {
ExitCode::Ok => Ok(()),
ExitCode::NotFound => Err(ContractError::NotFound),
ExitCode::InvalidState => Err(ContractError::InvalidState),
ExitCode::InvalidInput => Err(ContractError::InvalidInput),
ExitCode::InvalidOutput => Err(ContractError::InvalidOutput),
ExitCode::AccessDenied => Err(ContractError::AccessDenied),
}
}
}
#[derive(
Debug,
Display,
Default,
Copy,
Clone,
Ord,
PartialOrd,
Eq,
PartialEq,
Add,
AddAssign,
Sub,
SubAssign,
Mul,
MulAssign,
Div,
DivAssign,
From,
Into,
TrivialType,
)]
#[repr(transparent)]
pub struct Balance(u128);
impl Balance {
pub const MIN: Self = Self(0);
pub const MAX: Self = Self(u128::MAX);
}
/// Shard index
#[derive(Debug, Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq, TrivialType)]
#[repr(transparent)]
pub struct ShardIndex(
// Essentially 32-bit number, but using an array reduces alignment requirement to 1 byte
[u8; 4],
);
impl fmt::Display for ShardIndex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
u32::from_le_bytes(self.0).fmt(f)
}
}
impl ShardIndex {
/// Max possible shard index
pub const MAX_SHARD_INDEX: u32 = Self::MAX_SHARDS - 1;
/// Max possible number of shards
pub const MAX_SHARDS: u32 = 2u32.pow(20);
// TODO: Remove once traits work in const environment and `From` could be used
/// Convert shard index to `u32`.
///
/// This is typically only necessary for low-level code.
pub const fn to_u32(self) -> u32 {
u32::from_le_bytes(self.0)
}
// TODO: Remove once traits work in const environment and `From` could be used
/// Create shard index from `u32`.
///
/// Returns `None` if `shard_index > ShardIndex::MAX_SHARD_INDEX`
///
/// This is typically only necessary for low-level code.
pub const fn from_u32(shard_index: u32) -> Option<Self> {
if shard_index > Self::MAX_SHARD_INDEX {
return None;
}
Some(Self(shard_index.to_le_bytes()))
}
}
#[derive(Debug, Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq, TrivialType)]
#[repr(transparent)]
pub struct Address(
// Essentially 64-bit number, but using an array reduces alignment requirement to 1 byte
[u8; 8],
);
impl PartialEq<&Address> for Address {
#[inline]
fn eq(&self, other: &&Address) -> bool {
self.0 == other.0
}
}
impl PartialEq<Address> for &Address {
#[inline]
fn eq(&self, other: &Address) -> bool {
self.0 == other.0
}
}
impl From<u64> for Address {
#[inline]
fn from(value: u64) -> Self {
Self(value.to_le_bytes())
}
}
impl fmt::Display for Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// TODO: Would it be better to represent address as something non-decimal that is shorter?
u64::from_le_bytes(self.0).fmt(f)
}
}
// TODO: Method for getting creation shard out of the address
// TODO: There should be a notion of global address
impl Address {
// TODO: Various system contracts
/// Sentinel contract address, inaccessible and not owned by anyone
pub const NULL: Self = Self(0u64.to_le_bytes());
/// System contract for managing code of other contracts
pub const SYSTEM_CODE: Self = Self(1u64.to_le_bytes());
/// System contract for managing state of other contracts
pub const SYSTEM_STATE: Self = Self(2u64.to_le_bytes());
/// System contract for address allocation on a particular shard index
#[inline]
pub const fn system_address_allocator(shard_index: ShardIndex) -> Address {
// Shard `0` doesn't have its own allocator because there are no user-deployable contracts
// there, so address `0` is `NULL`, the rest up to `ShardIndex::MAX_SHARD_INDEX` correspond
// to address allocators of respective shards
Address((shard_index.to_u32() as u64 * ShardIndex::MAX_SHARDS as u64).to_le_bytes())
}
}