Bitcoin

javascript – How to sign a message with privateKey in Bitcoin using TS/JS?

I’m trying to sign a message to UniSat at this endpoint.
Bind btcAddress and nftAddress.

Use the following code:

import * as bitcoin from 'bitcoinjs-lib';
import * as ecc from 'tiny-secp256k1';
import * as bitcoinMessage from 'bitcoinjs-message';
import  ECPairFactory  from 'ecpair';
import * as crypto from 'crypto';
import * as secp256k1 from 'tiny-secp256k1';

const ECPair = ECPairFactory(ecc);


function signMessage(privateKeyWIF: string, message: string): string 
    const ecPair = ECPair.fromWIF(privateKeyWIF, bitcoin.networks.bitcoin);
    const privateKey = ecPair.privateKey;
    const compressed = ecPair.compressed;

    if (!privateKey) 
        throw new Error('Private key is missing');
    

    // Sign the message
    const signature = bitcoinMessage.sign(message, privateKey, compressed);

    // Encode the signature in base64
    const signatureCompact = signature.slice(1, 65).toString('hex');

    return signatureCompact;


const message: string = `Please confirm that\nPayment Address: $paymentAddress\nOrdinals Address: $ordinalsAddress`;

const signature: string = signMessage(privateKey, message);

But when I get a response:


  btcAddress: 'bc1q5fqwlf88dtu9qa2jkvwhjr94k07cerfau3mh9s',
  nftAddress: 'bc1p7n462ru9wtfgclwedfgp0eqe6w40pjwt7wvkxgdmzue2y6ptdkvsuzzmu2',
  sign: '732505d8a18002ec9b16600558457a1695c7b5b7b93b0001f566953fe8052c8b1d82d25d8233d675a8c22bacaa5858dab37b623d7fcccf5d58d8a80580d704af'


  code: -1,
  msg: 'Signature.fromCompact: Expected 64-byte hex',
  data: null

What am I doing wrong?

Thank you for your help.

Related Articles

Back to top button