Skip to content

Commit

Permalink
feat(api) remove test meta usage (#1710)
Browse files Browse the repository at this point in the history
  • Loading branch information
Zewasik authored Jan 27, 2025
1 parent 87187b3 commit 8bea095
Show file tree
Hide file tree
Showing 8 changed files with 186 additions and 138 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions apis/gear/programs/test/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ edition = "2021"

[dependencies]
gstd.workspace = true
codec.workspace = true

[build-dependencies]
gear-wasm-builder.workspace = true
73 changes: 69 additions & 4 deletions apis/gear/programs/test/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,79 @@
#![no_std]

extern crate gstd;
use codec::{Decode, Encode};
use gstd::{
collections::{BTreeMap, BTreeSet},
msg,
prelude::*,
};

#[derive(Decode, Encode)]
pub enum Action {
One(Option<String>),
Two((u8, u16)),
Four(),
Input(String),
Wait(),
}

#[derive(Decode, Encode)]
pub struct InputStruct {
pub input: String,
}

#[derive(Encode, Decode, Clone)]
pub struct EmptyStruct {
pub empty: (),
}

#[no_mangle]
unsafe extern "C" fn init() {
gstd::msg::reply("ok", 0).unwrap();
}
let _: BTreeSet<u8> = msg::load().expect("Failed to load init arguments");

let mut res: BTreeMap<String, u8> = BTreeMap::new();

res.insert("One".into(), 1);

msg::reply(res, 0).unwrap();
}

#[gstd::async_main]
async fn main() {
gstd::exec::wait();
let action: Action = msg::load().expect("Failed to load Action");

match action {
Action::One(_) => msg::send_with_gas(
msg::source(),
EmptyStruct { empty: () },
10000000,
10_000_000_000_000,
)
.unwrap(),
Action::Four() => {
let response: String = msg::send_for_reply_as(msg::source(), "reply", 0, 0)
.expect("Unable to send msg for reply")
.await
.expect("Error in async");
msg::reply(response, 0).unwrap()
}
Action::Input(input) => {
if input != "Handle" {
panic!("Wrong input");
}

let response: InputStruct = msg::send_bytes_for_reply_as(msg::source(), b"PING", 0, 0)
.expect("Unable to send message for reply")
.await
.expect("Error in async");

if response.input != "Reply" {
panic!("Wrong input");
}
msg::reply_bytes(b"ok", 0).unwrap()
}
Action::Wait() => {
gstd::exec::wait();
}
_ => msg::reply("ok", 0).unwrap(),
};
}
62 changes: 24 additions & 38 deletions apis/gear/test/Message.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ import { HexString } from '@polkadot/util/types';
import { KeyringPair } from '@polkadot/keyring/types';
import { readFileSync } from 'fs';

import { TEST_META, TEST_META_CODE } from './config';
import { ProgramMetadata } from '../src';
import { checkInit, getAccount, sendTransaction, sleep } from './utilsFunctions';
import { TEST_CODE } from './config';
import { checkInit, createPayload, getAccount, sendTransaction, sleep } from './utilsFunctions';
import { decodeAddress } from '../src/utils';
import { getApi } from './common';

Expand All @@ -13,9 +12,7 @@ let alice: KeyringPair;
let programId: HexString;
let messageToClaim: HexString;

const code = Uint8Array.from(readFileSync(TEST_META_CODE));
const metaHex: HexString = `0x${readFileSync(TEST_META, 'utf-8')}`;
const metadata = ProgramMetadata.from(metaHex);
const code = Uint8Array.from(readFileSync(TEST_CODE));

beforeAll(async () => {
await api.isReadyOrError;
Expand All @@ -29,14 +26,11 @@ afterAll(async () => {

describe('Gear Message', () => {
test('upload test_meta', async () => {
programId = api.program.upload(
{
code,
initPayload: [1, 2, 3],
gasLimit: 200_000_000_000,
},
metadata,
).programId;
programId = api.program.upload({
code,
initPayload: [1, 2, 3],
gasLimit: 200_000_000_000,
}).programId;
const status = checkInit(api, programId);
const [txData] = await sendTransaction(api.program, alice, ['MessageQueued']);
expect(txData.destination.toHex()).toBe(programId);
Expand All @@ -45,27 +39,22 @@ describe('Gear Message', () => {

test('send messages', async () => {
const messages = [
{ payload: { Two: [[8, 16]] }, reply: '0x086f6b', claim: true },
{ payload: createPayload('Action', { Two: [8, 16] }), reply: '0x086f6b', claim: true },
{
payload: {
One: 'Dmitriy',
},
payload: createPayload('Action', { One: 'Dmitriy' }),
value: 10_000_000_000_000,
reply: '0x',
},
];

for (const message of messages) {
const tx = api.message.send(
{
destination: programId,
payload: message.payload,
gasLimit: 20_000_000_000,
value: message.value,
keepAlive: true,
},
metadata,
);
const tx = api.message.send({
destination: programId,
payload: message.payload.toHex(),
gasLimit: 20_000_000_000,
value: message.value,
keepAlive: true,
});

const [txData, blockHash] = await sendTransaction(tx, alice, ['MessageQueued']);
expect(txData).toBeDefined();
Expand Down Expand Up @@ -115,20 +104,17 @@ describe('Gear Message', () => {
});

test('calculate reply', async () => {
const payload = { Two: [[8, 16]] };
const payload = createPayload('Action', { Two: [8, 16] }).toHex();

const origin = decodeAddress(alice.address);

await api.program.calculateGas.handle(origin, programId, { Two: [[8, 16]] }, 0, false, metadata);
await api.program.calculateGas.handle(origin, programId, payload, 0, false);

const result = await api.message.calculateReply(
{
origin,
destination: programId,
payload,
},
metadata,
);
const result = await api.message.calculateReply({
origin,
destination: programId,
payload,
});

const resultJson = result.toJSON();

Expand Down
56 changes: 19 additions & 37 deletions apis/gear/test/Program.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ import { blake2AsHex } from '@polkadot/util-crypto';
import { bufferToU8a } from '@polkadot/util';
import { readFileSync } from 'fs';

import { TEST_META, TEST_META_CODE } from './config';
import { ProgramMetadata } from '../src';
import { checkInit, getAccount, sendTransaction, sleep, waitForPausedProgram } from './utilsFunctions';
import { TEST_CODE } from './config';
import { checkInit, createPayload, getAccount, sendTransaction, sleep, waitForPausedProgram } from './utilsFunctions';
import { getApi } from './common';

const api = getApi();
Expand All @@ -18,8 +17,7 @@ let metaHash: HexString;
let expiredBN: number;
let pausedBlockHash: HexString;

const code = Uint8Array.from(readFileSync(TEST_META_CODE));
const metaHex: HexString = `0x${readFileSync(TEST_META, 'utf-8')}`;
const code = Uint8Array.from(readFileSync(TEST_CODE));

beforeAll(async () => {
await api.isReadyOrError;
Expand All @@ -33,16 +31,11 @@ afterAll(async () => {

describe('New Program', () => {
test('Upload program', async () => {
const metadata = ProgramMetadata.from(metaHex);

const program = api.program.upload(
{
code,
gasLimit: 200_000_000_000,
initPayload: [1, 2, 3],
},
metadata,
);
const program = api.program.upload({
code,
gasLimit: 200_000_000_000,
initPayload: [1, 2, 3],
});
expect(program.programId).toBeDefined();
expect(program.salt).toBeDefined();
expect(program.codeId).toBeDefined();
Expand Down Expand Up @@ -77,7 +70,7 @@ describe('New Program', () => {
expect(await status).toBe('success');

const reply = await api.message.getReplyEvent(programId, mqData.id.toHex(), blockHash);
expect(metadata.createType(metadata.types.init.output!, reply.data.message.payload).toJSON()).toMatchObject({
expect(createPayload('Init', reply.data.message.payload).toJSON()).toMatchObject({
One: 1,
});
expect(isProgramSetHappened).toBeTruthy();
Expand All @@ -93,17 +86,12 @@ describe('New Program', () => {

test('Create program', async () => {
expect(codeId).toBeDefined();
const metadata = ProgramMetadata.from(metaHex);

const { programId, salt } = api.program.create(
{
codeId,
gasLimit: 200_000_000_000,
initPayload: [4, 5, 6],
},
metadata,
metadata.types.init.input,
);

const { programId, salt } = api.program.create({
codeId,
gasLimit: 200_000_000_000,
initPayload: [4, 5, 6],
});

expect(programId).toBeDefined();
expect(salt).toBeDefined();
Expand All @@ -123,7 +111,7 @@ describe('New Program', () => {
expect(programChangedStatuses).toContain('Active');

const reply = await api.message.getReplyEvent(programId, transactionData.id.toHex(), blockHash);
expect(metadata.createType(metadata.types.init.output!, reply.data.message.payload).toJSON()).toMatchObject({
expect(createPayload('Init', reply.data.message.payload).toJSON()).toMatchObject({
One: 1,
});
});
Expand Down Expand Up @@ -188,25 +176,19 @@ describe('Program', () => {
expect(codeHash).toBe(codeId);
});

test('Get metahash by program id', async () => {
expect(programId).toBeDefined();
metaHash = await api.program.metaHash(programId);
expect(metaHash).toBe(blake2AsHex(metaHex, 256));
});

test('Get metahash by codeId', async () => {
test.skip('Get metahash by codeId', async () => {
expect(programId).toBeDefined();
expect(codeId).toBeDefined();
const codeMetaHash = await api.code.metaHash(codeId);
expect(codeMetaHash).toBe(metaHash);
});

test('Get metahash by wasm', async () => {
test.skip('Get metahash by wasm', async () => {
const codeMetaHash = await api.code.metaHashFromWasm(code);
expect(codeMetaHash).toBe(metaHash);
});

test('Get metahash by wasm if it is Uint8Array', async () => {
test.skip('Get metahash by wasm if it is Uint8Array', async () => {
const codeMetaHash = await api.code.metaHashFromWasm(bufferToU8a(code));
expect(codeMetaHash).toBe(metaHash);
});
Expand Down
Loading

0 comments on commit 8bea095

Please sign in to comment.