Bitcoin

Bitcoin

#Installation

Magic interacts with the Bitcoin blockchain via Magic's extension NPM package @magic-ext/bitcoin. The Bitcoin extension also lets you interact with the blockchain using methods from Bitcoinjs-lib.

note

You can skip straight to our kitchen sink example directly:

👉 Bitcoin Example

NPM
Yarn
01npm install --save @magic-ext/bitcoin

#Initialization

Typescript
01import { Magic } from 'magic-sdk';
02import { BitcoinExtension } from "@magic-ext/bitcoin";
03
04const magic = new Magic('YOUR_API_KEY', {
05  extensions: [
06    new BitcoinExtension({
07      rpcUrl: 'BTC_RPC_NODE_URL',
08      network: 'testnet' // testnet or mainnet
09    }),
10  ],
11});

#Common Methods

#Sign Transaction

To send a standard Bitcoin blockchain transaction, you can call the magic.bitcoin.signTransaction method to get the signature and raw transaction then send to blockchain by yourself.

Javascript
01import { Magic } from 'magic-sdk';
02import { BitcoinExtension } from "@magic-ext/bitcoin";
03import * as bitcoin from 'bitcoinjs-lib'
04
05const magic = new Magic('YOUR_API_KEY', {
06  extensions: [
07    new BitcoinExtension({
08      rpcUrl: 'BTC_RPC_NODE_URL',
09      network: 'testnet' // testnet or mainnet
10    }),
11  ],
12});
13
14const TESTNET = bitcoin.networks.testnet;
15
16const tx = new bitcoin.TransactionBuilder(TESTNET);
17tx.addInput('fde789dad13b52e33229baed29b11d3e6f6dd306eb159865957dce13219bf85c', 0);
18
19tx.addOutput('mfkv2a593E1TfDVFmf1szjAkyihLowyBaT', 80000);
20
21const txHex = tx.buildIncomplete().toHex();
22
23const signedTransactionHex = await magic.bitcoin.signTransaction(txHex, 0);
24
25console.log("signed transaction", signedTransactionHex);

#Resources