@polkadot/types/interfaces#Hash TypeScript Examples

The following examples show how to use @polkadot/types/interfaces#Hash. 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: 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 #2
Source File: store.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/require-await
  public async saveCode (codeHash: string | Hash, partial: Partial<CodeJson>): Promise<void> {
    const hex = (typeof codeHash === 'string' ? api.registry.createType('Hash', codeHash) : codeHash).toHex();
    const existing = this.getCode(hex);
    const json = {
      ...(existing ? existing.json : {}),
      ...partial,
      codeHash: hex,
      genesisHash: api.genesisHash.toHex(),
      whenCreated: existing?.json.whenCreated || Date.now()
    };
    const key = `${KEY_CODE}${json.codeHash}`;

    store.set(key, json);
    this.addCode(key, json as CodeJson);
  }
Example #3
Source File: Transaction.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
public async signAndSend(
    account: AddressOrPair,
    optionsOrCallback?: Partial<SignerOptions> | TransactionStatusCb,
    optionalCallback?: TransactionStatusCb,
  ): Promise<Hash | (() => void)> {
    const [options, callback] = isFunction(optionsOrCallback)
      ? [undefined, optionsOrCallback]
      : [optionsOrCallback, optionalCallback];

    try {
      return await this.submitted.signAndSend(account, options, callback);
    } catch (error) {
      const errorCode = +error.message.split(':')[0];
      if (errorCode === 1010) {
        throw new TransactionError('Account balance too low');
      } else {
        throw new TransactionError(error.message);
      }
    }
  }
Example #4
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 #5
Source File: historic.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default async function getHistoric<T extends Codec, I extends any[] = any[]>(
  atQuery: AtQuery<I>,
  params: I,
  hashes: Hash[]
): Promise<[Hash, T][]> {
  return Promise.all(hashes.map((hash): Promise<T> => atQuery(hash, ...params) as Promise<T>)).then(
    (results): [Hash, T][] => results.map((value, index): [Hash, T] => [hashes[index], value])
  );
}
Example #6
Source File: BlockProducer.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
/**
     * This sub-routine does the actual fetching and block processing.
     * It can throw errors which should be handled by the top-level code
     */
    private async _doBlockProduce(targetHash: Hash): Promise<BlockData> {
        debug(`\tHash ${targetHash.toString()}.`)

        const blockData = await this.substrateService.getBlockData(targetHash)
        if (getConfig().VERBOSE) {
            debug(`Received block data: ${JSON.stringify(blockData, null, 2)}`)
        }
        debug(`Produced query event block.`)

        return blockData
    }
Example #7
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 #8
Source File: index.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function TechCommApp ({ basePath, className }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const { api } = useApi();
  const { isMember, members } = useMembers('technicalCommittee');
  const prime = useCall<AccountId | null>(api.query.technicalCommittee.prime, undefined, transformPrime) || null;
  const proposals = useCall<Hash[]>(api.query.technicalCommittee.proposals);

  const items = useMemo(() => [
    {
      isRoot: true,
      name: 'overview',
      text: t<string>('Overview')
    },
    {
      name: 'proposals',
      text: t<string>('Proposals ({{count}})', { replace: { count: (proposals && proposals.length) || 0 } })
    }
  ], [proposals, t]);

  return (
    <main className={className}>
      <Tabs
        basePath={basePath}
        items={items}
      />
      <Switch>
        <Route path={`${basePath}/proposals`}>
          <Proposals
            isMember={isMember}
            members={members}
            prime={prime}
            proposals={proposals}
          />
        </Route>
        <Route path={basePath}>
          <Overview
            isMember={isMember}
            members={members}
            prime={prime}
            proposals={proposals}
          />
        </Route>
      </Switch>
    </main>
  );
}
Example #9
Source File: Transaction.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
signAndSend(account: AddressOrPair, options?: Partial<SignerOptions>): Promise<Hash>;
Example #10
Source File: democracy_proposals.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public async createTx(author: SubstrateAccount, action: Call, proposalHash: Hash, deposit: SubstrateCoin) {
    const txFunc = (api: ApiPromise) => api.tx.democracy.propose(proposalHash, deposit.asBN);
    const title = this._Chain.methodToTitle(action);
    return this._Chain.createTXModalData(author, txFunc, 'createDemocracyProposal', title);
  }