blue-sky
blue-sky

Reputation: 53866

Sending bitcoins using bitcoinjs-lib

I'm following tutorial for bitcoinjs at https://medium.com/@orweinberger/how-to-create-a-raw-transaction-using-bitcoinjs-lib-1347a502a3a#.wkf9g2lk0

I receive undefined error for

var key = bitcoin.ECKey.fromWIF("L1Kzcyy88LyckShYdvoLFg1FYpB5ce1JmTYtieHrhkN65GhVoq73");

Reading https://github.com/bitcoinjs/bitcoinjs-lib/issues/487 I use instead

var key = bitcoin.ECPair.fromWIF("L1Kzcyy88LyckShYdvoLFg1FYpB5ce1JmTYtieHrhkN65GhVoq73");

For line : console.log(key.pub.getAddress().toString()); (from tutorial)

I receive similar exception :

TypeError: Cannot read property 'getAddress' of undefined
    at repl:1:20
    at REPLServer.defaultEval (repl.js:262:27)
    at bound (domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:431:12)
    at emitOne (events.js:82:20)
    at REPLServer.emit (events.js:169:7)
    at REPLServer.Interface._onLine (readline.js:211:10)
    at REPLServer.Interface._line (readline.js:550:8)
    at REPLServer.Interface._ttyWrite (readline.js:827:14)

'getAddress' method is also deprecated, what to use instead ?

Any other tutorials for sending bitcoins ? They seem difficult to find ?

Upvotes: 2

Views: 2330

Answers (3)

vahid sabet
vahid sabet

Reputation: 583

NEWEST solution from 2023: As you may know, ECPair has separated from bitcoin in bitcoinjs-lib.

const bitcoin = require("bitcoinjs-lib");
const ECPairFactory = require('ecpair');
const ecc = require('tiny-secp256k1');


const ECPair = ECPairFactory.ECPairFactory(ecc);
const testnet = bitcoin.networks.testnet;
var key = 
ECPair.fromWIF("Your testnet wallet private key",testnet);
const { address } = bitcoin.payments.p2pkh({ pubkey: key.publicKey,network: testnet });
console.log('====================================');
console.log(address);
console.log('====================================');

Upvotes: 1

Tide
Tide

Reputation: 131

Better still using newer version of bitcoin.js library do

const bitcoin = require('bitcoinjs-lib');
let keyPair = bitcoin.ECPair.makeRandom();
let publicKey = keyPair.publicKey
const { address } = bitcoin.payments.p2pkh({ pubkey: publicKey });
const privateKey = keyPair.toWIF();
console.log(address)
console.log(privateKey)

Upvotes: 1

Enzo
Enzo

Reputation: 4181

This should work

var key = bitcoin.ECPair.fromWIF("L1Kzcyy88LyckShYdvoLFg1FYpB5ce1JmTYtieHrhkN65GhVoq73");
var address = key.getAddress().toString()

console.log(address) // 17hFoVScNKVDfDTT6vVhjYwvCu6iDEiXC4

Upvotes: 1

Related Questions