Skip to content

PublicKey

Utility functions for working with ECDSA public keys.

Examples

Below are some examples demonstrating common usages of the PublicKey module:

Serializing Public Keys

Public Keys can be serialized to Hex or Bytes using PublicKey.toHex:

import { PublicKey } from 'ox'
 
const publicKey = PublicKey.from({
  prefix: 4,
  x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,
  y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,
})
 
const serialized = PublicKey.toHex(publicKey)
'0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5'

Deserializing Public Keys

Public Keys can be deserialized from Hex or Bytes using PublicKey.fromHex:

import { PublicKey } from 'ox'
 
const publicKey = PublicKey.fromHex('0x8318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5')
{
prefix: 4,
x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,
y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,
}

Functions

NameDescription
PublicKey.assertAsserts that a PublicKey.PublicKey is valid.
PublicKey.compressCompresses a PublicKey.PublicKey.
PublicKey.fromInstantiates a typed PublicKey.PublicKey object from a PublicKey.PublicKey, Bytes.Bytes, or Hex.Hex.
PublicKey.fromBytesDeserializes a PublicKey.PublicKey from a Bytes.Bytes value.
PublicKey.fromHexDeserializes a PublicKey.PublicKey from a Hex.Hex value.
PublicKey.toBytesSerializes a PublicKey.PublicKey to Bytes.Bytes.
PublicKey.toHexSerializes a PublicKey.PublicKey to Hex.Hex.
PublicKey.validateValidates a PublicKey.PublicKey. Returns true if valid, false otherwise.

Errors

NameDescription
PublicKey.InvalidCompressedPrefixErrorThrown when the public key has an invalid prefix for a compressed public key.
PublicKey.InvalidErrorThrown when a public key is invalid.
PublicKey.InvalidPrefixErrorThrown when a public key has an invalid prefix.
PublicKey.InvalidSerializedSizeErrorThrown when the public key has an invalid serialized size.
PublicKey.InvalidUncompressedPrefixErrorThrown when the public key has an invalid prefix for an uncompressed public key.

Types

NameDescription
PublicKey.PublicKeyRoot type for an ECDSA Public Key.