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
use crate::{
    detail::BorrowingFn,
    handler_result::{ViewResult, WriteResult},
    optional_cell::{CloneContents, OptionalCell},
    warp_result::transmission::Transmission,
    warp_result::WarpResult,
};
use core::fmt::Debug;
use core::future::Future;
use serde::{de::DeserializeOwned, Serialize};
use serde_wasm_bindgen::from_value;
use wasm_bindgen::JsValue;

pub async fn write_async<S, A, E, F, Fut>(
    state: &OptionalCell<S>,
    interaction: JsValue,
    write_contract_method: F,
) -> JsValue
where
    S: Clone + Debug + Serialize,
    A: DeserializeOwned + Debug,
    E: Serialize,
    F: FnOnce(S, A) -> Fut,
    Fut: Future<Output = WriteResult<S, E>>,
{
    let result = match parse_input(state, interaction) {
        Err(value) => return value,
        Ok(action) => write_contract_method(state.clone_contents(), action).await,
    };

    map_write_result(result, state)
}

pub fn write_sync<S, A, E, F>(
    s: &OptionalCell<S>,
    interaction: JsValue,
    write_contract_method: F,
) -> JsValue
where
    S: Clone + Debug + Serialize,
    A: DeserializeOwned + Debug,
    E: Serialize,
    F: FnOnce(S, A) -> WriteResult<S, E>,
{
    let result = match parse_input(s, interaction) {
        Err(value) => return value,
        Ok(action) => write_contract_method(s.clone_contents(), action),
    };

    map_write_result(result, s)
}

// We need a dedicated trait BorrowingFn to attach the same lifetime
// that is not possible to specify by the caller of the view_async to both &State and Future
pub async fn view_async<S, A, V, E, F>(
    s: &OptionalCell<S>,
    interaction: JsValue,
    view_contract_method: F,
) -> JsValue
where
    S: Clone,
    A: DeserializeOwned + core::fmt::Debug,
    V: Serialize + Debug,
    E: Serialize + Debug,
    F: for<'a> BorrowingFn<'a, S, A, ViewResult<V, E>>,
{
    let result = match parse_input(s, interaction) {
        Err(value) => return value,
        Ok(action) => {
            view_contract_method
                .call(s.cell.borrow().as_ref().unwrap(), action)
                .await
        }
    };

    to_json_value::<Transmission<V, E>>(&WarpResult::from(result).into()).unwrap()
}

pub fn view_sync<S, A, V, E, F>(
    s: &OptionalCell<S>,
    interaction: JsValue,
    view_contract_method: F,
) -> JsValue
where
    S: Clone,
    A: DeserializeOwned + Debug,
    V: Serialize,
    E: Serialize,
    F: FnOnce(&S, A) -> ViewResult<V, E>,
{
    let result = match parse_input(s, interaction) {
        Err(value) => return value,
        Ok(action) => view_contract_method(s.cell.borrow().as_ref().unwrap(), action),
    };

    to_json_value::<Transmission<V, E>>(&WarpResult::from(result).into()).unwrap()
}

fn map_write_result<S, E>(result: WriteResult<S, E>, state: &OptionalCell<S>) -> JsValue
where
    S: Clone + Debug + Serialize,
    E: Serialize,
{
    if let WriteResult::WriteResponse(new_state) = result {
        state.cell.replace(Some(new_state));
        to_json_value::<Transmission<(), E>>(&WarpResult::WriteResponse().into()).unwrap()
    } else {
        to_json_value::<Transmission<(), E>>(&WarpResult::from(result).into()).unwrap()
    }
}

fn parse_input<S, A>(state: &OptionalCell<S>, interaction: JsValue) -> Result<A, JsValue>
where
    A: DeserializeOwned + core::fmt::Debug,
    S: Clone,
{
    let action = from_value(interaction);
    if action.is_err() {
        return Err(runtime_error(format!(
            "Error while parsing input {}",
            action.unwrap_err()
        )));
    }
    if state.is_empty() {
        return Err(runtime_error(format!(
            "initState MUST be called before interaction can take place"
        )));
    }

    Ok(action.unwrap())
}

pub fn init_state<S: DeserializeOwned>(state: &OptionalCell<S>, init_state: &JsValue) -> bool {
    match from_value(init_state.clone()) {
        Ok(parsed_state) => {
            state.cell.replace(Some(parsed_state));
            true
        }
        Err(_e) => {
            #[cfg(feature = "debug")]
            {
                web_sys::console::log_1(&JsValue::from_str(&format!(
                    "failed to parse init state {:?}",
                    _e
                )));
            }
            false
        }
    }
}

pub fn current_state<S: Serialize + Debug>(state: &OptionalCell<S>) -> JsValue {
    // not sure if that's deterministic - which is very important for the execution network.
    // TODO: perf - according to docs:
    // "This is unlikely to be super speedy so it's not recommended for large payload"
    // - we should minimize calls to serde_wasm_bindgen::to_json_value
    if state.is_empty() {
        runtime_error(
            "contract state not initialized. please run initState method first".to_owned(),
        )
    } else {
        match to_json_value(state.cell.borrow().as_ref().unwrap()) {
            Ok(v) => v,
            Err(e) => runtime_error(format!("failed to serialize return value {:?}", e)),
        }
    }
}

pub fn to_json_value<T: serde::ser::Serialize + ?Sized>(
    value: &T,
) -> core::result::Result<JsValue, serde_wasm_bindgen::Error> {
    let serializer = serde_wasm_bindgen::Serializer::new().serialize_maps_as_objects(true);
    value.serialize(&serializer)
}

pub fn runtime_error(error_message: String) -> JsValue {
    to_json_value::<Transmission<(), ()>>(&WarpResult::RuntimeError(error_message).into()).unwrap()
}