stringifyAttestationBytes.ts 923 Bytes
Newer Older
Will Cory's avatar
Will Cory committed
1 2
import { Address } from '@wagmi/core'
import { BigNumber } from 'ethers'
Will Cory's avatar
Will Cory committed
3 4 5 6 7 8
import {
  hexlify,
  isAddress,
  isHexString,
  toUtf8Bytes,
} from 'ethers/lib/utils.js'
Will Cory's avatar
Will Cory committed
9 10 11 12

import { WagmiBytes } from '../types/WagmiBytes'

export const stringifyAttestationBytes = (
13
  bytes: WagmiBytes | string | Address | number | boolean | BigNumber
14
): WagmiBytes => {
Will Cory's avatar
Will Cory committed
15
  bytes = bytes === '0x' ? '0x0' : bytes
16
  if (BigNumber.isBigNumber(bytes)) {
17
    return bytes.toHexString() as WagmiBytes
18
  }
Will Cory's avatar
Will Cory committed
19
  if (typeof bytes === 'number') {
20
    return BigNumber.from(bytes).toHexString() as WagmiBytes
Will Cory's avatar
Will Cory committed
21 22 23 24 25 26 27 28
  }
  if (typeof bytes === 'boolean') {
    return bytes ? '0x1' : '0x0'
  }
  if (isAddress(bytes)) {
    return bytes
  }
  if (isHexString(bytes)) {
29
    return bytes as WagmiBytes
Will Cory's avatar
Will Cory committed
30 31
  }
  if (typeof bytes === 'string') {
Will Cory's avatar
Will Cory committed
32
    return hexlify(toUtf8Bytes(bytes)) as WagmiBytes
Will Cory's avatar
Will Cory committed
33 34 35
  }
  throw new Error(`unrecognized bytes type ${bytes satisfies never}`)
}