Skip to content

Commit

Permalink
Update check for contract instantiation (#5699)
Browse files Browse the repository at this point in the history
* add risc v check

* run lint

* Update packages/api-contract/src/base/Code.ts

Co-authored-by: Jaco <[email protected]>

* add explicit return type

Co-authored-by: Jaco <[email protected]>

---------

Co-authored-by: Jaco <[email protected]>
  • Loading branch information
statictype and jacogr authored Sep 4, 2023
1 parent 257c957 commit ae24a99
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions packages/api-contract/src/base/Code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type { AbiConstructor, BlueprintOptions } from '../types.js';
import type { MapConstructorExec } from './types.js';

import { SubmittableResult } from '@polkadot/api';
import { BN_ZERO, compactAddLength, isUndefined, isWasm, u8aToU8a } from '@polkadot/util';
import { BN_ZERO, compactAddLength, isU8a, isUndefined, isWasm, u8aEq, u8aToU8a } from '@polkadot/util';

import { applyOnEvent } from '../util.js';
import { Base } from './Base.js';
Expand All @@ -34,6 +34,16 @@ export class CodeSubmittableResult<ApiType extends ApiTypes> extends Submittable
}
}

function isRiscV (bytes: unknown): bytes is Uint8Array {
const ELF_MAGIC = new Uint8Array([0x7f, 0x45, 0x4c, 0x46]); // ELF magic bytes: 0x7f, 'E', 'L', 'F'

return isU8a(bytes) && u8aEq(bytes.subarray(0, 4), ELF_MAGIC);
}

function isValidCode (code: Uint8Array): boolean {
return isWasm(code) || isRiscV(code);
}

export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
readonly code: Uint8Array;

Expand All @@ -42,12 +52,12 @@ export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
constructor (api: ApiBase<ApiType>, abi: string | Record<string, unknown> | Abi, wasm: Uint8Array | string | Buffer | null | undefined, decorateMethod: DecorateMethod<ApiType>) {
super(api, abi, decorateMethod);

this.code = isWasm(this.abi.info.source.wasm)
this.code = isValidCode(this.abi.info.source.wasm)
? this.abi.info.source.wasm
: u8aToU8a(wasm);

if (!isWasm(this.code)) {
throw new Error('No WASM code provided');
if (!isValidCode(this.code)) {
throw new Error('Invalid code provided');
}

this.abi.constructors.forEach((c): void => {
Expand Down

0 comments on commit ae24a99

Please sign in to comment.