@0xtemple/client
Version:
Tookit for interacting with vara eps framework
950 lines (938 loc) • 33.1 kB
JavaScript
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
// src/index.ts
var src_exports = {};
__export(src_exports, {
Network: () => Network,
Temples: () => Temples,
VaraAccountManager: () => VaraAccountManager
});
module.exports = __toCommonJS(src_exports);
__reExport(src_exports, require("@gear-js/api"), module.exports);
// src/libs/varaAccountManager/keypair.ts
var import_api = require("@gear-js/api");
function createAccount(seed) {
if (seed.startsWith("//")) {
return import_api.GearKeyring.fromSuri(seed);
}
if (seed.startsWith("0x")) {
return import_api.GearKeyring.fromSeed(seed);
}
return import_api.GearKeyring.fromMnemonic(seed);
}
// src/libs/varaAccountManager/crypto.ts
var import_bip39 = require("@scure/bip39");
var import_english = require("@scure/bip39/wordlists/english");
var generateMnemonic = (numberOfWords = 24) => {
const strength = numberOfWords === 12 ? 128 : 256;
return (0, import_bip39.generateMnemonic)(import_english.wordlist, strength);
};
// src/libs/varaAccountManager/index.ts
var VaraAccountManager = class {
// public currentAddress!: string;
/**
* Support the following ways to init the VaraToolkit:
* 1. mnemonics
* 2. secretKey (base64 or hex)
* If none of them is provided, will generate a random mnemonics with 24 words.
*
* @param mnemonics, 12 or 24 mnemonics words, separated by space
* @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored
*/
constructor({ mnemonics, secretKey } = {}) {
this.mnemonics = mnemonics || "";
this.secretKey = secretKey || "";
if (!this.mnemonics && !this.secretKey) {
this.mnemonics = generateMnemonic(24);
}
this.currentKeyPair = this.secretKey ? createAccount(this.secretKey) : createAccount(this.mnemonics);
}
getKeyPair() {
if (!this.mnemonics)
return this.currentKeyPair;
return createAccount(this.mnemonics);
}
async getAddress() {
if (!this.mnemonics)
return (await this.currentKeyPair).address;
return (await createAccount(this.mnemonics)).address;
}
/**
* Switch the current account with the given derivePathParams.
* This is only useful when the mnemonics is provided. For secretKey mode, it will always use the same account.
*/
switchAccount() {
if (this.mnemonics) {
this.currentKeyPair = createAccount(this.mnemonics);
}
}
};
// src/libs/varaInteractor/varaInteractor.ts
var import_api2 = require("@gear-js/api");
// src/libs/varaInteractor/util.ts
var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// src/libs/varaInteractor/varaInteractor.ts
var import_api3 = require("@gear-js/api");
var import_api4 = require("@polkadot/api");
var VaraInteractor = class {
constructor(fullNodeUrls, network, connectWs) {
if (fullNodeUrls.length === 0)
throw new Error("fullNodeUrls must not be empty");
this.fullNodes = fullNodeUrls;
if (connectWs === true) {
this.clients = fullNodeUrls.map((fullNodeUrl) => {
return new import_api2.GearApi({
providerAddress: fullNodeUrl.ws,
noInitWarn: true
});
});
} else {
this.clients = fullNodeUrls.map((fullNodeUrl) => {
const httpProvider = new import_api4.HttpProvider(fullNodeUrl.http);
return new import_api2.GearApi({ provider: httpProvider, noInitWarn: true });
});
}
this.currentFullNode = fullNodeUrls[0];
this.currentClient = this.clients[0];
this.network = network;
}
async nodeInfo() {
for (const clientIdx in this.clients) {
try {
const chain = await this.clients[clientIdx].chain();
const nodeName = await this.clients[clientIdx].nodeName();
const nodeVersion = await this.clients[clientIdx].nodeVersion();
return {
chain,
nodeName,
nodeVersion
};
} catch (err) {
console.warn(
`Failed to query node info with fullnode ${this.fullNodes[clientIdx]}: ${err}`
);
await delay(2e3);
}
}
throw new Error("Failed to send transaction with all fullnodes");
}
switchToNextClient() {
const currentClientIdx = this.clients.indexOf(this.currentClient);
this.currentClient = this.clients[(currentClientIdx + 1) % this.clients.length];
this.currentFullNode = this.fullNodes[(currentClientIdx + 1) % this.clients.length];
}
async signAndSend(signer, tx) {
for (const clientIdx in this.clients) {
try {
return await tx.signAndSend(signer, (event) => {
console.log(event.toHuman());
});
} catch (err) {
console.warn(
`Failed to send transaction with fullnode ${this.fullNodes[clientIdx]}: ${err}`
);
await delay(2e3);
}
}
throw new Error("Failed to send transaction with all fullnodes");
}
async structuredTransaction(signer, programId, payload, metadata, gasLimit, value) {
for (const clientIdx in this.clients) {
try {
await delay(1500);
const meta = import_api3.ProgramMetadata.from(
metadata
// '00020000010000000001070000000100000000000000000109000000010a000000d5072c000c34656e67696e655f736368656d611c73746f726167652c536368656d614576656e7400010c245365745265636f72640c0004011c4163746f724964000010011c5665633c75383e000010011c5665633c75383e0000003044656c6574655265636f7264080004011c4163746f724964000010011c5665633c75383e000100205265676973746572040014015c5665633c284163746f7249642c205665633c75383e293e000200000410106773746418636f6d6d6f6e287072696d6974697665731c4163746f724964000004000801205b75383b2033325d000008000003200000000c000c0000050300100000020c0014000002180018000004080410001c0838656e67696e655f73797374656d733053797374656d416374696f6e0001080c41646400000038536574456e746974794c6576656c08002001107531323800002001107531323800010000200000050700240838656e67696e655f73797374656d731c5374617465496e000108404765744c6576656c4279456e746974790400200110753132380000004447657443757272656e74436f756e74657200010000280838656e67696e655f73797374656d732053746174654f75740001083843757272656e74436f756e746572040020011075313238000000344c6576656c4279456e7469747904002001107531323800010000'
);
if (gasLimit === void 0) {
const gas = await this.clients[clientIdx].program.calculateGas.handle(
(0, import_api2.decodeAddress)(signer.address),
programId,
payload,
value,
true,
meta
);
gasLimit = gas.min_limit;
}
if (value === void 0) {
value = 1e13;
}
const tx = await this.clients[clientIdx].message.send(
{
destination: programId,
payload,
gasLimit,
value
},
meta
);
return tx;
} catch (err) {
console.warn(
`Failed to structured transaction with fullnode ${this.fullNodes[clientIdx]}: ${err}`
);
await delay(2e3);
}
}
throw new Error("Failed to structured transaction with all fullnodes");
}
async getMetaHash(programId) {
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(2e3);
}
}
throw new Error("Failed to get metaHash with all fullnodes");
}
async queryState(programId, payload, metadata) {
for (const clientIdx in this.clients) {
try {
await delay(1500);
const meta = import_api3.ProgramMetadata.from(
metadata
// '00020000010000000001070000000100000000000000000109000000010a000000d5072c000c34656e67696e655f736368656d611c73746f726167652c536368656d614576656e7400010c245365745265636f72640c0004011c4163746f724964000010011c5665633c75383e000010011c5665633c75383e0000003044656c6574655265636f7264080004011c4163746f724964000010011c5665633c75383e000100205265676973746572040014015c5665633c284163746f7249642c205665633c75383e293e000200000410106773746418636f6d6d6f6e287072696d6974697665731c4163746f724964000004000801205b75383b2033325d000008000003200000000c000c0000050300100000020c0014000002180018000004080410001c0838656e67696e655f73797374656d733053797374656d416374696f6e0001080c41646400000038536574456e746974794c6576656c08002001107531323800002001107531323800010000200000050700240838656e67696e655f73797374656d731c5374617465496e000108404765744c6576656c4279456e746974790400200110753132380000004447657443757272656e74436f756e74657200010000280838656e67696e655f73797374656d732053746174654f75740001083843757272656e74436f756e746572040020011075313238000000344c6576656c4279456e7469747904002001107531323800010000'
);
const state = await this.clients[clientIdx].programState.read(
{
programId,
payload
// payload: {
// GetCurrentCounter: null,
// },
},
meta
);
return state.toHuman();
} catch (err) {
console.warn(
`Failed to get metaHash with fullnode ${this.fullNodes[clientIdx]}: ${err}`
);
await delay(2e3);
}
}
throw new Error("Failed to get metaHash with all fullnodes");
}
async queryBalance(addr) {
for (const clientIdx in this.clients) {
try {
let balances_amount = await this.clients[clientIdx].query.system.account(addr);
return balances_amount.toHuman();
} catch (err) {
console.warn(
`Failed to query(${addr}) balance with fullnode ${this.fullNodes[clientIdx]}: ${err}`
);
await delay(2e3);
}
}
throw new Error(`Failed to query(${addr}) balance with all fullnodes`);
}
// async getObjects(
// ids: string[],
// options?: SuiObjectDataOptions
// ): Promise<SuiObjectData[]> {
// const opts: SuiObjectDataOptions = options ?? {
// showContent: true,
// showDisplay: true,
// showType: true,
// showOwner: true,
// };
// for (const clientIdx in this.clients) {
// try {
// const objects = await this.clients[clientIdx].multiGetObjects({
// ids,
// options: opts,
// });
// const parsedObjects = objects
// .map((object) => {
// return object.data;
// })
// .filter((object) => object !== null && object !== undefined);
// return parsedObjects as SuiObjectData[];
// } catch (err) {
// await delay(2000);
// console.warn(
// `Failed to get objects with fullnode ${this.fullNodes[clientIdx]}: ${err}`
// );
// }
// }
// throw new Error('Failed to get objects with all fullnodes');
// }
// async getObject(id: string) {
// const objects = await this.getObjects([id]);
// return objects[0];
// }
// async getDynamicFieldObject(
// parentId: string,
// name: RpcTypes.DynamicFieldName
// ) {
// for (const clientIdx in this.clients) {
// try {
// return await this.clients[clientIdx].getDynamicFieldObject({
// parentId,
// name,
// });
// } catch (err) {
// await delay(2000);
// console.warn(
// `Failed to get DynamicFieldObject with fullnode ${this.fullNodes[clientIdx]}: ${err}`
// );
// }
// }
// throw new Error('Failed to get DynamicFieldObject with all fullnodes');
// }
// async getDynamicFields(parentId: string, cursor?: string, limit?: number) {
// for (const clientIdx in this.clients) {
// try {
// return await this.clients[clientIdx].getDynamicFields({
// parentId,
// cursor,
// limit,
// });
// } catch (err) {
// await delay(2000);
// console.warn(
// `Failed to get DynamicFields with fullnode ${this.fullNodes[clientIdx]}: ${err}`
// );
// }
// }
// throw new Error('Failed to get DynamicFields with all fullnodes');
// }
// async getTxDetails(digest: string) {
// for (const clientIdx in this.clients) {
// try {
// const txResOptions: SuiTransactionBlockResponseOptions = {
// showEvents: true,
// showEffects: true,
// showObjectChanges: true,
// showBalanceChanges: true,
// };
// return await this.clients[clientIdx].getTransactionBlock({
// digest,
// options: txResOptions,
// });
// } catch (err) {
// await delay(2000);
// console.warn(
// `Failed to get TransactionBlocks with fullnode ${this.fullNodes[clientIdx]}: ${err}`
// );
// }
// }
// throw new Error('Failed to get TransactionBlocks with all fullnodes');
// }
// async getOwnedObjects(owner: string, cursor?: string, limit?: number) {
// for (const clientIdx in this.clients) {
// try {
// return await this.clients[clientIdx].getOwnedObjects({
// owner,
// cursor,
// limit,
// });
// } catch (err) {
// await delay(2000);
// console.warn(
// `Failed to get OwnedObjects with fullnode ${this.fullNodes[clientIdx]}: ${err}`
// );
// }
// }
// throw new Error('Failed to get OwnedObjects with all fullnodes');
// }
// async getNormalizedMoveModulesByPackage(packageId: string) {
// for (const clientIdx in this.clients) {
// try {
// return await this.clients[clientIdx].getNormalizedMoveModulesByPackage({
// package: packageId,
// });
// } catch (err) {
// await delay(2000);
// console.warn(
// `Failed to get NormalizedMoveModules with fullnode ${this.fullNodes[clientIdx]}: ${err}`
// );
// }
// }
// throw new Error('Failed to get NormalizedMoveModules with all fullnodes');
// }
// /**
// * @description Update objects in a batch
// * @param suiObjects
// */
// async updateObjects(suiObjects: (SuiOwnedObject | SuiSharedObject)[]) {
// const objectIds = suiObjects.map((obj) => obj.objectId);
// const objects = await this.getObjects(objectIds);
// for (const object of objects) {
// const suiObject = suiObjects.find(
// (obj) => obj.objectId === object?.objectId
// );
// if (suiObject instanceof SuiSharedObject) {
// if (
// object.owner &&
// typeof object.owner === 'object' &&
// 'Shared' in object.owner
// ) {
// suiObject.initialSharedVersion =
// object.owner.Shared.initial_shared_version;
// } else {
// suiObject.initialSharedVersion = undefined;
// }
// } else if (suiObject instanceof SuiOwnedObject) {
// suiObject.version = object?.version;
// suiObject.digest = object?.digest;
// }
// }
// }
// /**
// * @description Select coins that add up to the given amount.
// * @param addr the address of the owner
// * @param amount the amount that is needed for the coin
// * @param coinType the coin type, default is '0x2::SUI::SUI'
// */
// async selectCoins(
// addr: string,
// amount: number,
// coinType: string = '0x2::SUI::SUI'
// ) {
// const selectedCoins: {
// objectId: string;
// digest: string;
// version: string;
// }[] = [];
// let totalAmount = 0;
// let hasNext = true,
// nextCursor: string | null | undefined = null;
// while (hasNext && totalAmount < amount) {
// const coins = await this.currentClient.getCoins({
// owner: addr,
// coinType: coinType,
// cursor: nextCursor,
// });
// // Sort the coins by balance in descending order
// coins.data.sort((a, b) => parseInt(b.balance) - parseInt(a.balance));
// for (const coinData of coins.data) {
// selectedCoins.push({
// objectId: coinData.coinObjectId,
// digest: coinData.digest,
// version: coinData.version,
// });
// totalAmount = totalAmount + parseInt(coinData.balance);
// if (totalAmount >= amount) {
// break;
// }
// }
// nextCursor = coins.nextCursor;
// hasNext = coins.hasNextPage;
// }
// if (!selectedCoins.length) {
// throw new Error('No valid coins found for the transaction.');
// }
// return selectedCoins;
// }
// async requestFaucet(address: string, network: FaucetNetworkType) {
// await requestSuiFromFaucetV0({
// host: getFaucetHost(network),
// recipient: address,
// });
// }
};
// src/types/index.ts
var Network = /* @__PURE__ */ ((Network2) => {
Network2["MAINNET"] = "mainnet";
Network2["TESTNET"] = "testnet";
Network2["LOCAL"] = "local";
return Network2;
})(Network || {});
// src/libs/varaInteractor/defaultConfig.ts
var getDefaultURL = (networkType = "testnet" /* TESTNET */) => {
switch (networkType) {
case "local" /* LOCAL */:
return {
ws: "ws://127.0.0.1:9944",
http: "http://127.0.0.1:9933"
};
case "testnet" /* TESTNET */:
return {
ws: "wss://testnet.vara.network",
http: "https://testnet.vara.network"
};
case "mainnet" /* MAINNET */:
return {
ws: "wss://rpc.vara.network",
http: "https://rpc.vara.network"
};
default:
return {
ws: "wss://testnet.vara.network",
http: "https://testnet.vara.network"
};
}
};
// src/temples.ts
var import_api5 = require("@gear-js/api");
// src/utils/index.ts
function normalizeHexAddress(input) {
const hexRegex = /^(0x)?[0-9a-fA-F]{64}$/;
if (hexRegex.test(input)) {
if (input.startsWith("0x")) {
return input;
} else {
return "0x" + input;
}
} else {
return null;
}
}
function numberToAddressHex(num) {
const hex = num.toString(16);
const paddedHex = "0x" + hex.padStart(64, "0");
return paddedHex;
}
// src/temples.ts
function isUndefined(value) {
return value === void 0;
}
function withMeta(meta, creator) {
creator.meta = meta;
return creator;
}
function createQuery(meta, fn) {
return withMeta(meta, async (params) => {
const result = await fn(params);
return result;
});
}
function createTx(meta, fn) {
return withMeta(
meta,
async (params, isRaw) => {
return await fn(params, isRaw);
}
);
}
var _query, _tx, _exec, _read;
var Temples = class {
/**
* Support the following ways to init the TempleClient:
* 1. mnemonics
* 2. secretKey (base64 or hex)
* If none of them is provided, will generate a random mnemonics with 24 words.
*
* @param mnemonics, 12 or 24 mnemonics words, separated by space
* @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored
* @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'
* @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type
* @param packageId
*/
constructor({
mnemonics,
secretKey,
networkType,
fullnodeUrls,
packageId,
metadata,
connectWs
} = {}) {
__privateAdd(this, _query, {});
__privateAdd(this, _tx, {});
__privateAdd(this, _exec, async (meta, params, isRaw) => {
if (params === void 0) {
params = null;
}
const payload = {
[meta.funcName]: params
};
const account = await this.accountManager.getKeyPair();
const tx = await this.varaInteractor.structuredTransaction(
account,
this.packageId,
payload,
this.metadata
);
if (isRaw === true) {
return tx;
}
return await this.varaInteractor.signAndSend(account, tx);
});
__privateAdd(this, _read, async (meta, params) => {
if (params === void 0) {
params = null;
}
const payload = {
[meta.funcName]: params
};
let state = await this.varaInteractor.queryState(
this.packageId,
payload,
this.metadata
);
return state;
});
this.accountManager = new VaraAccountManager({ mnemonics, secretKey });
fullnodeUrls = fullnodeUrls || [
getDefaultURL(networkType ?? "mainnet" /* MAINNET */)
];
this.varaInteractor = new VaraInteractor(
fullnodeUrls,
networkType,
connectWs
);
this.packageId = packageId;
if (metadata !== void 0) {
this.metadata = metadata;
const metaraw = import_api5.ProgramMetadata.from(metadata);
const allTypes = metaraw.getAllTypes();
try {
const stateInRegex = /StateQuery$/;
const systemActionRegex = /SystemAction$/;
for (const [key, value] of Object.entries(allTypes)) {
let execEnumObj = null;
if (systemActionRegex.test(key)) {
if (value !== "Null") {
execEnumObj = JSON.parse(value)._enum;
}
}
let queryEnumObj = null;
if (stateInRegex.test(key)) {
if (value !== "Null") {
queryEnumObj = JSON.parse(value)._enum;
}
}
if (execEnumObj !== null) {
for (const [funcName, enumValue] of Object.entries(execEnumObj)) {
const meta = {
funcName,
paramType: enumValue
};
if (isUndefined(__privateGet(this, _tx)["contract"])) {
__privateGet(this, _tx)["contract"] = {};
}
if (isUndefined(__privateGet(this, _tx)["contract"][funcName])) {
console.log("exec func: ", funcName);
__privateGet(this, _tx)["contract"][funcName] = createTx(
meta,
(p, isRaw) => __privateGet(this, _exec).call(this, meta, p, isRaw)
);
}
}
}
if (queryEnumObj !== null) {
for (const [funcName, enumValue] of Object.entries(queryEnumObj)) {
const meta = {
funcName,
paramType: enumValue
};
if (isUndefined(__privateGet(this, _query)["contract"])) {
__privateGet(this, _query)["contract"] = {};
}
if (isUndefined(__privateGet(this, _query)["contract"][funcName])) {
console.log("query func: ", funcName);
__privateGet(this, _query)["contract"][funcName] = createQuery(
meta,
(p) => __privateGet(this, _read).call(this, meta, p)
);
}
}
}
}
} catch {
}
}
}
get query() {
return __privateGet(this, _query);
}
get tx() {
return __privateGet(this, _tx);
}
/**
* if derivePathParams is not provided or mnemonics is empty, it will return the keypair.
* else:
* it will generate signer from the mnemonic with the given derivePathParams.
* @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard
*/
getKeypair() {
return this.accountManager.getKeyPair();
}
/**
* @description Switch the current account with the given derivePathParams
* @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard
*/
switchAccount() {
this.accountManager.switchAccount();
}
/**
* @description Get the address of the account for the given derivePathParams
* @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard
*/
getAddress() {
return this.accountManager.getAddress();
}
async currentAddress() {
return await this.accountManager.getAddress();
}
getPackageId() {
return this.packageId;
}
async getMetaHash(programId) {
return await this.varaInteractor.getMetaHash(programId);
}
getMetadata() {
return this.metadata;
}
getAllTypes(metadata) {
if (metadata === void 0) {
metadata = this.metadata;
}
const metaraw = import_api5.ProgramMetadata.from(metadata);
const allTypes = metaraw.getAllTypes();
return allTypes;
}
async getBalance(account) {
if (account === void 0) {
account = await this.accountManager.getAddress();
}
return await this.varaInteractor.queryBalance(account);
}
client() {
return this.varaInteractor.currentClient;
}
wsProvider() {
return this.varaInteractor.wsApi;
}
// async signTxn(
// tx: Uint8Array | TransactionBlock | SuiTxBlock,
// derivePathParams?: DerivePathParams
// ) {
// if (tx instanceof SuiTxBlock || tx instanceof TransactionBlock) {
// tx.setSender(this.getAddress(derivePathParams));
// }
// const txBlock = tx instanceof SuiTxBlock ? tx.txBlock : tx;
// const txBytes =
// txBlock instanceof TransactionBlock
// ? await txBlock.build({ client: this.client() })
// : txBlock;
// const keyPair = await this.getKeypair();
// return await keyPair.signTransactionBlock(txBytes);
// }
// async signAndSend(
// signer: Keyring,
// programId: HexString,
// metaHash: HexString,
// payload: PayloadType,
// gasLimit: number | undefined,
// value: number | undefined
// async signAndSendTxn(
// tx: Uint8Array | TransactionBlock | SuiTxBlock,
// derivePathParams?: DerivePathParams
// ): Promise<SuiTransactionBlockResponse> {
// const { bytes, signature } = await this.signTxn(tx, derivePathParams);
// return this.suiInteractor.sendTx(bytes, signature);
// }
// /**
// * Transfer the given amount of SUI to the recipient
// * @param recipient
// * @param amount
// * @param derivePathParams
// */
// async transferVara(
// recipient: string,
// amount: number,
// derivePathParams?: DerivePathParams
// ) {
// const tx = new SuiTxBlock();
// tx.transferSui(recipient, amount);
// return this.signAndSendTxn(tx, derivePathParams);
// }
// /**
// * Transfer to mutliple recipients
// * @param recipients the recipients addresses
// * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients
// * @param derivePathParams
// */
// async transferSuiToMany(
// recipients: string[],
// amounts: number[],
// derivePathParams?: DerivePathParams
// ) {
// const tx = new SuiTxBlock();
// tx.transferSuiToMany(recipients, amounts);
// return this.signAndSendTxn(tx, derivePathParams);
// }
// async moveCall(callParams: {
// target: string;
// arguments?: (SuiTxArg | SuiVecTxArg)[];
// typeArguments?: string[];
// derivePathParams?: DerivePathParams;
// }) {
// const {
// target,
// arguments: args = [],
// typeArguments = [],
// derivePathParams,
// } = callParams;
// const tx = new SuiTxBlock();
// tx.moveCall(target, args, typeArguments);
// return this.signAndSendTxn(tx, derivePathParams);
// }
// async getWorld(worldObjectId: string) {
// return this.suiInteractor.getObject(worldObjectId);
// }
// async listSchemaNames(worldId: string) {
// const worldObject = await this.getObject(worldId);
// const newObjectContent = worldObject.content;
// if (newObjectContent != null) {
// const objectContent = newObjectContent as TempleObjectContent;
// const objectFields = objectContent.fields as Record<string, any>;
// return objectFields['schema_names'];
// } else {
// return [];
// }
// }
// async getEntity(
// worldId: string,
// schemaName: string,
// entityId?: string
// ): Promise<any[] | undefined> {
// const schemaModuleName = `${schemaName}_schema`;
// const tx = new TransactionBlock();
// const params = [tx.pure(worldId)] as TransactionArgument[];
// if (entityId !== undefined) {
// params.push(tx.pure(entityId));
// }
// const getResult = (await this.query[schemaModuleName].get(
// tx,
// params
// )) as DevInspectResults;
// const returnValue = [];
// // "success" | "failure";
// if (getResult.effects.status.status === 'success') {
// const resultList = getResult.results![0].returnValues!;
// for (const res of resultList) {
// const bcs = new BCS(getSuiMoveConfig());
// const value = Uint8Array.from(res[0]);
// const bcsType = res[1].replace(/0x1::ascii::String/g, 'string');
// const data = bcs.de(bcsType, value);
// returnValue.push(data);
// }
// return returnValue;
// } else {
// return undefined;
// }
// }
// async containEntity(
// worldId: string,
// schemaName: string,
// entityId?: string
// ): Promise<boolean | undefined> {
// const schemaModuleName = `${schemaName}_schema`;
// const tx = new TransactionBlock();
// const params = [tx.pure(worldId)] as TransactionArgument[];
// if (entityId !== undefined) {
// params.push(tx.pure(entityId));
// }
// const getResult = (await this.query[schemaModuleName].contains(
// tx,
// params
// )) as DevInspectResults;
// // "success" | "failure";
// if (getResult.effects.status.status === 'success') {
// const res = getResult.results![0].returnValues![0];
// const bcs = new BCS(getSuiMoveConfig());
// const value = Uint8Array.from(res[0]);
// return bcs.de(res[1], value);
// } else {
// return undefined;
// }
// }
// async getEntities(
// worldId: string,
// schemaName: string,
// cursor?: string,
// limit?: number
// ) {
// let schemaModuleName = `${schemaName}_schema`;
// const tx = new TransactionBlock();
// let params = [tx.pure(worldId)] as SuiTxArgument[];
// const tableResult = (await this.query[schemaonentModuleName].entities(
// tx,
// params
// )) as DevInspectResults;
// const entities = tableResult.results as SuiReturnValues;
// const bcs = new BCS(getSuiMoveConfig());
// let value = Uint8Array.from(entities[0].returnValues[0][0]);
// let tableId = '0x' + bcs.de('address', value);
// let dynamicFields = await this.suiInteractor.getDynamicFields(
// tableId,
// cursor,
// limit
// );
// let objectIds = dynamicFields.data.map((field) => field.objectId);
// let objectDatas = await this.suiInteractor.getEntitiesObjects(objectIds);
// return {
// data: objectDatas,
// nextCursor: dynamicFields.nextCursor,
// hasNextPage: dynamicFields.hasNextPage,
// };
// }
async entity_key_from_hex_string(hexString) {
const checkObjectId = normalizeHexAddress(hexString);
if (checkObjectId !== null) {
hexString = checkObjectId;
return hexString;
} else {
return void 0;
}
}
async entity_key_from_u256(x) {
return numberToAddressHex(x);
}
};
_query = new WeakMap();
_tx = new WeakMap();
_exec = new WeakMap();
_read = new WeakMap();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Network,
Temples,
VaraAccountManager,
...require("@gear-js/api")
});
//# sourceMappingURL=index.js.map