@polkadot/types#Option TypeScript Examples

The following examples show how to use @polkadot/types#Option. 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 polkadot-registrar-watcher with Apache License 2.0 7 votes vote down vote up
extractRegistrationEntry = (key: StorageKey, exposure: Option<Registration>): {accountId: string; judgements: Vec<RegistrationJudgement>; info: IdentityInfo} => {
  const registration = exposure as Option<Registration>
  const accountId = key.args.map((k) => k.toHuman()).toString()
  const judgements = registration.unwrap().judgements
  const info = registration.unwrap().info 
  
  return {
    accountId: accountId,
    judgements: judgements,
    info: info
  }
}
Example #2
Source File: base-provider.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
getSubstrateAddress = async (
    addressOrName: string | Promise<string>,
    blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<string> => {
    const { address, blockHash } = await resolveProperties({
      address: this._getAddress(addressOrName),
      blockHash: this._getBlockHash(blockTag)
    });

    const substrateAccount = await this.queryStorage<Option<AccountId>>('evmAccounts.accounts', [address], blockHash);

    return substrateAccount.isEmpty ? computeDefaultSubstrateAddress(address) : substrateAccount.toString();
  };
Example #3
Source File: extrinsics.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
async createChannel(
    memberId: MemberId,
    inputMetadata: ChannelInputMetadata,
    inputAssets: ChannelInputAssets,
    cb?: ExtrinsicStatusCallbackFn
  ): Promise<ChannelExtrinsicResult> {
    await this.ensureApi()

    const [channelMetadata, channelAssets] = await parseChannelExtrinsicInput(this.api, inputMetadata, inputAssets)
    const creationParameters = new ChannelCreationParameters(this.api.registry, {
      meta: channelMetadata,
      assets: channelAssets,
      collaborators: new BTreeSet(this.api.registry, RuntimeMemberId, [memberId]),
      moderators: new BTreeSet(this.api.registry, RuntimeMemberId, [memberId]),
      reward_account: new Option<RuntimeAccountId>(this.api.registry, RuntimeAccountId, inputMetadata.ownerAccount),
    })

    const contentActor = new ContentActor(this.api.registry, {
      member: memberId,
    })
    const tx = this.api.tx.content.createChannel(contentActor, creationParameters)
    const { block, getEventData } = await this.sendExtrinsic(tx, cb)

    const channelId = getEventData('content', 'ChannelCreated')[1]

    return {
      channelId: channelId.toString(),
      block,
      assetsIds: extractChannelResultAssetsIds(inputAssets, getEventData),
    }
  }
Example #4
Source File: api.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
getValidators = async (
  api: ApiPromise,
  hash: Hash
): Promise<AccountId[]> => {
  const snapshot = (await api.query.staking.snapshotValidators.at(
    hash
  )) as Option<Vec<AccountId>>;
  return snapshot.isSome ? snapshot.unwrap() : [];
}
Example #5
Source File: IdentitySub.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function extractInfo ([[ids], opts]: [[string[]], Option<ITuple<[AccountId, Data]>>[]]): [string, string][] {
  return ids.reduce((result: [string, string][], id, index): [string, string][] => {
    const opt = opts[index];

    if (opt.isSome) {
      const [, data] = opt.unwrap();

      if (data.isRaw) {
        result.push([id, u8aToString(data.asRaw)]);
      }
    }

    return result;
  }, []);
}
Example #6
Source File: utils.ts    From subsocial-js with GNU General Public License v3.0 6 votes vote down vote up
export class OptionId<T extends SubstrateId> extends Option<u64> {
  constructor (value?: T) {
    const textOrNull = value || new Null(registry)
    super(registry, 'u64', textOrNull)
  }
}
Example #7
Source File: Mailbox.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Read mailbox
   * @param accountId
   * @returns
   * @example
   * ```javascript
   * const api = await GearApi.create();
   * const mailbox = await api.mailbox.read('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY');
   * console.log(mailbox);
   * ```
   */
  async read(accountId: Hex | AccountId32 | string, messageId?: Hex | H256): Promise<MailboxType> {
    if (messageId) {
      const mailbox = await this.api.query.gearMessenger.mailbox(accountId, messageId);
      return mailbox.toHuman() as MailboxType;
    } else {
      const keys = await this.api.query.gearMessenger.mailbox.keys(accountId);
      if (keys.length === 0) {
        return [];
      }
      const keyPrefixes = this.api.query.gearMessenger.mailbox.keyPrefix(accountId);
      const keysPaged = await this.api.rpc.state.getKeysPaged(keyPrefixes, 1000, keyPrefixes);
      const mailbox = (await this.api.rpc.state.queryStorageAt(keysPaged)) as Option<StoredMessage>[];
      return mailbox.map((option, index) => {
        return [
          keys[index].toHuman() as [AccountId, MessageId],
          this.api.createType('GearCoreMessageStoredStoredMessage', option.unwrap()).toHuman() as unknown,
        ];
      }) as MailboxType;
    }
  }
Example #8
Source File: collective_proposal.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
public updateVoters = async () => {
    const v = await this._Chain.api.query[this.collectiveName].voting<Option<Votes>>(this.data.hash);
    if (v.isSome) {
      const votes = v.unwrap();
      this.clearVotes();
      votes.ayes.map(
        (who) => this.addOrUpdateVote(
          new SubstrateCollectiveVote(this, this._Accounts.fromAddress(who.toString()), true)
        )
      );
      votes.nays.map(
        (who) => this.addOrUpdateVote(
          new SubstrateCollectiveVote(this, this._Accounts.fromAddress(who.toString()), false)
        )
      );
    }
  }
Example #9
Source File: issue.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
async getRequestsByIds(issueIds: (H256 | string)[]): Promise<Issue[]> {
        const head = await this.api.rpc.chain.getFinalizedHead();
        const issueRequestData = await Promise.all(
            issueIds.map(
                async (issueId): Promise<[Option<InterbtcPrimitivesIssueIssueRequest>, H256 | string]> =>
                    new Promise((resolve, reject) => {
                        this.api.query.issue.issueRequests
                            .at(head, ensureHashEncoded(this.api, issueId))
                            .then((request) => resolve([request, issueId]))
                            .catch(reject);
                    })
            )
        );
        return Promise.all(
            issueRequestData
                .filter(([option, _]) => option.isSome)
                .map(([issueRequest, issueId]) =>
                    parseIssueRequest(this.vaultsAPI, issueRequest.unwrap(), this.btcNetwork, issueId)
                )
        );
    }
Example #10
Source File: gov.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Query tips of treasury.
 */
async function getTreasuryTips(api: ApiPromise) {
  const tipKeys = await (api.query.tips || api.query.treasury).tips.keys();
  const tipHashes = tipKeys.map((key) => key.args[0].toHex());
  const optTips = (await (api.query.tips || api.query.treasury).tips.multi(tipHashes)) as Option<OpenTip>[];
  const tips = optTips
    .map((opt, index) => [tipHashes[index], opt.unwrapOr(null)])
    .filter((val) => !!val[1])
    .sort((a: any[], b: any[]) => a[1].closes.unwrapOr(BN_ZERO).cmp(b[1].closes.unwrapOr(BN_ZERO)));
  return Promise.all(
    tips.map(async (tip: any[]) => {
      const detail = tip[1].toJSON();
      const reason = (await (api.query.tips || api.query.treasury).reasons(detail.reason)) as Option<Bytes>;
      const tips = detail.tips.map((e: any) => ({
        address: e[0],
        value: e[1],
      }));
      return {
        hash: tip[0],
        ...detail,
        reason: reason.isSome ? hexToString(reason.unwrap().toHex()) : null,
        tips,
      };
    })
  );
}
Example #11
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
/**
   * Get the transaction count of an account at a specified block.
   * @param addressOrName The address or name of the account
   * @param blockTag The block to get the transaction count of, defaults to the head block
   * @returns A promise resolving to the account's transaction count
   */
  async getTransactionCount(
    addressOrName: string | Promise<string>,
    blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<number> {
    await this.resolveApi;

    const resolvedBlockTag = await blockTag;

    const address = await this._resolveEvmAddress(addressOrName);

    let account: Option<EvmAccountInfo>;

    if (resolvedBlockTag === 'pending') {
      account = await this.api.query.evm.accounts<Option<EvmAccountInfo>>(
        address
      );
    } else {
      const blockHash = await this._resolveBlockHash(blockTag);

      account = blockHash
        ? await this.api.query.evm.accounts.at<Option<EvmAccountInfo>>(
            blockHash,
            address
          )
        : await this.api.query.evm.accounts<Option<EvmAccountInfo>>(address);
    }

    if (!account.isNone) {
      return account.unwrap().nonce.toNumber();
    } else {
      return 0;
    }
  }
Example #12
Source File: useOwnStashes.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function getStashes(
  allAccounts: string[],
  ownBonded: Option<AccountId>[],
  ownLedger: Option<StakingLedger>[]
): [string, IsInKeyring][] {
  const result: [string, IsInKeyring][] = [];

  ownBonded.forEach((value, index): void => {
    // eslint-disable-next-line
    value.isSome && result.push([allAccounts[index], true]);
  });

  ownLedger.forEach((ledger): void => {
    if (ledger.isSome) {
      const stashId = ledger.unwrap().stash.toString();

      // eslint-disable-next-line
      !result.some(([accountId]) => accountId === stashId) && result.push([stashId, false]);
    }
  });

  return result;
}
Example #13
Source File: helpers.ts    From atlas with GNU General Public License v3.0 5 votes vote down vote up
createCommonAuctionParams = (registry: Registry, inputMetadata: NftAuctionInputMetadata) => {
  return {
    starting_price: new Balance(registry, inputMetadata.startingPrice),
    buy_now_price: new Option(registry, Balance, inputMetadata.buyNowPrice),
    starts_at: new Option(registry, BlockNumber, inputMetadata.startsAtBlock),
    whitelist: new BTreeSet(registry, RuntimeMemberId, inputMetadata.whitelistedMembersIds || []),
  }
}
Example #14
Source File: api.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
getCouncilPayoutInterval = (
  api: ApiPromise,
  hash: Hash
): Promise<Option<BlockNumber>> => api.query.council.payoutInterval.at(hash)
Example #15
Source File: Account.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
transformRecovery = {
  transform: (opt: Option<RecoveryConfig>) => opt.unwrapOr(null)
}