utils.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { IExtrinsic } from '@polkadot/types/types';
  2. import { compactToU8a, stringToU8a, u8aToHex } from '@polkadot/util';
  3. import { blake2AsHex } from '@polkadot/util-crypto';
  4. import BN from 'bn.js';
  5. import fs from 'fs';
  6. import { decodeAddress } from '@polkadot/keyring';
  7. import { Seat } from '@rome/types';
  8. export class Utils {
  9. private static LENGTH_ADDRESS = 32 + 1; // publicKey + prefix
  10. private static LENGTH_ERA = 2; // assuming mortals
  11. private static LENGTH_SIGNATURE = 64; // assuming ed25519 or sr25519
  12. private static LENGTH_VERSION = 1; // 0x80 & version
  13. public static calcTxLength = (extrinsic?: IExtrinsic | null, nonce?: BN): BN => {
  14. return new BN(
  15. Utils.LENGTH_VERSION +
  16. Utils.LENGTH_ADDRESS +
  17. Utils.LENGTH_SIGNATURE +
  18. Utils.LENGTH_ERA +
  19. compactToU8a(nonce || 0).length +
  20. (extrinsic ? extrinsic.encodedLength : 0)
  21. );
  22. };
  23. /** hash(accountId + salt) */
  24. public static hashVote(accountId: string, salt: string): string {
  25. const accountU8a = decodeAddress(accountId);
  26. const saltU8a = stringToU8a(salt);
  27. const voteU8a = new Uint8Array(accountU8a.length + saltU8a.length);
  28. voteU8a.set(accountU8a);
  29. voteU8a.set(saltU8a, accountU8a.length);
  30. const hash = blake2AsHex(voteU8a, 256);
  31. // console.log('Vote hash:', hash, 'for', { accountId, salt });
  32. return hash;
  33. }
  34. public static wait(ms: number): Promise<void> {
  35. return new Promise(resolve => setTimeout(resolve, ms));
  36. }
  37. public static getTotalStake(seat: Seat): BN {
  38. return new BN(+seat.stake.toString() + seat.backers.reduce((a, baker) => a + +baker.stake.toString(), 0));
  39. }
  40. public static readRuntimeFromFile(path: string): string {
  41. return u8aToHex(fs.readFileSync(path));
  42. }
  43. }