// Copyright 2017-2019 @polkadot/api-contract authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { ApiTypes, DecorateMethod, SubmittableResultImpl } from '@polkadot/api/types'; import { AccountId, Address, Hash } from '@polkadot/types/interfaces'; import { IKeyringPair } from '@polkadot/types/types'; import { ApiObject, ContractABIPre } from '../types'; import BN from 'bn.js'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { SubmittableResult } from '@polkadot/api'; import { compactAddLength, u8aToU8a } from '@polkadot/util'; import Abi from '../Abi'; import Blueprint from './Blueprint'; import { BaseWithTx } from './util'; type CodePutCodeResultSubscription = Observable>; // eslint-disable-next-line @typescript-eslint/interface-name-prefix export interface CodePutCode { signAndSend (account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription; } class CodePutCodeResult extends SubmittableResult { public readonly blueprint?: Blueprint; constructor (result: SubmittableResultImpl, blueprint?: Blueprint) { super(result); this.blueprint = blueprint; } } // NOTE Experimental, POC, bound to change export default class Code extends BaseWithTx { public readonly code: Uint8Array; constructor (api: ApiObject, abi: ContractABIPre | Abi, decorateMethod: DecorateMethod, wasm: string | Uint8Array) { super(api, abi, decorateMethod); this.code = u8aToU8a(wasm); } public createBlueprint = (maxGas: number | BN): CodePutCode => { return { signAndSend: this.decorateMethod( (account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription => this.apiContracts .putCode(maxGas, compactAddLength(this.code)) .signAndSend(account) .pipe(map(this.createResult)) ) }; } private createResult = (result: SubmittableResultImpl): CodePutCodeResult => { let blueprint: Blueprint | undefined; if (result.isFinalized) { const record = result.findRecord('contract', 'CodeStored'); if (record) { blueprint = new Blueprint(this.api, this.abi, this.decorateMethod, record.event.data[0] as Hash); } } return new CodePutCodeResult(result, blueprint); } }