Skip to content

Commit

Permalink
update query metadata func
Browse files Browse the repository at this point in the history
  • Loading branch information
vladilen11 committed Feb 21, 2024
1 parent e7c3793 commit 1d21876
Show file tree
Hide file tree
Showing 7 changed files with 133 additions and 54 deletions.
1 change: 1 addition & 0 deletions packages/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"@polkadot/keyring": "^12.3.1",
"@polkadot/types": "^10.11.2",
"@polkadot/util": "^12.6.2",
"@polkadot/util-crypto": "^12.6.2",
"@scure/bip39": "^1.2.1",
"assert": "^2.1.0",
"colorts": "^0.1.63",
Expand Down
12 changes: 10 additions & 2 deletions packages/client/scripts/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ dotenv.config();
async function init() {
const network = Network.TESTNET;
const packageId =
'0xdd1a5cabd1b187dfef39a7c04b2e112ad999ec46f521a408db89297b7973b6c6';
'0x2ef238dc49a7c63bc87549f6b084123a35953265d7028a30ad53fc004b892c26';

const privateKey = process.env.PRIVATE_KEY;

Expand All @@ -23,7 +23,15 @@ async function init() {
secretKey: privateKey,
});

console.log(templs.getAddress());
// console.log(await templs.getAddress());
let addr = await templs.getAddress();
console.log('address: ' + addr);

let metadata = await templs.getMetadata(packageId);
console.log('metadata: ' + metadata);

let data = await templs.varaInteractor.queryState(packageId);
console.log('data: ', data);
}

init();
16 changes: 8 additions & 8 deletions packages/client/src/libs/varaAccountManager/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export class VaraAccountManager {
private mnemonics: string;
private secretKey: string;
public currentKeyPair: Promise<KeyringPair>;
public currentAddress!: string;
// public currentAddress!: string;

/**
* Support the following ways to init the VaraToolkit:
Expand All @@ -33,9 +33,9 @@ export class VaraAccountManager {
? createAccount(this.secretKey)
: createAccount(this.mnemonics);
// Wait for the promise to resolve and then set the currentAddress
this.currentKeyPair.then((keyPair: KeyringPair) => {
this.currentAddress = keyPair.address;
});
// this.currentKeyPair.then((keyPair: KeyringPair) => {
// this.currentAddress = keyPair.address;
// });
}

getKeyPair() {
Expand All @@ -44,7 +44,7 @@ export class VaraAccountManager {
}

async getAddress() {
if (!this.mnemonics) return this.currentAddress;
if (!this.mnemonics) return (await this.currentKeyPair).address;
return (await createAccount(this.mnemonics)).address;
}

Expand All @@ -55,9 +55,9 @@ export class VaraAccountManager {
switchAccount() {
if (this.mnemonics) {
this.currentKeyPair = createAccount(this.mnemonics);
this.currentKeyPair.then((keyPair: KeyringPair) => {
this.currentAddress = keyPair.address;
});
// this.currentKeyPair.then((keyPair: KeyringPair) => {
// this.currentAddress = keyPair.address;
// });
}
}
}
13 changes: 4 additions & 9 deletions packages/client/src/libs/varaInteractor/defaultConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,17 @@ export const defaultGasPrice = 1000; // 1000 MIST
* @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'
* @returns { fullNode: string, faucet?: string }
*/
export const getDefaultURL = (networkType: Network = Network.DEVNET) => {
export const getDefaultURL = (networkType: Network = Network.TESTNET) => {
switch (networkType) {
case Network.LOCAL:
return {
fullNode: 'ws://127.0.0.1:9944',
faucet: 'http://127.0.0.1:8081',
};
case Network.DEVNET:
return {
fullNode: 'wss://testnet.vara.network',
faucet: 'https://faucet.devnet.aptoslabs.com',
// faucet: 'http://127.0.0.1:8081',
};
case Network.TESTNET:
return {
fullNode: 'wss://testnet.vara.network',
faucet: 'https://faucet.testnet.aptoslabs.com',
// faucet: 'https://faucet.testnet.aptoslabs.com',
};
case Network.MAINNET:
return {
Expand All @@ -31,7 +26,7 @@ export const getDefaultURL = (networkType: Network = Network.DEVNET) => {
default:
return {
fullNode: 'wss://testnet.vara.network',
faucet: 'https://faucet.devnet.aptoslabs.com',
// faucet: 'https://faucet.devnet.aptoslabs.com',
};
}
};
130 changes: 103 additions & 27 deletions packages/client/src/libs/varaInteractor/varaInteractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,29 @@ import {
MessageSendOptions,
PayloadType,
HexString,
GearKeyring,
decodeAddress,
} from '@gear-js/api';
import { blake2AsHex } from '@polkadot/util-crypto';
// import { SubmittableExtrinsic } from '@polkadot/api/types';
import { ISubmittableResult } from '@polkadot/types/types';
import { FaucetNetworkType, Network } from '../../types';
// import { SuiOwnedObject, SuiSharedObject } from '../suiModel';
import { delay } from './util';
import { Keyring } from '@polkadot/keyring';
import { ProgramMetadata } from '@gear-js/api';
import { GearProgram } from '@gear-js/api/Program';
import { ProgramMetadata, GearProgram } from '@gear-js/api';
import { ApiPromise, WsProvider } from '@polkadot/api';
import { metadata } from '@polkadot/types/interfaces/essentials';
import { KeyringPair } from '@polkadot/keyring/types';

function hexToBinary(hex: string): string {
let binaryString = '';
for (let i = 0; i < hex.length; i++) {
const bin = parseInt(hex[i], 16).toString(2).padStart(4, '0');
binaryString += bin;
}
return binaryString;
}

/**
* `SuiTransactionSender` is used to send transaction with a given gas coin.
Expand Down Expand Up @@ -99,8 +112,7 @@ export class VaraInteractor {
// if you send message with issued voucher
};

const gearProgram = new GearProgram(this.clients[clientIdx]);
const meta = await gearProgram.metaHash(programId);
const meta = await this.clients[clientIdx].program.metaHash(programId);

// In that case payload will be encoded using meta.types.handle.input type
let extrinsic = this.clients[clientIdx].message.send(message, meta);
Expand All @@ -126,39 +138,47 @@ export class VaraInteractor {
}

async callContract(
signer: Keyring,
signer: KeyringPair,
programId: HexString,
metaHash: HexString,
// metaHash: HexString,
payload: PayloadType,
gasLimit: number | undefined,
value: number | undefined
gasLimit?: number,
value?: number
) {
for (const clientIdx in this.clients) {
try {
const message: MessageSendOptions = {
destination: programId, // programId
payload,
gasLimit: gasLimit ? gasLimit : 10000000,
value: value ? value : 1000,
// prepaid: true,
// account: accountId,
// if you send message with issued voucher
};
await delay(1500);
// const alice = signer;

// const payload = {
// One: 'String',
// };

const metaHash = await this.clients[clientIdx].program.metaHash(
programId
);
const meta = ProgramMetadata.from(metaHash);

// In that case payload will be encoded using meta.types.handle.input type
let extrinsic = this.clients[clientIdx].message.send(message, meta);
// So if you want to use another type you can specify it
const gas = await this.clients[clientIdx].program.calculateGas.handle(
decodeAddress(signer.address),
programId,
payload,
20000,
true,
meta
);

extrinsic = this.clients[clientIdx].message.send(
message,
const tx = await this.clients[clientIdx].message.send(
{
destination: programId,
payload,
gasLimit: gas.min_limit,
value: 20000,
},
meta
// meta.types.handle.input
);
// return extrinsic;
return await extrinsic.signAndSend(signer, (event: any) => {
console.log(event.toHuman());
});

return tx;
} catch (err) {
console.warn(
`Failed to send transaction with fullnode ${this.fullNodes[clientIdx]}: ${err}`
Expand All @@ -169,6 +189,62 @@ export class VaraInteractor {
throw new Error('Failed to send transaction with all fullnodes');
}

async getMetaHash(programId: HexString) {
for (const clientIdx in this.clients) {
try {
await delay(1500);
const metaHash = await this.clients[clientIdx].program.metaHash(
programId
);
return metaHash;
} catch (err) {
console.warn(
`Failed to get metaHash with fullnode ${this.fullNodes[clientIdx]}: ${err}`
);
await delay(2000);
}
}
throw new Error('Failed to get metaHash with all fullnodes');
}

async queryState(programId: HexString) {
for (const clientIdx in this.clients) {
try {
await delay(1500);
// const gearProgram = new GearProgram(this.clients[clientIdx]);
const metaHash = await this.clients[clientIdx].program.metaHash(
programId
);
console.log('test hex 1: ', blake2AsHex(metaHash, 256));
console.log('test hex 2: ', metaHash);
const hexString =
'ac3314cfb08f748652d46d8839ddab19d3aebcb100b312c3fcff5beac1f1c1ef';

const binaryString = hexToBinary(hexString);
console.log(binaryString);

const meta = ProgramMetadata.from(`0x${binaryString}`);
console.log(meta);
const state = await this.clients[clientIdx].programState.read(
{
programId: programId as HexString,
payload: {
GetCurrentCounter: null,
},
},
meta
);
return state;
} catch (err) {
console.warn(
`Failed to get metaHash with fullnode ${this.fullNodes[clientIdx]}: ${err}`
);
await delay(2000);
}
}
throw new Error('Failed to get metaHash with all fullnodes');
}

// async getObjects(
// ids: string[],
// options?: SuiObjectDataOptions
Expand Down
14 changes: 7 additions & 7 deletions packages/client/src/templs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
// SuiTxArgument,
Network,
} from './types';
import { GearApi, ProgramMetadata } from '@gear-js/api';
import { GearApi, ProgramMetadata, HexString } from '@gear-js/api';
import { normalizeHexAddress, numberToAddressHex } from './utils';
import keccak256 from 'keccak256';

Expand Down Expand Up @@ -106,8 +106,8 @@ export class Templs {
networkType,
fullnodeUrls,
packageId,
metadata,
}: TemplsParams = {}) {
}: // metadata,
TemplsParams = {}) {
// Init the account manager
this.accountManager = new VaraAccountManager({ mnemonics, secretKey });
// Init the rpc provider
Expand Down Expand Up @@ -233,16 +233,16 @@ export class Templs {
return this.accountManager.getAddress();
}

currentAddress() {
return this.accountManager.currentAddress;
async currentAddress() {
return await this.accountManager.getAddress();
}

getPackageId() {
return this.packageId;
}

getMetadata() {
return this.metadata;
async getMetadata(programId: HexString) {
return await this.varaInteractor.getMetaHash(programId);
}

async getBalance(account?: String) {
Expand Down
1 change: 0 additions & 1 deletion packages/client/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,6 @@ export type DerivePathParams = {
export enum Network {
MAINNET = 'mainnet',
TESTNET = 'testnet',
DEVNET = 'devnet',
LOCAL = 'local',
}
export type FaucetNetworkType = 'testnet' | 'devnet' | 'localnet';
Expand Down

0 comments on commit 1d21876

Please sign in to comment.