utils.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { IExtrinsic } from '@polkadot/types/types'
  2. import { compactToU8a, stringToU8a } from '@polkadot/util'
  3. import { blake2AsHex } from '@polkadot/util-crypto'
  4. import BN from 'bn.js'
  5. import fs from 'fs'
  6. import Keyring, { decodeAddress } from '@polkadot/keyring'
  7. import { Seat } from '@alexandria/types/council'
  8. import { KeyringPair } from '@polkadot/keyring/types'
  9. import { v4 as uuid } from 'uuid'
  10. export class Utils {
  11. private static LENGTH_ADDRESS = 32 + 1 // publicKey + prefix
  12. private static LENGTH_ERA = 2 // assuming mortals
  13. private static LENGTH_SIGNATURE = 64 // assuming ed25519 or sr25519
  14. private static LENGTH_VERSION = 1 // 0x80 & version
  15. public static calcTxLength = (extrinsic?: IExtrinsic | null, nonce?: BN): BN => {
  16. return new BN(
  17. Utils.LENGTH_VERSION +
  18. Utils.LENGTH_ADDRESS +
  19. Utils.LENGTH_SIGNATURE +
  20. Utils.LENGTH_ERA +
  21. compactToU8a(nonce || 0).length +
  22. (extrinsic ? extrinsic.encodedLength : 0)
  23. )
  24. }
  25. /** hash(accountId + salt) */
  26. public static hashVote(accountId: string, salt: string): string {
  27. const accountU8a = decodeAddress(accountId)
  28. const saltU8a = stringToU8a(salt)
  29. const voteU8a = new Uint8Array(accountU8a.length + saltU8a.length)
  30. voteU8a.set(accountU8a)
  31. voteU8a.set(saltU8a, accountU8a.length)
  32. const hash = blake2AsHex(voteU8a, 256)
  33. return hash
  34. }
  35. public static wait(ms: number): Promise<void> {
  36. return new Promise((resolve) => setTimeout(resolve, ms))
  37. }
  38. public static getTotalStake(seat: Seat): BN {
  39. return new BN(+seat.stake.toString() + seat.backers.reduce((a, baker) => a + +baker.stake.toString(), 0))
  40. }
  41. public static readRuntimeFromFile(path: string): string {
  42. return '0x' + fs.readFileSync(path).toString('hex')
  43. }
  44. public static camelToSnakeCase(key: string): string {
  45. return key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)
  46. }
  47. public static createKeyPairs(keyring: Keyring, n: number): KeyringPair[] {
  48. const nKeyPairs: KeyringPair[] = []
  49. for (let i = 0; i < n; i++) {
  50. nKeyPairs.push(keyring.addFromUri(i + uuid().substring(0, 8)))
  51. }
  52. return nKeyPairs
  53. }
  54. }