@btc-vision/transaction
Version:
OPNet transaction library allows you to create and sign transactions for the OPNet network.
68 lines (67 loc) • 2.26 kB
JavaScript
import { EcKeyPair } from './EcKeyPair.js';
import { networks, toXOnly } from '@btc-vision/bitcoin';
import { Address } from './Address.js';
import { BitcoinUtils } from '../utils/BitcoinUtils.js';
export class Wallet {
constructor(privateKeyOrWif, network = networks.bitcoin) {
this.network = network;
const parsedPrivateKey = privateKeyOrWif.startsWith('0x')
? privateKeyOrWif.replace('0x', '')
: privateKeyOrWif;
if (BitcoinUtils.isValidHex(parsedPrivateKey)) {
this._keypair = EcKeyPair.fromPrivateKey(Buffer.from(parsedPrivateKey, 'hex'), this.network);
}
else {
this._keypair = EcKeyPair.fromWIF(parsedPrivateKey, this.network);
}
this._bufferPubKey = this._keypair.publicKey;
this._address = new Address(this._keypair.publicKey);
this._p2tr = this._address.p2tr(this.network);
this._p2wpkh = this._address.p2wpkh(this.network);
this._legacy = this._address.p2pkh(this.network);
this._segwitLegacy = this._address.p2wpkh(this.network);
this._tweakedKey = this._address.toBuffer();
}
get address() {
return this._address;
}
get tweakedPubKeyKey() {
return this._tweakedKey;
}
get keypair() {
if (!this._keypair)
throw new Error('Keypair not set');
return this._keypair;
}
get p2wpkh() {
return this._p2wpkh;
}
get p2tr() {
return this._p2tr;
}
get legacy() {
return this._legacy;
}
get addresses() {
return [this.p2wpkh, this.p2tr, this.legacy, this.segwitLegacy];
}
get segwitLegacy() {
return this._segwitLegacy;
}
get publicKey() {
if (!this._bufferPubKey)
throw new Error('Public key not set');
return this._bufferPubKey;
}
get xOnly() {
if (!this.keypair)
throw new Error('Keypair not set');
return toXOnly(this._bufferPubKey);
}
static fromWif(wif, network = networks.bitcoin) {
return new Wallet(wif, network);
}
static new(network = networks.bitcoin) {
return new Wallet(EcKeyPair.generateWallet(network).privateKey, network);
}
}