@polkadot/types/interfaces#EventRecord TypeScript Examples

The following examples show how to use @polkadot/types/interfaces#EventRecord. 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: useEventTrigger.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export function useEventTrigger (checks: EventCheck[]): string {
  const { api } = useApi();
  const [trigger, setTrigger] = useState('0x00');
  const mountedRef = useIsMountedRef();
  const eventRecords = useCall<Vec<EventRecord>>(api.query.system.events);

  useEffect((): void => {
    mountedRef.current && eventRecords && eventRecords.filter(({ event }) =>
      event && checks.some((check) => check && (
        isString(check)
          ? event.section === check
          : check.is(event)
      ))
    ).length && setTrigger(() => eventRecords.createdAtHash?.toHex() || '0x00');
  }, [eventRecords, checks, mountedRef]);

  return trigger;
}
Example #2
Source File: embeds.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
getOpeningAddedEmbed = (opening: any, openingObject: OpeningOf, blockNumber: number, event: EventRecord): Discord.MessageEmbed => {

    return addCommonProperties(new Discord.MessageEmbed()
        .setTitle(`⛩ ${opening.headline} ⛩`)
        .setDescription(opening.job.description)
        .addFields(
            { name: 'ID', value: openingObject.hiring_opening_id + "", inline: true },
            { name: 'Reward', value: opening.reward, inline: true },
            { name: 'Application Stake', value: openingObject.policy_commitment.application_staking_policy.unwrap().amount.toString() || 'Not Set', inline: true },
            { name: 'Role Stake', value: openingObject.policy_commitment.role_staking_policy.unwrap().amount.toString() || 'Not Set', inline: true },
            { name: 'Created By', value: opening.creator.membership.handle, inline: true },
        ), blockNumber, event );
}
Example #3
Source File: substrate-rpc.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
// Log relay/parachain new blocks and events
export async function logEvents(api: ApiPromise, name: string) {
  api.derive.chain.subscribeNewHeads(async (header) => {
    debug(
      `------------- ${name} BLOCK#${header.number}: author ${header.author}, hash ${header.hash}`
    );
    const allRecords: EventRecord[] = (await (
      await api.at(header.hash)
    ).query.system.events()) as any;

    allRecords.forEach((e, i) => {
      debug(
        `${name} Event :`,
        i,
        header.hash.toHex(),
        (e.toHuman() as any).event.section,
        (e.toHuman() as any).event.method
      );
    });
  });
}
Example #4
Source File: Status.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function Status ({ optionsAll }: Props): React.ReactElement<Props> {
  const { queueAction } = useContext(StatusContext);
  const { api, isApiReady } = useApi();
  const { allAccounts } = useAccounts();
  const { t } = useTranslation();
  const events = useCall<EventRecord[]>(isApiReady && api.query.system?.events);

  useEffect((): void => {
    const filtered = filterEvents(allAccounts, t, optionsAll, events);

    filtered && queueAction(filtered);
  }, [allAccounts, events, optionsAll, queueAction, t]);

  return (
    <StatusDisplay />
  );
}
Example #5
Source File: embeds.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
getWorkerExitedOrTerminatedEmbed = (action: string, member: Membership, reason: string,
    blockNumber: number, event: EventRecord): Discord.MessageEmbed => {

    return addCommonProperties(new Discord.MessageEmbed()
        .setTitle(`? Worker ${member.handle} has ${action}`)
        .addFields(
            { name: 'Reason', value: reason, inline: true },
        ), blockNumber, event );
}
Example #6
Source File: execute.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export async function execute (extrinsic: SubmittableExtrinsic<'promise'>, singer: KeyringPair, logger = { info: console.log }): Promise<void> {
  let currentTxDone = false;

  function sendStatusCb ({ events = [], status }: { events?: EventRecord[], status: ExtrinsicStatus; }) {
    if (status.isInvalid) {
      logger.info('Transaction invalid');
      currentTxDone = true;
    } else if (status.isReady) {
      logger.info('Transaction is ready');
    } else if (status.isBroadcast) {
      logger.info('Transaction has been broadcasted');
    } else if (status.isInBlock) {
      logger.info('Transaction is in block');
    } else if (status.isFinalized) {
      logger.info(`Transaction has been included in blockHash ${status.asFinalized.toHex()}`);
      events.forEach(
        ({ event }) => {
          if (event.method === 'ExtrinsicSuccess') {
            logger.info('Transaction succeeded');
          } else if (event.method === 'ExtrinsicFailed') {
            logger.info('Transaction failed');
          }
        }
      );
      currentTxDone = true;
    }
  }

  await extrinsic.signAndSend(singer, sendStatusCb);
  await waitFor(() => currentTxDone, { timeout: 20000 });
}
Example #7
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 #8
Source File: issueRedeem.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
/**
 * @param events The EventRecord array returned after sending a transaction
 * @param methodToCheck The name of the event method whose existence to check
 * @returns The id associated with the transaction. If the EventRecord array does not
 * contain required events, the function throws an error.
 */
export function getRequestIdsFromEvents(
    events: EventRecord[],
    eventToFind: AugmentedEvent<ApiTypes, AnyTuple>,
    api: ApiPromise
): Hash[] {
    const ids = new Array<Hash>();
    for (const { event } of events) {
        if (eventToFind.is(event)) {
            // the redeem id has type H256 and is the first item of the event data array
            const id = api.createType("Hash", event.data[0]);
            ids.push(id);
        }
    }

    if (ids.length > 0) return ids;
    throw new Error("Transaction failed");
}
Example #9
Source File: Status.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function Status({ optionsAll }: Props): React.ReactElement<Props> {
  const { queueAction } = useContext(StatusContext);
  const { api, isApiReady } = useApi();
  const { allAccounts } = useAccounts();
  const { t } = useTranslation();
  const events = useCall<EventRecord[]>(isApiReady && api.query.system?.events);

  useEffect((): void => {
    const filtered = filterEvents(allAccounts, t, optionsAll, events);

    if (filtered) {
      queueAction(filtered);
    }
  }, [allAccounts, events, optionsAll, queueAction, t]);

  return <StatusDisplay />;
}
Example #10
Source File: QueryEvent.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
constructor(
    eventRecord: EventRecord,
    blockNumber: number,
    indexInBlock: number,
    blockTimestamp: number,
    extrinsic?: Extrinsic
  ) {
    this.eventRecord = eventRecord
    this.extrinsic = extrinsic
    this.blockNumber = blockNumber
    this.indexInBlock = indexInBlock
    this.blockTimestamp = blockTimestamp
  }
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: 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 #13
Source File: functions.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
export async function getChangeAction(api: ApiPromise, method: string, blockHeight:number, blockHash:Hash, eventIndex: number, event: EventRecord): Promise<ActionData|null> {
  const getBlock = await api.rpc.chain.getBlock(blockHash) as SignedBlock
  const extrinsics = getBlock.block.extrinsics as Vec<Extrinsic>
  for (let n=0; n<extrinsics.length; n++) {
    const extSection = extrinsics[n].method.section
    const extMethod = extrinsics[n].method.method
    let extrinscIndex = 0
    console.log(`Extrinsics section=${extSection}, Event method=${extMethod}`)
    if (extSection == "content" && extMethod == method) {
      extrinscIndex +=1
      if (eventIndex == extrinscIndex) {
        const extrinsic = extrinsics[n]
        const actor = extrinsic.args[0] as Actor
        const ent = event.event.data[1]
        let entityId:number = +(ent.toString())
        const video:ActionData = {
          blockHeight,
          action: method,
          entityId,
          signer: extrinsic.signer.toString(),
          actor: actor.toHuman()
        }
        return video
      }
    }
  }
  return null
}
Example #14
Source File: QueryEvent.ts    From squid with GNU General Public License v3.0 5 votes vote down vote up
readonly eventRecord: EventRecord
Example #15
Source File: embeds.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
getMintCapacityChangedEmbed = (minted: number, mint: u128, blockNumber: number, event: EventRecord): Discord.MessageEmbed => {

    return addCommonProperties(new Discord.MessageEmbed()
        .setTitle(`? ? ? ? ? ${formatBalance(minted, { withUnit: 'JOY' })} minted to the Treasury ? ? ? ? ? `)
        .addFields(
            { name: 'Balance', value: formatBalance(mint, { withUnit: 'JOY' }), inline: true },
        ), blockNumber, event );
}
Example #16
Source File: SubstrateEventEntity.ts    From squid with GNU General Public License v3.0 5 votes vote down vote up
static fromQueryEvent(q: {
    blockNumber: number
    blockTimestamp: number
    indexInBlock: number
    eventRecord: EventRecord
    extrinsicEntity?: SubstrateExtrinsicEntity
    blockEntity: SubstrateBlockEntity
  }): SubstrateEventEntity {
    const _entity = new SubstrateEventEntity()

    const { hash } = q.blockEntity

    _entity.blockNumber = q.blockNumber
    _entity.blockHash = q.blockEntity.hash
    _entity.blockTimestamp = q.blockTimestamp
    _entity.indexInBlock = q.indexInBlock
    _entity.id = formatId({
      height: _entity.blockNumber,
      index: _entity.indexInBlock,
      hash,
    })
    _entity.block = q.blockEntity

    _entity.method = q.eventRecord.event.method || 'NO_METHOD'
    _entity.section = q.eventRecord.event.section || 'NO_SECTION'
    _entity.name = `${_entity.section}.${_entity.method}`
    _entity.phase = q.eventRecord.phase.toJSON() || {}

    _entity.params = []
    _entity.data = {}

    const { event } = q.eventRecord

    if (event.data.length) {
      q.eventRecord.event.data.forEach((data, index) => {
        const type = event.typeDef[index].type
        const name = `param${index}`
        const value = data ? data.toJSON() : {}

        ;(_entity.data as any)[name] = { type, value }
        _entity.params.push({
          type,
          name,
          value,
        } as EventParam)
      })
    }

    const extrinsicArgs: any = {}

    if (q.extrinsicEntity) {
      _entity.extrinsic = q.extrinsicEntity
      _entity.extrinsic.args.forEach(({ name, value, type }: ExtrinsicArg) => {
        extrinsicArgs[name] = { type, value }
      })
      _entity.extrinsicName = _entity.extrinsic.name
      _entity.extrinsicHash = _entity.extrinsic.hash
      _entity.extrinsicIndex = _entity.extrinsic.indexInBlock
    }

    _entity.extrinsicArgs = extrinsicArgs

    return _entity
  }
Example #17
Source File: tokenomics.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
async buildBlocksEventCache(
    startBlock: number,
    endBlock: number,
    cacheDir: string
  ): Promise<void> {
    const cacheFile = `${cacheDir}/${startBlock}-${endBlock}.json`;
    const exists = await fs
      .access(cacheFile, fsSync.constants.R_OK)
      .then(() => true)
      .catch(() => false);
    if (!exists) {
      console.log("Building events cache...");
      let blocksEvents = new Map<number, CacheEvent[]>();
      for (let i = startBlock; i < endBlock; ++i) {
        process.stdout.write("\rCaching block: " + i + " until " + endBlock);
        const blockHash: Hash = await getBlockHash(this.api, i);
        let eventRecord: EventRecord[] = [];
        try {
          eventRecord = await getEvents(this.api, blockHash);
        } catch (e) {
          console.warn(`Failed to get events.`, e);
        }
        let cacheEvents = new Array<CacheEvent>();
        for (let { event } of eventRecord) {
          if (!event) {
            console.warn(`empty event record`);
            continue;
          }
          cacheEvents.push(
            new CacheEvent(event.section, event.method, event.data)
          );
        }
        blocksEvents.set(i, cacheEvents);
      }

      console.log("\nFinish events cache...");
      const json = JSON.stringify(Array.from(blocksEvents.entries()), null, 2);
      fsSync.writeFileSync(cacheFile, json);
      this.blocksEventsCache = new Map(JSON.parse(json));
    } else {
      console.log("Cache file found, loading it...");
      let fileData = await fs.readFile(cacheFile);
      this.blocksEventsCache = new Map(JSON.parse(fileData));
    }
  }
Example #18
Source File: Events.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
async function manageEvents(
  api: ApiPromise,
  prev: PrevHashes,
  records: Vec<EventRecord>,
  setState: React.Dispatch<React.SetStateAction<Events>>
): Promise<void> {
  const newEvents: IndexedEvent[] = records
    .map((record, index) => ({ indexes: [index], record }))
    .filter(
      ({
        record: {
          event: { method, section },
        },
      }) =>
        section !== 'system' &&
        (!['balances', 'treasury'].includes(section) || !['Deposit'].includes(method)) &&
        (!['parasInclusion', 'inclusion'].includes(section) ||
          !['CandidateBacked', 'CandidateIncluded'].includes(method))
    )
    .reduce((combined: IndexedEvent[], e): IndexedEvent[] => {
      const prev = combined.find(
        ({
          record: {
            event: { method, section },
          },
        }) => e.record.event.section === section && e.record.event.method === method
      );

      if (prev) {
        prev.indexes.push(...e.indexes);
      } else {
        combined.push(e);
      }

      return combined;
    }, [])
    .reverse();
  const newEventHash = xxhashAsHex(stringToU8a(stringify(newEvents)));

  if (newEventHash !== prev.event && newEvents.length) {
    prev.event = newEventHash;

    // retrieve the last header, this will map to the current state
    const header = await api.rpc.chain.getHeader(records.createdAtHash);
    const blockNumber = header.number.unwrap();
    const blockHash = header.hash.toHex();

    if (blockHash !== prev.block) {
      prev.block = blockHash;

      setState(({ events }) => ({
        eventCount: records.length,
        events: [
          ...newEvents.map(
            ({ indexes, record }): KeyedEvent => ({
              blockHash,
              blockNumber,
              indexes,
              key: `${blockNumber.toNumber()}-${blockHash}-${indexes.join('.')}`,
              record,
            })
          ),
          // remove all events for the previous same-height blockNumber
          ...events.filter((p) => !p.blockNumber?.eq(blockNumber)),
        ].slice(0, MAX_EVENTS),
      }));
    }
  } else {
    setState(({ events }) => ({
      eventCount: records.length,
      events,
    }));
  }
}
Example #19
Source File: embeds.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
getOpeningFilledEmbed = (opening: any, member: Membership, blockNumber: number, event: EventRecord): Discord.MessageEmbed => {

    return addCommonProperties(new Discord.MessageEmbed().setTitle(`? ? ?? ${member.handle} was hired as ${opening.job.title} ? ? ??`), blockNumber, event );
}
Example #20
Source File: transactionReceiptHelper.ts    From bodhi.js with Apache License 2.0 5 votes vote down vote up
getTransactionIndexAndHash = (
  hashOrNumber: string | number,
  extrinsics: GenericExtrinsic[],
  events: EventRecord[]
): {
  transactionIndex: number;
  transactionHash: string;
  isExtrinsicFailed: boolean;
  extrinsicIndex: number;
} => {
  const evmExtrinsicIndexes = getEvmExtrinsicIndexes(events);
  const extrinsicsHashes = extrinsics.map((extrinsic) => extrinsic.hash.toHex());

  let extrinsicIndex: number | undefined = undefined;

  if (isHexString(hashOrNumber, 32)) {
    extrinsicIndex = extrinsicsHashes.findIndex((hash) => hashOrNumber === hash);
  } else {
    const index = BigNumber.from(hashOrNumber).toNumber();
    extrinsicIndex = evmExtrinsicIndexes[index];
  }

  const transactionHash = extrinsicIndex ? extrinsics[extrinsicIndex]?.hash.toHex() : undefined;

  if (extrinsicIndex === undefined || transactionHash === undefined || extrinsicIndex < 0) {
    return logger.throwError(`transaction hash not found`, Logger.errors.UNKNOWN_ERROR, {
      hashOrNumber
    });
  }

  const transactionIndex = evmExtrinsicIndexes.findIndex((index) => index === extrinsicIndex);

  if (transactionIndex < 0) {
    return logger.throwError(`expected extrinsic include evm events`, Logger.errors.UNKNOWN_ERROR, {
      hashOrNumber
    });
  }

  const isExtrinsicFailed = events[events.length - 1].event.method === 'ExtrinsicFailed';

  return {
    transactionIndex,
    transactionHash,
    extrinsicIndex,
    isExtrinsicFailed
  };
}
Example #21
Source File: Status.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function filterEvents(
  allAccounts: string[],
  t: <T = string>(key: string, opts?: Record<string, unknown>) => T,
  optionsAll?: KeyringOptions,
  events?: EventRecord[]
): ActionStatus[] | null {
  const eventHash = xxhashAsHex(stringToU8a(JSON.stringify(events)));

  if (!optionsAll || !events || eventHash === prevEventHash) {
    return null;
  }

  prevEventHash = eventHash;

  return events
    .map(({ event: { data, method, section } }): ActionStatus | null => {
      if (section === 'balances' && method === 'Transfer') {
        const account = data[1].toString();

        if (allAccounts.includes(account)) {
          return {
            account,
            action: `${section}.${method}`,
            message: t<string>('transfer received'),
            status: 'event',
          };
        }
      } else if (section === 'democracy') {
        const index = data[0].toString();

        return {
          action: `${section}.${method}`,
          message: t<string>('update on #{{index}}', {
            replace: {
              index,
            },
          }),
          status: 'event',
        };
      }

      return null;
    })
    .filter((item): item is ActionStatus => !!item);
}
Example #22
Source File: tokenomics.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
async fillCouncilElectionInfo(startBlock: number): Promise<void> {
    let startBlockHash = await getBlockHash(this.api, startBlock);
    let events: Vec<EventRecord> = await getEvents(this.api, startBlockHash);
    let isStartBlockFirstCouncilBlock = events.some(
      ({ event }) =>
        event.section == "councilElection" && event.method == "CouncilElected"
    );

    if (!isStartBlockFirstCouncilBlock)
      return console.warn(
        "Note: The given start block is not the first block of the council round so council election information will be empty"
      );

    let lastBlockHash = await getBlockHash(this.api, startBlock - 1);
    let applicants: Vec<AccountId> = await getCouncilApplicants(
      this.api,
      lastBlockHash
    );
    let electionApplicantsStakes = 0;
    for (let applicant of applicants) {
      const applicantStakes: ElectionStake = await getCouncilApplicantStakes(
        this.api,
        lastBlockHash,
        applicant
      );
      electionApplicantsStakes += applicantStakes.new.toNumber();
    }
    // let seats = await getCouncil(this.api,startBlockHash) as Seats;
    //TODO: Find a more accurate way of getting the votes
    const votes: Vec<Hash> = await getCouncilCommitments(
      this.api,
      lastBlockHash
    );

    this.saveStats({
      electionApplicants: applicants.length,
      electionApplicantsStakes,
      electionVotes: votes.length,
    });
  }
Example #23
Source File: redeem.ts    From interbtc-api with Apache License 2.0 5 votes vote down vote up
private getRedeemIdsFromEvents(events: EventRecord[], event: AugmentedEvent<ApiTypes, AnyTuple>): Hash[] {
        return getRequestIdsFromEvents(events, event, this.api);
    }
Example #24
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 #25
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 #26
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 #27
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 #28
Source File: Status.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function filterEvents (allAccounts: string[], t: <T = string> (key: string, opts?: Record<string, unknown>) => T, optionsAll?: KeyringOptions, events?: EventRecord[]): ActionStatus[] | null {
  const eventHash = xxhashAsHex(stringToU8a(JSON.stringify(events)));

  if (!optionsAll || !events || eventHash === prevEventHash) {
    return null;
  }

  prevEventHash = eventHash;

  return events
    .map(({ event: { data, method, section } }): ActionStatus | null => {
      if (section === 'balances' && method === 'Transfer') {
        const account = data[1].toString();

        if (allAccounts.includes(account)) {
          return {
            account,
            action: `${section}.${method}`,
            message: t<string>('transfer received'),
            status: 'event'
          };
        }
      } else if (section === 'democracy') {
        const index = data[0].toString();

        return {
          action: `${section}.${method}`,
          message: t<string>('update on #{{index}}', {
            replace: {
              index
            }
          }),
          status: 'event'
        };
      }

      return null;
    })
    .filter((item): item is ActionStatus => !!item);
}
Example #29
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;
      }
    }
  }
}