Skip to main content

Fetching Public Key from an Address

The getPublicKeyInfo method allows you to fetch the public key associated with a Bitcoin address on the OP_NET network. This method is useful for retrieving the public key to interact with smart contracts, etc.

important

Method

getPublicKeyInfo(address: string): Promise<Address>;
  • Parameters:

    • address: string: The Bitcoin address for which you want to fetch the public key.
  • Returns:

    • Promise<Address>: An Address object containing the public key information.

Object Definitions

Address Object
MethodDescription
originalPublicKeyRetrieves the original public key (if available).
toHex()Converts the address to a hexadecimal string.
toBuffer()Converts the address to a Buffer object.
p2wpkh(network)Generates a P2WPKH address for the specified network.
p2pkh(network)Generates a P2PKH address for the specified network.
p2tr(network)Generates a P2TR address for the specified network.
toString()Converts the address to its string representation.
isValid(network)Checks if the address is valid for a specific Bitcoin network.

Example Usage

import { networks } from "@btc-vision/bitcoin";

const address = "bcrt1qexampleaddress...";
const publicKeyInfo = await provider.getPublicKeyInfo(address);

console.log(
"Original Public Key (Hex):",
publicKeyInfo.originalPublicKey?.toString()
);
console.log("P2WPKH Address:", publicKeyInfo.p2wpkh(networks.regtest));
console.log("P2PKH Address:", publicKeyInfo.p2pkh(networks.regtest));
console.log("P2TR Address:", publicKeyInfo.p2tr(networks.regtest));

Best Practices

  • Ensure the address provided is valid for the Bitcoin network you are working on.
  • The returned Address object provides utility methods for generating various address formats (e.g., P2WPKH, P2PKH, P2TR).

What’s Next?

After retrieving the public key, you can: