common.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { SubstrateEvent } from '@dzlzv/hydra-common'
  2. import { Network } from 'query-node/dist/src/modules/enums/enums'
  3. import { Event } from 'query-node/dist/src/modules/event/event.model'
  4. import { Bytes } from '@polkadot/types'
  5. export const CURRENT_NETWORK = Network.OLYMPIA
  6. export function genericEventFields(substrateEvent: SubstrateEvent): Partial<Event> {
  7. const { blockNumber, indexInBlock, extrinsic, blockTimestamp } = substrateEvent
  8. const eventTime = new Date(blockTimestamp)
  9. return {
  10. createdAt: eventTime,
  11. updatedAt: eventTime,
  12. id: `${CURRENT_NETWORK}-${blockNumber}-${indexInBlock}`,
  13. inBlock: blockNumber,
  14. network: CURRENT_NETWORK,
  15. inExtrinsic: extrinsic?.hash,
  16. indexInBlock,
  17. }
  18. }
  19. type AnyMessage<T> = T & {
  20. toJSON(): Record<string, unknown>
  21. }
  22. type AnyMetadataClass<T> = {
  23. name: string
  24. decode(binary: Uint8Array): AnyMessage<T>
  25. encode(obj: T): { finish(): Uint8Array }
  26. toObject(obj: AnyMessage<T>): Record<string, unknown>
  27. }
  28. export function deserializeMetadata<T>(metadataType: AnyMetadataClass<T>, metadataBytes: Bytes): T | null {
  29. try {
  30. // We use `toObject()` to get rid of .prototype defaults for optional fields
  31. return metadataType.toObject(metadataType.decode(metadataBytes.toU8a(true))) as T
  32. } catch (e) {
  33. console.error(`Cannot deserialize ${metadataType.name}! Provided bytes: (${metadataBytes.toHex()})`)
  34. return null
  35. }
  36. }
  37. export function bytesToString(b: Bytes): string {
  38. return (
  39. Buffer.from(b.toU8a(true))
  40. .toString()
  41. // eslint-disable-next-line no-control-regex
  42. .replace(/\u0000/g, '')
  43. )
  44. }
  45. export function hasValuesForProperties<
  46. T extends Record<string, unknown>,
  47. P extends keyof T & string,
  48. PA extends readonly P[]
  49. >(obj: T, props: PA): obj is T & { [K in PA[number]]: NonNullable<K> } {
  50. props.forEach((p) => {
  51. if (obj[p] === null || obj[p] === undefined) {
  52. return false
  53. }
  54. })
  55. return true
  56. }