@polkadot/types/types#ISubmittableResult TypeScript Examples

The following examples show how to use @polkadot/types/types#ISubmittableResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Claim.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Submit `claimValueFromMailbox` extrinsic
   * @param messageId MessageId with value to be claimed
   */
  submit(messageId: Hex): SubmittableExtrinsic<'promise', ISubmittableResult> {
    try {
      this.submitted = this.api.tx.gear.claimValueFromMailbox(messageId);
      return this.submitted;
    } catch (error) {
      throw new ClaimValueError();
    }
  }
Example #2
Source File: Code.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Submit code without initialization
   * @param code
   * @returns Code hash
   */
  submit(code: Buffer | Uint8Array): { codeHash: Hex; submitted: SubmittableExtrinsic<'promise', ISubmittableResult> } {
    const codeBytes = this.createType.create('bytes', Array.from(code)) as Bytes;
    this.submitted = this.api.tx.gear.submitCode(codeBytes);
    const codeHash = generateCodeHash(code);
    return { codeHash, submitted: this.submitted };
  }
Example #3
Source File: Message.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Send message
   * @param message Message parameters
   * @param meta Metadata
   * @param messageType MessageType
   * @returns Submitted result
   * ```javascript
   * const api = await GearApi.create()
   * const programId = '0xd7540ae9da85e33b47276e2cb4efc2f0b58fef1227834f21ddc8c7cb551cced6'
   * api.message.submit({
   *  destination: messageId,
   *  payload: 'Hello, World!',
   *  gasLimit: 20_000_000
   * }, undefiend, 'String')
   * api.message.signAndSend(account, (events) => {
   *  events.forEach(({event}) => console.log(event.toHuman()))
   * })
   * ```
   */
  submit(
    message: { destination: string | H256; payload: PayloadType; gasLimit: AnyNumber; value?: AnyNumber },
    meta?: Metadata,
    messageType?: string,
  ): SubmittableExtrinsic<'promise', ISubmittableResult> {
    let payload = createPayload(this.createType, messageType || meta?.handle_input, message.payload, meta);
    try {
      this.submitted = this.api.tx.gear.sendMessage(message.destination, payload, message.gasLimit, message.value || 0);
      return this.submitted;
    } catch (error) {
      throw new SendMessageError();
    }
  }
Example #4
Source File: useStatus.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
function useStatus() {
  const alert = useAlert();
  const { disableLoading } = useLoading();

  const handleEventsStatus = (events: EventRecord[]) => {
    events.forEach(({ event: { method } }) => {
      if (method === 'DispatchMessageEnqueued') {
        alert.success('Send message: Finalized');
        // resetValues();
      } else if (method === 'ExtrinsicFailed') {
        alert.info('Extrinsic failed');
      }
    });
  };

  const handleStatus = (result: ISubmittableResult) => {
    const { status, events } = result;
    const { isInBlock, isInvalid, isFinalized } = status;

    if (isInvalid) {
      alert.info('Transaction error. Status: isInvalid');
      disableLoading();
    } else if (isInBlock) {
      alert.success('Send message: In block');
    } else if (isFinalized) {
      handleEventsStatus(events);
      disableLoading();
    }
  };

  return handleStatus;
}
Example #5
Source File: Message.tsx    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
Message = ({ message }: Props) => {
  const { id } = message;

  const { api } = useApi();
  const { account } = useAccount();
  const alert = useAlert();

  const showErrorAlert = (error: string) => {
    alert.error(error);
  };

  const showSuccessAlert = (data: ISubmittableResult) => {
    if (!data.status.isBroadcast) {
      alert.success(`Status: ${data.status}`);
    }
  };

  const handleClaimButtonClick = () => {
    if (account) {
      const { address, meta } = account;

      api.claimValueFromMailbox.submit(id);
      web3FromSource(meta.source)
        .then(({ signer }) => api.claimValueFromMailbox.signAndSend(address, { signer }, showSuccessAlert))
        .catch((error: Error) => showErrorAlert(error.message));
    }
  };

  return (
    <div className={styles.message}>
      <pre className={styles.pre}>{getPreformattedText(message)}</pre>
      <div>
        <ReplyLink to={id} />
        <Button text="Claim value" icon={claimIcon} color="secondary" size="small" onClick={handleClaimButtonClick} />
      </div>
    </div>
  );
}
Example #6
Source File: transaction.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
async sendLogged<T extends AnyTuple>(
        transaction: SubmittableExtrinsic<"promise">,
        successEventType?: AugmentedEvent<ApiTypes, T>,
        onlyInBlock?: boolean
    ): Promise<ISubmittableResult> {
        if (this.account === undefined) {
            return Promise.reject(new Error(ACCOUNT_NOT_SET_ERROR_MESSAGE));
        }
        return DefaultTransactionAPI.sendLogged(this.api, this.account, transaction, successEventType, onlyInBlock);
    }
Example #7
Source File: MessageReply.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
/**
   * Sends reply message
   * @param message Message parameters
   * @param meta Metadata
   * @param messageType MessageType
   * @returns Submitted result
   * @example
   * ```javascript
   * const api = await GearApi.create()
   * const messageId = '0xd7540ae9da85e33b47276e2cb4efc2f0b58fef1227834f21ddc8c7cb551cced6'
   * api.reply.submit({
   *  replyToId: messageId,
   *  payload: 'Reply message',
   *  gasLimit: 20_000_000
   * }, undefiend, 'String')
   * api.reply.signAndSend(account, (events) => {
   *  events.forEach(({event}) => console.log(event.toHuman()))
   * })
   * ```
   */
  submit(
    message: {
      replyToId: H256 | string;
      payload: string | any;
      gasLimit: u64 | AnyNumber;
      value?: BalanceOf | AnyNumber;
    },
    meta?: Metadata,
    messageType?: string,
  ): SubmittableExtrinsic<'promise', ISubmittableResult> {
    let payload = createPayload(
      this.createType,
      messageType || meta?.async_handle_input || meta?.async_init_input,
      message.payload,
      meta,
    );

    try {
      this.submitted = this.api.tx.gear.sendReply(message.replyToId, payload, message.gasLimit, message.value);
      return this.submitted;
    } catch (error) {
      throw new SendReplyError();
    }
  }
Example #8
Source File: Program.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
/**
   * @param program Upload program data
   * @param meta Metadata
   * @returns ProgramId
   * @example
   * ```javascript
   * const code = fs.readFileSync('path/to/program.opt.wasm');
   * const meta = await getWasmMetadata(fs.readFileSync('path/to/program.meta.wasm'));
   * const api = await GearApi.create();
   * const { programId, salt, submitted } = api.program.submit({
   *   code,
   *   initPayload: {field: 'someValue'},
   *   gasLimit: 20_000_000,
   * }, meta)
   * api.program.signAndSend(account, (events) => {
   *   events.forEach(({event}) => console.log(event.toHuman()))
   * })
   * ```
   */
  submit(
    program: {
      code: Buffer | Uint8Array;
      salt?: `0x${string}`;
      initPayload?: string | any;
      gasLimit: u64 | AnyNumber;
      value?: BalanceOf | AnyNumber;
    },
    meta?: Metadata,
    messageType?: string,
  ): { programId: Hex; salt: Hex; submitted: SubmittableExtrinsic<'promise', ISubmittableResult> } {
    const salt = program.salt || randomAsHex(20);
    const code = this.createType.create('bytes', Array.from(program.code)) as Bytes;
    let payload = createPayload(this.createType, messageType || meta?.init_input, program.initPayload, meta);
    try {
      this.submitted = this.api.tx.gear.submitProgram(code, salt, payload, program.gasLimit, program.value || 0);
      const programId = generateProgramId(code, salt);
      return { programId, salt, submitted: this.submitted };
    } catch (error) {
      throw new SubmitProgramError();
    }
  }
Example #9
Source File: Transaction.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
submitted: SubmittableExtrinsic<'promise', ISubmittableResult>;
Example #10
Source File: useMessage.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
function useMessage(destination: Hex, metadata: Metadata | undefined) {
  const alert = useAlert();
  const { api } = useApi();
  const { account } = useAccount();
  const { enableLoading, disableLoading } = useLoading();

  const handleEventsStatus = (events: EventRecord[]) => {
    events.forEach(({ event: { method } }) => {
      if (method === 'DispatchMessageEnqueued') {
        alert.success('Send message: Finalized');
        // onSucessCallback();
      } else if (method === 'ExtrinsicFailed') {
        alert.error('Extrinsic failed');
      }
    });
  };

  const handleStatus = (result: ISubmittableResult) => {
    const { status, events } = result;
    const { isInBlock, isInvalid, isFinalized } = status;

    if (isInvalid) {
      alert.error('Transaction error. Status: isInvalid');
      disableLoading();
    } else if (isInBlock) {
      alert.success('Send message: In block');
    } else if (isFinalized) {
      handleEventsStatus(events);
      disableLoading();
    }
  };

  // TODO: eslint
  // eslint-disable-next-line consistent-return
  const sendMessage = async (payload: AnyJson, value: string | number = 0) => {
    if (account && metadata) {
      enableLoading();

      const { address, decodedAddress, meta } = account;
      const gasLimit = await api.program.gasSpent.handle(decodedAddress, destination, payload, value, metadata);

      const message = { destination, payload, gasLimit, value };
      api.message.submit(message, metadata);

      const { source } = meta;
      const { signer } = await web3FromSource(source);
      return api.message.signAndSend(address, { signer }, handleStatus);
    }
  };

  return sendMessage;
}
Example #11
Source File: useSendMessage.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
function useSendMessage(destination: Hex, metaSourceOrData: string | Metadata | undefined) {
  const { api } = useContext(ApiContext); // сircular dependency fix
  const { account } = useContext(AccountContext);
  const alert = useContext(AlertContext);

  const metadata = useConditionalMeta(metaSourceOrData);

  const title = 'gear.sendMessage';
  const loadingAlertId = useRef('');

  const handleEventsStatus = (events: EventRecord[]) => {
    events.forEach(({ event: { method, section } }) => {
      if (method === 'DispatchMessageEnqueued') {
        alert.success(`${section}.DispatchMessageEnqueued`);
        // onSucessCallback();
      } else if (method === 'ExtrinsicFailed') {
        alert.error('Extrinsic Failed', { title });
      }
    });
  };

  const handleStatus = (result: ISubmittableResult) => {
    const { status, events } = result;
    const { isReady, isInBlock, isInvalid, isFinalized } = status;

    if (isInvalid) {
      alert.update(loadingAlertId.current, 'Transaction error. Status: isInvalid', DEFAULT_ERROR_OPTIONS);
    } else if (isReady) {
      alert.update(loadingAlertId.current, 'Ready');
    } else if (isInBlock) {
      alert.update(loadingAlertId.current, 'In Block');
    } else if (isFinalized) {
      alert.update(loadingAlertId.current, 'Finalized', DEFAULT_SUCCESS_OPTIONS);
      handleEventsStatus(events);
    }
  };

  const sendMessage = async (payload: AnyJson, value: string | number = 0) => {
    if (account && metadata) {
      loadingAlertId.current = alert.loading('Sign In', { title });

      const { address, decodedAddress, meta } = account;
      const gasLimit = await api.program.gasSpent.handle(decodedAddress, destination, payload, value, metadata);

      const message = { destination, payload, gasLimit, value };
      api.message.submit(message, metadata);

      const { source } = meta;
      const { signer } = await web3FromSource(source);

      return api.message
        .signAndSend(address, { signer }, handleStatus)
        .catch(({ message }: Error) => alert.update(loadingAlertId.current, message, DEFAULT_ERROR_OPTIONS));
    }
  };

  return sendMessage;
}
Example #12
Source File: transaction.ts    From interbtc-api with Apache License 2.0 5 votes vote down vote up
static async sendLogged<T extends AnyTuple>(
        api: ApiPromise,
        account: AddressOrPair,
        transaction: SubmittableExtrinsic<"promise">,
        successEventType?: AugmentedEvent<ApiTypes, T>,
        onlyInBlock?: boolean
    ): Promise<ISubmittableResult> {
        const { unsubscribe, result } = await new Promise((resolve, reject) => {
            let unsubscribe: () => void;
            // When passing { nonce: -1 } to signAndSend the API will use system.accountNextIndex to determine the nonce
            transaction
                .signAndSend(account, { nonce: -1 }, (result: ISubmittableResult) => callback({ unsubscribe, result }))
                .then((u: () => void) => (unsubscribe = u))
                .catch((error) => reject(error));

            function callback(callbackObject: { unsubscribe: () => void; result: ISubmittableResult }): void {
                const status = callbackObject.result.status;
                if (onlyInBlock) {
                    if (status.isInBlock) {
                        resolve(callbackObject);
                    }
                } else {
                    if (status.isFinalized) {
                        resolve(callbackObject);
                    }
                }
            }
        });

        if (onlyInBlock) {
            console.log(`Transaction included at blockHash ${result.status.asInBlock}`);
        } else {
            console.log(`Transaction finalized at blockHash ${result.status.asFinalized}`);
        }
        unsubscribe(result);

        // Print all events for debugging
        DefaultTransactionAPI.printEvents(api, result.events);

        const dispatchError = result.dispatchError;
        if (dispatchError) {
            // Construct error message
            let message = "The transaction failed.";
            // Runtime error in one of the parachain modules
            if (dispatchError.isModule) {
                // for module errors, we have the section indexed, lookup
                const decoded = api.registry.findMetaError(dispatchError.asModule);
                const { docs, name, section } = decoded;
                message = message.concat(` The error code is ${section}.${name}. ${docs.join(" ")}`);
                // Bad origin
            } else if (dispatchError.isBadOrigin) {
                message = message.concat(` The error is caused by using an incorrect account.
                The error code is BadOrigin ${dispatchError}.`);
            }
            // Other, CannotLookup, no extra info
            else {
                message = message.concat(` The error is ${dispatchError}.`);
            }
            console.log(message);
            return Promise.reject(new Error(message));
        }
        return result;
    }
Example #13
Source File: admin.ts    From commonwealth with GNU General Public License v3.0 4 votes vote down vote up
SudoForm: m.Component<{}, ISudoFormState> = {
  view: (vnode) => {
    const author = app.user.activeAccount as SubstrateAccount;
    if (!(app.chain as Substrate).chain.sudoKey) {
      return m(
        '.SudoForm',
        {
          style:
            'padding: 20px 24px; border: 1px solid #eee; margin-bottom: 40px;',
        },
        'No sudo key available on this chain.'
      );
    }

    if (author && author.address !== (app.chain as Substrate).chain.sudoKey) {
      return m(
        '.SudoForm',
        {
          style:
            'padding: 20px 24px; border: 1px solid #eee; margin-bottom: 40px;',
        },
        [
          'Must be logged into admin account to use Sudo: ',
          m(User, {
            user: app.chain.accounts.get(
              (app.chain as Substrate).chain.sudoKey
            ),
          }),
        ]
      );
    }

    let keyring;
    try {
      // keyring = author.getKeyringPair();
      // TODO: FIXME: we do not support unlocking with seed/mnemonic, so we will need to use
      //   the signer from Polkadotjs web wallet to perform sudo actions.
    } catch (e) {
      return m(
        '.SudoForm',
        {
          style:
            'padding: 20px 24px; border: 1px solid #eee; margin-bottom: 40px;',
        },
        'Account must be unlocked to use Sudo.'
      );
    }

    return m(
      '.SudoForm',
      {
        style:
          'width: 80%; padding: 5px 24px; border: 1px solid #eee; margin-bottom: 15px;',
      },
      [
        m(
          'h2.header',
          { style: 'margin: 15px 0;' },
          'Sudo: run function as Admin'
        ),
        m(EdgewareFunctionPicker),
        m(
          'button',
          {
            type: 'submit',
            disabled: vnode.state.txProcessing,
            onclick: (e) => {
              e.preventDefault();
              const call = EdgewareFunctionPicker.getMethod();
              vnode.state.txProcessing = true;
              vnode.state.resultText = 'Waiting...';
              m.redraw();
              (app.chain as Substrate).chain.api.tx.sudo
                .sudo(call)
                .signAndSend(keyring, (result: ISubmittableResult) => {
                  if (result.isCompleted) {
                    vnode.state.txProcessing = false;
                    if (result.isFinalized) {
                      vnode.state.resultText = 'Action completed successfully.';
                    } else {
                      vnode.state.resultText = 'Action was unsuccessful.';
                    }
                    m.redraw();
                  }
                });
            },
          },
          'Submit Action'
        ),
        m('h4.header', { style: 'margin: 15px 0;' }, vnode.state.resultText),
        m('br'),
      ]
    );
  },
}