gsdk 1.10.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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
// This file is part of Gear.
//
// Copyright (C) 2023-2025 Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Requires node to be built in release mode

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

mod utils;

#[tokio::test]
async fn pallet_errors_formatting() -> Result<()> {
    let node = dev_node();
    let api = Api::new(node.ws().as_str()).await?;

    let err = api
        .calculate_upload_gas(
            [0u8; 32].into(),
            /* invalid code */ vec![],
            vec![],
            0,
            true,
            None,
        )
        .await
        .expect_err("Must return error")
        .unwrap_subxt_rpc();

    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 = dev_node();
    let api = Api::new(node.ws().as_str()).await?;

    let alice: [u8; 32] = *alice_account_id().as_ref();

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

    Ok(())
}

#[tokio::test]
async fn test_calculate_create_gas() -> Result<()> {
    let node = dev_node();

    // 1. upload code.
    let signer = Api::new(node.ws().as_str())
        .await?
        .signer("//Alice", None)?;
    signer
        .calls()
        .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 = signer
        .rpc()
        .calculate_create_gas(None, code_id, vec![], 0, true, None)
        .await?;

    signer
        .calls()
        .create_program(code_id, vec![], vec![], gas_info.min_limit, 0)
        .await?;

    Ok(())
}

#[tokio::test]
async fn test_calculate_handle_gas() -> Result<()> {
    let node = dev_node();

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

    // 1. upload program.
    let signer = Api::new(node.ws().as_str())
        .await?
        .signer("//Alice", None)?;

    signer
        .calls()
        .upload_program(
            demo_messenger::WASM_BINARY.to_vec(),
            salt,
            vec![],
            100_000_000_000,
            0,
        )
        .await?;

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

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

    signer
        .calls()
        .send_message(pid, vec![], gas_info.min_limit, 0)
        .await?;

    Ok(())
}

#[tokio::test]
async fn test_calculate_reply_gas() -> Result<()> {
    let node = dev_node();

    let alice: [u8; 32] = *alice_account_id().as_ref();

    let salt = vec![];

    let pid = ActorId::generate_from_user(CodeId::generate(demo_waiter::WASM_BINARY), &salt);
    let payload = demo_waiter::Command::SendUpTo(alice, 10);

    // 1. upload program.
    let signer = Api::new(node.ws().as_str())
        .await?
        .signer("//Alice", None)?;
    signer
        .calls()
        .upload_program(
            demo_waiter::WASM_BINARY.to_vec(),
            salt,
            vec![],
            100_000_000_000,
            0,
        )
        .await?;

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

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

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

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

    signer
        .calls()
        .send_reply(message_id, vec![], gas_info.min_limit, 0)
        .await?;

    Ok(())
}

#[tokio::test]
async fn test_subscribe_program_state_changes() -> Result<()> {
    let node = dev_node();
    let api = Api::new(node.ws().as_str()).await?;

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

    let signer = api.clone().signer("//Alice", None)?;
    let salt = b"state-change".to_vec();

    let tx = signer
        .calls()
        .upload_program(
            demo_messenger::WASM_BINARY.to_vec(),
            salt,
            vec![],
            100_000_000_000,
            0,
        )
        .await?;

    let program_id = api
        .events_of(&tx)
        .await?
        .into_iter()
        .find_map(|event| {
            if let Event::Gear(gear::gear::Event::ProgramChanged { id, .. }) = event {
                Some(id)
            } else {
                None
            }
        })
        .expect("program change event not found");

    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<()> {
    let git_commit_hash = || -> Cow<str> {
        // This code is taken from
        // https://github.com/paritytech/substrate/blob/ae1a608c91a5da441a0ee7c26a4d5d410713580d/utils/build-script-utils/src/version.rs#L21
        if let Ok(hash) = std::env::var("SUBSTRATE_CLI_GIT_COMMIT_HASH") {
            Cow::from(hash.trim().to_owned())
        } else {
            // 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() => {
                    let sha = String::from_utf8_lossy(&o.stdout).trim().to_owned();
                    Cow::from(sha)
                }
                Ok(o) => {
                    println!("cargo:warning=Git command failed with status: {}", o.status);
                    Cow::from("unknown")
                }
                Err(err) => {
                    println!("cargo:warning=Failed to execute git command: {err}");
                    Cow::from("unknown")
                }
            }
        }
    };

    // 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 = git_commit_hash();
    assert_ne!(git_commit_hash, "unknown");

    let node = dev_node();
    let api = Api::new(node.ws().as_str()).await?;
    let mut finalized_blocks = api.subscribe_finalized_blocks().await?;

    let wasm_blob_version_1 = api.runtime_wasm_blob_version(None).await?;
    assert!(
        wasm_blob_version_1.ends_with(git_commit_hash.as_ref()),
        "The WASM blob version {wasm_blob_version_1} does not end with the git commit hash {git_commit_hash}",
    );

    let block_hash_1 = finalized_blocks.next_events().await?.unwrap().block_hash();
    let wasm_blob_version_2 = api.runtime_wasm_blob_version(Some(block_hash_1)).await?;
    assert_eq!(wasm_blob_version_1, wasm_blob_version_2);

    let block_hash_2 = finalized_blocks.next_events().await?.unwrap().block_hash();
    let wasm_blob_version_3 = api.runtime_wasm_blob_version(Some(block_hash_2)).await?;
    assert_ne!(block_hash_1, block_hash_2);
    assert_eq!(wasm_blob_version_2, wasm_blob_version_3);

    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 wasm_blob_version_err = api
        .runtime_wasm_blob_version(Some(no_method_block_hash))
        .await
        .unwrap_err()
        .unwrap_subxt_rpc();

    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 = dev_node();

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

    let signer = Api::new(node.ws().as_str())
        .await?
        .signer("//Alice", None)?;

    signer
        .calls()
        .upload_program(
            demo_messenger::WASM_BINARY.to_vec(),
            salt,
            vec![],
            100_000_000_000,
            0,
        )
        .await?;

    let program = signer.api().gprog(pid).await?;
    let rpc = signer.api().backend();
    let block_hash = rpc.latest_finalized_block_ref().await?.hash();
    let code = signer
        .api()
        .original_code_storage_at(program.code_id.into_bytes().into(), Some(block_hash))
        .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 = dev_node();

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

    // 1. upload program.
    let signer = Api::new(node.ws().as_str())
        .await?
        .signer("//Alice", None)?;

    let payload = InitConfig::test_sequence().encode();

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

    assert!(
        signer.api().gprog(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 = signer
        .rpc()
        .calculate_reply_for_handle(None, pid, message_in.encode(), 100_000_000_000, 0, None)
        .await?;

    // 3. assert
    assert_eq!(
        reply_info,
        ReplyInfo {
            payload: message_out.encode(),
            value: 0,
            code: ReplyCode::Success(SuccessReplyReason::Manual)
        }
    );

    Ok(())
}

#[tokio::test]
async fn test_calculate_reply_for_handle_does_not_change_state() -> Result<()> {
    let node = dev_node();

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

    // 1. upload program.
    let signer = Api::new(node.ws().as_str())
        .await?
        .signer("//Alice", None)?;

    signer
        .calls()
        .upload_program(
            demo_vec::WASM_BINARY.to_vec(),
            salt,
            vec![],
            100_000_000_000,
            0,
        )
        .await?;

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

    // 2. read initial state
    let pid_h256 = H256::from_slice(pid.as_ref());
    let initial_state = signer.api().read_state(pid_h256, vec![], None).await?;

    // 3. calculate reply for handle
    let reply_info = signer
        .rpc()
        .calculate_reply_for_handle(None, pid, 42i32.encode(), 100_000_000_000, 0, None)
        .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 = signer.api().read_state(pid_h256, vec![], None).await?;

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

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

    // 8. read state after call
    let updated_state = signer.api().read_state(pid_h256, vec![], None).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 signer = Api::new(uri).await?.signer("//Alice", None)?;

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

            (hash, block.number())
        }

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

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

    let storage = signer.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 += signer.api().gpages(program_id, None).await?.len() as u64;
        }
    }

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