extrinsics.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { Keyring } from '@polkadot/keyring'
  2. import { KeyringPair } from '@polkadot/keyring/types'
  3. import { ApiPromise } from '@polkadot/api'
  4. import { SubmittableExtrinsic } from '@polkadot/api/types'
  5. export function getAlicePair() {
  6. const keyring = new Keyring({ type: 'sr25519' })
  7. keyring.addFromUri('//Alice', { name: 'Alice' })
  8. const ALICE = keyring.getPairs()[0]
  9. return ALICE
  10. }
  11. export class ExtrinsicsHelper {
  12. api: ApiPromise
  13. noncesByAddress: Map<string, number>
  14. constructor(api: ApiPromise, initialNonces?: [string, number][]) {
  15. this.api = api
  16. this.noncesByAddress = new Map<string, number>(initialNonces)
  17. }
  18. private async nextNonce(address: string): Promise<number> {
  19. const nonce = this.noncesByAddress.get(address) || (await this.api.query.system.account(address)).nonce.toNumber()
  20. this.noncesByAddress.set(address, nonce + 1)
  21. return nonce
  22. }
  23. async sendAndCheck(sender: KeyringPair, extrinsics: SubmittableExtrinsic<'promise'>[], errorMessage: string) {
  24. const promises: Promise<void>[] = []
  25. for (const tx of extrinsics) {
  26. const nonce = await this.nextNonce(sender.address)
  27. promises.push(
  28. new Promise((resolve, reject) => {
  29. tx.signAndSend(sender, { nonce }, (result) => {
  30. if (result.isError) {
  31. reject(new Error(errorMessage))
  32. }
  33. if (result.status.isInBlock) {
  34. if (
  35. result.events.some(({ event }) => event.section === 'system' && event.method === 'ExtrinsicSuccess')
  36. ) {
  37. resolve()
  38. } else {
  39. reject(new Error(errorMessage))
  40. }
  41. }
  42. })
  43. })
  44. )
  45. }
  46. await Promise.all(promises)
  47. }
  48. }