• About
  • FAQ
  • Privacy Policy
  • Support Forum
  • Disclaimer
  • Contact Us
Newsletter
Token Alytics
  • Home
  • Bitcoin
  • Blockchain
  • Cryptocurrency
  • Defi
  • Ripple
  • Ethereum
  • Metaverse
No Result
View All Result
  • Home
  • Bitcoin
  • Blockchain
  • Cryptocurrency
  • Defi
  • Ripple
  • Ethereum
  • Metaverse
No Result
View All Result
Token Alytics
No Result
View All Result
Home Bitcoin

signature – Getting error for transferring BTC utilizing node js code, getting error “No inputs have been signed”

thecryptogoblin by thecryptogoblin
August 14, 2024
in Bitcoin
0
189
SHARES
1.5k
VIEWS
Share on FacebookShare on Twitter


import * as bitcoin from 'bitcoinjs-lib';
import { ECPairFactory } from 'ecpair';
import * as ecc from 'tiny-secp256k1';
import mempoolJS from '@mempool/mempool.js';

const ECPair = ECPairFactory(ecc);
const community = bitcoin.networks.testnet; // Use 'bitcoin.networks.bitcoin' for mainnet

const estimateTransactionSize = (numInputs: quantity, numOutputs: quantity): quantity => {
  return numInputs * 148 + numOutputs * 34 + 10;
};

const calculateFee = (feeRate: quantity, numInputs: quantity, numOutputs: quantity): quantity => {
  const txSize = estimateTransactionSize(numInputs, numOutputs);
  return feeRate * txSize;
};

export const sendBTC = async (
  privateKey: string,
  toAddress: string,
  quantity: quantity
): Promise<{ success: boolean; txHash: string }> => {
  strive {
    const { bitcoin: { addresses, transactions, charges } } = mempoolJS({
      hostname: 'mempool.house',
      community: 'testnet',
    });

    const keyPair = ECPair.fromPrivateKey(Buffer.from(privateKey, 'hex'));
    const p2wpkh = bitcoin.funds.p2wpkh({ pubkey: keyPair.publicKey, community });

    const tackle = p2wpkh.tackle;
    if (!tackle) {
      return { success: false, txHash: '' };
    }

    const utxos = await addresses.getAddressTxsUtxo({ tackle });
    const feesRecommended = await charges.getFeesRecommended();

    let totalSatoshisAvailable = 0;
    utxos.forEach(utxo => {
      if (utxo.worth >= 1000) {
        totalSatoshisAvailable += utxo.worth;
      }
    });

    const numInputs = utxos.size;
    const numOutputs = 2; // Vacation spot + Change
    const charge = calculateFee(feesRecommended.minimumFee, numInputs, numOutputs);
    const change = totalSatoshisAvailable - quantity - charge;

    const psbt = new bitcoin.Psbt({ community });

    const guarantees = utxos.map(async (utxo) => {
      if (utxo.worth >= 1000) {
        psbt.addInput({
          hash: utxo.txid,
          index: utxo.vout,
          witnessUtxo: {
            script: Buffer.from(p2wpkh.output!.toString('hex'), 'hex'),
            worth: utxo.worth,
          },
        });
      }
    });
    await Promise.all(guarantees);

    psbt.addOutput({
      tackle: toAddress,
      worth: quantity,
    });

    if (change > 0) {
      psbt.addOutput({
        tackle: tackle!,
        worth: change,
      });
    }

    psbt.signAllInputs(keyPair);
    psbt.finalizeAllInputs();

    const rawTransaction = psbt.extractTransaction().toHex();
    const txId = await transactions.postTx({ txhex: rawTransaction });

    if (!txId) {
      return { success: false, txHash: '' };
    }

    return { success: true, txHash: txId.toString() };
  } catch (error) {
    console.error('Error whereas transferring bitcoin:', error);
    return { success: false, txHash: '' };
  }
};

Related articles

3 Greatest Altcoins Thriving Amid De-Dollarization and Pepe Wars

3 Greatest Altcoins Thriving Amid De-Dollarization and Pepe Wars

June 1, 2025
Tron (TRX) Future Retail Exercise Point out Extra Positive factors Forward

Tron (TRX) Future Retail Exercise Point out Extra Positive factors Forward

June 1, 2025


import * as bitcoin from 'bitcoinjs-lib';
import { ECPairFactory } from 'ecpair';
import * as ecc from 'tiny-secp256k1';
import mempoolJS from '@mempool/mempool.js';

const ECPair = ECPairFactory(ecc);
const community = bitcoin.networks.testnet; // Use 'bitcoin.networks.bitcoin' for mainnet

const estimateTransactionSize = (numInputs: quantity, numOutputs: quantity): quantity => {
  return numInputs * 148 + numOutputs * 34 + 10;
};

const calculateFee = (feeRate: quantity, numInputs: quantity, numOutputs: quantity): quantity => {
  const txSize = estimateTransactionSize(numInputs, numOutputs);
  return feeRate * txSize;
};

export const sendBTC = async (
  privateKey: string,
  toAddress: string,
  quantity: quantity
): Promise<{ success: boolean; txHash: string }> => {
  strive {
    const { bitcoin: { addresses, transactions, charges } } = mempoolJS({
      hostname: 'mempool.house',
      community: 'testnet',
    });

    const keyPair = ECPair.fromPrivateKey(Buffer.from(privateKey, 'hex'));
    const p2wpkh = bitcoin.funds.p2wpkh({ pubkey: keyPair.publicKey, community });

    const tackle = p2wpkh.tackle;
    if (!tackle) {
      return { success: false, txHash: '' };
    }

    const utxos = await addresses.getAddressTxsUtxo({ tackle });
    const feesRecommended = await charges.getFeesRecommended();

    let totalSatoshisAvailable = 0;
    utxos.forEach(utxo => {
      if (utxo.worth >= 1000) {
        totalSatoshisAvailable += utxo.worth;
      }
    });

    const numInputs = utxos.size;
    const numOutputs = 2; // Vacation spot + Change
    const charge = calculateFee(feesRecommended.minimumFee, numInputs, numOutputs);
    const change = totalSatoshisAvailable - quantity - charge;

    const psbt = new bitcoin.Psbt({ community });

    const guarantees = utxos.map(async (utxo) => {
      if (utxo.worth >= 1000) {
        psbt.addInput({
          hash: utxo.txid,
          index: utxo.vout,
          witnessUtxo: {
            script: Buffer.from(p2wpkh.output!.toString('hex'), 'hex'),
            worth: utxo.worth,
          },
        });
      }
    });
    await Promise.all(guarantees);

    psbt.addOutput({
      tackle: toAddress,
      worth: quantity,
    });

    if (change > 0) {
      psbt.addOutput({
        tackle: tackle!,
        worth: change,
      });
    }

    psbt.signAllInputs(keyPair);
    psbt.finalizeAllInputs();

    const rawTransaction = psbt.extractTransaction().toHex();
    const txId = await transactions.postTx({ txhex: rawTransaction });

    if (!txId) {
      return { success: false, txHash: '' };
    }

    return { success: true, txHash: txId.toString() };
  } catch (error) {
    console.error('Error whereas transferring bitcoin:', error);
    return { success: false, txHash: '' };
  }
};

Tags: BTCcodeerrorinputsnodesignaturesignedtransferring
Share76Tweet47

Related Posts

3 Greatest Altcoins Thriving Amid De-Dollarization and Pepe Wars

3 Greatest Altcoins Thriving Amid De-Dollarization and Pepe Wars

by thecryptogoblin
June 1, 2025
0

Trusted Editorial content material, reviewed by main business consultants and seasoned editors. Advert Disclosure The crypto world is buzzing once...

Tron (TRX) Future Retail Exercise Point out Extra Positive factors Forward

Tron (TRX) Future Retail Exercise Point out Extra Positive factors Forward

by thecryptogoblin
June 1, 2025
0

Semilore Faleti is a cryptocurrency author specialised within the discipline of journalism and content material creation. Whereas he began out...

Amboss Launches Rails, A Self-Custodial Bitcoin Yield Service

Amboss Launches Rails, A Self-Custodial Bitcoin Yield Service

by thecryptogoblin
May 31, 2025
0

Amboss, a frontrunner in AI-driven options for the Bitcoin Lightning Community, at this time introduced Rails, a groundbreaking self-custodial Bitcoin...

The transaction historical past made to the tackle by way of the Electrum Testnet pockets isn’t displayed

The transaction historical past made to the tackle by way of the Electrum Testnet pockets isn’t displayed

by thecryptogoblin
May 31, 2025
0

I'm new to this enterprise, so I apologize for such a probably fundamental and silly query, I attempted to seek...

NFT Market OpenSea Launches Its Upgraded OS2 Platform

NFT Market OpenSea Launches Its Upgraded OS2 Platform

by thecryptogoblin
May 30, 2025
0

Be part of Our Telegram channel to remain updated on breaking information protection OpenSea, one of many main multi-chain non-fungible...

Load More
  • Trending
  • Comments
  • Latest
CryptoRank Telegram Airdrop Information | How To Take part

CryptoRank Telegram Airdrop Information | How To Take part

September 7, 2024

bitcoin core – mandatory-script-verify-flag-failed (Script evaluated with out error however completed with a false/empty prime stack component) on wrapped SegWit enter

December 24, 2024
Lumina Hunt Telegram Sport Airdrop Information

Lumina Hunt Telegram Sport Airdrop Information

October 23, 2024
How Essential is Jito Solana MEV Bot Growth for the Cryptocurrency Ecosystem?

How Essential is Jito Solana MEV Bot Growth for the Cryptocurrency Ecosystem?

August 1, 2024

Ethereum Whales Quickly Accumulate ETH Amid Worth Decline

0

How Can a Web3 Neobanking Platform Be Useful for the Decentralized Enterprise Area?

0

2024 Recreation Growth Traits: Alternatives & Challenges | by Jon Radoff | Constructing the Metaverse

0

Prime Ethereum Analyst Says DOGE, PEPE, and RCOF Are About to Expertise a ‘Historic Breakout’

0
Prime 5 cryptocurrencies to be careful for within the close to time period

Prime 5 cryptocurrencies to be careful for within the close to time period

June 1, 2025
New Submitting in Ripple Case Blasts SEC’s Authorized Framework

New Submitting in Ripple Case Blasts SEC’s Authorized Framework

June 1, 2025
Binance Whales Are Accumulating Ethereum Once more – Will Historical past Repeat?

Binance Whales Are Accumulating Ethereum Once more – Will Historical past Repeat?

June 1, 2025
Bored Ape NFT Maker Sells Moonbirds IP To Orange Cap Video games

Bored Ape NFT Maker Sells Moonbirds IP To Orange Cap Video games

June 1, 2025

Token Alytics

We are a team of dedicated enthusiasts, analysts, and writers with a shared interest in the dynamic and fast-paced world of digital assets and blockchain innovation. Our diverse backgrounds in finance, technology, and media give us a unique perspective on the developments in the crypto space.

Categories

  • Bitcoin
  • Blockchain
  • Cryptocurrency
  • Defi
  • Ethereum
  • Metaverse
  • Ripple

Follow Us

  • 643 Followers

Recent News

Prime 5 cryptocurrencies to be careful for within the close to time period

Prime 5 cryptocurrencies to be careful for within the close to time period

June 1, 2025
New Submitting in Ripple Case Blasts SEC’s Authorized Framework

New Submitting in Ripple Case Blasts SEC’s Authorized Framework

June 1, 2025
  • About
  • FAQ
  • Privacy Policy
  • Support Forum
  • Disclaimer
  • Contact Us

© 2018- tokenalytics.io, All rights reserved

No Result
View All Result
  • Home
  • Bitcoin
  • Blockchain
  • Cryptocurrency
  • Defi
  • Ripple
  • Ethereum
  • Metaverse

© 2018- tokenalytics.io, All rights reserved