How to Integrate with the Bitcoin Blockchain with Magic
How to Integrate with the Bitcoin Blockchain with Magic
#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.
You can skip straight to our kitchen sink example directly:
👉 Bitcoin Example
#NPM
npm install --save @magic-ext/bitcoin
#Yarn
yarn add @magic-ext/bitcoin
#Initializing Extension
#ES Modules/TypeScript
import { Magic } from 'magic-sdk';
import { BitcoinExtension } from "@magic-ext/bitcoin";
const magic = new Magic('YOUR_API_KEY', {
extensions: [
new BitcoinExtension({
rpcUrl: 'BTC_RPC_NODE_URL',
network: 'testnet' // testnet or mainnet
}),
],
});
#Call signTransaction Extension Method
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.
#ES Modules/TypeScript
import { Magic } from 'magic-sdk';
import { BitcoinExtension } from "@magic-ext/bitcoin";
import * as bitcoin from 'bitcoinjs-lib'
const magic = new Magic('YOUR_API_KEY', {
extensions: [
new BitcoinExtension({
rpcUrl: 'BTC_RPC_NODE_URL',
network: 'testnet' // testnet or mainnet
}),
],
});
const TESTNET = bitcoin.networks.testnet;
const tx = new bitcoin.TransactionBuilder(TESTNET);
tx.addInput('fde789dad13b52e33229baed29b11d3e6f6dd306eb159865957dce13219bf85c', 0);
tx.addOutput('mfkv2a593E1TfDVFmf1szjAkyihLowyBaT', 80000);
const txHex = tx.buildIncomplete().toHex();
const signedTransactionHex = await magic.bitcoin.signTransaction(txHex, 0);
console.log("signed transaction", signedTransactionHex);