@polkadot/util#u8aToHex TypeScript Examples

The following examples show how to use @polkadot/util#u8aToHex. 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: utils.ts    From bodhi.js with Apache License 2.0 7 votes vote down vote up
export function dataToString(bytes: BytesLike): string {
  if (isBuffer(bytes)) {
    return u8aToHex(bufferToU8a(bytes));
  }
  if (isU8a(bytes)) {
    return u8aToHex(bytes);
  }
  if (Array.isArray(bytes)) {
    return u8aToHex(Buffer.from(bytes));
  }

  return bytes as string;
}
Example #2
Source File: utils.ts    From evm-provider.js with Apache License 2.0 7 votes vote down vote up
export function dataToString(bytes: BytesLike): string {
  if (isBuffer(bytes)) {
    return u8aToHex(bufferToU8a(bytes));
  }
  if (isU8a(bytes)) {
    return u8aToHex(bytes);
  }
  if (Array.isArray(bytes)) {
    return u8aToHex(Buffer.from(bytes));
  }

  return bytes as string;
}
Example #3
Source File: generate.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
export function createPayload(createType: CreateType, type: any, data: any, meta?: Metadata): Hex {
  if (data === undefined) {
    return '0x00';
  }
  if (isHex(data)) {
    return data;
  } else if (isU8a(data)) {
    return u8aToHex(data);
  }
  let payload = data;
  if (meta && type) {
    const encoded = createType.create(type, data, meta);
    payload = isHex(encoded) ? encoded : encoded.toHex();
  } else if (type) {
    try {
      const encoded = createType.create(type, data);
      payload = isHex(encoded) ? encoded : encoded.toHex();
    } catch (error) {
      console.error(error.message);
    }
  }
  return payload;
}
Example #4
Source File: keyring.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Add user's accounts to keyring incedence,
 * so user can use them to sign txs with password.
 * We use a list of ss58Formats to encode the accounts
 * into different address formats for different networks.
 */
async function initKeys(accounts: KeyringPair$Json[], ss58Formats: number[]) {
  await cryptoWaitReady();
  const res = {};
  ss58Formats.forEach((ss58) => {
    (<any>res)[ss58] = {};
  });

  accounts.forEach((i) => {
    // import account to keyring
    const keyPair = keyring.addFromJson(i);
    // then encode address into different ss58 formats
    ss58Formats.forEach((ss58) => {
      const pubKey = u8aToHex(keyPair.publicKey);
      (<any>res)[ss58][pubKey] = keyring.encodeAddress(keyPair.publicKey, ss58);
    });
  });
  return res;
}
Example #5
Source File: substrate-rpc.ts    From polkadot-launch with MIT License 6 votes vote down vote up
async function lookForExtrinsicAndEvents(
	api: ApiPromise,
	extrinsicHash: Uint8Array
) {
	// We retrieve the block (including the extrinsics)
	const signedBlock = await api.rpc.chain.getBlock();

	// We retrieve the events for that block
	const allRecords = await api.query.system.events.at(
		signedBlock.block.header.hash
	);

	const extrinsicIndex = signedBlock.block.extrinsics.findIndex((ext) => {
		return ext.hash.toHex() == u8aToHex(extrinsicHash);
	});
	if (extrinsicIndex < 0) {
		console.log(
			`Extrinsic ${extrinsicHash} is missing in the block ${signedBlock.block.header.hash}`
		);
	}
	const extrinsic = signedBlock.block.extrinsics[extrinsicIndex];

	// We retrieve the events associated with the extrinsic
	const events = allRecords
		.filter(
			({ phase }) =>
				phase.isApplyExtrinsic &&
				phase.asApplyExtrinsic.toNumber() == extrinsicIndex
		)
		.map(({ event }) => event);
	return { events, extrinsic };
}
Example #6
Source File: SingleAccountSigner.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
public async signRaw ({ address, data }: SignerPayloadRaw): Promise<SignerResult> {
      if (address !== this.#keyringPair.address) {
          throw new Error("does not have the keyringPair");
      }

      return new Promise((resolve): void => {
          setTimeout((): void => {
              const signature = u8aToHex(this.#keyringPair.sign(hexToU8a(data)));

              resolve({
                  id: ++id,
                  signature
              });
          }, this.#signDelay);
      });
  }
Example #7
Source File: treasury.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
public async init(ChainInfo: SubstrateChain, Accounts: SubstrateAccounts): Promise<void> {
    this._disabled = !ChainInfo.api.query.treasury;
    if (this._initializing || this._initialized || this.disabled) return;
    this._initializing = true;
    this._Chain = ChainInfo;
    this._Accounts = Accounts;

    // load server proposals
    const entities = this.app.chain.chainEntities.store.getByType(SubstrateTypes.EntityKind.TreasuryProposal);
    entities.forEach((e) => this._entityConstructor(e));

    // save parameters
    this._bondPct = +(ChainInfo.api.consts.treasury.proposalBond as Permill) / 1_000_000;
    this._bondMinimum = this._Chain.coins(ChainInfo.api.consts.treasury.proposalBondMinimum as BalanceOf);
    this._spendPeriod = +(ChainInfo.api.consts.treasury.spendPeriod as BlockNumber);
    this._burnPct = +(ChainInfo.api.consts.treasury.burn as Permill) / 1_000_000;

    const TREASURY_ACCOUNT = u8aToHex(stringToU8a('modlpy/trsry'.padEnd(32, '\0')));
    const pot = await ChainInfo.api.derive.balances.account(TREASURY_ACCOUNT);
    this._pot = this._Chain.coins(pot.freeBalance);

    // register new chain-event handlers
    this.app.chain.chainEntities.registerEntityHandler(
      SubstrateTypes.EntityKind.TreasuryProposal, (entity, event) => {
        this.updateProposal(entity, event);
      }
    );

    // fetch proposals from chain
    await this.app.chain.chainEntities.fetchEntities(
      this.app.chain.id,
      chainToEventNetwork(this.app.chain.meta),
      () => this._Chain.fetcher.fetchTreasuryProposals(this.app.chain.block.height),
    );

    this._initialized = true;
    this._initializing = false;
  }
Example #8
Source File: programs.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
export async function uploadMeta(genesis: string, program: IPreparedProgram): Promise<Passed> {
  const accs = await accounts();
  const metaFile = program.spec.pathToMeta ? readFileSync(program.spec.pathToMeta) : null;
  const meta = metaFile ? JSON.stringify(await getWasmMetadata(metaFile)) : null;
  const data = {
    genesis,
    programId: program.id,
    meta,
    metaFile: metaFile ? metaFile.toString('base64') : null,
    name: program.spec.name,
    title: `Test ${program.spec.name}`,
    signature: u8aToHex(accs[program.spec.account].sign(meta)),
  };
  const response = await request('program.meta.add', data);
  expect(response).to.have.property('result');
  expect(response.result).to.have.property('status');
  expect(response.result.status).to.eq('Metadata added');
  return true;
}
Example #9
Source File: Signer.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
async _signMessage(evmAddress: string, message: Bytes | string): Promise<string> {
    if (!evmAddress) {
      return logger.throwError('No binding evm address');
    }
    const messagePrefix = '\x19Ethereum Signed Message:\n';
    if (typeof message === 'string') {
      message = toUtf8Bytes(message);
    }
    const msg = u8aToHex(concat([toUtf8Bytes(messagePrefix), toUtf8Bytes(String(message.length)), message]));

    if (!this.signingKey.signRaw) {
      return logger.throwError('Need to implement signRaw method');
    }

    const result = await this.signingKey.signRaw({
      address: evmAddress,
      data: msg,
      type: 'bytes'
    });

    return joinSignature(result.signature);
  }
Example #10
Source File: substrate-rpc.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
async function lookForExtrinsicAndEvents(api: ApiPromise, extrinsicHash: Uint8Array) {
  // We retrieve the block (including the extrinsics)
  const signedBlock = await api.rpc.chain.getBlock();

  // We retrieve the events for that block
  const allRecords: EventRecord[] = (await (
    await api.at(signedBlock.block.header.hash)
  ).query.system.events()) as any;

  const extrinsicIndex = signedBlock.block.extrinsics.findIndex((ext) => {
    return ext.hash.toHex() == u8aToHex(extrinsicHash);
  });
  if (extrinsicIndex < 0) {
    console.log(
      `Extrinsic ${extrinsicHash} is missing in the block ${signedBlock.block.header.hash}`
    );
  }
  const extrinsic = signedBlock.block.extrinsics[extrinsicIndex];

  // We retrieve the events associated with the extrinsic
  const events = allRecords
    .filter(
      ({ phase }) => phase.isApplyExtrinsic && phase.asApplyExtrinsic.toNumber() == extrinsicIndex
    )
    .map(({ event }) => event);
  return { events, extrinsic };
}
Example #11
Source File: Storage.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Get codeHash of program on-chain
   * @param programId
   * @returns codeHash in hex format
   */
  async getCodeHash(programId: ProgramId): Promise<Hex> {
    const program = await this.gProg(programId);
    return u8aToHex(program.code_hash);
  }
Example #12
Source File: Create.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function newSeed (seed: string | undefined | null, seedType: SeedType): string {
  switch (seedType) {
    case 'bip':
      return mnemonicGenerate();
    case 'dev':
      return DEV_PHRASE;
    default:
      return seed || u8aToHex(randomAsU8a());
  }
}
Example #13
Source File: Keyring.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
static async create(
    name: string,
    passphrase?: string,
  ): Promise<{
    keyring: KeyringPair;
    mnemonic: string;
    seed: string;
    json: KeyringPair$Json;
  }> {
    const mnemonic = mnemonicGenerate();
    const seed = mnemonicToMiniSecret(mnemonic);
    const keyring = await GearKeyring.fromSeed(seed, name);
    return {
      keyring,
      mnemonic: mnemonic,
      seed: u8aToHex(seed),
      json: keyring.toJson(passphrase),
    };
  }
Example #14
Source File: valueToText.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export default function valueToText (type: string, value: Codec | undefined | null, swallowError = true, contentShorten = true): React.ReactNode {
  if (isNull(value) || isUndefined(value)) {
    return div({}, '<unknown>');
  }

  return div(
    {},
    ['Bytes', 'Raw', 'Option<Keys>', 'Keys'].includes(type)
      ? u8aToHex(value.toU8a(true), contentShorten ? 512 : -1)
      // HACK Handle Keys as hex-only (this should go away once the node value is
      // consistently swapped to `Bytes`)
      : type === 'Vec<(ValidatorId,Keys)>'
        ? toString(formatKeys(value as unknown as [ValidatorId, Keys][]))
        : value instanceof Raw
          ? value.isEmpty
            ? '<empty>'
            : value.toString()
          : (value instanceof Option) && value.isNone
            ? '<none>'
            : toString(toHuman(value))
  );
}
Example #15
Source File: keyring.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * sign bytes from dapp as extension
 */
async function signBytesAsExtension(password: string, json: any) {
  return new Promise((resolve) => {
    const keyPair = keyring.getPair(json["address"]);
    try {
      if (!keyPair.isLocked) {
        keyPair.lock();
      }
      keyPair.decodePkcs8(password);
      resolve({
        signature: u8aToHex(keyPair.sign(wrapBytes(json["data"]))),
      });
    } catch (err) {
      resolve({ error: err.message });
    }
  });
}
Example #16
Source File: index.test.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
describe('bodhi', () => {
  it('should export the Provider', () => {
    expect(Provider).to.not.be.undefined;
  });

  it('default evm address', () => {
    const accountid = decodeAddress('5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY');

    const encode = u8aConcat('evm:', accountid);

    expect(u8aToHex(blake2AsU8a(encode, 256).slice(0, 20))).to.equal('0xf4ca11ca834c9e2fb49f059ab71fb9c72dad05f9');
  });
});
Example #17
Source File: Signer.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
/**
   *
   * @returns The default EVM address generated for the signer's substrate address
   */
  computeDefaultEvmAddress(): string {
    const address = this._substrateAddress;
    const publicKey = decodeAddress(address);

    const isStartWithEvm = u8aEq('evm:', publicKey.slice(0, 4));

    if (isStartWithEvm) {
      return getAddress(u8aToHex(publicKey.slice(4, 24)));
    }

    return getAddress(
      u8aToHex(blake2AsU8a(u8aConcat('evm:', publicKey), 256).slice(0, 20))
    );
  }
Example #18
Source File: Signer.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   *
   * @returns The default EVM address generated for the signer's substrate address
   */
  computeDefaultEvmAddress(): string {
    const address = this._substrateAddress;
    const publicKey = decodeAddress(address);

    const isStartWithEvm = u8aEq('evm:', publicKey.slice(0, 4));

    if (isStartWithEvm) {
      return getAddress(u8aToHex(publicKey.slice(4, 24)));
    }

    return getAddress(u8aToHex(blake2AsU8a(u8aConcat('evm:', publicKey), 256).slice(0, 20)));
  }
Example #19
Source File: Signer.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
async _signMessage(
    evmAddress: string,
    message: Bytes | string
  ): Promise<string> {
    if (!evmAddress) {
      return logger.throwError('No binding evm address');
    }
    const messagePrefix = '\x19Ethereum Signed Message:\n';
    if (typeof message === 'string') {
      message = toUtf8Bytes(message);
    }
    const msg = u8aToHex(
      concat([
        toUtf8Bytes(messagePrefix),
        toUtf8Bytes(String(message.length)),
        message
      ])
    );

    if (!this.signingKey.signRaw) {
      return logger.throwError('Need to implement signRaw method');
    }

    const result = await this.signingKey.signRaw({
      address: evmAddress,
      data: msg,
      type: 'bytes'
    });

    return joinSignature(result.signature);
  }
Example #20
Source File: useAccounts.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export function useAccounts(): UseAccounts {
  const mountedRef = useIsMountedRef();
  const [state, setState] = useState<UseAccounts>(EMPTY);

  useEffect((): (() => void) => {
    const subscription = keyring.accounts.subject.subscribe((accounts): void => {
      if (mountedRef.current) {
        const allAccounts = accounts ? Object.keys(accounts) : [];
        const allAccountsHex = allAccounts.map((a) => u8aToHex(decodeAddress(a)));
        const hasAccounts = allAccounts.length !== 0;
        const isAccount = (address?: string | null) => !!address && allAccounts.includes(address);

        setState({ allAccounts, allAccountsHex, areAccountsLoaded: true, hasAccounts, isAccount });
      }
    });

    return (): void => {
      setTimeout(() => subscription.unsubscribe(), 0);
    };
  }, [mountedRef]);

  return state;
}
Example #21
Source File: address.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
computeDefaultEvmAddress = (substrateAddress: HexString | string | Uint8Array): string => {
  if (!isSubstrateAddress) {
    return logger.throwArgumentError('invalid substrate address', 'address', substrateAddress);
  }

  const publicKey = decodeAddress(substrateAddress);

  const isStartWithEvm = u8aEq('evm:', publicKey.slice(0, 4));

  if (isStartWithEvm) {
    return getAddress(u8aToHex(publicKey.slice(4, 24)));
  }

  return getAddress(u8aToHex(blake2AsU8a(u8aConcat('evm:', publicKey), 256).slice(0, 20)));
}
Example #22
Source File: address.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export function convertToEth(address: string): string | null {
  if (!address) {
    return '';
  }

  const startAt = 2;
  const result = u8aToHex(decodeAddress(address)).slice(startAt);
  const PREFIX = '64766d3a00000000000000';

  // eslint-disable-next-line no-magic-numbers
  return result.startsWith(PREFIX) ? '0x' + result.slice(-42, -2) : null;
}
Example #23
Source File: sign.ts    From metamask-snap-polkadot with Apache License 2.0 6 votes vote down vote up
export async function signPayloadRaw(
  wallet: Wallet, api: ApiPromise, payload: SignerPayloadRaw
): Promise<{ signature: string }|void> {
  // ask for confirmation
  const confirmation = await showConfirmationDialog(
    wallet,
    `Do you want to sign following message: \n "${payload.data}" \n with account ${payload.address}`
  );
  // return seed if user confirmed action
  if (confirmation) {
    const keyPair = await getKeyPair(wallet);
    const signedBytes = keyPair.sign(hexToU8a(payload.data));
    return {
      signature: u8aToHex(signedBytes)
    };
  }
}
Example #24
Source File: valueToText.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-unused-vars
// eslint-disable-next-line complexity
export default function valueToText(
  type: string,
  value: Codec | undefined | null,
  _swallowError = true,
  contentShorten = true
): React.ReactNode {
  if (isNull(value) || isUndefined(value)) {
    return div({}, '<unknown>');
  }

  return div(
    {},
    ['Bytes', 'Raw', 'Option<Keys>', 'Keys'].includes(type) && isFunction(value.toU8a)
      ? // eslint-disable-next-line no-magic-numbers
        u8aToHex(value.toU8a(true), contentShorten ? 512 : -1)
      : // HACK Handle Keys as hex-only (this should go away once the node value is
      // consistently swapped to `Bytes`)
      type === 'Vec<(ValidatorId,Keys)>'
      ? toString(formatKeys(value as unknown as [ValidatorId, Keys][]))
      : value instanceof Raw
      ? value.isEmpty
        ? '<empty>'
        : value.toString()
      : value instanceof Option && value.isNone
      ? '<none>'
      : toString(toHuman(value))
  );
}
Example #25
Source File: BaseBytes.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function BaseBytes ({ asHex, children, className = '', defaultValue: { value }, isDisabled, isError, label, length = -1, onChange, onEnter, onEscape, size = 'full', validate = defaultValidate, withCopy, withLabel, withLength }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const [defaultValue] = useState(
    value
      ? isDisabled && isU8a(value) && isAscii(value)
        ? u8aToString(value)
        : isHex(value)
          ? value
          : u8aToHex(value as Uint8Array, isDisabled ? 256 : -1)
      : undefined
  );
  const [isValid, setIsValid] = useState(false);

  const _onChange = useCallback(
    (hex: string): void => {
      let [isValid, value] = convertInput(hex);

      isValid = isValid && validate(value) && (
        length !== -1
          ? value.length === length
          : value.length !== 0
      );

      if (withLength && isValid) {
        value = compactAddLength(value);
      }

      onChange && onChange({
        isValid,
        value: asHex
          ? u8aToHex(value)
          : value
      });

      setIsValid(isValid);
    },
    [asHex, length, onChange, validate, withLength]
  );

  return (
    <Bare className={className}>
      <Input
        className={size}
        defaultValue={defaultValue as string}
        isAction={!!children}
        isDisabled={isDisabled}
        isError={isError || !isValid}
        label={label}
        onChange={_onChange}
        onEnter={onEnter}
        onEscape={onEscape}
        placeholder={t<string>('0x prefixed hex, e.g. 0x1234 or ascii data')}
        type='text'
        withEllipsis
        withLabel={withLabel}
      >
        {children}
        {withCopy && (
          <CopyButton value={defaultValue} />
        )}
      </Input>
    </Bare>
  );
}
Example #26
Source File: Keyring.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
static generateSeed(mnemonic?: string): { seed: `0x${string}`; mnemonic: string } {
    if (!mnemonic) {
      mnemonic = mnemonicGenerate();
    }
    return { seed: u8aToHex(mnemonicToMiniSecret(mnemonic)), mnemonic };
  }
Example #27
Source File: address.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
export function convertToDvm(address: string): string {
  if (!address) {
    return '';
  }

  return u8aToHex(decodeAddress(address));
}
Example #28
Source File: modelUtils.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
createAndVerifyAddress = async ({ chain }, mnemonic = 'Alice') => {
  if (chain === 'ethereum' || chain === 'alex') {
    const wallet_id = 'metamask';
    const { keypair, address } = generateEthAddress();
    let res = await chai.request
      .agent(app)
      .post('/api/createAddress')
      .set('Accept', 'application/json')
      .send({ address, chain, wallet_id });
    const address_id = res.body.result.id;
    const token = res.body.result.verification_token;
    const chain_id = chain === 'alex' ? 3 : 1;   // use ETH mainnet for testing except alex
    const data = constructTypedMessage(chain_id, token);
    const privateKey = keypair.getPrivateKey();
    const signature = signTypedData({ privateKey, data, version: SignTypedDataVersion.V4 });
    res = await chai.request
      .agent(app)
      .post('/api/verifyAddress')
      .set('Accept', 'application/json')
      .send({ address, chain, signature, wallet_id });
    console.log(JSON.stringify(res.body));
    const user_id = res.body.result.user.id;
    const email = res.body.result.user.email;
    return { address_id, address, user_id, email };
  }
  if (chain === 'edgeware') {
    const wallet_id = 'polkadot';
    const keyPair = new Keyring({
      type: 'sr25519',
      ss58Format: 7,
    }).addFromMnemonic(mnemonic);
    const address = keyPair.address;
    let res = await chai.request
      .agent(app)
      .post('/api/createAddress')
      .set('Accept', 'application/json')
      .send({ address: keyPair.address, chain, wallet_id });
    const address_id = res.body.result.id;
    const token = res.body.result.verification_token;
    const u8aSignature = keyPair.sign(stringToU8a(token));
    const signature = u8aToHex(u8aSignature).slice(2);
    res = await chai.request
      .agent(app)
      .post('/api/verifyAddress')
      .set('Accept', 'application/json')
      .send({ address, chain, signature, wallet_id });
    const user_id = res.body.result.user.id;
    const email = res.body.result.user.email;
    return { address_id, address, user_id, email };
  }
  throw new Error('invalid chain');
}
Example #29
Source File: index.ts    From parity-bridges-ui with GNU General Public License v3.0 5 votes vote down vote up
export async function getTransactionCallWeight({
  action,
  account,
  targetApi,
  transactionState
}: TransactionCallWeightInput) {
  let weight: number = 0;
  let call: Uint8Array | null = null;
  const { receiverAddress, transferAmount, remarkInput, customCallInput, weightInput } = transactionState;

  if (account) {
    switch (action) {
      case TransactionTypes.REMARK:
        call = (await targetApi.tx.system.remark(remarkInput)).toU8a();
        // TODO [#121] Figure out what the extra bytes are about
        logger.info(`system::remark: ${u8aToHex(call)}`);
        weight = (await targetApi.tx.system.remark(remarkInput).paymentInfo(account)).weight.toNumber();
        break;
      case TransactionTypes.TRANSFER:
        if (receiverAddress) {
          call = (await targetApi.tx.balances.transfer(receiverAddress, transferAmount || 0)).toU8a();
          // TODO [#121] Figure out what the extra bytes are about
          logger.info(`balances::transfer: ${u8aToHex(call)}`);
          logger.info(`after balances::transfer: ${u8aToHex(call)}`);
          weight = (
            await targetApi.tx.balances.transfer(receiverAddress, transferAmount || 0).paymentInfo(account)
          ).weight.toNumber();
        }
        break;
      case TransactionTypes.CUSTOM:
        if (customCallInput) {
          call = isHex(customCallInput) ? hexToU8a(customCallInput.toString()) : null;
          weight = parseInt(weightInput!);
        }
        break;
      default:
        throw new Error(`Unknown type: ${action}`);
    }
  }
  return { call, weight };
}