@polkadot/types#Vec TypeScript Examples

The following examples show how to use @polkadot/types#Vec. 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: mintingAndBurning.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
processStakingRewards = (
  events: Vec<EventRecord>,
  report: MintingAndBurningData
) => {
  const stakingEvents = filterByEvent("staking.Reward", events);
  const { minting } = report;
  if (stakingEvents.length > 0) {
    stakingEvents.forEach((event) => {
      const { data } = event.event;
      const dataJson = data.toJSON() as object[];
      const reward = dataJson[1] as unknown as number;
      const accountId = dataJson[0] as AccountId;
      minting.stakingRewardsTotal += reward;
      minting.stakingRewards.push({
        address: accountId,
        reward,
      });
    });
  }
}
Example #3
Source File: base-provider.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
_getExtrinsicsAndEventsAtBlock = async (
    blockHash: string,
    txHash?: string
  ): Promise<{
    extrinsics: GenericExtrinsic | GenericExtrinsic[] | undefined;
    extrinsicsEvents: EventRecord[] | undefined;
  }> => {
    const [block, blockEvents] = await Promise.all([
      this.api.rpc.chain.getBlock(blockHash.toLowerCase()),
      this.queryStorage<Vec<FrameSystemEventRecord>>('system.events', [], blockHash)
    ]);

    if (!txHash) return { extrinsics: block.block.extrinsics, extrinsicsEvents: undefined };

    const { transactionHash, transactionIndex, extrinsicIndex, isExtrinsicFailed } = getTransactionIndexAndHash(
      txHash.toLowerCase(),
      block.block.extrinsics,
      blockEvents
    );

    const extrinsicEvents = blockEvents.filter(
      (event) => event.phase.isApplyExtrinsic && event.phase.asApplyExtrinsic.toNumber() === extrinsicIndex
    );

    return {
      extrinsics: block.block.extrinsics[extrinsicIndex],
      extrinsicsEvents: extrinsicEvents
    };
  };
Example #4
Source File: joyApi.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
async findActiveValidators(hash: Hash, searchPreviousBlocks: boolean): Promise<AccountId[]> {
    const block = await this.api.rpc.chain.getBlock(hash);

    let currentBlockNr = block.block.header.number.toNumber();
    let activeValidators;
    do {
      let currentHash = (await this.api.rpc.chain.getBlockHash(currentBlockNr)) as Hash;
      let allValidators = await this.api.query.staking.snapshotValidators.at(currentHash) as Option<Vec<AccountId>>;
      if (!allValidators.isEmpty) {
        let max = (await this.api.query.staking.validatorCount.at(currentHash)).toNumber();
        activeValidators = Array.from(allValidators.unwrap()).slice(0, max);
      }

      if (searchPreviousBlocks) {
        --currentBlockNr;
      } else {
        ++currentBlockNr;
      }

    } while (activeValidators === undefined);
    return activeValidators;
  }
Example #5
Source File: useProxies.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export default function useProxies (address?: string | null): State {
  const { api } = useApi();
  const { allAccounts } = useAccounts();
  const mountedRef = useIsMountedRef();
  const [known, setState] = useState<State>(EMPTY_STATE);

  useEffect((): void => {
    setState(EMPTY_STATE);

    address && api.query.proxy &&
      api.query.proxy
        .proxies<ITuple<[Vec<ITuple<[AccountId, ProxyType]> | ProxyDefinition>, BalanceOf]>>(address)
        .then(([_proxies]): void => {
          const proxies = api.tx.proxy.addProxy.meta.args.length === 3
            ? (_proxies as ProxyDefinition[]).map(({ delay, delegate, proxyType }) =>
              createProxy(allAccounts, delegate, proxyType, delay)
            )
            : (_proxies as [AccountId, ProxyType][]).map(([delegate, proxyType]) =>
              createProxy(allAccounts, delegate, proxyType)
            );
          const owned = proxies.filter(({ isOwned }) => isOwned);

          mountedRef.current && setState({
            hasOwned: owned.length !== 0,
            owned,
            proxies
          });
        })
        .catch(console.error);
  }, [allAccounts, api, address, mountedRef]);

  return known;
}
Example #6
Source File: Blocks.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Get all events of particular block
   * @param blockHash hash of particular block
   * @returns Vec of events
   */
  async getEvents(blockHash: `0x${string}` | Uint8Array): Promise<Vec<FrameSystemEventRecord>> {
    const apiAt = await this.api.at(blockHash);
    return apiAt.query.system.events();
  }
Example #7
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 #8
Source File: index.ts    From parity-bridges-ui with GNU General Public License v3.0 6 votes vote down vote up
checkMessageDispatchedEvent = async (
  targetApi: ApiPromise,
  blockNumber: string | null,
  messageNonce: string | null
) => {
  if (!blockNumber || !messageNonce) {
    return TransactionStatusEnum.IN_PROGRESS;
  }
  const blockHash = (await targetApi.rpc.chain.getBlockHash(blockNumber)) as BlockHash;
  const signedBlock = (await targetApi.rpc.chain.getBlock(blockHash)) as SignedBlock;
  const allRecords = (await targetApi.query.system.events.at(signedBlock.block.header.hash)) as Vec<any>;

  let status = TransactionStatusEnum.FAILED;
  signedBlock.block.extrinsics.forEach((ext, index) => {
    const events = allRecords.filter(({ phase }) => phase.isApplyExtrinsic && phase.asApplyExtrinsic.eq(index));
    const found = events.find(({ event: { method, data } }) => {
      return method === MESSAGE_DISPATCH_EVENT && deepFind(data, messageNonce) && deepFind(data, OK);
    });
    if (found) {
      status = TransactionStatusEnum.COMPLETED;
    }
  });
  return status;
}
Example #9
Source File: useEventTrigger.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export function useEventTrigger(
  _checks: EventCheck[],
  filter: (record: EventRecord) => boolean = IDENTITY_FILTER
): Result {
  const { api } = useApi();
  const [state, setState] = useState(() => EMPTY_RESULT);
  const [checks] = useState(() => _checks);
  const mountedRef = useIsMountedRef();
  const eventRecords = useCall<Vec<EventRecord>>(api.query.system.events);

  useEffect((): void => {
    if (mountedRef.current && eventRecords) {
      const events = eventRecords.filter((r) => r.event && checks.some((c) => c && c.is(r.event)) && filter(r));

      if (events.length) {
        setState({
          blockHash: eventRecords.createdAtHash?.toHex() || '',
          events,
        });
      }
    }
  }, [eventRecords, checks, filter, mountedRef]);

  return state;
}
Example #10
Source File: utils.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
isJudgementsFieldDisplayNamesCompliant = (judgements: Vec<RegistrationJudgement>): boolean =>{
  let isCompliant = false
  for (const judgement of judgements) {
    if(_isAlreadyJudged(judgement) && !_isErroneousJudgement(judgement)) isCompliant = true 
  }
  return isCompliant
}
Example #11
Source File: mintingAndBurning.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
processSudoEvents = (
  events: Vec<EventRecord>,
  report: MintingAndBurningData
) => {
  const setBalanceEvents = filterByEvent("balances.BalanceSet", events);
  const { minting } = report;
  if (setBalanceEvents.length > 0) {
    setBalanceEvents.forEach((event: EventRecord) => {
      const { data } = event.event;
      const amount = Number(data[1]);
      minting.sudoEvents.push({ amount });
      minting.totalSudoMint += amount;
    });
  }
}
Example #12
Source File: helpers.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
getResultChannelDataObjectsIds = (
  assets: ChannelAssets<unknown>,
  dataObjectsIds: Vec<DataObjectId>
): ChannelAssetsIds => {
  const ids = dataObjectsIds.map((dataObjectsId) => dataObjectsId.toString())

  const hasAvatar = !!assets.avatarPhoto
  const hasCover = !!assets.coverPhoto

  return {
    ...(hasAvatar ? { avatarPhoto: ids[0] } : {}),
    ...(hasCover ? { coverPhoto: ids[hasAvatar ? 1 : 0] } : {}),
  }
}
Example #13
Source File: Address.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function filterProxies(
  allAccounts: string[],
  tx: Call | SubmittableExtrinsic<'promise'>,
  proxies: [string, ProxyType][]
): string[] {
  // check an array of calls to all have proxies as the address
  const checkCalls = (address: string, txs: Call[]): boolean =>
    !txs.some((tx) => !filterProxies(allAccounts, tx, proxies).includes(address));

  // get the call info
  const { method, section } = findCall(tx);

  return proxies
    .filter(([address, proxy]): boolean => {
      if (!allAccounts.includes(address)) {
        return false;
      }

      switch (proxy.toString()) {
        case 'Any':
          return true;
        case 'Governance':
          return [
            'council',
            'democracy',
            'elections',
            'electionsPhragmen',
            'phragmenElection',
            'poll',
            'society',
            'technicalCommittee',
            'tips',
            'treasury',
          ].includes(section);
        case 'IdentityJudgement':
          return section === 'identity' && method === 'provideJudgement';
        case 'NonTransfer':
          return !(
            section === 'balances' ||
            (section === 'indices' && method === 'transfer') ||
            (section === 'vesting' && method === 'vestedTransfer')
          );
        case 'Staking':
          return (
            section === 'staking' ||
            (section === 'utility' &&
              ((method === 'batch' && checkCalls(address, tx.args[0] as Vec<Call>)) ||
                (method === 'asLimitedSub' && checkCalls(address, [tx.args[0] as Call]))))
          );
        case 'SudoBalances':
          return (
            (section === 'sudo' && method === 'sudo' && findCall(tx.args[0] as Call).section === 'balances') ||
            (section === 'utility' && method === 'batch' && checkCalls(address, tx.args[0] as Vec<Call>))
          );
        default:
          return false;
      }
    })
    .map(([address]) => address);
}
Example #14
Source File: get-media-change.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
async function main() {
    // Initialise the provider to connect to the local node
    const provider = new WsProvider('ws://127.0.0.1:9944');

    const api = await ApiPromise.create({ provider, types })
    const firstBlock = 1292265 // first block after the upgrade to the new Content Directory
    const lastBlock = 2332000
    // note that with this blockheight, you will see a lot of jsgenesis initialization and uploads
    
    
    for (let blockHeight=firstBlock; blockHeight<lastBlock; blockHeight++) {
      const blockHash = await api.rpc.chain.getBlockHash(blockHeight) as Hash
      const events = await api.query.system.events.at(blockHash) as Vec<EventRecord>;
      const eventsArray: EventRecord[] = []
      let eventIndex = 0
      for (let i=0; i<events.length; i++) {
        const section = events[i].event.section
        const method = events[i].event.method
        if(section == 'content') {
          console.log(`Event section=${section}, Event method=${method}`)
          eventsArray.push(events[i])
          if (method == "VideoCreated") {
            eventIndex+=1
            const cdChange = await getChangeAction(api, 'createVideo', blockHeight, blockHash, eventIndex, events[i])
            console.log("Change",JSON.stringify(cdChange, null, 4))
          }
          if (method == "VideoUpdated") {
            eventIndex+=1
            const cdChange = await getChangeAction(api, 'updateVideo', blockHeight, blockHash, eventIndex, events[i])
            console.log("Change",JSON.stringify(cdChange, null, 4))
          }
          if (method == "VideoDeleted") {
            eventIndex+=1
            const cdChange = await getChangeAction(api, 'deleteVideo', blockHeight, blockHash, eventIndex, events[i])
            console.log("Change",JSON.stringify(cdChange, null, 4))
          }
          if (method == "ChannelCreated") {
            eventIndex+=1
            const cdChange = await getChangeAction(api, 'createChannel', blockHeight, blockHash, eventIndex, events[i])
            console.log("Change",JSON.stringify(cdChange, null, 4))
          }
          if (method == "ChannelUpdated") {
            eventIndex+=1
            const cdChange = await getChangeAction(api, 'updateChannel', blockHeight, blockHash, eventIndex, events[i])
            console.log("Change",JSON.stringify(cdChange, null, 4))
          }
        }
      }
    }
    
  api.disconnect()
}
Example #15
Source File: migrateCouncillorValidatorFlags.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
export default async function (models, chain?: string): Promise<void> {
  // 1. fetch the node and url of supported/selected chains
  log.info('Fetching node info for chain entity migrations...');
  const whereOption = chain ? { chain } : {};
  const nodes = await models.ChainNode.findAll({
    where: whereOption,
    include: [
      {
        model: models.Chain,
        where: {
          active: true,
          has_chain_events_listener: true,
          base: ChainBase.Substrate,
        },
        required: true,
      },
    ],
  });
  if (!nodes) {
    throw new Error('no nodes found for chain entity migration');
  }

  // 2. for each node, fetch councillors and validators
  for (const node of nodes) {
    log.info(`Fetching and migrating councillor/validator flags for ${node.chain}.`);
    const flagsHandler = new UserFlagsHandler(models, node.chain);

    const nodeUrl = constructSubstrateUrl(node.url);
    try {
      const api = await SubstrateEvents.createApi(nodeUrl, node.Chain.substrate_spec);

      log.info('Fetching councillor and validator lists...');
      const validators = await api.derive.staking?.validators();
      const section = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections';
      const councillors = await api.query[section].members<Vec<[ AccountId, Balance ] & Codec>>();
      await flagsHandler.forceSync(
        councillors.map(([ who ]) => who.toString()),
        validators ? validators.validators.map((v) => v.toString()) : [],
      );
    } catch (e) {
      log.error(`Failed to migrate flags for ${node.chain}: ${e.message}`);
    }
  }
}
Example #16
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 #17
Source File: phragmen_elections.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public async init(ChainInfo: SubstrateChain, Accounts: SubstrateAccounts): Promise<void> {
    this._disabled = !ChainInfo.api.query.elections;
    this._Chain = ChainInfo;
    this._Accounts = Accounts;

    const moduleName = ChainInfo.api.consts.elections
      ? 'elections'
      : ChainInfo.api.consts.phragmenElections
        ? 'phragmenElections'
        : 'electionsPhragmen';

    this._candidacyBond = this._Chain.coins(ChainInfo.api.consts[moduleName].candidacyBond as BalanceOf);
    this._votingBond = this._Chain.coins(ChainInfo.api.consts[moduleName].votingBond as BalanceOf);
    this._desiredMembers = +ChainInfo.api.consts[moduleName].desiredMembers;
    this._desiredRunnersUp = +ChainInfo.api.consts[moduleName].desiredRunnersUp;
    this._termDuration = +ChainInfo.api.consts[moduleName].termDuration;
    const members = (await ChainInfo.api.query[moduleName].members()) as Vec<any>;
    const runnersUp = (await ChainInfo.api.query[moduleName].runnersUp()) as Vec<any>;

    this._runnersUp = runnersUp.map((r) => ({
      who: r.who !== undefined ? r.who.toString() : r[0].toString(),
      // TODO: broken on KLP
      score: r.stake ? r.stake.toBn() : r[1].toBn()
    }));
    this._members = members.reduce((ms, r) => {
      const who = r.who !== undefined ? r.who : r[0];
      const bal = r.stake !== undefined ? r.stake : r[1];
      ms[who.toString()] = bal.toBn();
      return ms;
    }, {});

    const currentIndex = +(await ChainInfo.api.query[moduleName].electionRounds<u32>());
    const blockNumber = await ChainInfo.api.derive.chain.bestNumber();
    const termDuration = +ChainInfo.api.consts[moduleName].termDuration;
    const roundStartBlock = Math.floor((+blockNumber) / termDuration) * termDuration;
    const endBlock = roundStartBlock + termDuration;
    const p = {
      identifier: `${currentIndex}`,
      round: currentIndex,
      endBlock,
    };
    this._activeElection = new SubstratePhragmenElection(ChainInfo, Accounts, this, p, moduleName);
    this._initialized = true;
  }
Example #18
Source File: base-provider.ts    From bodhi.js with Apache License 2.0 5 votes vote down vote up
// @TODO Testing
  getTransactionReceiptAtBlock = async (
    hashOrNumber: number | string | Promise<string>,
    _blockTag: BlockTag | Promise<BlockTag>
  ): Promise<TransactionReceipt> => {
    const blockTag = await this._ensureSafeModeBlockTagFinalization(_blockTag);

    hashOrNumber = await hashOrNumber;
    const header = await this._getBlockHeader(blockTag);
    const blockHash = header.hash.toHex();
    const blockNumber = header.number.toNumber();

    const [block, blockEvents] = await Promise.all([
      this.api.rpc.chain.getBlock(blockHash),
      this.queryStorage<Vec<FrameSystemEventRecord>>('system.events', [], blockHash)
    ]);

    const { transactionHash, transactionIndex, extrinsicIndex, isExtrinsicFailed } = getTransactionIndexAndHash(
      hashOrNumber,
      block.block.extrinsics,
      blockEvents
    );

    const extrinsicEvents = blockEvents.filter(
      (event) => event.phase.isApplyExtrinsic && event.phase.asApplyExtrinsic.toNumber() === extrinsicIndex
    );

    if (isExtrinsicFailed) {
      const [dispatchError] = extrinsicEvents[extrinsicEvents.length - 1].event.data as any[];

      let message = dispatchError.type;

      if (dispatchError.isModule) {
        try {
          const mod = dispatchError.asModule;
          const error = this.api.registry.findMetaError(new Uint8Array([mod.index.toNumber(), mod.error.toNumber()]));
          message = `${error.section}.${error.name}: ${error.docs}`;
        } catch (error) {
          // swallow
        }
      }

      return logger.throwError(`ExtrinsicFailed: ${message}`, Logger.errors.UNKNOWN_ERROR, {
        hash: transactionHash,
        blockHash
      });
    }

    // @TODO
    const evmEvent = findEvmEvent(extrinsicEvents);

    if (!evmEvent) {
      return logger.throwError(`evm event not found`, Logger.errors.UNKNOWN_ERROR, {
        hash: transactionHash,
        blockHash
      });
    }

    const transactionInfo = { transactionIndex, blockHash, transactionHash, blockNumber };

    const partialTransactionReceipt = getPartialTransactionReceipt(evmEvent);

    // to and contractAddress may be undefined
    return this.formatter.receipt({
      confirmations: (await this._getBlockHeader('latest')).number.toNumber() - blockNumber,
      ...transactionInfo,
      ...partialTransactionReceipt,
      logs: partialTransactionReceipt.logs.map((log) => ({
        ...transactionInfo,
        ...log
      }))
    }) as any;
  };
Example #19
Source File: Blocks.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
/**
   * Get all extrinsic of particular block
   * @param blockHash hash of particular block
   * @returns Vec of extrinsics
   */
  async getExtrinsics(blockHash: `0x${string}` | Uint8Array): Promise<Vec<GenericExtrinsic<AnyTuple>>> {
    return (await this.get(blockHash)).block.extrinsics;
  }
Example #20
Source File: general.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
async function main() {
    // Initialise the provider to connect to the local node
    const provider = new WsProvider('ws://127.0.0.1:9944');
      
    //If you want to play around on our staging network, go ahead and connect to this staging network instead.
    //const provider = new WsProvider('wss://testnet-rpc-2-singapore.joystream.org');

    // Create the API and wait until ready
    const api = await ApiPromise.create({ provider, types })

    // get finalized head of chain, as number and hash:
    const finalizedHeadNumber = await api.derive.chain.bestNumberFinalized()
    const finalizedHeadHash = await api.rpc.chain.getFinalizedHead()
    // get head of chain, as hash or number:
    const headNumber = await api.derive.chain.bestNumber()
    const headHash = await api.rpc.chain.getBlockHash(headNumber)

    console.log(
      `Finalized head of chain
      - as number: ${finalizedHeadNumber}
      - with hash: ${finalizedHeadHash}`
      )
    console.log(
      `Head of chain
      - as number: ${headNumber}
      - with hash: ${headHash}`
      )

    // get current issuance 
    const issuance = await api.query.balances.totalIssuance() as Balance
    console.log(`current issuance is: ${issuance.toNumber()}tJOY`)
    
    // get events in newest block:
    const events = await api.query.system.events() as Vec<EventRecord>;
    for (let { event } of events) {
      const section = event.section
      const method = event.method
      const data = event.data
      console.log("section",section)
      console.log("method",method)
      console.log("data",data.toHuman())
      console.log("")
    }

    // get extrinsics in finalized head block:
    const getLatestBlock = await api.rpc.chain.getBlock(finalizedHeadHash) as SignedBlock
    const extrinsics = getLatestBlock.block.extrinsics as Vec<Extrinsic>
    for (let i=0; i<extrinsics.length; i++) {
      const section = extrinsics[i].method.section
      const method = extrinsics[i].method.method
      console.log("section",section)
      console.log("method",method)
      console.log("")
      // get signer of extrinsics if applicable
      const signer = extrinsics[i].signer
      if (!signer.isEmpty) {
        console.log("signer",signer)
      }
    }
    
    api.disconnect()
}
Example #21
Source File: index.ts    From substrate-api-explorer with Apache License 2.0 5 votes vote down vote up
function formatDocs(docs: Vec<Text>) {
  return docs.map((text) => text.toString()).join()
}
Example #22
Source File: mintingAndBurning.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
processProposals = async (
  api: ApiPromise,
  events: Vec<EventRecord>,
  report: MintingAndBurningData,
  hash: BlockHash
) => {
  const proposalEvents = filterByEvent(
    "proposalsEngine.ProposalStatusUpdated",
    events
  );
  const { minting, burning } = report;
  if (proposalEvents.length > 0) {
    for (const event of proposalEvents) {
      const { data } = event.event;
      const dataJson = data.toJSON() as object[];
      const proposalId = dataJson[0] as unknown as number;
      const block = await getBlock(api, hash);
      const cancelledProposals = filterBlockExtrinsicsByMethod(
        block,
        "proposalsEngine.cancelProposal"
      );
      for (const {} of cancelledProposals) {
        burning.totalProposalCancellationFee += 10000; // TODO get proposal cancellation fee from chains
        burning.cancelledProposals.push(proposalId);
      }
      const proposalStatusWrapper = dataJson[1] as unknown as ProposalStatus;
      const finalizationData = (
        proposalStatusWrapper as unknown as {
          [key: string]: FinalizationData[];
        }
      )["finalized"] as unknown as FinalizationData;
      for await (const key of Object.keys(finalizationData.proposalStatus)) {
        if (key.toString() === "expired" || key.toString() === "rejected") {
          burning.totalProposalCancellationFee += 5000; // TODO get proposal rejected/expired fee from chains
        }
      }

      const spendingProposalAmount = await getSpendingProposalAmount(
        api,
        hash,
        proposalId
      );
      if (
        spendingProposalAmount &&
        minting.spendingProposals.filter(
          (p) =>
            p.proposalId === proposalId && p.amount === spendingProposalAmount
        ).length === 0
      ) {
        minting.spendingProposals.push({
          proposalId,
          amount: spendingProposalAmount,
        });
        minting.totalSpendingProposalsMint += spendingProposalAmount;
      }
    }
  }
}
Example #23
Source File: IdentitySub.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
transformIds = {
  transform: ([, ids]: ITuple<[Balance, Vec<AccountId>]>) => ids.map((a) => a.toString())
}
Example #24
Source File: api.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
getCouncilCommitments = (
  api: ApiPromise,
  hash: Hash
): Promise<Vec<Hash>> => api.query.councilElection.commitments.at(hash)
Example #25
Source File: useAvailableSlashes.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
export function useAvailableSlashes (): [BN, UnappliedSlash[]][] {
  const { api } = useApi();
  const indexes = useCall<DeriveSessionIndexes>(api.derive.session?.indexes);
  const earliestSlash = useCall<Option<EraIndex>>(api.query.staking?.earliestUnappliedSlash);
  const mountedRef = useIsMountedRef();
  const [slashes, setSlashes] = useState<[BN, UnappliedSlash[]][]>([]);

  useEffect((): Unsub => {
    let unsub: Unsub | undefined;

    if (mountedRef.current && indexes && earliestSlash && earliestSlash.isSome) {
      const from = earliestSlash.unwrap();
      const range: BN[] = [];
      let start = new BN(from);

      // any <= activeEra (we include activeEra since slashes are immediately reflected)
      while (start.lte(indexes.activeEra)) {
        range.push(start);
        start = start.add(BN_ONE);
      }

      if (range.length) {
        (async (): Promise<void> => {
          unsub = await api.query.staking.unappliedSlashes.multi<Vec<UnappliedSlash>>(range, (values): void => {
            mountedRef.current && setSlashes(
              values
                .map((value, index): [BN, UnappliedSlash[]] => [from.addn(index), value])
                .filter(([, slashes]) => slashes.length)
            );
          });
        })().catch(console.error);
      }
    }

    return (): void => {
      unsub && unsub();
    };
  }, [api, earliestSlash, indexes, mountedRef]);

  return slashes;
}
Example #26
Source File: api.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
getEvents = (
  api: ApiPromise,
  hash: Hash
): Promise<Vec<EventRecord>> => api.query.system.events.at(hash)
Example #27
Source File: KeyValueArray.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function KeyValueArray ({ className = '', defaultValue, isDisabled, isError, label, onChange, onEnter, onEscape, withLabel }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const [placeholder, setPlaceholder] = useState<string>(t(EMPTY_PLACEHOLDER));

  const _onChange = useCallback(
    (raw: Uint8Array): void => {
      let encoded: Parsed = { isValid: false, value: [] };

      try {
        encoded = parseFile(raw);

        setPlaceholder(t('{{count}} key/value pairs encoded for submission', {
          replace: {
            count: encoded.value.length
          }
        }));
      } catch (error) {
        console.error('Error converting json k/v', error);

        setPlaceholder(t(EMPTY_PLACEHOLDER));
      }

      onChange && onChange(encoded);
    },
    [onChange, t]
  );

  if (isDisabled) {
    const pairs = defaultValue.value as Vec<Pair>;

    return (
      <>
        <Base
          className={className}
          label={label}
        >
          <div />
        </Base>
        <div className='ui--Params'>
          {pairs.map(([key, value]): React.ReactNode => {
            const keyHex = u8aToHex(key.toU8a(true));

            return (
              <Bytes
                defaultValue={{ value } as unknown as RawParam}
                isDisabled
                key={keyHex}
                label={keyHex}
                name={keyHex}
                onEnter={onEnter}
                onEscape={onEscape}
                type={BYTES_TYPE}
              />
            );
          })}
        </div>
      </>
    );
  }

  return (
    <File
      className={className}
      isDisabled={isDisabled}
      isError={isError}
      label={label}
      onChange={_onChange}
      placeholder={placeholder}
      withLabel={withLabel}
    />
  );
}
Example #28
Source File: get-events-and-extrinsics.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
async function main() {
    // Initialise the provider to connect to the local node
    const provider = new WsProvider('ws://127.0.0.1:9944');

    //If you want to play around on our staging network, go ahead and connect to this staging network instead.
    //const provider = new WsProvider('wss://testnet-rpc-2-singapore.joystream.org');

    // Create the API and wait until ready
    const api = await ApiPromise.create({ provider, types })

    // get all extrinsic and event types in a range of blocks (only works for last 200 blocks unless you are querying an archival node)
    // will take a loooong time if you check too many blocks :)
    const firstBlock = 800000
    const lastBlock = 801000
    const eventTypes:string[] = []
    const extrinsicTypes: string[] = []
    for (let blockHeight=firstBlock; blockHeight<lastBlock; blockHeight++) {
      const blockHash = await api.rpc.chain.getBlockHash(blockHeight)
      const events = await api.query.system.events.at(blockHash) as Vec<EventRecord>;
      const getBlock = await api.rpc.chain.getBlock(blockHash) as SignedBlock
      const extrinsics = getBlock.block.extrinsics as Vec<Extrinsic>
      for (let { event } of events) {
        const section = event.section
        const method = event.method
        const eventType = section+`:`+method
        if (!eventTypes.includes(eventType)) {
          eventTypes.push(eventType)
        }
      }
      for (let i=0; i<extrinsics.length; i++) {
        const section = extrinsics[i].method.section
        const method = extrinsics[i].method.method
        const extrinsicType = section+`:`+method
        if (!extrinsicTypes.includes(extrinsicType)) {
          extrinsicTypes.push(extrinsicType)
        }
      }
    }
    console.log("number of unique event types in range:",eventTypes.length)
    console.log("list of the unique event types in range:")
    console.log(JSON.stringify(eventTypes, null, 4))

    console.log("")

    console.log("number of unique extrinsic types in range",extrinsicTypes.length)
    console.log("list of the unique extrinsic types in range:")
    console.log(JSON.stringify(extrinsicTypes, null, 4))
    
    api.disconnect()
}
Example #29
Source File: KeyValueArray.tsx    From subscan-multisig-react with Apache License 2.0 4 votes vote down vote up
function KeyValueArray({
  className = '',
  defaultValue,
  isDisabled,
  isError,
  label,
  onChange,
  onEnter,
  onEscape,
  withLabel,
}: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const [placeholder, setPlaceholder] = useState<string>(t(EMPTY_PLACEHOLDER));

  const _onChange = useCallback(
    (raw: Uint8Array): void => {
      let encoded: Parsed = { isValid: false, value: [] };

      try {
        encoded = parseFile(raw);

        setPlaceholder(
          t('{{count}} key/value pairs encoded for submission', {
            replace: {
              count: encoded.value.length,
            },
          })
        );
      } catch (error) {
        console.error('Error converting json k/v', error);

        setPlaceholder(t(EMPTY_PLACEHOLDER));
      }

      // eslint-disable-next-line
      onChange && onChange(encoded);
    },
    [onChange, t]
  );

  if (isDisabled) {
    const pairs = defaultValue.value as Vec<Pair>;

    return (
      <>
        <Base className={className} label={label}>
          <div />
        </Base>
        <div className="ui--Params">
          {pairs.map(([key, value]): React.ReactNode => {
            const keyHex = u8aToHex(key.toU8a(true));

            return (
              <Bytes
                defaultValue={{ value } as unknown as RawParam}
                isDisabled
                key={keyHex}
                label={keyHex}
                name={keyHex}
                onEnter={onEnter}
                onEscape={onEscape}
                type={BYTES_TYPE}
              />
            );
          })}
        </div>
      </>
    );
  }

  return (
    <File
      className={className}
      isDisabled={isDisabled}
      isError={isError}
      label={label}
      onChange={_onChange}
      placeholder={placeholder}
      withLabel={withLabel}
    />
  );
}