@polkadot/types/interfaces#AccountId TypeScript Examples

The following examples show how to use @polkadot/types/interfaces#AccountId. 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: 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 #2
Source File: functions.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
export async function getParticipantAt(api: ApiPromise, accountId: AccountId, blockHash: Hash): Promise<Participant> {
  let memberId = -1
  const isMemberRoot = await api.query.members.memberIdsByRootAccountId.at(blockHash,accountId) as Vec<MemberId>
  const isMemberCtrl = await api.query.members.memberIdsByControllerAccountId.at(blockHash,accountId) as Vec<MemberId>
  if (isMemberRoot[0].toNumber() === isMemberCtrl[0].toNumber() && isMemberRoot.length == 1 && isMemberCtrl.length == 1) {
    memberId = isMemberRoot[0].toNumber()
    const handle = (await api.query.members.membershipById.at(blockHash,isMemberRoot[0]) as Membership).handle.toString()
    const partipant: Participant = {
      memberId,
      handle,
      accountId:accountId.toString(),
    }
    return partipant
  } else {
    const memberIds: number[] = []
    const handle: string[] = []
    for (let ids of (isMemberRoot && isMemberCtrl)) {
      if (!memberIds.includes(ids.toNumber())) {
        memberIds.push(ids.toNumber())
        handle.push((await api.query.members.membershipById.at(blockHash,ids) as Membership).handle.toString())
      }
    }
    if (memberIds.length === 1) {
      const partipant: Participant = {
        memberId: memberIds[0],
        handle : handle[0],
        accountId:accountId.toString(),
      }
      return partipant
    } else {
      const partipant: Participant = {
        memberId: memberIds,
        handle,
        accountId:accountId.toString(),
      }
      return partipant
    }
  }
}
Example #3
Source File: useProxies.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
function createProxy (allAccounts: string[], delegate: AccountId, type: ProxyType, delay = BN_ZERO): Proxy {
  const address = delegate.toString();

  return {
    address,
    delay,
    isOwned: allAccounts.includes(address),
    type
  };
}
Example #4
Source File: index.ts    From subsocial-js with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Find and load an array of information about social profiles from Subsocial blockchain by a given array of account
   * `ids`.
   *
   * @param ids - An array of account ids of desired profiles.
   *
   * @returns An array of data about desired profiles from Subsocial blockchain. If no corresponding profiles to given
   * array of `ids`, an empty array is returned.
   */
  async findSocialAccounts (ids: AnyAccountId[]): Promise<SocialAccountWithId[]> {
    const accountIds = ids.map(id => asAccountId(id)).filter(x => typeof x !== 'undefined') as AccountId[]
    return this.findStructs({ pallet: 'profiles', storage: 'socialAccountById' }, accountIds);
  }
Example #5
Source File: collective.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
// TODO: we may want to track membership here as well as in elections
  public async init(ChainInfo: SubstrateChain, Accounts: SubstrateAccounts): Promise<void> {
    this._disabled = !ChainInfo.api.query[this.moduleName];
    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.CollectiveProposal);
    entities.forEach((e) => {
      const event = e.chainEvents[0];
      if (event && (event.data as any).collectiveName === this.moduleName) {
        return this._entityConstructor(e);
      }
    });

    // register new chain-event handlers
    this.app.chain.chainEntities.registerEntityHandler(
      SubstrateTypes.EntityKind.CollectiveProposal, (entity, event) => {
        if ((event.data as any).collectiveName === this.moduleName) {
          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.fetchCollectiveProposals(this.moduleName, this.app.chain.block.height)
    );

    const members = await ChainInfo.api.query[this.moduleName].members() as Vec<AccountId>;
    this._members = members.toArray().map((v) => this._Accounts.fromAddress(v.toString()));

    this._initialized = true;
    this._initializing = false;
  }
Example #6
Source File: escrow.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
async getRewards<U extends GovernanceUnit>(accountId: AccountId): Promise<MonetaryAmount<Currency<U>, U>> {
        // Step 1. Get amount in reward pool for the account ID
        const [rewardStake, rewardPerToken, rewardTally] = await Promise.all([
            this.getEscrowStake(accountId),
            this.getRewardPerToken(),
            this.getRewardTally(accountId),
        ]);
        // Step 2. Calculate the rewards that can be withdrawn at the moment
        // Stake[currencyId, accountId] * RewardPerToken[currencyId] - RewardTally[currencyId, accountId]
        const rewards = rewardStake.mul(rewardPerToken).sub(rewardTally);
        return newMonetaryAmount(rewards, this.governanceCurrency as unknown as Currency<U>);
    }
Example #7
Source File: use-get-vault-overview.tsx    From interbtc-ui with Apache License 2.0 6 votes vote down vote up
getVaultOverview = async (
  vault: VaultExt<BitcoinUnit>,
  accountId: AccountId
): Promise<VaultOverview> => {
  const tokenIdLiteral = tickerToCurrencyIdLiteral(vault.backingCollateral.currency.ticker) as CollateralIdLiteral;

  const apy = await window.bridge.vaults.getAPY(accountId, tokenIdLiteral);
  const collateralization = await window.bridge.vaults.getVaultCollateralization(accountId, tokenIdLiteral);

  const issues = await fetch(HYDRA_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      query: issueCountQuery(`vault: {accountId_eq: "${accountId.toString()}"}, status_eq: Pending`)
    })
  });

  const issuesCount = await issues.json();

  return {
    apy,
    collateralization,
    issues: issuesCount.data.issuesConnection.totalCount,
    collateralId: tokenIdLiteral,
    wrappedId: CurrencyIdLiteral.KBTC
  };
}
Example #8
Source File: gov.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Query overview of treasury and spend proposals.
 */
async function getTreasuryOverview(api: ApiPromise) {
  const [bounties, proposals, balance] = await Promise.all([
    api.derive.bounties?.bounties(),
    api.derive.treasury.proposals(),
    api.derive.balances.account(TREASURY_ACCOUNT as AccountId),
  ]);
  const pendingBounties = bounties.reduce(
    (total, { bounty: { status, value } }) => total.iadd(status.isApproved ? value : BN_ZERO),
    new BN(0)
  );
  const pendingProposals = proposals.approvals.reduce((total, { proposal: { value } }) => total.iadd(value), new BN(0));
  const burn =
    balance.freeBalance.gt(BN_ZERO) && !(api.consts.treasury.burn as any).isZero()
      ? (api.consts.treasury.burn as any).mul(balance.freeBalance).div(BN_MILLION)
      : BN_ZERO;
  const res: any = {
    ...proposals,
  };
  res["balance"] = balance.freeBalance.toString();
  res["burn"] = burn.toString();
  res["approved"] = pendingProposals.toString();
  res["spendable"] = balance.freeBalance
    .sub(pendingBounties)
    .sub(pendingProposals)
    .toString();
  res.proposals.forEach((e: any) => {
    if (e.council.length) {
      e.council = e.council.map((i: any) => ({
        ...i,
        proposal: _transfromProposalMeta(i.proposal),
      }));
    }
  });
  return res;
}
Example #9
Source File: AccountName.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function defaultOrAddr(
  defaultName = '',
  _address: AccountId | AccountIndex | Address | string | Uint8Array,
  _accountIndex?: AccountIndex | null
): [React.ReactNode, boolean, boolean, boolean] {
  // eslint-disable-next-line @typescript-eslint/no-shadow
  const known = KNOWN.find(([known]) => known.eq(_address));

  if (known) {
    return [known[1], false, false, true];
  }

  const accountId = _address.toString();

  if (!accountId) {
    return [defaultName, false, false, false];
  }

  const [isAddressExtracted, , extracted] = getAddressName(accountId, null, defaultName);
  const accountIndex = (_accountIndex || '').toString() || indexCache.get(accountId);

  if (isAddressExtracted && accountIndex) {
    indexCache.set(accountId, accountIndex);

    return [accountIndex, false, true, false];
  }

  return [extracted, !isAddressExtracted, isAddressExtracted, false];
}
Example #10
Source File: functions.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
export async function getParticipant(api: ApiPromise, accountId: AccountId): Promise<Participant> {
  let memberId = -1
  const isMemberRoot = await api.query.members.memberIdsByRootAccountId(accountId) as Vec<MemberId>
  const isMemberCtrl = await api.query.members.memberIdsByControllerAccountId(accountId) as Vec<MemberId>
  if (isMemberRoot[0] === isMemberCtrl[0] && isMemberRoot.length == 1 && isMemberCtrl.length == 1) {
    console.log("true")
    memberId = isMemberRoot[0].toNumber()
    const handle = (await api.query.members.membershipById(isMemberRoot[0]) as Membership).handle.toString()
    const partipant: Participant = {
      memberId,
      handle,
      accountId:accountId.toString(),
    }
    return partipant
  } else {
    const memberIds: number[] = []
    const handle: string[] = []
    for (let ids of (isMemberRoot && isMemberCtrl)) {
      if (!memberIds.includes(ids.toNumber())) {
        memberIds.push(ids.toNumber())
        handle.push((await api.query.members.membershipById(ids) as Membership).handle.toString())
      }
    }
    if (memberIds.length === 1) {
      
      const partipant: Participant = {
        memberId: memberIds[0],
        handle,
        accountId:accountId.toString(),
      }
      return partipant
    } else {
      const partipant: Participant = {
        memberId: memberIds,
        handle,
        accountId:accountId.toString(),
      }
      return partipant
    }
  }
}
Example #11
Source File: index.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function Menu ({ className = '' }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const { allAccounts, hasAccounts } = useAccounts();
  const apiProps = useApi();
  const sudoKey = useCall<AccountId>(apiProps.isApiReady && apiProps.api.query.sudo?.key);
  const location = useLocation();

  const externalRef = useRef(createExternals(t));

  const groupRef = useRef({
    accounts: t('Accounts'),
    developer: t('Developer'),
    governance: t('Governance'),
    network: t('Network'),
    applications: t('Applications'),
    settings: t('Settings'),
    storage: t('Storage'),
    csmStaking: t('Profit Data')
  });

  const routeRef = useRef(createRoutes(t));

  const hasSudo = useMemo(
    () => !!sudoKey && allAccounts.some((address) => sudoKey.eq(address)),
    [allAccounts, sudoKey]
  );

  const visibleGroups = useMemo(
    () => extractGroups(routeRef.current, groupRef.current, apiProps, hasAccounts, hasSudo),
    [apiProps, hasAccounts, hasSudo]
  );

  const activeRoute = useMemo(
    () => routeRef.current.find((route) => location.pathname.startsWith(`/${route.name}`)) || null,
    [location]
  );

  const isLoading = !apiProps.isApiReady || !apiProps.isApiConnected;

  return (
    <div className={`${className}${isLoading ? ' isLoading' : ''} highlight--bg`}>
      <div className='menuContainer'>
        <div className='menuSection'>
          <ChainInfo />
          <ul className='menuItems'>
            {visibleGroups.map(({ name, routes }): React.ReactNode => (
              <Grouping
                isActive={ activeRoute && activeRoute.group === name.toLowerCase()}
                key={name}
                name={name}
                routes={routes}
              />
            ))}
          </ul>
        </div>
        <div className='menuSection media--1200'>
          <ul className='menuItems'>
            {externalRef.current.map((route): React.ReactNode => (
              <Item
                className='external'
                isLink
                isToplevel
                key={route.name}
                route={route}
              />
            ))}
          </ul>
        </div>
        <NodeInfo/>
      </div>
    </div>
  );
}