@polkadot/types/interfaces#Event TypeScript Examples

The following examples show how to use @polkadot/types/interfaces#Event. 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: subscriber.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
private _handleJudgementEvents = async (event: Event): Promise<void> => {

      if (isJudgementRequestedEvent(event)) {
        await this._judgementRequestedHandler(event)
      }

      if (isJudgementGivenEvent(event)) {
        await this._judgementGivendHandler(event)
      }

      if (isJudgementUnrequested(event)) {
        await this._judgementUnrequestedHandler(event)
      }

    }
Example #2
Source File: utils.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
isIdentitySetEvent = (event: Event): boolean => {
  return event.section == 'identity' && event.method == 'IdentitySet'
}
Example #3
Source File: utils.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
isIdentityClearedEvent = (event: Event): boolean => {
  return event.section == 'identity' && (
    event.method == 'IdentityCleared' || event.method == 'IdentityKilled' );
}
Example #4
Source File: utils.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
isJudgementGivenEvent = (event: Event): boolean => {
  return event.section == 'identity' && event.method == 'JudgementGiven';
}
Example #5
Source File: utils.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
isJudgementRequestedEvent = (event: Event): boolean => {
  return event.section == 'identity' && event.method == 'JudgementRequested';
}
Example #6
Source File: utils.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
isJudgementUnrequested = (event: Event): boolean => {
  return event.section == 'identity' && event.method == 'JudgementUnrequested';
}
Example #7
Source File: subscriber.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
private _judgementRequestedHandler = async (event: Event): Promise<void> => {
      this.logger.info('New JudgementRequested')
      const request = extractJudgementInfoFromEvent(event)
      this.logger.info('AccountId:'+request.accountId+'\tRegistrarIndex:'+request.registrarIndex)
      if(request.registrarIndex == this.registrarIndex) {
        this.logger.info(`event to be handled by registrar with index ${this.registrarIndex}`)
        this._performNewChallengeAttempt(request.accountId)       
      }
    }
Example #8
Source File: subscriber.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
private _judgementGivendHandler = async (event: Event): Promise<void> => {
      this.logger.info('New JudgementGiven')
      const request = extractJudgementInfoFromEvent(event)
      this.logger.info('AccountId:'+request.accountId+'\tRegistrarIndex:'+request.registrarIndex)
      // TODO should we do something particular if the judgement is provided by another requestor?
      if(request.registrarIndex == this.registrarIndex) {
        this.logger.info(`sending ack to challenger`)
        this.wsJudgementGievenHandler(buildJudgementGivenAck(request.accountId))
      }
    }
Example #9
Source File: subscriber.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
private _judgementUnrequestedHandler = async (event: Event): Promise<void> => {
      this.logger.info('New JudgementUnrequested')
      const request = extractJudgementInfoFromEvent(event)
      this.logger.info('AccountId:'+request.accountId+'\tRegistrarIndex:'+request.registrarIndex)
      if(request.registrarIndex == this.registrarIndex) {
 
        try {
          this.wsJudgementUnrequestedHandler(buildWsChallengeUnrequest(request.accountId))
        } catch (error) {
          this.logger.error(`problem on notifying the challenger about a ${request.accountId} JudgementUnrequested`)
          this.logger.error(error)
        }

      }
    }
Example #10
Source File: substrate-rpc.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
createBlockWithExtrinsicParachain = async <
  Call extends SubmittableExtrinsic<ApiType>,
  ApiType extends ApiTypes
>(
  api: ApiPromise,
  sender: AddressOrPair,
  polkadotCall: Call
): Promise<{ extrinsic: GenericExtrinsic<AnyTuple>; events: Event[] }> => {
  console.log("-------------- EXTRINSIC CALL -------------------------------");
  // This should return a Uint8Array
  const extrinsicHash = (await polkadotCall.signAndSend(sender)) as unknown as Uint8Array;

  // We create the block which is containing the extrinsic
  //const blockResult = await context.createBlock();
  return await tryLookingForEvents(api, extrinsicHash);
}
Example #11
Source File: subscriber.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
private _identityClearedHandler = async (event: Event): Promise<void> => {
      this.logger.info('Identity Cleared Event Received')
      const accountId = extractIdentityInfoFromEvent(event)
      this.logger.info(`AccountId: ${accountId}`)

      try {
        this.wsJudgementUnrequestedHandler(buildWsChallengeUnrequest(accountId))
      } catch (error) {
        this.logger.error(`problem on notifying the challenger about the account ${accountId} JudgementUnrequested`)
        this.logger.error(error)
      }
      
    }
Example #12
Source File: subscriber.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
private _handleIdentityEvents = async (event: Event): Promise<void> => {

      if (isIdentityClearedEvent(event)) {
        this._identityClearedHandler(event)
      }

      if (isIdentitySetEvent(event)) {
        this._judgementUpdateHandler(event)
      }

    }
Example #13
Source File: substrate-rpc.ts    From polkadot-launch with MIT License 6 votes vote down vote up
createBlockWithExtrinsicParachain = async <
	Call extends SubmittableExtrinsic<ApiType>,
	ApiType extends ApiTypes
>(
	api: ApiPromise,
	sender: AddressOrPair,
	polkadotCall: Call
): Promise<{ extrinsic: GenericExtrinsic<AnyTuple>; events: Event[] }> => {
	console.log("-------------- EXTRINSIC CALL -------------------------------");
	// This should return a Uint8Array
	const extrinsicHash = (await polkadotCall.signAndSend(
		sender
	)) as unknown as Uint8Array;

	// We create the block which is containing the extrinsic
	//const blockResult = await context.createBlock();
	return await tryLookingForEvents(api, extrinsicHash);
}
Example #14
Source File: substrate-rpc.ts    From polkadot-launch with MIT License 6 votes vote down vote up
async function tryLookingForEvents(
	api: ApiPromise,
	extrinsicHash: Uint8Array
): Promise<{ extrinsic: GenericExtrinsic<AnyTuple>; events: Event[] }> {
	await waitOneBlock(api);
	let { extrinsic, events } = await lookForExtrinsicAndEvents(
		api,
		extrinsicHash
	);
	if (events.length > 0) {
		return {
			extrinsic,
			events,
		};
	} else {
		return await tryLookingForEvents(api, extrinsicHash);
	}
}
Example #15
Source File: helpers.ts    From guardian with Apache License 2.0 6 votes vote down vote up
getEventParams = (event: Event): string[] => {
  // try to find fields name if it's struct format
  const params = event.data.meta.fields?.map((x) => x.name.isSome && x.name.unwrap().toString()).filter((x) => !!x);
  if (params?.length) {
    return params as string[];
  }

  // try to find fields name from documentation
  const args = event.meta.docs
    .reverse()
    .map((i) => i.toString())
    .map((doc) => {
      // try regex \[ key1, key2 \]
      let results = /\\\[(.*?)\\\]/gm.exec(doc);
      if (!results) {
        // try different regex [ key1, key2 ]
        results = /\[(.*?)\]/gm.exec(doc);
      }
      return results ? (results.length > 1 ? results[1].split(',').map((x) => x.trim()) : []) : [];
    });

  if (args.length > 0) {
    return args[0];
  }
  return [];
}
Example #16
Source File: utils.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
extractJudgementInfoFromEvent = (event: Event): JudgementRequest =>{
  const accountId = event.data[0].toString()
  const registrarIndex = event.data[1].toString()
  return {accountId,registrarIndex:parseInt(registrarIndex)}
}
Example #17
Source File: utils.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
extractIdentityInfoFromEvent = (event: Event): string =>{
  const accountId = event.data[0].toString()
  return accountId
}
Example #18
Source File: GearApi.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Method provides opportunity to get informations about error occurs in ExtrinsicFailed event
   * @param event
   * @returns
   */
  getExtrinsicFailedError(event: Event): RegistryError {
    const error = event.data[0] as ContractExecResultErr;

    const { isModule, asModule } = error;
    return isModule ? this.registry.findMetaError(asModule) : null;
  }
Example #19
Source File: Parachains.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function includeEntry (map: EventMap, event: Event, blockHash: string, blockNumber: BN): void {
  const { descriptor } = (event as unknown as IEvent<[CandidateReceipt]>).data[0];

  if (descriptor) {
    map[descriptor.paraId.toString()] = {
      blockHash,
      blockNumber,
      relayParent: descriptor.relayParent.toHex()
    };
  }
}
Example #20
Source File: utils.ts    From polkadot-watcher-csv-exporter with Apache License 2.0 6 votes vote down vote up
isNewEraEvent = (event: Event, api: ApiPromise): boolean => {
  return api.events.session.NewSession.is(event)
}
Example #21
Source File: subscriber.ts    From polkadot-registrar-watcher with Apache License 2.0 5 votes vote down vote up
private _judgementUpdateHandler = async (event: Event): Promise<void> => {
      const accountId = extractIdentityInfoFromEvent(event)
      if( await this._hasIdentityAlreadyRequestedOurJudgement(accountId) ) {

        this.logger.info(`New Update Identity Event for ${accountId}`)
        this._performNewChallengeAttempt(accountId)
      }
    }
Example #22
Source File: Event.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
constructor(event: Event) {
    super(event.registry, event.toU8a());
  }
Example #23
Source File: transactions.ts    From moonbeam with GNU General Public License v3.0 5 votes vote down vote up
/// Sign and send Substrate transaction and then create a block.
/// Will provide events emited by the transaction to check if they match what is expected.
export async function substrateTransaction(context, sender, polkadotCall): Promise<Event[]> {
  const { events } = await createBlockWithExtrinsic(context, sender, polkadotCall);
  return events;
}
Example #24
Source File: useCodeUpload.tsx    From gear-js with GNU General Public License v3.0 4 votes vote down vote up
useCodeUpload = () => {
  const { api } = useApi();
  const alert = useAlert();
  const { account } = useAccount();

  const submit = async (file: File) => {
    const arrayBuffer = (await readFileAsync(file)) as ArrayBuffer;
    const buffer = Buffer.from(arrayBuffer);

    return api.code.submit(buffer);
  };

  const getErrorMessage = (event: Event) => {
    const { docs, method: errorMethod } = api.getExtrinsicFailedError(event);
    const formattedDocs = docs.filter(Boolean).join('. ');

    return `${errorMethod}: ${formattedDocs}`;
  };

  const uploadCode = async (file: File) => {
    if (!account) {
      alert.error('Wallet not connected');

      return;
    }

    const { address, meta } = account;

    const alertTitle = 'gear.submitCode';
    const alertId = alert.loading('SignIn', { title: alertTitle });

    try {
      const { signer } = await web3FromSource(meta.source);
      const { codeHash } = await submit(file);

      await api.code.signAndSend(address, { signer }, ({ events, status }) => {
        if (status.isReady) {
          alert.update(alertId, 'Ready');

          return;
        }

        if (status.isInBlock) {
          alert.update(alertId, 'InBlock');

          events.forEach(({ event }) => {
            const { method, section } = event;

            if (method === 'CodeSaved') {
              alert.success(<CopiedInfo title="Code hash" info={codeHash} />, {
                title: `${section}.CodeSaved`,
                timeout: 0,
              });

              return;
            }

            if (method === 'ExtrinsicFailed') {
              alert.error(getErrorMessage(event), { title: `${section}.ExtrinsicFailed` });

              return;
            }
          });

          return;
        }

        if (status.isFinalized) {
          alert.update(alertId, 'Finalized', DEFAULT_SUCCESS_OPTIONS);

          return;
        }

        if (status.isInvalid) {
          alert.update(alertId, PROGRAM_ERRORS.INVALID_TRANSACTION, DEFAULT_ERROR_OPTIONS);
        }
      });
    } catch (error) {
      alert.update(alertId, `${error}`, DEFAULT_ERROR_OPTIONS);
      console.error(error);
    }
  };

  return uploadCode;
}