createValue.ts 1.39 KB
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

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

12 13 14 15 16 17 18 19 20 21
/**
 * Turns a value into bytes to make an attestation
 *
 * @example
 * createValue('hello world') // '0x68656c6c6f20776f726c64'
 * createValue(123) // '0x7b'
 * createValue(true) // '0x1'
 * createValue(BigNumber.from(10)) // '0xa'
 */
export const createValue = (
22
  bytes: WagmiBytes | string | Address | number | boolean | BigNumber
23
): WagmiBytes => {
Will Cory's avatar
Will Cory committed
24
  bytes = bytes === '0x' ? '0x0' : bytes
25
  if (BigNumber.isBigNumber(bytes)) {
26
    return bytes.toHexString() as WagmiBytes
27
  }
Will Cory's avatar
Will Cory committed
28
  if (typeof bytes === 'number') {
29
    return BigNumber.from(bytes).toHexString() as WagmiBytes
Will Cory's avatar
Will Cory committed
30 31 32 33 34 35 36 37
  }
  if (typeof bytes === 'boolean') {
    return bytes ? '0x1' : '0x0'
  }
  if (isAddress(bytes)) {
    return bytes
  }
  if (isHexString(bytes)) {
38
    return bytes as WagmiBytes
Will Cory's avatar
Will Cory committed
39 40
  }
  if (typeof bytes === 'string') {
Will Cory's avatar
Will Cory committed
41
    return hexlify(toUtf8Bytes(bytes)) as WagmiBytes
Will Cory's avatar
Will Cory committed
42 43 44
  }
  throw new Error(`unrecognized bytes type ${bytes satisfies never}`)
}
45 46 47 48 49 50 51 52 53 54 55

/**
 * @deprecated use createValue instead
 * Will be removed in v1.0.0
 */
export const stringifyAttestationBytes: typeof createValue = (bytes) => {
  console.warn(
    'stringifyAttestationBytes is deprecated, use createValue instead'
  )
  return createValue(bytes)
}