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
//! Exposes the public API to communicate with the host.

use core::panic;
use std::backtrace::{Backtrace, BacktraceStatus};
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use odra_mock_vm_types::{
    Address, Balance, BlockTime, Bytes, MockDeserializable, MockSerializable, OdraType, PublicKey
};
use odra_types::{event::OdraEvent, ExecutionError, OdraError};

use crate::{borrow_env, debug, native_token::NativeTokenMetadata};

/// Returns the current block time.
pub fn get_block_time() -> BlockTime {
    borrow_env().get_block_time()
}

/// Gets the address of the currently executing contract.
pub fn caller() -> Address {
    borrow_env().caller()
}

/// Returns the address of currently executing contract.
pub fn self_address() -> Address {
    borrow_env().callee()
}

/// Stores the `value` under `key`.
pub fn set_var<T: MockSerializable + MockDeserializable>(key: &[u8], value: T) {
    borrow_env().set_var(key, value)
}

/// Gets a value stored under `key`.
pub fn get_var<T: OdraType>(key: &[u8]) -> Option<T> {
    borrow_env().get_var(key)
}

/// Puts a key-value into a collection.
pub fn set_dict_value<
    K: MockSerializable + MockDeserializable,
    V: MockSerializable + MockDeserializable
>(
    dict: &[u8],
    key: &K,
    value: V
) {
    borrow_env().set_dict_value(dict, key.serialize().unwrap().as_slice(), value)
}

/// Gets the value from the `dict` collection under `key`.
pub fn get_dict_value<
    K: MockSerializable + MockDeserializable,
    T: MockSerializable + MockDeserializable
>(
    dict: &[u8],
    key: &K
) -> Option<T> {
    let key = key.ser().unwrap();
    let key = key.as_slice();
    borrow_env().get_dict_value(dict, key)
}

/// Stops execution of a contract and reverts execution effects with a given [`ExecutionError`].
pub fn revert<E>(error: E) -> !
where
    E: Into<ExecutionError>
{
    let execution_error: ExecutionError = error.into();
    let odra_error: OdraError = execution_error.clone().into();
    let callstack_tip = borrow_env().callstack_tip();

    borrow_env().revert(odra_error);

    std::panic::set_hook(Box::new(|info| {
        let backtrace = Backtrace::capture();
        if matches!(backtrace.status(), BacktraceStatus::Captured) {
            debug::print_first_n_frames(&backtrace, 30);
        }
        debug::print_panic_error(info);
    }));
    panic!(
        "{}",
        debug::format_panic_message(&execution_error, &callstack_tip)
    );
}

/// Sends an event to the execution environment.
pub fn emit_event<T: OdraType + OdraEvent>(event: T) {
    let event_data = event.ser().unwrap();
    borrow_env().emit_event(&event_data);
}

/// Returns amount of native token attached to the call.
pub fn attached_value() -> Balance {
    borrow_env().attached_value()
}

/// Returns the value that represents one native token.
pub fn one_token() -> Balance {
    Balance::one()
}

/// Transfers native token from the contract caller to the given address.
pub fn transfer_tokens<B: Into<Balance>>(to: &Address, amount: B) {
    let callee = borrow_env().callee();
    let amount = amount.into();
    borrow_env().transfer_tokens(&callee, to, &amount);
}

/// Returns the balance of the account associated with the current contract.
pub fn self_balance() -> Balance {
    borrow_env().self_balance()
}

/// Returns the platform native token metadata
pub fn native_token_metadata() -> NativeTokenMetadata {
    NativeTokenMetadata::new()
}

/// Verifies the signature created using the Backend's default signature scheme.
pub fn verify_signature(message: &Bytes, signature: &Bytes, public_key: &PublicKey) -> bool {
    let mut message = message.inner_bytes().clone();
    message.extend_from_slice(public_key.inner_bytes());
    let mock_signature_bytes = Bytes::from(message);
    mock_signature_bytes == *signature
}

/// Creates a hash of the given input. Uses default hash for given backend.
pub fn hash<T: AsRef<[u8]>>(input: T) -> Vec<u8> {
    let mut s = DefaultHasher::new();
    input.as_ref().hash(&mut s);
    let hash = s.finish();
    hash.to_le_bytes().to_vec()
}