import { Bytes, Option } from 'https://deno.land/x/polkadot@0.2.45/types/index.ts'; import { HexString } from 'https://deno.land/x/polkadot@0.2.45/util/types.ts'; import { u8aToHex } from 'https://deno.land/x/polkadot@0.2.45/util/index.ts'; import { CodeUploadResult, GearCommonCodeMetadata, GearCoreCodeInstrumentedInstrumentedCode } from './types/index.ts'; import { generateCodeHash, getIdsFromKeys, validateCodeId } from './utils/index.ts'; import { CodeDoesNotExistError } from './errors/index.ts'; import { GearTransaction } from './Transaction.ts'; import { getGrReply } from './wasm/index.ts'; export class GearCode extends GearTransaction { /** * ### Submit code without initialization * @param code * @returns Code hash */ async upload(code: Buffer | Uint8Array): Promise { const codeHash = generateCodeHash(code); await validateCodeId(codeHash, this._api); const codeBytes = this._api.createType('Bytes', Array.from(code)) as Bytes; this.extrinsic = this._api.tx.gear.uploadCode(codeBytes); return { codeHash, submitted: this.extrinsic, extrinsic: this.extrinsic }; } /** * ### Check that codeId exists on chain * @param codeId */ async exists(codeId: string) { const codeMetadata = (await this._api.query.gearProgram.metadataStorage(codeId)) as Option; return codeMetadata.isSome; } /** * ### Get code storage * @param codeId */ async storage(codeId: HexString): Promise> { return this._api.query.gearProgram.codeStorage(codeId); } /** * ### Get static pages of code * @param codeId */ async staticPages(codeId: HexString): Promise { const storage = await this.storage(codeId); return storage.isSome ? storage.unwrap().staticPages.toNumber() : null; } /** * ### Get all ids of codes uploaded on connected chain * @returns array of code ids uploaded on chain */ async all(): Promise { const prefix = this._api.query.gearProgram.metadataStorage.keyPrefix(); const keys = await this._api.rpc.state.getKeys(prefix); const codeIds = getIdsFromKeys(keys, prefix); return codeIds; } async metaHash(codeId: HexString): Promise { const code = (await this._api.query.gearProgram.originalCodeStorage(codeId)) as Option; if (code.isNone) { throw new CodeDoesNotExistError(codeId); } const metahash = await getGrReply(code.unwrap().toHex(), 'metahash'); return u8aToHex(metahash); } async metaHashFromWasm(wasm: Buffer | ArrayBuffer | HexString | Uint8Array) { const metahash = await getGrReply(wasm, 'metahash'); return u8aToHex(metahash); } }