Skip to navigation

Cross Chain Swaps with Bitcoin

View as Markdown

Use the /quotes and /status endpoints on the 0x Cross Chain API to swap native BTC across chains:

  • Buy BTC: sell a token on another chain and receive native BTC at a mainnet Bitcoin address.
  • Sell BTC: sell native BTC from a mainnet Bitcoin address and receive a token on another chain.

The examples below use USDC on Base as the other side of the swap.

Prerequisites

Before you start, make sure you have:

  • A 0x API key.
  • A mainnet Bitcoin address. Use a native SegWit address (bc1q, 42 characters) when you can.
  • To buy BTC: a funded EVM wallet set up as shown in Get started.
  • To sell BTC: confirmed BTC UTXOs at one mainnet Bitcoin address that cover both the sell amount and the miner fee.
  • To sell BTC: a private key in WIF format stored in BITCOIN_WIF, plus bitcoinjs-lib, ecpair, and tiny-secp256k1 to run the signing example.

Bitcoin request constants

Use these values in every Bitcoin request:

FieldValue
Chain namebitcoin
Chain ID999999999994
Native BTC tokenbc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmql8k8
Decimals8

Pass BTC amounts as base-unit integers, the same as EVM token amounts. The base unit of BTC is the satoshi, so 1 BTC = 100000000 satoshis.

TermMeaning
UTXOAn unspent output from an earlier Bitcoin transaction. Your wallet funds the sell amount and the miner fee from confirmed UTXOs at originAddress. See Bitcoin transaction data.
PSBTA Partially Signed Bitcoin Transaction. A Bitcoin sell quote returns an unsigned PSBT encoded as hex. See BIP 174.
WIFWallet Import Format, a text encoding of a Bitcoin private key. The signing example reads it from BITCOIN_WIF.

Supported Bitcoin addresses

When destinationChain is bitcoin, destinationAddress is required and accepts any mainnet Bitcoin address. When originChain is bitcoin, 0x funds the swap from confirmed UTXOs at one originAddress using one of the supported single-key types below.

Address typePrefixReceiving BTC (destinationAddress)Selling BTC (originAddress)Requirements for selling
Native SegWit (P2WPKH)bc1q (42 chars)SupportedSupportedRecommended default. Pass originAddress.
Taproot (P2TR)bc1pSupportedSupported (key-path only)Pass originAddress and omit bitcoinOriginPublicKey. Script-path spends are unsupported.
Wrapped SegWit (P2SH-P2WPKH)3SupportedSupportedPass originAddress and its 33-byte compressed SEC1 public key in bitcoinOriginPublicKey (hex, no 0x).
Other P2SH (multisig, P2SH-P2WSH, custom)3SupportedUnsupportedReceiving only.
Legacy (P2PKH)1SupportedSupported (compressed key)Pass originAddress. Requires a compressed public key. At most 50 UTXOs per quote.
Native SegWit script hash (P2WSH)bc1q (62 chars)SupportedUnsupportedReceiving only.

Keep these funding limits in mind when selling BTC:

  • 0x selects confirmed UTXOs from a single originAddress and cannot combine UTXOs across multiple addresses.
  • Every sell transaction must fit within Bitcoin’s standard 100,000-vbyte (400,000-weight-unit) limit. Legacy (1...) origins have an additional cap of 50 selected UTXOs per quote because each input embeds its full previous transaction. If your address holds many small UTXOs, consolidate them or reduce sellAmount.
  • Receiving BTC at an address does not guarantee that your wallet can sign PSBTs for that address type. Confirm that your wallet signs the returned PSBT with SIGHASH_ALL before requesting a sell quote.

Buy BTC with a token on another chain

1. Fetch a quote

Set destinationChain to bitcoin and buyToken to bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmql8k8.

const quotesParams = new URLSearchParams({
originChain: 'base', // Base mainnet
destinationChain: 'bitcoin', // Bitcoin mainnet
sellToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC on Base
buyToken: 'bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmql8k8', // native BTC
sellAmount: '20000000', // 20 USDC (6 decimals)
originAddress: '$USER_EVM_ADDRESS', // Base address that sells the USDC
destinationAddress: '$USER_BITCOIN_ADDRESS', // Mainnet Bitcoin address that receives the BTC
sortQuotesBy: 'price',
maxNumQuotes: '3',
});
const headers = {
'0x-api-key': '[api-key]', // Get your API key from https://dashboard.0x.org/apps
};
const response = await fetch('https://api.0x.org/cross-chain/quotes?' + quotesParams.toString(), { headers });
const quoteResponse = await response.json();

If you omit destinationAddress, the API returns HTTP 400 INPUT_INVALID with the reason Bitcoin destinationAddress is required.

2. Approve and send the transaction

Check quote.issues.allowance first. If an allowance is needed, approve the spender and wait for confirmation before sending the swap transaction.

import { createWalletClient, http, erc20Abi } from 'viem';
import { base } from 'viem/chains';
import { privateKeyToAccount } from 'viem/accounts';
const account = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({
account,
chain: base,
transport: http('https://mainnet.base.org'),
});
const quote = quoteResponse.quotes[0];
if (quote.issues.allowance) {
const approveTxHash = await walletClient.writeContract({
address: quoteResponse.sellToken as `0x${string}`,
abi: erc20Abi,
functionName: 'approve',
args: [quote.issues.allowance.spender as `0x${string}`, BigInt(quote.sellAmount)],
});
await walletClient.waitForTransactionReceipt({ hash: approveTxHash });
}
const txHash = await walletClient.sendTransaction({
to: quote.transaction.details.to as `0x${string}`,
data: quote.transaction.details.data as `0x${string}`,
value: BigInt(quote.transaction.details.value),
gas: quote.transaction.details.gas ? BigInt(quote.transaction.details.gas) : undefined,
});

3. Monitor execution

Poll /status with the origin transaction hash and the quoteId from the quote you executed.

const statusParams = new URLSearchParams({
originChain: 'base',
originTxHash: txHash, // Hash of the Base transaction from step 2
quoteId: quoteResponse.quotes[0].quoteId,
});
const statusResponse = await fetch('https://api.0x.org/cross-chain/status?' + statusParams.toString(), { headers });
console.log(await statusResponse.json());

When status reaches bridge_filled, the BTC has been sent to destinationAddress.

Sell BTC for a token on another chain

1. Fetch a quote

Set originChain to bitcoin and sellToken to bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmql8k8. If originAddress is a wrapped SegWit (3...) address, also pass its 33-byte compressed public key in bitcoinOriginPublicKey.

const quotesParams = new URLSearchParams({
originChain: 'bitcoin', // Bitcoin mainnet
destinationChain: 'base', // Base mainnet
sellToken: 'bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmql8k8', // native BTC
buyToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC on Base
sellAmount: '1000000', // 0.01 BTC (8 decimals)
originAddress: '$USER_BITCOIN_ADDRESS', // Bitcoin address that holds confirmed UTXOs
destinationAddress: '$USER_EVM_ADDRESS', // Base address that receives the USDC
// Required only for wrapped SegWit (3...) origins:
// bitcoinOriginPublicKey: '02...',
sortQuotesBy: 'price',
maxNumQuotes: '3',
});
const headers = {
'0x-api-key': '[api-key]', // Get your API key from https://dashboard.0x.org/apps
};
const response = await fetch('https://api.0x.org/cross-chain/quotes?' + quotesParams.toString(), { headers });
const quoteResponse = await response.json();

Review these response details before signing:

  • allowanceTarget is always null. Bitcoin swaps need no token approval and no wrap transaction.
  • quotes[i].sellAmount and steps[0].sellAmount report the bridge deposit plus payable service fees, before the miner fee. If wallet change is too small to create a valid change output, 0x adds that remainder to the bridge deposit instead of paying it to miners. That remainder can make sellAmount slightly higher than requested.
  • gasCosts.total reports the Bitcoin miner fee in satoshis (sum(inputs) - sum(outputs)).
{
"liquidityAvailable": true,
"allowanceTarget": null,
"originChainId": 999999999994,
"originChain": "bitcoin",
"destinationChainId": 8453,
"destinationChain": "base",
"sellToken": "bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmql8k8",
"buyToken": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"issues": {
"allowance": null,
"balance": null
},
"quotes": [
{
"sellAmount": "1000000",
"buyAmount": "<USDC base units>",
"minBuyAmount": "<USDC base units>",
"quoteId": "<quote id>",
"fees": {
"integratorFees": [],
"zeroExFee": null,
"bridgeNativeFee": null
},
"gasCosts": {
"chainType": "btc",
"total": "<satoshis>"
},
"steps": [
{
"type": "bridge",
"originChainId": 999999999994,
"destinationChainId": 8453,
"sellToken": "bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmql8k8",
"buyToken": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"sellAmount": "1000000",
"buyAmount": "<USDC base units>",
"minBuyAmount": "<USDC base units>",
"provider": "near_intents",
"estimatedTimeSeconds": "<seconds>"
}
],
"transaction": {
"chainType": "btc",
"details": {
"psbt": "70736274ff..."
}
},
"estimatedTimeSeconds": "<seconds>"
}
]
}

A Bitcoin block confirmation takes about 10 minutes.

2. Sign the PSBT

Decode the hex PSBT from quote.transaction.details.psbt, sign all inputs, finalize them, and extract the raw transaction hex.

import * as bitcoin from 'bitcoinjs-lib';
import * as ecc from 'tiny-secp256k1';
import { ECPairFactory } from 'ecpair';
bitcoin.initEccLib(ecc);
const ECPair = ECPairFactory(ecc);
const keyPair = ECPair.fromWIF(process.env.BITCOIN_WIF);
const quote = quoteResponse.quotes[0];
const psbt = bitcoin.Psbt.fromHex(quote.transaction.details.psbt.replace(/^0x/, ''));
psbt.signAllInputs(keyPair);
psbt.finalizeAllInputs();
const rawTx = psbt.extractTransaction().toHex();
  • Sign every input with SIGHASH_ALL. Returned PSBTs set each input’s sequence to 0xfffffffd, which signals opt-in Replace-By-Fee (BIP 125) with relative locktime disabled (BIP 68). 0x does not build or broadcast replacement transactions.
  • Legacy (1...): 0x attaches the verified full previous transaction in non_witness_utxo for every legacy input. Your wallet must use a compressed public key, and a single quote selects at most 50 legacy inputs.
  • Wrapped SegWit (3...): 0x derives the P2SH-P2WPKH redeemScript from bitcoinOriginPublicKey and attaches it to every input and any change output in the PSBT.
  • Taproot (bc1p...): Key-path spends require a BIP 86 tweaked Schnorr signer and the x-only tapInternalKey on each input before calling signAllInputs.

3. Broadcast the transaction

Submit the finalized raw transaction hex to a Bitcoin broadcast endpoint. The example below uses mempool.space, which returns the transaction ID (txid) as plain text.

const broadcastResponse = await fetch('https://mempool.space/api/tx', {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: rawTx,
});
const txid = (await broadcastResponse.text()).trim();
if (!broadcastResponse.ok) {
throw new Error(txid);
}

4. Monitor execution

Poll /status with originChain set to bitcoin, originTxHash set to the txid, and the quoteId from the quote you executed.

const statusParams = new URLSearchParams({
originChain: 'bitcoin',
originTxHash: txid, // 64 hex characters, with or without a 0x prefix
quoteId: quoteResponse.quotes[0].quoteId,
});
const statusResponse = await fetch('https://api.0x.org/cross-chain/status?' + statusParams.toString(), { headers });
console.log(await statusResponse.json());

For the full status lifecycle and failure handling, see Tracking Transaction Status.

Integrator fees

Pass feeBps or feePpm, and one or more mainnet Bitcoin addresses in feeRecipient, to collect integrator fees in native BTC. Omit feeToken, or set it to the native BTC token (bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmql8k8). Parameter format matches Monetize Your App.

Each payable fee is a separate output in the Bitcoin transaction. The fee has to meet the dust limit for that recipient address type on its own. If a fee is below the limit, 0x waives it, leaves those satoshis in the bridge deposit, and omits it from fees.integratorFees.

Recipient address typeDust limit (satoshis)
Native SegWit (P2WPKH, bc1q, 42 characters)294
Taproot (P2TR, bc1p) or Native SegWit (P2WSH, bc1q, 62 characters)330
Wrapped SegWit or P2SH (3)540
Legacy (P2PKH, 1)546