ink_env/engine/off_chain/mod.rs
1// Copyright (C) Use Ink (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
15mod call_data;
16mod impls;
17pub mod test_api;
18mod types;
19
20#[cfg(test)]
21mod tests;
22
23use super::OnInstance;
24use crate::Error;
25
26use derive_more::From;
27use ink_engine::ext::Engine;
28use ink_primitives::{
29 AccountId,
30 H160,
31};
32
33/// The off-chain environment.
34pub struct EnvInstance {
35 engine: Engine,
36}
37
38impl OnInstance for EnvInstance {
39 fn on_instance<F, R>(f: F) -> R
40 where
41 F: FnOnce(&mut Self) -> R,
42 {
43 use core::cell::RefCell;
44 thread_local!(
45 static INSTANCE: RefCell<EnvInstance> = RefCell::new(
46 EnvInstance {
47 engine: Engine::new()
48 }
49 )
50 );
51 /*
52 * This unsafe block is needed to be able to return a mut reference
53 * while another mut reference is still borrowed, because now that
54 * contracts can invoke other contracts some API functions are called
55 * nested. This should be safe, as the object is in a TLS, so there's no
56 * possibility of undefined behavior arising from race conditions.
57 */
58 INSTANCE.with(|instance| f(unsafe { &mut *instance.as_ptr() }))
59 }
60}
61
62#[derive(Debug, From, PartialEq, Eq)]
63pub enum OffChainError {
64 Account(AccountError),
65 #[from(ignore)]
66 UninitializedBlocks,
67 #[from(ignore)]
68 UninitializedExecutionContext,
69 #[from(ignore)]
70 UnregisteredChainExtension,
71}
72
73// todo rename
74/// Errors encountered upon interacting with the accounts database.
75#[derive(Debug, From, PartialEq, Eq)]
76pub enum AccountError {
77 Decoding(scale::Error),
78 #[from(ignore)]
79 UnexpectedUserAccount,
80 #[from(ignore)]
81 NoAccountForId(AccountId),
82 NoContractForId(H160),
83}