pjs_rs/
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
use std::fs;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;

use deno_ast::MediaType;
use deno_ast::ParseParams;
use deno_ast::SourceTextInfo;
use deno_core::error::AnyError;
use deno_core::serde_json;
use deno_core::serde_json::json;
use deno_core::serde_v8;
use deno_core::url;
use deno_core::v8;
use deno_core::JsRuntime;

mod perms;
use perms::ZombiePermissions;

// Not used anymore
// mod cert;
// use cert::ValueRootCertStoreProvider;

mod ext;
use ext::pjs_extension;

type DynLoader = Rc<dyn deno_core::ModuleLoader + 'static>;

#[derive(Debug, PartialEq)]
/// Js script return value, mapping types that can be deserialized as [serde_json::Value] or
/// not, for the latest an string is returned witht the error message.
pub enum ReturnValue {
    Deserialized(serde_json::Value),
    CantDeserialize(String),
}

/// Create a new runtime with the pjs extension built-in.
/// Allow to pass a [ModuleLoader](deno_core::ModuleLoader) to use, by default
/// [NoopModuleLoader](deno_core::NoopModuleLoader) is used.
pub fn create_runtime_with_loader(loader: Option<DynLoader>) -> JsRuntime {
    deno_core::JsRuntime::new(deno_core::RuntimeOptions {
        module_loader: if let Some(loader) = loader {
            Some(loader)
        } else {
            Some(Rc::new(deno_core::NoopModuleLoader))
        },
        startup_snapshot: None,
        extensions: vec![
            deno_console::deno_console::init_ops_and_esm(),
            deno_webidl::deno_webidl::init_ops_and_esm(),
            deno_url::deno_url::init_ops_and_esm(),
            deno_web::deno_web::init_ops_and_esm::<ZombiePermissions>(
                Arc::new(deno_web::BlobStore::default()),
                None,
            ),
            deno_crypto::deno_crypto::init_ops_and_esm(None),
            deno_fetch::deno_fetch::init_ops_and_esm::<ZombiePermissions>(deno_fetch::Options {
                user_agent: "zombienet-agent".to_string(),
                ..Default::default()
            }),
            deno_websocket::deno_websocket::init_ops_and_esm::<ZombiePermissions>(
                "zombienet-agent".to_string(),
                None,
                None,
            ),
            pjs_extension::init_ops_and_esm(),
        ],
        ..Default::default()
    })
}

/// Run a js/ts code from file in an isolated runtime with polkadotjs bundles embedded
///
/// The code runs without any wrapping clousure, and the arguments are binded to the `pjs` Object,
/// available as `pjs.arguments`. If you want to to use top level `await` you will need to wrap your
/// code like we do in [run_file_with_wrap].
///
/// # Example
/// ## Javascript file example
/// ```javascript
/// return pjs.api.consts.babe.epochDuration;
/// ```
/// NOTE: To return a value you need to **explicit** call `return <value>`
///
///
///
/// ## Executing:
/// ```rust
/// # use pjs_rs::run_file;
/// # use deno_core::error::AnyError;
/// # async fn example() -> Result<(), AnyError> {
/// let resp = run_file("./testing/epoch_duration_rococo.js", None).await?;
/// # Ok(())
/// # }
/// ```
///
///
pub async fn run_file(
    file_path: impl AsRef<Path>,
    json_args: Option<Vec<serde_json::Value>>,
) -> Result<ReturnValue, AnyError> {
    let code_content = get_code(file_path).await?;
    run_code(code_content, json_args, false).await
}

/// Run a js/ts code from file in an isolated runtime with polkadotjs bundles embedded
///
/// The code runs in a closure where the `json_args` are passed as `arguments` array
/// and the polkadotjs modules (util, utilCrypto, keyring, types) are exposed from the global `pjs` Object.
/// `ApiPromise` and `WsProvider` are also availables to easy access.
///
/// All code is wrapped within an async closure,
/// allowing access to api methods, keyring, types, util, utilCrypto.
/// ```javascript
/// (async (arguments, ApiPromise, WsProvider, util, utilCrypto, keyring, types) => {
///   ... any user code is executed here ...
/// })();
/// ```
///
/// # Example
/// ## Javascript file example
/// ```javascript
/// const api = await ApiPromise.create({ provider: new pjs.api.WsProvider('wss://rpc.polkadot.io') });
/// const parachains = (await api.query.paras.parachains()) || [];
/// console.log("parachain ids in polkadot:", parachains);
/// return parachains.toJSON();
/// ```
/// NOTE: To return a value you need to **explicit** call `return <value>`
///
///
///
/// ## Executing:
/// ```rust
/// # use pjs_rs::run_file_with_wrap;
/// # use deno_core::error::AnyError;
/// # async fn example() -> Result<(), AnyError> {
/// let resp = run_file_with_wrap("./testing/query_parachains.js", None).await?;
/// # Ok(())
/// # }
/// ```
///
///
pub async fn run_file_with_wrap(
    file_path: impl AsRef<Path>,
    json_args: Option<Vec<serde_json::Value>>,
) -> Result<ReturnValue, AnyError> {
    let code_content = get_code(file_path).await?;
    run_code(&code_content, json_args, true).await
}

pub async fn run_js_code(
    code_content: impl Into<String>,
    json_args: Option<Vec<serde_json::Value>>,
) -> Result<ReturnValue, AnyError> {
    run_code(code_content, json_args, false).await
}

pub async fn run_ts_code(
    code_content: impl Into<String>,
    json_args: Option<Vec<serde_json::Value>>,
) -> Result<ReturnValue, AnyError> {
    let transpiled = transpile(code_content)?;
    run_code(transpiled, json_args, false).await
}

fn transpile(code: impl Into<String>) -> Result<String, AnyError> {
    let parsed = deno_ast::parse_module(ParseParams {
        specifier: url::Url::parse("file:///inner")?,
        text_info: SourceTextInfo::from_string(code.into()),
        media_type: MediaType::TypeScript,
        capture_tokens: false,
        scope_analysis: false,
        maybe_syntax: None,
    })?;

    let transpiled = parsed.transpile(&Default::default(), &Default::default())?;
    Ok(transpiled.into_source().text)
}
async fn get_code(file_path: impl AsRef<Path>) -> Result<String, AnyError> {
    let content = fs::read_to_string(file_path.as_ref())?;

    // Check if we need to transpile (e.g .ts file)
    let code_content = if let MediaType::TypeScript = MediaType::from_path(file_path.as_ref()) {
        transpile(&content)?
    } else {
        content
    };

    Ok(code_content)
}

async fn run_code(
    code_content: impl Into<String>,
    json_args: Option<Vec<serde_json::Value>>,
    use_wrapper: bool,
) -> Result<ReturnValue, AnyError> {
    let code_content = code_content.into();
    let bundle_util = include_str!("js/bundle-polkadot-util.js");
    let bundle_util_crypto = include_str!("js/bundle-polkadot-util-crypto.js");
    let bundle_keyring = include_str!("js/bundle-polkadot-keyring.js");
    let bundle_types = include_str!("js/bundle-polkadot-types.js");
    let bundle_api = include_str!("js/bundle-polkadot-api.js");
    // Code templates
    let code = if use_wrapper {
        format!(
            r#"
        const {{ ApiPromise, WsProvider }} = pjs.api;
        const {{ util, utilCrypto, keyring, types }} = pjs;
        (async (arguments, ApiPromise, WsProvider, util, utilCrypto, keyring, types) => {{
            {}
        }})({}, ApiPromise, WsProvider, util, utilCrypto, keyring, types)"#,
            &code_content,
            json!(json_args.unwrap_or_default())
        )
    } else {
        format!(
            r#"
            pjs.arguments = {};
            {}
            "#,
            json!(json_args.unwrap_or_default()),
            &code_content
        )
    };

    log::trace!("code: \n{}", code);

    let mut js_runtime = create_runtime_with_loader(None);
    let with_bundle = format!(
        "
    {}
    {}
    {}
    {}
    {}

    let pjs = {{
        util: polkadotUtil,
        utilCrypto: polkadotUtilCrypto,
        keyring: polkadotKeyring,
        types: polkadotTypes,
        api: polkadotApi,
    }};

    {}
    ",
        bundle_util, bundle_util_crypto, bundle_keyring, bundle_types, bundle_api, code
    );
    log::trace!("full code: \n{}", with_bundle);
    execute_script(&mut js_runtime, &with_bundle).await
}
async fn execute_script(
    js_runtime: &mut JsRuntime,
    code: impl Into<String>,
) -> Result<ReturnValue, AnyError> {
    // Execution
    let executed = js_runtime.execute_script("name", deno_core::FastString::from(code.into()))?;
    let resolve = js_runtime.resolve(executed);
    let resolved = js_runtime
        .with_event_loop_promise(resolve, deno_core::PollEventLoopOptions::default())
        .await;
    match resolved {
        Ok(global) => {
            let scope = &mut js_runtime.handle_scope();
            let local = v8::Local::new(scope, global);
            // Deserialize a `v8` object into a Rust type using `serde_v8`,
            // in this case deserialize to a JSON `Value`.
            let deserialized_value = serde_v8::from_v8::<serde_json::Value>(scope, local);

            let resp = match deserialized_value {
                Ok(value) => {
                    log::debug!("{:#?}", value);
                    ReturnValue::Deserialized(value)
                }
                Err(err) => {
                    log::warn!("{}", format!("Cannot deserialize value: {:?}", err));
                    ReturnValue::CantDeserialize(err.to_string())
                }
            };

            Ok(resp)
        }
        Err(err) => {
            log::error!("{}", format!("Evaling error: {:?}", err));
            Err(err)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn query_parachains_works() {
        let resp = run_file_with_wrap("./testing/query_parachains.ts", None)
            .await
            .unwrap();
        if let ReturnValue::Deserialized(value) = resp {
            let first_para_id = value.as_array().unwrap().first().unwrap().as_u64().unwrap();
            assert_eq!(first_para_id, 1000_u64);
        }
    }

    #[tokio::test]
    async fn consts_works() {
        let resp = run_file("./testing/epoch_duration_rococo.js", None)
            .await
            .unwrap();

        println!("{:#?}", resp);
        assert!(matches!(resp, ReturnValue::Deserialized { .. }));
        if let ReturnValue::Deserialized(value) = resp {
            assert_eq!(value, json!(600));
        }
    }

    #[tokio::test]
    async fn query_parachains_without_wrap_works() {
        let resp = run_file("./testing/query_parachains_no_wrap.ts", None)
            .await
            .unwrap();
        assert!(matches!(resp, ReturnValue::Deserialized { .. }));
        if let ReturnValue::Deserialized(value) = resp {
            println!("{:?}", value);
            let first_para_id = value.as_array().unwrap().first().unwrap().as_u64().unwrap();
            assert_eq!(first_para_id, 1000_u64);
        }
    }

    #[tokio::test]
    async fn query_parachains_from_ts_code_works() {
        let ts_code = r#"
        (async () => {
            const api = await pjs.api.ApiPromise.create({ provider: new pjs.api.WsProvider('wss://rpc.polkadot.io') });
            const parachains: number[] = (await api.query.paras.parachains()) || [];

            return parachains.toJSON();
        })();
        "#;
        let resp = run_ts_code(ts_code, None).await.unwrap();
        assert!(matches!(resp, ReturnValue::Deserialized { .. }));
        if let ReturnValue::Deserialized(value) = resp {
            let first_para_id = value.as_array().unwrap().first().unwrap().as_u64().unwrap();
            assert_eq!(first_para_id, 1000_u64);
        }
    }

    #[tokio::test]
    async fn query_parachains_from_js_code_works() {
        let ts_code = r#"
        (async () => {
            const api = await pjs.api.ApiPromise.create({ provider: new pjs.api.WsProvider('wss://rpc.polkadot.io') });
            const parachains = (await api.query.paras.parachains()) || [];

            return parachains.toJSON();
        })();
        "#;
        let resp = run_ts_code(ts_code, None).await.unwrap();
        assert!(matches!(resp, ReturnValue::Deserialized { .. }));
        if let ReturnValue::Deserialized(value) = resp {
            let first_para_id = value.as_array().unwrap().first().unwrap().as_u64().unwrap();
            assert_eq!(first_para_id, 1000_u64);
        }
    }

    #[tokio::test]
    async fn query_historic_data_rococo_works() {
        run_file_with_wrap("./testing/query_historic_data.js", None)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn query_chain_state_info_rococo_works() {
        run_file_with_wrap(
            "./testing/get_chain_state_info.js",
            Some(vec![json!("wss://rococo-rpc.polkadot.io")]),
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn listen_new_head_works() {
        let resp = run_file_with_wrap(
            "./testing/rpc_listen_new_head.js",
            Some(vec![json!("wss://rococo-rpc.polkadot.io")]),
        )
        .await
        .unwrap();
        assert_eq!(resp, ReturnValue::Deserialized(json!(5)));
    }

    #[tokio::test]
    async fn transfer_works() {
        let args = vec![json!("wss://rococo-rpc.polkadot.io"), json!("//Alice")];
        run_file_with_wrap("./testing/transfer.js", Some(args))
            .await
            .unwrap();
    }
}