Skip to content

Commit 75f8d88

Browse files
authored
Create example-sign-transaction.js
1 parent 13aea8c commit 75f8d88

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/example-sign-transaction.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* Example: Signing a Bitcoin transaction using bitcoinjs-lib
3+
*
4+
* This demo creates a dummy transaction, signs it using a random private key,
5+
* and prints both the raw transaction hex and the public address.
6+
*/
7+
8+
import * as bitcoin from 'bitcoinjs-lib';
9+
import { ECPairFactory } from 'ecpair';
10+
import * as tinysecp from 'tiny-secp256k1';
11+
12+
const ECPair = ECPairFactory(tinysecp);
13+
14+
export function signExampleTx() {
15+
const keyPair = ECPair.makeRandom();
16+
const { address } = bitcoin.payments.p2wpkh({ pubkey: keyPair.publicKey });
17+
18+
// Create a fake transaction
19+
const psbt = new bitcoin.Psbt({ network: bitcoin.networks.testnet });
20+
psbt.addInput({
21+
hash: 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
22+
index: 0,
23+
witnessUtxo: {
24+
script: bitcoin.payments.p2wpkh({ pubkey: keyPair.publicKey }).output,
25+
value: 10_000,
26+
},
27+
});
28+
psbt.addOutput({
29+
address: address,
30+
value: 9_000,
31+
});
32+
33+
// Sign & finalize
34+
psbt.signAllInputs(keyPair);
35+
psbt.finalizeAllInputs();
36+
37+
const txHex = psbt.extractTransaction().toHex();
38+
console.log('Signed transaction (hex):', txHex);
39+
console.log('Sender address:', address);
40+
return txHex;
41+
}
42+
43+
// Uncomment below for direct testing
44+
// signExampleTx();

0 commit comments

Comments
 (0)