types.rs 5.87 KB
Newer Older
1
// Copyright 2018-2021 Parity Technologies (UK) Ltd.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Types for the default environment.
//!
17
//! These are simple mirrored types from the default substrate FRAME configuration.
18
19
//! Their interfaces and functionality might not be complete.
//!
20
//! Users are required to provide their own type definitions and `Environment`
21
//! implementations in order to write ink! contracts for other chain configurations.
22
23
24
//!
//! # Note
//!
25
//! When authoring a contract, the concrete `Environment` are available via aliases
26
27
28
29
//! generated by the `lang` macro. Therefore all functionality of the concrete
//! types is accessible in the contract, not constrained by the required trait
//! bounds.
//!
30
//! Outside the contract and its tests (e.g. in the off-chain environment), where
31
//! there is no knowledge of the concrete types, the functionality is restricted to
32
//! the trait bounds on the `Environment` trait types.
33

34
use super::arithmetic::AtLeast32BitUnsigned;
35
36
37
38
39
use core::{
    array::TryFromSliceError,
    convert::TryFrom,
};
use derive_more::From;
40
41
42
43
44
use scale::{
    Decode,
    Encode,
};
#[cfg(feature = "std")]
45
use scale_info::TypeInfo;
46
47

/// The environmental types usable by contracts defined with ink!.
48
pub trait Environment {
49
50
51
52
53
    /// The maximum number of supported event topics provided by the runtime.
    ///
    /// The value must match the maximum number of supported event topics of the used runtime.
    const MAX_EVENT_TOPICS: usize;

54
    /// The address type.
55
    type AccountId: 'static + scale::Codec + Clone + PartialEq + Eq + Ord;
56

57
58
59
60
61
62
63
    /// The type of balances.
    type Balance: 'static
        + scale::Codec
        + Copy
        + Clone
        + PartialEq
        + Eq
64
        + AtLeast32BitUnsigned;
65

66
67
68
69
70
71
72
73
74
75
76
    /// The type of hash.
    type Hash: 'static
        + scale::Codec
        + Copy
        + Clone
        + Clear
        + PartialEq
        + Eq
        + Ord
        + AsRef<[u8]>
        + AsMut<[u8]>;
77

78
79
80
81
82
83
84
    /// The type of timestamps.
    type Timestamp: 'static
        + scale::Codec
        + Copy
        + Clone
        + PartialEq
        + Eq
85
        + AtLeast32BitUnsigned;
86

87
88
89
90
91
92
93
    /// The type of block number.
    type BlockNumber: 'static
        + scale::Codec
        + Copy
        + Clone
        + PartialEq
        + Eq
94
        + AtLeast32BitUnsigned;
95
96
97

    /// The chain extension for the environment.
    ///
98
    /// This is a type that is defined through the `#[ink::chain_extension]` procedural macro.
99
100
101
102
    /// For more information about usage and definition click [this][chain_extension] link.
    ///
    /// [chain_extension]: https://paritytech.github.io/ink/ink_lang/attr.chain_extension.html
    type ChainExtension;
103
104
}

105
106
107
/// Placeholder for chains that have no defined chain extension.
pub enum NoChainExtension {}

108
109
/// The fundamental types of the default configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
110
#[cfg_attr(feature = "std", derive(TypeInfo))]
111
pub enum DefaultEnvironment {}
112

113
impl Environment for DefaultEnvironment {
114
115
    const MAX_EVENT_TOPICS: usize = 4;

116
117
118
119
120
    type AccountId = AccountId;
    type Balance = Balance;
    type Hash = Hash;
    type Timestamp = Timestamp;
    type BlockNumber = BlockNumber;
121
    type ChainExtension = NoChainExtension;
122
123
124
125
126
127
128
129
130
}

/// The default balance type.
pub type Balance = u128;

/// The default timestamp type.
pub type Timestamp = u64;

/// The default block number type.
131
pub type BlockNumber = u32;
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

/// The default environment `AccountId` type.
///
/// # Note
///
/// This is a mirror of the `AccountId` type used in the default configuration
/// of PALLET contracts.
#[derive(
    Debug,
    Copy,
    Clone,
    PartialEq,
    Eq,
    Ord,
    PartialOrd,
    Hash,
    Encode,
    Decode,
    From,
    Default,
)]
153
#[cfg_attr(feature = "std", derive(TypeInfo))]
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
pub struct AccountId([u8; 32]);

impl<'a> TryFrom<&'a [u8]> for AccountId {
    type Error = TryFromSliceError;

    fn try_from(bytes: &'a [u8]) -> Result<Self, TryFromSliceError> {
        let address = <[u8; 32]>::try_from(bytes)?;
        Ok(Self(address))
    }
}

/// The default environment `Hash` type.
///
/// # Note
///
/// This is a mirror of the `Hash` type used in the default configuration
/// of PALLET contracts.
#[derive(
    Debug,
    Copy,
    Clone,
    PartialEq,
    Eq,
    Ord,
    PartialOrd,
    Hash,
    Encode,
    Decode,
    From,
    Default,
)]
185
#[cfg_attr(feature = "std", derive(TypeInfo))]
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
pub struct Hash([u8; 32]);

impl<'a> TryFrom<&'a [u8]> for Hash {
    type Error = TryFromSliceError;

    fn try_from(bytes: &'a [u8]) -> Result<Self, TryFromSliceError> {
        let address = <[u8; 32]>::try_from(bytes)?;
        Ok(Self(address))
    }
}

impl AsRef<[u8]> for Hash {
    fn as_ref(&self) -> &[u8] {
        &self.0[..]
    }
}

impl AsMut<[u8]> for Hash {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0[..]
    }
}

/// The equivalent of `Zero` for hashes.
///
/// A hash that consists only of 0 bits is clear.
pub trait Clear {
    /// Returns `true` if the hash is clear.
    fn is_clear(&self) -> bool;

    /// Returns a clear hash.
    fn clear() -> Self;
}

220
impl Clear for [u8; 32] {
221
222
223
224
225
    fn is_clear(&self) -> bool {
        self.as_ref().iter().all(|&byte| byte == 0x00)
    }

    fn clear() -> Self {
226
227
228
229
230
231
232
233
234
235
236
        [0x00; 32]
    }
}

impl Clear for Hash {
    fn is_clear(&self) -> bool {
        <[u8; 32] as Clear>::is_clear(&self.0)
    }

    fn clear() -> Self {
        Self(<[u8; 32] as Clear>::clear())
237
238
    }
}