gsdk 2.0.0

Rust SDK of the Gear network
Documentation
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
// Copyright (C) Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

//! Requires node to be built in release mode

use futures::prelude::*;
use gear_core::{
    ids::{ActorId, CodeId, prelude::*},
    rpc::ReplyInfo,
};
use gear_core_errors::{ReplyCode, SuccessReplyReason};
use gsdk::{AccountKeyring, Api, Error, Result, gear};
use parity_scale_codec::Encode;
use std::{process::Command, str::FromStr, time::Instant};
use subxt::{
    ext::subxt_rpcs::{Error as SubxtRpcError, UserError, rpc_params},
    utils::{AccountId32, H256},
};
use tokio::time::{Duration, timeout};
use utils::dev_node;

mod utils;

#[tokio::test]
async fn pallet_errors_formatting() -> Result<()> {
    let (_node, api) = dev_node().await;

    let err = api
        .unsigned()
        .calculate_upload_gas(
            AccountId32([0u8; 32]),
            /* invalid code */ vec![],
            vec![],
            0,
            true,
        )
        .await
        .expect_err("Must return error");
    let Error::SubxtRpc(err) = err else {
        panic!("unexpected error variant: {err:?}")
    };

    let expected_err = SubxtRpcError::User(UserError {
        code: 8000,
        message: "Runtime error".into(),
        data: Some(
            serde_json::value::to_raw_value(
                "Extrinsic `gear.upload_program` failed: 'ProgramConstructionFailed'",
            )
            .unwrap(),
        ),
    });

    assert_eq!(err.to_string(), expected_err.to_string());

    Ok(())
}

#[tokio::test]
async fn test_calculate_upload_gas() -> Result<()> {
    let (_node, api) = dev_node().await;

    api.calculate_upload_gas(demo_messenger::WASM_BINARY.to_vec(), vec![], 0, true)
        .await?;

    Ok(())
}

#[tokio::test]
async fn test_calculate_create_gas() -> Result<()> {
    let (_node, api) = dev_node().await;

    // 1. upload code.
    api.upload_code(demo_messenger::WASM_BINARY.to_vec())
        .await?;

    // 2. calculate create gas and create program.
    let code_id = CodeId::generate(demo_messenger::WASM_BINARY);
    let gas_info = api.calculate_create_gas(code_id, vec![], 0, true).await?;

    api.create_program_bytes(code_id, vec![], vec![], gas_info.min_limit, 0)
        .await?;

    Ok(())
}

#[tokio::test]
async fn test_read_wasm_custom_section() -> Result<()> {
    let (_node, api) = dev_node().await;

    let wat_code = r#"
        (module
            (import "env" "memory" (memory 0))
            (export "init" (func $init))
            (func $init)
            (@custom "sails:idl" "hello idl")
        )
    "#;
    let wasm = wat::parse_str(wat_code).unwrap();

    let upload = api.upload_code(wasm).await?;
    let upload_block_hash = upload.block_hash;
    let code_id = upload.value;

    let present = api.read_wasm_custom_section(code_id, "sails:idl").await?;
    assert_eq!(
        present.as_ref().map(|bytes| bytes.0.as_slice()),
        Some(b"hello idl".as_ref())
    );

    let present_at_upload = api
        .read_wasm_custom_section_at(code_id, "sails:idl", upload_block_hash)
        .await?;
    assert_eq!(
        present_at_upload.as_ref().map(|bytes| bytes.0.as_slice()),
        Some(b"hello idl".as_ref())
    );

    let missing_section = api
        .read_wasm_custom_section(code_id, "no:such:section")
        .await?;
    assert!(missing_section.is_none());

    let unknown_code = api
        .read_wasm_custom_section(CodeId::from([0u8; 32]), "sails:idl")
        .await?;
    assert!(unknown_code.is_none());

    Ok(())
}

#[tokio::test]
async fn test_calculate_handle_gas() -> Result<()> {
    let (_node, api) = dev_node().await;

    let salt = vec![];
    let pid = ActorId::generate_from_user(CodeId::generate(demo_messenger::WASM_BINARY), &salt);

    // 1. upload program.
    api.upload_program_bytes(
        demo_messenger::WASM_BINARY.to_vec(),
        salt,
        vec![],
        100_000_000_000,
        0,
    )
    .await?;

    assert!(
        api.active_program(pid).await.is_ok(),
        "Program not exists on chain."
    );

    // 2. calculate handle gas and send message.
    let gas_info = api.calculate_handle_gas(pid, vec![], 0, true).await?;

    api.send_message_bytes(pid, vec![], gas_info.min_limit, 0)
        .await?;

    Ok(())
}

#[tokio::test]
async fn test_calculate_reply_gas() -> Result<()> {
    let (_node, api) = dev_node().await;

    let salt = vec![];

    let pid = ActorId::generate_from_user(CodeId::generate(demo_waiter::WASM_BINARY), &salt);
    let payload = demo_waiter::Command::SendUpTo(AccountKeyring::Alice.to_account_id().into(), 10);

    // 1. upload program.
    api.upload_program_bytes(
        demo_waiter::WASM_BINARY.to_vec(),
        salt,
        vec![],
        100_000_000_000,
        0,
    )
    .await?;

    assert!(
        api.active_program(pid).await.is_ok(),
        "Program not exists on chain"
    );

    // 2. send wait message.
    api.send_message(pid, payload, 100_000_000_000, 0).await?;

    let mailbox = api.mailbox_messages(10).await?;
    assert_eq!(mailbox.len(), 1);
    let message_id = mailbox[0].0.id();

    // 3. calculate reply gas and send reply.
    let gas_info = api.calculate_reply_gas(message_id, vec![], 0, true).await?;

    api.send_reply_bytes(message_id, vec![], gas_info.min_limit, 0)
        .await?;

    Ok(())
}

#[tokio::test]
async fn test_subscribe_program_state_changes() -> Result<()> {
    let (_node, api) = dev_node().await;

    let mut subscription = api.subscribe_program_state_changes(None).await?;

    let salt = b"state-change".to_vec();

    let program_id = api
        .upload_program_bytes(
            demo_messenger::WASM_BINARY.to_vec(),
            salt,
            vec![],
            100_000_000_000,
            0,
        )
        .await?
        .value
        .1;

    let expected_id = H256::from(program_id.into_bytes());

    let change = timeout(Duration::from_secs(30), async {
        loop {
            let event = subscription.next().await;
            println!("Got event: {event:?}");
            match event {
                Some(Ok(event)) if event.program_ids.contains(&expected_id) => break Ok(event),
                Some(Ok(_)) => continue,
                Some(Err(err)) => break Err(err),
                None => break Err(Error::EventNotFound),
            }
        }
    })
    .await
    .expect("timed out waiting for program state change")?;

    assert!(change.program_ids.contains(&expected_id));

    Ok(())
}

#[tokio::test]
async fn test_runtime_wasm_blob_version() -> Result<()> {
    // FIXME: this test relies on the fact the node has been built from the same commit hash
    //        as the test has been.
    let git_commit_hash = {
        // We deliberately set the length here to `11` to ensure that
        // the emitted hash is always of the same length; otherwise
        // it can (and will!) vary between different build environments.
        match Command::new("git")
            .args(["rev-parse", "--short=11", "HEAD"])
            .output()
        {
            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_owned(),
            Ok(o) => panic!("Git command failed with status: {}", o.status),
            Err(err) => panic!("cargo:warning=Failed to execute git command: {err}"),
        }
    };

    let (_node, api) = dev_node().await;
    api.blocks()
        .subscribe_finalized()
        .await?
        .then(|block| async { api.runtime_wasm_blob_version_at(block?.hash()).await })
        .take(4)
        .inspect_ok(|version| {
            assert!(
                version.ends_with(&git_commit_hash),
                "Version `{}` must end with commit hash `{}`",
                version,
                git_commit_hash
            )
        })
        .try_fold(
            api.runtime_wasm_blob_version().await?,
            |version_a, version_b| {
                assert_eq!(version_a, version_b);

                future::ready(Ok(version_b))
            },
        )
        .await?;

    Ok(())
}

#[tokio::test]
async fn test_runtime_wasm_blob_version_history() -> Result<()> {
    let api = Api::new("wss://archive-rpc.vara.network:443").await?;

    let no_method_block_hash =
        H256::from_str("0xa84349fc30b8f2d02cc31d49fe8d4a45b6de5a3ac1f1ad975b8920b0628dd6b9")
            .unwrap();

    let err = api
        .runtime_wasm_blob_version_at(no_method_block_hash)
        .await
        .unwrap_err();
    let Error::SubxtRpc(wasm_blob_version_err) = err else {
        panic!("unexpected error variant: {err:?}")
    };

    let err = SubxtRpcError::User(UserError {
        code: 9000,
        message: "Unable to find WASM blob version in WASM blob".into(),
        data: None,
    });

    assert_eq!(wasm_blob_version_err.to_string(), err.to_string());

    Ok(())
}

#[tokio::test]
async fn test_original_code_storage() -> Result<()> {
    let (_node, api) = dev_node().await;

    let salt = vec![];
    let pid = ActorId::generate_from_user(CodeId::generate(demo_messenger::WASM_BINARY), &salt);

    api.upload_program_bytes(
        demo_messenger::WASM_BINARY.to_vec(),
        salt,
        vec![],
        100_000_000_000,
        0,
    )
    .await?;

    let program = api.active_program(pid).await?;
    let code = api
        .original_code(program.code_id.into_bytes().into())
        .await?;

    assert_eq!(
        code,
        demo_messenger::WASM_BINARY.to_vec(),
        "Program code mismatched"
    );

    Ok(())
}

// The test demonstrates how to query some storage at a lower level.
#[ignore]
#[tokio::test]
async fn test_program_counters() -> Result<()> {
    // let uri = String::from("wss://rpc.vara.network:443");
    // let uri = String::from("wss://archive-rpc.vara.network:443");
    let uri = String::from("wss://testnet.vara.network:443");
    // https://polkadot.js.org/apps/?rpc=wss://archive-rpc.vara.network#/explorer/query/9642000
    // let block_hash = H256::from_slice(&hex::decode("533ab8551fc1ecc812cfa4fa91d8667bfb3bdbcf64eacc5fccdbbf9b20e539a3")?);
    let instant = Instant::now();
    let (block_hash, block_number, count_program, count_active_program, count_memory_page) =
        query_program_counters(&uri, None).await?;
    println!("elapsed = {:?}", instant.elapsed());
    println!(
        "testnet block_hash = {block_hash}, block_number = {block_number}, count_program = {count_program}, count_active_program = {count_active_program}, count_memory_page = {count_memory_page}"
    );

    Ok(())
}

#[tokio::test]
async fn test_calculate_reply_for_handle() -> Result<()> {
    use demo_fungible_token::{FTAction, FTEvent, InitConfig, WASM_BINARY};

    let (_node, api) = dev_node().await;

    let salt = vec![];
    let pid = ActorId::generate_from_user(CodeId::generate(WASM_BINARY), &salt);

    // 1. upload program.
    let payload = InitConfig::test_sequence();

    api.upload_program(WASM_BINARY.to_vec(), salt, payload, 100_000_000_000, 0)
        .await?;

    assert!(
        api.active_program(pid).await.is_ok(),
        "Program not exists on chain."
    );

    let message_in = FTAction::TotalSupply;

    let message_out = FTEvent::TotalSupply(0);

    // 2. calculate reply for handle
    let reply_info = api
        .calculate_reply_for_handle(pid, message_in.encode(), 100_000_000_000, 0)
        .await?;
    let raw_reply_info: serde_json::Value = api
        .rpc()
        .request(
            "gear_calculateReplyForHandle",
            rpc_params![
                H256::from_slice(api.account_id().as_ref()),
                H256(pid.into_bytes()),
                hex::encode(message_in.encode()),
                100_000_000_000u64,
                0
            ],
        )
        .await?;
    let reply_result = api
        .calculate_reply_for_handle_result(pid, message_in.encode(), 100_000_000_000, 0)
        .await?;

    // 3. assert
    assert_eq!(
        reply_info,
        ReplyInfo {
            payload: message_out.encode(),
            value: 0,
            code: ReplyCode::Success(SuccessReplyReason::Manual)
        }
    );
    assert_eq!(
        raw_reply_info,
        serde_json::json!({
            "payload": format!("0x{}", hex::encode(message_out.encode())),
            "value": 0,
            "code": {
                "Success": "Manual"
            }
        })
    );
    assert_eq!(reply_result.reply, reply_info);
    assert!(reply_result.messages.is_empty());

    Ok(())
}

#[tokio::test]
async fn test_calculate_reply_for_handle_does_not_change_state() -> Result<()> {
    let (_node, api) = dev_node().await;

    let salt = vec![];
    let pid = ActorId::generate_from_user(CodeId::generate(demo_vec::WASM_BINARY), &salt);

    // 1. upload program.
    api.upload_program_bytes(
        demo_vec::WASM_BINARY.to_vec(),
        salt,
        vec![],
        100_000_000_000,
        0,
    )
    .await?;

    assert!(
        api.active_program(pid).await.is_ok(),
        "Program not exists on chain."
    );

    // 2. read initial state
    let initial_state = api.read_state_bytes(pid, vec![]).await?;

    // 3. calculate reply for handle
    let reply_info = api
        .calculate_reply_for_handle(pid, 42i32.encode(), 100_000_000_000, 0)
        .await?;

    // 4. assert that calculated result correct
    assert_eq!(
        reply_info,
        ReplyInfo {
            payload: 42i32.encode(),
            value: 0,
            code: ReplyCode::Success(SuccessReplyReason::Manual)
        }
    );

    // 5. read state after calculate
    let calculated_state = api.read_state_bytes(pid, vec![]).await?;

    // 6. assert that state hasn't changed
    assert_eq!(initial_state, calculated_state);

    // 7. make call
    api.send_message(pid, 42i32, 100_000_000_000, 0).await?;

    // 8. read state after call
    let updated_state = api.read_state_bytes(pid, vec![]).await?;

    // 9. assert that state has changed
    assert_ne!(initial_state, updated_state);

    Ok(())
}

async fn query_program_counters(
    uri: &str,
    block_hash: Option<H256>,
) -> Result<(H256, u32, u64, u64, u64)> {
    use gsdk::gear::runtime_types::gear_core::program::Program;
    use parity_scale_codec::Decode;

    let api = Api::new(uri).await?.signed_as_alice();

    let (block_hash, block_number) = match block_hash {
        Some(hash) => {
            let block = api.blocks().at(hash).await?;
            assert_eq!(hash, block.hash(), "block hash mismatched");

            (hash, block.number())
        }

        None => {
            let latest_block = api.blocks().at_latest().await?;

            (latest_block.hash(), latest_block.number())
        }
    };

    let storage = api.storage_at(Some(block_hash)).await?;
    let addr = gear::storage().gear_program().program_storage_iter();

    let mut iter = storage.iter(addr).await?;
    let mut count_memory_page = 0u64;
    let mut count_program = 0u64;
    let mut count_active_program = 0u64;
    while let Some(pair) = iter.next().await {
        let pair = pair?;
        let (key, program) = (pair.key_bytes, pair.value);

        count_program += 1;

        let program_id = ActorId::decode(&mut key.as_ref())?;

        if let Program::Active(_) = program {
            count_active_program += 1;
            count_memory_page += api.program_pages(program_id).await?.len() as u64;
        }
    }

    Ok((
        block_hash,
        block_number,
        count_program,
        count_active_program,
        count_memory_page,
    ))
}